File: query.bs

package info (click to toggle)
storm-lang 0.7.4-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 52,004 kB
  • sloc: ansic: 261,462; cpp: 140,405; sh: 14,891; perl: 9,846; python: 2,525; lisp: 2,504; asm: 860; makefile: 678; pascal: 70; java: 52; xml: 37; awk: 12
file content (1950 lines) | stat: -rw-r--r-- 44,418 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
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
use core:lang;
use lang:bs;
use lang:bs:macro;

private Expr bindParam(SrcPos pos, Block block, Expr statement, Nat id, Expr param) on Compiler {
	Actuals params;
	params.add(NumLiteral(pos, id));
	params.add(param);
	namedExpr(block, pos, "bind", statement, params);
}

// Common parts of the code to create queries.
private Expr createQueryExpr(SrcPos pos, Block block, Expr connection, Query query, DatabaseType? type) on Compiler {
	if (type) {
		query.resolve(ResolveContext(block, type.contents));
	} else {
		query.resolve(ResolveContext(block));
	}

	var q = query.build();
	var cached = q.cachedQuery();

	if (type)
		type.queries << cached;

	ExprBlock r(pos, block);

	// Create a prepared statement.
	var prepared = {
		// Call connection.prepare(query). Note: It either refers to the one in
		// DBConnection or the one in TypedConnection, but they work the same way.
		Actuals params(lang:bs:util:ObjectLiteral(pos, cached));
		var stmt = namedExpr(r, pos, "prepare", connection, params);
		var varDecl = Var(r, SStr("statement"), stmt);
		r.add(varDecl);
		LocalVarAccess(pos, varDecl.var);
	};

	// Bind parameters.
	for (i, x in q.bind) {
		r.add(bindParam(pos, r, prepared, i, x));
	}

	// Execute it, and save the result.
	var resultDecl = Var(r, SStr("result"), namedExpr(r, pos, "execute", prepared));
	r.add(resultDecl);

	// Get the result, if desired. Otherwise, finalize it.
	LocalVarAccess resultAccess(pos, resultDecl.var);
	if (e = query.result(r, resultAccess))
		r.add(e);
	else
		r.add(namedExpr(r, pos, "finalize", resultAccess));

	r;
}


// Create a suitable query expression depending on what database connection was used.
Expr queryExpr(SrcPos pos, Block block, Expr expr, Query query) on Compiler {
	var result = expr.result().type();
	if (x = result.type as DatabaseType) {
		// Typed version.
		return createQueryExpr(pos, block, expr, query, x);
	} else if (Value(named{DBConnection}).mayReferTo(result)) {
		// Untyped version.
		return createQueryExpr(pos, block, expr, query, null);
	} else {
		throw SyntaxError(expr.pos, "Expected a database connection (typed or untyped).");
	}
}

// A Query block.
class QueryBlock extends ExprBlock {
	init(SrcPos pos, Block parent, Expr db) {
		var result = db.result.type;
		if (Value(named{DBConnection}).mayReferTo(result)) {
		} else if (result.type as DatabaseType) {
		} else {
			throw SyntaxError(db.pos, "Expected a database connection (typed or untyped).");
		}

		super(pos, parent);

		Var var(this, SStr(" db", db.pos), db);
		add(var);

		init {
			connection(db.pos, var.var);
		}
	}

	// Variable containing our database connection.
	LocalVarAccess connection;

	// Helper to find a Query block.
	QueryBlock find(Block in) : static {
		NameLookup? at = in.lookup;
		while (l = at as BlockLookup) {
			if (q = l.block as QueryBlock)
				return q;

			at = l.parent;
		}

		throw InternalError("Could not find a parent QueryBlock!");
	}
}

// Create a suitable query expression, assuming we're inside a WITH block.
Expr queryBlockExpr(SrcPos pos, Block block, Query query) on Compiler {
	QueryBlock q = QueryBlock:find(block);
	queryExpr(pos, block, q.connection, query);
}

/**
 * Table name. Optionally creates an alias for the query.
 */
class TableName on Compiler {
	SrcPos pos;
	Str name;
	Str alias;

	// No alias.
	init(SStr name) {
		init { pos = name.pos; name = name.v; alias = name.v; }
	}

	// Create an alias.
	init(SStr name, SStr alias) {
		init { pos = name.pos; name = name.v; alias = alias.v; }
	}

	// Build.
	void build(QueryBuilder b) {
		b.query.name(name);
		if (name != alias) {
			b.query.put(" AS ");
			b.query.name(alias);
		}
	}

	// To string.
	void toS(StrBuf to) {
		to << name;
		if (name != alias)
			to << " AS " << alias;
	}
}

/**
 * Context passed around while resolving a SQL query.
 */
class ResolveContext on Compiler {
	// Current BS block.
	Block block;

	// Contents of the database.
	Database? db;

	// Which tables are visible in the current context? Keys are aliases and not necessarily table names.
	Str->Table visible;

	// Which tables might be null due to a join? Keys are keys in 'visible'.
	Set<Str> nullTables;

	// Create typed version.
	init(Block block, Database db) {
		init { block = block; db = db; }
	}

	// Create untyped version.
	init(Block block) {
		init { block = block; }
	}

	// Is this a typed query?
	Bool typed() {
		db.any;
	}

	// Add a table to 'current'. Throws if the table is known not to exists.
	Table? addTable(SrcPos pos, Str to) {
		// Untyped version?
		unless (db)
			return null;

		unless (found = db.find(to))
			throw NoSuchTable(pos, to);
		if (visible.has(to))
			throw DuplicateAlias(pos, to);
		visible.put(to, found);
		found;
	}
	Table? addTable(TableName table) {
		unless (db)
			return null;

		unless (found = db.find(table.name))
			throw NoSuchTable(table.pos, table.name);
		if (visible.has(table.alias))
			throw DuplicateAlias(table.pos, table.alias);
		visible.put(table.alias, found);
		found;
	}

	// Result from "resolve"
	value ResolveResult {
		Str table;
		Column column;

		init(Str table, Column column) {
			init { table = table; column = column; }
		}
	}

	// Resolve a column.
	ResolveResult? resolve(SrcPos pos, Str? table, Str column) {
		if (table) {
			unless (t = visible.at(table))
				return null;
			if (col = t.find(column))
				return ResolveResult(table, col);
			return null;
		} else {
			ResolveResult? result;
			for (alias, t in visible) {
				if (col = t.find(column)) {
					if (result) {
						throw SyntaxError(pos, "The column name ${column} is ambigous. It exists in tables ${result.table} and ${t.name} at least.");
					} else {
						result = ResolveResult(alias, col);
					}
				}
			}
			return result;
		}
	}
}


/**
 * Query builder. Collects a SQL query string in a StrBuf, as well as BS expressions for any
 * parameters that need to be bound.
 */
class QueryBuilder on Compiler {
	// String builder that contains the final SQL query.
	QueryStrBuilder query;

	// Expressions that are used to bind parameters.
	Expr[] bind;

	// Append a bound parameter.
	void bind(Expr expr) {
		query.placeholder();
		bind << expr;
	}

	// Get a CachedQuery from the current state.
	CachedQuery cachedQuery() {
		SimpleCachedQuery(query.build);
	}

	// To string.
	void toS(StrBuf to) : override {
		to << "Query: " << query.build;
		to << "\nData: " << bind;
	}
}


/**
 * Query builder with support for fallbacks.
 */
class FallbackQueryBuilder extends QueryBuilder {
	// Features required to use the regular query.
	DBFeatures features;

	// Which query generates the result?
	Nat resultId;

	// Fallback queries.
	QueryStr[] fallbacks;

	// Create.
	init(DBFeatures features, Nat resultId) {
		init { features = features; resultId = resultId; }
	}

	// Cached query.
	CachedQuery cachedQuery() : override {
		MultiCachedQuery(query.build, features, fallbacks, resultId);
	}

	// To string.
	void toS(StrBuf to) : override {
		super:toS(to);
		to << "\nFeatures: " << features.toS;
		to << "\nFallbacks: " << join(fallbacks, ", ");
	}
}


/**
 * Base class for an SQL query.
 *
 * Note: .toS() looks like SQL, but does not take proper care of edge-cases, so should not be
 * treated as a proper SQL statement.
 */
class Query on Compiler {
	// Position in source.
	SrcPos pos;

	// Create.
	init(SrcPos pos) {
		init() {
			pos = pos;
		}
	}

	// Resolve any unknowns in this query, given a suitable context.
	// Also typechecks as applicable.
	void resolve(ResolveContext context) : abstract;

	// Build a query.
	QueryBuilder build() : abstract;

	// Compute the result of this query, if it should be available.
	Expr? result(Block context, Expr result) {
		null;
	}
}

/**
 * INSERT query.
 */
class InsertQuery extends Query {
	// Table name.
	SStr table;

	// Columns to insert into. If empty, we insert into all columns.
	SStr[] columns;

	// Values to insert.
	SQLExpr[] values;

	// Returning, if any.
	ReturningClause? returning;

	// Resolved table, after 'resolve' is called.
	private Table? resolvedTable;

	// Create, insert all columns.
	init(SrcPos pos, SStr table, SQLExpr[] values, ReturningClause? returning) {
		init(pos) {
			table = table;
			values = values;
			returning = returning;
		}
	}

	// Create, insert into only a subset of columns.
	init(SrcPos pos, SStr table, SStr[] columns, SQLExpr[] values, ReturningClause? returning) {
		init(pos) {
			table = table;
			columns = columns;
			values = values;
			returning = returning;
		}
	}

	// Resolve.
	void resolve(ResolveContext context) : override {
		var table = context.addTable(table.pos, table.v);
		this.resolvedTable = table;

		// If we found a table, explicitly specify the column names for easier typechecking later.
		Column[] cols;
		if (table) {
			if (columns.empty) {
				for (c in table.columns)
					columns << SStr(c.name, pos);
			} else {
				// Find all of the columns.
				Set<Str> used;
				for (c in columns) {
					used.put(c.v);
					unless (found = table.find(c.v))
						throw NoSuchColumn(c.pos, c.v, table.name);
					cols << found;
				}

				Bool multiPK = table.multiplePK();

				// Check the ones that are not inserted.
				for (c in table.columns) {
					if (used.has(c.name))
						continue;

					if (!c.hasDefault(multiPK))
						throw SyntaxError(pos, "The column ${c.name} has no default value, and needs to be given a value.");
				}
			}

			if (returning) {
				returning.resolve(context, table);

				// We need to reorder the columns of the table to match the order they are selected.
				// Otherwise, any bound parameters will not line up properly.
				Column[] orderedCols;
				SQLExpr[] orderedVals;
				for (desc in returning.rowDesc) {
					for (i, x in cols) {
						if (x.name == desc.name) {
							orderedCols << x;
							orderedVals << values[i];
							cols.remove(i);
							values.remove(i);
							break;
						}
					}
				}

				// Copy remaining ones.
				for (i, x in cols) {
					orderedCols << x;
					orderedVals << values[i];
				}

				cols = orderedCols;
				values = orderedVals;

				// Copy names to 'columns' since we changed the order.
				columns.clear();
				for (x in cols)
					columns << SStr(x.name);
			}
		}

		if (cols.any & (values.count != cols.count))
			throw SyntaxError(pos, "The number of values does not match the number of columns inserted into.");

		// It does not really make sense to refer to column names in an insert statement...
		context.visible.clear();

		for (Nat i = 0; i < values.count; i++)
			values[i] = values[i].resolve(context);

		for (i, col in cols) {
			Value result(values[i].result);
			if (col.allowNull)
				result = unwrapMaybe(result);

			if (!Value(col.datatype.storm).mayReferTo(result))
				throw SyntaxError(values[i].pos, "Can not store a value of type ${result} in the column \"${col.name}\".");
		}
	}

	// Build the query.
	QueryBuilder build() : override {
		if (returning) {
			// Note: We can not support RETURNING for non-typed databases!
			if (returning.rowDesc.empty)
				throw SyntaxError(returning.pos, "RETURNING statement can only be used for typed connections.");

			FallbackQueryBuilder r(DBFeatures:insertReturning, 1);
			buildNative(r);

			QueryStr part1 = r.query.build();

			r.query.put(" ");
			returning.build(r);

			QueryBuilder part2;
			part2.query.put("SELECT ");
			for (i, col in returning.rowDesc) {
				if (i > 0)
					part2.query.put(", ");
				putColValue(part2, col.name);
			}

			r.fallbacks << part1;
			r.fallbacks << part2.query.build();

			r;
		} else {
			QueryBuilder r;
			buildNative(r);
			r;
		}
	}

	// Find the value of a column.
	private void putColValue(QueryBuilder r, Str column) {
		unless (resolvedTable)
			return;

		// See if this is a column we inserted into:
		if (columns.any) {
			for (i, c in columns) {
				if (c.v == column) {
					values[i].build(r);
					return;
				}
			}
		}

		// Find the column:
		for (i, col in resolvedTable.columns) {
			if (col.name != column)
				continue;

			// If we insert into all columns, it is not caught from above. Check here instead.
			if (columns.empty) {
				values[i].build(r);
				return;
			}

			// Figure out the default value:
			if (d = col.default) {
				d.build(r);
				return;
			}

			// Is it an autoincrement column?
			Bool autoIncrement = col.autoIncrement;
			if (!autoIncrement)
				autoIncrement = i == resolvedTable.implicitAutoIncrementColumn();
			if (autoIncrement) {
				r.query.lastRowId();
				return;
			}

			// Nothing else, just put null.
			r.query.put("NULL");
			return;
		}
	}

	// Create the "native" query.
	private void buildNative(QueryBuilder r) {
		r.query.put("INSERT INTO ");
		r.query.name(table.v);
		if (columns.any) {
			r.query.put(" (");
			for (i, col in columns) {
				if (i > 0)
					r.query.put(", ");
				r.query.name(col.v);
			}
			r.query.put(")");
		}
		r.query.put(" VALUES (");
		for (i, v in values) {
			if (i > 0)
				r.query.put(", ");
			v.build(r);
		}
		r.query.put(")");
	}

	// Return the last created row ID.
	Expr? result(Block context, Expr result) {
		if (returning) {
			returning.singleResult(context, result);
		} else {
			namedExpr(context, pos, "lastRowId", result);
		}
	}

	// To string.
	void toS(StrBuf to) : override {
		to << "INSERT INTO " << table.v;
		if (columns.any)
			to << " (" << join(columns, ", ", (x) => x.v) << ")";

		to << " VALUES (" << join(values, ", ") << ");";
	}
}

// Helper to check that a condition returns a boolean. Assumes that the condition was resolved beforehand.
private void checkCondition(SQLExpr condition) on Compiler {
	var result = condition.result;
	if (!Value(named{Bool}).mayReferTo(unwrapMaybe(result)))
		throw SyntaxError(condition.pos, "Expressions in WHERE and ON clauses are expected to return a Bool, not ${result}.");
}

/**
 * UPDATE query.
 */
class UpdateQuery extends Query {
	// Table to update.
	SStr table;

	// Columns to update.
	AssignExpr[] update;

	// Condition, if any.
	SQLExpr? condition;

	// Returning clause, if any.
	ReturningClause? returning;

	// Create.
	init(SrcPos pos, SStr table, AssignExpr[] update, SQLExpr? condition, ReturningClause? returning) {
		init(pos) {
			table = table;
			update = update;
			condition = condition;
			returning = returning;
		}
	}

	// Resolve.
	void resolve(ResolveContext context) : override {
		var table = context.addTable(table.pos, table.v);

		// Resolve all assignments.
		for (x in update) {
			x.value = x.value.resolve(context);
		}

		// Update the expression if suitable.
		if (x = condition) {
			var resolved = x.resolve(context);
			if (context.typed)
				checkCondition(resolved);
			condition = resolved;
		}

		if (table) {
			// Check if all columns exist, and type-check the assignments.
			for (x in update) {
				unless (column = table.find(x.column.v))
					throw NoSuchColumn(x.column.pos, x.column.v, table.name);

				Value result(x.value.result);
				if (!Value(column.datatype.storm).mayReferTo(result))
					throw SyntaxError(x.value.pos, "Cannot assign a ${result} to column ${column.name}");
			}
		}

		if (returning) {
			returning.resolve(context, table);

			// For fallbacks to work, we need to re-order the updates to be in the same order as the
			// returned columns. Otherwise, any bound parameters may not line up in the separate
			// fallback queries!
			AssignExpr[] reordered;
			for (x in returning.rowDesc) {
				for (i, y in update) {
					if (y.column.v == x.name) {
						reordered << y;
						update.remove(i);
						break;
					}
				}
			}
			update = reordered;
		}
	}

	// Build the query.
	QueryBuilder build() : override {
		if (returning) {
			// Note: We can not support RETURNING for non-typed databases!
			if (returning.rowDesc.empty)
				throw SyntaxError(returning.pos, "RETURNING statement can only be used for typed connections.");

			FallbackQueryBuilder r(DBFeatures:updateReturning, 0);
			buildNative(r);

			// Save the first part of the good query.
			QueryStr part2 = r.query.build();

			r.query.put(" ");
			returning.build(r);

			// Create a select query that selects updated values for columns.
			QueryBuilder part1;
			part1.query.put("SELECT ");
			for (id, column in returning.rowDesc) {
				if (id > 0)
					part1.query.put(", ");

				if (!putReplacement(part1, column))
					part1.query.name(column.name);
			}
			part1.query.put(" FROM ");
			part1.query.name(table.v);
			if (condition) {
				part1.query.put(" WHERE ");
				condition.build(part1);
			}

			r.fallbacks << part1.query.build();
			r.fallbacks << part2;

			r;
		} else {
			QueryBuilder r;
			buildNative(r);
			r;
		}
	}

	// Find a replacement expression for a column.
	private Bool putReplacement(QueryBuilder r, TypedCol column) {
		for (u in update) {
			if (u.column.v == column.name) {
				u.value.build(r);
				return true;
			}
		}
		return false;
	}

	// Create the "native" query.
	private void buildNative(QueryBuilder r) {
		r.query.put("UPDATE ");
		r.query.name(table.v);
		r.query.put(" SET ");
		for (i, x in update) {
			if (i > 0)
				r.query.put(", ");
			r.query.put(x.column.v);
			r.query.put(" = ");
			x.value.build(r);
		}

		if (condition) {
			r.query.put(" WHERE ");
			condition.build(r);
		}
	}

	// Return the number of modified rows.
	Expr? result(Block context, Expr result) {
		if (returning) {
			returning.result(context, result);
		} else {
			namedExpr(context, pos, "changes", result);
		}
	}

	// To string.
	void toS(StrBuf to) : override {
		to << "UPDATE " << table.v << " SET " << join(update, ", ");
		if (condition)
			to << " WHERE " << condition;
		if (returning)
			to << " " << returning;
	}
}

/**
 * Value to update in an UPDATE query.
 */
class AssignExpr on Compiler {
	// Column to update.
	SStr column;

	// Value to assign.
	SQLExpr value;

	// Create.
	init(SStr column, SQLExpr value) {
		init { column = column; value = value; }
	}

	// To string.
	void toS(StrBuf to) : override {
		to << column.v << " = " << value;
	}
}


/**
 * DELETE query.
 */
class DeleteQuery extends Query {
	// Table to update.
	SStr table;

	// Condition, if any.
	SQLExpr? condition;

	// Returning clause, if any.
	ReturningClause? returning;

	// Create.
	init(SrcPos pos, SStr table, SQLExpr? condition, ReturningClause? returning) {
		init(pos) {
			table = table;
			condition = condition;
			returning = returning;
		}
	}

	// Resolve.
	void resolve(ResolveContext context) : override {
		var table = context.addTable(table.pos, table.v);

		if (x = condition) {
			var resolved = x.resolve(context);
			if (context.typed)
				checkCondition(resolved);
			condition = resolved;
		}
		if (returning) {
			returning.resolve(context, table);
		}
	}

	// Build the query.
	QueryBuilder build() : override {
		if (returning) {
			FallbackQueryBuilder r(DBFeatures:deleteReturning, 0);
			buildNative(r);

			// Save the DELETE FROM query.
			QueryStr part2 = r.query.build();

			r.query.put(" ");
			returning.build(r);
			r.query.put(";");

			// Create a select query.
			QueryBuilder part1;
			part1.query.put("SELECT ");
			returning.build(part1.query);
			part1.query.put(" FROM ");
			part1.query.name(table.v);
			if (condition) {
				part1.query.put(" WHERE ");
				condition.build(part1);
			}

			r.fallbacks << part1.query.build();
			r.fallbacks << part2;

			r;
		} else {
			QueryBuilder r;
			buildNative(r);
			r;
		}
	}

	// Crate the "native" query.
	private void buildNative(QueryBuilder r) {
		r.query.put("DELETE FROM ");
		r.query.name(table.v);
		if (condition) {
			r.query.put(" WHERE ");
			condition.build(r);
		}
	}

	// Return the number of modified rows.
	Expr? result(Block context, Expr result) {
		if (returning) {
			returning.result(context, result);
		} else {
			namedExpr(context, pos, "changes", result);
		}
	}

	// To string.
	void toS(StrBuf to) : override {
		to << "DELETE FROM " << table.v;
		if (condition)
			to << " WHERE " << condition;
		if (returning)
			to << " " << returning;
	}
}


/**
 * Common parts for SELECT-like queries (SELECT, SELECT ONE and COUNT currently).
 *
 * Handles the logic of JOIN and WHERE clauses.
 */
class SelectBase extends Query {
	// Table.
	TableName table;

	/**
	 * Join statement.
	 */
	class Join on Compiler {
		// Type of join.
		JoinType type;

		// Table.
		TableName table;

		// Condition for join.
		SQLExpr expr;

		// Create.
		init(JoinType type, TableName table, SQLExpr expr) {
			init {
				type = type;
				table = table;
				expr = expr;
			}
		}

		// Build.
		void build(QueryBuilder to) {
			to.query.put(typeStr());
			to.query.put(" ");
			table.build(to);
			to.query.put(" ON ");
			expr.build(to);
		}

		// String of join type.
		Str typeStr() {
			if (type == JoinType:inner) {
				"JOIN";
			} else if (type == JoinType:full) {
				"FULL JOIN";
			} else if (type == JoinType:left) {
				"LEFT JOIN";
			} else if (type == JoinType:right) {
				"RIGHT JOIN";
			} else {
				"";
			}
		}

		// ToS.
		void toS(StrBuf to) : override {
			to << typeStr() << " " << table << " ON " << expr;
		}
	}

	// Type of joins.
	// Masked to easily mask out which tables might be null.
	enum JoinType : bitmask {
		inner = 0x0,
		full = 0x3,
		left = 0x2,
		right = 0x1,

		nullBefore = 0x1,
		nullAfter = 0x2,
	}

	// Join clauses.
	Join[] joins;

	// Where clause, if present.
	SQLExpr? condition;

	init(SrcPos pos, TableName table, Join[] joins, SQLExpr? condition) {
		init(pos) {
			table = table;
			joins = joins;
			condition = condition;
		}
	}

	// Resolve.
	void resolve(ResolveContext context) : override {
		context.addTable(table);

		for (j in joins) {
			if (j.type.has(JoinType:nullBefore)) {
				// For left and full, all tables before might be null.
				for (k, v in context.visible)
					context.nullTables.put(k);
			}

			context.addTable(j.table);
			if (j.type.has(JoinType:nullAfter)) {
				// For right and full, current table might be null.
				context.nullTables.put(j.table.alias);
			}

			// TODO: Might be too early, but I think this is how SQL works.
			j.expr = j.expr.resolve(context);
			if (context.typed)
				checkCondition(j.expr);
		}

		if (x = condition) {
			var resolved = x.resolve(context);
			if (context.typed)
				checkCondition(resolved);
			condition = resolved;
		}
	}

	// Build the tail of the query (i.e. JOIN and WHERE clauses).
	protected void buildTail(QueryBuilder to) {
		for (j in joins) {
			to.query.put(" ");
			j.build(to);
		}

		if (condition) {
			to.query.put(" WHERE ");
			condition.build(to);
		}
	}

	// To string. Once again, only the tail parts.
	protected void tailToS(StrBuf to) {
		for (j in joins)
			to << j;
		if (condition)
			to << " WHERE " << condition;
	}
}


/**
 * Column to extract.
 */
class SelectedColumn on Compiler {
	// Position
	SrcPos pos;

	// Table (optional). Note, we use the alias of the table if specified.
	Str? table;

	// Column.
	Str column;

	// Alternate name as used in the output.
	Str? as;

	// Type of this column, if available.
	Type? type;

	init(SrcPos pos, SStr column) {
		init {
			pos = pos;
			column = column.v;
		}
	}

	init(SrcPos pos, SStr table, SStr column) {
		init {
			pos = pos;
			table = table.v;
			column = column.v;
		}
	}

	init(SrcPos pos, Str? table, Str column) {
		init {
			pos = pos;
			table = table;
			column = column;
		}
	}

	// Set alternate name in the output.
	void setAs(SStr to) {
		as = to.v;
	}

	// Build.
	void build(QueryBuilder to) {
		build(to.query);
	}

	void build(QueryStrBuilder to) {
		if (table) {
			to.name(table);
			to.put(".");
		}
		to.name(column);
	}

	// ToS.
	void toS(StrBuf to) : override {
		if (table)
			to << table << ".";
		to << column << " AS " << as;
	}
}


/**
 * Returning clause used for INSERT, DELETE, and UPDATE.
 */
class ReturningClause on Compiler {
	// Position.
	SrcPos pos;

	// Selected columns.
	SelectedColumn[] columns;

	// Description of the types in each row. Empty for non-typed queries.
	TypedCol[] rowDesc;

	// Create.
	init(SrcPos pos, SelectedColumn[] cols) {
		init { columns = cols; }
	}

	// Resolve columns.
	void resolve(ResolveContext context, Table? mainTable) {
		if (context.visible.any) {
			rowDesc.clear();
			if (columns.empty) {
				addAllCols(context);
			} else {
				resolveCols(context, mainTable);
			}
		}
	}

	// Add all columns to our output.
	private void addAllCols(ResolveContext context) {
		for (name, table in context.visible) {
			NestedTypedCol nested(name, false);

			for (id, col in table.columns) {
				SelectedColumn c(pos, null, col.name);
				Type t = resultType(false, col);
				c.type = t;
				nested.push(ScalarTypedCol(col.name, id, t));
			}

			rowDesc << nested;
		}

		// Remove scoping if we only had one table:
		if (rowDesc.count == 1) {
			if (nested = rowDesc[0] as NestedTypedCol) {
				rowDesc = nested.columns;
			}
		}
	}

	// Resolve columns and create our rowDesc.
	private void resolveCols(ResolveContext context, Table? table) {
		Nat id = 0;
		Str->NestedTypedCol nested;

		for (col in columns) {
			unless (result = context.resolve(col.pos, col.table, col.column)) {
				if (table = col.table)
					throw NoSuchColumn(col.pos, col.column, table);
				else if (table)
					throw NoSuchColumn(col.pos, col.column, table.name);
				else
					throw NoSuchColumn(col.pos, col.column, "<unknown table>");
			}

			Bool nullTable = context.nullTables.has(result.table);

			// Now, find the type and add it to the rowDesc. We need to wrap the type inside Maybe
			// only when we put it in a context where it is not scoped.
			if (altName = col.as) {
				// If it has an alternate name, it is never scoped.
				Type t = resultType(nullTable, result.column);
				col.type = t;
				rowDesc << ScalarTypedCol(altName, id++, t);
			} else if (table = col.table) {
				// A table was specified originally. Always scoped, no need for extra Maybe.
				Type t = resultType(false, result.column);
				col.type = t;

				if (!nested.has(table)) {
					NestedTypedCol created(table, nullTable);
					nested.put(table, created);
					rowDesc << created;
				}
				nested.get(table).push(ScalarTypedCol(col.column, id++, t));
			} else {
				// Else, the table was not specified originally and the result will not be scoped.
				Type t = resultType(nullTable, result.column);
				col.type = t;
				rowDesc << ScalarTypedCol(col.column, id++, t);
			}
		}
	}

	// Figure out the type for a column.
	private Type resultType(Bool nullTable, Column col) {
		Type t = col.datatype.storm;
		if (nullTable | col.allowNull) {
			if (maybe = wrapMaybe(t).type)
				return maybe;
		}
		t;
	}

	// Generate result.
	Expr result(Block context, Expr result) {
		if (rowDesc.empty)
			return namedExpr(context, pos, "iter", result);

		var iterType = getTypedIter(rowDesc);
		unless (ctor = iterType.find("__init", [Value(iterType), result.result.type.asRef(false)], Scope()) as Function)
			throw InternalError("Could not find a suitable constructor in the generated type.");

		CtorCall(pos, context.scope, ctor, Actuals(result));
	}

	// Generate a single result.
	Expr singleResult(Block context, Expr result) {
		// No type info - just return a Maybe<Row> object.
		if (rowDesc.empty)
			return namedExpr(context, pos, "next", result);

		// Otherwise, we want to return either <null> or an instance of the row-type.
		TypedRow t = getTypedRow(rowDesc);
		unless (ctor = t.find("__init", [Value(t), Value(named{Row})], Scope()) as Function)
			throw InternalError("Could not find a suitable constructor in the generated type.");

		unless (maybe = wrapMaybe(Value(t)).type)
			throw InternalError("Could not find the maybe type for the generated row type.");

		// Create an if-statement.
		WeakMaybeCast cast(namedExpr(context, pos, "next", result));
		cast.name(SStr("x"));
		If check(context, cast);

		if (created = cast.result) {
			check.success(CtorCall(pos, Scope(), ctor, Actuals(LocalVarAccess(pos, created))));
		}

		if (maybeCtor = maybe.find("__init", [Value(maybe, true)], Scope()) as Function) {
			check.fail(CtorCall(pos, Scope(), maybeCtor, Actuals()));
		}

		check;
	}

	// Build a query.
	void build(QueryBuilder out) {
		out.query.put("RETURNING ");
		build(out.query);
	}

	void build(QueryStrBuilder out) {
		if (columns.empty) {
			out.put("*");
		} else {
			for (i, col in columns) {
				if (i > 0)
					out.put(", ");
				col.build(out);
			}
		}
	}

	// ToS.
	void toS(StrBuf to) : override {
		to << "RETURNING ";
		if (columns.empty)
			to << "*";
		else
			to << join(columns, ", ");
	}
}


/**
 * SELECT query.
 */
class SelectQuery extends SelectBase {
	/**
	 * Single order by column.
	 */
	class OrderBy on Compiler {
		// Position
		SrcPos pos;

		// Table (optional).
		Str? table;

		// Column.
		Str column;

		// Ascending/descending.
		Bool ascending;

		init(SrcPos pos, SStr? table, SStr column, Bool ascending) {
			Str? t;
			if (table)
				t = table.v;

			init {
				pos = pos;
				table = t;
				column = column.v;
				ascending = ascending;
			}
		}

		// Build.
		void build(QueryBuilder to) {
			if (table) {
				to.query.name(table);
				to.query.put(".");
			}
			to.query.name(column);

			if (ascending)
				to.query.put(" ASC");
			else
				to.query.put(" DESC");
		}

		// To string.
		void toS(StrBuf to) {
			if (table)
				to << table << ".";
			to << column;
			if (ascending)
				to << " ASC";
			else
				to << " DESC";
		}
	}

	// Columns to select. If empty, we assume all columns.
	SelectedColumn[] cols;

	// Order by.
	OrderBy[] orderBy;

	// Description of types in each row. Empty for non-typed queries.
	TypedCol[] rowDesc;

	// Create.
	init(SrcPos pos, TableName table, SelectedColumn[] cols, Join[] joins, SQLExpr? condition, OrderBy[] orderBy) {
		init(pos, table, joins, condition) {
			cols = cols;
			orderBy = orderBy;
		}
	}

	// Resolve.
	void resolve(ResolveContext context) : override {
		super:resolve(context);

		// Type-check and prepare output format:
		if (context.visible.any) {
			rowDesc.clear();
			if (cols.empty) {
				addAllCols(context);
			} else {
				resolveCols(context);
			}

			resolveOrder(context);
		}
	}

	// Add all columns to our output.
	private void addAllCols(ResolveContext context) {
		if (joins.empty) {
			// Only one table, don't scope names:
			var name = this.table.alias;
			var table = context.visible.get(name);

			// Note: Currently, nullTable should always be true. This is, however, here for
			// completeness if this assumption would change in the future.
			Bool nullTable = context.nullTables.has(name);

			for (id, col in table.columns) {
				SelectedColumn c(pos, null, col.name);
				Type t = resultType(nullTable, col);

				c.type = t;
				cols << c;

				rowDesc << ScalarTypedCol(col.name, id, t);
			}
		} else {
			// Mutliple tables, scope them appropriately.

			// Note: We could loop through tables in 'context', but to get the order consistent in
			// the output of row types we traverse 'table' and 'join' instead.
			rowDesc << addAllCols(this.table.alias, context);

			for (x in joins)
				rowDesc << addAllCols(x.table.alias, context);
		}
	}

	// Add all names from a table to our output.
	private NestedTypedCol addAllCols(Str tableAlias, ResolveContext context) {
		NestedTypedCol nested(tableAlias, context.nullTables.has(tableAlias));

		var table = context.visible.get(tableAlias);
		for (col in table.columns) {
			SelectedColumn c(pos, tableAlias, col.name);
			Type t = resultType(false, col);

			nested.push(ScalarTypedCol(col.name, cols.count, t));

			c.type = t;
			cols << c;
		}

		nested;
	}

	// Resolve columns and create our rowDesc.
	private void resolveCols(ResolveContext context) {
		Nat id = 0;
		Str->NestedTypedCol nested;

		for (col in cols) {
			unless (result = context.resolve(col.pos, col.table, col.column)) {
				if (table = col.table)
					throw NoSuchColumn(col.pos, col.column, table);
				else
					throw NoSuchColumn(col.pos, col.column, table.name);
			}

			Bool nullTable = context.nullTables.has(result.table);

			// Now, find the type and add it to the rowDesc. We need to wrap the type inside Maybe
			// only when we put it in a context where it is not scoped.
			if (altName = col.as) {
				// If it has an alternate name, it is never scoped.
				Type t = resultType(nullTable, result.column);
				col.type = t;
				rowDesc << ScalarTypedCol(altName, id++, t);
			} else if (table = col.table) {
				// A table was specified originally. Always scoped, no need for extra Maybe.
				Type t = resultType(false, result.column);
				col.type = t;

				if (!nested.has(table)) {
					NestedTypedCol created(table, nullTable);
					nested.put(table, created);
					rowDesc << created;
				}
				nested.get(table).push(ScalarTypedCol(col.column, id++, t));
			} else {
				// Else, the table was not specified originally and the result will not be scoped.
				Type t = resultType(nullTable, result.column);
				col.type = t;
				rowDesc << ScalarTypedCol(col.column, id++, t);
			}
		}
	}

	// Resolve the "order by" portion.
	private void resolveOrder(ResolveContext context) {
		for (col in orderBy) {
			if (context.resolve(col.pos, col.table, col.column).empty) {
				if (table = col.table)
					throw NoSuchColumn(col.pos, col.column, table);
				else
					throw NoSuchColumn(col.pos, col.column, table.name);
			}
		}
	}

	// Figure out the type for a column.
	private Type resultType(Bool nullTable, Column col) {
		Type t = col.datatype.storm;
		if (nullTable | col.allowNull) {
			if (maybe = wrapMaybe(t).type)
				return maybe;
		}
		t;
	}

	// Build the query.
	QueryBuilder build() : override {
		QueryBuilder r;

		r.query.put("SELECT ");
		if (cols.empty) {
			r.query.put("*");
		} else {
			for (i, name in cols) {
				if (i > 0)
					r.query.put(", ");
				name.build(r);
			}
		}
		r.query.put(" FROM ");
		table.build(r);

		buildTail(r);

		if (orderBy.any) {
			r.query.put(" ORDER BY ");
			for (i, name in orderBy) {
				if (i > 0)
					r.query.put(", ");
				name.build(r);
			}
		}

		r.query.put(";");
		r;
	}

	// Return a proper iterator.
	Expr? result(Block context, Expr result) {
		// If no type information, fall back to the typeless version.
		if (rowDesc.empty)
			return namedExpr(context, pos, "iter", result);

		var iterType = getTypedIter(rowDesc);
		unless (ctor = iterType.find("__init", [Value(iterType), result.result.type.asRef(false)], Scope()) as Function)
			throw InternalError("Could not find a suitable constructor in the generated type.");

		CtorCall(pos, context.scope, ctor, Actuals(result));
	}

	// To string.
	void toS(StrBuf to) : override {
		to << "SELECT " << join(cols, ", ") << " FROM ";
		table.toS(to);
		tailToS(to);
		if (orderBy.any) {
			to << " ORDER BY ";
			for (i, name in orderBy) {
				if (i > 0)
					to << ", ";
				name.toS(to);
			}
		}
	}
}

/**
 * SELECT ONE query.
 *
 * Works just like SELECT, but returns Maybe<Row> rather than an iterator.
 */
class SelectOneQuery extends SelectQuery {
	init(SrcPos pos, TableName table, SelectedColumn[] cols, Join[] joins, SQLExpr? condition, OrderBy[] orderBy) {
		init(pos, table, cols, joins, condition, orderBy) {}
	}

	// Modified result. Returns a single row (wrapped in Maybe) rather than an iterator.
	Expr? result(Block context, Expr result) {
		// No type info - just return a Maybe<Row> object.
		if (rowDesc.empty)
			return namedExpr(context, pos, "next", result);

		// Otherwise, we want to return either <null> or an instance of the row-type.
		TypedRow t = getTypedRow(rowDesc);
		unless (ctor = t.find("__init", [Value(t), Value(named{Row})], Scope()) as Function)
			throw InternalError("Could not find a suitable constructor in the generated type.");

		unless (maybe = wrapMaybe(Value(t)).type)
			throw InternalError("Could not find the maybe type for the generated row type.");

		// Create an if-statement.
		WeakMaybeCast cast(namedExpr(context, pos, "next", result));
		cast.name(SStr("x"));
		If check(context, cast);

		if (created = cast.result) {
			check.success(CtorCall(pos, Scope(), ctor, Actuals(LocalVarAccess(pos, created))));
		}

		if (maybeCtor = maybe.find("__init", [Value(maybe, true)], Scope()) as Function) {
			check.fail(CtorCall(pos, Scope(), maybeCtor, Actuals()));
		}

		check;
	}
}

/**
 * COUNT FROM query.
 *
 * Works like SELECT COUNT(*) FROM, but clearer. Returns a Nat.
 */
class CountQuery extends SelectBase {
	init(SrcPos pos, TableName table, Join[] joins, SQLExpr? condition) {
		init(pos, table, joins, condition) {}
	}

	// Build the query.
	QueryBuilder build() : override {
		QueryBuilder r;

		r.query.put("SELECT COUNT(*) FROM ");
		table.build(r);

		buildTail(r);

		r.query.put(";");
		r;
	}

	// Return a Nat representing the number of rows.
	Expr? result(Block context, Expr result) {
		pattern(context) {
			if (row = ${result}.next()) {
				row.getLong(0).nat;
			} else {
				// This should not happen...
				0;
			}
		};
	}

	// To string.
	void toS(StrBuf to) : override {
		to << "COUNT FROM ";
		table.toS(to);
		tailToS(to);
	}
}

/**
 * CREATE TABLE query.
 *
 * Only for untyped connections.
 */
class CreateQuery extends Query {
	// Table declaration.
	Table table;

	// Is this a "CREATE IF NOT EXISTS"?
	Bool ifNotExists;

	// Create.
	init(SrcPos pos, Bool ifNotExists, Table table) {
		init(pos) {
			table = table;
			ifNotExists = ifNotExists;
		}
	}

	// Resolve.
	void resolve(ResolveContext context) : override {
		if (context.typed)
			throw SyntaxError(pos, "Can not use CREATE TABLE queries with typed connections.");
	}

	// Build the query.
	QueryBuilder build() : override {
		QueryBuilder r;
		// Note: We give 'true' for 'supports automatic autoincrement' to avoid modifying the query.
		table.toSQL(r.query, ifNotExists, true, []);
		r;
	}

}

/**
 * CREATE INDEX query.
 *
 * Only for untyped connections.
 */
class IndexQuery extends Query {
	// Index name.
	Str name;

	// Table name.
	SStr table;

	// Columns.
	SStr[] columns;

	// Create.
	init(SrcPos pos, SStr name, SStr table, SStr[] columns) {
		init(pos) {
			name = name.v;
			table = table;
			columns = columns;
		}
	}

	// Create.
	init(SrcPos pos, SStr table, SStr[] columns) {
		StrBuf name;
		name << table.v << "_" << join(columns, "_", (x) => x.v);

		init(pos) {
			name = name.toS;
			table = table;
			columns = columns;
		}
	}

	// Resolve.
	void resolve(ResolveContext context) : override {
		if (context.typed)
			throw SyntaxError(pos, "Can not use CREATE TABLE queries with typed connections.");
	}

	// Build the query.
	QueryBuilder build() : override {
		QueryBuilder r;

		r.query.put("CREATE INDEX ");
		r.query.name(name);
		r.query.put(" ON ");
		r.query.name(table.v);
		r.query.put("(");
		for (i, c in columns) {
			if (i > 0)
				r.query.put(", ");
			r.query.name(c.v);
		}
		r.query.put(");");

		r;
	}

}

/**
 * DROP TABLE query.
 *
 * Only for untyped connections.
 */
class DropQuery extends Query {
	// Table name.
	SStr table;

	// Create.
	init(SrcPos pos, SStr table) {
		init(pos) {
			table = table;
		}
	}

	// Resolve.
	void resolve(ResolveContext context) : override {
		if (context.typed)
			throw SyntaxError(pos, "Can not use CREATE TABLE queries with typed connections.");
	}

	// Build the query.
	QueryBuilder build() : override {
		QueryBuilder r;

		r.query.put("DROP TABLE ");
		r.query.name(table.v);
		r.query.put(";");

		r;
	}

}


/**
 * Custom syntax for transactions.
 */
class TransactionBlock extends Block {
	// Child block for actual code.
	ExprBlock child;

	// The variable created for the transaction object.
	private Var transactionVar;

	// Current block and label to exit the block.
	private core:asm:Label exitCommitLabel;
	private core:asm:Label exitRollbackLabel;
	private core:asm:Block exitBlock;
	private CodeResult exitResult;

	// Keep track of the current return type for this block.
	private ExprResult abortTypes;

	// Create, use an explicit expression for the connection.
	init(SrcPos pos, Block parent, Expr connection) {
		super(pos, parent);

		var result = connection.result.type;
		var toUse = if (Value(named{DBConnection}).mayReferTo(result)) {
			connection;
		} else if (result.type as DatabaseType) {
			MemberVarAccess(connection.pos, connection, named{TypedConnection:connection<TypedConnection>});
		} else {
			throw SyntaxError(connection.pos, "Expected a database connection (typed or untyped).");
		};

		init {
			child(pos, this);
			transactionVar(this, named{Transaction}, SStr(" transaction"), Actuals(toUse));
			abortTypes = noReturn;
		}
	}

	// Create, use a surrounding block.
	init(SrcPos pos, Block parent) {
		self(pos, parent, QueryBlock:find(parent).connection);
	}

	// Result type.
	ExprResult result() : override {
		var cResult = child.result;

		if (abortTypes.nothing) {
			cResult;
		} else if (cResult.nothing) {
			abortTypes;
		} else {
			var c = common(abortTypes.type, cResult.type);
			// Note: We explicitly allow using ROLLBACK or COMMIT to force the result to void.
			if (c == Value() & abortTypes.value) {
				StrBuf msg;
				msg << "Type mismatch in returns values from transaction. The early abort values result in "
					<< abortTypes.type << " while the final statement in the block results in "
					<< cResult.type << ", which is not compatible.";
				throw SyntaxError(pos, msg.toS);
			}
			c;
		}
	}

	// Called to "register" a new result from ROLLBACK or COMMIT stmts.
	void newAbortResult(SrcPos pos, ExprResult result) {
		if (result.nothing)
			return;

		if (abortTypes.nothing) {
			// First time.
			abortTypes = result;
		} else {
			var c = common(abortTypes.type, result.type);
			if (c == Value()) {
				StrBuf msg;
				msg << "Type mismatch in early abort values for transaction. ";
				msg << "So far, the common result type is " << abortTypes.type;
				msg << " but this can not be combined with " << result.type << ".";
				throw SyntaxError(pos, msg.toS);
			}
			abortTypes = c;
		}
	}

	// Generate code.
	void blockCode(CodeGen to, CodeResult result) : override {
		exitBlock = to.block;
		exitCommitLabel = to.l.label;
		exitRollbackLabel = to.l.label;
		var end = to.l.label;

		exitResult = result.split(to);

		transactionVar.code(to, CodeResult());
		child.code(to, exitResult);

		// Make sure it is activated properly.
		result.created(to);

		// Generate code to commit the transaction.
		to.l << exitCommitLabel;
		to.l << core:asm:lea(core:asm:ptrA, transactionVar.var.var.v);
		to.l << core:asm:fnParam(core:asm:ptrDesc, core:asm:ptrA);
		to.l << core:asm:fnCall(named{Transaction:commit<Transaction>}.ref, true);
		to.l << core:asm:jmp(end);

		// Generate code to roll back the transaction (so that we can jump there easily).
		to.l << exitRollbackLabel;
		to.l << core:asm:lea(core:asm:ptrA, transactionVar.var.var.v);
		to.l << core:asm:fnParam(core:asm:ptrDesc, core:asm:ptrA);
		to.l << core:asm:fnCall(named{Transaction:rollback<Transaction>}.ref, true);

		to.l << end;
	}

	// Either generate a commit or a rollback, optionally returning a value.
	void prematureAbort(CodeGen to, Bool commit, Expr? result) {
		if (result) {
			result.code(to, exitResult);
		}

		var lbl = if (commit) {
			exitCommitLabel;
		} else {
			exitRollbackLabel;
		};

		to.l << core:asm:jmpBlock(lbl, exitBlock);
	}

	// Helper to find a transaction.
	TransactionBlock find(Block from) : static {
		NameLookup? at = from.lookup;
		while (l = at as BlockLookup) {
			if (q = l.block as TransactionBlock)
				return q;

			at = l.parent;
		}

		throw InternalError("Can not find a transaction block.");
	}

	// To string.
	void toS(StrBuf to) : override {
		to << "TRANSACTION ";
		to << child;
	}
}


/**
 * Abort transactions prematurely.
 */
class TransactionAbort extends Expr {
	// Transaction to abort.
	private TransactionBlock transaction;

	// Value, if any.
	private Expr? resultExpr;

	// Commit?
	private Bool commit;

	// Create.
	init(SrcPos pos, Block parent, Bool commit, Expr? result) {
		init(pos) {
			transaction = TransactionBlock:find(parent);
			resultExpr = result;
			commit = commit;
		}

		if (result)
			transaction.newAbortResult(pos, result.result);
		else
			transaction.newAbortResult(pos, Value());
	}

	ExprResult result() : override {
		noReturn;
	}

	void code(CodeGen to, CodeResult r) : override {
		transaction.prematureAbort(to, commit, resultExpr);
	}

	void toS(StrBuf to) : override {
		if (commit)
			to << "COMMIT";
		else
			to << "ROLLBACK";
	}
}