-
-
Notifications
You must be signed in to change notification settings - Fork 744
/
Copy pathStatementColumnConvertible.swift
855 lines (816 loc) · 28.5 KB
/
StatementColumnConvertible.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
// Import C SQLite functions
#if GRDBCIPHER
import SQLCipher
#elseif SWIFT_PACKAGE
import GRDBSQLite
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// A type that can decode itself from the low-level C interface to
/// SQLite results.
///
/// `StatementColumnConvertible` is adopted by `Bool`, `Int`, `String`,
/// `Date`, and most common values.
///
/// When a type conforms to both ``DatabaseValueConvertible`` and
/// `StatementColumnConvertible`, GRDB can apply some optimization whenever
/// direct access to SQLite is possible. For example:
///
/// ```swift
/// // Optimized
/// let scores = Int.fetchAll(db, sql: "SELECT score FROM player")
///
/// let rows = try Row.fetchCursor(db, sql: "SELECT * FROM player")
/// while let row = try rows.next() {
/// // Optimized
/// let int: Int = row[0]
/// let name: String = row[1]
/// }
///
/// struct Player: FetchableRecord {
/// var name: String
/// var score: Int
///
/// init(row: Row) {
/// // Optimized
/// name = row["name"]
/// score = row["score"]
/// }
/// }
/// ```
///
/// To conform to `StatementColumnConvertible`, provide a custom implementation
/// of ``init(sqliteStatement:index:)-354je``. This implementation is ready-made
/// for `RawRepresentable` types whose `RawValue`
/// is `StatementColumnConvertible`.
///
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/column_blob.html>
///
/// ## Topics
///
/// ### Creating a Value
///
/// - ``init(sqliteStatement:index:)-354je``
/// - ``fromStatement(_:atUncheckedIndex:)-2i8y6``
///
/// ### Fetching Values from Raw SQL
///
/// - ``DatabaseValueConvertible/fetchCursor(_:sql:arguments:adapter:)-4xfxh``
/// - ``DatabaseValueConvertible/fetchAll(_:sql:arguments:adapter:)-7bn2i``
/// - ``DatabaseValueConvertible/fetchSet(_:sql:arguments:adapter:)-1ythd``
/// - ``DatabaseValueConvertible/fetchOne(_:sql:arguments:adapter:)-563lc``
///
/// ### Fetching Values from a Prepared Statement
///
/// - ``DatabaseValueConvertible/fetchCursor(_:arguments:adapter:)-81f9d``
/// - ``DatabaseValueConvertible/fetchAll(_:arguments:adapter:)-64gua``
/// - ``DatabaseValueConvertible/fetchSet(_:arguments:adapter:)-9fh2b``
/// - ``DatabaseValueConvertible/fetchOne(_:arguments:adapter:)-8cbzp``
///
/// ### Fetching Values from a Request
///
/// - ``DatabaseValueConvertible/fetchCursor(_:_:)-77a34``
/// - ``DatabaseValueConvertible/fetchAll(_:_:)-7tnun``
/// - ``DatabaseValueConvertible/fetchSet(_:_:)-4bc1m``
/// - ``DatabaseValueConvertible/fetchOne(_:_:)-94q4e``
///
/// ### Supporting Types
///
/// - ``FastDatabaseValueCursor``
public protocol StatementColumnConvertible {
/// Creates an instance from a raw SQLite statement pointer, if possible.
///
/// This method can be called with a NULL database value.
///
/// - warning: Do not customize the default implementation.
///
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
/// - returns: A decoded value, or, if decoding is impossible, nil.
static func fromStatement(
_ sqliteStatement: SQLiteStatement,
atUncheckedIndex index: CInt)
-> Self?
/// Creates an instance from a raw SQLite statement pointer, if possible.
///
/// Do not check for `NULL` in your implementation of this method. Null
/// database values are handled
/// in ``StatementColumnConvertible/fromStatement(_:atUncheckedIndex:)-2i8y6``.
///
/// For example, here is the how Int64 adopts StatementColumnConvertible:
///
/// ```swift
/// extension Int64: StatementColumnConvertible {
/// public init(sqliteStatement: SQLiteStatement, index: CInt) {
/// self = sqlite3_column_int64(sqliteStatement, index)
/// }
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/column_blob.html>
///
/// - precondition: This initializer is not called with a NULL
/// database value.
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
init?(sqliteStatement: SQLiteStatement, index: CInt)
}
extension StatementColumnConvertible {
// `Optional` overrides this default behavior.
/// Default implementation fails on decoding NULL.
@inline(__always)
@inlinable
public static func fromStatement(_ sqliteStatement: SQLiteStatement, atUncheckedIndex index: CInt) -> Self? {
if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL {
return nil
}
return self.init(sqliteStatement: sqliteStatement, index: index)
}
}
// MARK: - Conversions
extension DatabaseValueConvertible where Self: StatementColumnConvertible {
@usableFromInline
/* private */ static func _valueMismatch(
fromStatement sqliteStatement: SQLiteStatement,
atUncheckedIndex index: CInt,
context: @autoclosure () -> RowDecodingContext)
throws -> Never
{
throw RowDecodingError.valueMismatch(
Self.self,
sqliteStatement: sqliteStatement,
index: index,
context: context())
}
@inline(__always)
@inlinable
static func fastDecode(
fromRow row: Row,
atUncheckedIndex index: Int)
throws -> Self
{
if let sqliteStatement = row.sqliteStatement {
return try fastDecode(
fromStatement: sqliteStatement,
atUncheckedIndex: CInt(index),
context: RowDecodingContext(row: row, key: .columnIndex(index)))
}
// Support for fast decoding from adapted rows
return try row.fastDecode(Self.self, atUncheckedIndex: index)
}
@inline(__always)
@inlinable
static func fastDecode(
fromStatement sqliteStatement: SQLiteStatement,
atUncheckedIndex index: CInt,
context: @autoclosure () -> RowDecodingContext)
throws -> Self
{
if let value = fromStatement(sqliteStatement, atUncheckedIndex: index) {
return value
} else {
try _valueMismatch(fromStatement: sqliteStatement, atUncheckedIndex: index, context: context())
}
}
// Support for Decodable
@inline(__always)
@inlinable
static func fastDecodeIfPresent(
fromRow row: Row,
atUncheckedIndex index: Int)
throws -> Self?
{
try Optional<Self>.fastDecode(fromRow: row, atUncheckedIndex: index)
}
}
// MARK: - Cursors
/// A cursor of database values.
///
/// A `FastDatabaseValueCursor` iterates all rows from a database request. Its
/// elements are the database values decoded from the leftmost column.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let names: FastDatabaseValueCursor<String> = try String.fetchCursor(db, sql: """
/// SELECT name FROM player
/// """)
/// while let name = names.next() { // String
/// print(name)
/// }
/// }
/// ```
public final class FastDatabaseValueCursor<Value>: DatabaseCursor
where Value: DatabaseValueConvertible & StatementColumnConvertible
{
public typealias Element = Value
public let _statement: Statement
public var _isDone = false
@usableFromInline let columnIndex: CInt
init(statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws {
self._statement = statement
if let adapter {
// adapter may redefine the index of the leftmost column
columnIndex = try CInt(adapter.baseColumnIndex(atIndex: 0, layout: statement))
} else {
columnIndex = 0
}
// Assume cursor is created for immediate iteration: reset and set arguments
try statement.prepareExecution(withArguments: arguments)
}
deinit {
// Statement reset fails when sqlite3_step has previously failed.
// Just ignore reset error.
try? _statement.reset()
}
@inlinable
public func _element(sqliteStatement: SQLiteStatement) throws -> Value {
try Value.fastDecode(
fromStatement: sqliteStatement,
atUncheckedIndex: columnIndex,
context: RowDecodingContext(statement: _statement, index: Int(columnIndex)))
}
}
// Explicit non-conformance to Sendable: database cursors must be used from
// a serialized database access dispatch queue.
@available(*, unavailable)
extension FastDatabaseValueCursor: Sendable { }
/// Types that adopt both DatabaseValueConvertible and
/// StatementColumnConvertible can be efficiently initialized from
/// database values.
///
/// See DatabaseValueConvertible for more information.
extension DatabaseValueConvertible where Self: StatementColumnConvertible {
// MARK: Fetching From Prepared Statement
/// Returns a cursor over values fetched from a prepared statement.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
/// let sql = "SELECT score FROM player WHERE lastName = ?"
/// let statement = try db.makeStatement(sql: sql)
/// let scores = try Int.fetchCursor(statement, arguments: [lastName])
/// while let score = try scores.next() {
/// print(score)
/// }
/// }
/// ```
///
/// Values are decoded from the leftmost column if the `adapter` argument
/// is nil.
///
/// The returned cursor is valid only during the remaining execution of the
/// database access. Do not store or return the cursor for later use.
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// - parameters:
/// - statement: The statement to run.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: A ``FastDatabaseValueCursor`` over fetched values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchCursor(
_ statement: Statement,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
throws -> FastDatabaseValueCursor<Self>
{
try FastDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter)
}
/// Returns an array of values fetched from a prepared statement.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
/// let sql = "SELECT score FROM player WHERE lastName = ?"
/// let statement = try db.makeStatement(sql: sql)
/// let scores = try Int.fetchAll(statement, arguments: [lastName])
/// }
/// ```
///
/// Values are decoded from the leftmost column if the `adapter` argument
/// is nil.
///
/// - parameters:
/// - statement: The statement to run.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: An array of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(
_ statement: Statement,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
throws -> [Self]
{
try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
}
/// Returns a single value fetched from a prepared statement.
///
/// The value is decoded from the leftmost column if the `adapter` argument
/// is nil.
///
/// The result is nil if the request returns no row, or one row with a
/// `NULL` value.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
/// let sql = "SELECT score FROM player WHERE lastName = ? LIMIT 1"
/// let statement = try db.makeStatement(sql: sql)
/// let score = try Int.fetchOne(statement, arguments: [lastName])
/// }
/// ```
///
/// - parameters:
/// - statement: The statement to run.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: An optional value.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(
_ statement: Statement,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
throws -> Self?
{
// fetchOne handles both a missing row, and one row with a NULL value.
let cursor = try FastDatabaseValueCursor<Self?>(
statement: statement,
arguments: arguments,
adapter: adapter)
return try cursor.next() ?? nil
}
}
extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hashable {
/// Returns a set of values fetched from a prepared statement.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
/// let sql = "SELECT score FROM player WHERE lastName = ?"
/// let statement = try db.makeStatement(sql: sql)
/// let scores = try Int.fetchSet(statement, arguments: [lastName])
/// }
/// ```
///
/// Values are decoded from the leftmost column if the `adapter` argument
/// is nil.
///
/// - parameters:
/// - statement: The statement to run.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: A set of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(
_ statement: Statement,
arguments: StatementArguments? = nil,
adapter: (any RowAdapter)? = nil)
throws -> Set<Self>
{
try Set(fetchCursor(statement, arguments: arguments, adapter: adapter))
}
}
extension DatabaseValueConvertible where Self: StatementColumnConvertible {
// MARK: Fetching From SQL
/// Returns a cursor over values fetched from an SQL query.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
/// let sql = "SELECT score FROM player WHERE lastName = ?"
/// let scores = try Int.fetchCursor(db, sql: sql, arguments: [lastName])
/// while let score = try scores.next() {
/// print(score)
/// }
/// }
/// ```
///
/// Values are decoded from the leftmost column if the `adapter` argument
/// is nil.
///
/// The returned cursor is valid only during the remaining execution of the
/// database access. Do not store or return the cursor for later use.
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL string.
/// - arguments: Statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: A ``FastDatabaseValueCursor`` over fetched values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchCursor(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: (any RowAdapter)? = nil)
throws -> FastDatabaseValueCursor<Self>
{
try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
}
/// Returns an array of values fetched from an SQL query.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
/// let sql = "SELECT score FROM player WHERE lastName = ?"
/// let scores = try Int.fetchAll(db, sql: sql, arguments: [lastName])
/// }
/// ```
///
/// Values are decoded from the leftmost column if the `adapter` argument
/// is nil.
///
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL string.
/// - arguments: Statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: An array of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: (any RowAdapter)? = nil)
throws -> [Self]
{
try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
}
/// Returns a single value fetched from an SQL query.
///
/// The value is decoded from the leftmost column if the `adapter` argument
/// is nil.
///
/// The result is nil if the request returns no row, or one row with a
/// `NULL` value.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
/// let sql = "SELECT score FROM player WHERE lastName = ?"
/// let score = try Int.fetchOne(db, sql: sql, arguments: [lastName])
/// }
/// ```
///
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL string.
/// - arguments: Statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: An optional value.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: (any RowAdapter)? = nil)
throws -> Self?
{
try fetchOne(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
}
}
extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hashable {
/// Returns a set of values fetched from an SQL query.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
/// let sql = "SELECT score FROM player WHERE lastName = ?"
/// let scores = try Int.fetchSet(db, sql: sql, arguments: [lastName])
/// }
/// ```
///
/// Values are decoded from the leftmost column if the `adapter` argument
/// is nil.
///
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL string.
/// - arguments: Statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: A set of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: (any RowAdapter)? = nil)
throws -> Set<Self>
{
try fetchSet(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
}
}
extension DatabaseValueConvertible where Self: StatementColumnConvertible {
// MARK: Fetching From FetchRequest
/// Returns a cursor over values fetched from a fetch request.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player
/// .select(Column("score"))
/// .filter(Column("lastName") == lastName)
///
/// // SQL request
/// let request: SQLRequest<Int> = """
/// SELECT score FROM player WHERE lastName = \(lastName)
/// """
///
/// let scores = try Int.fetchCursor(db, request)
/// while let score = try scores.next() {
/// print(score)
/// }
/// }
/// ```
///
/// Values are decoded from the leftmost column.
///
/// The returned cursor is valid only during the remaining execution of the
/// database access. Do not store or return the cursor for later use.
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// - parameters:
/// - db: A database connection.
/// - request: A fetch request.
/// - returns: A ``FastDatabaseValueCursor`` over fetched values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ request: some FetchRequest)
throws -> FastDatabaseValueCursor<Self>
{
let request = try request.makePreparedRequest(db, forSingleResult: false)
return try fetchCursor(request.statement, adapter: request.adapter)
}
/// Returns an array of values fetched from a fetch request.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player
/// .select(Column("score"))
/// .filter(Column("lastName") == lastName)
///
/// // SQL request
/// let request: SQLRequest<Int> = """
/// SELECT score FROM player WHERE lastName = \(lastName)
/// """
///
/// let scores = try Int.fetchAll(db, request)
/// }
/// ```
///
/// Values are decoded from the leftmost column.
///
/// - parameters:
/// - db: A database connection.
/// - request: A fetch request.
/// - returns: An array of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Self] {
let request = try request.makePreparedRequest(db, forSingleResult: false)
return try fetchAll(request.statement, adapter: request.adapter)
}
/// Returns a single value fetched from a fetch request.
///
/// The value is decoded from the leftmost column.
///
/// The result is nil if the request returns no row, or one row with a
/// `NULL` value.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player
/// .select(Column("score"))
/// .filter(Column("lastName") == lastName)
///
/// // SQL request
/// let request: SQLRequest<Int> = """
/// SELECT score FROM player WHERE lastName = \(lastName) LIMIT 1
/// """
///
/// let scores = try Int.fetchOne(db, request)
/// }
/// ```
///
/// - parameters:
/// - db: A database connection.
/// - request: A fetch request.
/// - returns: An optional value.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Self? {
let request = try request.makePreparedRequest(db, forSingleResult: true)
return try fetchOne(request.statement, adapter: request.adapter)
}
}
extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hashable {
/// Returns a set of values fetched from a fetch request.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player
/// .select(Column("score"))
/// .filter(Column("lastName") == lastName)
///
/// // SQL request
/// let request: SQLRequest<Int> = """
/// SELECT score FROM player WHERE lastName = \(lastName)
/// """
///
/// let scores = try Int.fetchAll(db, request)
/// }
/// ```
///
/// Values are decoded from the leftmost column.
///
/// - parameters:
/// - db: A database connection.
/// - request: A fetch request.
/// - returns: A set of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set<Self> {
let request = try request.makePreparedRequest(db, forSingleResult: false)
return try fetchSet(request.statement, adapter: request.adapter)
}
}
extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementColumnConvertible {
// MARK: Fetching Values
/// Returns a cursor over fetched values.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player
/// .filter(Column("lastName") == lastName)
/// .select(Column("score"), as: Int.self)
///
/// // SQL request
/// let request: SQLRequest<Int> = """
/// SELECT score FROM player WHERE lastName = \(lastName)
/// """
///
/// let scores = try request.fetchCursor(db)
/// while let score = try scores.next() {
/// print(score)
/// }
/// }
/// ```
///
/// Values are decoded from the leftmost column.
///
/// The returned cursor is valid only during the remaining execution of the
/// database access. Do not store or return the cursor for later use.
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// - parameter db: A database connection.
/// - returns: A ``FastDatabaseValueCursor`` over fetched values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchCursor(_ db: Database) throws -> FastDatabaseValueCursor<RowDecoder> {
try RowDecoder.fetchCursor(db, self)
}
/// Returns an array of fetched values.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player
/// .filter(Column("lastName") == lastName)
/// .select(Column("score"), as: Int.self)
///
/// // SQL request
/// let request: SQLRequest<Int> = """
/// SELECT score FROM player WHERE lastName = \(lastName)
/// """
///
/// let scores = try request.fetchAll(db)
/// }
/// ```
///
/// Values are decoded from the leftmost column.
///
/// - parameter db: A database connection.
/// - returns: An array of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
try RowDecoder.fetchAll(db, self)
}
/// Returns a single fetched value.
///
/// The value is decoded from the leftmost column.
///
/// The result is nil if the request returns no row, or one row with a
/// `NULL` value.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player
/// .filter(Column("lastName") == lastName)
/// .select(Column("score"), as: Int.self)
///
/// // SQL request
/// let request: SQLRequest<Int> = """
/// SELECT score FROM player WHERE lastName = \(lastName) LIMIT 1
/// """
///
/// let score = try request.fetchOne(db)
/// }
/// ```
///
/// - parameter db: A database connection.
/// - returns: An optional value.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchOne(_ db: Database) throws -> RowDecoder? {
try RowDecoder.fetchOne(db, self)
}
}
extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementColumnConvertible & Hashable {
/// Returns a set of fetched values.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let lastName = "O'Reilly"
///
/// // Query interface request
/// let request = Player
/// .filter(Column("lastName") == lastName)
/// .select(Column("score"), as: Int.self)
///
/// // SQL request
/// let request: SQLRequest<Int> = """
/// SELECT score FROM player WHERE lastName = \(lastName)
/// """
///
/// let scores = try request.fetchSet(db)
/// }
/// ```
///
/// Values are decoded from the leftmost column.
///
/// - parameter db: A database connection.
/// - returns: A set of values.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
try RowDecoder.fetchSet(db, self)
}
}