KiCad PCB EDA Suite
Loading...
Searching...
No Matches
database_lib_settings.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
8* modify it under the terms of the GNU General Public License
9* as published by the Free Software Foundation; either version 2
10* of the License, or (at your option) any later version.
11*
12* This program is distributed in the hope that it will be useful,
13* but WITHOUT ANY WARRANTY; without even the implied warranty of
14* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15* GNU 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 <core/kicad_algo.h>
22#include <json_common.h>
23#include <algorithm>
24#include <cctype>
25#include <map>
26#include <set>
27
28#include <boost/algorithm/string.hpp>
29
31#include <kiplatform/secrets.h>
33#include <settings/parameters.h>
34#include <string_utils.h>
36
37#include <wx/filename.h>
38
39
40const int dblibSchemaVersion = 1;
41
42
44 visible_on_add( false ),
45 visible_in_chooser( false ),
46 show_name( false ),
47 inherit_properties( false ),
48 source( nlohmann::json::object() )
49{
50}
51
52
53DATABASE_FIELD_MAPPING::DATABASE_FIELD_MAPPING( const std::string& aColumn, const std::string& aName,
54 bool aVisibleOnAdd, bool aVisibleInChooser,
55 bool aShowName, bool aInheritProperties ) :
56 column( aColumn ),
57 name( aName ),
58 name_wx( aName.c_str(), wxConvUTF8 ),
59 visible_on_add( aVisibleOnAdd ),
60 visible_in_chooser( aVisibleInChooser ),
61 show_name( aShowName ),
62 inherit_properties( aInheritProperties ),
63 source( nlohmann::json::object() )
64{
65}
66
67
68void DATABASE_FIELD_MAPPING::SetName( const std::string& aName )
69{
70 name = aName;
71 name_wx = wxString( aName.c_str(), wxConvUTF8 );
72}
73
74
84static std::map<std::string, std::string> parseConnectionString( const std::string& aConnectionString )
85{
86 std::map<std::string, std::string> pairs;
87 const size_t len = aConnectionString.size();
88 size_t pos = 0;
89
90 auto skipSpaces = [&]()
91 {
92 while( pos < len && std::isspace( static_cast<unsigned char>( aConnectionString[pos] ) ) )
93 ++pos;
94 };
95
96 while( true )
97 {
98 skipSpaces();
99
100 if( pos >= len )
101 break;
102
103 if( aConnectionString[pos] == ';' )
104 {
105 ++pos;
106 continue;
107 }
108
109 size_t eq = aConnectionString.find_first_of( "=;", pos );
110
111 if( eq == std::string::npos || aConnectionString[eq] == ';' )
112 return {};
113
114 std::string key = boost::algorithm::trim_right_copy( aConnectionString.substr( pos, eq - pos ) );
115 boost::algorithm::to_lower( key );
116
117 if( key.empty() )
118 return {};
119
120 pos = eq + 1;
121 skipSpaces();
122
123 std::string value;
124
125 if( pos < len && aConnectionString[pos] == '{' )
126 {
127 ++pos;
128
129 bool closed = false;
130
131 while( pos < len && !closed )
132 {
133 const char c = aConnectionString[pos++];
134
135 if( c != '}' )
136 value += c;
137 else if( pos < len && aConnectionString[pos] == '}' )
138 value += aConnectionString[pos++];
139 else
140 closed = true;
141 }
142
143 if( !closed )
144 return {};
145
146 skipSpaces();
147
148 if( pos < len && aConnectionString[pos] != ';' )
149 return {};
150 }
151 else
152 {
153 size_t end = std::min( aConnectionString.find( ';', pos ), len );
154
155 value = boost::algorithm::trim_right_copy( aConnectionString.substr( pos, end - pos ) );
156
157 if( value.find_first_of( "={}\"'" ) != std::string::npos )
158 return {};
159
160 pos = end;
161 }
162
163 pairs.emplace( key, value );
164 }
165
166 return pairs;
167}
168
169
171static bool holdsAssignment( const std::string& aText )
172{
173 return aText.find( '=' ) != std::string::npos;
174}
175
176
177DATABASE_SOURCE DATABASE_SOURCE::Expanded( const wxString& aBaseDir ) const
178{
179 DATABASE_SOURCE expanded = *this;
180 const std::string basePath( aBaseDir.ToUTF8() );
181
182 // Database drivers that use files operate on absolute paths, so provide a mechanism
183 // for specifying on-disk databases that live next to the kicad_dbl file
184 boost::replace_all( expanded.connection_string, "${CWD}", basePath );
185 boost::replace_all( expanded.path, "${CWD}", basePath );
186
187 return expanded;
188}
189
190
191std::string DATABASE_SOURCE::Describe() const
192{
193 // A file path carries no credentials, so it is shown as is
195 return path;
196
197 if( connection_string.empty() )
198 return holdsAssignment( dsn ) ? std::string{} : dsn;
199
200 // A malformed string parses to no pairs, so nothing is shown
201 const std::map<std::string, std::string> pairs = parseConnectionString( connection_string );
202
203 auto find = [&]( std::initializer_list<const char*> aKeys ) -> std::string
204 {
205 for( const char* key : aKeys )
206 {
207 auto it = pairs.find( key );
208
209 if( it != pairs.end() && !it->second.empty() )
210 return holdsAssignment( it->second ) ? std::string{} : it->second;
211 }
212
213 return {};
214 };
215
216 // Each field is shown only if clean, so one contaminated value does not hide the other
217 const std::string driver = find( { "driver" } );
218 const std::string target = find( { "dbq", "database", "data source", "dsn", "server" } );
219
220 if( driver.empty() )
221 return target;
222
223 if( target.empty() )
224 return driver;
225
226 return target + " (" + driver + ")";
227}
228
229
234template <typename T>
235static void patchKey( nlohmann::json& aObj, const std::string& aKey, const T& aValue, const T& aParsed,
236 bool aRequired )
237{
238 if( aValue == aParsed && ( aObj.contains( aKey ) || !aRequired ) )
239 return;
240
241 if constexpr( std::is_same_v<T, std::string> )
242 {
243 if( aValue.empty() && !aRequired )
244 {
245 aObj.erase( aKey );
246 return;
247 }
248 }
249
250 aObj[aKey] = aValue;
251}
252
253
255{
256 DATABASE_FIELD_MAPPING field( fetchOrDefault<std::string>( aEntry, "column" ),
257 fetchOrDefault<std::string>( aEntry, "name" ),
258 fetchOrDefault<bool>( aEntry, "visible_on_add" ),
259 fetchOrDefault<bool>( aEntry, "visible_in_chooser" ),
260 fetchOrDefault<bool>( aEntry, "show_name" ),
261 fetchOrDefault<bool>( aEntry, "inherit_properties" ) );
262
263 field.source = aEntry;
264 return field;
265}
266
267
269{
270 nlohmann::json out = aField.source.is_object() ? aField.source : nlohmann::json::object();
272
273 patchKey( out, "column", aField.column, parsed.column, true );
274 patchKey( out, "name", aField.name, parsed.name, true );
275 patchKey( out, "visible_on_add", aField.visible_on_add, parsed.visible_on_add, false );
276 patchKey( out, "visible_in_chooser", aField.visible_in_chooser, parsed.visible_in_chooser, false );
277 patchKey( out, "show_name", aField.show_name, parsed.show_name, false );
278 patchKey( out, "inherit_properties", aField.inherit_properties, parsed.inherit_properties, false );
279
280 return out;
281}
282
283
285{
287
288 table.source = aEntry;
289 table.name = fetchOrDefault<std::string>( aEntry, "name" );
290 table.table = fetchOrDefault<std::string>( aEntry, "table" );
291 table.key_col = fetchOrDefault<std::string>( aEntry, "key" );
292 table.symbols_col = fetchOrDefault<std::string>( aEntry, "symbols" );
293 table.footprints_col = fetchOrDefault<std::string>( aEntry, "footprints" );
294 table.pins_col = fetchOrDefault<std::string>( aEntry, "pins" );
295
296 // Sanitize library display names; currently only `/` is removed because we
297 // use it as a separator and allow it in symbol names.
298 std::erase( table.name, '/' );
299
300 if( aEntry.contains( "properties" ) && aEntry["properties"].is_object() )
301 {
302 const nlohmann::json& propJson = aEntry["properties"];
303
304 table.properties.description = fetchOrDefault<std::string>( propJson, "description" );
305 table.properties.footprint_filters = fetchOrDefault<std::string>( propJson, "footprint_filters" );
306 table.properties.keywords = fetchOrDefault<std::string>( propJson, "keywords" );
307 table.properties.exclude_from_bom = fetchOrDefault<std::string>( propJson, "exclude_from_bom" );
308 table.properties.exclude_from_board = fetchOrDefault<std::string>( propJson, "exclude_from_board" );
309 table.properties.exclude_from_sim = fetchOrDefault<std::string>( propJson, "exclude_from_sim" );
310 }
311
312 if( aEntry.contains( "fields" ) && aEntry["fields"].is_array() )
313 {
314 for( const nlohmann::json& fieldJson : aEntry["fields"] )
315 {
316 if( fieldJson.empty() || !fieldJson.is_object() )
317 continue;
318
319 table.fields.emplace_back( fieldFromJson( fieldJson ) );
320 }
321 }
322
323 return table;
324}
325
326
328{
329 nlohmann::json out = aTable.source.is_object() ? aTable.source : nlohmann::json::object();
330 DATABASE_LIB_TABLE parsed = tableFromJson( out );
331
332 patchKey( out, "name", aTable.name, parsed.name, true );
333 patchKey( out, "table", aTable.table, parsed.table, true );
334 patchKey( out, "key", aTable.key_col, parsed.key_col, true );
335 patchKey( out, "symbols", aTable.symbols_col, parsed.symbols_col, true );
336 patchKey( out, "footprints", aTable.footprints_col, parsed.footprints_col, true );
337 patchKey( out, "pins", aTable.pins_col, parsed.pins_col, false );
338
339 const MAPPABLE_SYMBOL_PROPERTIES& props = aTable.properties;
340 const MAPPABLE_SYMBOL_PROPERTIES& oldProps = parsed.properties;
341 bool hadProps = out.contains( "properties" );
342 nlohmann::json propJson = hadProps ? out["properties"] : nlohmann::json::object();
343
344 // A wrong-typed raw value is left alone unless the user changed a mapping
345 if( props != oldProps && !propJson.is_object() )
346 propJson = nlohmann::json::object();
347
348 if( propJson.is_object() )
349 {
350 patchKey( propJson, "description", props.description, oldProps.description, false );
351 patchKey( propJson, "footprint_filters", props.footprint_filters, oldProps.footprint_filters, false );
352 patchKey( propJson, "keywords", props.keywords, oldProps.keywords, false );
353 patchKey( propJson, "exclude_from_bom", props.exclude_from_bom, oldProps.exclude_from_bom, false );
354 patchKey( propJson, "exclude_from_board", props.exclude_from_board, oldProps.exclude_from_board, false );
355 patchKey( propJson, "exclude_from_sim", props.exclude_from_sim, oldProps.exclude_from_sim, false );
356
357 if( hadProps || !propJson.empty() )
358 out["properties"] = propJson;
359 }
360
361 if( !aTable.fields.empty() || out.contains( "fields" ) )
362 {
363 nlohmann::json fieldsJson = nlohmann::json::array();
364
365 for( const DATABASE_FIELD_MAPPING& field : aTable.fields )
366 fieldsJson.push_back( fieldToJson( field ) );
367
368 // Keep raw entries the parser skipped (non-objects) when the mapping was not edited
369 bool fieldsEdited = aTable.fields.size() != parsed.fields.size();
370
371 for( size_t i = 0; !fieldsEdited && i < aTable.fields.size(); ++i )
372 fieldsEdited = fieldsJson[i] != fieldToJson( parsed.fields[i] );
373
374 if( fieldsEdited || !out.contains( "fields" ) )
375 out["fields"] = fieldsJson;
376 }
377
378 return out;
379}
380
381
382DATABASE_LIB_SETTINGS::DATABASE_LIB_SETTINGS( const std::string& aFilename ) :
384{
385 m_params.emplace_back( new PARAM<std::string>( "name", &m_Name, "" ) );
386
387 m_params.emplace_back( new PARAM<std::string>( "description", &m_Description, "" ) );
388
389 m_params.emplace_back( new PARAM_LAMBDA<nlohmann::json>(
390 "source.type",
391 [&]() -> nlohmann::json
392 {
393 switch( m_Source.type )
394 {
395 case DATABASE_SOURCE_TYPE::ODBC: return "odbc";
396 case DATABASE_SOURCE_TYPE::SQLITE: return "sqlite";
397 case DATABASE_SOURCE_TYPE::ACCESS: return "access";
398 case DATABASE_SOURCE_TYPE::INVALID: return m_Source.type_name;
399 }
400
401 return "odbc";
402 },
403 [&]( const nlohmann::json& aType )
404 {
405 m_Source.type_name.clear();
406
407 if( aType == "odbc" )
408 {
410 }
411 else if( aType == "sqlite" )
412 {
414 }
415 else if( aType == "access" )
416 {
418 }
419 else
420 {
422 m_Source.type_name = aType.is_string() ? aType.get<std::string>() : aType.dump();
423 }
424 },
425 "odbc" ) );
426
427 m_params.emplace_back( new PARAM<std::string>( "source.path", &m_Source.path, "" ) );
428
429 m_params.emplace_back( new PARAM<std::string>( "source.dsn", &m_Source.dsn, "" ) );
430
431 m_params.emplace_back( new PARAM<std::string>( "source.username", &m_Source.username, "" ) );
432
433 m_params.emplace_back( new PARAM<std::string>( "source.password", &m_Source.password, "" ) );
434
435 m_params.emplace_back( new PARAM<std::string>( "source.connection_string",
436 &m_Source.connection_string, "" ) );
437
438 m_params.emplace_back(
439 new PARAM<int>( "source.timeout_seconds", &m_Source.timeout, DEFAULT_DATABASE_TIMEOUT_SECONDS ) );
440
441 m_params.emplace_back( new PARAM_LAMBDA<nlohmann::json>(
442 "libraries",
443 [&]() -> nlohmann::json
444 {
445 nlohmann::json libraries = nlohmann::json::array();
446
447 for( const DATABASE_LIB_TABLE& table : m_Tables )
448 libraries.push_back( tableToJson( table ) );
449
450 return libraries;
451 },
452 [&]( const nlohmann::json& aObj )
453 {
454 m_Tables.clear();
455
456 if( !aObj.is_array() )
457 return;
458
459 for( const nlohmann::json& entry : aObj )
460 {
461 if( entry.empty() || !entry.is_object() )
462 continue;
463
464 m_Tables.emplace_back( tableFromJson( entry ) );
465 }
466 },
467 {} ) );
468
469 m_params.emplace_back( new PARAM<int>( "cache.max_size", &m_Cache.max_size, 256 ) );
470
471 m_params.emplace_back( new PARAM<int>( "cache.max_age", &m_Cache.max_age, 60 ) );
472
473 m_params.emplace_back( new PARAM<bool>( "globally_unique_keys", &m_GloballyUniqueKeys, false ) );
474
475 registerMigration( 0, 1,
476 [&]() -> bool
477 {
478 /*
479 * Schema 0 -> 1
480 * Move internal symbol properties from fields with special names to
481 * a separate place in the schema.
482 */
483 if( !Contains( "libraries" ) || !At( "libraries" ).is_array() )
484 return true;
485
486 for( nlohmann::json& library : At( "libraries" ) )
487 {
488 if( !library.contains( "fields" ) )
489 continue;
490
491 for( const nlohmann::json& field : library["fields"] )
492 {
493 if( !field.contains( "name" ) || !field.contains( "column" ) )
494 continue;
495
496 std::string name = field["name"].get<std::string>();
497 std::string col = field["column"].get<std::string>();
498
499 if( name == "ki_description" )
500 library["properties"]["description"] = col;
501 else if( name == "ki_fp_filters" )
502 library["properties"]["footprint_filters"] = col;
503 }
504 }
505
506 return true;
507 } );
508}
509
510
512static constexpr const char* c_scalarParents[] = { "/source", "/cache" };
513
514
517{
518 for( const char* parent : c_scalarParents )
519 {
520 nlohmann::json::json_pointer ptr( parent );
521
522 if( aInternals.contains( ptr ) && !aInternals[ptr].is_object() )
523 aInternals[ptr] = nlohmann::json::object();
524 }
525}
526
527
529{
531
532 // A schema migration saves right after loading, and that save already needs this baseline
534}
535
536
538{
540
541 bool modified = JSON_SETTINGS::Store();
542
543 const nlohmann::json& original = originalJson();
544
545 // A new file gets every key written
546 if( !original.is_object() || original.empty() )
547 return modified;
548
549 const std::vector<std::pair<std::string, bool>> unchanged = {
550 { "name", m_Name == m_loaded.name },
551 { "description", m_Description == m_loaded.description },
552 { "source.type", m_Source.type == m_loaded.source.type && m_Source.type_name == m_loaded.source.type_name },
553 { "source.path", m_Source.path == m_loaded.source.path },
554 { "source.dsn", m_Source.dsn == m_loaded.source.dsn },
555 { "source.username", m_Source.username == m_loaded.source.username },
556 { "source.password", m_Source.password == m_loaded.source.password },
557 { "source.connection_string", m_Source.connection_string == m_loaded.source.connection_string },
558 { "source.timeout_seconds", m_Source.timeout == m_loaded.source.timeout },
559 { "cache.max_size", m_Cache.max_size == m_loaded.cache.max_size },
560 { "cache.max_age", m_Cache.max_age == m_loaded.cache.max_age },
561 { "globally_unique_keys", m_GloballyUniqueKeys == m_loaded.globallyUniqueKeys }
562 };
563
564 std::set<std::string> editedParents;
565
566 for( const auto& [path, isUnchanged] : unchanged )
567 {
568 nlohmann::json::json_pointer ptr = JSON_SETTINGS_INTERNALS::PointerFromString( path );
569
570 if( !isUnchanged )
571 {
572 editedParents.insert( ptr.parent_pointer().to_string() );
573 continue;
574 }
575
576 if( original.contains( ptr ) )
577 ( *Internals() )[ptr] = original[ptr];
578 else if( Internals()->contains( ptr.parent_pointer() ) )
579 ( *Internals() )[ptr.parent_pointer()].erase( ptr.back() );
580 }
581
582 // Base Store() creates parent objects, so restore wholly untouched ones to their raw form
583 for( const char* parent : c_scalarParents )
584 {
585 nlohmann::json::json_pointer ptr( parent );
586
587 if( editedParents.contains( parent ) )
588 continue;
589
590 if( original.contains( ptr ) )
591 ( *Internals() )[ptr] = original[ptr];
592 else
593 Internals()->erase( ptr.back() );
594 }
595
596 return modified;
597}
598
599
601{
603 m_loaded.source.password = m_Source.password;
604}
605
606
608{
609 return m_Source.Expanded( aBaseDir.IsEmpty() ? wxFileName( GetFilename() ).GetPath() : aBaseDir );
610}
611
612
614{
615 wxFileName path( m_filename );
616 path.SetExt( getFileExt() );
617
618 return path.GetFullPath();
619}
620
621
626
627
628std::unique_ptr<DATABASE_LIB_SETTINGS> LoadDatabaseLibSettingsReadOnly( const wxString& aPath, bool* aLoaded )
629{
630 auto settings = std::make_unique<DATABASE_LIB_SETTINGS>( std::string( aPath.ToUTF8() ) );
631
632 // Read-only before loading so a schema migration cannot rewrite the file
633 settings->SetReadOnly( true );
634 bool loaded = settings->LoadFromFile();
635
636 // The path LoadFromFile() reads has the extension forced; an unreadable file loads as
637 // defaults with success reported
638 wxFileName path( settings->GetLoadPath() );
639
640 if( aLoaded )
641 *aLoaded = !path.FileExists() || ( loaded && path.IsFileReadable() );
642
643 return settings;
644}
645
646
647wxString DefaultDatabaseLibFileName( const wxString& aLibName )
648{
649 wxString name = aLibName;
650 name.Trim( true ).Trim( false );
652
653 // A name of only dots would hide the file or name its folder
654 if( name.IsEmpty() || name.find_first_not_of( wxS( "._" ) ) == wxString::npos )
655 return wxS( "database_library" );
656
657 return name;
658}
659
660
661std::string DatabasePathForStorage( const wxString& aPath, const wxString& aBaseDir )
662{
663 const std::string unchanged( aPath.ToUTF8() );
664
665 wxFileName file( aPath );
666 wxFileName base;
667 base.AssignDir( aBaseDir );
668
669 if( aPath.IsEmpty() || aBaseDir.IsEmpty() || !file.IsAbsolute() || !base.IsAbsolute() )
670 return unchanged;
671
672 file.Normalize( wxPATH_NORM_DOTS );
673 base.Normalize( wxPATH_NORM_DOTS );
674
675 if( !file.GetVolume().IsSameAs( base.GetVolume(), wxFileName::IsCaseSensitive() ) )
676 return unchanged;
677
678 // MakeRelativeTo resolves long names and shortcuts, which stalls on an unreachable share
679 const wxArrayString& baseDirs = base.GetDirs();
680 const wxArrayString& fileDirs = file.GetDirs();
681
682 if( file.GetFullName().IsEmpty() || fileDirs.GetCount() < baseDirs.GetCount() )
683 return unchanged;
684
685 for( size_t i = 0; i < baseDirs.GetCount(); ++i )
686 {
687 if( !fileDirs[i].IsSameAs( baseDirs[i], wxFileName::IsCaseSensitive() ) )
688 return unchanged;
689 }
690
691 wxString relative;
692
693 for( size_t i = baseDirs.GetCount(); i < fileDirs.GetCount(); ++i )
694 relative << fileDirs[i] << wxS( "/" );
695
696 relative << file.GetFullName();
697
698 return "${CWD}/" + std::string( relative.ToUTF8() );
699}
700
701
702wxString DatabasePathFromInput( const wxString& aInput, const wxString& aBaseDir )
703{
704 if( aInput.IsEmpty() )
705 return aInput;
706
708 source.path = aInput.ToUTF8();
709
710 const wxString expanded = wxString::FromUTF8( source.Expanded( aBaseDir ).path );
711 wxFileName file( expanded );
712
713 if( file.IsAbsolute() )
714 return file.GetFullPath();
715
716 // GetFullPath and Normalize switch to the working directory of a foreign volume, which touches that drive
717 const bool rooted = !expanded.IsEmpty() && wxFileName::GetPathSeparators().Find( expanded[0] ) != wxNOT_FOUND;
718
719 if( file.HasVolume() || rooted || aBaseDir.IsEmpty() )
720 return expanded;
721
722 file.Normalize( wxPATH_NORM_DOTS | wxPATH_NORM_ABSOLUTE, aBaseDir );
723
724 return file.GetFullPath();
725}
726
727
728static wxString passwordService( const DATABASE_SOURCE& aSource )
729{
730 return wxS( "KiCad ODBC:" ) + wxString::FromUTF8( aSource.dsn );
731}
732
733
738
739
741{
742 using NO_PROMPT_FN = bool ( * )( const wxString&, const wxString&, wxString& );
743
744 const NO_PROMPT_FN* target = aLookup.target<NO_PROMPT_FN>();
745
746 return target && *target == &KIPLATFORM::SECRETS::GetSecretNoPrompt;
747}
748
749
750static bool hasKeyringLogin( const DATABASE_SOURCE& aSource )
751{
752 // File sources have no login, and without a user name the DSN supplies its own credentials
753 return aSource.type == DATABASE_SOURCE_TYPE::ODBC && aSource.connection_string.empty() && !aSource.dsn.empty()
754 && !aSource.username.empty();
755}
756
757
758bool GetDatabasePassword( const DATABASE_SOURCE& aSource, std::string& aPassword,
759 const DATABASE_SECRET_LOOKUP& aLookup )
760{
761 if( !hasKeyringLogin( aSource ) )
762 return false;
763
764 DATABASE_SECRET_LOOKUP lookup = aLookup ? aLookup : DefaultDatabaseSecretLookup();
765 wxString secret;
766
767 if( !lookup( passwordService( aSource ), wxString::FromUTF8( aSource.username ), secret ) )
768 return false;
769
770 aPassword = secret.utf8_string();
771 return true;
772}
773
774
776{
777 if( aSource.password.empty() )
778 GetDatabasePassword( aSource, aSource.password, aLookup );
779}
780
781
782bool StoreDatabasePassword( const DATABASE_SOURCE& aSource, const std::string& aPassword )
783{
784 if( !hasKeyringLogin( aSource ) )
785 return false;
786
787 wxString service = passwordService( aSource );
788 wxString user = wxString::FromUTF8( aSource.username );
789
790 if( aPassword.empty() )
791 return KIPLATFORM::SECRETS::DeleteSecret( service, user );
792
793 return KIPLATFORM::SECRETS::StoreSecret( service, user, wxString::FromUTF8( aPassword ) );
794}
const char * name
static DATABASE_LIB_TABLE tableFromJson(const nlohmann::json &aEntry)
Missing or mistyped keys load as defaults so one incomplete entry cannot stop the others.
void ResolvePassword(const DATABASE_SECRET_LOOKUP &aLookup=nullptr)
Fills in the source password from the keyring when the file has none.
DATABASE_LIB_SETTINGS(const std::string &aFilename)
wxString getFileExt() const override
static DATABASE_FIELD_MAPPING fieldFromJson(const nlohmann::json &aEntry)
struct DATABASE_LIB_SETTINGS::LOADED_SCALARS m_loaded
DATABASE_SOURCE ExpandedSource(const wxString &aBaseDir=wxEmptyString) const
bool Store() override
Stores parameters, then restores the raw file value of every scalar the caller left unchanged so that...
void Load() override
Records the scalars as loaded; runs before a schema migration writes the file back.
static nlohmann::json tableToJson(const DATABASE_LIB_TABLE &aTable)
DATABASE_CACHE_SETTINGS m_Cache
static nlohmann::json fieldToJson(const DATABASE_FIELD_MAPPING &aField)
static nlohmann::json::json_pointer PointerFromString(std::string aPath)
Builds a JSON pointer based on a given string.
const nlohmann::json & originalJson() const
wxString m_filename
The filename (not including path) of this settings file (inicode)
virtual void Load()
Updates the parameters of this object based on the current JSON document contents.
std::vector< PARAM_BASE * > m_params
The list of parameters (owned by this object)
JSON_SETTINGS_INTERNALS * Internals()
static ResultType fetchOrDefault(const nlohmann::json &aJson, const std::string &aKey, ResultType aDefault=ResultType())
Helper to retrieve a value from a JSON object (dictionary) as a certain result type.
JSON_SETTINGS(const wxString &aFilename, SETTINGS_LOC aLocation, int aSchemaVersion)
virtual bool Store()
Stores the current parameters into the JSON document represented by this object Note: this doesn't do...
wxString GetFilename() const
Like a normal param, but with custom getter and setter functions.
Definition parameters.h:299
static std::map< std::string, std::string > parseConnectionString(const std::string &aConnectionString)
Splits a connection string into lower-case keys and values for display.
wxString DefaultDatabaseLibFileName(const wxString &aLibName)
static bool holdsAssignment(const std::string &aText)
A shown value holding '=' has swallowed another key's assignment, possibly a credential.
const int dblibSchemaVersion
bool IsNoPromptSecretLookup(const DATABASE_SECRET_LOOKUP &aLookup)
static constexpr const char * c_scalarParents[]
Objects that hold scalar settings rather than library tables.
static void normalizeScalarParents(JSON_SETTINGS_INTERNALS &aInternals)
Nested params cannot store into a non-object parent, so replace a malformed one before storing.
static void patchKey(nlohmann::json &aObj, const std::string &aKey, const T &aValue, const T &aParsed, bool aRequired)
Writes aValue to aObj[aKey] only if it differs from aParsed, the value the raw key was read as.
std::unique_ptr< DATABASE_LIB_SETTINGS > LoadDatabaseLibSettingsReadOnly(const wxString &aPath, bool *aLoaded)
Loads a database library settings file without allowing the load itself (e.g.
static wxString passwordService(const DATABASE_SOURCE &aSource)
std::string DatabasePathForStorage(const wxString &aPath, const wxString &aBaseDir)
void ResolveDatabasePassword(DATABASE_SOURCE &aSource, const DATABASE_SECRET_LOOKUP &aLookup)
Fills in the source password from the keyring, but only when the library file did not supply one.
static bool hasKeyringLogin(const DATABASE_SOURCE &aSource)
wxString DatabasePathFromInput(const wxString &aInput, const wxString &aBaseDir)
bool StoreDatabasePassword(const DATABASE_SOURCE &aSource, const std::string &aPassword)
Stores the password for the source's DSN login in the system keyring, or removes the entry when the p...
DATABASE_SECRET_LOOKUP DefaultDatabaseSecretLookup()
The lookup used when none is injected, which must never prompt to unlock the keyring.
bool GetDatabasePassword(const DATABASE_SOURCE &aSource, std::string &aPassword, const DATABASE_SECRET_LOOKUP &aLookup)
DSN passwords that are not saved in the (often shared) library file live in the system keyring,...
KICOMMON_API void ResolveDatabasePassword(DATABASE_SOURCE &aSource, const DATABASE_SECRET_LOOKUP &aLookup=nullptr)
Fills in the source password from the keyring, but only when the library file did not supply one.
std::function< bool(const wxString &aService, const wxString &aKey, wxString &aSecret)> DATABASE_SECRET_LOOKUP
Keyring lookup signature, matching KIPLATFORM::SECRETS::GetSecretNoPrompt.
constexpr int DEFAULT_DATABASE_TIMEOUT_SECONDS
The source timeout a library file gets when it sets none.
@ NONE
Definition eda_fill.h:42
nlohmann::json json
Definition gerbview.cpp:50
static const std::string DatabaseLibraryFileExtension
std::string source
SETTINGS_LOC
bool DeleteSecret(const wxString &aService, const wxString &aKey)
bool StoreSecret(const wxString &aService, const wxString &aKey, const wxString &aSecret)
bool GetSecretNoPrompt(const wxString &aService, const wxString &aKey, wxString &aSecret)
Like GetSecret(), but never waits on the user.
bool ReplaceIllegalFileNameChars(std::string &aName, int aReplaceChar)
Checks aName for illegal file name characters.
bool visible_in_chooser
Whether the column is shown by default in the chooser.
std::string column
Database column name.
std::string name
KiCad field name.
void SetName(const std::string &aName)
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.
nlohmann::json source
Raw JSON as loaded; untouched keys are written back verbatim.
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)
nlohmann::json source
Raw JSON as loaded; untouched keys are written back verbatim.
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)
DATABASE_SOURCE Expanded(const wxString &aBaseDir) const
std::string Describe() const
std::string path
Database file of a SQLITE or ACCESS source.
std::string connection_string
DATABASE_SOURCE_TYPE type
const std::string table
std::string path
VECTOR2I end
Definition of file extensions used in Kicad.