-
Notifications
You must be signed in to change notification settings - Fork 2
/
ma_statement.c
6482 lines (5804 loc) · 227 KB
/
ma_statement.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 (C) 2013,2019 MariaDB Corporation AB
2021 SingleStore, Inc.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not see <http://www.gnu.org/licenses>
or write to the Free Software Foundation, Inc.,
51 Franklin St., Fifth Floor, Boston, MA 02110, USA
*************************************************************************************/
#include <ma_odbc.h>
#define MADB_MIN_QUERY_LEN 5
// SingleStore imposes a limit on the number of parameters sent in one statement. It is defined by
// the global var parametrizer_query_max_params which defaults to 1048576.q
// TODO: PLAT-6999 respect parametrizer_query_max_params value
#define S2_MAX_PARAMS 1024000
struct st_ma_stmt_methods MADB_StmtMethods; /* declared at the end of file */
/* {{{ MADB_StmtInit */
SQLRETURN MADB_StmtInit(MADB_Dbc *Connection, SQLHANDLE *pHStmt)
{
MADB_Stmt *Stmt= NULL;
if (!(Stmt = (MADB_Stmt *)MADB_CALLOC(sizeof(MADB_Stmt))))
goto error;
MADB_PutErrorPrefix(Connection, &Stmt->Error);
*pHStmt= Stmt;
Stmt->Connection= Connection;
LOCK_MARIADB(Connection);
if (!(Stmt->stmt= MADB_NewStmtHandle(Stmt)) ||
!(Stmt->IApd= MADB_DescInit(Connection, MADB_DESC_APD, FALSE)) ||
!(Stmt->IArd= MADB_DescInit(Connection, MADB_DESC_ARD, FALSE)) ||
!(Stmt->IIpd= MADB_DescInit(Connection, MADB_DESC_IPD, FALSE)) ||
!(Stmt->IIrd= MADB_DescInit(Connection, MADB_DESC_IRD, FALSE)))
{
UNLOCK_MARIADB(Stmt->Connection);
goto error;
}
MDBUG_C_PRINT(Stmt->Connection, "-->inited %0x", Stmt->stmt);
UNLOCK_MARIADB(Connection);
Stmt->PutParam= -1;
Stmt->Methods= &MADB_StmtMethods;
Stmt->Options.CursorType= SQL_CURSOR_FORWARD_ONLY;
Stmt->Options.UseBookmarks= SQL_UB_OFF;
Stmt->Options.MetadataId= Connection->MetadataId;
Stmt->Apd= Stmt->IApd;
Stmt->Ard= Stmt->IArd;
Stmt->Ipd= Stmt->IIpd;
Stmt->Ird= Stmt->IIrd;
Stmt->ListItem.data= (void *)Stmt;
EnterCriticalSection(&Stmt->Connection->ListsCs);
Stmt->Connection->Stmts= MADB_ListAdd(Stmt->Connection->Stmts, &Stmt->ListItem);
LeaveCriticalSection(&Stmt->Connection->ListsCs);
Stmt->Ard->Header.ArraySize= 1;
return SQL_SUCCESS;
error:
if (Stmt && Stmt->stmt)
{
MADB_STMT_CLOSE_STMT(Stmt);
}
MADB_DescFree(Stmt->IApd, TRUE);
MADB_DescFree(Stmt->IArd, TRUE);
MADB_DescFree(Stmt->IIpd, TRUE);
MADB_DescFree(Stmt->IIrd, TRUE);
MADB_FREE(Stmt);
return SQL_ERROR;
}
/* }}} */
/* {{{ MADB_ExecuteQuery */
SQLRETURN MADB_ExecuteQuery(MADB_Stmt * Stmt, char *StatementText, SQLINTEGER TextLength)
{
SQLRETURN ret= SQL_ERROR;
LOCK_MARIADB(Stmt->Connection);
if (StatementText)
{
MDBUG_C_PRINT(Stmt->Connection, "mysql_real_query(%0x,%s,%lu)", Stmt->Connection->mariadb, StatementText, TextLength);
if(!mysql_real_query(Stmt->Connection->mariadb, StatementText, TextLength))
{
ret= SQL_SUCCESS;
MADB_CLEAR_ERROR(&Stmt->Error);
Stmt->AffectedRows= mysql_affected_rows(Stmt->Connection->mariadb);
}
else
{
MADB_SetNativeError(&Stmt->Error, SQL_HANDLE_DBC, Stmt->Connection->mariadb);
}
}
else
MADB_SetError(&Stmt->Error, MADB_ERR_HY001, mysql_error(Stmt->Connection->mariadb),
mysql_errno(Stmt->Connection->mariadb));
UNLOCK_MARIADB(Stmt->Connection);
return ret;
}
/* }}} */
/* {{{ MADB_StmtBulkOperations */
SQLRETURN MADB_StmtBulkOperations(MADB_Stmt *Stmt, SQLSMALLINT Operation)
{
MADB_CLEAR_ERROR(&Stmt->Error);
switch(Operation)
{
case SQL_ADD:
return Stmt->Methods->SetPos(Stmt, 0, SQL_ADD, SQL_LOCK_NO_CHANGE, 0);
default:
return MADB_SetError(&Stmt->Error, MADB_ERR_HYC00, "Operation is not supported", 0);
}
}
/* }}} */
/* {{{ RemoveStmtRefFromDesc
Helper function removing references to the stmt in the descriptor when explisitly allocated descriptor is substituted
by some other descriptor */
void RemoveStmtRefFromDesc(MADB_Desc *desc, MADB_Stmt *Stmt, BOOL all)
{
if (desc->AppType)
{
unsigned int i;
for (i=0; i < desc->Stmts.elements; ++i)
{
MADB_Stmt **refStmt= ((MADB_Stmt **)desc->Stmts.buffer) + i;
if (Stmt == *refStmt)
{
MADB_DeleteDynamicElement(&desc->Stmts, i);
if (!all)
{
return;
}
}
}
}
}
/* }}} */
/* {{{ ResetMetadata */
void ResetMetadata(MYSQL_RES** metadata, MYSQL_RES* new_metadata)
{
if (*metadata != NULL)
{
mysql_free_result(*metadata);
}
*metadata= new_metadata;
}
/* }}} */
/* {{{ MADB_CspsFreeResult
Frees the result set that was allocated by mysql_store_result for the client-side prepared statements mode. */
void MADB_CspsFreeResult(MADB_Stmt *Stmt, MYSQL_RES** CspsResult, MYSQL_STMT *stmt, my_bool FreeStmtResults)
{
if (MADB_SSPS_DISABLED(Stmt))
{
if (CspsResult && *CspsResult)
{
// Set the following fields to NULL, so we're sure they're released only once.
// Since we're not setting the alloc field, we should not reset it here, because it's being released
// differently.
if (stmt) // NULL shouldn't really happen.
{
stmt->result.data = NULL;
stmt->result_cursor = NULL;
stmt->field_count = 0;
stmt->fields = NULL;
if (FreeStmtResults)
{
while(mysql_more_results(stmt->mysql))
{
mysql_next_result(stmt->mysql);
}
}
}
// Free the result and set the ptr to NULL so it does not get released twice.
mysql_free_result(*CspsResult);
*CspsResult = NULL;
}
}
}
/* }}} */
/* {{{ MADB_CspsCopyResult
Makes a shallow copy of the result and stores it in the stmt.
This is relevant only for the client-side prepared statements mode. */
void MADB_CspsCopyResult(MADB_Stmt *Stmt, MYSQL_RES* CspsResult, MYSQL_STMT *stmt)
{
if (MADB_SSPS_DISABLED(Stmt))
{
// Both shouldn't be NULL, but just in case.
if (CspsResult && stmt)
{
// Make a shallow copy of the result.
// Also move all the metadata to Stmt to reuse it across API calls and avoid potential errors.
stmt->field_count = mysql_num_fields(CspsResult);
stmt->fields = mysql_fetch_fields(CspsResult);
// Currently, we always fetch the whole result set, so all these fields should be there by now.
if (CspsResult->data)
{
// Don't copy alloc, because it will not be used and will be released differently.
stmt->result.data = CspsResult->data->data;
stmt->result.fields = CspsResult->data->fields;
stmt->result.rows = CspsResult->data->rows;
stmt->result_cursor = CspsResult->data_cursor;
}
}
}
}
/* }}} */
/* {{{ MADB_StmtFree */
SQLRETURN MADB_StmtFree(MADB_Stmt *Stmt, SQLUSMALLINT Option)
{
if (!Stmt)
return SQL_INVALID_HANDLE;
switch (Option) {
case SQL_CLOSE:
if (Stmt->stmt)
{
if (Stmt->Ird)
MADB_DescFree(Stmt->Ird, TRUE);
if (Stmt->State > MADB_SS_PREPARED && !QUERY_IS_MULTISTMT(Stmt->Query))
{
MADB_CspsFreeResult(Stmt, &Stmt->CspsResult, Stmt->stmt, TRUE);
MDBUG_C_PRINT(Stmt->Connection, "mysql_stmt_free_result(%0x)", Stmt->stmt);
mysql_stmt_free_result(Stmt->stmt);
LOCK_MARIADB(Stmt->Connection);
MDBUG_C_PRINT(Stmt->Connection, "-->resetting %0x", Stmt->stmt);
mysql_stmt_reset(Stmt->stmt);
UNLOCK_MARIADB(Stmt->Connection);
}
if (QUERY_IS_MULTISTMT(Stmt->Query) && Stmt->MultiStmts)
{
unsigned int i;
LOCK_MARIADB(Stmt->Connection);
for (i=0; i < STMT_COUNT(Stmt->Query); ++i)
{
if (Stmt->MultiStmts[i] != NULL)
{
MADB_CspsFreeResult(Stmt, &Stmt->CspsMultiStmtResult[i], Stmt->MultiStmts[i], TRUE);
MDBUG_C_PRINT(Stmt->Connection, "-->resetting %0x(%u)", Stmt->MultiStmts[i], i);
mysql_stmt_reset(Stmt->MultiStmts[i]);
}
}
UNLOCK_MARIADB(Stmt->Connection);
}
ResetMetadata(&Stmt->metadata, NULL);
MADB_FREE(Stmt->result);
MADB_FREE(Stmt->CharOffset);
MADB_FREE(Stmt->Lengths);
RESET_STMT_STATE(Stmt);
RESET_DAE_STATUS(Stmt);
}
if (Stmt->State == MADB_SS_EMULATED)
{
LOCK_MARIADB(Stmt->Connection);
EmulatedCleanup(Stmt->Connection->mariadb);
UNLOCK_MARIADB(Stmt->Connection);
}
break;
case SQL_UNBIND:
MADB_FREE(Stmt->result);
MADB_DescFree(Stmt->Ard, TRUE);
break;
case SQL_RESET_PARAMS:
MADB_FREE(Stmt->params);
if (MADB_SSPS_DISABLED(Stmt))
{
// Release the memory allocated for the DAE params.
MADB_CspsFreeDAE(Stmt);
}
MADB_DescFree(Stmt->Apd, TRUE);
RESET_DAE_STATUS(Stmt);
break;
case SQL_DROP:
MADB_FREE(Stmt->params);
MADB_FREE(Stmt->result);
MADB_FREE(Stmt->Cursor.Name);
MADB_FREE(Stmt->CatalogName);
MADB_FREE(Stmt->TableName);
ResetMetadata(&Stmt->metadata, NULL);
/* For explicit descriptors we only remove reference to the stmt*/
if (Stmt->Apd->AppType)
{
EnterCriticalSection(&Stmt->Connection->ListsCs);
RemoveStmtRefFromDesc(Stmt->Apd, Stmt, TRUE);
LeaveCriticalSection(&Stmt->Connection->ListsCs);
MADB_DescFree(Stmt->IApd, FALSE);
}
else
{
MADB_DescFree( Stmt->Apd, FALSE);
}
if (Stmt->Ard->AppType)
{
EnterCriticalSection(&Stmt->Connection->ListsCs);
RemoveStmtRefFromDesc(Stmt->Ard, Stmt, TRUE);
LeaveCriticalSection(&Stmt->Connection->ListsCs);
MADB_DescFree(Stmt->IArd, FALSE);
}
else
{
MADB_DescFree(Stmt->Ard, FALSE);
}
if (MADB_SSPS_DISABLED(Stmt))
{
// Release the memory allocated for the DAE params.
MADB_CspsFreeDAE(Stmt);
}
MADB_DescFree(Stmt->Ipd, FALSE);
MADB_DescFree(Stmt->Ird, FALSE);
MADB_FREE(Stmt->CharOffset);
MADB_FREE(Stmt->Lengths);
ResetMetadata(&Stmt->DefaultsResult, NULL);
if (Stmt->DaeStmt != NULL)
{
Stmt->DaeStmt->Methods->StmtFree(Stmt->DaeStmt, SQL_DROP);
Stmt->DaeStmt= NULL;
}
EnterCriticalSection(&Stmt->Connection->cs);
if (Stmt->State == MADB_SS_EMULATED)
{
EmulatedCleanup(Stmt->Connection->mariadb);
}
/* TODO: if multistatement was prepared, but not executed, we would get here Stmt->stmt leaked. Unlikely that is very probable scenario,
thus leaving this for new version */
if (QUERY_IS_MULTISTMT(Stmt->Query) && Stmt->MultiStmts)
{
unsigned int i;
for (i= 0; i < STMT_COUNT(Stmt->Query); ++i)
{
/* This dirty hack allows to avoid crash in case stmt object was not allocated
TODO: The better place for this check would be where MultiStmts was not allocated
to avoid inconsistency(MultiStmtCount > 0 and MultiStmts is NULL */
if (Stmt->MultiStmts!= NULL && Stmt->MultiStmts[i] != NULL)
{
MADB_CspsFreeResult(Stmt, &Stmt->CspsMultiStmtResult[i], Stmt->MultiStmts[i], TRUE);
MDBUG_C_PRINT(Stmt->Connection, "mysql_stmt_free_result(%0x)", Stmt->MultiStmts[i]);
mysql_stmt_free_result(Stmt->MultiStmts[i]);
MDBUG_C_PRINT(Stmt->Connection, "-->closing %0x(%u)", Stmt->MultiStmts[i], i);
mysql_stmt_close(Stmt->MultiStmts[i]);
}
}
MADB_FREE(Stmt->MultiStmts);
MADB_FREE(Stmt->CspsMultiStmtResult);
Stmt->MultiStmtNr= 0;
}
else if (Stmt->stmt != NULL)
{
MADB_CspsFreeResult(Stmt, &Stmt->CspsResult, Stmt->stmt, TRUE);
MDBUG_C_PRINT(Stmt->Connection, "-->closing %0x", Stmt->stmt);
MADB_STMT_CLOSE_STMT(Stmt);
}
/* Query has to be deleted after multistmt handles are closed, since the depends on info in the Query */
MADB_DeleteQuery(&Stmt->Query);
LeaveCriticalSection(&Stmt->Connection->cs);
EnterCriticalSection(&Stmt->Connection->ListsCs);
Stmt->Connection->Stmts= MADB_ListDelete(Stmt->Connection->Stmts, &Stmt->ListItem);
LeaveCriticalSection(&Stmt->Connection->ListsCs);
MADB_FREE(Stmt);
} /* End of switch (Option) */
return SQL_SUCCESS;
}
/* }}} */
/* {{{ MADB_StmtExecDirect */
SQLRETURN MADB_StmtExecDirect(MADB_Stmt *Stmt, char *StatementText, SQLINTEGER TextLength)
{
SQLRETURN ret;
BOOL ExecDirect= TRUE;
ret= Stmt->Methods->Prepare(Stmt, StatementText, TextLength, ExecDirect);
/* In case statement is not supported, we use mysql_query instead */
if (!SQL_SUCCEEDED(ret))
{
/* This is not quite good - 1064 may simply mean that syntax is wrong. we are screwed then */
if ((Stmt->Error.NativeError == 1295/*ER_UNSUPPORTED_PS*/ ||
Stmt->Error.NativeError == 1064/*ER_PARSE_ERROR*/))
{
Stmt->State= MADB_SS_EMULATED;
}
else
{
return ret;
}
}
/* For multistmt we don't use mariadb_stmt_execute_direct so far */
if (QUERY_IS_MULTISTMT(Stmt->Query))
{
ExecDirect= FALSE;
}
ret = Stmt->Methods->Execute(Stmt, ExecDirect);
if (SQL_SUCCEEDED(ret)) return ret;
/* In case statement is not supported, we use mysql_query instead. */
/* Sometimes SingleStore returns this error only at the execute stage, */
/* prepare can be successful */
if (Stmt->Error.NativeError == 1295 /*ER_UNSUPPORTED_PS*/)
{
Stmt->Methods->Prepare(Stmt, StatementText, TextLength, ExecDirect);
Stmt->State= MADB_SS_EMULATED;
}
return Stmt->Methods->Execute(Stmt, ExecDirect);
}
/* }}} */
/* {{{ MADB_FindCursor */
MADB_Stmt *MADB_FindCursor(MADB_Stmt *Stmt, const char *CursorName)
{
MADB_Dbc *Dbc= Stmt->Connection;
MADB_List *LStmt, *LStmtNext;
for (LStmt= Dbc->Stmts; LStmt; LStmt= LStmtNext)
{
MADB_Cursor *Cursor= &((MADB_Stmt *)LStmt->data)->Cursor;
LStmtNext= LStmt->next;
if (Stmt != (MADB_Stmt *)LStmt->data &&
Cursor->Name && _stricmp(Cursor->Name, CursorName) == 0)
{
return (MADB_Stmt *)LStmt->data;
}
}
MADB_SetError(&Stmt->Error, MADB_ERR_34000, NULL, 0);
return NULL;
}
/* }}} */
/* {{{ FetchMetadata */
MYSQL_RES* FetchMetadata(MADB_Stmt *Stmt)
{
ResetMetadata(&Stmt->metadata, mysql_stmt_result_metadata(Stmt->stmt));
return Stmt->metadata;
}
/* }}} */
/* {{{ MADB_StmtReset - reseting Stmt handler for new use. Has to be called inside a lock */
void MADB_StmtReset(MADB_Stmt *Stmt)
{
if (!QUERY_IS_MULTISTMT(Stmt->Query) || Stmt->MultiStmts == NULL)
{
if (Stmt->State > MADB_SS_PREPARED)
{
MADB_CspsFreeResult(Stmt, &Stmt->CspsResult, Stmt->stmt, TRUE);
MDBUG_C_PRINT(Stmt->Connection, "mysql_stmt_free_result(%0x)", Stmt->stmt);
mysql_stmt_free_result(Stmt->stmt);
}
if (Stmt->State >= MADB_SS_PREPARED)
{
MDBUG_C_PRINT(Stmt->Connection, "-->closing %0x", Stmt->stmt);
MADB_STMT_CLOSE_STMT(Stmt);
Stmt->stmt= MADB_NewStmtHandle(Stmt);
MDBUG_C_PRINT(Stmt->Connection, "-->inited %0x", Stmt->stmt);
}
}
else
{
CloseMultiStatements(Stmt);
Stmt->stmt= MADB_NewStmtHandle(Stmt);
MDBUG_C_PRINT(Stmt->Connection, "-->inited %0x", Stmt->stmt);
}
switch (Stmt->State)
{
case MADB_SS_EXECUTED:
case MADB_SS_OUTPARAMSFETCHED:
MADB_FREE(Stmt->result);
MADB_FREE(Stmt->CharOffset);
MADB_FREE(Stmt->Lengths);
RESET_DAE_STATUS(Stmt);
case MADB_SS_PREPARED:
ResetMetadata(&Stmt->metadata, NULL);
Stmt->PositionedCursor= NULL;
Stmt->Ird->Header.Count= 0;
case MADB_SS_EMULATED:
/* We can have the case, then query did not succeed, and in case of direct execution we wouldn't
have ane state set, but some of stuff still needs to be cleaned. Perhaps we could introduce a state
for such case, smth like DIREXEC_PREPARED. Would be more proper, but yet overkill */
EmulatedCleanup(Stmt->Connection->mariadb);
default:
Stmt->PositionedCommand= 0;
Stmt->State= MADB_SS_INITED;
MADB_CLEAR_ERROR(&Stmt->Error);
}
}
/* }}} */
/* {{{ MADB_EDPrepare - Method called from SQLPrepare in case it is SQLExecDirect and if server >= 10.2
(i.e. we gonna do mariadb_stmt_exec_direct) */
SQLRETURN MADB_EDPrepare(MADB_Stmt *Stmt)
{
/* TODO: In case of positioned command it shouldn't be always*/
if ((Stmt->ParamCount= Stmt->Apd->Header.Count + (MADB_POSITIONED_COMMAND(Stmt) ? MADB_POS_COMM_IDX_FIELD_COUNT(Stmt) : 0)) != 0)
{
if (Stmt->params)
{
MADB_FREE(Stmt->params);
}
/* If we have "WHERE CURRENT OF", we will need bind additionaly parameters for each field in the index */
Stmt->params= (MYSQL_BIND *)MADB_CALLOC(sizeof(MYSQL_BIND) * Stmt->ParamCount);
}
return SQL_SUCCESS;
}
/* }}} */
/* {{{ MADB_RegularPrepare - Method called from SQLPrepare in case it is SQLExecDirect and if !(server > 10.2)
(i.e. we aren't going to do mariadb_stmt_exec_direct) */
SQLRETURN MADB_RegularPrepare(MADB_Stmt *Stmt)
{
LOCK_MARIADB(Stmt->Connection);
MDBUG_C_PRINT(Stmt->Connection, "mysql_stmt_prepare(%0x,%s)", Stmt->stmt, STMT_STRING(Stmt));
if (mysql_stmt_prepare(Stmt->stmt, STMT_STRING(Stmt), (unsigned long)strlen(STMT_STRING(Stmt))))
{
/* Need to save error first */
MADB_SetNativeError(&Stmt->Error, SQL_HANDLE_STMT, Stmt->stmt);
/* We need to close the stmt here, or it becomes unusable like in ODBC-21 */
MDBUG_C_PRINT(Stmt->Connection, "mysql_stmt_close(%0x)", Stmt->stmt);
MADB_STMT_CLOSE_STMT(Stmt);
Stmt->stmt= MADB_NewStmtHandle(Stmt);
UNLOCK_MARIADB(Stmt->Connection);
MDBUG_C_PRINT(Stmt->Connection, "mysql_stmt_init(%0x)->%0x", Stmt->Connection->mariadb, Stmt->stmt);
return Stmt->Error.ReturnValue;
}
UNLOCK_MARIADB(Stmt->Connection);
Stmt->State= MADB_SS_PREPARED;
/* If we have result returning query - fill descriptor records with metadata */
if (mysql_stmt_field_count(Stmt->stmt) > 0)
{
MADB_DescSetIrdMetadata(Stmt, mysql_fetch_fields(FetchMetadata(Stmt)), mysql_stmt_field_count(Stmt->stmt));
}
if ((Stmt->ParamCount= (SQLSMALLINT)mysql_stmt_param_count(Stmt->stmt)))
{
if (Stmt->params)
{
MADB_FREE(Stmt->params);
}
Stmt->params= (MYSQL_BIND *)MADB_CALLOC(sizeof(MYSQL_BIND) * Stmt->ParamCount);
}
return SQL_SUCCESS;
}
/* }}} */
/* {{{ MADB_StmtPrepare */
SQLRETURN MADB_StmtPrepare(MADB_Stmt *Stmt, char *StatementText, SQLINTEGER TextLength, BOOL ExecDirect)
{
char *CursorName= NULL;
unsigned int WhereOffset;
BOOL HasParameters= 0;
MDBUG_C_PRINT(Stmt->Connection, "%sMADB_StmtPrepare", "\t->");
LOCK_MARIADB(Stmt->Connection);
MADB_StmtReset(Stmt);
/* After this point we can't have SQL_NTS*/
ADJUST_LENGTH(StatementText, TextLength);
/* There is no need to send anything to the server to find out there is syntax error here */
if (TextLength < MADB_MIN_QUERY_LEN)
{
return MADB_SetError(&Stmt->Error, MADB_ERR_42000, NULL, 0);
}
if (MADB_ResetParser(Stmt, StatementText, TextLength) != 0)
{
return Stmt->Error.ReturnValue;
}
MADB_ParseQuery(&Stmt->Query, Stmt->Connection->Dsn->RewriteCallSP);
if ((Stmt->Query.QueryType == MADB_QUERY_INSERT || Stmt->Query.QueryType == MADB_QUERY_UPDATE || Stmt->Query.QueryType == MADB_QUERY_DELETE)
&& MADB_FindToken(&Stmt->Query, "RETURNING"))
{
Stmt->Query.ReturnsResult= '\1';
}
if (QUERY_IS_MULTISTMT(Stmt->Query) && NO_CACHE(Stmt))
{
return MADB_SetError(&Stmt->Error, MADB_ERR_HY000, "Execution of the multi-statement is not supported with Forward-Only cursor and NO_CACHE option enabled", 0);
}
/* if we have multiple statements we save single statements in Stmt->StrMultiStmt
and store the number in Stmt->MultiStmts */
/* If client-side prepared statements are enabled or neither of statements
returns result, and does not have parameters, we will run them using text protocol. */
if (QueryIsPossiblyMultistmt(&Stmt->Query) && QUERY_IS_MULTISTMT(Stmt->Query) &&
(Stmt->Query.ReturnsResult || Stmt->Query.HasParameters) && Stmt->Query.BatchAllowed)
{
// Do not yet understand this case.
// As the result of this codepath we end up assuming we have more params than we actually have, so I'll omit this
// for now.
if (MADB_SSPS_ENABLED(Stmt) && ExecDirect != FALSE)
{
return MADB_EDPrepare(Stmt);
}
/* We had error preparing any of statements */
else if (GetMultiStatements(Stmt, ExecDirect))
{
return Stmt->Error.ReturnValue;
}
/* all statemtens successfully prepared */
UNLOCK_MARIADB(Stmt->Connection);
return SQL_SUCCESS;
}
UNLOCK_MARIADB(Stmt->Connection);
if (!MADB_ValidateStmt(&Stmt->Query))
{
MADB_SetError(&Stmt->Error, MADB_ERR_HY000, "SQL command SET NAMES is not allowed", 0);
return Stmt->Error.ReturnValue;
}
/* Transform WHERE CURRENT OF [cursorname]:
Append WHERE with Parameter Markers
In StmtExecute we will call SQLSetPos with update or delete:
*/
if ((CursorName = MADB_ParseCursorName(&Stmt->Query, &WhereOffset)))
{
MADB_DynString StmtStr;
char *TableName;
/* Make sure we have a delete clause, update clause is not yet supported in the positioned command.
MADB_QUERY_DELETE is defined in the enum to have the same value as SQL_DELETE.
*/
if (Stmt->Query.QueryType == MADB_QUERY_DELETE)
{
Stmt->PositionedCommand= 1;
}
else if (Stmt->Query.QueryType == MADB_QUERY_UPDATE)
{
// TODO(PLAT-5080): Support positioned updates.
MADB_SetError(&Stmt->Error, MADB_ERR_HYC00, "UPDATE clause is not supported for a positioned command", 0);
return Stmt->Error.ReturnValue;
}
else
{
MADB_SetError(&Stmt->Error, MADB_ERR_42000, "Invalid SQL Syntax: DELETE is expected for a positioned command", 0);
return Stmt->Error.ReturnValue;
}
if (!(Stmt->PositionedCursor= MADB_FindCursor(Stmt, CursorName)))
return Stmt->Error.ReturnValue;
TableName= MADB_GetTableName(Stmt->PositionedCursor);
MADB_InitDynamicString(&StmtStr, "", 8192, 1024);
MADB_DynstrAppendMem(&StmtStr, Stmt->Query.RefinedText, WhereOffset);
MADB_DynStrGetWhere(Stmt->PositionedCursor, &StmtStr, TableName, TRUE);
// The new query is constructed, delete the previous one and re-calculate the parameter positions.
if (MADB_SSPS_DISABLED(Stmt))
{
MADB_DeleteQuery(&Stmt->Query);
Stmt->Query.allocated = Stmt->Query.RefinedText = strndup(StmtStr.str, StmtStr.length);
Stmt->Query.RefinedLength = StmtStr.length;
MADB_ParseQuery(&Stmt->Query, FALSE);
} else
{
MADB_RESET(STMT_STRING(Stmt), StmtStr.str);
/* Constructed query we've copied for execution has parameters */
Stmt->Query.HasParameters= 1;
}
MADB_DynstrFree(&StmtStr);
}
if (Stmt->Options.MaxRows && Stmt->Query.QueryType == MADB_QUERY_SELECT)
{
unsigned long tmpLen = strlen(Stmt->Query.RefinedText) + 60;
char *tmp = MADB_CALLOC(tmpLen);
unsigned int updateForOffset;
if (MADB_CompareToken(&Stmt->Query, Stmt->Query.Tokens.elements-1, "UPDATE", 6, NULL) &&
MADB_CompareToken(&Stmt->Query, Stmt->Query.Tokens.elements-2, "FOR", 3, &updateForOffset))
{
_snprintf(tmp, tmpLen, "SELECT * FROM (%.*s) LIMIT %zd FOR UPDATE", updateForOffset, Stmt->Query.RefinedText, Stmt->Options.MaxRows);
} else
{
_snprintf(tmp, tmpLen, "SELECT * FROM (%s) LIMIT %zd", Stmt->Query.RefinedText, Stmt->Options.MaxRows);
}
MADB_DeleteQuery(&Stmt->Query);
Stmt->Query.RefinedText = tmp;
Stmt->Query.RefinedLength = strlen(Stmt->Query.RefinedText);
Stmt->Query.allocated = Stmt->Query.RefinedText;
MADB_ParseQuery(&Stmt->Query, FALSE);
}
if (!Stmt->Query.ReturnsResult && !Stmt->Query.HasParameters &&
/* If have multistatement query, and this is not allowed, we want to do normal prepare.
To give it last chance. And to return correct error otherwise */
! (QUERY_IS_MULTISTMT(Stmt->Query) && !Stmt->Query.BatchAllowed))
{
Stmt->State= MADB_SS_EMULATED;
return SQL_SUCCESS;
}
// If server-side prepared statements are disabled, simply store the query on the client and wait for SQLExecute.
if (MADB_SSPS_DISABLED(Stmt))
{
if ((Stmt->ParamCount = Stmt->Query.ParamPositions.elements))
{
if (Stmt->params)
{
MADB_FREE(Stmt->params);
}
Stmt->params= (MYSQL_BIND *)MADB_CALLOC(sizeof(MYSQL_BIND) * Stmt->ParamCount);
}
Stmt->State = MADB_SS_PREPARED;
return SQL_SUCCESS;
}
return MADB_RegularPrepare(Stmt);
}
/* }}} */
/* {{{ MADB_StmtParamData */
SQLRETURN MADB_StmtParamData(MADB_Stmt *Stmt, SQLPOINTER *ValuePtrPtr)
{
MADB_Desc *Desc;
MADB_DescRecord *Record;
int ParamCount;
int i;
SQLRETURN ret;
if (Stmt->DataExecutionType == MADB_DAE_NORMAL)
{
if (!Stmt->Apd || !(ParamCount= Stmt->ParamCount))
{
MADB_SetError(&Stmt->Error, MADB_ERR_HY010, NULL, 0);
return Stmt->Error.ReturnValue;
}
Desc= Stmt->Apd;
}
else
{
if (!Stmt->Ard || !(ParamCount= Stmt->DaeStmt->ParamCount))
{
MADB_SetError(&Stmt->Error, MADB_ERR_HY010, NULL, 0);
return Stmt->Error.ReturnValue;
}
Desc= Stmt->DaeStmt->Apd;
}
/* If we have last DAE param(Stmt->PutParam), we are starting from the next one. Otherwise from first */
for (i= Stmt->PutParam > -1 ? Stmt->PutParam + 1 : 0; i < ParamCount; i++)
{
if ((Record= MADB_DescGetInternalRecord(Desc, i, MADB_DESC_READ)))
{
if (Record->OctetLengthPtr)
{
/* Stmt->DaeRowNumber is 1 based */
SQLLEN *OctetLength = (SQLLEN *)GetBindOffset(Desc, Record, Record->OctetLengthPtr, Stmt->DaeRowNumber > 1 ? Stmt->DaeRowNumber - 1 : 0, sizeof(SQLLEN));
if (PARAM_IS_DAE(OctetLength))
{
Stmt->PutDataRec= Record;
*ValuePtrPtr = GetBindOffset(Desc, Record, Record->DataPtr, Stmt->DaeRowNumber > 1 ? Stmt->DaeRowNumber - 1 : 0, Record->OctetLength);
Stmt->PutParam= i;
Stmt->Status= SQL_NEED_DATA;
return SQL_NEED_DATA;
}
}
}
}
/* reset status, otherwise SQLSetPos and SQLExecute will fail */
MARK_DAE_DONE(Stmt);
if (Stmt->DataExecutionType == MADB_DAE_ADD || Stmt->DataExecutionType == MADB_DAE_UPDATE)
{
MARK_DAE_DONE(Stmt->DaeStmt);
}
switch (Stmt->DataExecutionType) {
case MADB_DAE_NORMAL:
ret= Stmt->Methods->Execute(Stmt, FALSE);
RESET_DAE_STATUS(Stmt);
break;
case MADB_DAE_UPDATE:
ret= Stmt->Methods->SetPos(Stmt, Stmt->DaeRowNumber, SQL_UPDATE, SQL_LOCK_NO_CHANGE, 1);
RESET_DAE_STATUS(Stmt);
break;
case MADB_DAE_ADD:
ret= Stmt->DaeStmt->Methods->Execute(Stmt->DaeStmt, FALSE);
MADB_CopyError(&Stmt->Error, &Stmt->DaeStmt->Error);
RESET_DAE_STATUS(Stmt->DaeStmt);
break;
default:
ret= SQL_ERROR;
}
/* Interesting should we reset if execution failed? */
// Clear the Ipd record data that was used to construct the query in the CSPS.
if (MADB_SSPS_DISABLED(Stmt))
{
MADB_CspsFreeDAE(Stmt);
}
return ret;
}
/* }}} */
/* {{{ MADB_StmtPutData */
SQLRETURN MADB_StmtPutData(MADB_Stmt *Stmt, SQLPOINTER DataPtr, SQLLEN StrLen_or_Ind)
{
MADB_DescRecord *Record;
MADB_Stmt *MyStmt= Stmt;
SQLPOINTER ConvertedDataPtr= NULL;
SQLULEN Length= 0;
MADB_CLEAR_ERROR(&Stmt->Error);
if (DataPtr != NULL && StrLen_or_Ind < 0 && StrLen_or_Ind != SQL_NTS && StrLen_or_Ind != SQL_NULL_DATA)
{
MADB_SetError(&Stmt->Error, MADB_ERR_HY090, NULL, 0);
return Stmt->Error.ReturnValue;
}
if (Stmt->DataExecutionType != MADB_DAE_NORMAL)
{
MyStmt= Stmt->DaeStmt;
}
Record= MADB_DescGetInternalRecord(MyStmt->Apd, Stmt->PutParam, MADB_DESC_READ);
assert(Record);
if (StrLen_or_Ind == SQL_NULL_DATA)
{
// Check if we've already sent any data.
// For the csps we tell that by checking the InternalLength which is set only in this function.
if (MyStmt->stmt->params[Stmt->PutParam].long_data_used || Record->InternalLength > 0)
{
MADB_SetError(&Stmt->Error, MADB_ERR_HY020, "Concatenation of a null value is forbidden", 0);
return Stmt->Error.ReturnValue;
}
Record->Type= SQL_TYPE_NULL;
return SQL_SUCCESS;
}
/* This normally should be enforced by DM */
if (DataPtr == NULL && StrLen_or_Ind != 0)
{
MADB_SetError(&Stmt->Error, MADB_ERR_HY009, NULL, 0);
return Stmt->Error.ReturnValue;
}
/*
if (StrLen_or_Ind == SQL_NTS)
{
if (Record->ConciseType == SQL_C_WCHAR)
StrLen_or_Ind= wcslen((SQLWCHAR *)DataPtr);
else
StrLen_or_Ind= strlen((char *)DataPtr);
}
*/
if (Record->ConciseType == SQL_C_WCHAR)
{
/* Conn cs */
ConvertedDataPtr= MADB_ConvertFromWChar((SQLWCHAR *)DataPtr, (SQLINTEGER)(StrLen_or_Ind/sizeof(SQLWCHAR)), &Length, &Stmt->Connection->Charset, NULL);
if ((ConvertedDataPtr == NULL || Length == 0) && StrLen_or_Ind > 0)
{
MADB_SetError(&Stmt->Error, MADB_ERR_HY001, NULL, 0);
return Stmt->Error.ReturnValue;
}
}
else
{
if (StrLen_or_Ind == SQL_NTS)
{
Length= strlen((char *)DataPtr);
}
else
{
Length= StrLen_or_Ind;
}
}
// For client-side prepared statements we need to store the data within the driver before we're ready to execute.
// Making a deep copy of the data will probably be a bad news for the client memory (who would use SQLPutData if not
// for the long chars or blobs?); but seems like we don't have another option:
// 1) We cannot store it in the bound data buffer because it's not guaranteed that it fits all the data and it could
// easily be a dummy pointer in the DAE case. Furthermore, who would use SQLPutData if they can fully fit the data
// into their application buffers and just bind the parameters?
// 2) Clients can also call SQLPutData as many times as they need, and we'll have to concat all the data.
// For the binary protocol the codepath below is executed, where mysql_stmt_send_long_data sends a
// COM_STMT_SEND_LONG_DATA packet - a so-called "Long Data" feature which is not supported by SingleStore,
// so the client-side case probably won't make things worse.
//
// Another note: seems like for the SQLExecute+SQLPutData scenario the driver demonstrates a strange behavior:
// For SQLSetPos(SQL_ADD and SQL_DELETE operations) it recognizes the fact that paramset size may be greater than 1
// and return the proper data buffers.
// On the other hand, for generic SQLExecute API, the relevant fields are not used, so de-facto the driver assumes
// the paramset size is always 1. Besides that, it seems like the logic to send the long data multiple times for
// multiple parameters in the parameter array is simply missing (this is the case also for SQLSetPos).
// I don't see any information in the ODBC docs forbidding the use of big paramsets for SQLPutData, so it's probably
// a bug or missing intentionally.
// The current behavior for the client-side prepared statements will also work only for the paramset of size 1.
// TODO (PLAT-4993): support SQLPutData+SQLParamData for bigger paramsets.
// This can probably be done by iterating over the paramset in the SQLParamData and request the call to SQLPutData
// for every row in the paramset.
if (MADB_SSPS_DISABLED(Stmt))
{
// Currently client-side prepared statements support SQLPutData+SQLParamData only for paramsets of size 1.
if (MyStmt->Apd->Header.ArraySize > 1)
{
return MADB_SetError(&Stmt->Error, MADB_ERR_HY000, "SQLPutData for paramsets of size > 1 is not supported in the text protocol mode", 0);
}
// It's much more convenient to modify the IpdRecord since its DataPtr field is unused in ODBC.
// Messing around with Apd would be too dangerous - we'll have to keep track of the OctetLength for each parameter
// that is inserted via SQLPutData and any other relevant metadata.
MADB_DescRecord *IpdRecord= MADB_DescGetInternalRecord(MyStmt->Ipd, Stmt->PutParam, MADB_DESC_WRITE);
// SQLPutData may be called multiple times for a single parameter only if it's a binary or char parameter.
// Otherwise, the call should fail.
my_bool isStringType = FALSE;
switch (Record->ConciseType)
{
case SQL_C_CHAR:
case SQL_VARCHAR:
case SQL_LONGVARCHAR:
case SQL_C_WCHAR:
case SQL_WVARCHAR:
case SQL_WLONGVARCHAR:
case SQL_C_BINARY:
case SQL_VARBINARY:
case SQL_LONGVARBINARY:
isStringType = TRUE;
break;
default:
isStringType = FALSE;
}
SQLPOINTER dataToAppend = (ConvertedDataPtr ? ConvertedDataPtr : DataPtr);
// The clients don't have access to the InternalLength via descriptor API and this function is the only place
// where we update it. Therefore it's safe to allocate the memory based on this value as long as we support only
// paramsets of size 1. This needs to be updated after we support bigger paramsets.
if (!IpdRecord->InternalLength)
{
// It's the first time we get the call to SQLPutData for this parameter.
// Allocate the memory for this chunk of data. Add a null terminator if it's a string type.
SQLPOINTER dataBuffer = MADB_ALLOC(Length + isStringType);
if (!dataBuffer)
{