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
60
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
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( std::exception& 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( std::exception& 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( std::exception& 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( std::exception& e )
281 {
282 m_lastError = e.what();
283 wxLogTrace( traceDatabase, wxT( "Exception while querying quote char: %s" ), m_lastError );
284 return false;
285 }
286
287 return true;
288}
289
290
291std::string DATABASE_CONNECTION::columnsFor( const std::string& aTable )
292{
293 if( !m_columnCache.count( aTable ) )
294 {
295 wxLogTrace( traceDatabase, wxT( "columnsFor: requested table %s missing from cache!" ),
296 aTable );
297 return "*";
298 }
299
300 if( m_columnCache[aTable].empty() )
301 {
302 wxLogTrace( traceDatabase, wxT( "columnsFor: requested table %s has no columns mapped!" ),
303 aTable );
304 return "*";
305 }
306
307 std::string ret;
308
309 for( const auto& [ columnName, columnType ] : m_columnCache[aTable] )
310 ret += fmt::format( "{}{}{}, ", m_quoteChar, columnName, m_quoteChar );
311
312 // strip tailing ', '
313 ret.resize( ret.length() - 2 );
314
315 return ret;
316}
317
318//next step, make SelectOne take from the SelectAll cache if the SelectOne cache is missing.
319//To do this, need to build a map of PK->ROW for the cache result.
320bool DATABASE_CONNECTION::SelectOne( const std::string& aTable,
321 const std::pair<std::string, std::string>& aWhere,
322 DATABASE_CONNECTION::ROW& aResult )
323{
324 if( !m_conn )
325 {
326 wxLogTrace( traceDatabase, wxT( "Called SelectOne without valid connection!" ) );
327 return false;
328 }
329
330 auto tableMapIter = m_tables.find( aTable );
331
332 if( tableMapIter == m_tables.end() )
333 {
334 wxLogTrace( traceDatabase, wxT( "SelectOne: requested table %s not found in cache" ),
335 aTable );
336 return false;
337 }
338
339 const std::string& tableName = tableMapIter->first;
341
342 if( m_cache->Get( tableName, cacheEntry ) )
343 {
344 if( cacheEntry.count( aWhere.second ) )
345 {
346 wxLogTrace( traceDatabase, wxT( "SelectOne: `%s` with parameter `%s` - cache hit" ),
347 tableName, aWhere.second );
348 aResult = cacheEntry.at( aWhere.second );
349 return true;
350 }
351 }
352 else
353 {
354 wxLogTrace( traceDatabase, wxT( "SelectOne: table `%s` not in row cache; will SelectAll" ),
355 tableName, aWhere.second );
356
357 selectAllAndCache( tableName, aWhere.first );
358
359 if( m_cache->Get( tableName, cacheEntry ) )
360 {
361 if( cacheEntry.count( aWhere.second ) )
362 {
363 wxLogTrace( traceDatabase, wxT( "SelectOne: `%s` with parameter `%s` - cache hit" ),
364 tableName, aWhere.second );
365 aResult = cacheEntry.at( aWhere.second );
366 return true;
367 }
368 }
369 }
370
371 if( !m_columnCache.count( tableName ) )
372 {
373 wxLogTrace( traceDatabase, wxT( "SelectOne: requested table %s missing from column cache" ),
374 tableName );
375 return false;
376 }
377
378 auto columnCacheIter = m_columnCache.at( tableName ).find( aWhere.first );
379
380 if( columnCacheIter == m_columnCache.at( tableName ).end() )
381 {
382 wxLogTrace( traceDatabase, wxT( "SelectOne: requested column %s not found in cache for %s" ),
383 aWhere.first, tableName );
384 return false;
385 }
386
387 const std::string& columnName = columnCacheIter->first;
388
389 std::string cacheKey = fmt::format( "{}{}{}", tableName, columnName, aWhere.second );
390
391 std::string queryStr = fmt::format( "SELECT {} FROM {}{}{} WHERE {}{}{} = ?",
392 columnsFor( tableName ),
393 m_quoteChar, tableName, m_quoteChar,
394 m_quoteChar, columnName, m_quoteChar );
395 nanodbc::string query = fromUTF8( queryStr );
396
397 PROF_TIMER timer;
398 nanodbc::statement statement;
399
400 try
401 {
402 statement.prepare( *m_conn, query );
403 statement.bind( 0, aWhere.second.c_str() );
404 }
405 catch( std::exception& e )
406 {
407 m_lastError = e.what();
408 wxLogTrace( traceDatabase, wxT( "Exception while preparing statement for SelectOne: %s" ),
409 m_lastError );
410
411 // Exception may be due to a connection error; nanodbc won't auto-reconnect
412 Disconnect();
413
414 return false;
415 }
416
417 wxLogTrace( traceDatabase, wxT( "SelectOne: `%s` with parameter `%s`" ), toUTF8( query ),
418 aWhere.second );
419
420 nanodbc::result results;
421
422 try
423 {
424 results = nanodbc::execute( statement );
425 }
426 catch( std::exception& e )
427 {
428 m_lastError = e.what();
429 wxLogTrace( traceDatabase, wxT( "Exception while executing statement for SelectOne: %s" ),
430 m_lastError );
431
432 // Exception may be due to a connection error; nanodbc won't auto-reconnect
433 Disconnect();
434
435 return false;
436 }
437
438 timer.Stop();
439
440
441 if( !results.first() )
442 {
443 wxLogTrace( traceDatabase, wxT( "SelectOne: no results returned from query" ) );
444 return false;
445 }
446
447 wxLogTrace( traceDatabase, wxT( "SelectOne: %ld results returned from query in %0.1f ms" ),
448 results.rows(), timer.msecs() );
449
450 aResult.clear();
451
452 try
453 {
454 for( short i = 0; i < results.columns(); ++i )
455 {
456 std::string column = toUTF8( results.column_name( i ) );
457
458 switch( results.column_datatype( i ) )
459 {
460 case SQL_DOUBLE:
461 case SQL_FLOAT:
462 case SQL_REAL:
463 case SQL_DECIMAL:
464 case SQL_NUMERIC:
465 {
466 try
467 {
468 aResult[column] = fmt::format( "{:G}", results.get<double>( i ) );
469 }
470 catch( nanodbc::null_access_error& )
471 {
472 // Column was empty (null)
473 aResult[column] = std::string();
474 }
475
476 break;
477 }
478
479 default:
480 aResult[column] = toUTF8( results.get<nanodbc::string>( i, NANODBC_TEXT( "" ) ) );
481 }
482 }
483 }
484 catch( std::exception& e )
485 {
486 m_lastError = e.what();
487 wxLogTrace( traceDatabase, wxT( "Exception while parsing results from SelectOne: %s" ),
488 m_lastError );
489 return false;
490 }
491
492 return true;
493}
494
495
496bool DATABASE_CONNECTION::selectAllAndCache( const std::string& aTable, const std::string& aKey )
497{
498 nanodbc::statement statement( *m_conn );
499
500 nanodbc::string query = fromUTF8( fmt::format( "SELECT {} FROM {}{}{}", columnsFor( aTable ),
501 m_quoteChar, aTable, m_quoteChar ) );
502
503 wxLogTrace( traceDatabase, wxT( "selectAllAndCache: `%s`" ), toUTF8( query ) );
504
505 PROF_TIMER timer;
506
507 try
508 {
509 statement.prepare( query );
510 }
511 catch( std::exception& e )
512 {
513 m_lastError = e.what();
514 wxLogTrace( traceDatabase,
515 wxT( "Exception while preparing query for selectAllAndCache: %s" ),
516 m_lastError );
517
518 // Exception may be due to a connection error; nanodbc won't auto-reconnect
519 Disconnect();
520
521 return false;
522 }
523
524 nanodbc::result results;
525
526 try
527 {
528 results = nanodbc::execute( statement );
529 }
530 catch( std::exception& e )
531 {
532 m_lastError = e.what();
533 wxLogTrace( traceDatabase,
534 wxT( "Exception while executing query for selectAllAndCache: %s" ),
535 m_lastError );
536
537 // Exception may be due to a connection error; nanodbc won't auto-reconnect
538 Disconnect();
539
540 return false;
541 }
542
543 timer.Stop();
544
546
547 auto handleException =
548 [&]( std::runtime_error& aException, const std::string& aExtraContext = "" )
549 {
550 m_lastError = aException.what();
551 std::string extra = aExtraContext.empty() ? "" : ": " + aExtraContext;
552 wxLogTrace( traceDatabase,
553 wxT( "Exception while parsing result %d from selectAllAndCache: %s%s" ),
554 cacheEntry.size(), m_lastError, extra );
555 };
556
557 while( results.next() )
558 {
559 short columnCount = 0;
560 ROW result;
561
562 try
563 {
564 columnCount = results.columns();
565 }
566 catch( nanodbc::database_error& e )
567 {
568 handleException( e );
569 return false;
570 }
571
572 for( short j = 0; j < columnCount; ++j )
573 {
574 std::string column;
575 std::string columnExtraDbgInfo;
576 int datatype = SQL_UNKNOWN_TYPE;
577
578 try
579 {
580 column = toUTF8( results.column_name( j ) );
581 datatype = results.column_datatype( j );
582 columnExtraDbgInfo = fmt::format( "column index {}, name '{}', type {}", j, column,
583 datatype );
584 }
585 catch( nanodbc::index_range_error& e )
586 {
587 handleException( e, columnExtraDbgInfo );
588 return false;
589 }
590
591 switch( datatype )
592 {
593 case SQL_DOUBLE:
594 case SQL_FLOAT:
595 case SQL_REAL:
596 case SQL_DECIMAL:
597 case SQL_NUMERIC:
598 {
599 try
600 {
601 result[column] = fmt::format( "{:G}", results.get<double>( j ) );
602 }
603 catch( nanodbc::null_access_error& )
604 {
605 // Column was empty (null)
606 result[column] = std::string();
607 }
608 catch( std::runtime_error& e )
609 {
610 handleException( e, columnExtraDbgInfo );
611 return false;
612 }
613 break;
614 }
615
616 default:
617 {
618 try
619 {
620 result[column] = toUTF8( results.get<nanodbc::string>( j,
621 NANODBC_TEXT( "" ) ) );
622 }
623 catch( std::runtime_error& e )
624 {
625 handleException( e, columnExtraDbgInfo );
626 return false;
627 }
628 }
629 }
630 }
631
632 if( !result.count( aKey ) )
633 {
634 wxLogTrace( traceDatabase,
635 wxT( "selectAllAndCache: warning: key %s not found in result set" ), aKey );
636 continue;
637 }
638
639 std::string keyStr = std::any_cast<std::string>( result.at( aKey ) );
640 cacheEntry[keyStr] = result;
641 }
642
643 wxLogTrace( traceDatabase, wxT( "selectAllAndCache from %s completed in %0.1f ms" ), aTable,
644 timer.msecs() );
645
646 m_cache->Put( aTable, cacheEntry );
647 return true;
648}
649
650
651bool DATABASE_CONNECTION::SelectAll( const std::string& aTable, const std::string& aKey,
652 std::vector<ROW>& aResults )
653{
654 if( !m_conn )
655 {
656 wxLogTrace( traceDatabase, wxT( "Called SelectAll without valid connection!" ) );
657 return false;
658 }
659
660 auto tableMapIter = m_tables.find( aTable );
661
662 if( tableMapIter == m_tables.end() )
663 {
664 wxLogTrace( traceDatabase, wxT( "SelectAll: requested table %s not found in cache" ),
665 aTable );
666 return false;
667 }
668
670
671 if( !m_cache->Get( aTable, cacheEntry ) )
672 {
673 if( !selectAllAndCache( aTable, aKey ) )
674 {
675 wxLogTrace( traceDatabase, wxT( "SelectAll: `%s` cache fill failed" ), aTable );
676 return false;
677 }
678
679 // Now it should be filled
680 m_cache->Get( aTable, cacheEntry );
681 }
682
683 if( !m_cache->Get( aTable, cacheEntry ) )
684 {
685 wxLogTrace( traceDatabase, wxT( "SelectAll: `%s` failed to get results from cache!" ),
686 aTable );
687 return false;
688 }
689
690 wxLogTrace( traceDatabase, wxT( "SelectAll: `%s` - returning cached results" ), aTable );
691
692 aResults.reserve( cacheEntry.size() );
693
694 for( auto &[ key, row ] : cacheEntry )
695 aResults.emplace_back( row );
696
697 return true;
698}
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)
wxString result
Test unit parsing edge cases and error handling.