forked from alitrack/duckdb_fdw
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sqlite3_api_wrapper.cpp
2242 lines (1988 loc) · 67.8 KB
/
sqlite3_api_wrapper.cpp
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
#include "sqlite3.h"
#include "duckdb.hpp"
#ifdef __cplusplus
extern "C" {
#endif
#include "postgres.h"
#include "access/htup_details.h"
#include "catalog/pg_type.h"
#include "utils/array.h"
#include "utils/lsyscache.h"
#include "utils/syscache.h"
#ifdef __cplusplus
}
#endif
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <string>
#include <chrono>
#include <cassert>
#include <climits>
#include <thread>
using namespace duckdb;
using namespace std;
#ifndef PreservedError
typedef duckdb::ErrorData PreservedError;
#endif
struct TryCast {
template <class SRC, class DST>
DUCKDB_API static inline bool Operation(SRC input, DST &result, bool strict = false) {
throw NotImplementedException("Unimplemented type for cast (%s -> %s)", GetTypeId<SRC>(), GetTypeId<DST>());
}
};
enum class SQLiteTypeValue : uint8_t { INTEGER = 1, FLOAT = 2, TEXT = 3, BLOB = 4, NULL_VALUE = 5 };
enum class ErrorType : uint16_t {
// error message types
UNSIGNED_EXTENSION = 0,
INVALIDATED_TRANSACTION = 1,
INVALIDATED_DATABASE = 2,
// this should always be the last value
ERROR_COUNT,
INVALID = 65535,
};
struct sqlite3 {
std::unique_ptr<duckdb::DuckDB> db;
std::unique_ptr<duckdb::Connection> con;
PreservedError last_error;
int64_t last_changes = 0;
int64_t total_changes = 0;
int errCode; /* Most recent error code (SQLITE_*) */
};
struct sqlite3_value {
union MemValue {
double r; /* Real value used when MEM_Real is set in flags */
int64_t i; /* Integer value used when MEM_Int is set in flags */
// int nZero; /* Extra zero bytes when MEM_Zero and MEM_Blob set */
} u;
SQLiteTypeValue type;
std::string str;
sqlite3 *db; /* The associated database connection */
};
struct FuncDef {
// i8 nArg; /* Number of arguments. -1 means unlimited */
// u32 funcFlags; /* Some combination of SQLITE_FUNC_* */
void *pUserData; /* User data parameter */
// FuncDef *pNext; /* Next function with same name */
// void (*xSFunc)(sqlite3_context*,int,sqlite3_value**); /* func or agg-step */
// void (*xFinalize)(sqlite3_context*); /* Agg finalizer */
// void (*xValue)(sqlite3_context*); /* Current agg value */
// void (*xInverse)(sqlite3_context*,int,sqlite3_value**); /* inverse agg-step */
// const char *zName; /* SQL name of the function. */
// union {
// FuncDef *pHash; /* Next with a different name but the same hash */
// FuncDestructor *pDestructor; /* Reference counted destructor function */
// } u;
};
struct sqlite3_context {
sqlite3_value result; // Mem *pOut; /* The return value is stored here */
FuncDef pFunc; /* Pointer to function information */
// Mem *pMem; /* Memory cell used to store aggregate context */
// Vdbe *pVdbe; /* The VM that owns this context */
// int iOp; /* Instruction number of OP_Function */
int isError; /* Error code returned by the function. */
// u8 skipFlag; /* Skip accumulator loading if true */
// u8 argc; /* Number of arguments */
// sqlite3_value *argv[1]; /* Argument set */
};
static char *sqlite3_strdup(const char *str);
struct sqlite3_string_buffer {
//! String data
duckdb::unsafe_unique_array<char> data;
//! String length
int data_len;
};
struct sqlite3_stmt {
//! The DB object that this statement belongs to
sqlite3 *db;
//! The query string
string query_string;
//! The prepared statement object, if successfully prepared
duckdb::unique_ptr<PreparedStatement> prepared;
//! The result object, if successfully executed
duckdb::unique_ptr<QueryResult> result;
//! The current chunk that we are iterating over
duckdb::unique_ptr<DataChunk> current_chunk;
//! The current row into the current chunk that we are iterating over
int64_t current_row;
//! Bound values, used for binding to the prepared statement
duckdb::vector<duckdb::Value> bound_values;
//! Names of the prepared parameters
duckdb::vector<string> bound_names;
//! The current column values converted to string, used and filled by sqlite3_column_text
duckdb::unique_ptr<sqlite3_string_buffer[]> current_text;
};
void sqlite3_randomness(int N, void *pBuf) {
static bool init = false;
if (!init) {
srand(time(NULL));
init = true;
}
unsigned char *zBuf = (unsigned char *)pBuf;
while (N--) {
unsigned char nextByte = rand() % 255;
zBuf[N] = nextByte;
}
}
int sqlite3_open(const char *filename, /* Database filename (UTF-8) */
sqlite3 **ppDb /* OUT: SQLite db handle */
) {
return sqlite3_open_v2(filename, ppDb, 0, NULL);
}
int sqlite3_open_v2(const char *filename, /* Database filename (UTF-8) */
sqlite3 **ppDb, /* OUT: SQLite db handle */
int flags, /* Flags */
const char *zVfs /* Name of VFS module to use */
) {
return sqlite3_open_v3(filename, ppDb, flags, zVfs, NULL);
}
int sqlite3_open_v3(const char *filename, /* Database filename (UTF-8) */
sqlite3 **ppDb, /* OUT: SQLite db handle */
int flags, /* Flags */
const char *zVfs, /* Name of VFS module to use */
const char *temp_dir /* Temp directory to use */
) {
if (filename && strcmp(filename, ":memory:") == 0) {
filename = NULL;
}
*ppDb = nullptr;
if (zVfs) { /* unsupported so if set we complain */
return SQLITE_ERROR;
}
int rc = SQLITE_OK;
sqlite3 *pDb = nullptr;
try {
pDb = new sqlite3();
DBConfig config;
config.options.access_mode = AccessMode::AUTOMATIC;
if (flags & SQLITE_OPEN_READONLY) {
config.options.access_mode = AccessMode::READ_ONLY;
}
if (flags & DUCKDB_UNSIGNED_EXTENSIONS) {
config.options.allow_unsigned_extensions = true;
}
if (temp_dir) {
config.options.temporary_directory = string(temp_dir);
}
//TODO
// config.error_manager->AddCustomError(
// ErrorType::UNSIGNED_EXTENSION,
// "Extension \"%s\" could not be loaded because its signature is either missing or invalid and unsigned "
// "extensions are disabled by configuration.\nStart the shell with the -unsigned parameter to allow this "
// "(e.g. duckdb -unsigned).");
pDb->db = make_uniq<DuckDB>(filename, &config);
// pDb->db->LoadExtension<SQLAutoCompleteExtension>();
pDb->con = make_uniq<Connection>(*pDb->db);
} catch (const Exception &ex) {
if (pDb) {
pDb->last_error = PreservedError(ex);
pDb->errCode = SQLITE_ERROR;
}
rc = SQLITE_ERROR;
} catch (std::exception &ex) {
if (pDb) {
pDb->last_error = PreservedError(ex);
pDb->errCode = SQLITE_ERROR;
}
rc = SQLITE_ERROR;
}
*ppDb = pDb;
return rc;
}
int sqlite3_close(sqlite3 *db) {
if (db) {
delete db;
}
return SQLITE_OK;
}
int sqlite3_shutdown(void) {
return SQLITE_OK;
}
/* In SQLite this function compiles the query into VDBE bytecode,
* in the implementation it currently executes the query */
// TODO: prepare the statement instead of executing right away
int sqlite3_prepare_v2(sqlite3 *db, /* Database handle */
const char *zSql, /* SQL statement, UTF-8 encoded */
int nByte, /* Maximum length of zSql in bytes. */
sqlite3_stmt **ppStmt, /* OUT: Statement handle */
const char **pzTail /* OUT: Pointer to unused portion of zSql */
) {
if (!db || !ppStmt || !zSql) {
return SQLITE_MISUSE;
}
*ppStmt = nullptr;
duckdb::vector<duckdb::unique_ptr<SQLStatement>> statements;
const string query = nByte < 0 ? zSql : string(zSql, nByte);
if (pzTail) {
*pzTail = zSql + query.size();
}
try {
statements = db->con->context->ParseStatements(query);
// Parser parser(db->con->context->GetParserOptions());
// parser.ParseQuery(query);
// if (parser.statements.size() == 0) {
// return SQLITE_OK;
// }
if (statements.size() == 0) {
return SQLITE_OK;
}
// extract the remainder
// idx_t next_location = parser.statements[0]->stmt_location + parser.statements[0]->stmt_length;
idx_t next_location = statements[0]->stmt_location + statements[0]->stmt_length;
bool set_remainder = next_location < query.size();
// extract the first statement
duckdb::vector<duckdb::unique_ptr<SQLStatement>> _statements;
// statements.push_back(std::move(parser.statements[0]));
_statements.push_back(std::move(statements[0]));
db->con->context->HandlePragmaStatements(_statements);
// if there are multiple statements here, we are dealing with an import database statement
// we directly execute all statements besides the final one
for (idx_t i = 0; i + 1 < _statements.size(); i++) {
auto res = db->con->Query(std::move(_statements[i]));
if (res->HasError()) {
db->last_error = res->GetErrorObject();
return SQLITE_ERROR;
}
}
// now prepare the query
auto prepared = db->con->Prepare(std::move(_statements.back()));
if (prepared->HasError()) {
// failed to prepare: set the error message
db->last_error = prepared->error;
return SQLITE_ERROR;
}
// create the statement entry
duckdb::unique_ptr<sqlite3_stmt> stmt = make_uniq<sqlite3_stmt>();
stmt->db = db;
stmt->query_string = query;
stmt->prepared = std::move(prepared);
stmt->current_row = -1;
for (idx_t i = 0; i < stmt->prepared->n_param; i++) {
stmt->bound_names.push_back("$" + to_string(i + 1));
stmt->bound_values.push_back(duckdb::Value());
}
// extract the remainder of the query and assign it to the pzTail
if (pzTail && set_remainder) {
*pzTail = zSql + next_location + 1;
}
*ppStmt = stmt.release();
return SQLITE_OK;
} catch (const Exception &ex) {
db->last_error = PreservedError(ex);
return SQLITE_ERROR;
} catch (std::exception &ex) {
db->last_error = PreservedError(ex);
return SQLITE_ERROR;
}
}
// char *sqlite3_print_duckbox(sqlite3_stmt *pStmt, size_t max_rows, char *null_value) {
// if (!pStmt) {
// return nullptr;
// }
// if (!pStmt->prepared) {
// pStmt->db->last_error = PreservedError("Attempting sqlite3_step() on a non-successfully prepared statement");
// return nullptr;
// }
// if (pStmt->result) {
// pStmt->db->last_error = PreservedError("Statement has already been executed");
// return nullptr;
// }
// pStmt->result = pStmt->prepared->Execute(pStmt->bound_values, false);
// if (pStmt->result->HasError()) {
// // error in execute: clear prepared statement
// pStmt->db->last_error = pStmt->result->GetErrorObject();
// pStmt->prepared = nullptr;
// return nullptr;
// }
// auto &materialized = (MaterializedQueryResult &)*pStmt->result;
// auto properties = pStmt->prepared->GetStatementProperties();
// if (properties.return_type == StatementReturnType::CHANGED_ROWS && materialized.RowCount() > 0) {
// // update total changes
// auto row_changes = materialized.Collection().GetRows().GetValue(0, 0);
// if (!row_changes.IsNull() && row_changes.DefaultTryCastAs(LogicalType::BIGINT)) {
// pStmt->db->last_changes = row_changes.GetValue<int64_t>();
// pStmt->db->total_changes += row_changes.GetValue<int64_t>();
// }
// }
// if (properties.return_type != StatementReturnType::QUERY_RESULT) {
// // only SELECT statements return results
// return nullptr;
// }
// BoxRendererConfig config;
// if (max_rows != 0) {
// config.max_rows = max_rows;
// }
// if (null_value) {
// config.null_value = null_value;
// }
// BoxRenderer renderer(config);
// auto result_rendering =
// renderer.ToString(*pStmt->db->con->context, pStmt->result->names, materialized.Collection());
// return sqlite3_strdup(result_rendering.c_str());
// }
/* Prepare the next result to be retrieved */
int sqlite3_step(sqlite3_stmt *pStmt) {
if (!pStmt) {
return SQLITE_MISUSE;
}
if (!pStmt->prepared) {
pStmt->db->last_error = PreservedError("Attempting sqlite3_step() on a non-successfully prepared statement");
return SQLITE_ERROR;
}
pStmt->current_text = nullptr;
if (!pStmt->result) {
// no result yet! call Execute()
pStmt->result = pStmt->prepared->Execute(pStmt->bound_values, true);
if (pStmt->result->HasError()) {
// error in execute: clear prepared statement
pStmt->db->last_error = pStmt->result->GetErrorObject();
pStmt->prepared = nullptr;
return SQLITE_ERROR;
}
// fetch a chunk
if (!pStmt->result->TryFetch(pStmt->current_chunk, pStmt->db->last_error)) {
pStmt->prepared = nullptr;
return SQLITE_ERROR;
}
pStmt->current_row = -1;
auto properties = pStmt->prepared->GetStatementProperties();
if (properties.return_type == StatementReturnType::CHANGED_ROWS && pStmt->current_chunk &&
pStmt->current_chunk->size() > 0) {
// update total changes
auto row_changes = pStmt->current_chunk->GetValue(0, 0);
if (!row_changes.IsNull() && row_changes.DefaultTryCastAs(LogicalType::BIGINT)) {
pStmt->db->last_changes = row_changes.GetValue<int64_t>();
pStmt->db->total_changes += row_changes.GetValue<int64_t>();
}
}
if (properties.return_type != StatementReturnType::QUERY_RESULT) {
// only SELECT statements return results
sqlite3_reset(pStmt);
}
}
if (!pStmt->current_chunk || pStmt->current_chunk->size() == 0) {
return SQLITE_DONE;
}
pStmt->current_row++;
if (pStmt->current_row >= (int32_t)pStmt->current_chunk->size()) {
// have to fetch again!
pStmt->current_row = 0;
if (!pStmt->result->TryFetch(pStmt->current_chunk, pStmt->db->last_error)) {
pStmt->prepared = nullptr;
return SQLITE_ERROR;
}
if (!pStmt->current_chunk || pStmt->current_chunk->size() == 0) {
sqlite3_reset(pStmt);
return SQLITE_DONE;
}
}
return SQLITE_ROW;
}
/* Execute multiple semicolon separated SQL statements
* and execute the passed callback for each produced result,
* largely copied from the original sqlite3 source */
int sqlite3_exec(sqlite3 *db, /* The database on which the SQL executes */
const char *zSql, /* The SQL to be executed */
sqlite3_callback xCallback, /* Invoke this callback routine */
void *pArg, /* First argument to xCallback() */
char **pzErrMsg /* Write error messages here */
) {
int rc = SQLITE_OK; /* Return code */
const char *zLeftover; /* Tail of unprocessed SQL */
sqlite3_stmt *pStmt = nullptr; /* The current SQL statement */
char **azCols = nullptr; /* Names of result columns */
char **azVals = nullptr; /* Result values */
if (zSql == nullptr) {
zSql = "";
}
while (rc == SQLITE_OK && zSql[0]) {
int nCol;
pStmt = nullptr;
rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
if (rc != SQLITE_OK) {
if (pzErrMsg) {
auto errmsg = sqlite3_errmsg(db);
*pzErrMsg = errmsg ? sqlite3_strdup(errmsg) : nullptr;
}
continue;
}
if (!pStmt) {
/* this happens for a comment or white-space */
zSql = zLeftover;
continue;
}
nCol = sqlite3_column_count(pStmt);
azCols = (char **)malloc(nCol * sizeof(const char *));
azVals = (char **)malloc(nCol * sizeof(const char *));
if (!azCols || !azVals) {
goto exec_out;
}
for (int i = 0; i < nCol; i++) {
azCols[i] = (char *)sqlite3_column_name(pStmt, i);
}
while (true) {
rc = sqlite3_step(pStmt);
/* Invoke the callback function if required */
if (xCallback && rc == SQLITE_ROW) {
for (int i = 0; i < nCol; i++) {
azVals[i] = (char *)sqlite3_column_text(pStmt, i);
if (!azVals[i] && sqlite3_column_type(pStmt, i) != SQLITE_NULL) {
fprintf(stderr, "sqlite3_exec: out of memory.\n");
goto exec_out;
}
}
if (xCallback(pArg, nCol, azVals, azCols)) {
/* EVIDENCE-OF: R-38229-40159 If the callback function to
** sqlite3_exec() returns non-zero, then sqlite3_exec() will
** return SQLITE_ABORT. */
rc = SQLITE_ABORT;
sqlite3_finalize(pStmt);
pStmt = 0;
fprintf(stderr, "sqlite3_exec: callback returned non-zero. "
"Aborting.\n");
goto exec_out;
}
}
if (rc == SQLITE_DONE) {
rc = sqlite3_finalize(pStmt);
pStmt = nullptr;
zSql = zLeftover;
while (isspace(zSql[0]))
zSql++;
break;
} else if (rc != SQLITE_ROW) {
// error
if (pzErrMsg) {
auto errmsg = sqlite3_errmsg(db);
*pzErrMsg = errmsg ? sqlite3_strdup(errmsg) : nullptr;
}
goto exec_out;
}
}
sqlite3_free(azCols);
sqlite3_free(azVals);
azCols = nullptr;
azVals = nullptr;
}
exec_out:
if (pStmt) {
sqlite3_finalize(pStmt);
}
sqlite3_free(azCols);
sqlite3_free(azVals);
if (rc != SQLITE_OK && pzErrMsg && !*pzErrMsg) {
// error but no error message set
*pzErrMsg = sqlite3_strdup("Unknown error in DuckDB!");
}
return rc;
}
/* Return the text of the SQL that was used to prepare the statement */
const char *sqlite3_sql(sqlite3_stmt *pStmt) {
return pStmt->query_string.c_str();
}
int sqlite3_column_count(sqlite3_stmt *pStmt) {
if (!pStmt || !pStmt->prepared) {
return 0;
}
return (int)pStmt->prepared->ColumnCount();
}
////////////////////////////
// sqlite3_column //
////////////////////////////
int sqlite3_column_type(const LogicalType& column_type) {
switch (column_type.id()) {
case LogicalTypeId::BOOLEAN:
case LogicalTypeId::TINYINT:
case LogicalTypeId::SMALLINT:
case LogicalTypeId::INTEGER:
case LogicalTypeId::BIGINT: /* TODO: Maybe blob? */
return SQLITE_INTEGER;
case LogicalTypeId::FLOAT:
case LogicalTypeId::DOUBLE:
case LogicalTypeId::DECIMAL:
return SQLITE_FLOAT;
case LogicalTypeId::DATE:
case LogicalTypeId::TIME:
case LogicalTypeId::TIMESTAMP:
case LogicalTypeId::TIMESTAMP_SEC:
case LogicalTypeId::TIMESTAMP_MS:
case LogicalTypeId::TIMESTAMP_NS:
case LogicalTypeId::VARCHAR:
case LogicalTypeId::STRUCT:
case LogicalTypeId::MAP:
return SQLITE_TEXT;
case LogicalTypeId::BLOB:
return SQLITE_BLOB;
case LogicalTypeId::LIST:
{
auto child_type = ListType::GetChildType(column_type);
return sqlite3_column_type(child_type);
}
default:
// TODO(wangfenjin): agg function don't have type?
return SQLITE_TEXT;
}
return 0;
}
int sqlite3_column_type(sqlite3_stmt *pStmt, int iCol) {
if (!pStmt || !pStmt->result || !pStmt->current_chunk) {
return 0;
}
if (iCol < 0 || iCol >= (int)pStmt->result->types.size()) {
return 0;
}
if (FlatVector::IsNull(pStmt->current_chunk->data[iCol], pStmt->current_row)) {
return SQLITE_NULL;
}
auto column_type = pStmt->result->types[iCol];
return sqlite3_column_type(column_type);
}
const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N) {
if (!pStmt || !pStmt->prepared) {
return nullptr;
}
return pStmt->prepared->GetNames()[N].c_str();
}
static bool sqlite3_column_get_value(sqlite3_stmt *pStmt, int iCol, duckdb::Value &val) {
if (!pStmt || !pStmt->result || !pStmt->current_chunk) {
return false;
}
if (iCol < 0 || iCol >= (int)pStmt->result->types.size()) {
return false;
}
if (FlatVector::IsNull(pStmt->current_chunk->data[iCol], pStmt->current_row)) {
return false;
}
val = pStmt->current_chunk->data[iCol].GetValue(pStmt->current_row);
return true;
}
static bool sqlite3_column_has_value(sqlite3_stmt *pStmt, int iCol, LogicalType target_type, duckdb::Value &val) {
try {
if (sqlite3_column_get_value(pStmt, iCol, val)) {
val = val.CastAs(*pStmt->db->con->context, target_type);
return true;
}
} catch (...) {
}
return false;
}
double sqlite3_column_double(sqlite3_stmt *stmt, int iCol) {
duckdb::Value val;
if (!sqlite3_column_has_value(stmt, iCol, LogicalType::DOUBLE, val)) {
return 0;
}
return DoubleValue::Get(val);
}
int sqlite3_column_int(sqlite3_stmt *stmt, int iCol) {
duckdb::Value val;
if (!sqlite3_column_has_value(stmt, iCol, LogicalType::INTEGER, val)) {
return 0;
}
return IntegerValue::Get(val);
}
sqlite3_int64 sqlite3_column_int64(sqlite3_stmt *stmt, int iCol) {
duckdb::Value val;
if (!sqlite3_column_has_value(stmt, iCol, LogicalType::BIGINT, val)) {
return 0;
}
return BigIntValue::Get(val);
}
const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int iCol) {
duckdb::Value val;
if (!sqlite3_column_has_value(pStmt, iCol, LogicalType::VARCHAR, val)) {
return nullptr;
}
try {
if (!pStmt->current_text) {
pStmt->current_text =
duckdb::unique_ptr<sqlite3_string_buffer[]>(new sqlite3_string_buffer[pStmt->result->types.size()]);
}
auto &entry = pStmt->current_text[iCol];
if (!entry.data) {
// not initialized yet, convert the value and initialize it
auto &str_val = StringValue::Get(val);
entry.data = duckdb::make_unsafe_uniq_array<char>(str_val.size() + 1);
memcpy(entry.data.get(), str_val.c_str(), str_val.size() + 1);
entry.data_len = str_val.length();
}
return (const unsigned char *)entry.data.get();
} catch (...) {
// memory error!
return nullptr;
}
}
const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int iCol) {
duckdb::Value val;
if (!sqlite3_column_has_value(pStmt, iCol, LogicalType::BLOB, val)) {
return nullptr;
}
try {
if (!pStmt->current_text) {
pStmt->current_text =
duckdb::unique_ptr<sqlite3_string_buffer[]>(new sqlite3_string_buffer[pStmt->result->types.size()]);
}
auto &entry = pStmt->current_text[iCol];
if (!entry.data) {
// not initialized yet, convert the value and initialize it
auto &str_val = StringValue::Get(val);
entry.data = duckdb::make_unsafe_uniq_array<char>(str_val.size() + 1);
memcpy(entry.data.get(), str_val.c_str(), str_val.size() + 1);
entry.data_len = str_val.length();
}
return (const unsigned char *)entry.data.get();
} catch (...) {
// memory error!
return nullptr;
}
}
static bool duckdb_value_as_datum(const duckdb::Value &val, Oid pgType, Datum *value) {
const LogicalType &column_type = val.type();
switch (column_type.id()) {
case LogicalTypeId::BOOLEAN:
{
bool v = val.GetValue<bool>();
*value = BoolGetDatum(v);
return true;
}
case LogicalTypeId::TINYINT:
{
int8_t v = val.GetValue<int8_t>();
*value = Int8GetDatum(v);
return true;
}
case LogicalTypeId::SMALLINT:
{
int16_t v = val.GetValue<int16_t>();
*value = Int16GetDatum(v);
return true;
}
case LogicalTypeId::INTEGER:
{
int32_t v = val.GetValue<int32_t>();
*value = Int32GetDatum(v);
return true;
}
case LogicalTypeId::BIGINT:
{
int64_t v = val.GetValue<int64_t>();
*value = Int64GetDatum(v);
return true;
}
case LogicalTypeId::FLOAT:
{
float4 v = val.GetValue<float4>();
*value = Float4GetDatum(v);
return true;
}
case LogicalTypeId::DOUBLE:
{
float8 v = val.GetValue<float8>();
*value = Float8GetDatum(v);
return true;
}
case LogicalTypeId::DECIMAL:
case LogicalTypeId::DATE:
case LogicalTypeId::TIME:
case LogicalTypeId::TIMESTAMP:
case LogicalTypeId::TIMESTAMP_SEC:
case LogicalTypeId::TIMESTAMP_MS:
case LogicalTypeId::TIMESTAMP_NS:
case LogicalTypeId::TIME_TZ:
case LogicalTypeId::TIMESTAMP_TZ:
{
HeapTuple tuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(pgType));
if (HeapTupleIsValid(tuple)) {
regproc typeinput = ((Form_pg_type) GETSTRUCT(tuple))->typinput;
int typemod = ((Form_pg_type) GETSTRUCT(tuple))->typtypmod;
ReleaseSysCache(tuple);
std::string value_s = val.ToString();
Datum temp_ = CStringGetDatum(value_s.c_str());
*value =
OidFunctionCall3(typeinput, temp_, ObjectIdGetDatum(InvalidOid), Int32GetDatum(typemod));
return true;
}
break;
}
case LogicalTypeId::LIST:
{
Oid element_type = get_element_type(pgType);
ArrayBuildState *astate = NULL;
astate = initArrayResult(element_type, CurrentMemoryContext, false);
const auto &children = ListValue::GetChildren(val);
for (const auto &child : children) {
Datum child_value = 0;
if (duckdb_value_as_datum(child, element_type, &child_value)) {
astate = accumArrayResult(astate,
child_value,
false,
element_type,
CurrentMemoryContext);
}
}
Datum array_result = makeArrayResult(astate, CurrentMemoryContext);
*value = array_result;
return true;
}
case LogicalTypeId::VARCHAR:
default:
{
std::string value_s = val.ToString();
char *text_ptr = (char *) palloc(value_s.size() + VARHDRSZ);
SET_VARSIZE(text_ptr, value_s.size() + VARHDRSZ);
memcpy(VARDATA(text_ptr), value_s.c_str(), value_s.size());
*value = CStringGetDatum(text_ptr);
return true;
}
}
return false;
}
bool sqlite3_column_value_datum(sqlite3_stmt *pStmt, int iCol, Oid pgType, Datum *value) {
duckdb::Value val;
if (sqlite3_column_get_value(pStmt, iCol, val) && duckdb_value_as_datum(val, pgType, value)) {
return true;
}
return false;
}
////////////////////////////
// sqlite3_bind //
////////////////////////////
int sqlite3_bind_parameter_count(sqlite3_stmt *stmt) {
if (!stmt) {
return 0;
}
return stmt->prepared->n_param;
}
const char *sqlite3_bind_parameter_name(sqlite3_stmt *stmt, int idx) {
if (!stmt) {
return nullptr;
}
if (idx < 1 || idx > (int)stmt->prepared->n_param) {
return nullptr;
}
return stmt->bound_names[idx - 1].c_str();
}
int sqlite3_bind_parameter_index(sqlite3_stmt *stmt, const char *zName) {
if (!stmt || !zName) {
return 0;
}
for (idx_t i = 0; i < stmt->bound_names.size(); i++) {
if (stmt->bound_names[i] == string(zName)) {
return i + 1;
}
}
return 0;
}
int sqlite3_internal_bind_value(sqlite3_stmt *stmt, int idx, duckdb::Value value) {
if (!stmt || !stmt->prepared || stmt->result) {
return SQLITE_MISUSE;
}
if (idx < 1 || idx > (int)stmt->prepared->n_param) {
return SQLITE_RANGE;
}
stmt->bound_values[idx - 1] = value;
return SQLITE_OK;
}
int sqlite3_bind_int(sqlite3_stmt *stmt, int idx, int val) {
return sqlite3_internal_bind_value(stmt, idx, duckdb::Value::INTEGER(val));
}
int sqlite3_bind_int64(sqlite3_stmt *stmt, int idx, sqlite3_int64 val) {
return sqlite3_internal_bind_value(stmt, idx, duckdb::Value::BIGINT(val));
}
int sqlite3_bind_double(sqlite3_stmt *stmt, int idx, double val) {
return sqlite3_internal_bind_value(stmt, idx, duckdb::Value::DOUBLE(val));
}
int sqlite3_bind_null(sqlite3_stmt *stmt, int idx) {
return sqlite3_internal_bind_value(stmt, idx, duckdb::Value());
}
SQLITE_API int sqlite3_bind_value(sqlite3_stmt *, int, const sqlite3_value *) {
fprintf(stderr, "sqlite3_bind_value: unsupported.\n");
return SQLITE_ERROR;
}
int sqlite3_bind_text(sqlite3_stmt *stmt, int idx, const char *val, int length, void (*free_func)(void *)) {
if (!val) {
return SQLITE_MISUSE;
}
string value;
if (length < 0) {
value = string(val);
} else {
value = string(val, length);
}
if (free_func && ((ptrdiff_t)free_func) != -1) {
free_func((void *)val);
val = nullptr;
}
try {
return sqlite3_internal_bind_value(stmt, idx, duckdb::Value(value));
} catch (std::exception &ex) {
return SQLITE_ERROR;
}
}
int sqlite3_bind_blob(sqlite3_stmt *stmt, int idx, const void *val, int length, void (*free_func)(void *)) {
if (!val) {
return SQLITE_MISUSE;
}
duckdb::Value blob;
if (length < 0) {
blob = duckdb::Value::BLOB(string((const char *)val));
} else {
blob = duckdb::Value::BLOB((const_data_ptr_t)val, length);
}
if (free_func && ((ptrdiff_t)free_func) != -1) {
free_func((void *)val);
val = nullptr;
}
try {
return sqlite3_internal_bind_value(stmt, idx, blob);
} catch (std::exception &ex) {
return SQLITE_ERROR;
}
}
SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *stmt, int idx, int length) {
fprintf(stderr, "sqlite3_bind_zeroblob: unsupported.\n");
return SQLITE_ERROR;
}
int sqlite3_clear_bindings(sqlite3_stmt *stmt) {
if (!stmt) {
return SQLITE_MISUSE;
}
return SQLITE_OK;
}
int sqlite3_initialize(void) {
return SQLITE_OK;
}
int sqlite3_finalize(sqlite3_stmt *pStmt) {
if (pStmt) {
if (pStmt->result && pStmt->result->HasError()) {
pStmt->db->last_error = pStmt->result->GetErrorObject();
delete pStmt;
return SQLITE_ERROR;
}
delete pStmt;
}
return SQLITE_OK;
}
/*
** Some systems have stricmp(). Others have strcasecmp(). Because
** there is no consistency, we will define our own.
**
** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
** sqlite3_strnicmp() APIs allow applications and extensions to compare
** the contents of two buffers containing UTF-8 strings in a
** case-independent fashion, using the same definition of "case
** independence" that SQLite uses internally when comparing identifiers.
*/
const unsigned char sqlite3UpperToLower[] = {
0, 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, 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, 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};
int sqlite3StrICmp(const char *zLeft, const char *zRight) {
unsigned char *a, *b;
int c;
a = (unsigned char *)zLeft;
b = (unsigned char *)zRight;
for (;;) {
c = (int)sqlite3UpperToLower[*a] - (int)sqlite3UpperToLower[*b];
if (c || *a == 0)
break;
a++;
b++;
}
return c;
}
SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight) {
if (zLeft == 0) {
return zRight ? -1 : 0;
} else if (zRight == 0) {
return 1;
}
return sqlite3StrICmp(zLeft, zRight);
}
SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N) {