-
Notifications
You must be signed in to change notification settings - Fork 376
/
vdbeapi.c
1717 lines (1603 loc) · 41 KB
/
vdbeapi.c
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
/*
* Copyright 2010-2017, Tarantool AUTHORS, please see AUTHORS file.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* 1. Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* <COPYRIGHT HOLDER> OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
* THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/*
*
* This file contains code use to implement APIs that are part of the
* VDBE.
*/
#include "sqlInt.h"
#include "vdbeInt.h"
/*
* Check on a Vdbe to make sure it has not been finalized. Log
* an error and return true if it has been finalized (or is otherwise
* invalid). Return false if it is ok.
*/
static int
vdbeSafety(Vdbe * p)
{
if (p->db == 0) {
sql_log(SQL_MISUSE,
"API called with finalized prepared statement");
return 1;
} else {
return 0;
}
}
static int
vdbeSafetyNotNull(Vdbe * p)
{
if (p == 0) {
sql_log(SQL_MISUSE,
"API called with NULL prepared statement");
return 1;
} else {
return vdbeSafety(p);
}
}
#ifndef SQL_OMIT_TRACE
/*
* Invoke the profile callback. This routine is only called if we already
* know that the profile callback is defined and needs to be invoked.
*/
static SQL_NOINLINE void
invokeProfileCallback(sql * db, Vdbe * p)
{
sql_int64 iNow;
sql_int64 iElapse;
assert(p->startTime > 0);
assert(db->xProfile != 0 || (db->mTrace & SQL_TRACE_PROFILE) != 0);
assert(db->init.busy == 0);
assert(p->zSql != 0);
sqlOsCurrentTimeInt64(db->pVfs, &iNow);
iElapse = (iNow - p->startTime) * 1000000;
if (db->xProfile) {
db->xProfile(db->pProfileArg, p->zSql, iElapse);
}
if (db->mTrace & SQL_TRACE_PROFILE) {
db->xTrace(SQL_TRACE_PROFILE, db->pTraceArg, p,
(void *)&iElapse);
}
p->startTime = 0;
}
/*
* The checkProfileCallback(DB,P) macro checks to see if a profile callback
* is needed, and it invokes the callback if it is needed.
*/
#define checkProfileCallback(DB,P) \
if( ((P)->startTime)>0 ){ invokeProfileCallback(DB,P); }
#else
#define checkProfileCallback(DB,P) /*no-op */
#endif
/*
* The following routine destroys a virtual machine that is created by
* the sql_compile() routine. The integer returned is an SQL_
* success/failure code that describes the result of executing the virtual
* machine.
*
* This routine sets the error code and string returned by
* sql_errcode(), sql_errmsg() and sql_errmsg16().
*/
int
sql_finalize(sql_stmt * pStmt)
{
int rc;
if (pStmt == 0) {
/* IMPLEMENTATION-OF: R-57228-12904 Invoking sql_finalize() on a NULL
* pointer is a harmless no-op.
*/
rc = SQL_OK;
} else {
Vdbe *v = (Vdbe *) pStmt;
sql *db = v->db;
if (vdbeSafety(v))
return SQL_MISUSE;
checkProfileCallback(db, v);
rc = sqlVdbeFinalize(v);
rc = sqlApiExit(db, rc);
}
return rc;
}
/*
* Terminate the current execution of an SQL statement and reset it
* back to its starting state so that it can be reused. A success code from
* the prior execution is returned.
*
* This routine sets the error code and string returned by
* sql_errcode(), sql_errmsg() and sql_errmsg16().
*/
int
sql_reset(sql_stmt * pStmt)
{
int rc;
if (pStmt == 0) {
rc = SQL_OK;
} else {
Vdbe *v = (Vdbe *) pStmt;
sql *db = v->db;
checkProfileCallback(db, v);
rc = sqlVdbeReset(v);
sqlVdbeRewind(v);
assert((rc & (db->errMask)) == rc);
rc = sqlApiExit(db, rc);
}
return rc;
}
/*
* Set all the parameters in the compiled SQL statement to NULL.
*/
int
sql_clear_bindings(sql_stmt * pStmt)
{
int i;
int rc = SQL_OK;
Vdbe *p = (Vdbe *) pStmt;
for (i = 0; i < p->nVar; i++) {
sqlVdbeMemRelease(&p->aVar[i]);
p->aVar[i].flags = MEM_Null;
}
if (p->isPrepareV2 && p->expmask) {
p->expired = 1;
}
return rc;
}
/**************************** sql_value_ ******************************
* The following routines extract information from a Mem or sql_value
* structure.
*/
const void *
sql_value_blob(sql_value * pVal)
{
Mem *p = (Mem *) pVal;
if (p->flags & (MEM_Blob | MEM_Str)) {
if (ExpandBlob(p) != SQL_OK) {
assert(p->flags == MEM_Null && p->z == 0);
return 0;
}
p->flags |= MEM_Blob;
return p->n ? p->z : 0;
} else {
return sql_value_text(pVal);
}
}
int
sql_value_bytes(sql_value * pVal)
{
return sqlValueBytes(pVal);
}
double
sql_value_double(sql_value * pVal)
{
double v;
sqlVdbeRealValue((Mem *) pVal, &v);
return v;
}
int
sql_value_int(sql_value * pVal)
{
int64_t i;
sqlVdbeIntValue((Mem *) pVal, &i);
return (int)i;
}
sql_int64
sql_value_int64(sql_value * pVal)
{
int64_t i;
sqlVdbeIntValue((Mem *) pVal, &i);
return i;
}
enum sql_subtype
sql_value_subtype(sql_value * pVal)
{
return (pVal->flags & MEM_Subtype) != 0 ? pVal->subtype : SQL_SUBTYPE_NO;
}
const unsigned char *
sql_value_text(sql_value * pVal)
{
return (const unsigned char *)sqlValueText(pVal);
}
/* EVIDENCE-OF: R-12793-43283 Every value in sql has one of five
* fundamental datatypes: 64-bit signed integer 64-bit IEEE floating
* point number string BLOB NULL
*/
int
sql_value_type(sql_value * pVal)
{
static const u8 aType[] = {
SQL_BLOB, /* 0x00 */
SQL_NULL, /* 0x01 */
SQL_TEXT, /* 0x02 */
SQL_NULL, /* 0x03 */
SQL_INTEGER, /* 0x04 */
SQL_NULL, /* 0x05 */
SQL_INTEGER, /* 0x06 */
SQL_NULL, /* 0x07 */
SQL_FLOAT, /* 0x08 */
SQL_NULL, /* 0x09 */
SQL_FLOAT, /* 0x0a */
SQL_NULL, /* 0x0b */
SQL_INTEGER, /* 0x0c */
SQL_NULL, /* 0x0d */
SQL_INTEGER, /* 0x0e */
SQL_NULL, /* 0x0f */
SQL_BLOB, /* 0x10 */
SQL_NULL, /* 0x11 */
SQL_TEXT, /* 0x12 */
SQL_NULL, /* 0x13 */
SQL_INTEGER, /* 0x14 */
SQL_NULL, /* 0x15 */
SQL_INTEGER, /* 0x16 */
SQL_NULL, /* 0x17 */
SQL_FLOAT, /* 0x18 */
SQL_NULL, /* 0x19 */
SQL_FLOAT, /* 0x1a */
SQL_NULL, /* 0x1b */
SQL_INTEGER, /* 0x1c */
SQL_NULL, /* 0x1d */
SQL_INTEGER, /* 0x1e */
SQL_NULL, /* 0x1f */
};
return aType[pVal->flags & MEM_PURE_TYPE_MASK];
}
/* Make a copy of an sql_value object
*/
sql_value *
sql_value_dup(const sql_value * pOrig)
{
sql_value *pNew;
if (pOrig == 0)
return 0;
pNew = sql_malloc(sizeof(*pNew));
if (pNew == 0)
return 0;
memset(pNew, 0, sizeof(*pNew));
memcpy(pNew, pOrig, MEMCELLSIZE);
pNew->flags &= ~MEM_Dyn;
pNew->db = 0;
if (pNew->flags & (MEM_Str | MEM_Blob)) {
pNew->flags &= ~(MEM_Static | MEM_Dyn);
pNew->flags |= MEM_Ephem;
if (sqlVdbeMemMakeWriteable(pNew) != SQL_OK) {
sqlValueFree(pNew);
pNew = 0;
}
}
return pNew;
}
/* Destroy an sql_value object previously obtained from
* sql_value_dup().
*/
void
sql_value_free(sql_value * pOld)
{
sqlValueFree(pOld);
}
/**************************** sql_result_ ******************************
* The following routines are used by user-defined functions to specify
* the function result.
*
* The setStrOrError() function calls sqlVdbeMemSetStr() to store the
* result as a string or blob but if the string or blob is too large, it
* then sets the error code to SQL_TOOBIG
*
* The invokeValueDestructor(P,X) routine invokes destructor function X()
* on value P is not going to be used and need to be destroyed.
*/
static void
setResultStrOrError(sql_context * pCtx, /* Function context */
const char *z, /* String pointer */
int n, /* Bytes in string, or negative */
void (*xDel) (void *) /* Destructor function */
)
{
if (sqlVdbeMemSetStr(pCtx->pOut, z, n,1, xDel) == SQL_TOOBIG) {
sql_result_error_toobig(pCtx);
}
}
static int
invokeValueDestructor(const void *p, /* Value to destroy */
void (*xDel) (void *), /* The destructor */
sql_context * pCtx /* Set a SQL_TOOBIG error if no NULL */
)
{
assert(xDel != SQL_DYNAMIC);
if (xDel == 0) {
/* noop */
} else if (xDel == SQL_TRANSIENT) {
/* noop */
} else {
xDel((void *)p);
}
if (pCtx)
sql_result_error_toobig(pCtx);
return SQL_TOOBIG;
}
void
sql_result_blob(sql_context * pCtx,
const void *z, int n, void (*xDel) (void *)
)
{
assert(n >= 0);
if (sqlVdbeMemSetStr(pCtx->pOut, z, n,0, xDel) == SQL_TOOBIG) {
sql_result_error_toobig(pCtx);
}
}
void
sql_result_blob64(sql_context * pCtx,
const void *z, sql_uint64 n, void (*xDel) (void *)
)
{
assert(xDel != SQL_DYNAMIC);
if (n > 0x7fffffff) {
(void)invokeValueDestructor(z, xDel, pCtx);
} else {
setResultStrOrError(pCtx, z, (int)n, xDel);
}
}
void
sql_result_double(sql_context * pCtx, double rVal)
{
sqlVdbeMemSetDouble(pCtx->pOut, rVal);
}
void
sql_result_error(sql_context * pCtx, const char *z, int n)
{
pCtx->isError = SQL_ERROR;
pCtx->fErrorOrAux = 1;
sqlVdbeMemSetStr(pCtx->pOut, z, n, 1, SQL_TRANSIENT);
}
void
sql_result_int(sql_context * pCtx, int iVal)
{
sqlVdbeMemSetInt64(pCtx->pOut, (i64) iVal);
}
void
sql_result_int64(sql_context * pCtx, i64 iVal)
{
sqlVdbeMemSetInt64(pCtx->pOut, iVal);
}
void
sql_result_null(sql_context * pCtx)
{
sqlVdbeMemSetNull(pCtx->pOut);
}
void
sql_result_text(sql_context * pCtx,
const char *z, int n, void (*xDel) (void *)
)
{
setResultStrOrError(pCtx, z, n, xDel);
}
void
sql_result_text64(sql_context * pCtx,
const char *z,
sql_uint64 n,
void (*xDel) (void *))
{
assert(xDel != SQL_DYNAMIC);
if (n > 0x7fffffff) {
(void)invokeValueDestructor(z, xDel, pCtx);
} else {
setResultStrOrError(pCtx, z, (int)n, xDel);
}
}
void
sql_result_value(sql_context * pCtx, sql_value * pValue)
{
sqlVdbeMemCopy(pCtx->pOut, pValue);
}
void
sql_result_zeroblob(sql_context * pCtx, int n)
{
sqlVdbeMemSetZeroBlob(pCtx->pOut, n);
}
int
sql_result_zeroblob64(sql_context * pCtx, u64 n)
{
Mem *pOut = pCtx->pOut;
if (n > (u64) pOut->db->aLimit[SQL_LIMIT_LENGTH]) {
return SQL_TOOBIG;
}
sqlVdbeMemSetZeroBlob(pCtx->pOut, (int)n);
return SQL_OK;
}
void
sql_result_error_code(sql_context * pCtx, int errCode)
{
pCtx->isError = errCode;
pCtx->fErrorOrAux = 1;
if (pCtx->pOut->flags & MEM_Null) {
sqlVdbeMemSetStr(pCtx->pOut, sqlErrStr(errCode), -1, 1,
SQL_STATIC);
}
}
/* Force an SQL_TOOBIG error. */
void
sql_result_error_toobig(sql_context * pCtx)
{
pCtx->isError = SQL_TOOBIG;
pCtx->fErrorOrAux = 1;
sqlVdbeMemSetStr(pCtx->pOut, "string or blob too big", -1, 1,
SQL_STATIC);
}
/* An SQL_NOMEM error. */
void
sql_result_error_nomem(sql_context * pCtx)
{
sqlVdbeMemSetNull(pCtx->pOut);
pCtx->isError = SQL_NOMEM;
pCtx->fErrorOrAux = 1;
sqlOomFault(pCtx->pOut->db);
}
/*
* Execute the statement pStmt, either until a row of data is ready, the
* statement is completely executed or an error occurs.
*
* This routine implements the bulk of the logic behind the sql_step()
* API. The only thing omitted is the automatic recompile if a
* schema change has occurred. That detail is handled by the
* outer sql_step() wrapper procedure.
*/
static int
sqlStep(Vdbe * p)
{
sql *db;
int rc;
assert(p);
if (p->magic != VDBE_MAGIC_RUN) {
/* We used to require that sql_reset() be called before retrying
* sql_step() after any error or after SQL_DONE. But beginning
* with version 3.7.0, we changed this so that sql_reset() would
* be called automatically instead of throwing the SQL_MISUSE error.
* This "automatic-reset" change is not technically an incompatibility,
* since any application that receives an SQL_MISUSE is broken by
* definition.
*
* Nevertheless, some published applications that were originally written
* for version 3.6.23 or earlier do in fact depend on SQL_MISUSE
* returns, and those were broken by the automatic-reset change. As a
* a work-around, the SQL_OMIT_AUTORESET compile-time restores the
* legacy behavior of returning SQL_MISUSE for cases where the
* previous sql_step() returned something other than a SQL_LOCKED
* or SQL_BUSY error.
*/
#ifdef SQL_OMIT_AUTORESET
if ((rc = p->rc & 0xff) == SQL_BUSY || rc == SQL_LOCKED) {
sql_reset((sql_stmt *) p);
} else {
return SQL_MISUSE;
}
#else
sql_reset((sql_stmt *) p);
#endif
}
/* Check that malloc() has not failed. If it has, return early. */
db = p->db;
if (db->mallocFailed) {
p->rc = SQL_NOMEM;
return SQL_NOMEM;
}
if (p->pc <= 0 && p->expired) {
p->rc = SQL_SCHEMA;
rc = SQL_ERROR;
goto end_of_step;
}
if (p->pc < 0) {
/* If there are no other statements currently running, then
* reset the interrupt flag. This prevents a call to sql_interrupt
* from interrupting a statement that has not yet started.
*/
if (db->nVdbeActive == 0) {
db->u1.isInterrupted = 0;
}
#ifndef SQL_OMIT_TRACE
if ((db->xProfile || (db->mTrace & SQL_TRACE_PROFILE) != 0)
&& !db->init.busy && p->zSql) {
sqlOsCurrentTimeInt64(db->pVfs, &p->startTime);
} else {
assert(p->startTime == 0);
}
#endif
db->nVdbeActive++;
p->pc = 0;
}
if (p->explain) {
rc = sqlVdbeList(p);
} else {
db->nVdbeExec++;
rc = sqlVdbeExec(p);
db->nVdbeExec--;
}
#ifndef SQL_OMIT_TRACE
/* If the statement completed successfully, invoke the profile callback */
if (rc != SQL_ROW)
checkProfileCallback(db, p);
#endif
db->errCode = rc;
if (SQL_NOMEM == sqlApiExit(p->db, p->rc)) {
p->rc = SQL_NOMEM;
}
end_of_step:
/* At this point local variable rc holds the value that should be
* returned if this statement was compiled using the legacy
* sql_prepare() interface. According to the docs, this can only
* be one of the values in the first assert() below. Variable p->rc
* contains the value that would be returned if sql_finalize()
* were called on statement p.
*/
assert(rc == SQL_ROW || rc == SQL_DONE || rc == SQL_ERROR
|| (rc & 0xff) == SQL_BUSY || rc == SQL_MISUSE);
if (p->isPrepareV2 && rc != SQL_ROW && rc != SQL_DONE) {
/* If this statement was prepared using sql_prepare_v2(), and an
* error has occurred, then return the error code in p->rc to the
* caller. Set the error code in the database handle to the same value.
*/
rc = sqlVdbeTransferError(p);
}
return (rc & db->errMask);
}
/*
* This is the top-level implementation of sql_step(). Call
* sqlStep() to do most of the work. If a schema error occurs,
* call sqlReprepare() and try again.
*/
int
sql_step(sql_stmt * pStmt)
{
int rc; /* Result from sqlStep() */
int rc2 = SQL_OK; /* Result from sqlReprepare() */
Vdbe *v = (Vdbe *) pStmt; /* the prepared statement */
int cnt = 0; /* Counter to prevent infinite loop of reprepares */
sql *db; /* The database connection */
if (vdbeSafetyNotNull(v)) {
return SQL_MISUSE;
}
db = v->db;
v->doingRerun = 0;
while ((rc = sqlStep(v)) == SQL_SCHEMA
&& cnt++ < SQL_MAX_SCHEMA_RETRY) {
int savedPc = v->pc;
rc2 = rc = sqlReprepare(v);
if (rc != SQL_OK)
break;
sql_reset(pStmt);
if (savedPc >= 0)
v->doingRerun = 1;
assert(v->expired == 0);
}
if (rc2 != SQL_OK) {
/* This case occurs after failing to recompile an sql statement.
* The error message from the SQL compiler has already been loaded
* into the database handle. This block copies the error message
* from the database handle into the statement and sets the statement
* program counter to 0 to ensure that when the statement is
* finalized or reset the parser error message is available via
* sql_errmsg() and sql_errcode().
*/
const char *zErr = (const char *)sql_value_text(db->pErr);
sqlDbFree(db, v->zErrMsg);
if (!db->mallocFailed) {
v->zErrMsg = sqlDbStrDup(db, zErr);
v->rc = rc2;
} else {
v->zErrMsg = 0;
v->rc = rc = SQL_NOMEM;
}
}
rc = sqlApiExit(db, rc);
return rc;
}
/*
* Extract the user data from a sql_context structure and return a
* pointer to it.
*/
void *
sql_user_data(sql_context * p)
{
assert(p && p->pFunc);
return p->pFunc->pUserData;
}
/*
* Extract the user data from a sql_context structure and return a
* pointer to it.
*
* IMPLEMENTATION-OF: R-46798-50301 The sql_context_db_handle() interface
* returns a copy of the pointer to the database connection (the 1st
* parameter) of the sql_create_function() and
* sql_create_function16() routines that originally registered the
* application defined function.
*/
sql *
sql_context_db_handle(sql_context * p)
{
assert(p && p->pOut);
return p->pOut->db;
}
/*
* Return the current time for a statement. If the current time
* is requested more than once within the same run of a single prepared
* statement, the exact same time is returned for each invocation regardless
* of the amount of time that elapses between invocations. In other words,
* the time returned is always the time of the first call.
*/
sql_int64
sqlStmtCurrentTime(sql_context * p)
{
int rc;
#ifndef SQL_ENABLE_OR_STAT4
sql_int64 *piTime = &p->pVdbe->iCurrentTime;
assert(p->pVdbe != 0);
#else
sql_int64 iTime = 0;
sql_int64 *piTime =
p->pVdbe != 0 ? &p->pVdbe->iCurrentTime : &iTime;
#endif
if (*piTime == 0) {
rc = sqlOsCurrentTimeInt64(p->pOut->db->pVfs, piTime);
if (rc)
*piTime = 0;
}
return *piTime;
}
/*
* The following is the implementation of an SQL function that always
* fails with an error message stating that the function is used in the
* wrong context. The sql_overload_function() API might construct
* SQL function that use this routine so that the functions will exist
* for name resolution.
*/
void
sqlInvalidFunction(sql_context * context, /* The function calling context */
int NotUsed, /* Number of arguments to the function */
sql_value ** NotUsed2 /* Value of each argument */
)
{
const char *zName = context->pFunc->zName;
char *zErr;
UNUSED_PARAMETER2(NotUsed, NotUsed2);
zErr =
sql_mprintf
("unable to use function %s in the requested context", zName);
sql_result_error(context, zErr, -1);
sql_free(zErr);
}
/*
* Create a new aggregate context for p and return a pointer to
* its pMem->z element.
*/
static SQL_NOINLINE void *
createAggContext(sql_context * p, int nByte)
{
Mem *pMem = p->pMem;
assert((pMem->flags & MEM_Agg) == 0);
if (nByte <= 0) {
sqlVdbeMemSetNull(pMem);
pMem->z = 0;
} else {
sqlVdbeMemClearAndResize(pMem, nByte);
pMem->flags = MEM_Agg;
pMem->u.pDef = p->pFunc;
if (pMem->z) {
memset(pMem->z, 0, nByte);
}
}
return (void *)pMem->z;
}
/*
* Allocate or return the aggregate context for a user function. A new
* context is allocated on the first call. Subsequent calls return the
* same context that was returned on prior calls.
*/
void *
sql_aggregate_context(sql_context * p, int nByte)
{
assert(p && p->pFunc && p->pFunc->xFinalize);
testcase(nByte < 0);
if ((p->pMem->flags & MEM_Agg) == 0) {
return createAggContext(p, nByte);
} else {
return (void *)p->pMem->z;
}
}
/*
* Return the auxiliary data pointer, if any, for the iArg'th argument to
* the user-function defined by pCtx.
*/
void *
sql_get_auxdata(sql_context * pCtx, int iArg)
{
AuxData *pAuxData;
if (pCtx->pVdbe == 0)
return 0;
for (pAuxData = pCtx->pVdbe->pAuxData; pAuxData;
pAuxData = pAuxData->pNext) {
if (pAuxData->iOp == pCtx->iOp && pAuxData->iArg == iArg)
break;
}
return (pAuxData ? pAuxData->pAux : 0);
}
/*
* Set the auxiliary data pointer and delete function, for the iArg'th
* argument to the user-function defined by pCtx. Any previous value is
* deleted by calling the delete function specified when it was set.
*/
void
sql_set_auxdata(sql_context * pCtx,
int iArg, void *pAux, void (*xDelete) (void *)
)
{
AuxData *pAuxData;
Vdbe *pVdbe = pCtx->pVdbe;
if (iArg < 0)
goto failed;
if (pVdbe == 0)
goto failed;
for (pAuxData = pVdbe->pAuxData; pAuxData; pAuxData = pAuxData->pNext) {
if (pAuxData->iOp == pCtx->iOp && pAuxData->iArg == iArg)
break;
}
if (pAuxData == 0) {
pAuxData = sqlDbMallocZero(pVdbe->db, sizeof(AuxData));
if (!pAuxData)
goto failed;
pAuxData->iOp = pCtx->iOp;
pAuxData->iArg = iArg;
pAuxData->pNext = pVdbe->pAuxData;
pVdbe->pAuxData = pAuxData;
if (pCtx->fErrorOrAux == 0) {
pCtx->isError = 0;
pCtx->fErrorOrAux = 1;
}
} else if (pAuxData->xDelete) {
pAuxData->xDelete(pAuxData->pAux);
}
pAuxData->pAux = pAux;
pAuxData->xDelete = xDelete;
return;
failed:
if (xDelete) {
xDelete(pAux);
}
}
/*
* Return the number of columns in the result set for the statement pStmt.
*/
int
sql_column_count(sql_stmt * pStmt)
{
Vdbe *pVm = (Vdbe *) pStmt;
return pVm ? pVm->nResColumn : 0;
}
/*
* Return the number of values available from the current row of the
* currently executing statement pStmt.
*/
int
sql_data_count(sql_stmt * pStmt)
{
Vdbe *pVm = (Vdbe *) pStmt;
if (pVm == 0 || pVm->pResultSet == 0)
return 0;
return pVm->nResColumn;
}
/*
* Return a pointer to static memory containing an SQL NULL value.
*/
static const Mem *
columnNullValue(void)
{
/* Even though the Mem structure contains an element
* of type i64, on certain architectures (x86) with certain compiler
* switches (-Os), gcc may align this Mem object on a 4-byte boundary
* instead of an 8-byte one. This all works fine, except that when
* running with SQL_DEBUG defined the sql code sometimes assert()s
* that a Mem structure is located on an 8-byte boundary. To prevent
* these assert()s from failing, when building with SQL_DEBUG defined
* using gcc, we force nullMem to be 8-byte aligned using the magical
* __attribute__((aligned(8))) macro.
*/
static const Mem nullMem
#if defined(SQL_DEBUG) && defined(__GNUC__)
__attribute__ ((aligned(8)))
#endif
= {
/* .u = */ {
0},
/* .flags = */ (u16) MEM_Null,
/* .eSubtype = */ (u8) 0,
/* .n = */ (int)0,
/* .z = */ (char *)0,
/* .zMalloc = */ (char *)0,
/* .szMalloc = */ (int)0,
/* .uTemp = */ (u32) 0,
/* .db = */ (sql *) 0,
/* .xDel = */ (void (*)(void *))0,
#ifdef SQL_DEBUG
/* .pScopyFrom = */ (Mem *) 0,
/* .pFiller = */ (void *)0,
#endif
};
return &nullMem;
}
/*
* Check to see if column iCol of the given statement is valid. If
* it is, return a pointer to the Mem for the value of that column.
* If iCol is not valid, return a pointer to a Mem which has a value
* of NULL.
*/
static Mem *
columnMem(sql_stmt * pStmt, int i)
{
Vdbe *pVm;
Mem *pOut;
pVm = (Vdbe *) pStmt;
if (pVm == 0)
return (Mem *) columnNullValue();
assert(pVm->db);
if (pVm->pResultSet != 0 && i < pVm->nResColumn && i >= 0) {
pOut = &pVm->pResultSet[i];
} else {
sqlError(pVm->db, SQL_RANGE);
pOut = (Mem *) columnNullValue();
}
return pOut;
}
/*
* This function is called after invoking an sql_value_XXX function on a
* column value (i.e. a value returned by evaluating an SQL expression in the
* select list of a SELECT statement) that may cause a malloc() failure. If
* malloc() has failed, the threads mallocFailed flag is cleared and the result
* code of statement pStmt set to SQL_NOMEM.
*
* Specifically, this is called from within:
*
* sql_column_int()
* sql_column_int64()
* sql_column_text()
* sql_column_real()
* sql_column_bytes()
* sql_column_bytes16()
* sqiite3_column_blob()
*/
static void
columnMallocFailure(sql_stmt * pStmt)
{
/* If malloc() failed during an encoding conversion within an
* sql_column_XXX API, then set the return code of the statement to
* SQL_NOMEM. The next call to _step() (if any) will return SQL_ERROR
* and _finalize() will return NOMEM.
*/
Vdbe *p = (Vdbe *) pStmt;
if (p) {
assert(p->db != 0);
p->rc = sqlApiExit(p->db, p->rc);
}
}
/**************************** sql_column_ ******************************
* The following routines are used to access elements of the current row
* in the result set.
*/
const void *
sql_column_blob(sql_stmt * pStmt, int i)
{
const void *val;
val = sql_value_blob(columnMem(pStmt, i));
/* Even though there is no encoding conversion, value_blob() might
* need to call malloc() to expand the result of a zeroblob()
* expression.
*/
columnMallocFailure(pStmt);
return val;
}
int
sql_column_bytes(sql_stmt * pStmt, int i)
{
int val = sql_value_bytes(columnMem(pStmt, i));
columnMallocFailure(pStmt);
return val;
}
double
sql_column_double(sql_stmt * pStmt, int i)
{
double val = sql_value_double(columnMem(pStmt, i));
columnMallocFailure(pStmt);
return val;