KiCad PCB EDA Suite
Loading...
Searching...
No Matches
database_connection.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 along
18 * with this program. If not, see <http://www.gnu.org/licenses/>.
19 */
20
21#include <boost/algorithm/string.hpp>
22#include <boost/locale.hpp>
23#include <fmt/core.h>
24#include <nanodbc/nanodbc.h>
25
26// Some outdated definitions are used in sql.h
27// We need to define them for "recent" dev tools
28#define INT64 int64_t
29#define UINT64 uint64_t
30
31#ifdef __MINGW32__
32#define BYTE uint8_t
33#define WORD uint16_t
34#define DWORD uint32_t
35#define HWND uint32_t /* dummy define */
36#endif
37
38#ifdef WIN32
39#include <windows.h> // for sql.h
40#endif
41
42#include <sql.h> // SQL_IDENTIFIER_QUOTE_CHAR
43
44#include <wx/log.h>
45
48#include <core/profile.h>
49
50
51const char* const traceDatabase = "KICAD_DATABASE";
52
66nanodbc::string fromUTF8( const std::string& aString )
67{
68 return boost::locale::conv::utf_to_utf<nanodbc::string::value_type>( aString );
69}
70
71
77std::string toUTF8( const nanodbc::string& aString )
78{
79 return boost::locale::conv::utf_to_utf<char>( aString );
80}
81
82
83DATABASE_CONNECTION::DATABASE_CONNECTION( const std::string& aDataSourceName,
84 const std::string& aUsername,
85 const std::string& aPassword, int aTimeoutSeconds,
86 bool aConnectNow ) :
87 m_quoteChar( '"' )
88{
89 m_dsn = aDataSourceName;
90 m_user = aUsername;
91 m_pass = aPassword;
92 m_timeout = aTimeoutSeconds;
93
94 init();
95
96 if( aConnectNow )
97 Connect();
98}
99
100
101DATABASE_CONNECTION::DATABASE_CONNECTION( const std::string& aConnectionString,
102 int aTimeoutSeconds, bool aConnectNow ) :
103 m_quoteChar( '"' )
104{
105 m_connectionString = aConnectionString;
106 m_timeout = aTimeoutSeconds;
107
108 init();
109
110 if( aConnectNow )
111 Connect();
112}
113
114
116{
117 Disconnect();
118 m_conn.reset();
119}
120
121
123{
124 m_cache = std::make_unique<DB_CACHE_TYPE>( 10, 1 );
125}
126
127
128void DATABASE_CONNECTION::SetCacheParams( int aMaxSize, int aMaxAge )
129{
130 if( !m_cache )
131 return;
132
133 if( aMaxSize < 0 )
134 aMaxSize = 0;
135
136 if( aMaxAge < 0 )
137 aMaxAge = 0;
138
139 m_cache->SetMaxSize( static_cast<size_t>( aMaxSize ) );
140 m_cache->SetMaxAge( static_cast<time_t>( aMaxAge ) );
141}
142
143
145{
146 nanodbc::string dsn = fromUTF8( m_dsn );
147 nanodbc::string user = fromUTF8( m_user );
148 nanodbc::string pass = fromUTF8( m_pass );
149 nanodbc::string cs = fromUTF8( m_connectionString );
150
151 try
152 {
153 if( cs.empty() )
154 {
155 wxLogTrace( traceDatabase, wxT( "Creating connection to DSN %s" ), m_dsn );
156 m_conn = std::make_unique<nanodbc::connection>( dsn, user, pass, m_timeout );
157 }
158 else
159 {
160 wxLogTrace( traceDatabase, wxT( "Creating connection with connection string" ) );
161 m_conn = std::make_unique<nanodbc::connection>( cs, m_timeout );
162 }
163 }
164 catch( nanodbc::database_error& e )
165 {
166 m_lastError = e.what();
167 return false;
168 }
169
170 m_tables.clear();
171
172 if( IsConnected() )
173 getQuoteChar();
174
175 return IsConnected();
176}
177
178
180{
181 if( !m_conn )
182 {
183 wxLogTrace( traceDatabase, wxT( "Note: Disconnect() called without valid connection" ) );
184 return false;
185 }
186
187 try
188 {
189 m_conn->disconnect();
190 }
191 catch( boost::locale::conv::conversion_error& exc )
192 {
193 wxLogTrace( traceDatabase, wxT( "Disconnect() error \"%s\" occured." ), exc.what() );
194 return false;
195 }
196
197 return !m_conn->connected();
198}
199
200
202{
203 if( !m_conn )
204 return false;
205
206 return m_conn->connected();
207}
208
209
210bool DATABASE_CONNECTION::CacheTableInfo( const std::string& aTable,
211 const std::set<std::string>& aColumns )
212{
213 if( !m_conn )
214 return false;
215
216 try
217 {
218 nanodbc::catalog catalog( *m_conn );
219 nanodbc::catalog::tables tables = catalog.find_tables( fromUTF8( aTable ) );
220
221 if( !tables.next() )
222 {
223 wxLogTrace( traceDatabase, wxT( "CacheTableInfo: table '%s' not found in catalog" ),
224 aTable );
225 return false;
226 }
227
228 std::string key = toUTF8( tables.table_name() );
229 m_tables[key] = toUTF8( tables.table_type() );
230
231 try
232 {
233 nanodbc::catalog::columns columns =
234 catalog.find_columns( NANODBC_TEXT( "" ), tables.table_name() );
235
236 while( columns.next() )
237 {
238 std::string columnKey = toUTF8( columns.column_name() );
239
240 if( aColumns.count( boost::to_lower_copy( columnKey ) ) )
241 m_columnCache[key][columnKey] = columns.data_type();
242 }
243
244 }
245 catch( nanodbc::database_error& e )
246 {
247 m_lastError = e.what();
248 wxLogTrace( traceDatabase, wxT( "Exception while syncing columns for table '%s': %s" ),
249 key, m_lastError );
250 return false;
251 }
252 }
253 catch( nanodbc::database_error& e )
254 {
255 m_lastError = e.what();
256 wxLogTrace( traceDatabase, wxT( "Exception while caching table info: %s" ), m_lastError );
257 return false;
258 }
259
260 return true;
261}
262
263
265{
266 if( !m_conn )
267 return false;
268
269 try
270 {
271 nanodbc::string qc = m_conn->get_info<nanodbc::string>( SQL_IDENTIFIER_QUOTE_CHAR );
272
273 if( qc.empty() )
274 return false;
275
276 m_quoteChar = *toUTF8( qc ).begin();
277
278 wxLogTrace( traceDatabase, wxT( "Quote char retrieved: %c" ), m_quoteChar );
279 }
280 catch( nanodbc::database_error& )
281 {
282 wxLogTrace( traceDatabase, wxT( "Exception while querying quote char: %s" ), m_lastError );
283 return false;
284 }
285
286 return true;
287}
288
289
290std::string DATABASE_CONNECTION::columnsFor( const std::string& aTable )
291{
292 if( !m_columnCache.count( aTable ) )
293 {
294 wxLogTrace( traceDatabase, wxT( "columnsFor: requested table %s missing from cache!" ),
295 aTable );
296 return "*";
297 }
298
299 if( m_columnCache[aTable].empty() )
300 {
301 wxLogTrace( traceDatabase, wxT( "columnsFor: requested table %s has no columns mapped!" ),
302 aTable );
303 return "*";
304 }
305
306 std::string ret;
307
308 for( const auto& [ columnName, columnType ] : m_columnCache[aTable] )
309 ret += fmt::format( "{}{}{}, ", m_quoteChar, columnName, m_quoteChar );
310
311 // strip tailing ', '
312 ret.resize( ret.length() - 2 );
313
314 return ret;
315}
316
317//next step, make SelectOne take from the SelectAll cache if the SelectOne cache is missing.
318//To do this, need to build a map of PK->ROW for the cache result.
319bool DATABASE_CONNECTION::SelectOne( const std::string& aTable,
320 const std::pair<std::string, std::string>& aWhere,
321 DATABASE_CONNECTION::ROW& aResult )
322{
323 if( !m_conn )
324 {
325 wxLogTrace( traceDatabase, wxT( "Called SelectOne without valid connection!" ) );
326 return false;
327 }
328
329 auto tableMapIter = m_tables.find( aTable );
330
331 if( tableMapIter == m_tables.end() )
332 {
333 wxLogTrace( traceDatabase, wxT( "SelectOne: requested table %s not found in cache" ),
334 aTable );
335 return false;
336 }
337
338 const std::string& tableName = tableMapIter->first;
340
341 if( m_cache->Get( tableName, cacheEntry ) )
342 {
343 if( cacheEntry.count( aWhere.second ) )
344 {
345 wxLogTrace( traceDatabase, wxT( "SelectOne: `%s` with parameter `%s` - cache hit" ),
346 tableName, aWhere.second );
347 aResult = cacheEntry.at( aWhere.second );
348 return true;
349 }
350 }
351 else
352 {
353 wxLogTrace( traceDatabase, wxT( "SelectOne: table `%s` not in row cache; will SelectAll" ),
354 tableName, aWhere.second );
355
356 selectAllAndCache( tableName, aWhere.first );
357
358 if( m_cache->Get( tableName, cacheEntry ) )
359 {
360 if( cacheEntry.count( aWhere.second ) )
361 {
362 wxLogTrace( traceDatabase, wxT( "SelectOne: `%s` with parameter `%s` - cache hit" ),
363 tableName, aWhere.second );
364 aResult = cacheEntry.at( aWhere.second );
365 return true;
366 }
367 }
368 }
369
370 if( !m_columnCache.count( tableName ) )
371 {
372 wxLogTrace( traceDatabase, wxT( "SelectOne: requested table %s missing from column cache" ),
373 tableName );
374 return false;
375 }
376
377 auto columnCacheIter = m_columnCache.at( tableName ).find( aWhere.first );
378
379 if( columnCacheIter == m_columnCache.at( tableName ).end() )
380 {
381 wxLogTrace( traceDatabase, wxT( "SelectOne: requested column %s not found in cache for %s" ),
382 aWhere.first, tableName );
383 return false;
384 }
385
386 const std::string& columnName = columnCacheIter->first;
387
388 std::string cacheKey = fmt::format( "{}{}{}", tableName, columnName, aWhere.second );
389
390 std::string queryStr = fmt::format( "SELECT {} FROM {}{}{} WHERE {}{}{} = ?",
391 columnsFor( tableName ),
392 m_quoteChar, tableName, m_quoteChar,
393 m_quoteChar, columnName, m_quoteChar );
394 nanodbc::string query = fromUTF8( queryStr );
395
396 PROF_TIMER timer;
397 nanodbc::statement statement;
398
399 try
400 {
401 statement.prepare( *m_conn, query );
402 statement.bind( 0, aWhere.second.c_str() );
403 }
404 catch( nanodbc::database_error& e )
405 {
406 m_lastError = e.what();
407 wxLogTrace( traceDatabase, wxT( "Exception while preparing statement for SelectOne: %s" ),
408 m_lastError );
409
410 // Exception may be due to a connection error; nanodbc won't auto-reconnect
411 m_conn->disconnect();
412
413 return false;
414 }
415
416 wxLogTrace( traceDatabase, wxT( "SelectOne: `%s` with parameter `%s`" ), toUTF8( query ),
417 aWhere.second );
418
419 nanodbc::result results;
420
421 try
422 {
423 results = nanodbc::execute( statement );
424 }
425 catch( nanodbc::database_error& e )
426 {
427 m_lastError = e.what();
428 wxLogTrace( traceDatabase, wxT( "Exception while executing statement for SelectOne: %s" ),
429 m_lastError );
430
431 // Exception may be due to a connection error; nanodbc won't auto-reconnect
432 m_conn->disconnect();
433
434 return false;
435 }
436
437 timer.Stop();
438
439
440 if( !results.first() )
441 {
442 wxLogTrace( traceDatabase, wxT( "SelectOne: no results returned from query" ) );
443 return false;
444 }
445
446 wxLogTrace( traceDatabase, wxT( "SelectOne: %ld results returned from query in %0.1f ms" ),
447 results.rows(), timer.msecs() );
448
449 aResult.clear();
450
451 try
452 {
453 for( short i = 0; i < results.columns(); ++i )
454 {
455 std::string column = toUTF8( results.column_name( i ) );
456
457 switch( results.column_datatype( i ) )
458 {
459 case SQL_DOUBLE:
460 case SQL_FLOAT:
461 case SQL_REAL:
462 case SQL_DECIMAL:
463 case SQL_NUMERIC:
464 {
465 try
466 {
467 aResult[column] = fmt::format( "{:G}", results.get<double>( i ) );
468 }
469 catch( nanodbc::null_access_error& )
470 {
471 // Column was empty (null)
472 aResult[column] = std::string();
473 }
474
475 break;
476 }
477
478 default:
479 aResult[column] = toUTF8( results.get<nanodbc::string>( i, NANODBC_TEXT( "" ) ) );
480 }
481 }
482 }
483 catch( nanodbc::database_error& e )
484 {
485 m_lastError = e.what();
486 wxLogTrace( traceDatabase, wxT( "Exception while parsing results from SelectOne: %s" ),
487 m_lastError );
488 return false;
489 }
490
491 return true;
492}
493
494
495bool DATABASE_CONNECTION::selectAllAndCache( const std::string& aTable, const std::string& aKey )
496{
497 nanodbc::statement statement( *m_conn );
498
499 nanodbc::string query = fromUTF8( fmt::format( "SELECT {} FROM {}{}{}", columnsFor( aTable ),
500 m_quoteChar, aTable, m_quoteChar ) );
501
502 wxLogTrace( traceDatabase, wxT( "selectAllAndCache: `%s`" ), toUTF8( query ) );
503
504 PROF_TIMER timer;
505
506 try
507 {
508 statement.prepare( query );
509 }
510 catch( nanodbc::database_error& e )
511 {
512 m_lastError = e.what();
513 wxLogTrace( traceDatabase,
514 wxT( "Exception while preparing query for selectAllAndCache: %s" ),
515 m_lastError );
516
517 // Exception may be due to a connection error; nanodbc won't auto-reconnect
518 m_conn->disconnect();
519
520 return false;
521 }
522
523 nanodbc::result results;
524
525 try
526 {
527 results = nanodbc::execute( statement );
528 }
529 catch( nanodbc::database_error& e )
530 {
531 m_lastError = e.what();
532 wxLogTrace( traceDatabase,
533 wxT( "Exception while executing query for selectAllAndCache: %s" ),
534 m_lastError );
535
536 // Exception may be due to a connection error; nanodbc won't auto-reconnect
537 m_conn->disconnect();
538
539 return false;
540 }
541
542 timer.Stop();
543
545
546 auto handleException =
547 [&]( std::runtime_error& aException, const std::string& aExtraContext = "" )
548 {
549 m_lastError = aException.what();
550 std::string extra = aExtraContext.empty() ? "" : ": " + aExtraContext;
551 wxLogTrace( traceDatabase,
552 wxT( "Exception while parsing result %d from selectAllAndCache: %s%s" ),
553 cacheEntry.size(), m_lastError, extra );
554 };
555
556 while( results.next() )
557 {
558 short columnCount = 0;
559 ROW result;
560
561 try
562 {
563 columnCount = results.columns();
564 }
565 catch( nanodbc::database_error& e )
566 {
567 handleException( e );
568 return false;
569 }
570
571 for( short j = 0; j < columnCount; ++j )
572 {
573 std::string column;
574 std::string columnExtraDbgInfo;
575 int datatype = SQL_UNKNOWN_TYPE;
576
577 try
578 {
579 column = toUTF8( results.column_name( j ) );
580 datatype = results.column_datatype( j );
581 columnExtraDbgInfo = fmt::format( "column index {}, name '{}', type {}", j, column,
582 datatype );
583 }
584 catch( nanodbc::index_range_error& e )
585 {
586 handleException( e, columnExtraDbgInfo );
587 return false;
588 }
589
590 switch( datatype )
591 {
592 case SQL_DOUBLE:
593 case SQL_FLOAT:
594 case SQL_REAL:
595 case SQL_DECIMAL:
596 case SQL_NUMERIC:
597 {
598 try
599 {
600 result[column] = fmt::format( "{:G}", results.get<double>( j ) );
601 }
602 catch( nanodbc::null_access_error& )
603 {
604 // Column was empty (null)
605 result[column] = std::string();
606 }
607 catch( std::runtime_error& e )
608 {
609 handleException( e, columnExtraDbgInfo );
610 return false;
611 }
612 break;
613 }
614
615 default:
616 {
617 try
618 {
619 result[column] = toUTF8( results.get<nanodbc::string>( j,
620 NANODBC_TEXT( "" ) ) );
621 }
622 catch( std::runtime_error& e )
623 {
624 handleException( e, columnExtraDbgInfo );
625 return false;
626 }
627 }
628 }
629 }
630
631 if( !result.count( aKey ) )
632 {
633 wxLogTrace( traceDatabase,
634 wxT( "selectAllAndCache: warning: key %s not found in result set" ), aKey );
635 continue;
636 }
637
638 std::string keyStr = std::any_cast<std::string>( result.at( aKey ) );
639 cacheEntry[keyStr] = result;
640 }
641
642 wxLogTrace( traceDatabase, wxT( "selectAllAndCache from %s completed in %0.1f ms" ), aTable,
643 timer.msecs() );
644
645 m_cache->Put( aTable, cacheEntry );
646 return true;
647}
648
649
650bool DATABASE_CONNECTION::SelectAll( const std::string& aTable, const std::string& aKey,
651 std::vector<ROW>& aResults )
652{
653 if( !m_conn )
654 {
655 wxLogTrace( traceDatabase, wxT( "Called SelectAll without valid connection!" ) );
656 return false;
657 }
658
659 auto tableMapIter = m_tables.find( aTable );
660
661 if( tableMapIter == m_tables.end() )
662 {
663 wxLogTrace( traceDatabase, wxT( "SelectAll: requested table %s not found in cache" ),
664 aTable );
665 return false;
666 }
667
669
670 if( !m_cache->Get( aTable, cacheEntry ) )
671 {
672 if( !selectAllAndCache( aTable, aKey ) )
673 {
674 wxLogTrace( traceDatabase, wxT( "SelectAll: `%s` cache fill failed" ), aTable );
675 return false;
676 }
677
678 // Now it should be filled
679 m_cache->Get( aTable, cacheEntry );
680 }
681
682 if( !m_cache->Get( aTable, cacheEntry ) )
683 {
684 wxLogTrace( traceDatabase, wxT( "SelectAll: `%s` failed to get results from cache!" ),
685 aTable );
686 return false;
687 }
688
689 wxLogTrace( traceDatabase, wxT( "SelectAll: `%s` - returning cached results" ), aTable );
690
691 aResults.reserve( cacheEntry.size() );
692
693 for( auto &[ key, row ] : cacheEntry )
694 aResults.emplace_back( row );
695
696 return true;
697}
CacheValueType CACHE_VALUE
bool CacheTableInfo(const std::string &aTable, const std::set< std::string > &aColumns)
std::map< std::string, std::any > ROW
std::map< std::string, std::map< std::string, int > > m_columnCache
Map of table -> map of column name -> data type.
void SetCacheParams(int aMaxSize, int aMaxAge)
bool selectAllAndCache(const std::string &aTable, const std::string &aKey)
bool SelectAll(const std::string &aTable, const std::string &aKey, std::vector< ROW > &aResults)
Retrieves all rows from a database table.
DATABASE_CONNECTION(const std::string &aDataSourceName, const std::string &aUsername, const std::string &aPassword, int aTimeoutSeconds=DEFAULT_TIMEOUT, bool aConnectNow=true)
std::unique_ptr< DB_CACHE_TYPE > m_cache
std::string columnsFor(const std::string &aTable)
std::unique_ptr< nanodbc::connection > m_conn
bool SelectOne(const std::string &aTable, const std::pair< std::string, std::string > &aWhere, ROW &aResult)
Retrieves a single row from a database table.
std::map< std::string, std::string > m_tables
A small class to help profiling.
Definition: profile.h:49
void Stop()
Save the time when this function was called, and set the counter stane to stop.
Definition: profile.h:88
double msecs(bool aSinceLast=false)
Definition: profile.h:149
const char *const traceDatabase
std::string toUTF8(const nanodbc::string &aString)
Converts a string from nanodbc-native to KiCad-native.
nanodbc::string fromUTF8(const std::string &aString)
When Unicode support is enabled in nanodbc, string formats are used matching the appropriate characte...
const char *const traceDatabase
static bool empty(const wxTextEntryBase *aCtrl)