KiCad PCB EDA Suite
Loading...
Searching...
No Matches
sch_io_database.cpp
Go to the documentation of this file.
1/*
2 * This program source code file is part of KiCad, a free EDA CAD application.
3 *
4 * Copyright (C) 2022 Jon Evans <[email protected]>
5 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
6 *
7 * This program is free software: you can redistribute it and/or modify it
8 * under the terms of the GNU General Public License as published by the
9 * Free Software Foundation, either version 3 of the License, or (at your
10 * option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19 */
20
21#include <iostream>
22#include <string_view>
23#include <unordered_set>
24#include <utility>
25#include <wx/datetime.h>
26#include <wx/log.h>
27#include <wx/tokenzr.h>
28
29#include <boost/algorithm/string.hpp>
30#include <json_common.h>
31#include <pin_map.h>
32
36#include <fmt.h>
37#include <hash.h>
38#include <ki_exception.h>
39#include <lib_symbol.h>
40
41#include "sch_io_database.h"
42
44
45
47 SCH_IO( wxS( "Database library" ) ),
48 m_adapter( nullptr ),
49 m_settings(),
50 m_conn()
51{
53 m_cachePopulated = false;
55}
56
57
61
62
63void SCH_IO_DATABASE::EnumerateSymbolLib( wxArrayString& aSymbolNameList,
64 const wxString& aLibraryPath,
65 const std::map<std::string, UTF8>* aProperties )
66{
67 std::vector<LIB_SYMBOL*> symbols;
68 EnumerateSymbolLib( symbols, aLibraryPath, aProperties );
69
70 for( LIB_SYMBOL* symbol : symbols )
71 aSymbolNameList.Add( symbol->GetName() );
72}
73
74
75void SCH_IO_DATABASE::EnumerateSymbolLib( std::vector<LIB_SYMBOL*>& aSymbolList,
76 const wxString& aLibraryPath,
77 const std::map<std::string, UTF8>* aProperties )
78{
79 wxCHECK_RET( m_adapter, "Database plugin missing library manager adapter handle!" );
80 ensureSettings( aLibraryPath );
82 cacheLib();
83
84 if( !m_conn )
86
87 bool powerSymbolsOnly = ( aProperties && aProperties->contains( SYMBOL_LIBRARY_ADAPTER::PropPowerSymsOnly ) );
88
89 for( auto const& pair : m_nameToSymbolcache )
90 {
91 LIB_SYMBOL* symbol = pair.second.get();
92
93 if( !powerSymbolsOnly || symbol->IsPower() )
94 aSymbolList.emplace_back( symbol );
95 }
96}
97
98
99LIB_SYMBOL* SCH_IO_DATABASE::LoadSymbol( const wxString& aLibraryPath,
100 const wxString& aAliasName,
101 const std::map<std::string, UTF8>* aProperties )
102{
103 wxCHECK_MSG( m_adapter, nullptr, "Database plugin missing library manager adapter handle!" );
104 ensureSettings( aLibraryPath );
106
107 if( !m_conn )
109
110 cacheLib();
111
112 /*
113 * Table names are tricky, in order to allow maximum flexibility to the user.
114 * The slash character is used as a separator between a table name and symbol name, but symbol
115 * names may also contain slashes and table names may now also be empty (which results in the
116 * slash being dropped in the symbol name when placing a new symbol). So, if a slash is found,
117 * we check if the string before the slash is a valid table name. If not, we assume the table
118 * name is blank if our config has an entry for the null table.
119 */
120
121 std::string tableName;
122 std::string symbolName( aAliasName.ToUTF8() );
123
124 auto sanitizedIt = m_sanitizedNameMap.find( aAliasName );
125
126 if( sanitizedIt != m_sanitizedNameMap.end() )
127 {
128 tableName = sanitizedIt->second.first;
129 symbolName = sanitizedIt->second.second;
130 }
131 else
132 {
133 tableName.clear();
134
135 if( aAliasName.Contains( '/' ) )
136 {
137 tableName = std::string( aAliasName.BeforeFirst( '/' ).ToUTF8() );
138 symbolName = std::string( aAliasName.AfterFirst( '/' ).ToUTF8() );
139 }
140 }
141
142 std::vector<const DATABASE_LIB_TABLE*> tablesToTry;
143
144 for( const DATABASE_LIB_TABLE& tableIter : m_settings->m_Tables )
145 {
146 // no table means globally unique keys, try all tables
147 if( tableName.empty() || tableIter.name == tableName )
148 tablesToTry.emplace_back( &tableIter );
149 }
150
151 if( tablesToTry.empty() )
152 {
153 wxLogTrace( traceDatabase, wxT( "LoadSymbol: table '%s' not found in config" ), tableName );
154 return nullptr;
155 }
156
157 const DATABASE_LIB_TABLE* foundTable = nullptr;
159
160 for( const DATABASE_LIB_TABLE* table : tablesToTry )
161 {
162 if( m_conn->SelectOne( table->table, std::make_pair( table->key_col, symbolName ), result ) )
163 {
164 foundTable = table;
165 wxLogTrace( traceDatabase, wxT( "LoadSymbol: SelectOne (%s, %s) found in %s" ),
166 table->key_col, symbolName, table->table );
167 }
168 else
169 {
170 wxLogTrace( traceDatabase, wxT( "LoadSymbol: SelectOne (%s, %s) failed for table %s" ),
171 table->key_col, symbolName, table->table );
172 }
173 }
174
175 if( !foundTable )
176 return nullptr;
177
178 return loadSymbolFromRow( aAliasName, *foundTable, result ).release();
179}
180
181
182void SCH_IO_DATABASE::GetSubLibraryNames( std::vector<wxString>& aNames )
183{
184 ensureSettings( wxEmptyString );
185
186 aNames.clear();
187
188 std::set<wxString> tableNames;
189
190 for( const DATABASE_LIB_TABLE& tableIter : m_settings->m_Tables )
191 {
192 if( tableNames.count( tableIter.name ) )
193 continue;
194
195 aNames.emplace_back( tableIter.name );
196 tableNames.insert( tableIter.name );
197 }
198}
199
200
201void SCH_IO_DATABASE::GetAvailableSymbolFields( std::vector<wxString>& aNames )
202{
203 std::copy( m_customFields.begin(), m_customFields.end(), std::back_inserter( aNames ) );
204}
205
206
207void SCH_IO_DATABASE::GetDefaultSymbolFields( std::vector<wxString>& aNames )
208{
209 std::copy( m_defaultShownFields.begin(), m_defaultShownFields.end(), std::back_inserter( aNames ) );
210}
211
212
213bool SCH_IO_DATABASE::TestConnection( wxString* aErrorMsg )
214{
215 if( m_conn && m_conn->IsConnected() )
216 return true;
217
218 connect();
219
220 if( aErrorMsg && ( !m_conn || !m_conn->IsConnected() ) )
221 *aErrorMsg = m_lastError;
222
223 return m_conn && m_conn->IsConnected();
224}
225
226
228{
229 // Guard against re-entrant cacheLib() calls. A self-referential symbol row (issue #24249)
230 // causes m_adapter->LoadSymbol to route back into SCH_IO_DATABASE::LoadSymbol, which would
231 // otherwise call cacheLib() again while it is in the middle of populating its caches.
232 if( m_inCacheLib )
233 return;
234
235 long long currentTimestampSeconds = wxDateTime::Now().GetValue().GetValue() / 1000;
236
237 // The materialized LIB_SYMBOL cache is expensive to rebuild for large databases because every
238 // row is duplicated from its source library and has all of its fields processed. Re-check the
239 // database only after max_age has elapsed, and even then rebuild the symbols only if the
240 // underlying row data has actually changed. The global library modify hash must not gate this:
241 // the async library loader bumps it whenever any unrelated library finishes loading, which
242 // would otherwise freeze the symbol chooser for seconds at a time.
243 if( m_cachePopulated && ( currentTimestampSeconds - m_cacheTimestamp ) < m_settings->m_Cache.max_age )
244 return;
245
246 m_inCacheLib = true;
247
248 struct CACHE_LIB_GUARD
249 {
250 bool* flag;
251 ~CACHE_LIB_GUARD() { *flag = false; }
252 } cacheLibGuard{ &m_inCacheLib };
253
254 // Re-query the database (the connection layer caches results subject to its own max_age) and
255 // compute a lightweight signature of the raw rows so we can skip the costly materialization
256 // when nothing relevant has changed.
257 std::vector<std::pair<const DATABASE_LIB_TABLE*, std::vector<DATABASE_CONNECTION::ROW>>> tableResults;
258 size_t signature = 0;
259
260 for( const DATABASE_LIB_TABLE& table : m_settings->m_Tables )
261 {
262 std::vector<DATABASE_CONNECTION::ROW> results;
263
264 if( !m_conn->SelectAll( table.table, table.key_col, results ) )
265 {
266 if( !m_conn->GetLastError().empty() )
267 THROW_IO_ERRORF( _( "Error reading database table %s: %s" ), table.table, m_conn->GetLastError() );
268
269 continue;
270 }
271
272 hash_combine( signature, std::string_view( table.table ) );
273
274 for( const DATABASE_CONNECTION::ROW& result : results )
275 {
276 for( const auto& [column, value] : result )
277 {
278 hash_combine( signature, std::string_view( column ) );
279
280 if( const std::string* str = std::any_cast<std::string>( &value ) )
281 hash_combine( signature, std::string_view( *str ) );
282 }
283
284 // The materialized symbols are duplicated from their source libraries, so fold the
285 // modify hash of each referenced (and loaded) source library into the signature. This
286 // rebuilds the cache when a dependency actually changes - for example when an
287 // asynchronously loaded source library finishes loading and a previously empty
288 // placeholder can now be resolved - without being disturbed by unrelated libraries.
289 if( auto it = result.find( table.symbols_col ); it != result.end() )
290 {
291 if( const std::string* str = std::any_cast<std::string>( &it->second ) )
292 {
293 LIB_ID symbolId;
294 symbolId.Parse( *str );
295
296 if( symbolId.IsValid() )
297 {
298 const UTF8& nickname = symbolId.GetLibNickname();
299 hash_combine( signature, std::string_view( nickname.c_str() ) );
300
301 if( std::optional<int> libHash = m_adapter->GetLibraryModifyHash( nickname ) )
302 hash_combine( signature, *libHash );
303 }
304 }
305 }
306 }
307
308 tableResults.emplace_back( &table, std::move( results ) );
309 }
310
311 if( m_cachePopulated && signature == m_cacheSignature )
312 {
313 // Data is unchanged; just reset the timer so we throttle the next re-check.
314 m_cacheTimestamp = currentTimestampSeconds;
315 return;
316 }
317
318 std::map<wxString, std::unique_ptr<LIB_SYMBOL>> newSymbolCache;
319 std::map<wxString, std::pair<std::string, std::string>> newSanitizedNameMap;
320
321 for( const auto& [table, results] : tableResults )
322 {
323 for( const DATABASE_CONNECTION::ROW& result : results )
324 {
325 if( !result.count( table->key_col ) )
326 continue;
327
328 std::string rawName = std::any_cast<std::string>( result.at( table->key_col ) );
329 UTF8 sanitizedName = LIB_ID::FixIllegalChars( rawName, false );
330 std::string sanitizedKey = sanitizedName.c_str();
331 std::string prefix = ( m_settings->m_GloballyUniqueKeys || table->name.empty() ) ? ""
332 : fmt::format( "{}/", table->name );
333 std::string sanitizedDisplayName = fmt::format( "{}{}", prefix, sanitizedKey );
334 wxString name( sanitizedDisplayName );
335
336 newSanitizedNameMap[name] = std::make_pair( table->name, rawName );
337
338 std::unique_ptr<LIB_SYMBOL> symbol = loadSymbolFromRow( name, *table, result );
339
340 if( symbol )
341 newSymbolCache[symbol->GetName()] = std::move( symbol );
342 }
343 }
344
345 m_nameToSymbolcache = std::move( newSymbolCache );
346 m_sanitizedNameMap = std::move( newSanitizedNameMap );
347
348 m_cacheTimestamp = currentTimestampSeconds;
349 m_cacheSignature = signature;
350 m_cachePopulated = true;
351}
352
353void SCH_IO_DATABASE::ensureSettings( const wxString& aSettingsPath )
354{
355 auto tryLoad =
356 [&]()
357 {
358 if( !m_settings->LoadFromFile() )
359 {
360 THROW_IO_ERRORF( _( "Could not load database library: settings file %s missing or invalid" ),
361 aSettingsPath );
362 }
363 };
364
365 if( !m_settings && !aSettingsPath.IsEmpty() )
366 {
367 std::string path( aSettingsPath.ToUTF8() );
368 m_settings = std::make_unique<DATABASE_LIB_SETTINGS>( path );
369 m_settings->SetReadOnly( true );
370
371 tryLoad();
372 }
373 else if( !m_conn && m_settings )
374 {
375 // If we have valid settings but no connection yet; reload settings in case user is editing
376 tryLoad();
377 }
378 else if( m_conn && m_settings && !aSettingsPath.IsEmpty() )
379 {
380 wxASSERT_MSG( aSettingsPath == m_settings->GetFilename(),
381 "Path changed for database library without re-initializing plugin!" );
382 }
383 else if( !m_settings )
384 {
385 wxLogTrace( traceDatabase, wxT( "ensureSettings: no settings but no valid path!" ) );
386 }
387}
388
389
391{
392 wxCHECK_RET( m_settings, "Call ensureSettings before ensureConnection!" );
393
394 connect();
395
396 if( !m_conn || !m_conn->IsConnected() )
397 {
398 THROW_IO_ERRORF( _( "Could not load database library: could not connect to database %s (%s)" ),
399 m_settings->m_Source.dsn, m_lastError );
400 }
401}
402
403
405{
406 wxCHECK_RET( m_settings, "Call ensureSettings before connect()!" );
407
408 if( m_conn && !m_conn->IsConnected() )
409 m_conn.reset();
410
411 if( !m_conn )
412 {
413 if( m_settings->m_Source.connection_string.empty() )
414 {
415 m_conn = std::make_unique<DATABASE_CONNECTION>( m_settings->m_Source.dsn,
416 m_settings->m_Source.username,
417 m_settings->m_Source.password,
418 m_settings->m_Source.timeout );
419 }
420 else
421 {
422 std::string cs = m_settings->m_Source.connection_string;
423 std::string basePath( wxFileName( m_settings->GetFilename() ).GetPath().ToUTF8() );
424
425 // Database drivers that use files operate on absolute paths, so provide a mechanism
426 // for specifying on-disk databases that live next to the kicad_dbl file
427 boost::replace_all( cs, "${CWD}", basePath );
428
429 m_conn = std::make_unique<DATABASE_CONNECTION>( cs, m_settings->m_Source.timeout );
430 }
431
432 if( !m_conn->IsConnected() )
433 {
434 m_lastError = m_conn->GetLastError();
435 m_conn.reset();
436 return;
437 }
438
439 for( const DATABASE_LIB_TABLE& tableIter : m_settings->m_Tables )
440 {
441 std::set<std::string> columns;
442
443 columns.insert( boost::to_lower_copy( tableIter.key_col ) );
444 columns.insert( boost::to_lower_copy( tableIter.footprints_col ) );
445 columns.insert( boost::to_lower_copy( tableIter.symbols_col ) );
446
447 columns.insert( boost::to_lower_copy( tableIter.properties.description ) );
448 columns.insert( boost::to_lower_copy( tableIter.properties.footprint_filters ) );
449 columns.insert( boost::to_lower_copy( tableIter.properties.keywords ) );
450 columns.insert( boost::to_lower_copy( tableIter.properties.exclude_from_sim ) );
451 columns.insert( boost::to_lower_copy( tableIter.properties.exclude_from_bom ) );
452 columns.insert( boost::to_lower_copy( tableIter.properties.exclude_from_board ) );
453
454 for( const DATABASE_FIELD_MAPPING& field : tableIter.fields )
455 columns.insert( boost::to_lower_copy( field.column ) );
456
457 m_conn->CacheTableInfo( tableIter.table, columns );
458 }
459
460 m_conn->SetCacheParams( m_settings->m_Cache.max_size, m_settings->m_Cache.max_age );
461 }
462}
463
464
465std::optional<bool> SCH_IO_DATABASE::boolFromAny( const std::any& aVal )
466{
467 try
468 {
469 bool val = std::any_cast<bool>( aVal );
470 return val;
471 }
472 catch( const std::bad_any_cast& )
473 {
474 }
475
476 try
477 {
478 int val = std::any_cast<int>( aVal );
479 return static_cast<bool>( val );
480 }
481 catch( const std::bad_any_cast& )
482 {
483 }
484
485 try
486 {
487 wxString strval( std::any_cast<std::string>( aVal ).c_str(), wxConvUTF8 );
488
489 if( strval.IsEmpty() )
490 return std::nullopt;
491
492 strval.MakeLower();
493
494 for( const auto& trueVal : { wxS( "true" ), wxS( "yes" ), wxS( "y" ), wxS( "1" ) } )
495 {
496 if( strval.Matches( trueVal ) )
497 return true;
498 }
499
500 for( const auto& falseVal : { wxS( "false" ), wxS( "no" ), wxS( "n" ), wxS( "0" ) } )
501 {
502 if( strval.Matches( falseVal ) )
503 return false;
504 }
505 }
506 catch( const std::bad_any_cast& )
507 {
508 }
509
510 return std::nullopt;
511}
512
513
514std::unique_ptr<LIB_SYMBOL> SCH_IO_DATABASE::loadSymbolFromRow( const wxString& aSymbolName,
515 const DATABASE_LIB_TABLE& aTable,
516 const DATABASE_CONNECTION::ROW& aRow )
517{
518 std::unique_ptr<LIB_SYMBOL> symbol = nullptr;
519
520 if( aRow.count( aTable.symbols_col ) )
521 {
522 LIB_SYMBOL* originalSymbol = nullptr;
523
524 // TODO: Support multiple options for symbol
525 std::string symbolIdStr = std::any_cast<std::string>( aRow.at( aTable.symbols_col ) );
526 LIB_ID symbolId;
527 symbolId.Parse( std::any_cast<std::string>( aRow.at( aTable.symbols_col ) ) );
528
529 // A row's Symbols column may resolve back into the same database library (issue #24249,
530 // e.g. a mistyped library nickname). The adapter would route that lookup back into
531 // SCH_IO_DATABASE::LoadSymbol and re-enter loadSymbolFromRow on the same row until the
532 // stack overflows. Track in-flight LIB_IDs and skip the recursive load on re-entry.
533 struct CYCLE_GUARD
534 {
535 std::unordered_set<wxString>* set;
536 wxString key;
537 bool owns = false;
538
539 ~CYCLE_GUARD()
540 {
541 if( owns )
542 set->erase( key );
543 }
544 } guard{ &m_inProgressLoads, {}, false };
545
546 bool cycle = false;
547
548 if( symbolId.IsValid() )
549 {
550 guard.key = symbolId.Format().wx_str();
551 guard.owns = m_inProgressLoads.insert( guard.key ).second;
552 cycle = !guard.owns;
553
554 if( cycle )
555 {
556 wxLogTrace( traceDatabase, wxT( "loadSymbolFromRow: cycle detected resolving '%s' "
557 "(row '%s' in table '%s'); skipping recursive load" ),
558 symbolIdStr, aSymbolName, aTable.name );
559 }
560 else
561 {
562 originalSymbol = m_adapter->LoadSymbol( symbolId );
563 }
564 }
565
566 if( originalSymbol )
567 {
568 wxLogTrace( traceDatabase, wxT( "loadSymbolFromRow: found original symbol '%s'" ), symbolIdStr );
569 symbol.reset( originalSymbol->Duplicate() );
570 symbol->SetSourceLibId( symbolId );
571 }
572 else if( cycle )
573 {
574 wxLogTrace( traceDatabase, wxT( "loadSymbolFromRow: source symbol '%s' is a self-reference, "
575 "will create empty symbol" ), symbolIdStr );
576 }
577 else if( !symbolId.IsValid() )
578 {
579 wxLogTrace( traceDatabase, wxT( "loadSymboFromRow: source symbol id '%s' is invalid, "
580 "will create empty symbol" ), symbolIdStr );
581 }
582 else
583 {
584 wxLogTrace( traceDatabase, wxT( "loadSymboFromRow: source symbol '%s' not found, "
585 "will create empty symbol" ), symbolIdStr );
586 }
587 }
588
589 if( !symbol )
590 {
591 // Actual symbol not found: return metadata only; error will be indicated in the
592 // symbol chooser
593 symbol.reset( new LIB_SYMBOL( aSymbolName ) );
594 }
595 else
596 {
597 symbol->SetName( aSymbolName );
598 }
599
600 LIB_ID libId = symbol->GetLibId();
601 libId.SetSubLibraryName( aTable.name );
602 symbol->SetLibId( libId );
603
604 wxArrayString footprintsList;
605
606 if( aRow.count( aTable.footprints_col ) )
607 {
608 std::string footprints = std::any_cast<std::string>( aRow.at( aTable.footprints_col ) );
609
610 wxString footprintsStr = wxString( footprints.c_str(), wxConvUTF8 );
611 wxStringTokenizer tokenizer( footprintsStr, ";\t\r\n", wxTOKEN_STRTOK );
612
613 while( tokenizer.HasMoreTokens() )
614 footprintsList.Add( tokenizer.GetNextToken() );
615
616 if( footprintsList.size() > 0 )
617 symbol->GetFootprintField().SetText( footprintsList[0] );
618 }
619 else
620 {
621 wxLogTrace( traceDatabase, wxT( "loadSymboFromRow: footprint field %s not found." ), aTable.footprints_col );
622 }
623
624 // Pin-to-pad maps (issue #2282): attach non-destructively. The pins column carries either the
625 // spec-form named object { "pin_maps": [...], "associated_footprints": [...] } or the legacy
626 // flat MR !2540 array (read for one release, bound to the row's footprints).
627 if( !aTable.pins_col.empty() && aRow.count( aTable.pins_col ) )
628 {
629 try
630 {
631 std::string jsonStr = std::any_cast<std::string>( aRow.at( aTable.pins_col ) );
632
633 if( !jsonStr.empty() )
634 {
635 nlohmann::json json = nlohmann::json::parse( jsonStr );
636
637 if( json.is_object() && json.contains( "pin_maps" ) )
638 {
639 symbol->SetPinMaps( ParsePinMapSet( json ) );
640 symbol->SetAssociatedFootprints( ParseAssociatedFootprints( json ) );
641 }
642 else if( !footprintsList.IsEmpty() )
643 {
644 std::unordered_map<wxString, std::vector<wxString>> assignments = ParseLegacyPinAssignments( json );
645
646 if( !assignments.empty() )
647 {
648 const wxString mapName = wxS( "Database" );
649
650 symbol->PinMaps().AddOrReplace( MakeLegacyPinMap( mapName, assignments ) );
651
652 // Bind the one named map to every footprint the row offers, mirroring the
653 // old behaviour where the assignment applied regardless of footprint.
654 std::vector<ASSOCIATED_FOOTPRINT> associations;
655
656 for( const wxString& footprint : footprintsList )
657 {
658 LIB_ID fpId;
659 fpId.Parse( footprint );
660 associations.push_back( { fpId, mapName } );
661 }
662
663 symbol->SetAssociatedFootprints( std::move( associations ) );
664 }
665 }
666 }
667 }
668 catch( const std::exception& e )
669 {
670 // Surface a malformed pin-map payload to the user instead of silently dropping it; the
671 // symbol still loads without the map (issue #2282).
672 Report( wxString::Format( _( "Error parsing pin map for database symbol '%s': %s" ),
673 aSymbolName, e.what() ),
675 }
676 }
677
678 if( !aTable.properties.description.empty() && aRow.count( aTable.properties.description ) )
679 {
680 wxString value(
681 std::any_cast<std::string>( aRow.at( aTable.properties.description ) ).c_str(),
682 wxConvUTF8 );
683 symbol->SetDescription( value );
684 }
685
686 if( !aTable.properties.keywords.empty() && aRow.count( aTable.properties.keywords ) )
687 {
688 wxString value( std::any_cast<std::string>( aRow.at( aTable.properties.keywords ) ).c_str(),
689 wxConvUTF8 );
690 symbol->SetKeyWords( value );
691 }
692
693 if( !aTable.properties.footprint_filters.empty()
694 && aRow.count( aTable.properties.footprint_filters ) )
695 {
696 wxString value( std::any_cast<std::string>( aRow.at( aTable.properties.footprint_filters ) )
697 .c_str(),
698 wxConvUTF8 );
699 footprintsList.push_back( value );
700 }
701
702 symbol->SetFPFilters( footprintsList );
703
704 if( !aTable.properties.exclude_from_sim.empty()
705 && aRow.count( aTable.properties.exclude_from_sim ) )
706 {
707 std::optional<bool> val = boolFromAny( aRow.at( aTable.properties.exclude_from_sim ) );
708
709 if( val )
710 {
711 symbol->SetExcludedFromSim( *val );
712 }
713 else
714 {
715 wxLogTrace( traceDatabase, wxT( "loadSymbolFromRow: exclude_from_sim value for %s "
716 "could not be cast to a boolean" ), aSymbolName );
717 }
718 }
719
720 if( !aTable.properties.exclude_from_board.empty()
721 && aRow.count( aTable.properties.exclude_from_board ) )
722 {
723 std::optional<bool> val = boolFromAny( aRow.at( aTable.properties.exclude_from_board ) );
724
725 if( val )
726 {
727 symbol->SetExcludedFromBoard( *val );
728 }
729 else
730 {
731 wxLogTrace( traceDatabase, wxT( "loadSymbolFromRow: exclude_from_board value for %s "
732 "could not be cast to a boolean" ), aSymbolName );
733 }
734 }
735
736 if( !aTable.properties.exclude_from_bom.empty()
737 && aRow.count( aTable.properties.exclude_from_bom ) )
738 {
739 std::optional<bool> val = boolFromAny( aRow.at( aTable.properties.exclude_from_bom ) );
740
741 if( val )
742 {
743 symbol->SetExcludedFromBOM( *val );
744 }
745 else
746 {
747 wxLogTrace( traceDatabase, wxT( "loadSymbolFromRow: exclude_from_bom value for %s "
748 "could not be cast to a boolean" ), aSymbolName );
749 }
750 }
751
752 std::vector<SCH_FIELD*> fields;
753 symbol->GetFields( fields );
754
755 std::unordered_map<wxString, SCH_FIELD*> fieldsMap;
756
757 for( SCH_FIELD* field : fields )
758 fieldsMap[field->GetName()] = field;
759
760 static const wxString c_valueFieldName( wxS( "Value" ) );
761 static const wxString c_datasheetFieldName( wxS( "Datasheet" ) );
762 static const wxString c_footprintFieldName( wxS( "Footprint" ) );
763
764 // User fields produced from the database mapping must appear in the order they are
765 // declared in the .kicad_dbl file, not in lexicographic order of their values. Start
766 // assigning ordinals above whatever the source LIB_SYMBOL already uses so that any
767 // pre-existing user fields keep their relative position before the database fields.
768 int dbFieldOrdinal = symbol->GetNextFieldOrdinal();
769
770 for( const DATABASE_FIELD_MAPPING& mapping : aTable.fields )
771 {
772 if( !aRow.count( mapping.column ) )
773 {
774 wxLogTrace( traceDatabase, wxT( "loadSymbolFromRow: field %s not found in result" ), mapping.column );
775 continue;
776 }
777
778 // Skip footprint field if it maps to the footprints column, since that column is
779 // already processed above with tokenization for semicolon-separated multiple footprints.
780 if( mapping.name_wx == c_footprintFieldName && mapping.column == aTable.footprints_col )
781 continue;
782
783 std::string strValue;
784
785 try
786 {
787 strValue = std::any_cast<std::string>( aRow.at( mapping.column ) );
788 }
789 catch( std::bad_any_cast& )
790 {
791 }
792
793 wxString value( strValue.c_str(), wxConvUTF8 );
794
795 if( mapping.name_wx == c_valueFieldName )
796 {
797 SCH_FIELD& field = symbol->GetValueField();
798 field.SetText( value );
799
800 if( !mapping.inherit_properties )
801 {
802 field.SetVisible( mapping.visible_on_add );
803 field.SetNameShown( mapping.show_name );
804 }
805
806 continue;
807 }
808 else if( mapping.name_wx == c_datasheetFieldName )
809 {
810 SCH_FIELD& field = symbol->GetDatasheetField();
811 field.SetText( value );
812
813 if( !mapping.inherit_properties )
814 {
815 field.SetVisible( mapping.visible_on_add );
816 field.SetNameShown( mapping.show_name );
817
818 if( mapping.visible_on_add )
819 field.SetAutoAdded( true );
820 }
821
822 continue;
823 }
824
825 SCH_FIELD* field;
826 bool isNew = false;
827
828 if( fieldsMap.count( mapping.name_wx ) )
829 {
830 field = fieldsMap[mapping.name_wx];
831 }
832 else
833 {
834 field = new SCH_FIELD( nullptr, FIELD_T::USER );
835 field->SetName( mapping.name_wx );
836 isNew = true;
837 fieldsMap[mapping.name_wx] = field;
838 }
839
840 // Assign a sort-order ordinal so the property editor and BOM see the fields in the
841 // order declared in the .kicad_dbl file. Without this, all USER fields share the
842 // same FIELD_T::USER id and fall through to value-based comparison in operator<.
843 // SetOrdinal forces m_id to FIELD_T::USER, so only apply it to non-mandatory fields
844 // - a DB mapping that lands on a mandatory field by name (e.g. Reference or
845 // Description) must keep its FIELD_T identity for downstream lookups.
846 if( !field->IsMandatory() )
847 field->SetOrdinal( dbFieldOrdinal++ );
848
849 if( !mapping.inherit_properties || isNew )
850 {
851 field->SetVisible( mapping.visible_on_add );
852 field->SetAutoAdded( true );
853 field->SetNameShown( mapping.show_name );
854 }
855
856 field->SetText( value );
857
858 if( isNew )
859 symbol->AddDrawItem( field, false );
860
861 m_customFields.insert( mapping.name_wx );
862
863 if( mapping.visible_in_chooser )
864 m_defaultShownFields.insert( mapping.name_wx );
865 }
866
867 symbol->GetDrawItems().sort();
868
869 // Field mappings (including Description) are applied with SCH_FIELD::SetText, which does not
870 // refresh the cached values the library tree and chooser read. Without this the upper chooser
871 // panel keeps the source symbol's description while the details panel shows the database value.
872 symbol->RefreshLibraryTreeCaches();
873
874 return symbol;
875}
876
877
879{
880 return new DIALOG_DATABASE_LIB_SETTINGS( aParent, this );
881}
const char * name
std::map< std::string, std::any > ROW
Dialog helper object to sit in the inheritance tree between wxDialog and any class written by wxFormB...
Definition dialog_shim.h:80
virtual void SetVisible(bool aVisible)
Definition eda_text.cpp:381
virtual void Report(const wxString &aText, SEVERITY aSeverity=RPT_SEVERITY_UNDEFINED) const
Definition io_base.cpp:124
A logical library item identifier and consists of various portions much like a URI.
Definition lib_id.h:45
int Parse(const UTF8 &aId, bool aFix=false)
Parse LIB_ID with the information from aId.
Definition lib_id.cpp:65
bool IsValid() const
Check if this LID_ID is valid.
Definition lib_id.h:168
UTF8 Format() const
Definition lib_id.cpp:132
void SetSubLibraryName(const UTF8 &aName)
Definition lib_id.h:127
const UTF8 & GetLibNickname() const
Return the logical library name portion of a LIB_ID.
Definition lib_id.h:83
static UTF8 FixIllegalChars(const UTF8 &aLibItemName, bool aLib)
Replace illegal LIB_ID item name characters with underscores '_'.
Definition lib_id.cpp:205
Define a library symbol object.
Definition lib_symbol.h:114
bool IsPower() const override
virtual LIB_SYMBOL * Duplicate() const
Create a copy of a LIB_SYMBOL and assigns unique KIIDs to the copy and its children.
Definition lib_symbol.h:128
void SetOrdinal(int aOrdinal)
Definition sch_field.h:138
bool IsMandatory() const
void SetAutoAdded(bool aAutoAdded)
Definition sch_field.h:237
void SetName(const wxString &aName)
void SetText(const wxString &aText) override
void SetNameShown(bool aShown=true)
Definition sch_field.h:219
void EnumerateSymbolLib(wxArrayString &aSymbolNameList, const wxString &aLibraryPath, const std::map< std::string, UTF8 > *aProperties=nullptr) override
Populate a list of LIB_SYMBOL alias names contained within the library aLibraryPath.
std::unordered_set< wxString > m_inProgressLoads
LIB_IDs whose resolution is in flight, used to break self-referential cycles where a row's Symbols co...
std::unique_ptr< DATABASE_CONNECTION > m_conn
Generally will be null if no valid connection is established.
void GetDefaultSymbolFields(std::vector< wxString > &aNames) override
Retrieves a list of (custom) field names that should be shown by default for this library in the symb...
void ensureSettings(const wxString &aSettingsPath)
bool m_cachePopulated
True once the LIB_SYMBOL cache has been materialized at least once.
bool TestConnection(wxString *aErrorMsg=nullptr)
bool m_inCacheLib
Re-entrancy guard for cacheLib(), tripped when a self-referential load routes back through the adapte...
std::map< wxString, std::unique_ptr< LIB_SYMBOL > > m_nameToSymbolcache
std::map< wxString, std::pair< std::string, std::string > > m_sanitizedNameMap
std::set< wxString > m_defaultShownFields
virtual ~SCH_IO_DATABASE()
size_t m_cacheSignature
Signature of the raw database rows at last materialization; used to skip rebuilding the LIB_SYMBOL ca...
void GetSubLibraryNames(std::vector< wxString > &aNames) override
Retrieves a list of sub-libraries in this library.
std::unique_ptr< DATABASE_LIB_SETTINGS > m_settings
static std::optional< bool > boolFromAny(const std::any &aVal)
SYMBOL_LIBRARY_ADAPTER * m_adapter
long long m_cacheTimestamp
DIALOG_SHIM * CreateConfigurationDialog(wxWindow *aParent) override
void GetAvailableSymbolFields(std::vector< wxString > &aNames) override
Retrieves a list of (custom) field names that are present on symbols in this library.
std::unique_ptr< LIB_SYMBOL > loadSymbolFromRow(const wxString &aSymbolName, const DATABASE_LIB_TABLE &aTable, const DATABASE_CONNECTION::ROW &aRow)
std::set< wxString > m_customFields
LIB_SYMBOL * LoadSymbol(const wxString &aLibraryPath, const wxString &aAliasName, const std::map< std::string, UTF8 > *aProperties=nullptr) override
Load a LIB_SYMBOL object having aPartName from the aLibraryPath containing a library format that this...
SCH_IO(const wxString &aName)
Definition sch_io.h:384
static const char * PropPowerSymsOnly
An 8 bit string that is assuredly encoded in UTF8, and supplies special conversion support to and fro...
Definition utf8.h:67
const char * c_str() const
Definition utf8.h:104
wxString wx_str() const
Definition utf8.cpp:41
const char *const traceDatabase
#define _(s)
nlohmann::json json
Definition gerbview.cpp:50
static constexpr void hash_combine(std::size_t &seed)
This is a dummy function to take the final case of hash_combine below.
Definition hash.h:28
#define THROW_IO_ERROR(msg)
macro which captures the "call site" values of FILE_, __FUNCTION & LINE
#define THROW_IO_ERRORF(msg,...)
PIN_MAP MakeLegacyPinMap(const wxString &aName, const std::unordered_map< wxString, std::vector< wxString > > &aAssignments)
Build a single named PIN_MAP from a legacy symbol-pin to footprint-pad(s) assignment table (the flat ...
Definition pin_map.cpp:151
std::vector< ASSOCIATED_FOOTPRINT > ParseAssociatedFootprints(const nlohmann::json &aParent)
Parse the spec-form footprint associations from aParent["associated_footprints"] (issue #2282).
Definition pin_map.cpp:254
std::unordered_map< wxString, std::vector< wxString > > ParseLegacyPinAssignments(const nlohmann::json &aArray)
Parse the legacy flat pin-assignment JSON array (MR !2540 form) into a symbol-pin to footprint-pad(s)...
Definition pin_map.cpp:187
PIN_MAP_SET ParsePinMapSet(const nlohmann::json &aParent)
Parse the spec-form named maps from aParent["pin_maps"] into a PIN_MAP_SET (issue #2282).
Definition pin_map.cpp:221
@ RPT_SEVERITY_ERROR
static std::string strValue(double aValue)
bool visible_in_chooser
Whether the column is shown by default in the chooser.
std::string column
Database column name.
bool inherit_properties
Whether or not to inherit properties from symbol field.
bool visible_on_add
Whether to show the field when placing the symbol.
bool show_name
Whether or not to show the field name as well as its value.
wxString name_wx
KiCad field name (converted)
A database library table will be mapped to a sub-library provided by the database library entry in th...
std::string key_col
Unique key column name (will form part of the LIB_ID)
std::string name
KiCad library nickname (will form part of the LIB_ID)
std::string symbols_col
Column name containing KiCad symbol refs.
std::string footprints_col
Column name containing KiCad footprint refs.
std::vector< DATABASE_FIELD_MAPPING > fields
std::string table
Database table to pull content from.
MAPPABLE_SYMBOL_PROPERTIES properties
std::string pins_col
Column name containing JSON pin assignments (optional)
@ USER
The field ID hasn't been set yet; field is invalid.
std::string path
wxString result
Test unit parsing edge cases and error handling.