23#include <unordered_set>
25#include <wx/datetime.h>
27#include <wx/tokenzr.h>
29#include <boost/algorithm/string.hpp>
47 SCH_IO( wxS(
"Database library" ) ),
64 const wxString& aLibraryPath,
65 const std::map<std::string, UTF8>* aProperties )
67 std::vector<LIB_SYMBOL*> symbols;
71 aSymbolNameList.Add( symbol->GetName() );
76 const wxString& aLibraryPath,
77 const std::map<std::string, UTF8>* aProperties )
79 wxCHECK_RET(
m_adapter,
"Database plugin missing library manager adapter handle!" );
93 if( !powerSymbolsOnly || symbol->
IsPower() )
94 aSymbolList.emplace_back( symbol );
100 const wxString& aAliasName,
101 const std::map<std::string, UTF8>* aProperties )
103 wxCHECK_MSG(
m_adapter,
nullptr,
"Database plugin missing library manager adapter handle!" );
121 std::string tableName;
122 std::string symbolName( aAliasName.ToUTF8() );
128 tableName = sanitizedIt->second.first;
129 symbolName = sanitizedIt->second.second;
135 if( aAliasName.Contains(
'/' ) )
137 tableName = std::string( aAliasName.BeforeFirst(
'/' ).ToUTF8() );
138 symbolName = std::string( aAliasName.AfterFirst(
'/' ).ToUTF8() );
142 std::vector<const DATABASE_LIB_TABLE*> tablesToTry;
147 if( tableName.empty() || tableIter.
name == tableName )
148 tablesToTry.emplace_back( &tableIter );
151 if( tablesToTry.empty() )
153 wxLogTrace(
traceDatabase, wxT(
"LoadSymbol: table '%s' not found in config" ), tableName );
162 if(
m_conn->SelectOne(
table->table, std::make_pair(
table->key_col, symbolName ),
166 wxLogTrace(
traceDatabase, wxT(
"LoadSymbol: SelectOne (%s, %s) found in %s" ),
171 wxLogTrace(
traceDatabase, wxT(
"LoadSymbol: SelectOne (%s, %s) failed for table %s" ),
189 std::set<wxString> tableNames;
193 if( tableNames.count( tableIter.
name ) )
196 aNames.emplace_back( tableIter.
name );
197 tableNames.insert( tableIter.
name );
211 std::back_inserter( aNames ) );
222 if( aErrorMsg && ( !
m_conn || !
m_conn->IsConnected() ) )
237 long long currentTimestampSeconds = wxDateTime::Now().GetValue().GetValue() / 1000;
253 struct CACHE_LIB_GUARD
256 ~CACHE_LIB_GUARD() { *
flag =
false; }
262 std::vector<std::pair<const DATABASE_LIB_TABLE*, std::vector<DATABASE_CONNECTION::ROW>>> tableResults;
263 size_t signature = 0;
267 std::vector<DATABASE_CONNECTION::ROW> results;
271 if( !
m_conn->GetLastError().empty() )
273 wxString msg = wxString::Format(
_(
"Error reading database table %s: %s" ),
285 for(
const auto& [column, value] :
result )
289 if(
const std::string* str = std::any_cast<std::string>( &value ) )
300 if(
const std::string* str = std::any_cast<std::string>( &it->second ) )
303 symbolId.
Parse( *str );
310 if( std::optional<int> libHash =
m_adapter->GetLibraryModifyHash( nickname ) )
317 tableResults.emplace_back( &
table, std::move( results ) );
327 std::map<wxString, std::unique_ptr<LIB_SYMBOL>> newSymbolCache;
328 std::map<wxString, std::pair<std::string, std::string>> newSanitizedNameMap;
330 for(
const auto& [
table, results] : tableResults )
337 std::string rawName = std::any_cast<std::string>(
result.at(
table->key_col ) );
339 std::string sanitizedKey = sanitizedName.
c_str();
341 (
m_settings->m_GloballyUniqueKeys ||
table->name.empty() ) ?
"" : fmt::format(
"{}/",
table->name );
342 std::string sanitizedDisplayName = fmt::format(
"{}{}", prefix, sanitizedKey );
343 wxString
name( sanitizedDisplayName );
345 newSanitizedNameMap[
name] = std::make_pair(
table->name, rawName );
350 newSymbolCache[symbol->GetName()] = std::move( symbol );
369 wxString msg = wxString::Format(
370 _(
"Could not load database library: settings file %s missing or invalid" ),
379 std::string
path( aSettingsPath.ToUTF8() );
392 wxASSERT_MSG( aSettingsPath ==
m_settings->GetFilename(),
393 "Path changed for database library without re-initializing plugin!" );
397 wxLogTrace(
traceDatabase, wxT(
"ensureSettings: no settings but no valid path!" ) );
404 wxCHECK_RET(
m_settings,
"Call ensureSettings before ensureConnection!" );
410 wxString msg = wxString::Format(
411 _(
"Could not load database library: could not connect to database %s (%s)" ),
421 wxCHECK_RET(
m_settings,
"Call ensureSettings before connect()!" );
428 if(
m_settings->m_Source.connection_string.empty() )
437 std::string cs =
m_settings->m_Source.connection_string;
438 std::string basePath( wxFileName(
m_settings->GetFilename() ).GetPath().ToUTF8() );
442 boost::replace_all( cs,
"${CWD}", basePath );
444 m_conn = std::make_unique<DATABASE_CONNECTION>( cs,
m_settings->m_Source.timeout );
447 if( !
m_conn->IsConnected() )
456 std::set<std::string> columns;
458 columns.insert( boost::to_lower_copy( tableIter.
key_col ) );
459 columns.insert( boost::to_lower_copy( tableIter.
footprints_col ) );
460 columns.insert( boost::to_lower_copy( tableIter.
symbols_col ) );
470 columns.insert( boost::to_lower_copy( field.
column ) );
472 m_conn->CacheTableInfo( tableIter.
table, columns );
484 bool val = std::any_cast<bool>( aVal );
487 catch(
const std::bad_any_cast& )
493 int val = std::any_cast<int>( aVal );
494 return static_cast<bool>( val );
496 catch(
const std::bad_any_cast& )
502 wxString strval( std::any_cast<std::string>( aVal ).c_str(), wxConvUTF8 );
504 if( strval.IsEmpty() )
509 for(
const auto& trueVal : { wxS(
"true" ), wxS(
"yes" ), wxS(
"y" ), wxS(
"1" ) } )
511 if( strval.Matches( trueVal ) )
515 for(
const auto& falseVal : { wxS(
"false" ), wxS(
"no" ), wxS(
"n" ), wxS(
"0" ) } )
517 if( strval.Matches( falseVal ) )
521 catch(
const std::bad_any_cast& )
533 std::unique_ptr<LIB_SYMBOL> symbol =
nullptr;
540 std::string symbolIdStr = std::any_cast<std::string>( aRow.at( aTable.
symbols_col ) );
542 symbolId.
Parse( std::any_cast<std::string>( aRow.at( aTable.
symbols_col ) ) );
550 std::unordered_set<wxString>* set;
572 wxT(
"loadSymbolFromRow: cycle detected resolving '%s' "
573 "(row '%s' in table '%s'); skipping recursive load" ),
574 symbolIdStr, aSymbolName, aTable.
name );
578 originalSymbol =
m_adapter->LoadSymbol( symbolId );
584 wxLogTrace(
traceDatabase, wxT(
"loadSymbolFromRow: found original symbol '%s'" ),
586 symbol.reset( originalSymbol->
Duplicate() );
587 symbol->SetSourceLibId( symbolId );
591 wxLogTrace(
traceDatabase, wxT(
"loadSymbolFromRow: source symbol '%s' is a "
592 "self-reference, will create empty symbol" ),
597 wxLogTrace(
traceDatabase, wxT(
"loadSymboFromRow: source symbol id '%s' is invalid, "
598 "will create empty symbol" ), symbolIdStr );
602 wxLogTrace(
traceDatabase, wxT(
"loadSymboFromRow: source symbol '%s' not found, "
603 "will create empty symbol" ), symbolIdStr );
611 symbol.reset(
new LIB_SYMBOL( aSymbolName ) );
615 symbol->SetName( aSymbolName );
618 LIB_ID libId = symbol->GetLibId();
620 symbol->SetLibId( libId );
622 wxArrayString footprintsList;
626 std::string footprints = std::any_cast<std::string>( aRow.at( aTable.
footprints_col ) );
628 wxString footprintsStr = wxString( footprints.c_str(), wxConvUTF8 );
629 wxStringTokenizer tokenizer( footprintsStr,
";\t\r\n", wxTOKEN_STRTOK );
631 while( tokenizer.HasMoreTokens() )
632 footprintsList.Add( tokenizer.GetNextToken() );
634 if( footprintsList.size() > 0 )
635 symbol->GetFootprintField().SetText( footprintsList[0] );
639 wxLogTrace(
traceDatabase, wxT(
"loadSymboFromRow: footprint field %s not found." ),
650 std::string jsonStr = std::any_cast<std::string>( aRow.at( aTable.
pins_col ) );
652 if( !jsonStr.empty() )
654 nlohmann::json
json = nlohmann::json::parse( jsonStr );
656 if(
json.is_object() &&
json.contains(
"pin_maps" ) )
661 else if( !footprintsList.IsEmpty() )
665 if( !assignments.empty() )
667 const wxString mapName = wxS(
"Database" );
673 std::vector<ASSOCIATED_FOOTPRINT> associations;
675 for(
const wxString& footprint : footprintsList )
678 fpId.
Parse( footprint );
679 associations.push_back( { fpId, mapName } );
682 symbol->SetAssociatedFootprints( std::move( associations ) );
687 catch(
const std::exception& e )
691 wxLogError(
_(
"Error parsing pin map for database symbol '%s': %s" ), aSymbolName, e.what() );
700 symbol->SetDescription( value );
705 wxString value( std::any_cast<std::string>( aRow.at( aTable.
properties.
keywords ) ).c_str(),
707 symbol->SetKeyWords( value );
716 footprintsList.push_back( value );
719 symbol->SetFPFilters( footprintsList );
728 symbol->SetExcludedFromSim( *val );
732 wxLogTrace(
traceDatabase, wxT(
"loadSymbolFromRow: exclude_from_sim value for %s "
733 "could not be cast to a boolean" ), aSymbolName );
744 symbol->SetExcludedFromBoard( *val );
748 wxLogTrace(
traceDatabase, wxT(
"loadSymbolFromRow: exclude_from_board value for %s "
749 "could not be cast to a boolean" ), aSymbolName );
760 symbol->SetExcludedFromBOM( *val );
764 wxLogTrace(
traceDatabase, wxT(
"loadSymbolFromRow: exclude_from_bom value for %s "
765 "could not be cast to a boolean" ), aSymbolName );
769 std::vector<SCH_FIELD*> fields;
770 symbol->GetFields( fields );
772 std::unordered_map<wxString, SCH_FIELD*> fieldsMap;
775 fieldsMap[field->GetName()] = field;
777 static const wxString c_valueFieldName( wxS(
"Value" ) );
778 static const wxString c_datasheetFieldName( wxS(
"Datasheet" ) );
779 static const wxString c_footprintFieldName( wxS(
"Footprint" ) );
785 int dbFieldOrdinal = symbol->GetNextFieldOrdinal();
789 if( !aRow.count( mapping.
column ) )
791 wxLogTrace(
traceDatabase, wxT(
"loadSymbolFromRow: field %s not found in result" ),
805 strValue = std::any_cast<std::string>( aRow.at( mapping.
column ) );
807 catch( std::bad_any_cast& )
811 wxString value(
strValue.c_str(), wxConvUTF8 );
813 if( mapping.
name_wx == c_valueFieldName )
815 SCH_FIELD& field = symbol->GetValueField();
825 else if( mapping.
name_wx == c_datasheetFieldName )
827 SCH_FIELD& field = symbol->GetDatasheetField();
845 if( fieldsMap.count( mapping.
name_wx ) )
847 field = fieldsMap[mapping.
name_wx];
854 fieldsMap[mapping.
name_wx] = field;
876 symbol->AddDrawItem( field,
false );
884 symbol->GetDrawItems().sort();
889 symbol->RefreshLibraryTreeCaches();
std::map< std::string, std::any > ROW
Dialog helper object to sit in the inheritance tree between wxDialog and any class written by wxFormB...
virtual void SetVisible(bool aVisible)
A logical library item identifier and consists of various portions much like a URI.
int Parse(const UTF8 &aId, bool aFix=false)
Parse LIB_ID with the information from aId.
bool IsValid() const
Check if this LID_ID is valid.
void SetSubLibraryName(const UTF8 &aName)
const UTF8 & GetLibNickname() const
Return the logical library name portion of a LIB_ID.
static UTF8 FixIllegalChars(const UTF8 &aLibItemName, bool aLib)
Replace illegal LIB_ID item name characters with underscores '_'.
Define a library symbol object.
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.
void SetOrdinal(int aOrdinal)
void SetAutoAdded(bool aAutoAdded)
void SetName(const wxString &aName)
void SetText(const wxString &aText) override
void SetNameShown(bool aShown=true)
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)
static const char * PropPowerSymsOnly
An 8 bit string that is assuredly encoded in UTF8, and supplies special conversion support to and fro...
const char * c_str() const
const char *const traceDatabase
static constexpr void hash_combine(std::size_t &seed)
This is a dummy function to take the final case of hash_combine below.
#define THROW_IO_ERROR(msg)
macro which captures the "call site" values of FILE_, __FUNCTION & LINE
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 ...
std::vector< ASSOCIATED_FOOTPRINT > ParseAssociatedFootprints(const nlohmann::json &aParent)
Parse the spec-form footprint associations from aParent["associated_footprints"] (issue #2282).
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)...
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).
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)
std::string footprint_filters
std::string exclude_from_sim
std::string exclude_from_board
std::string exclude_from_bom
@ USER
The field ID hasn't been set yet; field is invalid.
std::vector< std::vector< std::string > > table
wxString result
Test unit parsing edge cases and error handling.