-
-
Notifications
You must be signed in to change notification settings - Fork 744
/
Copy pathRow.swift
2628 lines (2419 loc) · 87.7 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 C SQLite functions
#if GRDBCIPHER
import SQLCipher
#elseif SWIFT_PACKAGE
import GRDBSQLite
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
/// A database row.
///
/// To get `Row` instances, you will generally fetch them from a ``Database``
/// instance. For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let rows = try Row.fetchCursor(db, sql: """
/// SELECT * FROM player
/// """)
/// while let row = try rows.next() {
/// let id: Int64 = row["id"]
/// let name: String = row["name"]
/// }
/// }
/// ```
///
/// ## Topics
///
/// ### Creating Rows
///
/// - ``init()``
/// - ``init(_:)-5uezw``
/// - ``init(_:)-65by6``
///
/// ### Copying a Row
///
/// - ``copy()``
///
/// ### Row Informations
///
/// - ``columnNames``
/// - ``containsNonNullValue``
/// - ``count-5flaw``
/// - ``databaseValues``
/// - ``hasColumn(_:)``
/// - ``hasNull(atIndex:)``
///
/// ### Accessing Row Values by Int Index
///
/// - ``subscript(_:)-9c1fw``
/// - ``subscript(_:)-3jhwm``
/// - ``subscript(_:)-7krrg``
/// - ``withUnsafeData(atIndex:_:)``
/// - ``dataNoCopy(atIndex:)``
///
/// ### Accessing Row Values by Column Name
///
/// - ``subscript(_:)-3tp8o``
/// - ``subscript(_:)-4k8od``
/// - ``subscript(_:)-9rbo7``
/// - ``coalesce(_:)-359k7``
/// - ``coalesce(_:)-6nbah``
/// - ``withUnsafeData(named:_:)``
/// - ``dataNoCopy(named:)``
///
/// ### Accessing Row Values by Column
///
/// - ``subscript(_:)-9txgm``
/// - ``subscript(_:)-2esg7``
/// - ``subscript(_:)-wl9a``
/// - ``withUnsafeData(at:_:)``
/// - ``dataNoCopy(_:)``
///
/// ### Row Scopes & Associated Rows
///
/// - ``prefetchedRows``
/// - ``scopes``
/// - ``scopesTree``
/// - ``unadapted``
/// - ``unscoped``
/// - ``subscript(_:)-4dx01``
/// - ``subscript(_:)-8god3``
/// - ``subscript(_:)-jwnx``
/// - ``subscript(_:)-6ge6t``
/// - ``PrefetchedRowsView``
/// - ``ScopesTreeView``
/// - ``ScopesView``
///
/// ### Fetching Rows from Raw SQL
///
/// - ``fetchCursor(_:sql:arguments:adapter:)``
/// - ``fetchAll(_:sql:arguments:adapter:)``
/// - ``fetchSet(_:sql:arguments:adapter:)``
/// - ``fetchOne(_:sql:arguments:adapter:)``
///
/// ### Fetching Rows from a Prepared Statement
///
/// - ``fetchCursor(_:arguments:adapter:)``
/// - ``fetchAll(_:arguments:adapter:)``
/// - ``fetchSet(_:arguments:adapter:)``
/// - ``fetchOne(_:arguments:adapter:)``
///
/// ### Fetching Rows from a Request
///
/// - ``fetchCursor(_:_:)``
/// - ``fetchAll(_:_:)``
/// - ``fetchSet(_:_:)``
/// - ``fetchOne(_:_:)``
///
/// ### Row as RandomAccessCollection
///
/// - ``count-5flaw``
/// - ``subscript(_:)-68yae``
/// - ``Index``
///
/// ### Adapting Rows
///
/// - ``RowAdapter``
///
/// ### Supporting Types
///
/// - ``RowCursor``
public final class Row {
// It is not a violation of the Demeter law when another type uses this
// property, which is exposed for optimizations.
let impl: any RowImpl
/// Unless we are producing a row array, we use a single row when iterating
/// a statement:
///
/// let rows = try Row.fetchCursor(db, sql: "SELECT ...")
/// let players = try Player.fetchAll(db, sql: "SELECT ...")
let statement: Statement?
@usableFromInline
let sqliteStatement: SQLiteStatement?
/// The number of columns in the row.
public let count: Int
/// A view on the prefetched associated rows.
///
/// Prefetched rows are defined by the ``JoinableRequest/including(all:)``
/// request method.
///
/// For example:
///
/// ```swift
/// struct Author: TableRecord {
/// static let books = hasMany(Book.self)
/// }
///
/// struct Book: TableRecord { }
///
/// let request = Author.including(all: Author.books)
/// let authorRow = try Row.fetchOne(db, request)!
///
/// print(authorRow)
/// // Prints [id:1, name:"Herman Melville"]
///
/// let bookRows = authorRow.prefetchedRows["books"]!
/// print(bookRows[0])
/// // Prints [id:42, title:"Moby-Dick", authorId:1]
/// print(bookRows[1])
/// // Prints [id:57, title:"Pierre", authorId:1]
/// ```
public internal(set) var prefetchedRows = PrefetchedRowsView()
// MARK: - Building rows
/// Creates an empty row.
public convenience init() {
self.init(impl: EmptyRowImpl())
}
/// Creates a row from a dictionary of database values.
public convenience init(_ dictionary: [String: (any DatabaseValueConvertible)?]) {
self.init(impl: ArrayRowImpl(columns: dictionary.map { ($0, $1?.databaseValue ?? .null) }))
}
/// Creates a row from a dictionary.
///
/// The result is nil unless all dictionary keys are strings, and values
/// conform to ``DatabaseValueConvertible``.
public convenience init?(_ dictionary: [AnyHashable: Any]) {
var initDictionary = [String: (any 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 {
impl.copiedRow(self)
}
// MARK: - Not Public
/// Returns true if and only if the row was fetched from a database.
var isFetched: Bool { impl.isFetched }
/// 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: Statement) {
self.statement = statement
self.sqliteStatement = statement.sqliteStatement
self.impl = StatementRowImpl(sqliteStatement: statement.sqliteStatement, statement: statement)
self.count = Int(sqlite3_column_count(sqliteStatement))
}
/// Creates a row that maps an SQLite statement. Further calls to
/// sqlite3_step() modify the row.
init(sqliteStatement: SQLiteStatement) {
self.statement = nil
self.sqliteStatement = sqliteStatement
self.impl = SQLiteStatementRowImpl(sqliteStatement: sqliteStatement)
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,
statement: Statement)
{
self.init(impl: StatementCopyRowImpl(
sqliteStatement: sqliteStatement,
columnNames: statement.columnNames))
}
init(impl: any RowImpl) {
self.statement = nil
self.sqliteStatement = nil
self.impl = impl
self.count = impl.count
}
}
// Explicit non-conformance to Sendable: a row contains transient
// information. TODO GRDB7: split non sendable statement rows from sendable
// copied rows.
@available(*, unavailable)
extension Row: Sendable { }
extension Row {
// MARK: - Columns
/// The names of columns in the row, from left to right.
///
/// 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> {
lazy.map { $0.0 }
}
/// Returns whether the row has one column with the given name
/// (case-insensitive).
public func hasColumn(_ columnName: String) -> Bool {
index(forColumn: columnName) != nil
}
@usableFromInline
func index(forColumn name: String) -> Int? {
impl.index(forColumn: name)
}
}
extension Row {
// MARK: - Extracting Values
/// Fatal errors if index is out of bounds
@inline(__always)
@usableFromInline
/* private */ func _checkIndex(_ index: Int, file: StaticString = #file, line: UInt = #line) {
GRDBPrecondition(index >= 0 && index < count, "row index out of range", file: file, line: line)
}
/// Returns a boolean value indicating if the row contains one value this
/// is not `NULL`.
///
/// For example:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT 'foo', NULL")!
/// row.containsNonNullValue // true
///
/// let row = try Row.fetchOne(db, sql: "SELECT NULL, NULL")!
/// row.containsNonNullValue // false
/// ```
public var containsNonNullValue: Bool {
for i in (0..<count) where !impl.hasNull(atUncheckedIndex: i) {
return true
}
for (_, scopedRow) in scopes where scopedRow.containsNonNullValue {
return true
}
return false
}
/// Returns whether the row has a `NULL` value at given index.
///
/// Indexes span from `0` for the leftmost column to `row.count - 1` for the
/// rightmost column.
///
/// This method is equivalent to `row[index] == nil`, but may be preferred
/// in performance-critical code because it avoids decoding
/// database values.
public func hasNull(atIndex index: Int) -> Bool {
_checkIndex(index)
return impl.hasNull(atUncheckedIndex: index)
}
/// 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
/// rightmost column.
public subscript(_ index: Int) -> (any DatabaseValueConvertible)? {
_checkIndex(index)
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
/// rightmost column.
///
/// For example:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT 42")!
/// let score: Int = row[0] // 42
///
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice'")!
/// let name: String = row[0] // "Alice"
/// ```
///
/// When the database value may be nil, ask for an optional:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT NULL")!
/// let name: String? = row[0] // nil
/// ```
@inlinable
public subscript<Value: DatabaseValueConvertible>(_ index: Int) -> Value {
try! decode(Value.self, atIndex: index)
}
/// Returns the value at given index, converted to the requested type.
///
/// This method exists as an optimization opportunity for types that adopt
/// ``StatementColumnConvertible``. It can trigger [SQLite built-in
/// conversions](https://www.sqlite.org/datatype3.html).
///
/// Indexes span from `0` for the leftmost column to `row.count - 1` for the
/// rightmost column.
///
/// For example:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT 42")!
/// let score: Int = row[0] // 42
///
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice'")!
/// let name: String = row[0] // "Alice"
/// ```
///
/// When the database value may be nil, ask for an optional:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT NULL")!
/// let name: String? = row[0] // nil
/// ```
@inline(__always)
@inlinable
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ index: Int) -> Value {
try! decode(Value.self, atIndex: index)
}
/// Returns `Int64`, `Double`, `String`, `Data` or nil, depending on the
/// value stored at the given column.
///
/// Column name lookup is case-insensitive. When several columns exist with
/// the same name, the leftmost column is considered.
///
/// The result is nil if the row does not contain any column with that name.
public subscript(_ columnName: String) -> (any DatabaseValueConvertible)? {
// IMPLEMENTATION NOTE
// This method has a single known 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 = index(forColumn: 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. When several columns exist with
/// the same name, the leftmost column is considered.
///
/// For example:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")!
/// let score: Int = row["score"] // 42
///
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
/// let name: String = row["name"] // "Alice"
/// ```
///
/// When the database value may be nil, ask for an optional:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")!
/// let name: String? = row["name"] // nil
/// ```
///
/// When the column does not exist, nil is returned:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
/// let name: String? = row["missing"] // nil
/// ```
@inlinable
public subscript<Value: DatabaseValueConvertible>(_ columnName: String) -> Value {
try! decode(Value.self, forKey: columnName)
}
/// Returns the value at given column, converted to the requested type.
///
/// This method exists as an optimization opportunity for types that adopt
/// ``StatementColumnConvertible``. It can trigger [SQLite built-in
/// conversions](https://www.sqlite.org/datatype3.html).
///
/// Column name lookup is case-insensitive. When several columns exist with
/// the same name, the leftmost column is considered.
///
/// For example:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")!
/// let score: Int = row["score"] // 42
///
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
/// let name: String = row["name"] // "Alice"
/// ```
///
/// When the database value may be nil, ask for an optional:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")!
/// let name: String? = row["name"] // nil
/// ```
///
/// When the column does not exist, nil is returned:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
/// let name: String? = row["missing"] // nil
/// ```
@inlinable
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ columnName: String) -> Value {
try! decode(Value.self, forKey: columnName)
}
/// Returns `Int64`, `Double`, `String`, `Data` or nil, depending on the
/// value stored at the given column.
///
/// Column name lookup is case-insensitive. When several columns exist with
/// the same name, the leftmost column is considered.
///
/// The result is nil if the row does not contain any column with that name.
public subscript(_ column: some ColumnExpression) -> (any DatabaseValueConvertible)? {
self[column.name]
}
/// Returns the value at given column, converted to the requested type.
///
/// Column name lookup is case-insensitive. When several columns exist with
/// the same name, the leftmost column is considered.
///
/// For example:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")!
/// let score: Int = row[Column("score")] // 42
///
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
/// let name: String = row[Column("name")] // "Alice"
/// ```
///
/// When the database value may be nil, ask for an optional:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")!
/// let name: String? = row[Column("name")] // nil
/// ```
///
/// When the column does not exist, nil is returned:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
/// let name: String? = row[Column("missing")] // nil
/// ```
@inlinable
public subscript<Value: DatabaseValueConvertible>(_ column: some ColumnExpression) -> Value {
try! decode(Value.self, forKey: column.name)
}
/// Returns the value at given column, converted to the requested type.
///
/// This method exists as an optimization opportunity for types that adopt
/// ``StatementColumnConvertible``. It can trigger [SQLite built-in
/// conversions](https://www.sqlite.org/datatype3.html).
///
/// Column name lookup is case-insensitive. When several columns exist with
/// the same name, the leftmost column is considered.
///
/// For example:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")!
/// let score: Int = row[Column("score")] // 42
///
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
/// let name: String = row[Column("name")] // "Alice"
/// ```
///
/// When the database value may be nil, ask for an optional:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")!
/// let name: String? = row[Column("name")] // nil
/// ```
///
/// When the column does not exist, nil is returned:
///
/// ```swift
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
/// let name: String? = row[Column("missing")] // nil
/// ```
@inlinable
public subscript<Value>(_ column: some ColumnExpression)
-> Value
where Value: DatabaseValueConvertible & StatementColumnConvertible
{
try! decode(Value.self, forKey: column.name)
}
/// Calls the given closure with the `Data` at given index.
///
/// Indexes span from `0` for the leftmost column to `row.count - 1` for the
/// rightmost column.
///
/// If the SQLite value is `NULL`, the data is nil. If the SQLite value can
/// not be converted to `Data`, an error is thrown.
///
/// - warning: The `Data` argument to the body must not be stored or used
/// outside of the lifetime of the call to the closure.
public func withUnsafeData<T>(atIndex index: Int, _ body: (Data?) throws -> T) throws -> T {
_checkIndex(index)
return try impl.withUnsafeData(atUncheckedIndex: index, body)
}
/// Calls the given closure with the `Data` at the given column.
///
/// Column name lookup is case-insensitive. When several columns exist with
/// the same name, the leftmost column is considered.
///
/// If the row does not contain any column with that name, or if the SQLite
/// value is `NULL`, the data is nil. If the SQLite value can not be
/// converted to `Data`, an error is thrown.
///
/// - warning: The `Data` argument to the body must not be stored or used
/// outside of the lifetime of the call to the closure.
public func withUnsafeData<T>(named columnName: String, _ body: (Data?) throws -> T) throws -> T {
guard let index = index(forColumn: columnName) else {
return try body(nil)
}
return try impl.withUnsafeData(atUncheckedIndex: index, body)
}
/// Calls the given closure with the `Data` at the given column.
///
/// Column name lookup is case-insensitive. When several columns exist with
/// the same name, the leftmost column is considered.
///
/// If the row does not contain any column with that name, or if the SQLite
/// value is `NULL`, the data is nil. If the SQLite value can not be
/// converted to `Data`, an error is thrown.
///
/// - warning: The `Data` argument to the body must not be stored or used
/// outside of the lifetime of the call to the closure.
public func withUnsafeData<T>(at column: some ColumnExpression, _ body: (Data?) throws -> T) throws -> T {
try withUnsafeData(named: column.name, body)
}
/// Returns the optional `Data` at given index.
///
/// Indexes span from `0` for the leftmost column to `row.count - 1` for the
/// rightmost 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.
@available(*, deprecated, message: "Use withUnsafeData(atIndex:_:) instead.")
public func dataNoCopy(atIndex index: Int) -> Data? {
try! withUnsafeData(atIndex: index, { $0 })
}
/// Returns the optional `Data` at given column.
///
/// Column name lookup is case-insensitive. When several columns exist with
/// 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.
@available(*, deprecated, message: "Use withUnsafeData(named:_:) instead.")
public func dataNoCopy(named columnName: String) -> Data? {
guard let index = index(forColumn: columnName) else {
return nil
}
return try! withUnsafeData(atUncheckedIndex: index, { $0 })
}
/// Returns the optional `Data` at given column.
///
/// Column name lookup is case-insensitive. When several columns exist with
/// 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.
@available(*, deprecated, message: "Use withUnsafeData(at:_:) instead.")
public func dataNoCopy(_ column: some ColumnExpression) -> Data? {
dataNoCopy(named: column.name)
}
/// Returns the first non-null value, if any. Identical to SQL `COALESCE` function.
///
/// For example:
///
/// ```swift
/// let name: String? = row.coalesce(["nickname", "name"])
/// ```
///
/// Prefer `coalesce` to nil-coalescing row values, which does not
/// return the expected value:
///
/// ```swift
/// // INCORRECT
/// let name: String? = row["nickname"] ?? row["name"]
/// ```
public func coalesce<T: DatabaseValueConvertible>(
_ columns: some Collection<String>
) -> T? {
for column in columns {
if let value = self[column] as T? {
return value
}
}
return nil
}
/// Returns the first non-null value, if any. Identical to SQL `COALESCE` function.
///
/// For example:
///
/// ```swift
/// let name: String? = row.coalesce([Column("nickname"), Column("name")])
/// ```
///
/// Prefer `coalesce` to nil-coalescing row values, which does not
/// return the expected value:
///
/// ```swift
/// // INCORRECT
/// let name: String? = row[Column("nickname")] ?? row[Column("name")]
/// ```
public func coalesce<T: DatabaseValueConvertible>(
_ columns: some Collection<any ColumnExpression>
) -> T? {
return coalesce(columns.lazy.map { $0.name })
}
}
extension Row {
// MARK: - Extracting DatabaseValue
/// The database values in the row, from left to right.
///
/// 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> {
lazy.map { $0.1 }
}
}
extension Row {
// MARK: - Extracting Records
/// The record associated to the given scope.
///
/// Row scopes can be defined manually, with ``ScopeAdapter``.
/// The ``JoinableRequest/including(required:)`` and
/// ``JoinableRequest/including(optional:)`` request methods define scopes
/// named after the key of included associations between record types.
///
/// A breadth-first search is performed in all available scopes in the row,
/// recursively.
///
/// A fatal error is raised if the scope is not available, or contains only
/// `NULL` values.
///
/// For example:
///
/// ```swift
/// struct Book: TableRecord, FetchableRecord {
/// static let author = belongsTo(Author.self)
/// }
///
/// struct Author: TableRecord, FetchableRecord {
/// static let country = belongsTo(Country.self)
/// }
///
/// struct Country: TableRecord, FetchableRecord { }
///
/// // Fetch a book, with its author, and the country of its author.
/// let request = Book
/// .including(required: Book.author
/// .including(required: Author.country))
/// let bookRow = try Row.fetchOne(db, request)!
///
/// let book = try Book(row: bookRow)
/// let author: Author = bookRow["author"]
/// let country: Country = bookRow["country"]
/// ```
///
/// See also: ``scopesTree``
///
/// - parameter scope: A scope identifier.
public subscript<Record: FetchableRecord>(_ scope: String) -> Record {
try! decode(Record.self, forKey: scope)
}
/// The eventual record associated to the given scope.
///
/// Row scopes can be defined manually, with ``ScopeAdapter``.
/// The ``JoinableRequest/including(required:)`` and
/// ``JoinableRequest/including(optional:)`` request methods define scopes
/// named after the key of included associations between record types.
///
/// A breadth-first search is performed in all available scopes in the row,
/// recursively.
///
/// The result is nil if the scope is not available, or contains only
/// `NULL` values.
///
/// For example:
///
/// ```swift
/// struct Book: TableRecord, FetchableRecord {
/// static let author = belongsTo(Author.self)
/// }
///
/// struct Author: TableRecord, FetchableRecord {
/// static let country = belongsTo(Country.self)
/// }
///
/// struct Country: TableRecord, FetchableRecord { }
///
/// // Fetch a book, with its author, and the country of its author.
/// let request = Book
/// .including(optional: Book.author
/// .including(optional: Author.country))
/// let bookRow = try Row.fetchOne(db, request)!
///
/// let book = try Book(row: bookRow)
/// let author: Author? = bookRow["author"]
/// let country: Country? = bookRow["country"]
/// ```
///
/// See also: ``scopesTree``
///
/// - parameter scope: A scope identifier.
public subscript<Record: FetchableRecord>(_ scope: String) -> Record? {
try! decodeIfPresent(Record.self, forKey: scope)
}
/// A collection of prefetched records associated to the given
/// association key.
///
/// Prefetched rows are defined by the ``JoinableRequest/including(all:)``
/// request method.
///
/// For example:
///
/// ```swift
/// struct Author: TableRecord, FetchableRecord {
/// static let books = hasMany(Book.self)
/// }
///
/// struct Book: TableRecord, FetchableRecord { }
///
/// let request = Author.including(all: Author.books)
/// let authorRow = try Row.fetchOne(db, request)!
///
/// let author = try Author(row: authorRow)
/// let books: [Book] = author["books"]
/// ```
///
/// See also: ``prefetchedRows``
///
/// - parameter key: An association key.
public subscript<Records>(_ key: String)
-> Records
where
Records: RangeReplaceableCollection,
Records.Element: FetchableRecord
{
try! decode(Records.self, forKey: key)
}
/// A set prefetched records associated to the given association key.
///
/// Prefetched rows are defined by the ``JoinableRequest/including(all:)``
/// request method.
///
/// For example:
///
/// ```swift
/// struct Author: TableRecord, FetchableRecord {
/// static let books = hasMany(Book.self)
/// }
///
/// struct Book: TableRecord, FetchableRecord, Hashable { }
///
/// let request = Author.including(all: Author.books)
/// let authorRow = try Row.fetchOne(db, request)!
///
/// let author = try Author(row: authorRow)
/// let books: Set<Book> = author["books"]
/// ```
///
/// See also: ``prefetchedRows``
///
/// - parameter key: An association key.
public subscript<Record: FetchableRecord & Hashable>(_ key: String) -> Set<Record> {
try! decode(Set<Record>.self, forKey: key)
}
}
extension Row {
// MARK: - Scopes
/// A view on the scopes defined by row adapters.
///
/// The returned object provides an access to all available scopes in
/// the row.
///
/// Row scopes can be defined manually, with ``ScopeAdapter``.
/// The ``JoinableRequest/including(required:)`` and
/// ``JoinableRequest/including(optional:)`` request methods define scopes
/// named after the key of included associations between record types.
///
/// For example:
///
/// ```swift
/// struct Book: TableRecord {
/// static let author = belongsTo(Author.self)
/// }
///
/// struct Author: TableRecord {
/// static let country = belongsTo(Country.self)
/// }
///
/// struct Country: TableRecord { }
///
/// // Fetch a book, with its author, and the country of its author.
/// let request = Book
/// .including(required: Book.author
/// .including(required: Author.country))
/// let bookRow = try Row.fetchOne(db, request)!
///
/// print(bookRow)
/// // Prints [id:42, title:"Moby-Dick", authorId:1]
///
/// let authorRow = bookRow.scopes["author"]!
/// print(authorRow)
/// // Prints [id:1, name:"Herman Melville", countryCode: "US"]
///
/// let countryRow = authorRow.scopes["country"]!
/// print(countryRow)
/// // Prints [code:"US" name:"United States of America"]
/// ```
///
/// See also ``scopesTree``.
public var scopes: ScopesView {
impl.scopes(prefetchedRows: prefetchedRows)
}
/// A view on the scopes tree defined by row adapters.
///
/// The returned object provides an access to all available scopes in
/// the row, recursively. For any given scope identifier, a breadth-first
/// search is performed.
///
/// Row scopes can be defined manually, with ``ScopeAdapter``.
/// The ``JoinableRequest/including(required:)`` and
/// ``JoinableRequest/including(optional:)`` request methods define scopes
/// named after the key of included associations between record types.
///
/// For example:
///
/// ```swift
/// struct Book: TableRecord {
/// static let author = belongsTo(Author.self)
/// }
///
/// struct Author: TableRecord {
/// static let country = belongsTo(Country.self)
/// }
///
/// struct Country: TableRecord { }
///
/// // Fetch a book, with its author, and the country of its author.
/// let request = Book
/// .including(required: Book.author
/// .including(required: Author.country))
/// let bookRow = try Row.fetchOne(db, request)!
///
/// print(bookRow)
/// // Prints [id:42, title:"Moby-Dick", authorId:1]
///
/// print(bookRow.scopesTree["author"])
/// // Prints [id:1, name:"Herman Melville", countryCode: "US"]
///
/// print(bookRow.scopesTree["country"])
/// // Prints [code:"US" name:"United States of America"]
/// ```
///
/// See also ``scopes``.
public var scopesTree: ScopesTreeView {
ScopesTreeView(scopes: scopes)
}
/// The row, without any scope of prefetched rows.
///
/// This property is useful when testing the content of rows fetched from
/// joined requests.
///
/// For example:
///
/// ```swift
/// struct Book: TableRecord {
/// static let author = belongsTo(Author.self)
/// static let awards = hasMany(Award.self)
/// }
///