-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathsql_interface.hpp
1553 lines (1285 loc) · 48.6 KB
/
sql_interface.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* <!-- mksqlite: A MATLAB Interface to SQLite -->
*
* @file sql_interface.hpp
* @brief SQLite interface class
* @details SQLite accessing functions, for single-file databases
* @see http://undocumentedmatlab.com/blog/serializing-deserializing-matlab-data
* @authors Martin Kortmann <mail@kortmann.de>,
* Andreas Martin <andimartin@users.sourceforge.net>
* @version 2.14
* @date 2008-2024
* @copyright Distributed under BSD-2
* @pre
* @warning
* @bug
*/
#pragma once
//#include "config.h"
//#include "global.hpp"
//#include "sqlite/sqlite3.h"
#include "sql_builtin_functions.hpp"
//#include "utils.hpp"
//#include "value.hpp"
//#include "locale.hpp"
#include <map>
// Handling Ctrl+C functions, see also http://undocumentedmatlab.com/blog/mex-ctrl-c-interrupt
extern "C" bool utIsInterruptPending();
extern "C" bool utSetInterruptEnabled( bool );
extern "C" bool utSetInterruptHandled( bool );
#if MKSQLITE_CONFIG_USE_UUID
// sqlite/uuid.c
extern "C" int sqlite3_uuid_init( sqlite3 *db );
#endif
/// type for column container
typedef vector<ValueSQLCol> ValueSQLCols;
extern ValueMex createItemFromValueSQL( const ValueSQL& value, int& err_id ); /* mksqlite.cpp */
extern ValueSQL createValueSQLFromItem( const ValueMex& item, bool bStreamable, int& iTypeComplexity, int& err_id ); /* mksqlite.cpp */
class SQLstack;
class SQLiface;
class MexFunctors;
/// Class holding an error
class SQLerror : public Err
{
public:
/// Set error by its result code
void setSqlError( sqlite3* dbid, int rc )
{
if( SQLITE_OK == rc )
{
clear();
}
else
{
if( rc < 0 )
{
rc = sqlite3_extended_errcode( dbid );
}
set_printf( sqlite3_errmsg( dbid ), trans_err_to_ident( rc ) );
}
}
/**
* \brief Get least SQLite error code and return identifier as string
*/
const char* trans_err_to_ident( int errorcode )
{
static char dummy[32];
//int errorcode = sqlite3_extended_errcode( m_db );
switch( errorcode )
{
case SQLITE_OK: return( "SQLITE:OK" );
case SQLITE_ERROR: return( "SQLITE:ERROR" );
case SQLITE_INTERNAL: return( "SQLITE:INTERNAL" );
case SQLITE_PERM: return( "SQLITE:PERM" );
case SQLITE_ABORT: return( "SQLITE:ABORT" );
case SQLITE_BUSY: return( "SQLITE:BUSY" );
case SQLITE_LOCKED: return( "SQLITE:LOCKED" );
case SQLITE_NOMEM: return( "SQLITE:NOMEM" );
case SQLITE_READONLY: return( "SQLITE:READONLY" );
case SQLITE_INTERRUPT: return( "SQLITE:INTERRUPT" );
case SQLITE_IOERR: return( "SQLITE:IOERR" );
case SQLITE_CORRUPT: return( "SQLITE:CORRUPT" );
case SQLITE_NOTFOUND: return( "SQLITE:NOTFOUND" );
case SQLITE_FULL: return( "SQLITE:FULL" );
case SQLITE_CANTOPEN: return( "SQLITE:CANTOPEN" );
case SQLITE_PROTOCOL: return( "SQLITE:PROTOCOL" );
case SQLITE_EMPTY: return( "SQLITE:EMPTY" );
case SQLITE_SCHEMA: return( "SQLITE:SCHEMA" );
case SQLITE_TOOBIG: return( "SQLITE:TOOBIG" );
case SQLITE_CONSTRAINT: return( "SQLITE:CONSTRAINT" );
case SQLITE_MISMATCH: return( "SQLITE:MISMATCH" );
case SQLITE_MISUSE: return( "SQLITE:MISUSE" );
case SQLITE_NOLFS: return( "SQLITE:NOLFS" );
case SQLITE_AUTH: return( "SQLITE:AUTH" );
case SQLITE_FORMAT: return( "SQLITE:FORMAT" );
case SQLITE_RANGE: return( "SQLITE:RANGE" );
case SQLITE_NOTADB: return( "SQLITE:NOTADB" );
case SQLITE_NOTICE: return( "SQLITE:NOTICE" );
case SQLITE_WARNING: return( "SQLITE:WARNING" );
case SQLITE_ROW: return( "SQLITE:ROW" );
case SQLITE_DONE: return( "SQLITE:DONE" );
/* extended codes */
case SQLITE_IOERR_READ: return( "SQLITE:IOERR_READ" );
case SQLITE_IOERR_SHORT_READ: return( "SQLITE:IOERR_SHORT_READ" );
case SQLITE_IOERR_WRITE: return( "SQLITE:IOERR_WRITE" );
case SQLITE_IOERR_FSYNC: return( "SQLITE:IOERR_FSYNC" );
case SQLITE_IOERR_DIR_FSYNC: return( "SQLITE:IOERR_DIR_FSYNC" );
case SQLITE_IOERR_TRUNCATE: return( "SQLITE:IOERR_TRUNCATE" );
case SQLITE_IOERR_FSTAT: return( "SQLITE:IOERR_FSTAT" );
case SQLITE_IOERR_UNLOCK: return( "SQLITE:IOERR_UNLOCK" );
case SQLITE_IOERR_RDLOCK: return( "SQLITE:IOERR_RDLOCK" );
case SQLITE_IOERR_DELETE: return( "SQLITE:IOERR_DELETE" );
case SQLITE_IOERR_BLOCKED: return( "SQLITE:IOERR_BLOCKED" );
case SQLITE_IOERR_NOMEM: return( "SQLITE:IOERR_NOMEM" );
case SQLITE_IOERR_ACCESS: return( "SQLITE:IOERR_ACCESS" );
case SQLITE_IOERR_CHECKRESERVEDLOCK: return( "SQLITE:IOERR_CHECKRESERVEDLOCK" );
case SQLITE_IOERR_LOCK: return( "SQLITE:IOERR_LOCK" );
case SQLITE_IOERR_CLOSE: return( "SQLITE:IOERR_CLOSE" );
case SQLITE_IOERR_DIR_CLOSE: return( "SQLITE:IOERR_DIR_CLOSE" );
case SQLITE_IOERR_SHMOPEN: return( "SQLITE:IOERR_SHMOPEN" );
case SQLITE_IOERR_SHMSIZE: return( "SQLITE:IOERR_SHMSIZE" );
case SQLITE_IOERR_SHMLOCK: return( "SQLITE:IOERR_SHMLOCK" );
case SQLITE_IOERR_SHMMAP: return( "SQLITE:IOERR_SHMMAP" );
case SQLITE_IOERR_SEEK: return( "SQLITE:IOERR_SEEK" );
case SQLITE_IOERR_DELETE_NOENT: return( "SQLITE:IOERR_DELETE_NOENT" );
case SQLITE_IOERR_MMAP: return( "SQLITE:IOERR_MMAP" );
case SQLITE_IOERR_GETTEMPPATH: return( "SQLITE:IOERR_GETTEMPPATH" );
case SQLITE_IOERR_CONVPATH: return( "SQLITE:IOERR_CONVPATH" );
case SQLITE_LOCKED_SHAREDCACHE: return( "SQLITE:LOCKED_SHAREDCACHE" );
case SQLITE_BUSY_RECOVERY: return( "SQLITE:BUSY_RECOVERY" );
case SQLITE_BUSY_SNAPSHOT: return( "SQLITE:BUSY_SNAPSHOT" );
case SQLITE_CANTOPEN_NOTEMPDIR: return( "SQLITE:CANTOPEN_NOTEMPDIR" );
case SQLITE_CANTOPEN_ISDIR: return( "SQLITE:CANTOPEN_ISDIR" );
case SQLITE_CANTOPEN_FULLPATH: return( "SQLITE:CANTOPEN_FULLPATH" );
case SQLITE_CANTOPEN_CONVPATH: return( "SQLITE:CANTOPEN_CONVPATH" );
case SQLITE_CORRUPT_VTAB: return( "SQLITE:CORRUPT_VTAB" );
case SQLITE_READONLY_RECOVERY: return( "SQLITE:READONLY_RECOVERY" );
case SQLITE_READONLY_CANTLOCK: return( "SQLITE:READONLY_CANTLOCK" );
case SQLITE_READONLY_ROLLBACK: return( "SQLITE:READONLY_ROLLBACK" );
case SQLITE_READONLY_DBMOVED: return( "SQLITE:READONLY_DBMOVED" );
case SQLITE_ABORT_ROLLBACK: return( "SQLITE:ABORT_ROLLBACK" );
case SQLITE_CONSTRAINT_CHECK: return( "SQLITE:CONSTRAINT_CHECK" );
case SQLITE_CONSTRAINT_COMMITHOOK: return( "SQLITE:CONSTRAINT_COMMITHOOK" );
case SQLITE_CONSTRAINT_FOREIGNKEY: return( "SQLITE:CONSTRAINT_FOREIGNKEY" );
case SQLITE_CONSTRAINT_FUNCTION: return( "SQLITE:CONSTRAINT_FUNCTION" );
case SQLITE_CONSTRAINT_NOTNULL: return( "SQLITE:CONSTRAINT_NOTNULL" );
case SQLITE_CONSTRAINT_PRIMARYKEY: return( "SQLITE:CONSTRAINT_PRIMARYKEY" );
case SQLITE_CONSTRAINT_TRIGGER: return( "SQLITE:CONSTRAINT_TRIGGER" );
case SQLITE_CONSTRAINT_UNIQUE: return( "SQLITE:CONSTRAINT_UNIQUE" );
case SQLITE_CONSTRAINT_VTAB: return( "SQLITE:CONSTRAINT_VTAB" );
case SQLITE_CONSTRAINT_ROWID: return( "SQLITE:CONSTRAINT_ROWID" );
case SQLITE_NOTICE_RECOVER_WAL: return( "SQLITE:NOTICE_RECOVER_WAL" );
case SQLITE_NOTICE_RECOVER_ROLLBACK: return( "SQLITE:NOTICE_RECOVER_ROLLBACK" );
case SQLITE_WARNING_AUTOINDEX: return( "SQLITE:WARNING_AUTOINDEX" );
case SQLITE_AUTH_USER: return( "SQLITE:AUTH_USER" );
default:
_snprintf( dummy, sizeof( dummy ), "SQLITE:ERRNO%d", errorcode );
return dummy;
}
}
};
/// Functors for SQL application-defined (aggregation) functions
class MexFunctors
{
ValueMex m_functors[3]; ///< Function handles (function, step, final)
ValueMex m_group_data; ///< Data container for "step" and "final" functions
ValueMex* m_pexception; ///< Exception stack information
/// inhibit standard Ctor
MexFunctors() {}
/// Copy Ctor
MexFunctors( const MexFunctors& other )
{
ValueMex exception = other.m_pexception->Duplicate();
*this = MexFunctors( exception, other.getFunc(FCN), other.getFunc(STEP), other.getFunc(FINAL) );
m_group_data = other.m_group_data;
}
public:
bool m_busy; ///< true, if function is in progress to prevent recursive calls
enum {FCN, STEP, FINAL}; ///< Subfunction number
/// Ctor
MexFunctors( ValueMex& exception, const ValueMex& func, const ValueMex& step, const ValueMex& final )
{
m_busy = false;
m_functors[FCN] = ValueMex(func).Duplicate();
m_functors[STEP] = ValueMex(step).Duplicate();
m_functors[FINAL] = ValueMex(final).Duplicate();
for( int i = 0; i < 3; i++ )
{
// Prevent function handles to be deleted when mex function returns
// (MATLAB automatically deletes arrays, allocated in mex functions)
m_functors[i].MakePersistent();
}
initGroupData();
m_pexception = &exception;
}
/// Copy Ctor
MexFunctors( MexFunctors& other )
{
*this = MexFunctors( *other.m_pexception, other.getFunc(FCN), other.getFunc(STEP), other.getFunc(FINAL) );
m_group_data = other.m_group_data;
}
/// Move Ctor
MexFunctors( MexFunctors&& other )
{
for( int i = 0; i < 3; i++ )
{
m_functors[i] = other.m_functors[i];
}
m_group_data = other.m_group_data;
m_pexception = other.m_pexception;
}
/// Copy assignment
MexFunctors& operator=( const MexFunctors& other )
{
if( this != &other )
{
*this = MexFunctors( other );
}
return *this;
}
/// Move assignment
MexFunctors& operator=( MexFunctors&& other )
{
if( this != &other )
{
*this = MexFunctors( other );
}
return *this;
}
/// Dtor
~MexFunctors()
{
for( int i = 0; i < 3; i++ )
{
m_functors[i].Destroy();
}
m_group_data.Destroy();
#ifndef NDEBUG
PRINTF( "%s\n", "Functors destroyed" );
#endif
}
/// Exchange exception stack information
void swapException( ValueMex& exception )
{
std::swap( *m_pexception, exception );
}
/// Initialize data for "step" and "final" function
void initGroupData()
{
m_group_data.Destroy();
m_group_data = ValueMex::CreateCellMatrix( 0, 0 );
m_group_data.MakePersistent();
}
/// Return data array from "step" and "final" function
ValueMex& getData()
{
return m_group_data;
}
/// Return one of the functors (function, init or final)
const ValueMex& getFunc(int nr) const
{
return m_functors[nr];
}
/// Duplicate one of the functors (function, init or final)
ValueMex dupFunc(int nr) const
{
return ValueMex( getFunc(nr) ).Duplicate();
}
/// Check if function handle is valid (not empty and of functon handle class)
bool checkFunc(int nr) const
{
return ValueMex( getFunc(nr) ).IsFunctionHandle();
}
/// Check if one of the functors is empty
bool IsEmpty() const
{
return m_functors[FCN].IsEmpty() && m_functors[STEP].IsEmpty() && m_functors[FINAL].IsEmpty();
}
/// Check if all functors are valid
bool IsValid() const
{
for( int i = 0; i < 3; i++ )
{
if( m_functors[i].IsEmpty() )
{
continue;
}
if( !m_functors[i].IsFunctionHandle() || m_functors[i].NumElements() != 1 )
{
return false;
}
}
if( IsEmpty() )
{
return false;
}
return true;
}
};
/// Class holding an exception array, the function map and the handle for one database
class SQLstackitem
{
typedef map<string, MexFunctors*> MexFunctorsMap; ///< Dictionary: function name => function handles
sqlite3* m_db; ///< SQLite db object
MexFunctorsMap m_fcnmap; ///< MEX function map with MATLAB functions for application-defined SQL functions
ValueMex m_exception; ///< MATALAB exception array, may be thrown when mksqlite function leaves
public:
/// Ctor
SQLstackitem() : m_db( NULL )
{}
/// Dtor
~SQLstackitem()
{
SQLerror err;
closeDb( err );
}
/// Return
sqlite3* dbid()
{
return m_db;
}
/// Returns the exception array for this database
ValueMex& getException()
{
return m_exception;
}
/// (Re-)Throws an exception, if any occurred
void throwOnException()
{
m_exception.Throw();
}
/// Returns the function map for this database
MexFunctorsMap& fcnmap()
{
return m_fcnmap;
}
/// Progress handler (watchdog)
static
int progressHandler( void* data )
{
// Ctrl+C pressed?
if( utIsInterruptPending() )
{
utSetInterruptHandled( true );
PRINTF( "%s\n", ::getLocaleMsg( MSG_ABORTED ) );
return 1;
}
return 0;
}
/// Installing progress handler to enable aborting by Ctrl+C
void setProgressHandler( bool enable = true )
{
const int N_INSTRUCTIONS = 1000;
sqlite3_progress_handler( m_db, enable ? N_INSTRUCTIONS : 0, &SQLstackitem::progressHandler, NULL );
}
/**
* \brief Opens (or create) database
*
* \param[in] filename Name of database file
* \param[in] openFlags Flags for access rights (see SQLite documentation for sqlite3_open_v2())
* \param[out] err Error information
* \returns true if succeeded
*/
bool openDb( const char* filename, int openFlags, SQLerror& err )
{
if( !closeDb( err ) )
{
return false;
}
/*
* Open the database
* m_db is assigned by sqlite3_open_v2(), even if an error
* occures
*/
unsigned char* filename_utf8 = NULL;
int filename_utf8_bytes = utils_latin2utf( (const unsigned char*)filename, NULL );
if( filename_utf8_bytes )
{
filename_utf8 = (unsigned char*)MEM_ALLOC( filename_utf8_bytes, sizeof(char) );
utils_latin2utf( (const unsigned char*)filename, filename_utf8 );
if( !filename_utf8 )
{
err.set( MSG_ERRMEMORY );
}
}
if( filename_utf8 && !err.isPending() )
{
int rc = sqlite3_open_v2( (char*)filename_utf8, &m_db, openFlags, NULL );
if( SQLITE_OK != rc )
{
err.setSqlError( m_db, -1 );
}
sqlite3_extended_result_codes( m_db, true );
attachBuiltinFunctions();
utSetInterruptEnabled( true );
setProgressHandler( true );
}
MEM_FREE( filename_utf8 );
return !err.isPending();
}
/// Close database
bool closeDb( SQLerror& err )
{
// Deallocate functors
for( MexFunctorsMap::iterator it = m_fcnmap.begin(); it != m_fcnmap.end(); it++ )
{
delete it->second;
}
m_fcnmap.clear();
// m_db may be NULL, since sqlite3_close with a NULL argument is a harmless no-op
int rc = sqlite3_close( m_db );
if( SQLITE_OK == rc )
{
m_db = NULL;
}
else
{
PRINTF( "%s\n", ::getLocaleMsg( MSG_ERRCANTCLOSE ) );
err.setSqlError( m_db, -1 ); /* not SQL_ERR_CLOSE */
}
return !isOpen();
}
/// Returns true, if database is opened
bool isOpen()
{
return NULL != m_db;
}
/**
* \brief Attach builtin functions to database object
*
* Following builtin functions are involved:
* - pow
* - regex
* - bcdratio
* - bdcpacktime
* - bdcunpacktime
* - md5
*/
void attachBuiltinFunctions()
{
if( !isOpen() )
{
assert( false );
}
else
{
// attach new SQL commands to opened database
sqlite3_create_function( m_db, "lg", 1, SQLITE_UTF8, NULL, lg_func, NULL, NULL ); // power function (math)
sqlite3_create_function( m_db, "regex", 2, SQLITE_UTF8, NULL, regex_func, NULL, NULL ); // regular expressions (MATCH mode)
sqlite3_create_function( m_db, "regex", 3, SQLITE_UTF8, NULL, regex_func, NULL, NULL ); // regular expressions (REPLACE mode)
sqlite3_create_function( m_db, "bdcratio", 1, SQLITE_UTF8, NULL, BDC_ratio_func, NULL, NULL ); // compression ratio (blob data compression)
sqlite3_create_function( m_db, "bdcpacktime", 1, SQLITE_UTF8, NULL, BDC_pack_time_func, NULL, NULL ); // compression time (blob data compression)
sqlite3_create_function( m_db, "bdcunpacktime", 1, SQLITE_UTF8, NULL, BDC_unpack_time_func, NULL, NULL ); // decompression time (blob data compression)
sqlite3_create_function( m_db, "md5", 1, SQLITE_UTF8, NULL, MD5_func, NULL, NULL ); // Message-Digest (RSA)
#ifndef SQLITE_ENABLE_MATH_FUNCTIONS
sqlite3_create_function( m_db, "ceil", 1, SQLITE_UTF8, NULL, ceil_func, NULL, NULL ); // ceil function (math)
sqlite3_create_function( m_db, "floor", 1, SQLITE_UTF8, NULL, floor_func, NULL, NULL ); // floor function (math)
sqlite3_create_function( m_db, "pow", 2, SQLITE_UTF8, NULL, pow_func, NULL, NULL ); // power function (math)
sqlite3_create_function( m_db, "exp", 1, SQLITE_UTF8, NULL, exp_func, NULL, NULL ); // power function (math)
sqlite3_create_function( m_db, "ln", 1, SQLITE_UTF8, NULL, ln_func, NULL, NULL ); // power function (math)
#endif
#if MKSQLITE_CONFIG_USE_UUID
// uuid.c (sqlite.org)
sqlite3_uuid_init( m_db );
#endif
}
}
};
/**
* \brief SQLite interface
*
* Encapsulates one sqlite object with pending command and statement.
*/
class SQLiface
{
SQLstackitem* m_pstackitem; ///< pointer to current database
sqlite3* m_db; ///< SQLite db handle
const char* m_command; ///< SQL query (no ownership, read-only!)
sqlite3_stmt* m_stmt; ///< SQL statement (sqlite bridge)
SQLerror m_lasterr; ///< recent error message
public:
friend class SQLerror;
/// Standard ctor
SQLiface( SQLstackitem& stackitem ) :
m_pstackitem( &stackitem ),
m_db( stackitem.dbid() ),
m_command( NULL ),
m_stmt( NULL )
{
// Multiple calls of sqlite3_initialize() are harmless no-ops
sqlite3_initialize();
}
/// Dtor
~SQLiface()
{
closeStmt();
}
/// Returns true, if database is open
bool isOpen()
{
return NULL != m_db;
}
/// Clear recent error message
void clearErr()
{
m_lasterr.clear();
}
/// Get recent error message
const char* getErr( const char** errid = NULL )
{
return m_lasterr.get( errid );
}
/// Sets an error by its ID (see \ref MSG_IDS)
void setErr( int err_id )
{
m_lasterr.set( err_id );
}
/// Sets an error by its SQL return code
void setSqlError( int rc )
{
m_lasterr.setSqlError( m_db, rc );
}
/// Returns true, if an unhandled error is pending
bool errPending()
{
return m_lasterr.isPending();
}
/// Get the filename of current database
const char* getDbFilename( const char* database )
{
if( !isOpen() )
{
assert( false );
return NULL;
}
return sqlite3_db_filename( m_db, database ? database : "MAIN" );
}
/// Sets the busy timemout in milliseconds
bool setBusyTimeout( int iTimeoutValue )
{
if( !isOpen() )
{
assert( false );
return false;
}
int rc = sqlite3_busy_timeout( m_db, iTimeoutValue );
if( SQLITE_OK != rc )
{
setSqlError( rc );
return false;
}
return true;
}
/// Returns the busy timeout in milliseconds
bool getBusyTimeout( int& iTimeoutValue )
{
if( !isOpen() )
{
assert( false );
return false;
}
int rc = sqlite3_busy_timeout( m_db, iTimeoutValue );
if( SQLITE_OK != rc )
{
setSqlError( rc );
return false;
}
return true;
}
/// Enable or disable load extensions
bool setEnableLoadExtension( int flagOnOff )
{
if( !isOpen() )
{
assert( false );
return false;
}
int rc = sqlite3_enable_load_extension( m_db, flagOnOff != 0 );
if( SQLITE_OK != rc )
{
setSqlError( rc );
return false;
}
return true;
}
/// Closing current statement
void closeStmt()
{
if( m_stmt )
{
// sqlite3_reset() does not reset the bindings on a prepared statement!
sqlite3_clear_bindings( m_stmt );
sqlite3_reset( m_stmt );
sqlite3_finalize( m_stmt );
m_stmt = NULL;
m_command = NULL;
}
}
/// Wrapper for SQL function
static
void mexFcnWrapper_FCN( sqlite3_context *ctx, int argc, sqlite3_value **argv )
{
mexFcnWrapper( ctx, argc, argv, MexFunctors::FCN );
}
/// Wrapper for SQL step function (aggregation)
static
void mexFcnWrapper_STEP( sqlite3_context *ctx, int argc, sqlite3_value **argv )
{
mexFcnWrapper( ctx, argc, argv, MexFunctors::STEP );
}
/// Wrapper for SQL final function (aggregation)
static
void mexFcnWrapper_FINAL( sqlite3_context *ctx )
{
mexFcnWrapper( ctx, 0, NULL, MexFunctors::FINAL );
}
/// Common wrapper for all user defined SQL functions
static
void mexFcnWrapper( sqlite3_context *ctx, int argc, sqlite3_value **argv, int func_nr )
{
MexFunctors* fcn = (MexFunctors*)sqlite3_user_data( ctx );
int nArgs = argc + 1 + (func_nr > MexFunctors::FCN); // Number of arguments for "feval"
ValueMex arg( ValueMex::CreateCellMatrix( 1, nArgs ) );
bool failed = false;
assert( fcn && arg.Item() );
if( !fcn->checkFunc(func_nr) )
{
arg.Destroy();
sqlite3_result_error( ctx, ::getLocaleMsg( MSG_INVALIDFUNCTION ), -1 );
failed = true;
}
if( fcn->m_busy )
{
arg.Destroy();
sqlite3_result_error( ctx, ::getLocaleMsg( MSG_RECURSIVECALL ), -1 );
failed = true;
}
// Transform SQL value arguments into a MATLAB cell array
for( int j = 0; j < nArgs && !failed; j++ )
{
int err_id = MSG_NOERROR;
int i = j;
ValueSQL value;
ValueMex item;
if( j == 0 )
{
arg.SetCell( j, fcn->dupFunc(func_nr).Detach() );
continue;
}
i--;
if( func_nr > MexFunctors::FCN )
{
if( j == 1 )
{
assert( fcn->getData().Item() );
arg.SetCell( j, fcn->getData().Duplicate().Detach() );
continue;
}
i--;
}
switch( sqlite3_value_type( argv[i] ) )
{
case SQLITE_NULL:
break;
case SQLITE_INTEGER:
value = ValueSQL( sqlite3_value_int64( argv[i] ) );
break;
case SQLITE_FLOAT:
value = ValueSQL( sqlite3_value_double( argv[i] ) );
break;
case SQLITE_TEXT:
{
char* str = (char*)utils_strnewdup( (const char*)sqlite3_value_text( argv[i] ), g_convertUTF8 );
if( str )
{
value = ValueSQL( str );
break;
}
}
case SQLITE_BLOB:
{
size_t bytes = sqlite3_value_bytes( argv[i] );
item = ValueMex( (int)bytes, bytes ? 1 : 0, ValueMex::UINT8_CLASS );
if( item.Data() )
{
if( bytes )
{
memcpy( item.Data(), sqlite3_value_blob( argv[i] ), bytes );
}
value = ValueSQL( item.Detach() );
}
else
{
sqlite3_result_error( ctx, getLocaleMsg( MSG_ERRMEMORY ), -1 );
failed = true;
}
break;
}
default:
sqlite3_result_error( ctx, getLocaleMsg( MSG_UNKNWNDBTYPE ), -1 );
failed = true;
}
if( failed )
{
value.Destroy();
}
else
{
// Cumulate arguments into a cell array
arg.SetCell( j, createItemFromValueSQL( value, err_id ).Detach() );
if( MSG_NOERROR != err_id )
{
sqlite3_result_error( ctx, ::getLocaleMsg( err_id ), -1 );
failed = true;
}
}
}
if( !failed )
{
ValueMex exception, item;
fcn->m_busy = true;
arg.Call( &item, &exception );
fcn->m_busy = false;
if( !exception.IsEmpty() )
{
// Exception handling
fcn->swapException( exception );
sqlite3_result_error( ctx, "MATLAB Exception!", -1 );
failed = true;
}
else
{
if( func_nr == MexFunctors::STEP )
{
if( !item.IsEmpty() )
{
item.MakePersistent();
std::swap( fcn->getData(), item );
item.Destroy();
}
sqlite3_result_null( ctx );
}
else
{
if( !item.IsEmpty() )
{
int iTypeComplexity;
int err_id = MSG_NOERROR;
ValueSQL value = createValueSQLFromItem( item, can_serialize(), iTypeComplexity, err_id );
if( MSG_NOERROR != err_id )
{
Err err;
err.set( err_id );
sqlite3_result_error( ctx, err.get(), -1 );
}
else
{
switch( value.m_typeID )
{
case SQLITE_NULL:
sqlite3_result_null( ctx );
break;
case SQLITE_FLOAT:
// scalar floating point value
sqlite3_result_double( ctx, item.GetScalar() );
break;
case SQLITE_INTEGER:
if( (int)item.ClassID() == (int)ValueMex::INT64_CLASS )
{
// scalar integer value
sqlite3_result_int64( ctx, item.GetInt64() );
}
else
{
// scalar integer value
sqlite3_result_int( ctx, item.GetInt() );
}
break;
case SQLITE_TEXT:
// string argument
// SQLite makes a local copy of the text (thru SQLITE_TRANSIENT)
sqlite3_result_text( ctx, value.m_text, -1, SQLITE_TRANSIENT );
break;
case SQLITE_BLOB:
// SQLite makes a local copy of the blob (thru SQLITE_TRANSIENT)
sqlite3_result_blob( ctx, item.Data(),
(int)item.ByData(),
SQLITE_TRANSIENT );
break;
case SQLITE_BLOBX:
// sqlite takes custody of the blob, even if sqlite3_bind_blob() fails
// the sqlite allocator provided blob memory
sqlite3_result_blob( ctx, value.Detach(),
(int)value.m_blobsize,
sqlite3_free );
break;
default:
{
// all other (unsuppored types)
Err err;
err.set( MSG_INVALIDARG );
sqlite3_result_error( ctx, err.get(), - 1 );
break;
}
}
}
}
else
{
sqlite3_result_null( ctx );
}
}
}
item.Destroy();
exception.Destroy();
}
arg.Destroy();
if( func_nr == MexFunctors::FINAL )
{
fcn->initGroupData();
}
}
/**
* \brief Attach application-defined function to database object
*/
bool attachMexFunction( const char* name, const ValueMex& func, const ValueMex& step, const ValueMex& final, ValueMex& exception )
{
if( !isOpen() )
{
assert( false );
}
else