-
-
Notifications
You must be signed in to change notification settings - Fork 745
/
Copy pathDatabase+Schema.swift
1676 lines (1520 loc) · 63.8 KB
/
Database+Schema.swift
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
// Import C SQLite functions
#if GRDBCIPHER
import SQLCipher
#elseif SWIFT_PACKAGE
import GRDBSQLite
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
extension Database {
/// A cache for the available database schemas.
struct SchemaCache {
/// The available schema identifiers, in the order of SQLite resolution:
/// temp, main, then attached databases.
var schemaIdentifiers: [SchemaIdentifier]?
/// The schema cache for each identifier.
fileprivate var schemas: [SchemaIdentifier: DatabaseSchemaCache] = [:]
/// The schema cache for a given identifier
subscript(schemaID: SchemaIdentifier) -> DatabaseSchemaCache { // internal so that it can be tested
get {
schemas[schemaID] ?? DatabaseSchemaCache()
}
set {
schemas[schemaID] = newValue
}
}
mutating func clear() {
schemaIdentifiers = nil
schemas.removeAll()
}
}
/// An SQLite schema. See <https://sqlite.org/lang_naming.html>
enum SchemaIdentifier: Hashable {
/// The main database
case main
/// The temp database
case temp
/// An attached database: <https://sqlite.org/lang_attach.html>
case attached(String)
/// The name of the schema in SQL queries.
///
/// For example:
///
/// SELECT * FROM main.player;
/// -- ~~~~
var sql: String {
switch self {
case .main: return "main"
case .temp: return "temp"
case let .attached(name): return name
}
}
/// The name of the master sqlite table
var masterTableName: String { // swiftlint:disable:this inclusive_language
switch self {
case .main: return "sqlite_master"
case .temp: return "sqlite_temp_master"
case let .attached(name): return "\(name).sqlite_master"
}
}
/// The name of the master sqlite table, without the schema name.
var unqualifiedMasterTableName: String { // swiftlint:disable:this inclusive_language
switch self {
case .main, .attached: return "sqlite_master"
case .temp: return "sqlite_temp_master"
}
}
}
/// The identifier of a database table or view.
struct TableIdentifier {
/// The SQLite schema
var schemaID: SchemaIdentifier
/// The table or view name
var name: String
/// Returns the receiver, quoted for safe insertion as an identifier in
/// an SQL query.
///
/// // SELECT * FROM temp.player
/// db.execute(sql: "SELECT * FROM \(table.quotedDatabaseIdentifier)")
var quotedDatabaseIdentifier: String {
"\(schemaID.sql).\(name.quotedDatabaseIdentifier)"
}
}
// MARK: - Database Schema
/// Returns the current schema version (`PRAGMA schema_version`).
///
/// For example:
///
/// ```swift
/// let version = try dbQueue.read { db in
/// try db.schemaVersion()
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/pragma.html#pragma_schema_version>
public func schemaVersion() throws -> Int32 {
try Int32.fetchOne(internalCachedStatement(sql: "PRAGMA schema_version"))!
}
/// Clears the database schema cache.
///
/// If the database schema is modified by another SQLite connection to the
/// same database file, your application may need to call this method in
/// order to avoid undesired consequences.
public func clearSchemaCache() {
// TODO: can't we automatically clear the cache for writer connection,
// just as we do for DatabasePool reader connections?
SchedulingWatchdog.preconditionValidQueue(self)
schemaCache.clear()
// We also clear statement cache despite the automatic statement
// recompilation (see https://www.sqlite.org/c3ref/prepare.html)
// because the automatic statement recompilation only happens a
// limited number of times (`SQLITE_MAX_SCHEMA_RETRY`).
internalStatementCache.clear()
publicStatementCache.clear()
}
/// Clears the database schema cache if the database schema has changed
/// since this method was last called.
func clearSchemaCacheIfNeeded() throws {
// `PRAGMA schema_version` fetches a 4-bytes integer (Int32), stored
// at offset 40 of the database header:
// <https://sqlite.org/pragma.html#pragma_schema_version>
// <https://sqlite.org/fileformat2.html#database_header>
let schemaVersion = try self.schemaVersion()
if lastSchemaVersion != schemaVersion {
lastSchemaVersion = schemaVersion
clearSchemaCache()
}
}
/// The list of database schemas, in the order of SQLite resolution:
/// temp, main, then attached databases.
func schemaIdentifiers() throws -> [SchemaIdentifier] {
if let schemaIdentifiers = schemaCache.schemaIdentifiers {
return schemaIdentifiers
}
var schemaIdentifiers = try Array(Row
.fetchCursor(self, sql: "PRAGMA database_list")
.map { row -> SchemaIdentifier in
switch row[1] as String {
case "main": return .main
case "temp": return .temp
case let other: return .attached(other)
}
})
// Temp schema shadows all other schemas: put it first
if let tempIdx = schemaIdentifiers.firstIndex(of: .temp) {
schemaIdentifiers.swapAt(tempIdx, 0)
}
schemaCache.schemaIdentifiers = schemaIdentifiers
return schemaIdentifiers
}
/// The `SchemaIdentifier` named `schemaName` if it exists.
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or
/// if no such schema exists.
private func schemaIdentifier(named schemaName: String) throws -> SchemaIdentifier {
let allIdentifiers = try schemaIdentifiers()
if let result = allIdentifiers.first(where: { $0.sql.lowercased() == schemaName.lowercased() }) {
return result
} else {
throw DatabaseError.noSuchSchema(schemaName)
}
}
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// Returns information about a table or a view
func table(_ tableName: String) throws -> TableInfo? {
for schemaIdentifier in try schemaIdentifiers() {
if let result = try table(for: TableIdentifier(schemaID: schemaIdentifier, name: tableName)) {
return result
}
}
return nil
}
/// Returns information about a table or a view
func table(for table: TableIdentifier) throws -> TableInfo? {
// Maybe SQLCipher is too old: check actual version
GRDBPrecondition(sqlite3_libversion_number() >= 3037000, "SQLite 3.37+ required")
return try _table(for: table)
}
#else
/// Returns information about a table or a view
@available(iOS 15.4, macOS 12.4, tvOS 15.4, watchOS 8.5, *) // SQLite 3.37+
func table(_ tableName: String) throws -> TableInfo? {
for schemaIdentifier in try schemaIdentifiers() {
if let result = try table(for: TableIdentifier(schemaID: schemaIdentifier, name: tableName)) {
return result
}
}
return nil
}
/// Returns information about a table or a view
@available(iOS 15.4, macOS 12.4, tvOS 15.4, watchOS 8.5, *) // SQLite 3.37+
func table(for table: TableIdentifier) throws -> TableInfo? {
try _table(for: table)
}
#endif
/// Returns information about a table or a view
private func _table(for table: TableIdentifier) throws -> TableInfo? {
assert(sqlite3_libversion_number() >= 3037000, "SQLite 3.37+ required")
SchedulingWatchdog.preconditionValidQueue(self)
if let tableInfo = schemaCache[table.schemaID].table(table.name) {
return tableInfo.value
}
guard let tableInfo = try TableInfo
.fetchOne(self, sql: "PRAGMA \(table.schemaID.sql).table_list(\(table.name.quotedDatabaseIdentifier))")
else {
// table does not exist
schemaCache[table.schemaID].set(tableInfo: .missing, forTable: table.name)
return nil
}
schemaCache[table.schemaID].set(tableInfo: .value(tableInfo), forTable: table.name)
return tableInfo
}
/// Returns whether a table exists
///
/// When `schemaName` is not specified, the result is true if any known
/// schema contains the table.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// if try db.tableExists("player") { ... }
/// if try db.tableExists("player", in: "main") { ... }
/// if try db.tableExists("player", in: "temp") { ... }
/// if try db.tableExists("player", in: "attached") { ... }
/// }
/// ```
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or
/// if the specified schema does not exist
public func tableExists(_ name: String, in schemaName: String? = nil) throws -> Bool {
if let schemaName {
return try exists(type: .table, name: name, in: schemaName)
}
return try schemaIdentifiers().contains {
try exists(type: .table, name: name, in: $0)
}
}
private func tableExists(_ table: TableIdentifier) throws -> Bool {
try exists(type: .table, name: table.name, in: table.schemaID)
}
/// Returns whether a table is an internal SQLite table.
///
/// Those are tables whose name begins with `sqlite_` and `pragma_`.
///
/// For more information, see <https://www.sqlite.org/fileformat2.html>
public static func isSQLiteInternalTable(_ tableName: String) -> Bool {
// https://www.sqlite.org/fileformat2.html#internal_schema_objects
// > The names of internal schema objects always begin with "sqlite_"
// > and any table, index, view, or trigger whose name begins with
// > "sqlite_" is an internal schema object. SQLite prohibits
// > applications from creating objects whose names begin with
// > "sqlite_".
tableName.starts(with: "sqlite_") || tableName.starts(with: "pragma_")
}
/// Returns whether a table is an internal GRDB table.
///
/// Those are tables whose name begins with `grdb_`.
public static func isGRDBInternalTable(_ tableName: String) -> Bool {
tableName.starts(with: "grdb_")
}
/// Returns whether a view exists, in the main or temp schema, or in an
/// attached database.
///
/// When `schemaName` is not specified, the result is true if any known
/// schema contains the table.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// if try db.viewExists("player") { ... }
/// if try db.viewExists("player", in: "main") { ... }
/// if try db.viewExists("player", in: "temp") { ... }
/// if try db.viewExists("player", in: "attached") { ... }
/// }
/// ```
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or
/// if the specified schema does not exist
public func viewExists(_ name: String, in schemaName: String? = nil) throws -> Bool {
if let schemaName {
return try exists(type: .view, name: name, in: schemaName)
}
return try schemaIdentifiers().contains {
try exists(type: .view, name: name, in: $0)
}
}
/// Returns whether a trigger exists, in the main or temp schema, or in an
/// attached database.
///
/// When `schemaName` is not specified, the result is true if any known
/// schema contains the table.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// if try db.triggerExists("on_player_update") { ... }
/// if try db.triggerExists("on_player_update", in: "main") { ... }
/// if try db.triggerExists("on_player_update", in: "temp") { ... }
/// if try db.triggerExists("on_player_update", in: "attached") { ... }
/// }
/// ```
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or
/// if the specified schema does not exist
public func triggerExists(_ name: String, in schemaName: String? = nil) throws -> Bool {
if let schemaName {
return try exists(type: .trigger, name: name, in: schemaName)
}
return try schemaIdentifiers().contains {
try exists(type: .trigger, name: name, in: $0)
}
}
/// Checks if an entity exists in a given schema
///
/// This is checking for the existence of the entity specified by
/// `type` and `name`. It is assumed that the existence of a schema
/// named `schemaName` is already known and will throw an error if it
/// cannot be found.
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or
/// if the specified schema does not exist
private func exists(type: SchemaObjectType, name: String, in schemaName: String) throws -> Bool {
if let schemaID = try schemaIdentifiers().first(where: { $0.sql.lowercased() == schemaName.lowercased() }) {
return try exists(type: type, name: name, in: schemaID)
} else {
throw DatabaseError.noSuchSchema(schemaName)
}
}
private func exists(type: SchemaObjectType, name: String, in schemaID: SchemaIdentifier) throws -> Bool {
// SQLite identifiers are case-insensitive, case-preserving:
// http://www.alberton.info/dbms_identifiers_and_case_sensitivity.html
try schema(schemaID).containsObjectNamed(name, ofType: type)
}
/// The primary key for table named `tableName`.
///
/// All tables have a primary key, even when it is not explicit. When a
/// table has no explicit primary key, the result is the hidden
/// "rowid" column.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let primaryKey = try db.primaryKey("player")
/// print(primaryKey.columns)
/// }
/// ```
///
/// When `schemaName` is not specified, known schemas are iterated in
/// SQLite resolution order and the first matching result is returned.
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, if
/// the specified schema does not exist, or if no such table exists in
/// the main or temp schema, or in an attached database.
public func primaryKey(_ tableName: String, in schemaName: String? = nil) throws -> PrimaryKeyInfo {
if let schemaName {
return try introspect(tableNamed: tableName, inSchemaNamed: schemaName, using: primaryKey(_:))
}
for schemaIdentifier in try schemaIdentifiers() {
if let result = try primaryKey(TableIdentifier(schemaID: schemaIdentifier, name: tableName)) {
return result
}
}
throw DatabaseError.noSuchTable(tableName)
}
/// Returns the name of the single-column primary key.
///
/// A fatal error is raised if the primary key has several columns, or
/// if `tableName` is the name of a database view.
func filteringPrimaryKeyColumn(_ tableName: String) throws -> String {
do {
let primaryKey = try primaryKey(tableName)
GRDBPrecondition(
primaryKey.columns.count == 1,
"Filtering by primary key requires a single-column primary key in the table '\(tableName)'")
return primaryKey.columns[0]
} catch let error as DatabaseError {
// Maybe the user tries to filter a view by primary key,
// as in <https://github.com/groue/GRDB.swift/issues/1648>.
// In this case, raise a fatalError because this is a
// programmer error which is very likely to be detected
// during development.
if case .SQLITE_ERROR = error.resultCode,
(try? viewExists(tableName)) == true
{
fatalError("""
Filtering by primary key is not available on the database view '\(tableName)'. \
Use `filter(Column("...") == value)` instead.
""")
} else {
throw error
}
}
}
/// Returns nil if table does not exist
private func primaryKey(_ table: TableIdentifier) throws -> PrimaryKeyInfo? {
SchedulingWatchdog.preconditionValidQueue(self)
if let primaryKey = schemaCache[table.schemaID].primaryKey(table.name) {
return primaryKey.value
}
if try !tableExists(table) {
// Views, CTEs, etc.
schemaCache[table.schemaID].set(primaryKey: .missing, forTable: table.name)
return nil
}
// https://www.sqlite.org/pragma.html
//
// > PRAGMA database.table_info(table-name);
// >
// > This pragma returns one row for each column in the named table.
// > Columns in the result set include the column name, data type,
// > whether or not the column can be NULL, and the default value for
// > the column. The "pk" column in the result set is zero for columns
// > that are not part of the primary key, and is the index of the
// > column in the primary key for columns that are part of the primary
// > key.
//
// CREATE TABLE players (
// id INTEGER PRIMARY KEY,
// name TEXT,
// score INTEGER)
//
// PRAGMA table_info("players")
//
// cid | name | type | notnull | dflt_value | pk |
// 0 | id | INTEGER | 0 | NULL | 1 |
// 1 | name | TEXT | 0 | NULL | 0 |
// 2 | score | INTEGER | 0 | NULL | 0 |
guard let columns = try self.columns(in: table) else {
// table does not exist
schemaCache[table.schemaID].set(primaryKey: .missing, forTable: table.name)
return nil
}
let primaryKey: PrimaryKeyInfo
let pkColumns = columns
.filter { $0.primaryKeyIndex > 0 }
.sorted { $0.primaryKeyIndex < $1.primaryKeyIndex }
switch pkColumns.count {
case 0:
// No explicit primary key => primary key is hidden rowID column
primaryKey = .hiddenRowID
case 1:
// Single column
let pkColumn = pkColumns[0]
// https://www.sqlite.org/lang_createtable.html:
//
// > With one exception noted below, if a rowid table has a primary
// > key that consists of a single column and the declared type of
// > that column is "INTEGER" in any mixture of upper and lower
// > case, then the column becomes an alias for the rowid. Such a
// > column is usually referred to as an "integer primary key".
// > A PRIMARY KEY column only becomes an integer primary key if the
// > declared type name is exactly "INTEGER". Other integer type
// > names like "INT" or "BIGINT" or "SHORT INTEGER" or "UNSIGNED
// > INTEGER" causes the primary key column to behave as an ordinary
// > table column with integer affinity and a unique index, not as
// > an alias for the rowid.
// >
// > The exception mentioned above is that if the declaration of a
// > column with declared type "INTEGER" includes an "PRIMARY KEY
// > DESC" clause, it does not become an alias for the rowid [...]
//
// FIXME: We ignore the exception, and consider all INTEGER primary
// keys as aliases for the rowid:
if pkColumn.type.uppercased() == "INTEGER" {
primaryKey = .rowID(pkColumn)
} else {
primaryKey = try .regular([pkColumn], tableHasRowID: tableHasRowID(table))
}
default:
// Multi-columns primary key
primaryKey = try .regular(pkColumns, tableHasRowID: tableHasRowID(table))
}
schemaCache[table.schemaID].set(primaryKey: .value(primaryKey), forTable: table.name)
return primaryKey
}
/// Returns whether the column identifies the rowid column
func columnIsRowID(_ column: String, of tableName: String) throws -> Bool {
let pk = try primaryKey(tableName)
return pk.rowIDColumn == column || (pk.tableHasRowID && column.uppercased() == "ROWID")
}
/// Returns whether the table has a rowid column.
///
/// - precondition: table exists.
private func tableHasRowID(_ table: TableIdentifier) throws -> Bool {
// No need to cache the result, because this information feeds
// `PrimaryKeyInfo`, which is cached.
// Prefer PRAGMA table_list if available
#if GRDBCUSTOMSQLITE || GRDBCIPHER
// Maybe SQLCipher is too old: check actual version
if sqlite3_libversion_number() >= 3037000 {
return try self.table(for: table)!.hasRowID
}
#else
if #available(iOS 15.4, macOS 12.4, tvOS 15.4, watchOS 8.5, *) { // SQLite 3.37+
return try self.table(for: table)!.hasRowID
}
#endif
// To check if the table has a rowid, we compile a statement that
// selects the `rowid` column. If compilation fails, we assume that the
// table is WITHOUT ROWID. This is not a very robust test (users may
// create WITHOUT ROWID tables with a `rowid` column), but nobody has
// reported any problem yet.
//
// Since compilation may fail, we may feed the SQLite error log, and
// users may wonder what are those errors. That's why we use a
// distinctive alias (`checkWithoutRowidOptimization`), so that anyone
// can search the GRDB code, find this documentation, and understand why
// this query appears in the error log:
// <https://github.com/groue/GRDB.swift/issues/945#issuecomment-804896196>
//
// We don't use `try makeStatement(sql:)` in order to avoid throwing an
// error (this annoys users who set a breakpoint on Swift errors).
let sql = "SELECT rowid AS checkWithoutRowidOptimization FROM \(table.quotedDatabaseIdentifier)"
var statement: SQLiteStatement? = nil
let code = sqlite3_prepare_v2(sqliteConnection, sql, -1, &statement, nil)
defer { sqlite3_finalize(statement) }
return code == SQLITE_OK
}
/// The indexes on table named `tableName`.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let indexes = db.indexes(in: "player")
/// for index in indexes {
/// print(index.columns)
/// }
/// }
/// ```
///
/// Only indexes on columns are returned. Indexes on expressions are
/// not returned.
///
/// SQLite does not define any index for INTEGER PRIMARY KEY columns:
/// this method does not return any index that represents the
/// primary key.
///
/// If you want to know if a set of columns uniquely identifies a row,
/// because the columns contain the primary key or a unique index, use
/// ``table(_:hasUniqueKey:)``.
///
/// When `schemaName` is not specified, known schemas are iterated in
/// SQLite resolution order and the first matching result is returned.
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, if
/// the specified schema does not exist, or if no such table or view
/// with this name exists in the main or temp schema, or in an attached
/// database.
public func indexes(on tableName: String, in schemaName: String? = nil) throws -> [IndexInfo] {
if let schemaName {
return try introspect(tableNamed: tableName, inSchemaNamed: schemaName, using: indexes(on:))
}
for schemaIdentifier in try schemaIdentifiers() {
if let result = try indexes(on: TableIdentifier(schemaID: schemaIdentifier, name: tableName)) {
return result
}
}
throw DatabaseError.noSuchTable(tableName)
}
/// Returns nil if table does not exist
private func indexes(on table: TableIdentifier) throws -> [IndexInfo]? {
if let indexes = schemaCache[table.schemaID].indexes(on: table.name) {
return indexes.value
}
let indexes = try Row
// [seq:0 name:"index" unique:0 origin:"c" partial:0]
.fetchAll(self, sql: "PRAGMA \(table.schemaID.sql).index_list(\(table.name.quotedDatabaseIdentifier))")
.compactMap { row -> IndexInfo? in
let indexName: String = row[1]
let unique: Bool = row[2]
let origin: IndexInfo.Origin = row[3]
let indexInfoRows = try Row
// [seqno:0 cid:2 name:"column"]
.fetchAll(self, sql: """
PRAGMA \(table.schemaID.sql).index_info(\(indexName.quotedDatabaseIdentifier))
""")
// Sort by rank
.sorted(by: { ($0[0] as Int) < ($1[0] as Int) })
var columns: [String] = []
for indexInfoRow in indexInfoRows {
guard let column = indexInfoRow[2] as String? else {
// https://sqlite.org/pragma.html#pragma_index_info
// > The name of the column being indexed is NULL if the
// > column is the rowid or an expression.
//
// IndexInfo does not support expressing such index.
// Maybe in a future GRDB version?
return nil
}
columns.append(column)
}
return IndexInfo(name: indexName, columns: columns, isUnique: unique, origin: origin)
}
if indexes.isEmpty {
// PRAGMA index_list doesn't throw any error when table does
// not exist. So let's check if table exists:
if try tableExists(table) == false {
schemaCache[table.schemaID].set(indexes: .missing, forTable: table.name)
return nil
}
}
schemaCache[table.schemaID].set(indexes: .value(indexes), forTable: table.name)
return indexes
}
/// Returns whether a sequence of columns uniquely identifies a row.
///
/// The result is true if and only if the primary key, or a unique index, is
/// included in the sequence.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// // One table with one primary key (id)
/// // and a unique index (a, b):
/// //
/// // > CREATE TABLE t(id INTEGER PRIMARY KEY, a, b, c);
/// // > CREATE UNIQUE INDEX i ON t(a, b);
/// try db.table("t", hasUniqueKey: ["id"]) // true
/// try db.table("t", hasUniqueKey: ["a", "b"]) // true
/// try db.table("t", hasUniqueKey: ["b", "a"]) // true
/// try db.table("t", hasUniqueKey: ["c"]) // false
/// try db.table("t", hasUniqueKey: ["id", "a"]) // true
/// try db.table("t", hasUniqueKey: ["id", "a", "b", "c"]) // true
/// }
/// ```
public func table(
_ tableName: String,
hasUniqueKey columns: some Collection<String>
) throws -> Bool {
try columnsForUniqueKey(columns, in: tableName) != nil
}
/// Returns the foreign keys defined on table named `tableName`.
///
/// When `schemaName` is not specified, known schemas are iterated in
/// SQLite resolution order and the first matching result is returned.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let foreignKeys = try db.foreignKeys(in: "player")
/// for foreignKey in foreignKeys {
/// print(foreignKey.destinationTable)
/// }
/// }
/// ```
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, if
/// the specified schema does not exist, or if no such table or view
/// with this name exists in the main or temp schema, or in an attached
/// database.
public func foreignKeys(on tableName: String, in schemaName: String? = nil) throws -> [ForeignKeyInfo] {
if let schemaName {
return try introspect(tableNamed: tableName, inSchemaNamed: schemaName, using: foreignKeys(on:))
}
for schemaIdentifier in try schemaIdentifiers() {
if let result = try foreignKeys(on: TableIdentifier(schemaID: schemaIdentifier, name: tableName)) {
return result
}
}
throw DatabaseError.noSuchTable(tableName)
}
/// Returns nil if table does not exist
private func foreignKeys(on table: TableIdentifier) throws -> [ForeignKeyInfo]? {
if let foreignKeys = schemaCache[table.schemaID].foreignKeys(on: table.name) {
return foreignKeys.value
}
var rawForeignKeys: [(
id: Int,
destinationTable: String,
mapping: [(origin: String, destination: String?, seq: Int)])] = []
var previousId: Int? = nil
for row in try Row.fetchAll(self, sql: """
PRAGMA \(table.schemaID.sql).foreign_key_list(\(table.name.quotedDatabaseIdentifier))
""")
{
// row = [id:0 seq:0 table:"parents" from:"parentId" to:"id" on_update:"..." on_delete:"..." match:"..."]
let id: Int = row[0]
let seq: Int = row[1]
let table: String = row[2]
let origin: String = row[3]
let destination: String? = row[4]
if previousId == id {
rawForeignKeys[rawForeignKeys.count - 1]
.mapping
.append((origin: origin, destination: destination, seq: seq))
} else {
let mapping = [(origin: origin, destination: destination, seq: seq)]
rawForeignKeys.append((id: id, destinationTable: table, mapping: mapping))
previousId = id
}
}
if rawForeignKeys.isEmpty {
// PRAGMA foreign_key_list doesn't throw any error when table does
// not exist. So let's check if table exists:
if try tableExists(table) == false {
schemaCache[table.schemaID].set(foreignKeys: .missing, forTable: table.name)
return nil
}
}
let foreignKeys = try rawForeignKeys.map { (id, destinationTable, columnMapping) -> ForeignKeyInfo in
let orderedMapping = columnMapping
.sorted { $0.seq < $1.seq }
.map { (origin: $0.origin, destination: $0 .destination) }
let completeMapping: [(origin: String, destination: String)]
if orderedMapping.contains(where: { (_, destination) in destination == nil }) {
let pk = try primaryKey(destinationTable)
completeMapping = zip(pk.columns, orderedMapping).map { (pkColumn, arrow) in
(origin: arrow.origin, destination: pkColumn)
}
} else {
completeMapping = orderedMapping.map { (origin, destination) in
(origin: origin, destination: destination!)
}
}
return ForeignKeyInfo(id: id, destinationTable: destinationTable, mapping: completeMapping)
}
schemaCache[table.schemaID].set(foreignKeys: .value(foreignKeys), forTable: table.name)
return foreignKeys
}
/// Returns a cursor over foreign key violations in the database.
public func foreignKeyViolations() throws -> RecordCursor<ForeignKeyViolation> {
try ForeignKeyViolation.fetchCursor(self, sql: "PRAGMA foreign_key_check")
}
/// Returns a cursor over foreign key violations in the table.
///
/// When `schemaName` is not specified, known schemas are checked in
/// SQLite resolution order and the first matching table is used.
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, if
/// the specified schema does not exist, or if no such table or view
/// with this name exists in the main or temp schema, or in an attached
/// database.
public func foreignKeyViolations(
in tableName: String,
in schemaName: String? = nil)
throws -> RecordCursor<ForeignKeyViolation>
{
if let schemaName {
let schemaID = try schemaIdentifier(named: schemaName)
if try exists(type: .table, name: tableName, in: schemaID) {
return try foreignKeyViolations(in: TableIdentifier(schemaID: schemaID, name: tableName))
} else {
throw DatabaseError.noSuchTable(tableName)
}
}
for schemaIdentifier in try schemaIdentifiers() {
if try exists(type: .table, name: tableName, in: schemaIdentifier) {
return try foreignKeyViolations(in: TableIdentifier(schemaID: schemaIdentifier, name: tableName))
}
}
throw DatabaseError.noSuchTable(tableName)
}
private func foreignKeyViolations(in table: TableIdentifier) throws -> RecordCursor<ForeignKeyViolation> {
try ForeignKeyViolation.fetchCursor(self, sql: """
PRAGMA \(table.schemaID.sql).foreign_key_check(\(table.name.quotedDatabaseIdentifier))
""")
}
/// Throws an error if there exists a foreign key violation in the database.
///
/// On the first foreign key violation found in the database, this method
/// throws a ``DatabaseError`` with extended code
/// `SQLITE_CONSTRAINT_FOREIGNKEY`.
///
/// If you are looking for the list of foreign key violations, prefer
/// ``foreignKeyViolations()`` instead.
public func checkForeignKeys() throws {
try checkForeignKeys(from: foreignKeyViolations())
}
/// Throws an error if there exists a foreign key violation in the table.
///
/// When `schemaName` is not specified, known schemas are checked in
/// SQLite resolution order and the first matching table is used.
///
/// On the first foreign key violation found in the table, this method
/// throws a ``DatabaseError`` with extended code
/// `SQLITE_CONSTRAINT_FOREIGNKEY`.
///
/// If you are looking for the list of foreign key violations, prefer
/// ``foreignKeyViolations(in:in:)`` instead.
///
/// - throws: A ``DatabaseError`` as described above; when a
/// specified schema does not exist; if no such table or view with this
/// name exists in the main or temp schema or in an attached database.
public func checkForeignKeys(in tableName: String, in schemaName: String? = nil) throws {
try checkForeignKeys(from: foreignKeyViolations(in: tableName, in: schemaName))
}
private func checkForeignKeys(from violations: RecordCursor<ForeignKeyViolation>) throws {
if let violation = try violations.next() {
throw violation.databaseError(self)
}
}
/// Returns the actual name of the database table, or nil if the table does
/// not exist.
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or if no
/// such table exists in the main or temp schema, or in an
/// attached database.
func canonicalTableName(_ tableName: String) throws -> String? {
for schemaIdentifier in try schemaIdentifiers() {
// Regular tables
if let result = try schema(schemaIdentifier).canonicalName(tableName, ofType: .table) {
return result
}
// Master table (sqlite_master, sqlite_temp_master)
// swiftlint:disable:next inclusive_language
let masterTableName = schemaIdentifier.unqualifiedMasterTableName
if tableName.lowercased() == masterTableName.lowercased() {
return masterTableName
}
}
return nil
}
func schema(_ schemaID: SchemaIdentifier) throws -> SchemaInfo {
if let schemaInfo = schemaCache[schemaID].schemaInfo {
return schemaInfo
}
let schemaInfo = try SchemaInfo(self, masterTableName: schemaID.masterTableName)
schemaCache[schemaID].schemaInfo = schemaInfo
return schemaInfo
}
/// Attempts to perform a table introspection function on a given
/// table and schema
///
/// - parameter tableName: The name of the table to examine
/// - parameter schemaName: The name of the schema to check
/// - parameter introspector: An introspection function taking a
/// `TableIdentifier` as the only parameter
private func introspect<T>(
tableNamed tableName: String,
inSchemaNamed schemaName: String,
using introspector: (TableIdentifier) throws -> T?
) throws -> T {
let schemaIdentifier = try schemaIdentifier(named: schemaName)
if let result = try introspector(TableIdentifier(schemaID: schemaIdentifier, name: tableName)) {
return result
} else {
throw DatabaseError.noSuchTable(tableName)
}
}
}
extension Database {
/// Returns the columns in a table or a view.
///
/// When `schemaName` is not specified, known schemas are iterated in
/// SQLite resolution order and the first matching result is returned.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let columns = try db.columns(in: "player")
/// for column in columns {
/// print(column.name)
/// }
/// }
/// ```
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, if
/// the specified schema does not exist,or if no such table or view
/// with this name exists in the main or temp schema, or in an attached
/// database.
public func columns(in tableName: String, in schemaName: String? = nil) throws -> [ColumnInfo] {
if let schemaName {
return try introspect(tableNamed: tableName, inSchemaNamed: schemaName, using: columns(in:))
}
for schemaIdentifier in try schemaIdentifiers() {
if let result = try columns(in: TableIdentifier(schemaID: schemaIdentifier, name: tableName)) {
return result
}
}
throw DatabaseError.noSuchTable(tableName)
}
/// Returns nil if table does not exist
private func columns(in table: TableIdentifier) throws -> [ColumnInfo]? {
if let columns = schemaCache[table.schemaID].columns(in: table.name) {
return columns.value
}
// https://www.sqlite.org/pragma.html
//
// > PRAGMA database.table_info(table-name);
// >
// > This pragma returns one row for each column in the named table.
// > Columns in the result set include the column name, data type,
// > whether or not the column can be NULL, and the default value for
// > the column. The "pk" column in the result set is zero for columns
// > that are not part of the primary key, and is the index of the
// > column in the primary key for columns that are part of the primary
// > key.
//
// sqlite> CREATE TABLE players (
// id INTEGER PRIMARY KEY,
// firstName TEXT,
// lastName TEXT);
//
// sqlite> PRAGMA table_info("players");
// cid | name | type | notnull | dflt_value | pk |
// 0 | id | INTEGER | 0 | NULL | 1 |
// 1 | name | TEXT | 0 | NULL | 0 |
// 2 | score | INTEGER | 0 | NULL | 0 |
//
//
// PRAGMA table_info does not expose hidden and generated columns. For
// that, we need PRAGMA table_xinfo, introduced in SQLite 3.26.0:
// https://sqlite.org/releaselog/3_26_0.html