/
Row.swift
1102 lines (962 loc) · 40.2 KB
/
Row.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 Foundation
#if SWIFT_PACKAGE
import CSQLite
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// A database row.
public final class Row : Equatable, Hashable, RandomAccessCollection, ExpressibleByDictionaryLiteral, CustomStringConvertible {
let impl: RowImpl
/// Unless we are producing a row array, we use a single row when iterating
/// a statement:
///
/// let rows = try Row.fetchCursor(db, "SELECT ...")
/// let players = try Player.fetchAll(db, "SELECT ...")
///
/// This row keeps an unmanaged reference to the statement, and a handle to
/// the sqlite statement, so that we avoid many retain/release invocations.
///
/// The statementRef is released in deinit.
let statementRef: Unmanaged<SelectStatement>?
let sqliteStatement: SQLiteStatement?
/// The number of columns in the row.
public let count: Int
// MARK: - Building rows
/// Creates an empty row.
public convenience init() {
self.init(impl: EmptyRowImpl())
}
/// Creates a row from a dictionary of values.
public convenience init(_ dictionary: [String: DatabaseValueConvertible?]) {
self.init(impl: ArrayRowImpl(columns: dictionary.map { ($0, $1?.databaseValue ?? .null) }))
}
/// Creates a row from [AnyHashable: Any].
///
/// The result is nil unless all dictionary keys are strings, and values
/// adopt DatabaseValueConvertible.
public convenience init?(_ dictionary: [AnyHashable: Any]) {
var initDictionary = [String: DatabaseValueConvertible?]()
for (key, value) in dictionary {
guard let columnName = key as? String else {
return nil
}
guard let dbValue = DatabaseValue(value: value) else {
return nil
}
initDictionary[columnName] = dbValue
}
self.init(initDictionary)
}
/// Returns an immutable copy of the row.
///
/// For performance reasons, rows fetched from a cursor are reused during
/// the iteration of a query: make sure to make a copy of it whenever you
/// want to keep a specific one: `row.copy()`.
public func copy() -> Row {
return impl.copy(self)
}
// MARK: - Not Public
/// Returns true if and only if the row was fetched from a database.
var isFetched: Bool {
return impl.isFetched
}
deinit {
statementRef?.release()
}
/// Creates a row that maps an SQLite statement. Further calls to
/// sqlite3_step() modify the row.
///
/// The row is implemented on top of StatementRowImpl, which grants *direct*
/// access to the SQLite statement. Iteration of the statement does modify
/// the row.
init(statement: SelectStatement) {
let statementRef = Unmanaged.passRetained(statement) // released in deinit
self.statementRef = statementRef
self.sqliteStatement = statement.sqliteStatement
self.impl = StatementRowImpl(sqliteStatement: statement.sqliteStatement, statementRef: statementRef)
self.count = Int(sqlite3_column_count(sqliteStatement))
}
/// Creates a row that contain a copy of the current state of the
/// SQLite statement. Further calls to sqlite3_step() do not modify the row.
///
/// The row is implemented on top of StatementCopyRowImpl, which *copies*
/// the values from the SQLite statement so that further iteration of the
/// statement does not modify the row.
convenience init(copiedFromSQLiteStatement sqliteStatement: SQLiteStatement, statementRef: Unmanaged<SelectStatement>) {
self.init(impl: StatementCopyRowImpl(sqliteStatement: sqliteStatement, columnNames: statementRef.takeUnretainedValue().columnNames))
}
init(impl: RowImpl) {
self.impl = impl
self.count = impl.count
self.statementRef = nil
self.sqliteStatement = nil
}
}
extension Row {
// MARK: - Columns
/// The names of columns in the row.
///
/// Columns appear in the same order as they occur as the `.0` member
/// of column-value pairs in `self`.
public var columnNames: LazyMapCollection<Row, String> {
return lazy.map { $0.0 }
}
/// Returns true if and only if the row has that column.
///
/// This method is case-insensitive.
public func hasColumn(_ columnName: String) -> Bool {
return impl.index(ofColumn: columnName) != nil
}
}
extension Row {
// MARK: - Extracting Values
/// Returns Int64, Double, String, Data or nil, depending on the value
/// stored at the given index.
///
/// Indexes span from 0 for the leftmost column to (row.count - 1) for the
/// righmost column.
public subscript(_ index: Int) -> DatabaseValueConvertible? {
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
return impl.databaseValue(atUncheckedIndex: index).storage.value
}
/// Returns the value at given index, converted to the requested type.
///
/// Indexes span from 0 for the leftmost column to (row.count - 1) for the
/// righmost column.
///
/// If the SQLite value is NULL, the result is nil. Otherwise the SQLite
/// value is converted to the requested type `Value`. Should this conversion
/// fail, a fatal error is raised.
public subscript<Value: DatabaseValueConvertible>(_ index: Int) -> Value? {
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
}
/// Returns the value at given index, converted to the requested type.
///
/// Indexes span from 0 for the leftmost column to (row.count - 1) for the
/// righmost column.
///
/// If the SQLite value is NULL, the result is nil. Otherwise the SQLite
/// value is converted to the requested type `Value`. Should this conversion
/// fail, a fatal error is raised.
///
/// This method exists as an optimization opportunity for types that adopt
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
/// (see https://www.sqlite.org/datatype3.html).
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ index: Int) -> Value? {
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
if let sqliteStatement = sqliteStatement { // fast path
return Row.statementColumnConvertible(atUncheckedIndex: Int32(index), in: sqliteStatement)
}
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
}
/// Returns the value at given index, converted to the requested type.
///
/// Indexes span from 0 for the leftmost column to (row.count - 1) for the
/// righmost column.
///
/// This method crashes if the fetched SQLite value is NULL, or if the
/// SQLite value can not be converted to `Value`.
public subscript<Value: DatabaseValueConvertible>(_ index: Int) -> Value {
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
}
/// Returns the value at given index, converted to the requested type.
///
/// Indexes span from 0 for the leftmost column to (row.count - 1) for the
/// righmost column.
///
/// This method crashes if the fetched SQLite value is NULL, or if the
/// SQLite value can not be converted to `Value`.
///
/// This method exists as an optimization opportunity for types that adopt
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
/// (see https://www.sqlite.org/datatype3.html).
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ index: Int) -> Value {
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
if let sqliteStatement = sqliteStatement { // fast path
return Row.statementColumnConvertible(atUncheckedIndex: Int32(index), in: sqliteStatement)
}
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
}
/// Returns Int64, Double, String, Data or nil, depending on the value
/// stored at the given column.
///
/// Column name lookup is case-insensitive, and when several columns have
/// the same name, the leftmost column is considered.
///
/// The result is nil if the row does not contain the column.
public subscript(_ columnName: String) -> DatabaseValueConvertible? {
// IMPLEMENTATION NOTE
// This method has a single know use case: checking if the value is nil,
// as in:
//
// if row["foo"] != nil { ... }
//
// Without this method, the code above would not compile.
guard let index = impl.index(ofColumn: columnName) else {
return nil
}
return impl.databaseValue(atUncheckedIndex: index).storage.value
}
/// Returns the value at given column, converted to the requested type.
///
/// Column name lookup is case-insensitive, and when several columns have
/// the same name, the leftmost column is considered.
///
/// If the column is missing or if the SQLite value is NULL, the result is
/// nil. Otherwise the SQLite value is converted to the requested type
/// `Value`. Should this conversion fail, a fatal error is raised.
public subscript<Value: DatabaseValueConvertible>(_ columnName: String) -> Value? {
guard let index = impl.index(ofColumn: columnName) else {
return nil
}
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
}
/// Returns the value at given column, converted to the requested type.
///
/// Column name lookup is case-insensitive, and when several columns have
/// the same name, the leftmost column is considered.
///
/// If the column is missing or if the SQLite value is NULL, the result is
/// nil. Otherwise the SQLite value is converted to the requested type
/// `Value`. Should this conversion fail, a fatal error is raised.
///
/// This method exists as an optimization opportunity for types that adopt
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
/// (see https://www.sqlite.org/datatype3.html).
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ columnName: String) -> Value? {
guard let index = impl.index(ofColumn: columnName) else {
return nil
}
if let sqliteStatement = sqliteStatement { // fast path
return Row.statementColumnConvertible(atUncheckedIndex: Int32(index), in: sqliteStatement)
}
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
}
/// Returns the value at given column, converted to the requested type.
///
/// Column name lookup is case-insensitive, and when several columns have
/// the same name, the leftmost column is considered.
///
/// If the row does not contain the column, a fatal error is raised.
///
/// This method crashes if the fetched SQLite value is NULL, or if the
/// SQLite value can not be converted to `Value`.
public subscript<Value: DatabaseValueConvertible>(_ columnName: String) -> Value {
guard let index = impl.index(ofColumn: columnName) else {
// Programmer error
fatalError("no such column: \(columnName)")
}
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
}
/// Returns the value at given column, converted to the requested type.
///
/// Column name lookup is case-insensitive, and when several columns have
/// the same name, the leftmost column is considered.
///
/// If the row does not contain the column, a fatal error is raised.
///
/// This method crashes if the fetched SQLite value is NULL, or if the
/// SQLite value can not be converted to `Value`.
///
/// This method exists as an optimization opportunity for types that adopt
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
/// (see https://www.sqlite.org/datatype3.html).
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ columnName: String) -> Value {
guard let index = impl.index(ofColumn: columnName) else {
// Programmer error
fatalError("no such column: \(columnName)")
}
if let sqliteStatement = sqliteStatement { // fast path
return Row.statementColumnConvertible(atUncheckedIndex: Int32(index), in: sqliteStatement)
}
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
}
/// Returns Int64, Double, String, NSData or nil, depending on the value
/// stored at the given column.
///
/// Column name lookup is case-insensitive, and when several columns have
/// the same name, the leftmost column is considered.
///
/// The result is nil if the row does not contain the column.
public subscript(_ column: Column) -> DatabaseValueConvertible? {
return self[column.name]
}
/// Returns the value at given column, converted to the requested type.
///
/// Column name lookup is case-insensitive, and when several columns have
/// the same name, the leftmost column is considered.
///
/// If the column is missing or if the SQLite value is NULL, the result is
/// nil. Otherwise the SQLite value is converted to the requested type
/// `Value`. Should this conversion fail, a fatal error is raised.
public subscript<Value: DatabaseValueConvertible>(_ column: Column) -> Value? {
return self[column.name]
}
/// Returns the value at given column, converted to the requested type.
///
/// Column name lookup is case-insensitive, and when several columns have
/// the same name, the leftmost column is considered.
///
/// If the column is missing or if the SQLite value is NULL, the result is
/// nil. Otherwise the SQLite value is converted to the requested type
/// `Value`. Should this conversion fail, a fatal error is raised.
///
/// This method exists as an optimization opportunity for types that adopt
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
/// (see https://www.sqlite.org/datatype3.html).
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ column: Column) -> Value? {
return self[column.name]
}
/// Returns the value at given column, converted to the requested type.
///
/// Column name lookup is case-insensitive, and when several columns have
/// the same name, the leftmost column is considered.
///
/// If the row does not contain the column, a fatal error is raised.
///
/// This method crashes if the fetched SQLite value is NULL, or if the
/// SQLite value can not be converted to `Value`.
public subscript<Value: DatabaseValueConvertible>(_ column: Column) -> Value {
return self[column.name]
}
/// Returns the value at given column, converted to the requested type.
///
/// Column name lookup is case-insensitive, and when several columns have
/// the same name, the leftmost column is considered.
///
/// If the row does not contain the column, a fatal error is raised.
///
/// This method crashes if the fetched SQLite value is NULL, or if the
/// SQLite value can not be converted to `Value`.
///
/// This method exists as an optimization opportunity for types that adopt
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
/// (see https://www.sqlite.org/datatype3.html).
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ column: Column) -> Value {
return self[column.name]
}
/// Returns the optional Data at given index.
///
/// Indexes span from 0 for the leftmost column to (row.count - 1) for the
/// righmost column.
///
/// If the SQLite value is NULL, the result is nil. If the SQLite value can
/// not be converted to Data, a fatal error is raised.
///
/// The returned data does not owns its bytes: it must not be used longer
/// than the row's lifetime.
public func dataNoCopy(atIndex index: Int) -> Data? {
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
return impl.dataNoCopy(atUncheckedIndex: index)
}
/// Returns the optional Data at given column.
///
/// Column name lookup is case-insensitive, and when several columns have
/// the same name, the leftmost column is considered.
///
/// If the column is missing or if the SQLite value is NULL, the result is
/// nil. If the SQLite value can not be converted to Data, a fatal error
/// is raised.
///
/// The returned data does not owns its bytes: it must not be used longer
/// than the row's lifetime.
public func dataNoCopy(named columnName: String) -> Data? {
guard let index = impl.index(ofColumn: columnName) else {
return nil
}
return impl.dataNoCopy(atUncheckedIndex: index)
}
/// Returns the optional `NSData` at given column.
///
/// Column name lookup is case-insensitive, and when several columns have
/// the same name, the leftmost column is considered.
///
/// If the column is missing or if the SQLite value is NULL, the result is
/// nil. If the SQLite value can not be converted to NSData, a fatal error
/// is raised.
///
/// The returned data does not owns its bytes: it must not be used longer
/// than the row's lifetime.
public func dataNoCopy(_ column: Column) -> Data? {
return dataNoCopy(named: column.name)
}
}
extension Row {
// MARK: - Extracting DatabaseValue
/// The database values in the row.
///
/// Values appear in the same order as they occur as the `.1` member
/// of column-value pairs in `self`.
public var databaseValues: LazyMapCollection<Row, DatabaseValue> {
return lazy.map { $0.1 }
}
}
extension Row {
// MARK: - Helpers
@inline(__always)
private static func statementColumnConvertible<Value: StatementColumnConvertible>(atUncheckedIndex index: Int32, in sqliteStatement: SQLiteStatement) -> Value? {
guard sqlite3_column_type(sqliteStatement, index) != SQLITE_NULL else {
return nil
}
return Value.init(sqliteStatement: sqliteStatement, index: index)
}
@inline(__always)
private static func statementColumnConvertible<Value: StatementColumnConvertible>(atUncheckedIndex index: Int32, in sqliteStatement: SQLiteStatement) -> Value {
guard sqlite3_column_type(sqliteStatement, index) != SQLITE_NULL else {
// Programmer error
fatalError("could not convert database value NULL to \(Value.self)")
}
return Value.init(sqliteStatement: sqliteStatement, index: index)
}
}
extension Row {
// MARK: - Scopes
/// Returns a scoped row, if the row was fetched along with a row adapter
/// that defines this scope.
///
/// // Two adapters
/// let fooAdapter = ColumnMapping(["value": "foo"])
/// let barAdapter = ColumnMapping(["value": "bar"])
///
/// // Define scopes
/// let adapter = ScopeAdapter([
/// "foo": fooAdapter,
/// "bar": barAdapter])
///
/// // Fetch
/// let sql = "SELECT 'foo' AS foo, 'bar' AS bar"
/// let row = try Row.fetchOne(db, sql, adapter: adapter)!
///
/// // Scoped rows:
/// if let fooRow = row.scoped(on: "foo") {
/// fooRow["value"] // "foo"
/// }
/// if let barRow = row.scopeed(on: "bar") {
/// barRow["value"] // "bar"
/// }
public func scoped(on name: String) -> Row? {
return impl.scoped(on: name)
}
}
/// A cursor of database rows. For example:
///
/// try dbQueue.inDatabase { db in
/// let rows: RowCursor = try Row.fetchCursor(db, "SELECT * FROM players")
/// }
public final class RowCursor : Cursor {
public let statement: SelectStatement
private let sqliteStatement: SQLiteStatement
private let row: Row // Reused for performance
private var done = false
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
self.statement = statement
self.row = try Row(statement: statement).adapted(with: adapter, layout: statement)
self.sqliteStatement = statement.sqliteStatement
statement.cursorReset(arguments: arguments)
}
/// :nodoc:
public func next() throws -> Row? {
if done { return nil }
switch sqlite3_step(sqliteStatement) {
case SQLITE_DONE:
done = true
return nil
case SQLITE_ROW:
return row
case let code:
statement.database.selectStatementDidFail(statement)
throw DatabaseError(resultCode: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments)
}
}
}
extension Row {
// MARK: - Fetching From SelectStatement
/// Returns a cursor over rows fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT ...")
/// let rows = try Row.fetchCursor(statement) // RowCursor
/// while let row = try rows.next() { // Row
/// let id: Int64 = row[0]
/// let name: String = row[1]
/// }
///
/// Fetched rows are reused during the cursor iteration: don't turn a row
/// cursor into an array with `Array(rows)` or `rows.filter { ... }` since
/// you would not get the distinct rows you expect. Use `Row.fetchAll(...)`
/// instead.
///
/// For the same reason, make sure you make a copy whenever you extract a
/// row for later use: `row.copy()`.
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// The cursor must be iterated in a protected dispath queue.
///
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched rows.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RowCursor {
return try RowCursor(statement: statement, arguments: arguments, adapter: adapter)
}
/// Returns an array of rows fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT ...")
/// let rows = try Row.fetchAll(statement)
///
/// - parameters:
/// - statement: The statement to run.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: An array of rows.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Row] {
// The cursor reuses a single mutable row. Return immutable copies.
return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter).map { $0.copy() })
}
/// Returns a single row fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT ...")
/// let row = try Row.fetchOne(statement)
///
/// - parameters:
/// - statement: The statement to run.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: An optional row.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Row? {
// The cursor reuses a single mutable row. Return an immutable copy.
return try fetchCursor(statement, arguments: arguments, adapter: adapter).next().map { $0.copy() }
}
}
extension Row {
// MARK: - Fetching From Request
/// Returns a cursor over rows fetched from a fetch request.
///
/// let idColumn = Column("id")
/// let nameColumn = Column("name")
/// let request = Player.select(idColumn, nameColumn)
/// let rows = try Row.fetchCursor(db) // RowCursor
/// while let row = try rows.next() { // Row
/// let id: Int64 = row[0]
/// let name: String = row[1]
/// }
///
/// Fetched rows are reused during the cursor iteration: don't turn a row
/// cursor into an array with `Array(rows)` or `rows.filter { ... }` since
/// you would not get the distinct rows you expect. Use `Row.fetchAll(...)`
/// instead.
///
/// For the same reason, make sure you make a copy whenever you extract a
/// row for later use: `row.copy()`.
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// The cursor must be iterated in a protected dispath queue.
///
/// - parameters:
/// - db: A database connection.
/// - request: A fetch request.
/// - returns: A cursor over fetched rows.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ request: Request) throws -> RowCursor {
let (statement, adapter) = try request.prepare(db)
return try fetchCursor(statement, adapter: adapter)
}
/// Returns an array of rows fetched from a fetch request.
///
/// let idColumn = Column("id")
/// let nameColumn = Column("name")
/// let request = Player.select(idColumn, nameColumn)
/// let rows = try Row.fetchAll(db, request)
///
/// - parameter db: A database connection.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, _ request: Request) throws -> [Row] {
let (statement, adapter) = try request.prepare(db)
return try fetchAll(statement, adapter: adapter)
}
/// Returns a single row fetched from a fetch request.
///
/// let idColumn = Column("id")
/// let nameColumn = Column("name")
/// let request = Player.select(idColumn, nameColumn)
/// let row = try Row.fetchOne(db, request)
///
/// - parameter db: A database connection.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne(_ db: Database, _ request: Request) throws -> Row? {
let (statement, adapter) = try request.prepare(db)
return try fetchOne(statement, adapter: adapter)
}
}
extension Row {
// MARK: - Fetching From SQL
/// Returns a cursor over rows fetched from an SQL query.
///
/// let rows = try Row.fetchCursor(db, "SELECT id, name FROM players") // RowCursor
/// while let row = try rows.next() { // Row
/// let id: Int64 = row[0]
/// let name: String = row[1]
/// }
///
/// Fetched rows are reused during the cursor iteration: don't turn a row
/// cursor into an array with `Array(rows)` or `rows.filter { ... }` since
/// you would not get the distinct rows you expect. Use `Row.fetchAll(...)`
/// instead.
///
/// For the same reason, make sure you make a copy whenever you extract a
/// row for later use: `row.copy()`.
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// The cursor must be iterated in a protected dispath queue.
///
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched rows.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RowCursor {
return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
}
/// Returns an array of rows fetched from an SQL query.
///
/// let rows = try Row.fetchAll(db, "SELECT ...")
///
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: An array of rows.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Row] {
return try fetchAll(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
}
/// Returns a single row fetched from an SQL query.
///
/// let row = try Row.fetchOne(db, "SELECT ...")
///
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: An optional row.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Row? {
return try fetchOne(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
}
}
// ExpressibleByDictionaryLiteral
extension Row {
/// Creates a row initialized with elements. Column order is preserved, and
/// duplicated columns names are allowed.
///
/// let row: Row = ["foo": 1, "foo": "bar", "baz": nil]
/// print(row)
/// // Prints <Row foo:1 foo:"bar" baz:NULL>
public convenience init(dictionaryLiteral elements: (String, DatabaseValueConvertible?)...) {
self.init(impl: ArrayRowImpl(columns: elements.map { ($0, $1?.databaseValue ?? .null) }))
}
}
// RandomAccessCollection
extension Row {
// MARK: - Row as a Collection of (ColumnName, DatabaseValue) Pairs
/// The index of the first (ColumnName, DatabaseValue) pair.
/// :nodoc:
public var startIndex: RowIndex {
return Index(0)
}
/// The "past-the-end" index, successor of the index of the last
/// (ColumnName, DatabaseValue) pair.
/// :nodoc:
public var endIndex: RowIndex {
return Index(count)
}
/// Accesses the (ColumnName, DatabaseValue) pair at given index.
public subscript(position: RowIndex) -> (String, DatabaseValue) {
let index = position.index
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
return (
impl.columnName(atUncheckedIndex: index),
impl.databaseValue(atUncheckedIndex: index))
}
}
// Equatable
extension Row {
/// Returns true if and only if both rows have the same columns and values,
/// in the same order. Columns are compared in a case-sensitive way.
/// :nodoc:
public static func == (lhs: Row, rhs: Row) -> Bool {
if lhs === rhs {
return true
}
guard lhs.count == rhs.count else {
return false
}
for ((lcol, lval), (rcol, rval)) in zip(lhs, rhs) {
guard lcol == rcol else {
return false
}
guard lval == rval else {
return false
}
}
let lscopeNames = lhs.impl.scopeNames
let rscopeNames = rhs.impl.scopeNames
guard lscopeNames == rscopeNames else {
return false
}
for name in lscopeNames {
let lscope = lhs.scoped(on: name)
let rscope = rhs.scoped(on: name)
guard lscope == rscope else {
return false
}
}
return true
}
}
// Hashable
extension Row {
/// The hash value
/// :nodoc:
public var hashValue: Int {
return columnNames.reduce(0) { (acc, column) in acc ^ column.hashValue } ^
databaseValues.reduce(0) { (acc, dbValue) in acc ^ dbValue.hashValue }
}
}
// CustomStringConvertible
extension Row {
/// :nodoc:
public var description: String {
return "<Row"
+ map { (column, dbValue) in
" \(column):\(dbValue)"
}.joined(separator: "")
+ ">"
}
}
// MARK: - RowIndex
/// Indexes to (ColumnName, DatabaseValue) pairs in a database row.
public struct RowIndex : Comparable, Strideable {
let index: Int
init(_ index: Int) { self.index = index }
}
// Comparable
extension RowIndex {
/// :nodoc:
public static func == (lhs: RowIndex, rhs: RowIndex) -> Bool {
return lhs.index == rhs.index
}
/// :nodoc:
public static func < (lhs: RowIndex, rhs: RowIndex) -> Bool {
return lhs.index < rhs.index
}
}
// Strideable: support for Row: RandomAccessCollection
extension RowIndex {
/// :nodoc:
public func distance(to other: RowIndex) -> Int {
return other.index - index
}
/// :nodoc:
public func advanced(by n: Int) -> RowIndex {
return RowIndex(index + n)
}
}
// MARK: - RowImpl
// The protocol for Row underlying implementation
protocol RowImpl {
var count: Int { get }
var isFetched: Bool { get }
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue
func dataNoCopy(atUncheckedIndex index:Int) -> Data?
func columnName(atUncheckedIndex index: Int) -> String
// This method MUST be case-insensitive, and returns the index of the
// leftmost column that matches *name*.
func index(ofColumn name: String) -> Int?
func scoped(on name: String) -> Row?
var scopeNames: Set<String> { get }
// row.impl is guaranteed to be self.
func copy(_ row: Row) -> Row
}
/// See Row.init(dictionary:)
private struct ArrayRowImpl : RowImpl {
let columns: [(String, DatabaseValue)]
init(columns: [(String, DatabaseValue)]) {
self.columns = columns
}
var count: Int {
return columns.count
}
var isFetched: Bool {
return false
}
func dataNoCopy(atUncheckedIndex index:Int) -> Data? {
return databaseValue(atUncheckedIndex: index).losslessConvert()
}
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue {
return columns[index].1
}
func columnName(atUncheckedIndex index: Int) -> String {
return columns[index].0
}
// This method MUST be case-insensitive, and returns the index of the
// leftmost column that matches *name*.
func index(ofColumn name: String) -> Int? {
let lowercaseName = name.lowercased()
return columns.index { (column, _) in column.lowercased() == lowercaseName }
}
func scoped(on name: String) -> Row? {
return nil
}
var scopeNames: Set<String> {
return []
}
func copy(_ row: Row) -> Row {
return row
}
}
/// See Row.init(copiedFromStatementRef:sqliteStatement:)
private struct StatementCopyRowImpl : RowImpl {
let dbValues: ContiguousArray<DatabaseValue>
let columnNames: [String]
init(sqliteStatement: SQLiteStatement, columnNames: [String]) {
let sqliteStatement = sqliteStatement
self.dbValues = ContiguousArray((0..<sqlite3_column_count(sqliteStatement)).map { DatabaseValue(sqliteStatement: sqliteStatement, index: $0) } as [DatabaseValue])
self.columnNames = columnNames
}
var count: Int {
return columnNames.count
}
var isFetched: Bool {
return true
}
func dataNoCopy(atUncheckedIndex index:Int) -> Data? {
return databaseValue(atUncheckedIndex: index).losslessConvert()
}
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue {
return dbValues[index]
}
func columnName(atUncheckedIndex index: Int) -> String {
return columnNames[index]
}
// This method MUST be case-insensitive, and returns the index of the
// leftmost column that matches *name*.
func index(ofColumn name: String) -> Int? {
let lowercaseName = name.lowercased()
return columnNames.index { $0.lowercased() == lowercaseName }
}
func scoped(on name: String) -> Row? {
return nil
}
var scopeNames: Set<String> {
return []
}
func copy(_ row: Row) -> Row {
return row
}
}
/// See Row.init(statement:)
private struct StatementRowImpl : RowImpl {
let statementRef: Unmanaged<SelectStatement>
let sqliteStatement: SQLiteStatement
let lowercaseColumnIndexes: [String: Int]
init(sqliteStatement: SQLiteStatement, statementRef: Unmanaged<SelectStatement>) {