File: firebird_driver.c

package info (click to toggle)
php8.4 8.4.11-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 208,108 kB
  • sloc: ansic: 1,060,628; php: 35,345; sh: 11,866; cpp: 7,201; pascal: 4,913; javascript: 3,091; asm: 2,810; yacc: 2,411; makefile: 689; xml: 446; python: 301; awk: 148
file content (1455 lines) | stat: -rw-r--r-- 39,407 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
/*
  +----------------------------------------------------------------------+
  | Copyright (c) The PHP Group                                          |
  +----------------------------------------------------------------------+
  | This source file is subject to version 3.01 of the PHP license,      |
  | that is bundled with this package in the file LICENSE, and is        |
  | available through the world-wide-web at the following url:           |
  | https://www.php.net/license/3_01.txt                                 |
  | If you did not receive a copy of the PHP license and are unable to   |
  | obtain it through the world-wide-web, please send a note to          |
  | license@php.net so we can mail you a copy immediately.               |
  +----------------------------------------------------------------------+
  | Author: Ard Biesheuvel <abies@php.net>                               |
  +----------------------------------------------------------------------+
*/

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#ifndef _GNU_SOURCE
# define _GNU_SOURCE
#endif

#include "php.h"
#include "zend_exceptions.h"
#include "php_ini.h"
#include "ext/standard/info.h"
#include "ext/pdo/php_pdo.h"
#include "ext/pdo/php_pdo_driver.h"
#include "php_pdo_firebird.h"
#include "php_pdo_firebird_int.h"
#include "pdo_firebird_utils.h"

static int php_firebird_alloc_prepare_stmt(pdo_dbh_t*, const zend_string*, XSQLDA*, isc_stmt_handle*,
	HashTable*);
static bool php_firebird_rollback_transaction(pdo_dbh_t *dbh);

const char CHR_LETTER = 1;
const char CHR_DIGIT = 2;
const char CHR_IDENT = 4;
const char CHR_QUOTE = 8;
const char CHR_WHITE = 16;
const char CHR_HEX = 32;
const char CHR_INTRODUCER = 64;

static const char classes_array[] = {
	/* 000     */ 0,
	/* 001     */ 0,
	/* 002     */ 0,
	/* 003     */ 0,
	/* 004     */ 0,
	/* 005     */ 0,
	/* 006     */ 0,
	/* 007     */ 0,
	/* 008     */ 0,
	/* 009     */ 16, /* CHR_WHITE */
	/* 010     */ 16, /* CHR_WHITE */
	/* 011     */ 0,
	/* 012     */ 0,
	/* 013     */ 16, /* CHR_WHITE */
	/* 014     */ 0,
	/* 015     */ 0,
	/* 016     */ 0,
	/* 017     */ 0,
	/* 018     */ 0,
	/* 019     */ 0,
	/* 020     */ 0,
	/* 021     */ 0,
	/* 022     */ 0,
	/* 023     */ 0,
	/* 024     */ 0,
	/* 025     */ 0,
	/* 026     */ 0,
	/* 027     */ 0,
	/* 028     */ 0,
	/* 029     */ 0,
	/* 030     */ 0,
	/* 031     */ 0,
	/* 032     */ 16, /* CHR_WHITE */
	/* 033  !  */ 0,
	/* 034  "  */ 8, /* CHR_QUOTE */
	/* 035  #  */ 0,
	/* 036  $  */ 4, /* CHR_IDENT */
	/* 037  %  */ 0,
	/* 038  &  */ 0,
	/* 039  '  */ 8, /* CHR_QUOTE */
	/* 040  (  */ 0,
	/* 041  )  */ 0,
	/* 042  *  */ 0,
	/* 043  +  */ 0,
	/* 044  ,  */ 0,
	/* 045  -  */ 0,
	/* 046  .  */ 0,
	/* 047  /  */ 0,
	/* 048  0  */ 38, /* CHR_DIGIT | CHR_IDENT | CHR_HEX */
	/* 049  1  */ 38, /* CHR_DIGIT | CHR_IDENT | CHR_HEX */
	/* 050  2  */ 38, /* CHR_DIGIT | CHR_IDENT | CHR_HEX */
	/* 051  3  */ 38, /* CHR_DIGIT | CHR_IDENT | CHR_HEX */
	/* 052  4  */ 38, /* CHR_DIGIT | CHR_IDENT | CHR_HEX */
	/* 053  5  */ 38, /* CHR_DIGIT | CHR_IDENT | CHR_HEX */
	/* 054  6  */ 38, /* CHR_DIGIT | CHR_IDENT | CHR_HEX */
	/* 055  7  */ 38, /* CHR_DIGIT | CHR_IDENT | CHR_HEX */
	/* 056  8  */ 38, /* CHR_DIGIT | CHR_IDENT | CHR_HEX */
	/* 057  9  */ 38, /* CHR_DIGIT | CHR_IDENT | CHR_HEX */
	/* 058  :  */ 0,
	/* 059  ;  */ 0,
	/* 060  <  */ 0,
	/* 061  =  */ 0,
	/* 062  >  */ 0,
	/* 063  ?  */ 0,
	/* 064  @  */ 0,
	/* 065  A  */ 37, /* CHR_LETTER | CHR_IDENT | CHR_HEX */
	/* 066  B  */ 37, /* CHR_LETTER | CHR_IDENT | CHR_HEX */
	/* 067  C  */ 37, /* CHR_LETTER | CHR_IDENT | CHR_HEX */
	/* 068  D  */ 37, /* CHR_LETTER | CHR_IDENT | CHR_HEX */
	/* 069  E  */ 37, /* CHR_LETTER | CHR_IDENT | CHR_HEX */
	/* 070  F  */ 37, /* CHR_LETTER | CHR_IDENT | CHR_HEX */
	/* 071  G  */ 5, /* CHR_LETTER | CHR_IDENT */
	/* 072  H  */ 5, /* CHR_LETTER | CHR_IDENT */
	/* 073  I  */ 5, /* CHR_LETTER | CHR_IDENT */
	/* 074  J  */ 5, /* CHR_LETTER | CHR_IDENT */
	/* 075  K  */ 5, /* CHR_LETTER | CHR_IDENT */
	/* 076  L  */ 5, /* CHR_LETTER | CHR_IDENT */
	/* 077  M  */ 5, /* CHR_LETTER | CHR_IDENT */
	/* 078  N  */ 5, /* CHR_LETTER | CHR_IDENT */
	/* 079  O  */ 5, /* CHR_LETTER | CHR_IDENT */
	/* 080  P  */ 5, /* CHR_LETTER | CHR_IDENT */
	/* 081  Q  */ 5, /* CHR_LETTER | CHR_IDENT */
	/* 082  R  */ 5, /* CHR_LETTER | CHR_IDENT */
	/* 083  S  */ 5, /* CHR_LETTER | CHR_IDENT */
	/* 084  T  */ 5, /* CHR_LETTER | CHR_IDENT */
	/* 085  U  */ 5, /* CHR_LETTER | CHR_IDENT */
	/* 086  V  */ 5, /* CHR_LETTER | CHR_IDENT */
	/* 087  W  */ 5, /* CHR_LETTER | CHR_IDENT */
	/* 088  X  */ 5, /* CHR_LETTER | CHR_IDENT */
	/* 089  Y  */ 5, /* CHR_LETTER | CHR_IDENT */
	/* 090  Z  */ 5, /* CHR_LETTER | CHR_IDENT */
	/* 091  [  */ 0,
	/* 092  \  */ 0,
	/* 093  ]  */ 0,
	/* 094  ^  */ 0,
	/* 095  _  */ 68, /* CHR_IDENT | CHR_INTRODUCER */
	/* 096  `  */ 0,
	/* 097  a  */ 37, /* CHR_LETTER | CHR_IDENT | CHR_HEX */
	/* 098  b  */ 37, /* CHR_LETTER | CHR_IDENT | CHR_HEX */
	/* 099  c  */ 37, /* CHR_LETTER | CHR_IDENT | CHR_HEX */
	/* 100  d  */ 37, /* CHR_LETTER | CHR_IDENT | CHR_HEX */
	/* 101  e  */ 37, /* CHR_LETTER | CHR_IDENT | CHR_HEX */
	/* 102  f  */ 37, /* CHR_LETTER | CHR_IDENT | CHR_HEX */
	/* 103  g  */ 5, /* CHR_LETTER | CHR_IDENT */
	/* 104  h  */ 5, /* CHR_LETTER | CHR_IDENT */
	/* 105  i  */ 5, /* CHR_LETTER | CHR_IDENT */
	/* 106  j  */ 5, /* CHR_LETTER | CHR_IDENT */
	/* 107  k  */ 5, /* CHR_LETTER | CHR_IDENT */
	/* 108  l  */ 5, /* CHR_LETTER | CHR_IDENT */
	/* 109  m  */ 5, /* CHR_LETTER | CHR_IDENT */
	/* 110  n  */ 5, /* CHR_LETTER | CHR_IDENT */
	/* 111  o  */ 5, /* CHR_LETTER | CHR_IDENT */
	/* 112  p  */ 5, /* CHR_LETTER | CHR_IDENT */
	/* 113  q  */ 5, /* CHR_LETTER | CHR_IDENT */
	/* 114  r  */ 5, /* CHR_LETTER | CHR_IDENT */
	/* 115  s  */ 5, /* CHR_LETTER | CHR_IDENT */
	/* 116  t  */ 5, /* CHR_LETTER | CHR_IDENT */
	/* 117  u  */ 5, /* CHR_LETTER | CHR_IDENT */
	/* 118  v  */ 5, /* CHR_LETTER | CHR_IDENT */
	/* 119  w  */ 5, /* CHR_LETTER | CHR_IDENT */
	/* 120  x  */ 5, /* CHR_LETTER | CHR_IDENT */
	/* 121  y  */ 5, /* CHR_LETTER | CHR_IDENT */
	/* 122  z  */ 5, /* CHR_LETTER | CHR_IDENT */
	/* 123  {  */ 5, /* CHR_LETTER | CHR_IDENT */
	/* 124  |  */ 0,
	/* 125  }  */ 5, /* CHR_LETTER | CHR_IDENT */
	/* 126  ~  */ 0,
	/* 127     */ 0
};

static inline char php_firebird_classes(char idx)
{
	unsigned char uidx = (unsigned char) idx;
	if (uidx > 127) return 0;
	return classes_array[uidx];
}

typedef enum {
	ttNone,
	ttWhite,
	ttComment,
	ttBrokenComment,
	ttString,
	ttParamMark,
	ttIdent,
	ttOther
} FbTokenType;

static FbTokenType php_firebird_get_token(const char** begin, const char* end)
{
	FbTokenType ret = ttNone;
	const char* p = *begin;

	char c = *p++;
	switch (c)
	{
	case ':':
	case '?':
		ret = ttParamMark;
		break;

	case '\'':
	case '"':
		while (p < end)
		{
			if (*p++ == c)
			{
				ret = ttString;
				break;
			}
		}
		break;

	case '/':
		if (p < end && *p == '*')
		{
			ret = ttBrokenComment;
			p++;
			while (p < end)
			{
				if (*p++ == '*' && p < end && *p == '/')
				{
					p++;
					ret = ttComment;
					break;
				}
			}
		}
		else {
			ret = ttOther;
		}
		break;

	case '-':
		if (p < end && *p == '-')
		{
			while (++p < end)
			{
				if (*p == '\r')
				{
					p++;
					if (p < end && *p == '\n')
						p++;
					break;
				}
				else if (*p == '\n')
					break;
			}

			ret = ttComment;
		}
		else
			ret = ttOther;
		break;

	default:
		if (php_firebird_classes(c) & CHR_DIGIT)
		{
			while (p < end && (php_firebird_classes(*p) & CHR_DIGIT))
				p++;
			ret = ttOther;
		}
		else if (php_firebird_classes(c) & CHR_IDENT)
		{
			while (p < end && (php_firebird_classes(*p) & CHR_IDENT))
				p++;
			ret = ttIdent;
		}
		else if (php_firebird_classes(c) & CHR_WHITE)
		{
			while (p < end && (php_firebird_classes(*p) & CHR_WHITE))
				p++;
			ret = ttWhite;
		}
		else
		{
			while (p < end && !(php_firebird_classes(*p) & (CHR_DIGIT | CHR_IDENT | CHR_WHITE)) &&
				(*p != '/') && (*p != '-') && (*p != ':') && (*p != '?') &&
				(*p != '\'') && (*p != '"'))
			{
				p++;
			}
			ret = ttOther;
		}
	}

	*begin = p;
	return ret;
}

static int php_firebird_preprocess(const zend_string* sql, char* sql_out, HashTable* named_params)
{
	bool passAsIs = 1, execBlock = 0;
	zend_long pindex = -1;
	char pname[254], ident[253], ident2[253];
	unsigned int l;
	const char* p = ZSTR_VAL(sql), * end = ZSTR_VAL(sql) + ZSTR_LEN(sql);
	const char* start = p;
	FbTokenType tok = php_firebird_get_token(&p, end);

	const char* i = start;
	while (p < end && (tok == ttComment || tok == ttWhite))
	{
		i = p;
		tok = php_firebird_get_token(&p, end);
	}

	if (p >= end || tok != ttIdent)
	{
		/* Execute statement preprocess SQL error */
		/* Statement expected */
		return 0;
	}
	/* skip leading comments ?? */
	start = i;
	l = p - i;
	/* check the length of the identifier */
	/* in Firebird 4.0 it is 63 characters, in previous versions 31 bytes */
	if (l > 252) {
		return 0;
	}
	strncpy(ident, i, l);
	ident[l] = '\0';
	if (!strcasecmp(ident, "EXECUTE"))
	{
		/* For EXECUTE PROCEDURE and EXECUTE BLOCK statements, named parameters must be processed. */
		/* However, in EXECUTE BLOCK this is done in a special way. */
		const char* i2 = p;
		tok = php_firebird_get_token(&p, end);
		while (p < end && (tok == ttComment || tok == ttWhite))
		{
			i2 = p;
			tok = php_firebird_get_token(&p, end);
		}
		if (p >= end || tok != ttIdent)
		{
			/* Execute statement preprocess SQL error */
			/* Statement expected */
			return 0;
		}
		l = p - i2;
		/* check the length of the identifier */
		/* in Firebird 4.0 it is 63 characters, in previous versions 31 bytes */
		if (l > 252) {
			return 0;
		}
		strncpy(ident2, i2, l);
		ident2[l] = '\0';
		execBlock = !strcasecmp(ident2, "BLOCK");
		passAsIs = 0;
	}
	else
	{
		/* Named parameters must be processed in the INSERT, UPDATE, DELETE, MERGE statements. */
		/* If CTEs are present in the query, they begin with the WITH keyword. */
		passAsIs = strcasecmp(ident, "INSERT") && strcasecmp(ident, "UPDATE") &&
			strcasecmp(ident, "DELETE") && strcasecmp(ident, "MERGE") &&
			strcasecmp(ident, "SELECT") && strcasecmp(ident, "WITH");
	}

	if (passAsIs)
	{
		strcpy(sql_out, ZSTR_VAL(sql));
		return 1;
	}

	strncat(sql_out, start, p - start);

	while (p < end)
	{
		start = p;
		tok = php_firebird_get_token(&p, end);
		switch (tok)
		{
		case ttParamMark:
			tok = php_firebird_get_token(&p, end);
			if (tok == ttIdent /*|| tok == ttString*/)
			{
				++pindex;
				l = p - start;
				/* check the length of the identifier */
				/* in Firebird 4.0 it is 63 characters, in previous versions 31 bytes */
				/* + symbol ":" */
				if (l > 253) {
					return 0;
				}
				strncpy(pname, start, l);
				pname[l] = '\0';

				if (named_params) {
					zval tmp;
					ZVAL_LONG(&tmp, pindex);
					zend_hash_str_update(named_params, pname, l, &tmp);
				}

				strcat(sql_out, "?");
			}
			else
			{
				if (strncmp(start, "?", 1)) {
					/* Execute statement preprocess SQL error */
					/* Parameter name expected */
					return 0;
				}
				++pindex;
				strncat(sql_out, start, p - start);
			}
			break;

		case ttIdent:
			if (execBlock)
			{
				/* In the EXECUTE BLOCK statement, processing must be */
				/* carried out up to the keyword AS. */
				l = p - start;
				/* check the length of the identifier */
				/* in Firebird 4.0 it is 63 characters, in previous versions 31 bytes */
				if (l > 252) {
					return 0;
				}
				strncpy(ident, start, l);
				ident[l] = '\0';
				if (!strcasecmp(ident, "AS"))
				{
					strncat(sql_out, start, end - start);
					return 1;
				}
			}
			/* TODO Check this is correct? */
			ZEND_FALLTHROUGH;

		case ttWhite:
		case ttComment:
		case ttString:
		case ttOther:
			strncat(sql_out, start, p - start);
			break;

		case ttBrokenComment:
		{
			/* Execute statement preprocess SQL error */
			/* Unclosed comment found near ''@1'' */
			return 0;
		}
		break;


		case ttNone:
			/* Execute statement preprocess SQL error */
			return 0;
			break;
		}
	}
	return 1;
}

#if FB_API_VER >= 40
/* set coercing a data type */
static void set_coercing_output_data_types(XSQLDA* sqlda)
{
	/* Data types introduced in Firebird 4.0 are difficult to process using the Firebird Legacy API. */
	/* These data types include DECFLOAT(16), DECFLOAT(34), INT128 (NUMERIC/DECIMAL(38, x)). */
	/* In any case, at this data types can only be mapped to strings. */
	/* This function allows you to ensure minimal performance of queries if they contain columns of the above types. */
	unsigned int i;
	short dtype;
	short nullable;
	XSQLVAR* var;
	unsigned fb_client_version = fb_get_client_version();
	unsigned fb_client_major_version = (fb_client_version >> 8) & 0xFF;
	for (i=0, var = sqlda->sqlvar; i < sqlda->sqld; i++, var++) {
		dtype = (var->sqltype & ~1); /* drop flag bit  */
		nullable = (var->sqltype & 1);
		switch(dtype) {
			case SQL_INT128:
				var->sqltype = SQL_VARYING + nullable;
				var->sqllen = 46;
				var->sqlscale = 0;
				break;

			case SQL_DEC16:
				var->sqltype = SQL_VARYING + nullable;
				var->sqllen = 24;
				break;

			case SQL_DEC34:
				var->sqltype = SQL_VARYING + nullable;
				var->sqllen = 43;
				break;

			case SQL_TIMESTAMP_TZ:
			    if (fb_client_major_version < 4) {
					/* If the client version is below 4.0, then it is impossible to handle time zones natively, */
					/* so we convert these types to a string. */
					var->sqltype = SQL_VARYING + nullable;
					var->sqllen = 58;
				}
				break;

			case SQL_TIME_TZ:
				if (fb_client_major_version < 4) {
					/* If the client version is below 4.0, then it is impossible to handle time zones natively, */
					/* so we convert these types to a string. */
					var->sqltype = SQL_VARYING + nullable;
					var->sqllen = 46;
				}
				break;

			default:
				break;
		}
	}
}
#endif

/* map driver specific error message to PDO error */
void php_firebird_set_error(pdo_dbh_t *dbh, pdo_stmt_t *stmt, const char *state, const size_t state_len,
	const char *msg, const size_t msg_len) /* {{{ */
{
	pdo_error_type *const error_code = stmt ? &stmt->error_code : &dbh->error_code;
	pdo_firebird_db_handle *H = (pdo_firebird_db_handle *)dbh->driver_data;
	pdo_firebird_error_info *einfo = &H->einfo;
	int sqlcode = -999;

	if (einfo->errmsg) {
		pefree(einfo->errmsg, dbh->is_persistent);
		einfo->errmsg = NULL;
		einfo->errmsg_length = 0;
	}

	if (H->isc_status && (H->isc_status[0] == 1 && H->isc_status[1] > 0)) {
		char buf[512];
		size_t buf_size = sizeof(buf), read_len = 0;
		ssize_t tmp_len;
		const ISC_STATUS *s = H->isc_status;
		sqlcode = isc_sqlcode(s);

		while ((buf_size > (read_len + 1)) && (tmp_len = fb_interpret(&buf[read_len], (buf_size - read_len - 1), &s)) && tmp_len > 0) {
			read_len += tmp_len;
			buf[read_len++] = ' ';
		}

		/* remove last space */
		if (read_len) {
			buf[read_len--] = '\0';
		}

		einfo->errmsg_length = read_len;
		einfo->errmsg = pestrndup(buf, read_len, dbh->is_persistent);

		char sqlstate[sizeof(pdo_error_type)];
		fb_sqlstate(sqlstate, H->isc_status);
		if (sqlstate != NULL && strlen(sqlstate) < sizeof(pdo_error_type)) {
			strcpy(*error_code, sqlstate);
			goto end;
		}
	} else if (msg && msg_len) {
		einfo->errmsg_length = msg_len;
		einfo->errmsg = pestrndup(msg, einfo->errmsg_length, dbh->is_persistent);
	}

	if (state && state_len && state_len < sizeof(pdo_error_type)) {
		memcpy(*error_code, state, state_len + 1);
	} else {
		memcpy(*error_code, "HY000", sizeof("HY000"));
	}

end:
	einfo->sqlcode = sqlcode;
	if (!dbh->methods) {
		pdo_throw_exception(0, einfo->errmsg, error_code);
	}
}
/* }}} */

/* called by PDO to close a db handle */
static void firebird_handle_closer(pdo_dbh_t *dbh) /* {{{ */
{
	pdo_firebird_db_handle *H = (pdo_firebird_db_handle *)dbh->driver_data;

	if (H->tr) {
		if (dbh->auto_commit) {
			php_firebird_commit_transaction(dbh, /* retain */ false);
		} else {
			php_firebird_rollback_transaction(dbh);
		}
	}
	H->in_manually_txn = 0;

	/* isc_detach_database returns 0 on success, 1 on failure. */
	if (H->db && isc_detach_database(H->isc_status, &H->db)) {
		php_firebird_error(dbh);
	}

	if (H->date_format) {
		pefree(H->date_format, dbh->is_persistent);
	}
	if (H->time_format) {
		pefree(H->time_format, dbh->is_persistent);
	}
	if (H->timestamp_format) {
		pefree(H->timestamp_format, dbh->is_persistent);
	}

	if (H->einfo.errmsg) {
		pefree(H->einfo.errmsg, dbh->is_persistent);
		H->einfo.errmsg = NULL;
	}

	pefree(H, dbh->is_persistent);
}
/* }}} */

/* called by PDO to prepare an SQL query */
static bool firebird_handle_preparer(pdo_dbh_t *dbh, zend_string *sql, /* {{{ */
	pdo_stmt_t *stmt, zval *driver_options)
{
	pdo_firebird_db_handle *H = (pdo_firebird_db_handle *)dbh->driver_data;
	pdo_firebird_stmt *S = NULL;
	HashTable *np;

	do {
		isc_stmt_handle s = PDO_FIREBIRD_HANDLE_INITIALIZER;
		XSQLDA num_sqlda;
		static char const info[] = { isc_info_sql_stmt_type };
		char result[8];

		num_sqlda.version = PDO_FB_SQLDA_VERSION;
		num_sqlda.sqln = 1;

		ALLOC_HASHTABLE(np);
		zend_hash_init(np, 8, NULL, NULL, 0);

		/* allocate and prepare statement */
		if (!php_firebird_alloc_prepare_stmt(dbh, sql, &num_sqlda, &s, np)) {
			break;
		}

		/* allocate a statement handle struct of the right size (struct out_sqlda is inlined) */
		S = ecalloc(1, sizeof(*S)-sizeof(XSQLDA) + XSQLDA_LENGTH(num_sqlda.sqld));
		S->H = H;
		S->stmt = s;
		S->out_sqlda.version = PDO_FB_SQLDA_VERSION;
		S->out_sqlda.sqln = stmt->column_count = num_sqlda.sqld;
		S->named_params = np;

		/* determine the statement type */
		if (isc_dsql_sql_info(H->isc_status, &s, sizeof(info), const_cast(info), sizeof(result),
				result)) {
			break;
		}
		S->statement_type = result[3];

		/* fill the output sqlda with information about the prepared query */
		if (isc_dsql_describe(H->isc_status, &s, PDO_FB_SQLDA_VERSION, &S->out_sqlda)) {
			php_firebird_error(dbh);
			break;
		}

#if FB_API_VER >= 40
		/* set coercing a data type */
		set_coercing_output_data_types(&S->out_sqlda);
#endif

		/* allocate the input descriptors */
		if (isc_dsql_describe_bind(H->isc_status, &s, PDO_FB_SQLDA_VERSION, &num_sqlda)) {
			break;
		}

		if (num_sqlda.sqld) {
			S->in_sqlda = ecalloc(1,XSQLDA_LENGTH(num_sqlda.sqld));
			S->in_sqlda->version = PDO_FB_SQLDA_VERSION;
			S->in_sqlda->sqln = num_sqlda.sqld;

			if (isc_dsql_describe_bind(H->isc_status, &s, PDO_FB_SQLDA_VERSION, S->in_sqlda)) {
				break;
			}

			/* make all parameters nullable */
			unsigned int i;
			XSQLVAR* var;
			for (i = 0, var = S->in_sqlda->sqlvar; i < S->in_sqlda->sqld; i++, var++) {
				/* The low bit of sqltype indicates that the parameter can take a NULL value */
				var->sqltype |= 1;
			}
		}

		stmt->driver_data = S;
		stmt->methods = &firebird_stmt_methods;
		stmt->supports_placeholders = PDO_PLACEHOLDER_POSITIONAL;

		return true;

	} while (0);

	php_firebird_error(dbh);

	zend_hash_destroy(np);
	FREE_HASHTABLE(np);

	if (S) {
		if (S->in_sqlda) {
			efree(S->in_sqlda);
		}
		efree(S);
	}

	return false;
}
/* }}} */

/* called by PDO to execute a statement that doesn't produce a result set */
static zend_long firebird_handle_doer(pdo_dbh_t *dbh, const zend_string *sql) /* {{{ */
{
	pdo_firebird_db_handle *H = (pdo_firebird_db_handle *)dbh->driver_data;
	isc_stmt_handle stmt = PDO_FIREBIRD_HANDLE_INITIALIZER;
	static char const info_count[] = { isc_info_sql_records };
	char result[64];
	int ret = 0;
	XSQLDA in_sqlda, out_sqlda;

	/* TODO no placeholders in exec() for now */
	in_sqlda.version = out_sqlda.version = PDO_FB_SQLDA_VERSION;
	in_sqlda.sqld = out_sqlda.sqld = 0;
	out_sqlda.sqln = 1;

	/* allocate and prepare statement */
	if (!php_firebird_alloc_prepare_stmt(dbh, sql, &out_sqlda, &stmt, 0)) {
		return -1;
	}

	/* execute the statement */
	if (isc_dsql_execute2(H->isc_status, &H->tr, &stmt, PDO_FB_SQLDA_VERSION, &in_sqlda, &out_sqlda)) {
		php_firebird_error(dbh);
		ret = -1;
		goto free_statement;
	}

	/* find out how many rows were affected */
	if (isc_dsql_sql_info(H->isc_status, &stmt, sizeof(info_count), const_cast(info_count),
			sizeof(result),	result)) {
		php_firebird_error(dbh);
		ret = -1;
		goto free_statement;
	}

	if (result[0] == isc_info_sql_records) {
		unsigned i = 3, result_size = isc_vax_integer(&result[1],2);

		if (result_size > sizeof(result)) {
			ret = -1;
			goto free_statement;
		}
		while (result[i] != isc_info_end && i < result_size) {
			short len = (short)isc_vax_integer(&result[i+1],2);
			/* bail out on bad len */
			if (len != 1 && len != 2 && len != 4) {
				ret = -1;
				goto free_statement;
			}
			if (result[i] != isc_info_req_select_count) {
				ret += isc_vax_integer(&result[i+3],len);
			}
			i += len+3;
		}
	}

	if (dbh->auto_commit && !H->in_manually_txn) {
		if (!php_firebird_commit_transaction(dbh, /* retain */ true)) {
			ret = -1;
		}
	}

free_statement:

	if (isc_dsql_free_statement(H->isc_status, &stmt, DSQL_drop)) {
		php_firebird_error(dbh);
	}

	return ret;
}
/* }}} */

/* called by the PDO SQL parser to add quotes to values that are copied into SQL */
static zend_string* firebird_handle_quoter(pdo_dbh_t *dbh, const zend_string *unquoted, enum pdo_param_type paramtype)
{
	size_t qcount = 0;
	char const *co, *l, *r;
	char *c;
	size_t quotedlen;
	zend_string *quoted_str;

	if (ZSTR_LEN(unquoted) == 0) {
		return ZSTR_INIT_LITERAL("''", 0);
	}

	/* Firebird only requires single quotes to be doubled if string lengths are used */
	/* count the number of ' characters */
	for (co = ZSTR_VAL(unquoted); (co = strchr(co,'\'')); qcount++, co++);

	if (UNEXPECTED(ZSTR_LEN(unquoted) + 2 > ZSTR_MAX_LEN - qcount)) {
		return NULL;
	}

	quotedlen = ZSTR_LEN(unquoted) + qcount + 2;
	quoted_str = zend_string_alloc(quotedlen, 0);
	c = ZSTR_VAL(quoted_str);
	*c++ = '\'';

	/* foreach (chunk that ends in a quote) */
	for (l = ZSTR_VAL(unquoted); (r = strchr(l,'\'')); l = r+1) {
		strncpy(c, l, r-l+1);
		c += (r-l+1);
		/* add the second quote */
		*c++ = '\'';
	}

	/* copy the remainder */
	strncpy(c, l, quotedlen-(c-ZSTR_VAL(quoted_str))-1);
	ZSTR_VAL(quoted_str)[quotedlen-1] = '\'';
	ZSTR_VAL(quoted_str)[quotedlen]   = '\0';

	return quoted_str;
}
/* }}} */

/* php_firebird_begin_transaction */
static bool php_firebird_begin_transaction(pdo_dbh_t *dbh, bool is_auto_commit_txn) /* {{{ */
{
	pdo_firebird_db_handle *H = (pdo_firebird_db_handle *)dbh->driver_data;

	/* isc_xxx are all 1 byte. */
	char tpb[4] = { isc_tpb_version3 };
	size_t tpb_size;

	/* access mode. writable or readonly */
	tpb[1] = H->is_writable_txn ? isc_tpb_write : isc_tpb_read;

	if (is_auto_commit_txn) {
		/*
		 * In autocommit mode, we need to always read the latest information, so we set `read committed`.
		 */
		tpb[2] = isc_tpb_read_committed;
		/* Ignore indeterminate data from other transactions. This option only required with `read committed`. */
		tpb[3] = isc_tpb_rec_version;
		tpb_size = 4;
	} else {
		switch (H->txn_isolation_level) {
			/*
			* firebird's `read committed` has the option to wait until other transactions
			* commit or rollback if there is indeterminate data.
			* Introducing too many configuration values at once can cause confusion, so
			* we don't support in PDO that feature yet.
			*/
			case PDO_FB_READ_COMMITTED:
				tpb[2] = isc_tpb_read_committed;
				/* Ignore indeterminate data from other transactions. This option only required with `read committed`. */
				tpb[3] = isc_tpb_rec_version;
				tpb_size = 4;
				break;

			case PDO_FB_SERIALIZABLE:
				tpb[2] = isc_tpb_consistency;
				tpb_size = 3;
				break;

			case PDO_FB_REPEATABLE_READ:
			default:
				tpb[2] = isc_tpb_concurrency;
				tpb_size = 3;
				break;
		}
	}

	if (isc_start_transaction(H->isc_status, &H->tr, 1, &H->db, tpb_size, tpb)) {
		php_firebird_error(dbh);
		return false;
	}
	return true;
}
/* }}} */

/* called by PDO to start a transaction */
static bool firebird_handle_manually_begin(pdo_dbh_t *dbh) /* {{{ */
{
	pdo_firebird_db_handle *H = (pdo_firebird_db_handle *)dbh->driver_data;

	/**
	 * If in autocommit mode and in transaction, we will need to close the transaction once.
	 */
	if (dbh->auto_commit && H->tr) {
		if (!php_firebird_commit_transaction(dbh, /* retain */ false)) {
			return false;
		}
	}

	if (!php_firebird_begin_transaction(dbh, /* auto commit mode */ false)) {
		return false;
	}
	H->in_manually_txn = 1;
	return true;
}
/* }}} */

/* php_firebird_commit_transaction */
bool php_firebird_commit_transaction(pdo_dbh_t *dbh, bool retain) /* {{{ */
{
	pdo_firebird_db_handle *H = (pdo_firebird_db_handle *)dbh->driver_data;

	/**
	 * `retaining` keeps the transaction open without closing it.
	 *
	 * firebird needs to always have a transaction open to emulate autocommit mode,
	 * and in autocommit mode it keeps the transaction open.
	 *
	 * Same as close and then begin again, but use retain to save overhead.
	 */
	if (retain) {
		if (isc_commit_retaining(H->isc_status, &H->tr)) {
			php_firebird_error(dbh);
			return false;
		}
	} else {
		if (isc_commit_transaction(H->isc_status, &H->tr)) {
			php_firebird_error(dbh);
			return false;
		}
	}
	return true;
}
/* }}} */

/* called by PDO to commit a transaction */
static bool firebird_handle_manually_commit(pdo_dbh_t *dbh) /* {{{ */
{
	pdo_firebird_db_handle *H = (pdo_firebird_db_handle *)dbh->driver_data;
	if (!php_firebird_commit_transaction(dbh, /*release*/ false)) {
		return false;
	}

	/**
	 * If in autocommit mode, begin the transaction again
	 * Reopen instead of retain because isolation level may change
	 */
	if (dbh->auto_commit) {
		if (!php_firebird_begin_transaction(dbh, /* auto commit mode */ true)) {
			return false;
		}
	}
	H->in_manually_txn = 0;
	return true;
}
/* }}} */

/* php_firebird_rollback_transaction */
static bool php_firebird_rollback_transaction(pdo_dbh_t *dbh) /* {{{ */
{
	pdo_firebird_db_handle *H = (pdo_firebird_db_handle *)dbh->driver_data;

	if (isc_rollback_transaction(H->isc_status, &H->tr)) {
		php_firebird_error(dbh);
		return false;
	}
	return true;
}
/* }}} */

/* called by PDO to rollback a transaction */
static bool firebird_handle_manually_rollback(pdo_dbh_t *dbh) /* {{{ */
{
	pdo_firebird_db_handle *H = (pdo_firebird_db_handle *)dbh->driver_data;

	if (!php_firebird_rollback_transaction(dbh)) {
		return false;
	}

	/**
	 * If in autocommit mode, begin the transaction again
	 * Reopen instead of retain because isolation level may change
	 */
	if (dbh->auto_commit) {
		if (!php_firebird_begin_transaction(dbh, /* auto commit mode */ true)) {
			return false;
		}
	}
	H->in_manually_txn = 0;
	return true;
}
/* }}} */

/* used by prepare and exec to allocate a statement handle and prepare the SQL */
static int php_firebird_alloc_prepare_stmt(pdo_dbh_t *dbh, const zend_string *sql,
	XSQLDA *out_sqlda, isc_stmt_handle *s, HashTable *named_params)
{
	pdo_firebird_db_handle *H = (pdo_firebird_db_handle *)dbh->driver_data;
	char *new_sql;

	/* allocate the statement */
	if (isc_dsql_allocate_statement(H->isc_status, &H->db, s)) {
		php_firebird_error(dbh);
		return 0;
	}

	/* in order to support named params, which Firebird itself doesn't,
	   we need to replace :foo by ?, and store the name we just replaced */
	new_sql = emalloc(ZSTR_LEN(sql)+1);
	new_sql[0] = '\0';
	if (!php_firebird_preprocess(sql, new_sql, named_params)) {
		php_firebird_error_with_info(dbh, "07000", strlen("07000"), NULL, 0);
		efree(new_sql);
		return 0;
	}

	/* prepare the statement */
	if (isc_dsql_prepare(H->isc_status, &H->tr, s, 0, new_sql, H->sql_dialect, out_sqlda)) {
		php_firebird_error(dbh);
		efree(new_sql);
		return 0;
	}

	efree(new_sql);
	return 1;
}

/* called by PDO to set a driver-specific dbh attribute */
static bool pdo_firebird_set_attribute(pdo_dbh_t *dbh, zend_long attr, zval *val) /* {{{ */
{
	pdo_firebird_db_handle *H = (pdo_firebird_db_handle *)dbh->driver_data;
	bool bval;
	zend_long lval;

	switch (attr) {
		case PDO_ATTR_AUTOCOMMIT:
			{
				if (!pdo_get_bool_param(&bval, val)) {
					return false;
				}

				if (H->in_manually_txn) {
					/* change auto commit mode with an open transaction is illegal, because
						we won't know what to do with it */
					pdo_raise_impl_error(dbh, NULL, "HY000", "Cannot change autocommit mode while a transaction is already open");
					return false;
				}

				/* ignore if the new value equals the old one */
				if (dbh->auto_commit ^ bval) {
					if (bval) {
						/*
						 * change to auto commit mode.
						 * If the transaction is not started, start it.
						 */
						if (!H->tr) {
							if (!php_firebird_begin_transaction(dbh, /* auto commit mode */ true)) {
								return false;
							}
						}
					} else {
						/*
						 * change to not auto commit mode.
						 * close the transaction if exists.
						 */
						if (H->tr) {
							if (!php_firebird_commit_transaction(dbh, /* retain */ false)) {
								return false;
							}
						}
					}
					dbh->auto_commit = bval;
				}
			}
			return true;

		case PDO_ATTR_FETCH_TABLE_NAMES:
			if (!pdo_get_bool_param(&bval, val)) {
				return false;
			}
			H->fetch_table_names = bval;
			return true;

		case PDO_FB_ATTR_DATE_FORMAT:
			{
				zend_string *str = zval_try_get_string(val);
				if (UNEXPECTED(!str)) {
					return false;
				}
				if (H->date_format) {
					pefree(H->date_format, dbh->is_persistent);
					H->date_format = NULL;
				}
				H->date_format = pestrndup(ZSTR_VAL(str), ZSTR_LEN(str),dbh->is_persistent);
				zend_string_release_ex(str, 0);
			}
			return true;

		case PDO_FB_ATTR_TIME_FORMAT:
			{
				zend_string *str = zval_try_get_string(val);
				if (UNEXPECTED(!str)) {
					return false;
				}
				if (H->time_format) {
					pefree(H->time_format, dbh->is_persistent);
					H->time_format = NULL;
				}
				H->time_format = pestrndup(ZSTR_VAL(str), ZSTR_LEN(str),dbh->is_persistent);
				zend_string_release_ex(str, 0);
			}
			return true;

		case PDO_FB_ATTR_TIMESTAMP_FORMAT:
			{
				zend_string *str = zval_try_get_string(val);
				if (UNEXPECTED(!str)) {
					return false;
				}
				if (H->timestamp_format) {
					pefree(H->timestamp_format, dbh->is_persistent);
					H->timestamp_format = NULL;
				}
				H->timestamp_format = pestrndup(ZSTR_VAL(str), ZSTR_LEN(str),dbh->is_persistent);
				zend_string_release_ex(str, 0);
			}
			return true;

		case PDO_FB_TRANSACTION_ISOLATION_LEVEL:
			{
				if (!pdo_get_long_param(&lval, val)) {
					return false;
				}

				if (H->in_manually_txn) {
					pdo_raise_impl_error(dbh, NULL, "HY000", "Cannot change transaction isolation level while a transaction is already open");
					return false;
				}

				/* ignore if the new value equals the old one */
				if (H->txn_isolation_level != lval) {
					if (lval == PDO_FB_READ_COMMITTED ||
						lval == PDO_FB_REPEATABLE_READ ||
						lval == PDO_FB_SERIALIZABLE
					) {
						/*
						 * Autocommit mode is always read-committed, so this setting is used the next time
						 * a manual transaction starts. Therefore, there is no need to immediately reopen the transaction.
						 */
						H->txn_isolation_level = lval;
					} else {
						zend_value_error("Pdo\\Firebird::TRANSACTION_ISOLATION_LEVEL must be a valid transaction isolation level "
							"(Pdo\\Firebird::READ_COMMITTED, Pdo\\Firebird::REPEATABLE_READ, or Pdo\\Firebird::SERIALIZABLE)");
						return false;
					}
				}
			}
			return true;

		case PDO_FB_WRITABLE_TRANSACTION:
			{
				if (!pdo_get_bool_param(&bval, val)) {
					return false;
				}

				if (H->in_manually_txn) {
					pdo_raise_impl_error(dbh, NULL, "HY000", "Cannot change access mode while a transaction is already open");
					return false;
				}

				/* ignore if the new value equals the old one */
				if (H->is_writable_txn != bval) {
					H->is_writable_txn = bval;
					if (dbh->auto_commit) {
						if (H->tr) {
							if (!php_firebird_commit_transaction(dbh, /* retain */ false)) {
								/* In case of error, revert the setting */
								H->is_writable_txn = !bval;
								return false;
							}
						}
						if (!php_firebird_begin_transaction(dbh, /* auto commit mode */ true)) {
							/* In case of error, revert the setting */
							H->is_writable_txn = !bval;
							return false;
						}
					}
				}
			}
			return true;
	}
	return false;
}
/* }}} */

#define INFO_BUF_LEN 512

/* callback to used to report database server info */
static void php_firebird_info_cb(void *arg, char const *s) /* {{{ */
{
	if (arg) {
		if (*(char*)arg) { /* second call */
			strlcat(arg, " ", INFO_BUF_LEN);
		}
		strlcat(arg, s, INFO_BUF_LEN);
	}
}
/* }}} */

/* called by PDO to get a driver-specific dbh attribute */
static int pdo_firebird_get_attribute(pdo_dbh_t *dbh, zend_long attr, zval *val) /* {{{ */
{
	pdo_firebird_db_handle *H = (pdo_firebird_db_handle *)dbh->driver_data;

	switch (attr) {
		char tmp[INFO_BUF_LEN];

		case PDO_ATTR_AUTOCOMMIT:
			ZVAL_BOOL(val,dbh->auto_commit);
			return 1;

		case PDO_ATTR_CONNECTION_STATUS:
			ZVAL_BOOL(val, !isc_version(&H->db, php_firebird_info_cb, NULL));
			return 1;

		case PDO_ATTR_CLIENT_VERSION: {
#if defined(__GNUC__) || defined(PHP_WIN32)
			info_func_t info_func = NULL;
#ifdef __GNUC__
			info_func = (info_func_t)dlsym(RTLD_DEFAULT, "isc_get_client_version");
#else
			HMODULE l = GetModuleHandle("fbclient");

			if (!l) {
				break;
			}
			info_func = (info_func_t)GetProcAddress(l, "isc_get_client_version");
#endif
			if (info_func) {
				info_func(tmp);
				ZVAL_STRING(val, tmp);
			}
#else
			ZVAL_NULL(val);
#endif
			}
			return 1;

		case PDO_ATTR_SERVER_VERSION:
		case PDO_ATTR_SERVER_INFO:
			*tmp = 0;

			if (!isc_version(&H->db, php_firebird_info_cb, (void*)tmp)) {
				ZVAL_STRING(val, tmp);
				return 1;
			}
			return -1;

		case PDO_ATTR_FETCH_TABLE_NAMES:
			ZVAL_BOOL(val, H->fetch_table_names);
			return 1;

		case PDO_FB_ATTR_DATE_FORMAT:
			ZVAL_STRING(val, H->date_format ? H->date_format : PDO_FB_DEF_DATE_FMT);
			return 1;

		case PDO_FB_ATTR_TIME_FORMAT:
			ZVAL_STRING(val, H->time_format ? H->time_format : PDO_FB_DEF_TIME_FMT);
			return 1;

		case PDO_FB_ATTR_TIMESTAMP_FORMAT:
			ZVAL_STRING(val, H->timestamp_format ? H->timestamp_format : PDO_FB_DEF_TIMESTAMP_FMT);
			return 1;

		case PDO_FB_TRANSACTION_ISOLATION_LEVEL:
			ZVAL_LONG(val, H->txn_isolation_level);
			return 1;

		case PDO_FB_WRITABLE_TRANSACTION:
			ZVAL_BOOL(val, H->is_writable_txn);
			return 1;
	}
	return 0;
}
/* }}} */

/* called by PDO to check liveness */
static zend_result pdo_firebird_check_liveness(pdo_dbh_t *dbh) /* {{{ */
{
	pdo_firebird_db_handle *H = (pdo_firebird_db_handle *)dbh->driver_data;

	/* fb_ping return 0 if the connection is alive */
	return fb_ping(H->isc_status, &H->db) ? FAILURE : SUCCESS;
}
/* }}} */

/* called by PDO to retrieve driver-specific information about an error that has occurred */
static void pdo_firebird_fetch_error_func(pdo_dbh_t *dbh, pdo_stmt_t *stmt, zval *info) /* {{{ */
{
	pdo_firebird_db_handle *H = (pdo_firebird_db_handle *)dbh->driver_data;
	if (H->einfo.sqlcode != IS_NULL) {
		add_next_index_long(info, H->einfo.sqlcode);
	}
	if (H->einfo.errmsg && H->einfo.errmsg_length) {
		add_next_index_stringl(info, H->einfo.errmsg, H->einfo.errmsg_length);
	}
}
/* }}} */

/* {{{ firebird_in_manually_transaction */
static bool pdo_firebird_in_manually_transaction(pdo_dbh_t *dbh)
{
	/**
	 * we can tell if a transaction exists now by checking H->tr,
	 * but which will always be true in autocommit mode.
	 * So this function checks if there is currently a "manually begun transaction".
	 */
	pdo_firebird_db_handle *H = (pdo_firebird_db_handle *)dbh->driver_data;
	return H->in_manually_txn;
}
/* }}} */

static const struct pdo_dbh_methods firebird_methods = { /* {{{ */
	firebird_handle_closer,
	firebird_handle_preparer,
	firebird_handle_doer,
	firebird_handle_quoter,
	firebird_handle_manually_begin,
	firebird_handle_manually_commit,
	firebird_handle_manually_rollback,
	pdo_firebird_set_attribute,
	NULL, /* last_id not supported */
	pdo_firebird_fetch_error_func,
	pdo_firebird_get_attribute,
	pdo_firebird_check_liveness,
	NULL, /* get driver methods */
	NULL, /* request shutdown */
	pdo_firebird_in_manually_transaction,
	NULL, /* get gc */
	NULL /* scanner */
};
/* }}} */

/* the driver-specific PDO handle constructor */
static int pdo_firebird_handle_factory(pdo_dbh_t *dbh, zval *driver_options) /* {{{ */
{
	struct pdo_data_src_parser vars[] = {
		{ "dbname", NULL, 0 },
		{ "charset",  NULL,	0 },
		{ "role", NULL,	0 },
		{ "dialect", "3", 0 },
		{ "user", NULL, 0 },
		{ "password", NULL, 0 }
	};
	int i, ret = 0;
	short buf_len = 256, dpb_len;

	pdo_firebird_db_handle *H = dbh->driver_data = pecalloc(1,sizeof(*H),dbh->is_persistent);

	php_pdo_parse_data_source(dbh->data_source, dbh->data_source_len, vars, 6);

	if (!dbh->username && vars[4].optval) {
		dbh->username = pestrdup(vars[4].optval, dbh->is_persistent);
	}

	if (!dbh->password && vars[5].optval) {
		dbh->password = pestrdup(vars[5].optval, dbh->is_persistent);
	}

	H->in_manually_txn = 0;
	H->is_writable_txn = pdo_attr_lval(driver_options, PDO_FB_WRITABLE_TRANSACTION, 1);
	zend_long txn_isolation_level = pdo_attr_lval(driver_options, PDO_FB_TRANSACTION_ISOLATION_LEVEL, PDO_FB_REPEATABLE_READ);
	if (txn_isolation_level == PDO_FB_READ_COMMITTED ||
		txn_isolation_level == PDO_FB_REPEATABLE_READ ||
		txn_isolation_level == PDO_FB_SERIALIZABLE
	) {
		H->txn_isolation_level = txn_isolation_level;
	} else {
		zend_value_error("Pdo\\Firebird::TRANSACTION_ISOLATION_LEVEL must be a valid transaction isolation level "
			"(Pdo\\Firebird::READ_COMMITTED, Pdo\\Firebird::REPEATABLE_READ, or Pdo\\Firebird::SERIALIZABLE)");
		ret = 0;
	}

	do {
		static char const dpb_flags[] = {
			isc_dpb_user_name, isc_dpb_password, isc_dpb_lc_ctype, isc_dpb_sql_role_name };
		char const *dpb_values[] = { dbh->username, dbh->password, vars[1].optval, vars[2].optval };
		char dpb_buffer[256] = { isc_dpb_version1 }, *dpb;

		dpb = dpb_buffer + 1;

		/* loop through all the provided arguments and set dpb fields accordingly */
		for (i = 0; i < sizeof(dpb_flags); ++i) {
			if (dpb_values[i] && buf_len > 0) {
				dpb_len = slprintf(dpb, buf_len, "%c%c%s", dpb_flags[i], (unsigned char)strlen(dpb_values[i]),
					dpb_values[i]);
				dpb += dpb_len;
				buf_len -= dpb_len;
			}
		}

		H->sql_dialect = PDO_FB_DIALECT;
		if (vars[3].optval) {
			H->sql_dialect = atoi(vars[3].optval);
		}

		/* fire it up baby! */
		if (isc_attach_database(H->isc_status, 0, vars[0].optval, &H->db,(short)(dpb-dpb_buffer), dpb_buffer)) {
			break;
		}

		dbh->methods = &firebird_methods;
		dbh->native_case = PDO_CASE_UPPER;
		dbh->alloc_own_columns = 1;

		ret = 1;

	} while (0);

	for (i = 0; i < sizeof(vars)/sizeof(vars[0]); ++i) {
		if (vars[i].freeme) {
			efree(vars[i].optval);
		}
	}

	if (!dbh->methods) {
		char errmsg[512];
		const ISC_STATUS *s = H->isc_status;
		fb_interpret(errmsg, sizeof(errmsg),&s);
		zend_throw_exception_ex(php_pdo_get_exception(), H->isc_status[1], "SQLSTATE[%s] [%ld] %s",
				"HY000", H->isc_status[1], errmsg);
	}

	if (ret && dbh->auto_commit && !H->tr) {
		ret = php_firebird_begin_transaction(dbh, /* auto commit mode */ true);
	}

	if (!ret) {
		firebird_handle_closer(dbh);
	}

	return ret;
}
/* }}} */


const pdo_driver_t pdo_firebird_driver = { /* {{{ */
	PDO_DRIVER_HEADER(firebird),
	pdo_firebird_handle_factory
};
/* }}} */