Merge pull request #574 from groue/dev/swiftlint

SwiftLint
This commit is contained in:
Gwendal Roué authored and GitHub committed 2019-07-27 12:46:53 +02:00
commit cf2a6763b5
122 files changed
+3257 -1595

No files matched your search

+57
View File
@@ -0,0 +1,57 @@
included:
- GRDB
disabled_rules:
- cyclomatic_complexity
- file_length
- force_cast
- force_try
- function_body_length
- function_parameter_count
- identifier_name
- is_disjoint
- nesting
- opening_brace
- redundant_optional_initialization
- syntactic_sugar
- todo
- trailing_comma
- trailing_whitespace
- type_body_length
- type_name
- unused_setter_value
opt_in_rules:
- anyobject_protocol
- array_init
- attributes
- closure_spacing
- collection_alignment
- contains_over_first_not_nil
- convenience_type
- empty_count
- empty_string
- explicit_init
- fatal_error_message
- first_where
- joined_default_parameter
- last_where
- legacy_multiple
- legacy_random
- modifier_order
- no_extension_access_modifier
- overridden_super_call
- pattern_matching_keywords
- prohibited_super_call
- reduce_into
- redundant_type_annotation
- sorted_first_last
- toggle_bool
- unused_declaration
- unused_import
- unused_private_declaration
- yoda_condition
vertical_whitespace:
max_empty_lines: 2
+1
View File
@@ -55,6 +55,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one expection:
## Next Release
- [#562](https://github.com/groue/GRDB.swift/pull/562): Fix crash when using more than one DatabaseCollation
- [#574](https://github.com/groue/GRDB.swift/pull/574): SwiftLint
## 4.1.1
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1020"
LastUpgradeVersion = "1030"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1020"
LastUpgradeVersion = "1030"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
+41
View File
@@ -2313,6 +2313,7 @@
56E5D7C61B4D3FED00430942 /* Frameworks */,
56E5D7C71B4D3FED00430942 /* Headers */,
56E5D7C81B4D3FED00430942 /* Resources */,
56EB54FA22C9115E00850069 /* Swiftlint */,
);
buildRules = (
);
@@ -2367,6 +2368,7 @@
DC3773EF19C8CBB3004FCF85 /* Frameworks */,
DC3773F019C8CBB3004FCF85 /* Headers */,
DC3773F119C8CBB3004FCF85 /* Resources */,
56EB54F322C8ED5100850069 /* Swiftlint */,
);
buildRules = (
);
@@ -2559,6 +2561,45 @@
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
56EB54F322C8ED5100850069 /* Swiftlint */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
);
inputPaths = (
);
name = Swiftlint;
outputFileListPaths = (
);
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "if which swiftlint >/dev/null; then\n swiftlint\nelse\n echo \"warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint\"\nfi\n";
};
56EB54FA22C9115E00850069 /* Swiftlint */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
);
inputPaths = (
);
name = Swiftlint;
outputFileListPaths = (
);
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "if which swiftlint >/dev/null; then\n swiftlint\nelse\n echo \"warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint\"\nfi\n";
};
/* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
560C97D41C0E22D300BF8471 /* Sources */ = {
isa = PBXSourcesBuildPhase;
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1020"
LastUpgradeVersion = "1030"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1020"
LastUpgradeVersion = "1030"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1020"
LastUpgradeVersion = "1030"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1020"
LastUpgradeVersion = "1030"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1020"
LastUpgradeVersion = "1030"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
+7 -7
View File
@@ -1,11 +1,11 @@
import Foundation
import Dispatch
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
/// Configuration for a DatabaseQueue or DatabasePool.
@@ -85,7 +85,7 @@ public struct Configuration {
public var passphrase: String?
#endif
/// If set, allows custom configuration to be run every time
/// a new connection is opened.
///
@@ -181,9 +181,9 @@ public struct Configuration {
// MARK: - Not Public
var threadingMode: Database.ThreadingMode = .`default`
var SQLiteConnectionDidOpen: (() -> ())?
var SQLiteConnectionWillClose: ((SQLiteConnection) -> ())?
var SQLiteConnectionDidClose: (() -> ())?
var SQLiteConnectionDidOpen: (() -> Void)?
var SQLiteConnectionWillClose: ((SQLiteConnection) -> Void)?
var SQLiteConnectionDidClose: (() -> Void)?
var SQLiteOpenFlags: Int32 {
let readWriteFlags = readonly ? SQLITE_OPEN_READONLY : (SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE)
return threadingMode.SQLiteOpenFlags | readWriteFlags
+27 -16
View File
@@ -29,7 +29,10 @@ extension Sequence {
/// Returns a cursor over the concatenated results of mapping transform
/// over self.
public func flatMap<SegmentOfResult: Cursor>(_ transform: @escaping (Iterator.Element) throws -> SegmentOfResult) -> FlattenCursor<MapCursor<AnyCursor<Iterator.Element>, SegmentOfResult>> {
public func flatMap<SegmentOfResult: Cursor>(
_ transform: @escaping (Iterator.Element) throws -> SegmentOfResult)
-> FlattenCursor<MapCursor<AnyCursor<Iterator.Element>, SegmentOfResult>>
{
return AnyCursor(self).flatMap(transform)
}
}
@@ -76,7 +79,7 @@ extension Set {
/// `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`,
/// `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`,
/// `suffix`.
public protocol Cursor : class {
public protocol Cursor: AnyObject {
/// The type of element traversed by the cursor.
associatedtype Element
@@ -141,7 +144,9 @@ extension Cursor {
/// Returns a cursor over the concatenated non-nil results of mapping
/// transform over this cursor.
public func compactMap<ElementOfResult>(_ transform: @escaping (Element) throws -> ElementOfResult?) -> MapCursor<FilterCursor<MapCursor<Self, ElementOfResult?>>, ElementOfResult> {
public func compactMap<ElementOfResult>(_ transform: @escaping (Element) throws -> ElementOfResult?)
-> MapCursor<FilterCursor<MapCursor<Self, ElementOfResult?>>, ElementOfResult>
{
return map(transform).filter { $0 != nil }.map { $0! }
}
@@ -190,7 +195,7 @@ extension Cursor {
public func dropFirst() -> DropFirstCursor<Self> {
return dropFirst(1)
}
/// Returns an array containing all but the given number of final
/// elements.
///
@@ -243,13 +248,19 @@ extension Cursor {
/// Returns a cursor over the concatenated results of mapping transform
/// over self.
public func flatMap<SegmentOfResult: Sequence>(_ transform: @escaping (Element) throws -> SegmentOfResult) -> FlattenCursor<MapCursor<Self, AnyCursor<SegmentOfResult.Element>>> {
public func flatMap<SegmentOfResult>(_ transform: @escaping (Element) throws -> SegmentOfResult)
-> FlattenCursor<MapCursor<Self, AnyCursor<SegmentOfResult.Element>>>
where SegmentOfResult: Sequence
{
return flatMap { try AnyCursor(transform($0)) }
}
/// Returns a cursor over the concatenated results of mapping transform
/// over self.
public func flatMap<SegmentOfResult: Cursor>(_ transform: @escaping (Element) throws -> SegmentOfResult) -> FlattenCursor<MapCursor<Self, SegmentOfResult>> {
public func flatMap<SegmentOfResult>(_ transform: @escaping (Element) throws -> SegmentOfResult)
-> FlattenCursor<MapCursor<Self, SegmentOfResult>>
where SegmentOfResult: Cursor
{
return map(transform).joined()
}
@@ -503,7 +514,7 @@ extension Cursor where Element: StringProtocol {
/// This cursor forwards its next() method to an arbitrary underlying cursor
/// having the same Element type, hiding the specifics of the underlying
/// cursor.
public final class AnyCursor<Element> : Cursor {
public final class AnyCursor<Element>: Cursor {
private let element: () throws -> Element?
/// Creates a cursor that wraps a base cursor but whose type depends only on
@@ -539,11 +550,11 @@ public final class AnyCursor<Element> : Cursor {
}
/// :nodoc:
public final class DropFirstCursor<Base: Cursor> : Cursor {
public final class DropFirstCursor<Base: Cursor>: Cursor {
private let base: Base
private let limit: Int
private var dropped: Int = 0
init(_ base: Base, limit: Int) {
GRDBPrecondition(limit >= 0, "Can't drop a negative number of elements from a cursor")
self.base = base
@@ -566,7 +577,7 @@ public final class DropFirstCursor<Base: Cursor> : Cursor {
/// consecutive elements of some base cursor that satisfy a given predicate.
///
/// :nodoc:
public final class DropWhileCursor<Base: Cursor> : Cursor {
public final class DropWhileCursor<Base: Cursor>: Cursor {
private let base: Base
private let predicate: (Base.Element) throws -> Bool
private var predicateHasFailed = false
@@ -605,7 +616,7 @@ public final class DropWhileCursor<Base: Cursor> : Cursor {
/// // Prints: "1: bar"
///
/// :nodoc:
public final class EnumeratedCursor<Base: Cursor> : Cursor {
public final class EnumeratedCursor<Base: Cursor>: Cursor {
private let base: Base
private var index: Int
@@ -628,7 +639,7 @@ public final class EnumeratedCursor<Base: Cursor> : Cursor {
/// also satisfy a given predicate.
///
/// :nodoc:
public final class FilterCursor<Base: Cursor> : Cursor {
public final class FilterCursor<Base: Cursor>: Cursor {
private let base: Base
private let isIncluded: (Base.Element) throws -> Bool
@@ -656,7 +667,7 @@ public final class FilterCursor<Base: Cursor> : Cursor {
/// See Cursor.joined(), Cursor.flatMap(_:), Sequence.flatMap(_:)
///
/// :nodoc:
public final class FlattenCursor<Base: Cursor> : Cursor where Base.Element: Cursor {
public final class FlattenCursor<Base: Cursor>: Cursor where Base.Element: Cursor {
private let base: Base
private var inner: Base.Element?
@@ -686,7 +697,7 @@ public final class FlattenCursor<Base: Cursor> : Cursor where Base.Element: Curs
/// See Cursor.map(_:)
///
/// :nodoc:
public final class MapCursor<Base: Cursor, Element> : Cursor {
public final class MapCursor<Base: Cursor, Element>: Cursor {
private let base: Base
private let transform: (Base.Element) throws -> Element
@@ -708,7 +719,7 @@ public final class MapCursor<Base: Cursor, Element> : Cursor {
/// `Base` cursor.
///
/// :nodoc:
public final class PrefixCursor<Base: Cursor> : Cursor {
public final class PrefixCursor<Base: Cursor>: Cursor {
private let base: Base
private let maxLength: Int
private var taken = 0
@@ -735,7 +746,7 @@ public final class PrefixCursor<Base: Cursor> : Cursor {
/// some base cursor that satisfy a given predicate.
///
/// :nodoc:
public final class PrefixWhileCursor<Base: Cursor> : Cursor {
public final class PrefixWhileCursor<Base: Cursor>: Cursor {
private let base: Base
private let predicate: (Base.Element) throws -> Bool
private var predicateHasFailed = false
+40 -18
View File
@@ -1,15 +1,15 @@
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
extension Database {
// MARK: - Database Schema
/// Clears the database schema cache.
///
/// You may need to clear the cache manually if the database schema is
@@ -71,7 +71,7 @@ extension Database {
.names(ofType: type)
.contains { $0.lowercased() == name }
}
/// The primary key for table named `tableName`.
///
/// All tables have a primary key, even when it is not explicit. When a
@@ -203,7 +203,12 @@ extension Database {
/// True if a sequence of columns uniquely identifies a row, that is to say
/// if the columns are the primary key, or if there is a unique index on them.
public func table<T: Sequence>(_ tableName: String, hasUniqueKey columns: T) throws -> Bool where T.Iterator.Element == String {
public func table<T: Sequence>(
_ tableName: String,
hasUniqueKey columns: T)
throws -> Bool
where T.Iterator.Element == String
{
return try columnsForUniqueKey(Array(columns), in: tableName) != nil
}
@@ -213,7 +218,9 @@ extension Database {
return foreignKeys
}
var rawForeignKeys: [(destinationTable: String, mapping: [(origin: String, destination: String?, seq: Int)])] = []
var rawForeignKeys: [(
destinationTable: String,
mapping: [(origin: String, destination: String?, seq: Int)])] = []
var previousId: Int? = nil
for row in try Row.fetchAll(self, sql: "PRAGMA foreign_key_list(\(tableName.quotedDatabaseIdentifier))") {
// row = [id:0 seq:0 table:"parents" from:"parentId" to:"id" on_update:"..." on_delete:"..." match:"..."]
@@ -224,9 +231,13 @@ extension Database {
let destination: String? = row[4]
if previousId == id {
rawForeignKeys[rawForeignKeys.count - 1].mapping.append((origin: origin, destination: destination, seq: seq))
rawForeignKeys[rawForeignKeys.count - 1]
.mapping
.append((origin: origin, destination: destination, seq: seq))
} else {
rawForeignKeys.append((destinationTable: table, mapping: [(origin: origin, destination: destination, seq: seq)]))
rawForeignKeys.append((
destinationTable: table,
mapping: [(origin: origin, destination: destination, seq: seq)]))
previousId = id
}
}
@@ -281,7 +292,7 @@ extension Database {
}
extension Database {
/// The columns in the table named `tableName`
///
/// - throws: A DatabaseError if table does not exist.
@@ -313,7 +324,7 @@ extension Database {
// 0 | id | INTEGER | 0 | NULL | 1 |
// 1 | name | TEXT | 0 | NULL | 0 |
// 2 | score | INTEGER | 0 | NULL | 0 |
if sqlite3_libversion_number() < 3008005 {
// Work around a bug in SQLite where PRAGMA table_info would
// return a result even after the table was deleted.
@@ -324,7 +335,7 @@ extension Database {
let columns = try ColumnInfo
.fetchAll(self, sql: "PRAGMA table_info(\(tableName.quotedDatabaseIdentifier))")
.sorted(by: { $0.cid < $1.cid })
guard columns.count > 0 else {
if columns.isEmpty {
throw DatabaseError(message: "no such table: \(tableName)")
}
@@ -335,14 +346,25 @@ extension Database {
/// If there exists a unique key on columns, return the columns
/// ordered as the matching index (or primay key). Case of returned columns
/// is not guaranteed.
func columnsForUniqueKey<T: Sequence>(_ columns: T, in tableName: String) throws -> [String]? where T.Iterator.Element == String {
let primaryKey = try self.primaryKey(tableName) // first, so that we fail early and consistently should the table not exist
func columnsForUniqueKey<T: Sequence>(
_ columns: T,
in tableName: String)
throws -> [String]?
where T.Iterator.Element == String
{
// Check primaryKey first, so that we fail early if the table does not exist
let primaryKey = try self.primaryKey(tableName)
let lowercasedColumns = Set(columns.map { $0.lowercased() })
if Set(primaryKey.columns.map { $0.lowercased() }) == lowercasedColumns {
return primaryKey.columns
}
if let index = try indexes(on: tableName).first(where: { index in index.isUnique && Set(index.columns.map { $0.lowercased() }) == lowercasedColumns }) {
// There is an explicit unique index on the columns
// Is there is an explicit unique index on the columns?
let indexes = try self.indexes(on: tableName)
let matchingIndex = indexes.first { index in
index.isUnique && Set(index.columns.map { $0.lowercased() }) == lowercasedColumns
}
if let index = matchingIndex {
return index.columns
}
return nil
@@ -366,7 +388,7 @@ extension Database {
/// 2 score INTEGER 0 NULL 0
///
/// See `Database.columns(in:)` and https://www.sqlite.org/pragma.html#pragma_table_info
public struct ColumnInfo : FetchableRecord {
public struct ColumnInfo: FetchableRecord {
let cid: Int
/// The column name
+8 -6
View File
@@ -1,10 +1,10 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
extension Database {
@@ -213,13 +213,15 @@ extension Database {
// Check that all arguments were consumed: it is a programmer error to
// provide arguments that do not match the statement.
if arguments.values.isEmpty == false {
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "wrong number of statement arguments: \(initialValuesCount)")
throw DatabaseError(
resultCode: .SQLITE_MISUSE,
message: "wrong number of statement arguments: \(initialValuesCount)")
}
}
}
extension Database {
func updateStatementWillExecute(_ statement: UpdateStatement) {
observationBroker.updateStatementWillExecute(statement)
}
@@ -294,7 +296,7 @@ struct StatementCache {
selectStatements[sql] = statement
return statement
}
mutating func updateStatement(_ sql: String) throws -> UpdateStatement {
if let statement = updateStatements[sql] {
return statement
+106 -83
View File
@@ -1,10 +1,10 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
/// A raw SQLite connection, suitable for the SQLite C API.
@@ -36,7 +36,7 @@ public final class Database {
public let sqliteConnection: SQLiteConnection
// MARK: - Configuration
/// The error logging function.
///
/// Quoting https://www.sqlite.org/errlog.html:
@@ -53,7 +53,7 @@ public final class Database {
if logError != nil {
registerErrorLogCallback { (_, code, message) in
guard let logError = Database.logError else { return }
guard let message = message.map({ String(cString: $0) }) else { return }
guard let message = message.map(String.init) else { return }
let resultCode = ResultCode(rawValue: code)
logError(resultCode, message)
}
@@ -137,11 +137,14 @@ public final class Database {
sqlite3_set_authorizer(sqliteConnection, nil, nil)
case (nil, .some):
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_set_authorizer(sqliteConnection, { (dbPointer, actionCode, cString1, cString2, cString3, cString4) -> Int32 in
guard let dbPointer = dbPointer else { return SQLITE_OK }
let db = Unmanaged<Database>.fromOpaque(dbPointer).takeUnretainedValue()
return db.authorizer!.authorize(actionCode, cString1, cString2, cString3, cString4)
}, dbPointer)
sqlite3_set_authorizer(
sqliteConnection,
{ (dbPointer, actionCode, cString1, cString2, cString3, cString4) -> Int32 in
guard let dbPointer = dbPointer else { return SQLITE_OK }
let db = Unmanaged<Database>.fromOpaque(dbPointer).takeUnretainedValue()
return db.authorizer!.authorize(actionCode, cString1, cString2, cString3, cString4)
},
dbPointer)
default:
break
}
@@ -164,9 +167,9 @@ public final class Database {
private var collations = Set<DatabaseCollation>()
private var _readOnlyDepth = 0 // Modify with beginReadOnly/endReadOnly
private var isClosed: Bool = false
// MARK: - Initializer
init(path: String, configuration: Configuration, schemaCache: DatabaseSchemaCache) throws {
self.sqliteConnection = try Database.openConnection(path: path, flags: configuration.SQLiteOpenFlags)
self.configuration = configuration
@@ -179,7 +182,7 @@ public final class Database {
}
extension Database {
// MARK: - Database Opening
private static func openConnection(path: String, flags: Int32) throws -> SQLiteConnection {
@@ -207,7 +210,7 @@ extension Database {
}
extension Database {
// MARK: - Database Setup
/// This method must be called after database initialization
@@ -220,14 +223,14 @@ extension Database {
setupDefaultCollations()
observationBroker.installCommitAndRollbackHooks()
try activateExtendedCodes()
#if SQLITE_HAS_CODEC
try validateSQLCipher()
if let passphrase = configuration.passphrase {
try setCipherPassphrase(passphrase)
}
#endif
// Last step before we can start accessing the database.
// This is the opportunity to run SQLCipher configuration
// pragmas such as cipher_page_size, for example.
@@ -240,24 +243,34 @@ extension Database {
guard configuration.trace != nil else {
return
}
// sqlite3_trace_v2 and sqlite3_expanded_sql were introduced in SQLite 3.14.0 http://www.sqlite.org/changes.html#version_3_14
// It is available from iOS 10.0 and OS X 10.12 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
// sqlite3_trace_v2 and sqlite3_expanded_sql were introduced in SQLite 3.14.0
// http://www.sqlite.org/changes.html#version_3_14
// It is available from iOS 10.0 and OS X 10.12
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
#if GRDBCUSTOMSQLITE || GRDBCIPHER
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_trace_v2(sqliteConnection, UInt32(SQLITE_TRACE_STMT), { (mask, dbPointer, stmt, unexpandedSQL) -> Int32 in
return Database.trace_v2(mask, dbPointer, stmt, unexpandedSQL, sqlite3_expanded_sql)
}, dbPointer)
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_trace_v2(
sqliteConnection,
UInt32(SQLITE_TRACE_STMT),
{ (mask, dbPointer, stmt, unexpandedSQL) -> Int32 in
Database.trace_v2(mask, dbPointer, stmt, unexpandedSQL, sqlite3_expanded_sql)
},
dbPointer)
#elseif os(Linux)
setupTrace_v1()
setupTrace_v1()
#else
if #available(iOS 10.0, OSX 10.12, watchOS 3.0, *) {
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_trace_v2(sqliteConnection, UInt32(SQLITE_TRACE_STMT), { (mask, dbPointer, stmt, unexpandedSQL) -> Int32 in
return Database.trace_v2(mask, dbPointer, stmt, unexpandedSQL, sqlite3_expanded_sql)
}, dbPointer)
} else {
setupTrace_v1()
}
if #available(iOS 10.0, OSX 10.12, watchOS 3.0, *) {
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_trace_v2(
sqliteConnection,
UInt32(SQLITE_TRACE_STMT),
{ (mask, dbPointer, stmt, unexpandedSQL) -> Int32 in
Database.trace_v2(mask, dbPointer, stmt, unexpandedSQL, sqlite3_expanded_sql)
},
dbPointer)
} else {
setupTrace_v1()
}
#endif
}
@@ -265,7 +278,7 @@ extension Database {
private func setupTrace_v1() {
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_trace(sqliteConnection, { (dbPointer, sql) in
guard let sql = sql.map({ String(cString: $0) }) else { return }
guard let sql = sql.map(String.init) else { return }
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
db.configuration.trace!(sql)
}, dbPointer)
@@ -391,7 +404,7 @@ extension Database {
}
extension Database {
// MARK: - Database Closing
/// This method must be called before database deallocation
@@ -409,18 +422,19 @@ extension Database {
private static func closeConnection(_ sqliteConnection: SQLiteConnection) {
// sqlite3_close_v2 was added in SQLite 3.7.14 http://www.sqlite.org/changes.html#version_3_7_14
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
// It is available from iOS 8.2 and OS X 10.10
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
#if GRDBCUSTOMSQLITE || GRDBCIPHER
closeConnection_v2(sqliteConnection, sqlite3_close_v2)
closeConnection_v2(sqliteConnection, sqlite3_close_v2)
#else
if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, *) {
closeConnection_v2(sqliteConnection, sqlite3_close_v2)
} else {
closeConnection_v1(sqliteConnection)
}
if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, *) {
closeConnection_v2(sqliteConnection, sqlite3_close_v2)
} else {
closeConnection_v1(sqliteConnection)
}
#endif
}
private static func closeConnection_v1(_ sqliteConnection: SQLiteConnection) {
// https://www.sqlite.org/c3ref/close.html
// > If the database connection is associated with unfinalized prepared
@@ -466,7 +480,7 @@ extension Database {
}
extension Database {
// MARK: - Functions
/// Add or redefine an SQL function.
@@ -492,7 +506,7 @@ extension Database {
}
extension Database {
// MARK: - Collations
/// Add or redefine a collation.
@@ -539,7 +553,8 @@ extension Database {
_readOnlyDepth += 1
if _readOnlyDepth == 1 && configuration.readonly == false {
// PRAGMA query_only was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
// It is available from iOS 8.2 and OS X 10.10
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
try internalCachedUpdateStatement(sql: "PRAGMA query_only = 1").execute()
}
}
@@ -548,7 +563,8 @@ extension Database {
_readOnlyDepth -= 1
if _readOnlyDepth == 0 && configuration.readonly == false {
// PRAGMA query_only was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
// It is available from iOS 8.2 and OS X 10.10
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
try internalCachedUpdateStatement(sql: "PRAGMA query_only = 0").execute()
}
}
@@ -583,7 +599,7 @@ extension Database {
}
extension Database {
// MARK: - Transactions & Savepoint
/// Executes a block inside a database transaction.
@@ -640,7 +656,7 @@ extension Database {
}
}
}
if let firstError = firstError {
throw firstError
}
@@ -674,7 +690,7 @@ extension Database {
if !isInsideTransaction && configuration.defaultTransactionKind != .deferred {
return try inTransaction(configuration.defaultTransactionKind, block)
}
// If the savepoint is top-level, we'll use ROLLBACK TRANSACTION in
// order to perform the special error handling of rollbacks (see
// the rollback method).
@@ -849,7 +865,7 @@ extension Database {
}
extension Database {
// MARK: - Memory Management
func releaseMemory() {
@@ -864,12 +880,18 @@ extension Database {
// MARK: - Backup
static func backup(from dbFrom: Database, to dbDest: Database, afterBackupInit: (() -> ())? = nil, afterBackupStep: (() -> ())? = nil) throws {
static func backup(
from dbFrom: Database,
to dbDest: Database,
afterBackupInit: (() -> Void)? = nil,
afterBackupStep: (() -> Void)? = nil)
throws
{
guard let backup = sqlite3_backup_init(dbDest.sqliteConnection, "main", dbFrom.sqliteConnection, "main") else {
throw DatabaseError(resultCode: dbDest.lastErrorCode, message: dbDest.lastErrorMessage)
}
guard Int(bitPattern: backup) != Int(SQLITE_ERROR) else {
throw DatabaseError(resultCode: .SQLITE_ERROR)
throw DatabaseError()
}
afterBackupInit?()
@@ -904,35 +926,36 @@ extension Database {
}
#if SQLITE_HAS_CODEC
extension Database {
// MARK: - Encryption
func change(passphrase: String) throws {
// FIXME: sqlite3_rekey is discouraged.
//
// https://github.com/ccgus/fmdb/issues/547#issuecomment-259219320
//
// > We (Zetetic) have been discouraging the use of sqlite3_rekey in
// > favor of attaching a new database with the desired encryption
// > options and using sqlcipher_export() to migrate the contents and
// > schema of the original db into the new one:
// > https://discuss.zetetic.net/t/how-to-encrypt-a-plaintext-sqlite-database-to-use-sqlcipher-and-avoid-file-is-encrypted-or-is-not-a-database-errors/
let data = passphrase.data(using: .utf8)!
#if swift(>=5.0)
let code = data.withUnsafeBytes {
sqlite3_rekey(sqliteConnection, $0.baseAddress, Int32($0.count))
}
#else
let code = data.withUnsafeBytes {
sqlite3_rekey(sqliteConnection, $0, Int32(data.count))
}
#endif
guard code == SQLITE_OK else {
throw DatabaseError(resultCode: code, message: lastErrorMessage)
}
extension Database {
// MARK: - Encryption
func change(passphrase: String) throws {
// FIXME: sqlite3_rekey is discouraged.
//
// https://github.com/ccgus/fmdb/issues/547#issuecomment-259219320
//
// > We (Zetetic) have been discouraging the use of sqlite3_rekey in
// > favor of attaching a new database with the desired encryption
// > options and using sqlcipher_export() to migrate the contents and
// > schema of the original db into the new one:
// > https://discuss.zetetic.net/t/how-to-encrypt-a-plaintext-sqlite-database-to-use-sqlcipher-and-avoid-file-is-encrypted-or-is-not-a-database-errors/
// swiftlint:disable:previous line_length
let data = passphrase.data(using: .utf8)!
#if swift(>=5.0)
let code = data.withUnsafeBytes {
sqlite3_rekey(sqliteConnection, $0.baseAddress, Int32($0.count))
}
#else
let code = data.withUnsafeBytes {
sqlite3_rekey(sqliteConnection, $0, Int32(data.count))
}
#endif
guard code == SQLITE_OK else {
throw DatabaseError(resultCode: code, message: lastErrorMessage)
}
}
}
#endif
extension Database {
@@ -991,7 +1014,7 @@ extension Database {
/// A built-in SQLite collation.
///
/// See https://www.sqlite.org/datatype3.html#collation
public struct CollationName : RawRepresentable, Hashable {
public struct CollationName: RawRepresentable, Hashable {
/// :nodoc:
public let rawValue: String
@@ -1022,7 +1045,7 @@ extension Database {
/// }
///
/// See https://www.sqlite.org/datatype3.html
public struct ColumnType : RawRepresentable, Hashable {
public struct ColumnType: RawRepresentable, Hashable {
/// :nodoc:
public let rawValue: String
@@ -1063,7 +1086,7 @@ extension Database {
/// An SQLite conflict resolution.
///
/// See https://www.sqlite.org/lang_conflict.html.
public enum ConflictResolution : String {
public enum ConflictResolution: String {
case rollback = "ROLLBACK"
case abort = "ABORT"
case fail = "FAIL"
@@ -1074,7 +1097,7 @@ extension Database {
/// A foreign key action.
///
/// See https://www.sqlite.org/foreignkeys.html
public enum ForeignKeyAction : String {
public enum ForeignKeyAction: String {
case cascade = "CASCADE"
case restrict = "RESTRICT"
case setNull = "SET NULL"
@@ -1091,7 +1114,7 @@ extension Database {
}
/// An SQLite transaction kind. See https://www.sqlite.org/lang_transaction.html
public enum TransactionKind : String {
public enum TransactionKind: String {
case deferred = "DEFERRED"
case immediate = "IMMEDIATE"
case exclusive = "EXCLUSIVE"
+13 -5
View File
@@ -1,10 +1,10 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
/// A Collation is a string comparison function used by SQLite.
@@ -27,8 +27,16 @@ public final class DatabaseCollation {
self.name = name
self.function = { (length1, buffer1, length2, buffer2) in
// Buffers are not C strings: they do not end with \0.
let string1 = String(bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer1.unsafelyUnwrapped), length: Int(length1), encoding: .utf8, freeWhenDone: false)!
let string2 = String(bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer2.unsafelyUnwrapped), length: Int(length2), encoding: .utf8, freeWhenDone: false)!
let string1 = String(
bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer1.unsafelyUnwrapped),
length: Int(length1),
encoding: .utf8,
freeWhenDone: false)!
let string2 = String(
bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer2.unsafelyUnwrapped),
length: Int(length2),
encoding: .utf8,
freeWhenDone: false)!
return function(string1, string2)
}
}
+24 -14
View File
@@ -1,13 +1,13 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible {
public struct ResultCode: RawRepresentable, Equatable, CustomStringConvertible {
public let rawValue: Int32
public init(rawValue: Int32) {
@@ -48,6 +48,7 @@ public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible
// Primary Result codes
// https://www.sqlite.org/rescode.html#primary_result_code_list
// swiftlint:disable operator_usage_whitespace
public static let SQLITE_OK = ResultCode(rawValue: 0) // Successful result
public static let SQLITE_ERROR = ResultCode(rawValue: 1) // SQL error or missing database
public static let SQLITE_INTERNAL = ResultCode(rawValue: 2) // Internal logic error in SQLite
@@ -79,10 +80,12 @@ public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible
public static let SQLITE_WARNING = ResultCode(rawValue: 28) // Warnings from sqlite3_log()
public static let SQLITE_ROW = ResultCode(rawValue: 100) // sqlite3_step() has another row ready
public static let SQLITE_DONE = ResultCode(rawValue: 101) // sqlite3_step() has finished executing
// swiftlint:enable operator_usage_whitespace
// Extended Result Code
// https://www.sqlite.org/rescode.html#extended_result_code_list
// swiftlint:disable operator_usage_whitespace
public static let SQLITE_IOERR_READ = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (1<<8)))
public static let SQLITE_IOERR_SHORT_READ = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (2<<8)))
public static let SQLITE_IOERR_WRITE = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (3<<8)))
@@ -139,21 +142,23 @@ public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible
public static let SQLITE_WARNING_AUTOINDEX = ResultCode(rawValue: (SQLITE_WARNING.rawValue | (1<<8)))
public static let SQLITE_AUTH_USER = ResultCode(rawValue: (SQLITE_AUTH.rawValue | (1<<8)))
public static let SQLITE_OK_LOAD_PERMANENTLY = ResultCode(rawValue: (SQLITE_OK.rawValue | (1<<8)))
// swiftlint:enable operator_usage_whitespace
}
// CustomStringConvertible
extension ResultCode {
var errorString: String? {
// sqlite3_errstr was added in SQLite 3.7.15 http://www.sqlite.org/changes.html#version_3_7_15
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
// It is available from iOS 8.2 and OS X 10.10
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
#if GRDBCUSTOMSQLITE || GRDBCIPHER
return String(cString: sqlite3_errstr(rawValue))
return String(cString: sqlite3_errstr(rawValue))
#else
if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, *) {
return String(cString: sqlite3_errstr(rawValue))
} else {
return nil
}
if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, *) {
return String(cString: sqlite3_errstr(rawValue))
} else {
return nil
}
#endif
}
@@ -168,7 +173,7 @@ extension ResultCode {
}
/// DatabaseError wraps an SQLite error.
public struct DatabaseError : Error, CustomStringConvertible, CustomNSError {
public struct DatabaseError: Error, CustomStringConvertible, CustomNSError {
/// The SQLite error code (see
/// https://www.sqlite.org/rescode.html#primary_result_code_list).
@@ -207,7 +212,12 @@ public struct DatabaseError : Error, CustomStringConvertible, CustomNSError {
public let sql: String?
/// Creates a Database Error
public init(resultCode: ResultCode = .SQLITE_ERROR, message: String? = nil, sql: String? = nil, arguments: StatementArguments? = nil) {
public init(
resultCode: ResultCode = .SQLITE_ERROR,
message: String? = nil,
sql: String? = nil,
arguments: StatementArguments? = nil)
{
self.extendedResultCode = resultCode
self.message = message ?? resultCode.errorString
self.sql = sql
@@ -264,7 +274,7 @@ extension DatabaseError {
/// NSError bridging: the user-info dictionary.
/// :nodoc:
public var errorUserInfo: [String : Any] {
public var errorUserInfo: [String: Any] {
return [NSLocalizedDescriptionKey: description]
}
}
+25 -9
View File
@@ -1,9 +1,9 @@
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
/// An SQL function or aggregate.
@@ -44,7 +44,12 @@ public final class DatabaseFunction: Hashable {
/// as Int, String, NSDate, etc. The array is guaranteed to have
/// exactly *argumentCount* elements, provided *argumentCount* is
/// not nil.
public init(_ name: String, argumentCount: Int32? = nil, pure: Bool = false, function: @escaping ([DatabaseValue]) throws -> DatabaseValueConvertible?) {
public init(
_ name: String,
argumentCount: Int32? = nil,
pure: Bool = false,
function: @escaping ([DatabaseValue]) throws -> DatabaseValueConvertible?)
{
self.identity = Identity(name: name, nArg: argumentCount ?? -1)
self.pure = pure
self.kind = .function{ (argc, argv) in
@@ -94,10 +99,15 @@ public final class DatabaseFunction: Hashable {
/// an array of DatabaseValue arguments. The array is guaranteed to
/// have exactly *argumentCount* elements, provided *argumentCount* is
/// not nil.
public init<Aggregate: DatabaseAggregate>(_ name: String, argumentCount: Int32? = nil, pure: Bool = false, aggregate: Aggregate.Type) {
public init<Aggregate: DatabaseAggregate>(
_ name: String,
argumentCount: Int32? = nil,
pure: Bool = false,
aggregate: Aggregate.Type)
{
self.identity = Identity(name: name, nArg: argumentCount ?? -1)
self.pure = pure
self.kind = .aggregate { return Aggregate() }
self.kind = .aggregate { Aggregate() }
}
/// Calls sqlite3_create_function_v2
@@ -197,7 +207,9 @@ public final class DatabaseFunction: Hashable {
var xFunc: (@convention(c) (OpaquePointer?, Int32, UnsafeMutablePointer<OpaquePointer?>?) -> Void)? {
guard case .function = self else { return nil }
return { (sqliteContext, argc, argv) in
let definition = Unmanaged<FunctionDefinition>.fromOpaque(sqlite3_user_data(sqliteContext)).takeUnretainedValue()
let definition = Unmanaged<FunctionDefinition>
.fromOpaque(sqlite3_user_data(sqliteContext))
.takeUnretainedValue()
do {
try DatabaseFunction.report(
result: definition.compute(argc, argv),
@@ -262,11 +274,15 @@ public final class DatabaseFunction: Hashable {
private static func unmanagedAggregateContext(_ sqliteContext: OpaquePointer?) -> Unmanaged<AggregateContext> {
// The current aggregate buffer
let stride = MemoryLayout<Unmanaged<AggregateContext>>.stride
let aggregateContextBufferP = UnsafeMutableRawBufferPointer(start: sqlite3_aggregate_context(sqliteContext, Int32(stride))!, count: stride)
let aggregateContextBufferP = UnsafeMutableRawBufferPointer(
start: sqlite3_aggregate_context(sqliteContext, Int32(stride))!,
count: stride)
if aggregateContextBufferP.contains(where: { $0 != 0 }) { // TODO: This testt looks weird. Review.
// Buffer contains non-null pointer: load aggregate context
let aggregateContextP = aggregateContextBufferP.baseAddress!.assumingMemoryBound(to: Unmanaged<AggregateContext>.self)
let aggregateContextP = aggregateContextBufferP
.baseAddress!
.assumingMemoryBound(to: Unmanaged<AggregateContext>.self)
return aggregateContextP.pointee
} else {
// Buffer contains null pointer: create aggregate context...
+46 -30
View File
@@ -1,14 +1,14 @@
import Foundation
import Dispatch
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
#if os(iOS)
import UIKit
import UIKit
#endif
/// A DatabasePool grants concurrent accesses to an SQLite database.
@@ -79,7 +79,10 @@ public final class DatabasePool: DatabaseWriter {
// opens a pool to an existing non-WAL database, and
// attempts to read from it.
// See https://github.com/groue/GRDB.swift/issues/102
try db.execute(sql: "CREATE TABLE grdb_issue_102 (id INTEGER PRIMARY KEY); DROP TABLE grdb_issue_102;")
try db.execute(sql: """
CREATE TABLE grdb_issue_102 (id INTEGER PRIMARY KEY);
DROP TABLE grdb_issue_102;
""")
}
}
}
@@ -87,8 +90,13 @@ public final class DatabasePool: DatabaseWriter {
// Readers
readerConfig = configuration
readerConfig.readonly = true
readerConfig.defaultTransactionKind = .deferred // Make it the default for readers. Other transaction kinds are forbidden by SQLite in read-only connections.
readerConfig.allowsUnsafeTransactions = false // Because there's no guarantee that one can get the same reader in order to close its opened transaction.
// Readers use deferred transactions by default.
// Other transaction kinds are forbidden by SQLite in read-only connections.
readerConfig.defaultTransactionKind = .deferred
// Readers can't allow dangling transactions because there's no
// guarantee that one can get the same reader later in order to close
// an opened transaction.
readerConfig.allowsUnsafeTransactions = false
var readerCount = 0
readerPool = Pool(maximumCount: configuration.maximumReaderCount, makeElement: { [unowned self] in
readerCount += 1 // protected by pool's ReadWriteBox (undocumented behavior and protection)
@@ -134,9 +142,9 @@ public final class DatabasePool: DatabaseWriter {
}
extension DatabasePool {
// MARK: - WAL Checkpoints
/// Runs a WAL checkpoint
///
/// See https://www.sqlite.org/wal.html and
@@ -151,16 +159,16 @@ extension DatabasePool {
// when kind is not .Passive.
let code = sqlite3_wal_checkpoint_v2(db.sqliteConnection, nil, kind.rawValue, nil, nil)
guard code == SQLITE_OK else {
throw DatabaseError(resultCode: code, message: db.lastErrorMessage, sql: nil)
throw DatabaseError(resultCode: code, message: db.lastErrorMessage)
}
}
}
}
extension DatabasePool {
// MARK: - Memory management
/// Free as much memory as possible.
///
/// This method blocks the current thread until all database accesses are completed.
@@ -195,7 +203,8 @@ extension DatabasePool {
object: nil)
}
@objc private func applicationDidEnterBackground(_ notification: NSNotification) {
@objc
private func applicationDidEnterBackground(_ notification: NSNotification) {
guard let application = application else {
return
}
@@ -213,7 +222,8 @@ extension DatabasePool {
}
}
@objc private func applicationDidReceiveMemoryWarning(_ notification: NSNotification) {
@objc
private func applicationDidReceiveMemoryWarning(_ notification: NSNotification) {
DispatchQueue.global().async {
self.releaseMemory()
}
@@ -222,24 +232,24 @@ extension DatabasePool {
}
#if SQLITE_HAS_CODEC
extension DatabasePool {
// MARK: - Encryption
/// Changes the passphrase of an encrypted database
public func change(passphrase: String) throws {
try readerPool.clear(andThen: {
try writer.sync { try $0.change(passphrase: passphrase) }
readerConfig.passphrase = passphrase
})
}
extension DatabasePool {
// MARK: - Encryption
/// Changes the passphrase of an encrypted database
public func change(passphrase: String) throws {
try readerPool.clear(andThen: {
try writer.sync { try $0.change(passphrase: passphrase) }
readerConfig.passphrase = passphrase
})
}
}
#endif
extension DatabasePool : DatabaseReader {
extension DatabasePool: DatabaseReader {
// MARK: - Reading from Database
/// Synchronously executes a read-only block in a protected dispatch queue,
/// and returns its result. The block is wrapped in a deferred transaction.
///
@@ -493,7 +503,7 @@ extension DatabasePool : DatabaseReader {
asyncConcurrentRead(block)
}
#endif
#if compiler(>=5.0)
/// Asynchronously executes a read-only block in a protected dispatch queue.
///
@@ -649,7 +659,11 @@ extension DatabasePool : DatabaseReader {
/// - updates: The updates to the database.
/// - throws: The error thrown by the updates, or by the
/// wrapping transaction.
public func writeInTransaction(_ kind: Database.TransactionKind? = nil, _ updates: (Database) throws -> Database.TransactionCompletion) throws {
public func writeInTransaction(
_ kind: Database.TransactionKind? = nil,
_ updates: (Database) throws -> Database.TransactionCompletion)
throws
{
try writer.sync { db in
try db.inTransaction(kind) {
try updates(db)
@@ -811,7 +825,9 @@ extension DatabasePool {
// Sanity check
if writer.onValidQueue {
writer.execute { db in
GRDBPrecondition(!db.isInsideTransaction, "makeSnapshot() must not be called from inside a transaction.")
GRDBPrecondition(
!db.isInsideTransaction,
"makeSnapshot() must not be called from inside a transaction.")
}
}
+21 -15
View File
@@ -71,9 +71,9 @@ public final class DatabaseQueue: DatabaseWriter {
}
extension DatabaseQueue {
// MARK: - Memory management
/// Free as much memory as possible.
///
/// This method blocks the current thread until all database accesses are completed.
@@ -106,7 +106,8 @@ extension DatabaseQueue {
object: nil)
}
@objc private func applicationDidEnterBackground(_ notification: NSNotification) {
@objc
private func applicationDidEnterBackground(_ notification: NSNotification) {
guard let application = application else {
return
}
@@ -124,7 +125,8 @@ extension DatabaseQueue {
}
}
@objc private func applicationDidReceiveMemoryWarning(_ notification: NSNotification) {
@objc
private func applicationDidReceiveMemoryWarning(_ notification: NSNotification) {
DispatchQueue.global().async {
self.releaseMemory()
}
@@ -133,15 +135,15 @@ extension DatabaseQueue {
}
#if SQLITE_HAS_CODEC
extension DatabaseQueue {
// MARK: - Encryption
/// Changes the passphrase of an encrypted database
public func change(passphrase: String) throws {
try writer.sync { try $0.change(passphrase: passphrase) }
}
extension DatabaseQueue {
// MARK: - Encryption
/// Changes the passphrase of an encrypted database
public func change(passphrase: String) throws {
try writer.sync { try $0.change(passphrase: passphrase) }
}
}
#endif
extension DatabaseQueue {
@@ -202,7 +204,7 @@ extension DatabaseQueue {
}
}
#endif
/// Synchronously executes a block in a protected dispatch queue, and
/// returns its result.
///
@@ -302,7 +304,11 @@ extension DatabaseQueue {
/// - updates: The updates to the database.
/// - throws: The error thrown by the updates, or by the
/// wrapping transaction.
public func inTransaction(_ kind: Database.TransactionKind? = nil, _ updates: (Database) throws -> Database.TransactionCompletion) throws {
public func inTransaction(
_ kind: Database.TransactionKind? = nil,
_ updates: (Database) throws -> Database.TransactionCompletion)
throws
{
try writer.sync { db in
try db.inTransaction(kind) {
try updates(db)
@@ -323,7 +329,7 @@ extension DatabaseQueue {
public func writeWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
return try writer.sync(updates)
}
/// Synchronously executes database updates in a protected dispatch queue,
/// outside of any transaction, and returns the result.
///
+11 -7
View File
@@ -1,9 +1,9 @@
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
/// The protocol for all types that can fetch values from a database.
@@ -21,7 +21,7 @@
/// connection to the database. Should you have to cope with external
/// connections, protect yourself with transactions, and be ready to setup a
/// [busy handler](https://www.sqlite.org/c3ref/busy_handler.html).
public protocol DatabaseReader : class {
public protocol DatabaseReader: AnyObject {
/// The database configuration
var configuration: Configuration { get }
@@ -220,10 +220,14 @@ extension DatabaseReader {
try backup(to: writer, afterBackupInit: nil, afterBackupStep: nil)
}
func backup(to writer: DatabaseWriter, afterBackupInit: (() -> ())?, afterBackupStep: (() -> ())?) throws {
func backup(to writer: DatabaseWriter, afterBackupInit: (() -> Void)?, afterBackupStep: (() -> Void)?) throws {
try read { dbFrom in
try writer.writeWithoutTransaction { dbDest in
try Database.backup(from: dbFrom, to: dbDest, afterBackupInit: afterBackupInit, afterBackupStep: afterBackupStep)
try Database.backup(
from: dbFrom,
to: dbDest,
afterBackupInit: afterBackupInit,
afterBackupStep: afterBackupStep)
}
}
}
@@ -233,7 +237,7 @@ extension DatabaseReader {
///
/// Instances of AnyDatabaseReader forward their methods to an arbitrary
/// underlying database reader.
public final class AnyDatabaseReader : DatabaseReader {
public final class AnyDatabaseReader: DatabaseReader {
private let base: DatabaseReader
/// Creates a database reader that wraps a base database reader.
+16 -14
View File
@@ -31,6 +31,7 @@
/// let region = try request.databaseRegion(db)
public struct DatabaseRegion: CustomStringConvertible, Equatable {
private let tableRegions: [String: TableRegion]?
private init(tableRegions: [String: TableRegion]?) {
self.tableRegions = tableRegions
}
@@ -125,9 +126,9 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable {
switch (tableRegion, otherTableRegion) {
case (nil, nil):
preconditionFailure()
case (nil, let tableRegion?), (let tableRegion?, nil):
case let (nil, tableRegion?), let (tableRegion?, nil):
tableRegionUnion = tableRegion
case (let tableRegion?, let otherTableRegion?):
case let (tableRegion?, otherTableRegion?):
tableRegionUnion = tableRegion.union(otherTableRegion)
}
tableRegionsUnion[table] = tableRegionUnion
@@ -184,7 +185,10 @@ extension DatabaseRegion {
// Slow path when several tables are observed.
guard let tableRegion = tableRegions[event.tableName] else {
// Shouldn't happen if the precondition is met.
fatalError("precondition failure: event was not filtered out in observes(eventsOfKind:) by region.isModified(byEventsOfKind:)")
fatalError("""
precondition failure: event was not filtered out in observes(eventsOfKind:) \
by region.isModified(byEventsOfKind:)
""")
}
return tableRegion.contains(rowID: event.rowID)
}
@@ -198,16 +202,14 @@ extension DatabaseRegion {
switch (lhs.tableRegions, rhs.tableRegions) {
case (nil, nil):
return true
case (let ltableRegions?, let rtableRegions?):
case let (ltableRegions?, rtableRegions?):
let ltableNames = Set(ltableRegions.keys)
let rtableNames = Set(rtableRegions.keys)
guard ltableNames == rtableNames else {
return false
}
for tableName in ltableNames {
if ltableRegions[tableName]! != rtableRegions[tableName]! {
return false
}
for tableName in ltableNames where ltableRegions[tableName]! != rtableRegions[tableName]! {
return false
}
return true
default:
@@ -257,17 +259,17 @@ private struct TableRegion: Equatable {
func intersection(_ other: TableRegion) -> TableRegion {
let columnsIntersection: Set<String>?
switch (self.columns, other.columns) {
case (nil, let columns), (let columns, nil):
case let (nil, columns), let (columns, nil):
columnsIntersection = columns
case (let columns?, let other?):
case let (columns?, other?):
columnsIntersection = columns.intersection(other)
}
let rowIdsIntersection: Set<Int64>?
switch (self.rowIds, other.rowIds) {
case (nil, let rowIds), (let rowIds, nil):
case let (nil, rowIds), let (rowIds, nil):
rowIdsIntersection = rowIds
case (let rowIds?, let other?):
case let (rowIds?, other?):
rowIdsIntersection = rowIds.intersection(other)
}
@@ -279,7 +281,7 @@ private struct TableRegion: Equatable {
switch (self.columns, other.columns) {
case (nil, _), (_, nil):
columnsUnion = nil
case (let columns?, let other?):
case let (columns?, other?):
columnsUnion = columns.union(other)
}
@@ -287,7 +289,7 @@ private struct TableRegion: Equatable {
switch (self.rowIds, other.rowIds) {
case (nil, _), (_, nil):
rowIdsUnion = nil
case (let rowIds?, let other?):
case let (rowIds?, other?):
rowIdsUnion = rowIds.union(other)
}
+7 -3
View File
@@ -18,7 +18,7 @@ public struct DatabaseRegionObservation {
/// A closure that is evaluated when the observation starts, and returns
/// the observed database region.
var observedRegion: (Database) throws -> DatabaseRegion
// Not public because we foster DatabaseRegionConvertible.
init(tracking region: @escaping (Database) throws -> DatabaseRegion) {
self.observedRegion = { db in
@@ -87,7 +87,11 @@ extension DatabaseRegionObservation {
/// - parameter onChange: A closure that is provided a database connection
/// with write access each time the observed region has been modified.
/// - returns: a TransactionObserver
public func start(in dbWriter: DatabaseWriter, onChange: @escaping (Database) -> Void) throws -> TransactionObserver {
public func start(
in dbWriter: DatabaseWriter,
onChange: @escaping (Database) -> Void)
throws -> TransactionObserver
{
// Use unsafeReentrantWrite so that observation can start from any
// dispatch queue.
return try dbWriter.unsafeReentrantWrite { db -> TransactionObserver in
@@ -123,7 +127,7 @@ private class DatabaseRegionObserver: TransactionObserver {
func databaseDidCommit(_ db: Database) {
guard isChanged else { return }
isChanged = false
onChange(db)
}
+1 -1
View File
@@ -6,7 +6,7 @@ import Dispatch
/// See DatabasePool.makeSnapshot()
///
/// For more information, read about "snapshot isolation" at https://sqlite.org/isolation.html
public class DatabaseSnapshot : DatabaseReader {
public class DatabaseSnapshot: DatabaseReader {
private var serializedDatabase: SerializedDatabase
/// The database configuration
+25 -23
View File
@@ -1,10 +1,10 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
// MARK: - DatabaseValue
@@ -20,7 +20,7 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon
public static let null = DatabaseValue(storage: .null)
/// An SQLite storage (NULL, INTEGER, REAL, TEXT, BLOB).
public enum Storage : Equatable {
public enum Storage: Equatable {
/// The NULL storage class.
case null
@@ -60,10 +60,10 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon
public static func == (_ lhs: Storage, _ rhs: Storage) -> Bool {
switch (lhs, rhs) {
case (.null, .null): return true
case (.int64(let lhs), .int64(let rhs)): return lhs == rhs
case (.double(let lhs), .double(let rhs)): return lhs == rhs
case (.string(let lhs), .string(let rhs)): return lhs == rhs
case (.blob(let lhs), .blob(let rhs)): return lhs == rhs
case let (.int64(lhs), .int64(rhs)): return lhs == rhs
case let (.double(lhs), .double(rhs)): return lhs == rhs
case let (.string(lhs), .string(rhs)): return lhs == rhs
case let (.blob(lhs), .blob(rhs)): return lhs == rhs
default: return false
}
}
@@ -120,7 +120,7 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon
fatalError("Unexpected SQLite value type: \(type)")
}
}
/// Returns a DatabaseValue initialized from a raw SQLite statement pointer.
init(sqliteStatement: SQLiteStatement, index: Int32) {
switch sqlite3_column_type(sqliteStatement, index) {
@@ -187,17 +187,17 @@ extension DatabaseValue {
switch (lhs.storage, rhs.storage) {
case (.null, .null):
return true
case (.int64(let lhs), .int64(let rhs)):
case let (.int64(lhs), .int64(rhs)):
return lhs == rhs
case (.double(let lhs), .double(let rhs)):
case let (.double(lhs), .double(rhs)):
return lhs == rhs
case (.int64(let lhs), .double(let rhs)):
case let (.int64(lhs), .double(rhs)):
return Int64(exactly: rhs) == lhs
case (.double(let lhs), .int64(let rhs)):
case let (.double(lhs), .int64(rhs)):
return rhs == Int64(exactly: lhs)
case (.string(let lhs), .string(let rhs)):
case let (.string(lhs), .string(rhs)):
return lhs == rhs
case (.blob(let lhs), .blob(let rhs)):
case let (.blob(lhs), .blob(rhs)):
return lhs == rhs
default:
return false
@@ -266,8 +266,10 @@ extension DatabaseValue {
case .blob:
// We can't assume all blobs are true, and return false:
//
// SELECT NOT X'31' -- 0 (because X'31' is turned into the string '1', then into integer 1, which is negated into 0)
// SELECT NOT X'30' -- 1 (because X'30' is turned into the string '0', then into integer 0, which is negated into 1)
// SELECT NOT X'31' -- 0 (because X'31' is turned into the string '1',
// then into integer 1, which is negated into 0)
// SELECT NOT X'30' -- 1 (because X'30' is turned into the string '0',
// then into integer 0, which is negated into 1)
return SQLExpressionNot(self)
}
}
@@ -309,17 +311,17 @@ extension DatabaseValue {
/// easier testing.
func < (lhs: DatabaseValue, rhs: DatabaseValue) -> Bool {
switch (lhs.storage, rhs.storage) {
case (.int64(let lhs), .int64(let rhs)):
case let (.int64(lhs), .int64(rhs)):
return lhs < rhs
case (.double(let lhs), .double(let rhs)):
case let (.double(lhs), .double(rhs)):
return lhs < rhs
case (.int64(let lhs), .double(let rhs)):
case let (.int64(lhs), .double(rhs)):
return Double(lhs) < rhs
case (.double(let lhs), .int64(let rhs)):
case let (.double(lhs), .int64(rhs)):
return lhs < Double(rhs)
case (.string(let lhs), .string(let rhs)):
case let (.string(lhs), .string(rhs)):
return lhs.utf8.lexicographicallyPrecedes(rhs.utf8)
case (.blob(let lhs), .blob(let rhs)):
case let (.blob(lhs), .blob(rhs)):
return lhs.lexicographicallyPrecedes(rhs, by: <)
case (.blob, _):
return false
+72 -14
View File
@@ -1,9 +1,9 @@
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
// MARK: - Conversion Context and Errors
@@ -14,6 +14,7 @@ struct ValueConversionContext {
case columnIndex(Int)
case columnName(String)
}
var row: Row?
var sql: String?
var arguments: StatementArguments?
@@ -89,7 +90,12 @@ extension ValueConversionContext {
/// The canonical conversion error message
///
/// - parameter dbValue: nil means "missing column"
func conversionErrorMessage<T>(to: T.Type, from dbValue: DatabaseValue?, conversionContext: ValueConversionContext?) -> String {
func conversionErrorMessage<T>(
to: T.Type,
from dbValue: DatabaseValue?,
conversionContext: ValueConversionContext?)
-> String
{
var message: String
var extras: [String] = []
@@ -128,12 +134,33 @@ func conversionErrorMessage<T>(to: T.Type, from dbValue: DatabaseValue?, convers
/// The canonical conversion fatal error
///
/// - parameter dbValue: nil means "missing column", for consistency with (row["missing"] as DatabaseValue? == nil)
func fatalConversionError<T>(to: T.Type, from dbValue: DatabaseValue?, conversionContext: ValueConversionContext?, file: StaticString = #file, line: UInt = #line) -> Never {
fatalError(conversionErrorMessage(to: T.self, from: dbValue, conversionContext: conversionContext), file: file, line: line)
func fatalConversionError<T>(
to: T.Type,
from dbValue: DatabaseValue?,
conversionContext: ValueConversionContext?,
file: StaticString = #file,
line: UInt = #line)
-> Never
{
fatalError(
conversionErrorMessage(
to: T.self,
from: dbValue,
conversionContext: conversionContext),
file: file,
line: line)
}
@usableFromInline
func fatalConversionError<T>(to: T.Type, from dbValue: DatabaseValue?, in row: Row, atColumn columnName: String, file: StaticString = #file, line: UInt = #line) -> Never {
func fatalConversionError<T>(
to: T.Type,
from dbValue: DatabaseValue?,
in row: Row,
atColumn columnName: String,
file: StaticString = #file,
line: UInt = #line)
-> Never
{
fatalConversionError(
to: T.self,
from: dbValue,
@@ -141,7 +168,14 @@ func fatalConversionError<T>(to: T.Type, from dbValue: DatabaseValue?, in row: R
}
@usableFromInline
func fatalConversionError<T>(to: T.Type, sqliteStatement: SQLiteStatement, index: Int32, file: StaticString = #file, line: UInt = #line) -> Never {
func fatalConversionError<T>(
to: T.Type,
sqliteStatement: SQLiteStatement,
index: Int32,
file: StaticString = #file,
line: UInt = #line)
-> Never
{
let row = Row(sqliteStatement: sqliteStatement)
fatalConversionError(
to: T.self,
@@ -150,7 +184,15 @@ func fatalConversionError<T>(to: T.Type, sqliteStatement: SQLiteStatement, index
}
@usableFromInline
func fatalConversionError<T>(to: T.Type, from dbValue: DatabaseValue?, sqliteStatement: SQLiteStatement, index: Int32, file: StaticString = #file, line: UInt = #line) -> Never {
func fatalConversionError<T>(
to: T.Type,
from dbValue: DatabaseValue?,
sqliteStatement: SQLiteStatement,
index: Int32,
file: StaticString = #file,
line: UInt = #line)
-> Never
{
let row = Row(sqliteStatement: sqliteStatement)
fatalConversionError(
to: T.self,
@@ -172,7 +214,11 @@ extension DatabaseValueConvertible {
}
}
static func decode(from dbValue: DatabaseValue, conversionContext: @autoclosure () -> ValueConversionContext?) -> Self {
static func decode(
from dbValue: DatabaseValue,
conversionContext: @autoclosure () -> ValueConversionContext?)
-> Self
{
if let value = fromDatabaseValue(dbValue) {
return value
} else {
@@ -198,8 +244,12 @@ extension DatabaseValueConvertible {
fatalConversionError(to: Self.self, from: dbValue, sqliteStatement: sqliteStatement, index: index)
}
}
static func decodeIfPresent(from dbValue: DatabaseValue, conversionContext: @autoclosure () -> ValueConversionContext?) -> Self? {
static func decodeIfPresent(
from dbValue: DatabaseValue,
conversionContext: @autoclosure () -> ValueConversionContext?)
-> Self?
{
// Use fromDatabaseValue before checking for null: this allows DatabaseValue to convert NULL to .null.
if let value = fromDatabaseValue(dbValue) {
return value
@@ -258,12 +308,20 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
// Support for @inlinable decoding
extension Row {
@usableFromInline
func fastDecode<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ type: Value.Type, atUncheckedIndex index: Int) -> Value {
func fastDecode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
_ type: Value.Type,
atUncheckedIndex index: Int)
-> Value
{
return impl.fastDecode(type, atUncheckedIndex: index)
}
@usableFromInline
func fastDecodeIfPresent<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ type: Value.Type, atUncheckedIndex index: Int) -> Value? {
func fastDecodeIfPresent<Value: DatabaseValueConvertible & StatementColumnConvertible>(
_ type: Value.Type,
atUncheckedIndex index: Int)
-> Value?
{
return impl.fastDecodeIfPresent(type, atUncheckedIndex: index)
}
}
+76 -20
View File
@@ -1,9 +1,9 @@
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
// MARK: - DatabaseValueConvertible
@@ -24,7 +24,7 @@
/// try String.fetchOne(statement, arguments:...) // String?
///
/// DatabaseValueConvertible is adopted by Bool, Int, String, etc.
public protocol DatabaseValueConvertible : SQLExpressible {
public protocol DatabaseValueConvertible: SQLExpressible {
/// Returns a value that can be stored in the database.
var databaseValue: DatabaseValue { get }
@@ -49,7 +49,7 @@ extension DatabaseValueConvertible {
/// print(url)
/// }
/// }
public final class DatabaseValueCursor<Value: DatabaseValueConvertible> : Cursor {
public final class DatabaseValueCursor<Value: DatabaseValueConvertible>: Cursor {
@usableFromInline let _statement: SelectStatement
@usableFromInline let _sqliteStatement: SQLiteStatement
@usableFromInline let _columnIndex: Int32
@@ -102,12 +102,12 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible> : Cursor
/// print(url)
/// }
/// }
public final class NullableDatabaseValueCursor<Value: DatabaseValueConvertible> : Cursor {
public final class NullableDatabaseValueCursor<Value: DatabaseValueConvertible>: Cursor {
@usableFromInline let _statement: SelectStatement
@usableFromInline let _sqliteStatement: SQLiteStatement
@usableFromInline let _columnIndex: Int32
@usableFromInline var _done = false
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
_statement = statement
_sqliteStatement = statement.sqliteStatement
@@ -182,7 +182,12 @@ extension DatabaseValueConvertible {
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseValueCursor<Self> {
public static func fetchCursor(
_ statement: SelectStatement,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> DatabaseValueCursor<Self>
{
return try DatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter)
}
@@ -197,7 +202,12 @@ extension DatabaseValueConvertible {
/// - adapter: Optional RowAdapter
/// - returns: An array.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] {
public static func fetchAll(
_ statement: SelectStatement,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> [Self]
{
return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
}
@@ -215,7 +225,12 @@ extension DatabaseValueConvertible {
/// - adapter: Optional RowAdapter
/// - returns: An optional value.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? {
public static func fetchOne(
_ statement: SelectStatement,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> Self?
{
// fetchOne returns nil if there is no row, or if there is a row with a null value
let cursor = try NullableDatabaseValueCursor<Self>(statement: statement, arguments: arguments, adapter: adapter)
return try cursor.next() ?? nil
@@ -223,7 +238,7 @@ extension DatabaseValueConvertible {
}
extension DatabaseValueConvertible {
// MARK: Fetching From SQL
/// Returns a cursor over values fetched from an SQL query.
@@ -245,7 +260,13 @@ extension DatabaseValueConvertible {
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> DatabaseValueCursor<Self> {
public static func fetchCursor(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: RowAdapter? = nil)
throws -> DatabaseValueCursor<Self>
{
return try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
@@ -260,7 +281,13 @@ extension DatabaseValueConvertible {
/// - adapter: Optional RowAdapter
/// - returns: An array.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Self] {
public static func fetchAll(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: RowAdapter? = nil)
throws -> [Self]
{
return try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
@@ -278,7 +305,13 @@ extension DatabaseValueConvertible {
/// - adapter: Optional RowAdapter
/// - returns: An optional value.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> Self? {
public static func fetchOne(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: RowAdapter? = nil)
throws -> Self?
{
return try fetchOne(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
}
@@ -430,7 +463,12 @@ extension Optional where Wrapped: DatabaseValueConvertible {
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor<Wrapped> {
public static func fetchCursor(
_ statement: SelectStatement,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> NullableDatabaseValueCursor<Wrapped>
{
return try NullableDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter)
}
@@ -445,7 +483,12 @@ extension Optional where Wrapped: DatabaseValueConvertible {
/// - adapter: Optional RowAdapter
/// - returns: An array of optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] {
public static func fetchAll(
_ statement: SelectStatement,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> [Wrapped?]
{
return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
}
}
@@ -473,7 +516,13 @@ extension Optional where Wrapped: DatabaseValueConvertible {
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor<Wrapped> {
public static func fetchCursor(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: RowAdapter? = nil)
throws -> NullableDatabaseValueCursor<Wrapped>
{
return try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
@@ -488,7 +537,13 @@ extension Optional where Wrapped: DatabaseValueConvertible {
/// - adapter: Optional RowAdapter
/// - returns: An array of optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Wrapped?] {
public static func fetchAll(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: RowAdapter? = nil)
throws -> [Wrapped?]
{
return try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
}
@@ -515,7 +570,9 @@ extension Optional where Wrapped: DatabaseValueConvertible {
/// - request: A FetchRequest.
/// - returns: A cursor over fetched optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor<R: FetchRequest>(_ db: Database, _ request: R) throws -> NullableDatabaseValueCursor<Wrapped> {
public static func fetchCursor<R: FetchRequest>(_ db: Database, _ request: R)
throws -> NullableDatabaseValueCursor<Wrapped>
{
let request = try request.makePreparedRequest(db, forSingleResult: false)
return try fetchCursor(request.statement, adapter: request.adapter)
}
@@ -572,4 +629,3 @@ extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped:
return try Optional<RowDecoder._Wrapped>.fetchAll(db, self)
}
}
+28 -15
View File
@@ -15,10 +15,10 @@ import Dispatch
/// connection to the database. Should you have to cope with external
/// connections, protect yourself with transactions, and be ready to setup a
/// [busy handler](https://www.sqlite.org/c3ref/busy_handler.html).
public protocol DatabaseWriter : DatabaseReader {
public protocol DatabaseWriter: DatabaseReader {
// MARK: - Writing in Database
/// Synchronously executes database updates in a protected dispatch queue,
/// wrapped inside a transaction, and returns the result.
///
@@ -76,16 +76,18 @@ public protocol DatabaseWriter : DatabaseReader {
/// - parameter completion: A closure that is called with the eventual
/// transaction error.
/// - throws: The error thrown by the updates, or by the wrapping transaction.
func asyncWrite<T>(_ updates: @escaping (Database) throws -> T, completion: @escaping (Database, Result<T, Error>) -> Void)
func asyncWrite<T>(
_ updates: @escaping (Database) throws -> T,
completion: @escaping (Database, Result<T, Error>) -> Void)
#endif
/// Asynchronously executes database updates in a protected dispatch queue,
/// outside of any transaction.
///
/// Eventual concurrent reads may see partial updates unless you wrap them
/// in a transaction.
func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void)
/// Synchronously executes database updates in a protected dispatch queue,
/// outside of any transaction, and returns the result.
///
@@ -98,7 +100,7 @@ public protocol DatabaseWriter : DatabaseReader {
/// This method is reentrant. It should be avoided because it fosters
/// dangerous concurrency practices.
func unsafeReentrantWrite<T>(_ updates: (Database) throws -> T) rethrows -> T
// MARK: - Reading from Database
/// Concurrently executes a read-only block in a protected dispatch queue.
@@ -175,7 +177,7 @@ public protocol DatabaseWriter : DatabaseReader {
}
extension DatabaseWriter {
/// Synchronously executes database updates in a protected dispatch queue,
/// wrapped inside a transaction, and returns the result.
///
@@ -228,7 +230,10 @@ extension DatabaseWriter {
/// - parameter completion: A closure that is called with the eventual
/// transaction error.
/// - throws: The error thrown by the updates, or by the wrapping transaction.
public func asyncWrite<T>(_ updates: @escaping (Database) throws -> T, completion: @escaping (Database, Result<T, Error>) -> Void) {
public func asyncWrite<T>(
_ updates: @escaping (Database) throws -> T,
completion: @escaping (Database, Result<T, Error>) -> Void)
{
asyncWriteWithoutTransaction { db in
do {
var result: T?
@@ -255,7 +260,10 @@ extension DatabaseWriter {
/// - parameter extent: The duration of the observation. The default is
/// the observer lifetime (observation lasts until observer
/// is deallocated).
public func add(transactionObserver: TransactionObserver, extent: Database.TransactionObservationExtent = .observerLifetime) {
public func add(
transactionObserver: TransactionObserver,
extent: Database.TransactionObservationExtent = .observerLifetime)
{
writeWithoutTransaction { $0.add(transactionObserver: transactionObserver, extent: extent) }
}
@@ -273,7 +281,8 @@ extension DatabaseWriter {
/// execution of this method.
public func erase() throws {
#if SQLITE_HAS_CODEC
// SQLCipher does not support the backup API: https://discuss.zetetic.net/t/using-the-sqlite-online-backup-api/2631
// SQLCipher does not support the backup API:
// https://discuss.zetetic.net/t/using-the-sqlite-online-backup-api/2631
// So we'll drop all database objects one after the other.
try writeWithoutTransaction { db in
// Prevent foreign keys from messing with drop table statements
@@ -285,7 +294,8 @@ extension DatabaseWriter {
// Remove all database objects, one after the other
do {
try db.inTransaction {
while let row = try Row.fetchOne(db, sql: "SELECT type, name FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'") {
let sql = "SELECT type, name FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'"
while let row = try Row.fetchOne(db, sql: sql) {
let type: String = row["type"]
let name: String = row["name"]
try db.execute(sql: "DROP \(type) \(name.quotedDatabaseIdentifier)")
@@ -545,7 +555,7 @@ public class DatabaseFuture<Value> {
///
/// Instances of AnyDatabaseWriter forward their methods to an arbitrary
/// underlying database writer.
public final class AnyDatabaseWriter : DatabaseWriter {
public final class AnyDatabaseWriter: DatabaseWriter {
private let base: DatabaseWriter
/// Creates a database writer that wraps a base database writer.
@@ -608,7 +618,10 @@ public final class AnyDatabaseWriter : DatabaseWriter {
#if compiler(>=5.0)
/// :nodoc:
public func asyncWrite<T>(_ updates: @escaping (Database) throws -> T, completion: @escaping (Database, Result<T, Error>) -> Void) {
public func asyncWrite<T>(
_ updates: @escaping (Database) throws -> T,
completion: @escaping (Database, Result<T, Error>) -> Void)
{
base.asyncWrite(updates, completion: completion)
}
#endif
@@ -617,12 +630,12 @@ public final class AnyDatabaseWriter : DatabaseWriter {
public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
base.asyncWriteWithoutTransaction(updates)
}
/// :nodoc:
public func unsafeReentrantWrite<T>(_ updates: (Database) throws -> T) rethrows -> T {
return try base.unsafeReentrantWrite(updates)
}
// MARK: - Functions
/// :nodoc:
+5 -5
View File
@@ -23,7 +23,7 @@ public struct PreparedRequest {
{
self.init(statement: statement, adapter: adapter, supplementaryFetch: nil)
}
init(
statement: SelectStatement,
adapter: RowAdapter?,
@@ -62,7 +62,7 @@ public protocol FetchRequest: DatabaseRegionConvertible {
/// prepared statement.
/// - returns: A prepared statement and an eventual row adapter.
func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?)
/// Returns a PreparedRequest that is ready to be executed.
///
/// - parameter db: A database connection.
@@ -86,7 +86,7 @@ public protocol FetchRequest: DatabaseRegionConvertible {
}
extension FetchRequest {
/// Returns an adapted request.
public func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedFetchRequest<Self> {
return AdaptedFetchRequest(self, adapter)
@@ -134,7 +134,7 @@ extension FetchRequest {
// MARK: - AdaptedFetchRequest
/// An adapted request.
public struct AdaptedFetchRequest<Base: FetchRequest> : FetchRequest {
public struct AdaptedFetchRequest<Base: FetchRequest>: FetchRequest {
public typealias RowDecoder = Base.RowDecoder
private let base: Base
@@ -175,7 +175,7 @@ public struct AdaptedFetchRequest<Base: FetchRequest> : FetchRequest {
///
/// An AnyFetchRequest forwards its operations to an underlying request,
/// hiding its specifics.
public struct AnyFetchRequest<T> : FetchRequest {
public struct AnyFetchRequest<T>: FetchRequest {
public typealias RowDecoder = T
private let _preparedRequest: (Database, _ singleResult: Bool) throws -> PreparedRequest
+102 -40
View File
@@ -1,14 +1,17 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
/// A database row.
public final class Row : Equatable, Hashable, RandomAccessCollection, ExpressibleByDictionaryLiteral, CustomStringConvertible, CustomDebugStringConvertible {
public final class Row: Equatable, Hashable, RandomAccessCollection,
ExpressibleByDictionaryLiteral, CustomStringConvertible,
CustomDebugStringConvertible
{
// It is not a violation of the Demeter law when another type uses this
// property, which is exposed for optimizations.
let impl: RowImpl
@@ -45,7 +48,7 @@ public final class Row : Equatable, Hashable, RandomAccessCollection, Expressibl
/// let bookRows = row.prefetchedRows["books"]
/// print(bookRows[0])
/// // Prints [id:42 title:"Moby-Dick"]
public internal(set) var prefetchedRows: PrefetchedRowsView = PrefetchedRowsView()
public internal(set) var prefetchedRows = PrefetchedRowsView()
// MARK: - Building rows
@@ -126,8 +129,13 @@ public final class Row : Equatable, Hashable, RandomAccessCollection, Expressibl
/// 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))
convenience init(
copiedFromSQLiteStatement sqliteStatement: SQLiteStatement,
statementRef: Unmanaged<SelectStatement>)
{
self.init(impl: StatementCopyRowImpl(
sqliteStatement: sqliteStatement,
columnNames: statementRef.takeUnretainedValue().columnNames))
}
init(impl: RowImpl) {
@@ -139,7 +147,7 @@ public final class Row : Equatable, Hashable, RandomAccessCollection, Expressibl
}
extension Row {
// MARK: - Columns
/// The names of columns in the row.
@@ -416,7 +424,12 @@ extension Row {
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
/// (see https://www.sqlite.org/datatype3.html).
@inlinable
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible, Column: ColumnExpression>(_ column: Column) -> Value? {
public subscript<Value, Column>(_ column: Column)
-> Value?
where
Value: DatabaseValueConvertible & StatementColumnConvertible,
Column: ColumnExpression
{
return self[column.name]
}
@@ -448,7 +461,12 @@ extension Row {
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
/// (see https://www.sqlite.org/datatype3.html).
@inlinable
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible, Column: ColumnExpression>(_ column: Column) -> Value {
public subscript<Value, Column>(_ column: Column)
-> Value
where
Value: DatabaseValueConvertible & StatementColumnConvertible,
Column: ColumnExpression
{
return self[column.name]
}
@@ -565,7 +583,7 @@ extension Row {
}
return Record(row: scopedRow)
}
/// Returns the eventual record associated with the given scope.
///
/// For example:
@@ -761,7 +779,7 @@ extension Row {
/// try dbQueue.read { db in
/// let rows: RowCursor = try Row.fetchCursor(db, sql: "SELECT * FROM player")
/// }
public final class RowCursor : Cursor {
public final class RowCursor: Cursor {
public let statement: SelectStatement
@usableFromInline let _sqliteStatement: SQLiteStatement
@usableFromInline let _row: Row // Reused for performance
@@ -833,7 +851,12 @@ extension Row {
/// - 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 {
public static func fetchCursor(
_ statement: SelectStatement,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> RowCursor
{
return try RowCursor(statement: statement, arguments: arguments, adapter: adapter)
}
@@ -848,7 +871,12 @@ extension Row {
/// - 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] {
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() })
}
@@ -864,7 +892,12 @@ extension Row {
/// - 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? {
public static func fetchOne(
_ statement: SelectStatement,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> Row?
{
let cursor = try fetchCursor(statement, arguments: arguments, adapter: adapter)
// Keep cursor alive until we can copy the fetched row
return try withExtendedLifetime(cursor) {
@@ -905,7 +938,13 @@ extension Row {
/// - 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 = StatementArguments(), adapter: RowAdapter? = nil) throws -> RowCursor {
public static func fetchCursor(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: RowAdapter? = nil)
throws -> RowCursor
{
return try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
@@ -924,7 +963,13 @@ extension Row {
/// - 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 = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Row] {
public static func fetchAll(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: RowAdapter? = nil)
throws -> [Row]
{
return try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
@@ -943,7 +988,13 @@ extension Row {
/// - 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 = StatementArguments(), adapter: RowAdapter? = nil) throws -> Row? {
public static func fetchOne(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: RowAdapter? = nil)
throws -> Row?
{
return try fetchOne(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
}
@@ -1079,7 +1130,7 @@ extension FetchRequest where RowDecoder == Row {
return try Row.fetchOne(db, self)
}
}
// ExpressibleByDictionaryLiteral
extension Row {
@@ -1198,7 +1249,7 @@ extension Row {
if level == 0 && self == self.unadapted && prefetchedRows.prefetches.isEmpty {
return description
}
let prefix = repeatElement(" ", count: level + 1).joined(separator: "")
let prefix = repeatElement(" ", count: level + 1).joined()
var str = ""
if level == 0 {
str = "▿ " + description
@@ -1234,7 +1285,7 @@ extension Row {
// MARK: - RowIndex
/// Indexes to (ColumnName, DatabaseValue) pairs in a database row.
public struct RowIndex : Comparable, Strideable {
public struct RowIndex: Comparable, Strideable {
let index: Int
init(_ index: Int) { self.index = index }
}
@@ -1386,7 +1437,7 @@ extension Row {
}
return names
}
/// Returns the row associated with the given scope.
///
/// For example:
@@ -1461,7 +1512,7 @@ extension Row {
public var isEmpty: Bool {
return prefetches.isEmpty
}
/// The keys for available prefetched rows
///
/// For example:
@@ -1483,7 +1534,7 @@ extension Row {
}
return result
}
/// Returns the prefetched rows associated with the given key.
///
/// For example:
@@ -1538,13 +1589,20 @@ extension OrderedDictionary where Key == String, Value == Row.Prefetch {
protocol RowImpl {
var count: Int { get }
var isFetched: Bool { get }
func scopes(prefetchedRows: Row.PrefetchedRowsView) -> Row.ScopesView
func columnName(atUncheckedIndex index: Int) -> String
func hasNull(atUncheckedIndex index:Int) -> Bool
func hasNull(atUncheckedIndex index: Int) -> Bool
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue
func fastDecode<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ type: Value.Type, atUncheckedIndex index: Int) -> Value
func fastDecodeIfPresent<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ type: Value.Type, atUncheckedIndex index: Int) -> Value?
func dataNoCopy(atUncheckedIndex index:Int) -> Data?
func fastDecode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
_ type: Value.Type,
atUncheckedIndex index: Int)
-> Value
func fastDecodeIfPresent<Value: DatabaseValueConvertible & StatementColumnConvertible>(
_ type: Value.Type,
atUncheckedIndex index: Int)
-> Value?
func dataNoCopy(atUncheckedIndex index: Int) -> Data?
/// Returns the index of the leftmost column that matches *name* (case-insensitive)
func index(ofColumn name: String) -> Int?
@@ -1558,7 +1616,7 @@ protocol RowImpl {
extension RowImpl {
func copiedRow(_ row: Row) -> Row {
// unless customized, assume unsafe and unadapted row
return Row(impl: ArrayRowImpl(columns: row.map { $0 }))
return Row(impl: ArrayRowImpl(columns: Array(row)))
}
func unscopedRow(_ row: Row) -> Row {
@@ -1576,7 +1634,7 @@ extension RowImpl {
return Row.ScopesView()
}
func hasNull(atUncheckedIndex index:Int) -> Bool {
func hasNull(atUncheckedIndex index: Int) -> Bool {
// unless customized, use slow check (see StatementRowImpl and AdaptedRowImpl for customization)
return databaseValue(atUncheckedIndex: index).isNull
}
@@ -1601,7 +1659,7 @@ extension RowImpl {
conversionContext: ValueConversionContext(Row(impl: self)).atColumn(index))
}
func dataNoCopy(atUncheckedIndex index:Int) -> Data? {
func dataNoCopy(atUncheckedIndex index: Int) -> Data? {
// unless customized, copy data (see StatementRowImpl and AdaptedRowImpl for customization)
return Data.decodeIfPresent(
from: databaseValue(atUncheckedIndex: index),
@@ -1611,7 +1669,7 @@ extension RowImpl {
// TODO: merge with StatementCopyRowImpl eventually?
/// See Row.init(dictionary:)
private struct ArrayRowImpl : RowImpl {
private struct ArrayRowImpl: RowImpl {
let columns: [(String, DatabaseValue)]
init(columns: [(String, DatabaseValue)]) {
@@ -1647,13 +1705,16 @@ private struct ArrayRowImpl : RowImpl {
// TODO: merge with ArrayRowImpl eventually?
/// See Row.init(copiedFromStatementRef:sqliteStatement:)
private struct StatementCopyRowImpl : RowImpl {
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.dbValues = ContiguousArray(
(0..<sqlite3_column_count(sqliteStatement))
.map { DatabaseValue(sqliteStatement: sqliteStatement, index: $0) }
as [DatabaseValue])
self.columnNames = columnNames
}
@@ -1685,7 +1746,7 @@ private struct StatementCopyRowImpl : RowImpl {
/// See Row.init(statement:)
private struct StatementRowImpl : RowImpl {
private struct StatementRowImpl: RowImpl {
let statementRef: Unmanaged<SelectStatement>
let sqliteStatement: SQLiteStatement
let lowercaseColumnIndexes: [String: Int]
@@ -1694,7 +1755,8 @@ private struct StatementRowImpl : RowImpl {
self.statementRef = statementRef
self.sqliteStatement = sqliteStatement
// Optimize row[columnName]
let lowercaseColumnNames = (0..<sqlite3_column_count(sqliteStatement)).map { String(cString: sqlite3_column_name(sqliteStatement, Int32($0))).lowercased() }
let lowercaseColumnNames = (0..<sqlite3_column_count(sqliteStatement))
.map { String(cString: sqlite3_column_name(sqliteStatement, Int32($0))).lowercased() }
self.lowercaseColumnIndexes = Dictionary(
lowercaseColumnNames
.enumerated()
@@ -1710,12 +1772,12 @@ private struct StatementRowImpl : RowImpl {
return true
}
func hasNull(atUncheckedIndex index:Int) -> Bool {
func hasNull(atUncheckedIndex index: Int) -> Bool {
// Avoid extracting values, because this modifies the SQLite statement.
return sqlite3_column_type(sqliteStatement, Int32(index)) == SQLITE_NULL
}
func dataNoCopy(atUncheckedIndex index:Int) -> Data? {
func dataNoCopy(atUncheckedIndex index: Int) -> Data? {
guard sqlite3_column_type(sqliteStatement, Int32(index)) != SQLITE_NULL else {
return nil
}
@@ -1761,7 +1823,7 @@ private struct StatementRowImpl : RowImpl {
}
// This one is not optimized at all, since it is only used in fatal conversion errors, so far
private struct SQLiteStatementRowImpl : RowImpl {
private struct SQLiteStatementRowImpl: RowImpl {
let sqliteStatement: SQLiteStatement
var count: Int { return Int(sqlite3_column_count(sqliteStatement)) }
var isFetched: Bool { return true }
@@ -1784,7 +1846,7 @@ private struct SQLiteStatementRowImpl : RowImpl {
}
/// See Row.init()
private struct EmptyRowImpl : RowImpl {
private struct EmptyRowImpl: RowImpl {
var count: Int {
return 0
}
+20 -15
View File
@@ -100,7 +100,7 @@ public struct LayoutedColumnMapping {
/// LayoutedColumnMapping adopts LayoutedRowAdapter
///
/// :nodoc:
extension LayoutedColumnMapping : LayoutedRowAdapter {
extension LayoutedColumnMapping: LayoutedRowAdapter {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// Returns self.
@@ -117,7 +117,7 @@ extension LayoutedColumnMapping : LayoutedRowAdapter {
}
/// :nodoc:
extension LayoutedColumnMapping : RowLayout {
extension LayoutedColumnMapping: RowLayout {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// Returns the index of the leftmost column named `name`, in a
@@ -171,7 +171,7 @@ public protocol RowLayout {
func layoutIndex(ofColumn name: String) -> Int?
}
extension SelectStatement : RowLayout {
extension SelectStatement: RowLayout {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public var layoutColumns: [(Int, String)] {
@@ -270,7 +270,7 @@ public struct EmptyRowAdapter: RowAdapter {
///
/// // [foo:"bar"]
/// try Row.fetchOne(db, sql: sql, adapter: adapter)
public struct ColumnMapping : RowAdapter {
public struct ColumnMapping: RowAdapter {
/// A dictionary from mapped column names to column names in a base row.
let mapping: [String: String]
@@ -287,7 +287,12 @@ public struct ColumnMapping : RowAdapter {
.map { (mappedColumn, baseColumn) -> (Int, String) in
guard let index = layout.layoutIndex(ofColumn: baseColumn) else {
let columnNames = layout.layoutColumns.map { $0.1 }
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "Mapping references missing column \(baseColumn). Valid column names are: \(columnNames.joined(separator: ", ")).")
throw DatabaseError(
resultCode: .SQLITE_MISUSE,
message: """
Mapping references missing column \(baseColumn). \
Valid column names are: \(columnNames.joined(separator: ", ")).
""")
}
let baseIndex = layout.layoutColumns[index].0
return (baseIndex, mappedColumn)
@@ -304,7 +309,7 @@ public struct ColumnMapping : RowAdapter {
///
/// // [baz:3]
/// try Row.fetchOne(db, sql: sql, adapter: adapter)
public struct SuffixRowAdapter : RowAdapter {
public struct SuffixRowAdapter: RowAdapter {
/// The suffix index
let index: Int
@@ -331,7 +336,7 @@ public struct SuffixRowAdapter : RowAdapter {
///
/// // [bar:2 baz:3]
/// try Row.fetchOne(db, sql: sql, adapter: adapter)
public struct RangeRowAdapter : RowAdapter {
public struct RangeRowAdapter: RowAdapter {
/// The range
let range: CountableRange<Int>
@@ -376,7 +381,7 @@ public struct RangeRowAdapter : RowAdapter {
/// if let barRow = row.scopes["bar"] {
/// barRow["value"] // "bar"
/// }
public struct ScopeAdapter : RowAdapter {
public struct ScopeAdapter: RowAdapter {
/// The base adapter
let base: RowAdapter
@@ -439,15 +444,15 @@ public struct ScopeAdapter : RowAdapter {
}
/// The LayoutedRowAdapter for ScopeAdapter
struct LayoutedScopeAdapter : LayoutedRowAdapter {
struct LayoutedScopeAdapter: LayoutedRowAdapter {
let mapping: LayoutedColumnMapping
let scopes: [String: LayoutedRowAdapter]
}
struct ChainedAdapter : RowAdapter {
struct ChainedAdapter: RowAdapter {
let first: RowAdapter
let second: RowAdapter
func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
return try second.layoutedAdapter(from: first.layoutedAdapter(from: layout).mapping)
}
@@ -458,7 +463,7 @@ extension Row {
convenience init(base: Row, adapter: LayoutedRowAdapter) {
self.init(impl: AdaptedRowImpl(base: base, adapter: adapter))
}
/// Returns self if adapter is nil
func adapted(with adapter: RowAdapter?, layout: RowLayout) throws -> Row {
guard let adapter = adapter else {
@@ -468,7 +473,7 @@ extension Row {
}
}
struct AdaptedRowImpl : RowImpl {
struct AdaptedRowImpl: RowImpl {
let base: Row
let adapter: LayoutedRowAdapter
let mapping: LayoutedColumnMapping
@@ -517,7 +522,7 @@ struct AdaptedRowImpl : RowImpl {
return Value.fastDecodeIfPresent(from: base, atUncheckedIndex: mappedIndex)
}
func dataNoCopy(atUncheckedIndex index:Int) -> Data? {
func dataNoCopy(atUncheckedIndex index: Int) -> Data? {
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
return base.impl.dataNoCopy(atUncheckedIndex: mappedIndex)
}
@@ -533,7 +538,7 @@ struct AdaptedRowImpl : RowImpl {
func copiedRow(_ row: Row) -> Row {
return Row(base: base.copy(), adapter: adapter)
}
func unscopedRow(_ row: Row) -> Row {
assert(adapter.mapping.scopes.isEmpty)
return Row(base: base, adapter: adapter.mapping)
+4 -4
View File
@@ -7,23 +7,23 @@ public struct SQLInterpolation: StringInterpolationProtocol {
get { return context.arguments! }
set { context.arguments = newValue }
}
public init(literalCapacity: Int, interpolationCount: Int) {
sql = ""
sql.reserveCapacity(literalCapacity + interpolationCount)
}
/// "SELECT * FROM player"
public mutating func appendLiteral(_ sql: String) {
self.sql += sql
}
/// "SELECT * FROM \(sql: "player")"
public mutating func appendInterpolation(sql: String, arguments: StatementArguments = StatementArguments()) {
self.sql += sql
self.arguments += arguments
}
/// "SELECT * FROM player WHERE \(literal: condition)"
public mutating func appendInterpolation(literal sqlLiteral: SQLLiteral) {
sql += sqlLiteral.sql
+5 -4
View File
@@ -1,4 +1,5 @@
/// SQLLiteral is a type which support [SQL Interpolation](https://github.com/groue/GRDB.swift/blob/master/Documentation/SQLInterpolation.md).
/// SQLLiteral is a type which support [SQL
/// Interpolation](https://github.com/groue/GRDB.swift/blob/master/Documentation/SQLInterpolation.md).
///
/// For example:
///
@@ -9,8 +10,8 @@
/// try db.execute(literal: query)
/// }
public struct SQLLiteral {
private(set) public var sql: String
private(set) public var arguments: StatementArguments
public private(set) var sql: String
public private(set) var arguments: StatementArguments
/// Creates an SQLLiteral from a plain SQL string, and eventual arguments.
///
@@ -63,7 +64,7 @@ extension SQLLiteral {
public mutating func append(literal sqlLiteral: SQLLiteral) {
self += sqlLiteral
}
/// Appends a plain SQL string to the receiver, and eventual arguments.
///
/// let name = "O'Brien"
+21 -7
View File
@@ -1,5 +1,5 @@
/// A FetchRequest built from raw SQL.
public struct SQLRequest<T> : FetchRequest {
public struct SQLRequest<T>: FetchRequest {
/// There are two statement caches: one "public" for statements generated by
/// the user, and one "internal" for the statements generated by GRDB. Those
/// are separated so that GRDB has no opportunity to inadvertently modify
@@ -30,10 +30,10 @@ public struct SQLRequest<T> : FetchRequest {
/// The request adapter
public var adapter: RowAdapter?
private var sqlLiteral: SQLLiteral
private let cache: Cache?
/// Creates a request from an SQL string, optional arguments, and
/// optional row adapter.
///
@@ -51,8 +51,16 @@ public struct SQLRequest<T> : FetchRequest {
/// - cached: Defaults to false. If true, the request reuses a cached
/// prepared statement.
/// - returns: A SQLRequest
public init(sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil, cached: Bool = false) {
self.init(literal: SQLLiteral(sql: sql, arguments: arguments), adapter: adapter, fromCache: cached ? .public : nil)
public init(
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: RowAdapter? = nil,
cached: Bool = false)
{
self.init(
literal: SQLLiteral(sql: sql, arguments: arguments),
adapter: adapter,
fromCache: cached ? .public : nil)
}
/// Creates a request from an SQLLiteral, and optional row adapter.
@@ -80,7 +88,7 @@ public struct SQLRequest<T> : FetchRequest {
public init(literal sqlLiteral: SQLLiteral, adapter: RowAdapter? = nil, cached: Bool = false) {
self.init(literal: sqlLiteral, adapter: adapter, fromCache: cached ? .public : nil)
}
/// Creates an SQL request from any other fetch request.
///
/// - parameters:
@@ -89,7 +97,13 @@ public struct SQLRequest<T> : FetchRequest {
/// - cached: Defaults to false. If true, the request reuses a cached
/// prepared statement.
/// - returns: An SQLRequest
public init<Request: FetchRequest>(_ db: Database, request: Request, cached: Bool = false) throws where Request.RowDecoder == RowDecoder {
public init<Request>(
_ db: Database,
request: Request,
cached: Bool = false)
throws
where Request: FetchRequest, Request.RowDecoder == RowDecoder
{
let request = try request.makePreparedRequest(db, forSingleResult: false)
self.init(
literal: SQLLiteral(sql: request.statement.sql, arguments: request.statement.arguments),
+6 -1
View File
@@ -43,7 +43,12 @@ final class SchedulingWatchdog {
return try body()
}
static func preconditionValidQueue(_ db: Database, _ message: @autoclosure() -> String = "Database was not used on the correct thread.", file: StaticString = #file, line: UInt = #line) {
static func preconditionValidQueue(
_ db: Database,
_ message: @autoclosure() -> String = "Database was not used on the correct thread.",
file: StaticString = #file,
line: UInt = #line)
{
GRDBPrecondition(current?.allows(db) ?? false, message(), file: file, line: line)
}
+24 -4
View File
@@ -16,7 +16,14 @@ final class SerializedDatabase {
/// The dispatch queue
private let queue: DispatchQueue
init(path: String, configuration: Configuration = Configuration(), schemaCache: DatabaseSchemaCache, defaultLabel: String, purpose: String? = nil) throws {
init(
path: String,
configuration: Configuration = Configuration(),
schemaCache: DatabaseSchemaCache,
defaultLabel: String,
purpose: String? = nil)
throws
{
// According to https://www.sqlite.org/threadsafe.html
//
// > SQLite support three different threading modes:
@@ -193,12 +200,25 @@ final class SerializedDatabase {
}
/// Fatal error if current dispatch queue is not valid.
func preconditionValidQueue(_ message: @autoclosure() -> String = "Database was not used on the correct thread.", file: StaticString = #file, line: UInt = #line) {
func preconditionValidQueue(
_ message: @autoclosure() -> String = "Database was not used on the correct thread.",
file: StaticString = #file,
line: UInt = #line)
{
SchedulingWatchdog.preconditionValidQueue(db, message(), file: file, line: line)
}
/// Fatal error if a transaction has been left opened.
private func preconditionNoUnsafeTransactionLeft(_ db: Database, _ message: @autoclosure() -> String = "A transaction has been left opened at the end of a database access", file: StaticString = #file, line: UInt = #line) {
GRDBPrecondition(configuration.allowsUnsafeTransactions || !db.isInsideTransaction, message(), file: file, line: line)
private func preconditionNoUnsafeTransactionLeft(
_ db: Database,
_ message: @autoclosure() -> String = "A transaction has been left opened at the end of a database access",
file: StaticString = #file,
line: UInt = #line)
{
GRDBPrecondition(
configuration.allowsUnsafeTransactions || !db.isInsideTransaction,
message(),
file: file,
line: line)
}
}
+62 -28
View File
@@ -1,10 +1,10 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
/// A raw SQLite statement, suitable for the SQLite C API.
@@ -56,18 +56,25 @@ public class Statement {
var sqliteStatement: SQLiteStatement? = nil
// sqlite3_prepare_v3 was introduced in SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20
#if GRDBCUSTOMSQLITE || GRDBCIPHER
let code = sqlite3_prepare_v3(database.sqliteConnection, statementStart, -1, UInt32(bitPattern: prepFlags), &sqliteStatement, statementEnd)
let code = sqlite3_prepare_v3(
database.sqliteConnection, statementStart, -1, UInt32(bitPattern: prepFlags),
&sqliteStatement, statementEnd)
#else
let code: Int32
if #available(iOS 12.0, OSX 10.14, watchOS 5.0, *) {
code = sqlite3_prepare_v3(database.sqliteConnection, statementStart, -1, UInt32(bitPattern: prepFlags), &sqliteStatement, statementEnd)
code = sqlite3_prepare_v3(
database.sqliteConnection, statementStart, -1, UInt32(bitPattern: prepFlags),
&sqliteStatement, statementEnd)
} else {
code = sqlite3_prepare_v2(database.sqliteConnection, statementStart, -1, &sqliteStatement, statementEnd)
}
#endif
guard code == SQLITE_OK else {
throw DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: String(cString: statementStart))
throw DatabaseError(
resultCode: code,
message: database.lastErrorMessage,
sql: String(cString: statementStart))
}
guard let statement = sqliteStatement else {
@@ -102,7 +109,7 @@ public class Statement {
// Returns ["id", nil", "name"] for "INSERT INTO table VALUES (:id, ?, :name)"
fileprivate lazy var sqliteArgumentNames: [String?] = {
return (0..<self.sqliteArgumentCount).map {
(0..<self.sqliteArgumentCount).map {
guard let cString = sqlite3_bind_parameter_name(self.sqliteStatement, Int32($0 + 1)) else {
return nil
}
@@ -203,7 +210,7 @@ public class Statement {
fatalError(DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql).description)
}
}
fileprivate func prepare(withArguments arguments: StatementArguments?) {
// Force arguments validity: it is a programmer error to provide
// arguments that do not match the statement.
@@ -242,17 +249,18 @@ extension StatementProtocol where Self: Statement {
throw DatabaseError(
resultCode: .SQLITE_ERROR,
message: "empty statement",
sql: sql,
arguments: nil)
sql: sql)
}
let remainingSQL = String(cString: statementEnd!).trimmingCharacters(in: .sqlStatementSeparators)
guard remainingSQL.isEmpty else {
throw DatabaseError(
resultCode: .SQLITE_MISUSE,
message: "Multiple statements found. To execute multiple statements, use Database.execute(sql:) instead.",
sql: sql,
arguments: nil)
message: """
Multiple statements found. To execute multiple statements, \
use Database.execute(sql:) instead.
""",
sql: sql)
}
return statement
@@ -271,7 +279,7 @@ extension StatementProtocol where Self: Statement {
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
/// }
public final class SelectStatement : Statement {
public final class SelectStatement: Statement {
/// The database region that the statement looks into.
public private(set) var databaseRegion = DatabaseRegion()
@@ -301,8 +309,12 @@ public final class SelectStatement : Statement {
prepFlags: prepFlags,
authorizer: authorizer)
GRDBPrecondition(authorizer.invalidatesDatabaseSchemaCache == false, "Invalid statement type for query \(String(reflecting: sql)): use UpdateStatement instead.")
GRDBPrecondition(authorizer.transactionEffect == nil, "Invalid statement type for query \(String(reflecting: sql)): use UpdateStatement instead.")
GRDBPrecondition(
authorizer.invalidatesDatabaseSchemaCache == false,
"Invalid statement type for query \(String(reflecting: sql)): use UpdateStatement instead.")
GRDBPrecondition(
authorizer.transactionEffect == nil,
"Invalid statement type for query \(String(reflecting: sql)): use UpdateStatement instead.")
self.databaseRegion = authorizer.databaseRegion
}
@@ -320,7 +332,7 @@ public final class SelectStatement : Statement {
/// Cache for index(ofColumn:). Keys are lowercase.
private lazy var columnIndexes: [String: Int] = {
return Dictionary(
Dictionary(
self.columnNames.enumerated().map { ($0.element.lowercased(), $0.offset) },
uniquingKeysWith: { (left, _) in left }) // keep leftmost indexes
}()
@@ -353,7 +365,6 @@ public final class SelectStatement : Statement {
message: database.lastErrorMessage,
sql: sql,
arguments: arguments)
}
}
@@ -418,7 +429,7 @@ final class StatementCursor: Cursor {
/// try statement.execute(arguments: ["Barbara"])
/// return .commit
/// }
public final class UpdateStatement : Statement {
public final class UpdateStatement: Statement {
enum TransactionEffect {
case beginTransaction
case commitTransaction
@@ -502,7 +513,11 @@ public final class UpdateStatement : Statement {
case let code:
try database.updateStatementDidFail(self)
throw DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql, arguments: self.arguments) // Error uses self.arguments, not the optional arguments parameter.
throw DatabaseError(
resultCode: code,
message: database.lastErrorMessage,
sql: sql,
arguments: self.arguments) // Error uses self.arguments, not the optional arguments parameter.
}
}
}
@@ -589,7 +604,9 @@ public final class UpdateStatement : Statement {
/// .filter(sql: "team = :team", arguments: ["team": "Blue"])
/// .filter(sql: "score > ?", arguments: [1000])
/// .fetchAll(db)
public struct StatementArguments: CustomStringConvertible, Equatable, ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral {
public struct StatementArguments: CustomStringConvertible, Equatable,
ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral
{
private(set) var values: [DatabaseValue] = []
private(set) var namedValues: [String: DatabaseValue] = [:]
@@ -667,7 +684,9 @@ public struct StatementArguments: CustomStringConvertible, Equatable, Expressibl
///
/// - parameter sequence: A sequence of (key, value) pairs
/// - returns: A StatementArguments.
public init<Sequence: Swift.Sequence>(_ sequence: Sequence) where Sequence.Element == (String, DatabaseValueConvertible?) {
public init<Sequence>(_ sequence: Sequence)
where Sequence: Swift.Sequence, Sequence.Element == (String, DatabaseValueConvertible?)
{
namedValues = Dictionary(uniqueKeysWithValues: sequence.map { ($0.0, $0.1?.databaseValue ?? .null) })
}
@@ -843,33 +862,48 @@ public struct StatementArguments: CustomStringConvertible, Equatable, Expressibl
/// append(contentsOf:) method.
public static func += (lhs: inout StatementArguments, rhs: StatementArguments) {
let replacedValues = lhs.append(contentsOf: rhs)
GRDBPrecondition(replacedValues.isEmpty, "already defined statement argument: \(replacedValues.keys.joined(separator: ", "))")
GRDBPrecondition(
replacedValues.isEmpty,
"already defined statement argument: \(replacedValues.keys.joined(separator: ", "))")
}
// MARK: Not Public
mutating func extractBindings(forStatement statement: Statement, allowingRemainingValues: Bool) throws -> [DatabaseValue] {
mutating func extractBindings(
forStatement statement: Statement,
allowingRemainingValues: Bool)
throws -> [DatabaseValue]
{
let initialValuesCount = values.count
let bindings = try statement.sqliteArgumentNames.map { argumentName -> DatabaseValue in
if let argumentName = argumentName {
if let dbValue = namedValues[argumentName] {
return dbValue
} else if values.isEmpty {
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "missing statement argument: \(argumentName)", sql: statement.sql, arguments: nil)
throw DatabaseError(
resultCode: .SQLITE_MISUSE,
message: "missing statement argument: \(argumentName)",
sql: statement.sql)
} else {
return values.removeFirst()
}
} else {
if values.isEmpty {
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "wrong number of statement arguments: \(initialValuesCount)", sql: statement.sql, arguments: nil)
throw DatabaseError(
resultCode: .SQLITE_MISUSE,
message: "wrong number of statement arguments: \(initialValuesCount)",
sql: statement.sql)
} else {
return values.removeFirst()
}
}
}
if !allowingRemainingValues && !values.isEmpty {
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "wrong number of statement arguments: \(initialValuesCount)", sql: statement.sql, arguments: nil)
throw DatabaseError(
resultCode: .SQLITE_MISUSE,
message: "wrong number of statement arguments: \(initialValuesCount)",
sql: statement.sql)
}
return bindings
}
@@ -907,7 +941,7 @@ extension StatementArguments {
public var description: String {
let valuesDescriptions = values.map { $0.description }
let namedValuesDescriptions = namedValues.map { (key, value) -> String in
return "\(String(reflecting: key)): \(value)"
"\(String(reflecting: key)): \(value)"
}
return "[" + (namedValuesDescriptions + valuesDescriptions).joined(separator: ", ") + "]"
}
+23 -16
View File
@@ -1,16 +1,16 @@
#if os(Linux)
import Glibc
import Glibc
#endif
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
/// A protocol around sqlite3_set_authorizer
protocol StatementAuthorizer : class {
protocol StatementAuthorizer: AnyObject {
func authorize(
_ actionCode: Int32,
_ cString1: UnsafePointer<Int8>?,
@@ -21,7 +21,7 @@ protocol StatementAuthorizer : class {
}
/// A class that gathers information about one statement during its compilation.
final class StatementCompilationAuthorizer : StatementAuthorizer {
final class StatementCompilationAuthorizer: StatementAuthorizer {
/// What this statements reads
var databaseRegion = DatabaseRegion()
@@ -47,7 +47,11 @@ final class StatementCompilationAuthorizer : StatementAuthorizer {
_ cString4: UnsafePointer<Int8>?)
-> Int32
{
// print("StatementCompilationAuthorizer: \(actionCode) \([cString1, cString2, cString3, cString4].flatMap { $0.map({ String(cString: $0) }) })")
// print("""
// StatementCompilationAuthorizer: \
// \(actionCode) \
// \([cString1, cString2, cString3, cString4].compactMap { $0.map(String.init) })
// """)
switch actionCode {
case SQLITE_DROP_TABLE, SQLITE_DROP_VTABLE, SQLITE_DROP_TEMP_TABLE,
@@ -67,8 +71,8 @@ final class StatementCompilationAuthorizer : StatementAuthorizer {
return SQLITE_OK
case SQLITE_READ:
guard let tableName = cString1.map({ String(cString: $0) }) else { return SQLITE_OK }
guard let columnName = cString2.map({ String(cString: $0) }) else { return SQLITE_OK }
guard let tableName = cString1.map(String.init) else { return SQLITE_OK }
guard let columnName = cString2.map(String.init) else { return SQLITE_OK }
if columnName.isEmpty {
// SELECT COUNT(*) FROM table
databaseRegion.formUnion(DatabaseRegion(table: tableName))
@@ -79,7 +83,7 @@ final class StatementCompilationAuthorizer : StatementAuthorizer {
return SQLITE_OK
case SQLITE_INSERT:
guard let tableName = cString1.map({ String(cString: $0) }) else { return SQLITE_OK }
guard let tableName = cString1.map(String.init) else { return SQLITE_OK }
databaseEventKinds.append(.insert(tableName: tableName))
return SQLITE_OK
@@ -100,8 +104,8 @@ final class StatementCompilationAuthorizer : StatementAuthorizer {
return SQLITE_IGNORE
case SQLITE_UPDATE:
guard let tableName = cString1.map({ String(cString: $0) }) else { return SQLITE_OK }
guard let columnName = cString2.map({ String(cString: $0) }) else { return SQLITE_OK }
guard let tableName = cString1.map(String.init) else { return SQLITE_OK }
guard let columnName = cString2.map(String.init) else { return SQLITE_OK }
insertUpdateEventKind(tableName: tableName, columnName: columnName)
return SQLITE_OK
@@ -118,7 +122,7 @@ final class StatementCompilationAuthorizer : StatementAuthorizer {
case SQLITE_SAVEPOINT:
guard let cString1 = cString1 else { return SQLITE_OK }
guard let name = cString2.map({ String(cString: $0) }) else { return SQLITE_OK }
guard let name = cString2.map(String.init) else { return SQLITE_OK }
if strcmp(cString1, "BEGIN") == 0 {
transactionEffect = .beginSavepoint(name)
} else if strcmp(cString1, "RELEASE") == 0 {
@@ -168,7 +172,7 @@ final class StatementCompilationAuthorizer : StatementAuthorizer {
//
/// Warning: to perform well, this authorizer must be used during statement
/// execution, not during statement compilation.
final class TruncateOptimizationBlocker : StatementAuthorizer {
final class TruncateOptimizationBlocker: StatementAuthorizer {
func authorize(
_ actionCode: Int32,
_ cString1: UnsafePointer<Int8>?,
@@ -177,8 +181,11 @@ final class TruncateOptimizationBlocker : StatementAuthorizer {
_ cString4: UnsafePointer<Int8>?)
-> Int32
{
// print("TruncateOptimizationBlocker: \(actionCode) \([cString1, cString2, cString3, cString4].flatMap { $0.map({ String(cString: $0) }) })")
// print("""
// TruncateOptimizationBlocker: \
// \(actionCode) \
// \([cString1, cString2, cString3, cString4].compactMap { $0.map(String.init) })
// """)
return (actionCode == SQLITE_DELETE) ? SQLITE_IGNORE : SQLITE_OK
}
}
+90 -21
View File
@@ -1,9 +1,9 @@
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
/// The StatementColumnConvertible protocol grants access to the low-level C
@@ -109,17 +109,20 @@ public final class FastDatabaseValueCursor<Value: DatabaseValueConvertible & Sta
/// For example:
///
/// try dbQueue.read { db in
/// let emails: NullableColumnCursor<String> = try Optional<String>.fetchCursor(db, sql: "SELECT email FROM player")
/// let emails: FastNullableDatabaseValueCursor<String> =
/// try Optional<String>.fetchCursor(db, sql: "SELECT email FROM player")
/// while let email = emails.next() { // String?
/// print(email ?? "<NULL>")
/// }
/// }
public final class FastNullableDatabaseValueCursor<Value: DatabaseValueConvertible & StatementColumnConvertible> : Cursor {
public final class FastNullableDatabaseValueCursor<Value>: Cursor
where Value: DatabaseValueConvertible & StatementColumnConvertible
{
@usableFromInline let _statement: SelectStatement
@usableFromInline let _columnIndex: Int32
@usableFromInline let _sqliteStatement: SQLiteStatement
@usableFromInline var _done = false
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
_statement = statement
_sqliteStatement = statement.sqliteStatement
@@ -187,7 +190,12 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> FastDatabaseValueCursor<Self> {
public static func fetchCursor(
_ statement: SelectStatement,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> FastDatabaseValueCursor<Self>
{
return try FastDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter)
}
@@ -202,7 +210,12 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - adapter: Optional RowAdapter
/// - returns: An array of values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] {
public static func fetchAll(
_ statement: SelectStatement,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> [Self]
{
return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
}
@@ -217,15 +230,23 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - adapter: Optional RowAdapter
/// - returns: An optional value.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? {
public static func fetchOne(
_ statement: SelectStatement,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> Self?
{
// fetchOne returns nil if there is no row, or if there is a row with a null value
let cursor = try FastNullableDatabaseValueCursor<Self>(statement: statement, arguments: arguments, adapter: adapter)
let cursor = try FastNullableDatabaseValueCursor<Self>(
statement: statement,
arguments: arguments,
adapter: adapter)
return try cursor.next() ?? nil
}
}
extension DatabaseValueConvertible where Self: StatementColumnConvertible {
// MARK: Fetching From SQL
/// Returns a cursor over values fetched from an SQL query.
@@ -247,7 +268,13 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> FastDatabaseValueCursor<Self> {
public static func fetchCursor(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: RowAdapter? = nil)
throws -> FastDatabaseValueCursor<Self>
{
return try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
@@ -262,7 +289,13 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - adapter: Optional RowAdapter
/// - returns: An array of values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Self] {
public static func fetchAll(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: RowAdapter? = nil)
throws -> [Self]
{
return try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
@@ -277,7 +310,13 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - adapter: Optional RowAdapter
/// - returns: An optional value.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> Self? {
public static func fetchOne(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: RowAdapter? = nil)
throws -> Self?
{
return try fetchOne(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
}
@@ -304,7 +343,9 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - request: A FetchRequest.
/// - returns: A cursor over fetched values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor<R: FetchRequest>(_ db: Database, _ request: R) throws -> FastDatabaseValueCursor<Self> {
public static func fetchCursor<R: FetchRequest>(_ db: Database, _ request: R)
throws -> FastDatabaseValueCursor<Self>
{
let request = try request.makePreparedRequest(db, forSingleResult: false)
return try fetchCursor(request.statement, adapter: request.adapter)
}
@@ -426,7 +467,12 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> FastNullableDatabaseValueCursor<Wrapped> {
public static func fetchCursor(
_ statement: SelectStatement,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> FastNullableDatabaseValueCursor<Wrapped>
{
return try FastNullableDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter)
}
@@ -441,7 +487,12 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
/// - adapter: Optional RowAdapter
/// - returns: An array of optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] {
public static func fetchAll(
_ statement: SelectStatement,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> [Wrapped?]
{
return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
}
}
@@ -469,7 +520,13 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> FastNullableDatabaseValueCursor<Wrapped> {
public static func fetchCursor(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: RowAdapter? = nil)
throws -> FastNullableDatabaseValueCursor<Wrapped>
{
return try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
@@ -484,7 +541,13 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
/// - adapter: Optional RowAdapter
/// - returns: An array of optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Wrapped?] {
public static func fetchAll(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: RowAdapter? = nil)
throws -> [Wrapped?]
{
return try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
}
@@ -511,7 +574,9 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
/// - request: A FetchRequest.
/// - returns: A cursor over fetched optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor<R: FetchRequest>(_ db: Database, _ request: R) throws -> FastNullableDatabaseValueCursor<Wrapped> {
public static func fetchCursor<R: FetchRequest>(_ db: Database, _ request: R)
throws -> FastNullableDatabaseValueCursor<Wrapped>
{
let request = try request.makePreparedRequest(db, forSingleResult: false)
return try fetchCursor(request.statement, adapter: request.adapter)
}
@@ -532,7 +597,11 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
}
}
extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible & StatementColumnConvertible {
extension FetchRequest
where
RowDecoder: _OptionalProtocol,
RowDecoder._Wrapped: DatabaseValueConvertible & StatementColumnConvertible
{
// MARK: Fetching Optional values
+2 -2
View File
@@ -2,8 +2,8 @@
import CoreGraphics
/// CGFloat adopts DatabaseValueConvertible
extension CGFloat : DatabaseValueConvertible {
extension CGFloat: DatabaseValueConvertible {
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return Double(self).databaseValue
+4 -4
View File
@@ -1,14 +1,14 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
/// Data is convertible to and from DatabaseValue.
extension Data : DatabaseValueConvertible, StatementColumnConvertible {
extension Data: DatabaseValueConvertible, StatementColumnConvertible {
@inlinable
public init(sqliteStatement: SQLiteStatement, index: Int32) {
if let bytes = sqlite3_column_blob(sqliteStatement, index) {
@@ -1,17 +1,17 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
/// DatabaseDateComponents reads and stores DateComponents in the database.
public struct DatabaseDateComponents : DatabaseValueConvertible, StatementColumnConvertible {
public struct DatabaseDateComponents: DatabaseValueConvertible, StatementColumnConvertible {
/// The available formats for reading and storing date components.
public enum Format : String {
public enum Format: String {
/// The format "yyyy-MM-dd".
case YMD = "yyyy-MM-dd"
@@ -81,8 +81,10 @@ public struct DatabaseDateComponents : DatabaseValueConvertible, StatementColumn
fatalConversionError(to: DatabaseDateComponents.self, sqliteStatement: sqliteStatement, index: index)
}
let length = Int(sqlite3_column_bytes(sqliteStatement, index)) // avoid an strlen
let optionalComponents = cString.withMemoryRebound(to: Int8.self, capacity: length + 1 /* trailing \0 */) { cString in
SQLiteDateParser().components(cString: cString, length: length)
let optionalComponents = cString.withMemoryRebound(
to: Int8.self,
capacity: length + 1 /* trailing \0 */) { cString in
SQLiteDateParser().components(cString: cString, length: length)
}
guard let components = optionalComponents else {
fatalConversionError(to: DatabaseDateComponents.self, sqliteStatement: sqliteStatement, index: index)
@@ -122,7 +124,9 @@ public struct DatabaseDateComponents : DatabaseValueConvertible, StatementColumn
let minute = dateComponents.minute ?? 0
let second = dateComponents.second ?? 0
let nanosecond = dateComponents.nanosecond ?? 0
timeString = String(format: "%02d:%02d:%02d.%03d", hour, minute, second, Int(round(Double(nanosecond) / 1_000_000.0)))
timeString = String(
format: "%02d:%02d:%02d.%03d",
hour, minute, second, Int(round(Double(nanosecond) / 1_000_000.0)))
default:
timeString = nil
}
@@ -26,14 +26,22 @@ extension DatabaseValueConvertible where Self: ReferenceConvertible, Self.Refere
}
}
extension DatabaseValueConvertible where Self: Decodable & ReferenceConvertible, Self.ReferenceType: DatabaseValueConvertible {
extension DatabaseValueConvertible
where
Self: Decodable & ReferenceConvertible,
Self.ReferenceType: DatabaseValueConvertible
{
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
// Preserve custom database decoding
return ReferenceType.fromDatabaseValue(databaseValue).flatMap { cast($0) }
}
}
extension DatabaseValueConvertible where Self: Encodable & ReferenceConvertible, Self.ReferenceType: DatabaseValueConvertible {
extension DatabaseValueConvertible
where
Self: Encodable & ReferenceConvertible,
Self.ReferenceType: DatabaseValueConvertible
{
public var databaseValue: DatabaseValue {
// Preserve custom database encoding
return (self as! ReferenceType).databaseValue
+7 -7
View File
@@ -1,16 +1,16 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
#if !os(Linux)
/// NSDate is stored in the database using the format
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
extension NSDate : DatabaseValueConvertible {
extension NSDate: DatabaseValueConvertible {
/// Returns a database value that contains the date encoded as
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
public var databaseValue: DatabaseValue {
@@ -38,7 +38,7 @@ extension NSDate : DatabaseValueConvertible {
/// Date is stored in the database using the format
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
extension Date : DatabaseValueConvertible {
extension Date: DatabaseValueConvertible {
/// Returns a database value that contains the date encoded as
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
public var databaseValue: DatabaseValue {
@@ -149,7 +149,7 @@ private let storageDateFormatter: DateFormatter = {
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
return formatter
}()
}()
// The NSCalendar for stored dates.
private let UTCCalendar: Calendar = {
@@ -157,4 +157,4 @@ private let UTCCalendar: Calendar = {
calendar.locale = Locale(identifier: "en_US_POSIX")
calendar.timeZone = TimeZone(secondsFromGMT: 0)!
return calendar
}()
}()
+1 -1
View File
@@ -2,7 +2,7 @@
import Foundation
/// NSData is convertible to and from DatabaseValue.
extension NSData : DatabaseValueConvertible {
extension NSData: DatabaseValueConvertible {
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
+1 -1
View File
@@ -1,7 +1,7 @@
import Foundation
/// NSNull adopts DatabaseValueConvertible
extension NSNull : DatabaseValueConvertible {
extension NSNull: DatabaseValueConvertible {
/// Returns DatabaseValue.null.
public var databaseValue: DatabaseValue {
+14 -4
View File
@@ -1,10 +1,16 @@
#if !os(Linux)
import Foundation
private let integerRoundingBehavior = NSDecimalNumberHandler(roundingMode: .plain, scale: 0, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false)
private let integerRoundingBehavior = NSDecimalNumberHandler(
roundingMode: .plain,
scale: 0,
raiseOnExactness: false,
raiseOnOverflow: false,
raiseOnUnderflow: false,
raiseOnDivideByZero: false)
/// NSNumber adopts DatabaseValueConvertible
extension NSNumber : DatabaseValueConvertible {
extension NSNumber: DatabaseValueConvertible {
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
@@ -34,13 +40,17 @@ extension NSNumber : DatabaseValueConvertible {
return Int64(intValue).databaseValue
case "L":
let uint = uintValue
GRDBPrecondition(UInt64(uint) <= UInt64(Int64.max), "could not convert \(uint) to an Int64 that can be stored in the database")
GRDBPrecondition(
UInt64(uint) <= UInt64(Int64.max),
"could not convert \(uint) to an Int64 that can be stored in the database")
return Int64(uint).databaseValue
case "q":
return Int64(int64Value).databaseValue
case "Q":
let uint64 = uint64Value
GRDBPrecondition(uint64 <= UInt64(Int64.max), "could not convert \(uint64) to an Int64 that can be stored in the database")
GRDBPrecondition(
uint64 <= UInt64(Int64.max),
"could not convert \(uint64) to an Int64 that can be stored in the database")
return Int64(uint64).databaseValue
case "f":
return Double(floatValue).databaseValue
+1 -1
View File
@@ -2,7 +2,7 @@
import Foundation
/// NSString adopts DatabaseValueConvertible
extension NSString : DatabaseValueConvertible {
extension NSString: DatabaseValueConvertible {
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
@@ -58,6 +58,7 @@ class SQLiteDateParser {
withUnsafeMutablePointer(to: &parserComponents.minute) { minuteP in
withUnsafeMutablePointer(to: &parserComponents.second) { secondP in
parserComponents.nanosecond.withUnsafeMutableBufferPointer { nanosecondBuffer in
// swiftlint:disable:next line_length
withVaList([yearP, monthP, dayP, hourP, minuteP, secondP, nanosecondBuffer.baseAddress!]) { pointer in
vsscanf(cString, "%4d-%2d-%2d%*1[ T]%2d:%2d:%2d.%9s", pointer)
}
+2 -2
View File
@@ -2,7 +2,7 @@ import Foundation
#if !os(Linux)
/// NSURL stores its absoluteString in the database.
extension NSURL : DatabaseValueConvertible {
extension NSURL: DatabaseValueConvertible {
/// Returns a value that can be stored in the database.
/// (the URL's absoluteString).
@@ -21,4 +21,4 @@ extension NSURL : DatabaseValueConvertible {
#endif
/// URL stores its absoluteString in the database.
extension URL : DatabaseValueConvertible { }
extension URL: DatabaseValueConvertible { }
+3 -3
View File
@@ -1,10 +1,10 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
#if !os(Linux)
@@ -13,7 +13,8 @@ private struct DatabaseValueDecodingContainer: SingleValueDecodingContainer {
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null.
func decode(_ type: Bool.Type) throws -> Bool {
if let result = Bool.fromDatabaseValue(dbValue) {
@@ -131,9 +132,10 @@ private struct DatabaseValueDecodingContainer: SingleValueDecodingContainer {
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null.
func decode<T>(_ type: T.Type) throws -> T where T : Decodable {
func decode<T>(_ type: T.Type) throws -> T where T: Decodable {
if let type = T.self as? DatabaseValueConvertible.Type {
// Prefer DatabaseValueConvertible decoding over Decodable.
// This allows custom database decoding, such as decoding Date from
@@ -159,7 +161,7 @@ private struct DatabaseValueDecoder: Decoder {
// Decoder
let codingPath: [CodingKey]
var userInfo: [CodingUserInfoKey : Any] { return [:] }
var userInfo: [CodingUserInfoKey: Any] { return [:] }
func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> {
throw DecodingError.typeMismatch(
@@ -1,4 +1,4 @@
private struct DatabaseValueEncodingContainer : SingleValueEncodingContainer {
private struct DatabaseValueEncodingContainer: SingleValueEncodingContainer {
let encode: (DatabaseValue) -> Void
var codingPath: [CodingKey] { return [] }
@@ -34,7 +34,7 @@ private struct DatabaseValueEncodingContainer : SingleValueEncodingContainer {
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)` call.
mutating func encode<T>(_ value: T) throws where T : Encodable {
mutating func encode<T>(_ value: T) throws where T: Encodable {
if let dbValueConvertible = value as? DatabaseValueConvertible {
// Prefer DatabaseValueConvertible encoding over Decodable.
// This allows us to encode Date as String, for example.
@@ -45,7 +45,7 @@ private struct DatabaseValueEncodingContainer : SingleValueEncodingContainer {
}
}
private struct DatabaseValueEncoder : Encoder {
private struct DatabaseValueEncoder: Encoder {
let encode: (DatabaseValue) -> Void
/// The path of coding keys taken to get to this point in encoding.
@@ -53,7 +53,7 @@ private struct DatabaseValueEncoder : Encoder {
var codingPath: [CodingKey] { return [] }
/// Any contextual information set by the user for encoding.
var userInfo: [CodingUserInfoKey : Any] = [:]
var userInfo: [CodingUserInfoKey: Any] = [:]
init(encode: @escaping (DatabaseValue) -> Void) {
self.encode = encode
@@ -64,7 +64,8 @@ private struct DatabaseValueEncoder : Encoder {
/// - parameter type: The key type to use for the container.
/// - returns: A new keyed encoding container.
/// - precondition: May not be called after a prior `self.unkeyedContainer()` call.
/// - precondition: May not be called after a value has been encoded through a previous `self.singleValueContainer()` call.
/// - precondition: May not be called after a value has been encoded through
/// a previous `self.singleValueContainer()` call.
func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> {
fatalError("keyed encoding is not supported")
}
@@ -73,7 +74,8 @@ private struct DatabaseValueEncoder : Encoder {
///
/// - returns: A new empty unkeyed container.
/// - precondition: May not be called after a prior `self.container(keyedBy:)` call.
/// - precondition: May not be called after a value has been encoded through a previous `self.singleValueContainer()` call.
/// - precondition: May not be called after a value has been encoded through
/// a previous `self.singleValueContainer()` call.
func unkeyedContainer() -> UnkeyedEncodingContainer {
fatalError("unkeyed encoding is not supported")
}
@@ -83,7 +85,8 @@ private struct DatabaseValueEncoder : Encoder {
/// - returns: A new empty single value container.
/// - precondition: May not be called after a prior `self.container(keyedBy:)` call.
/// - precondition: May not be called after a prior `self.unkeyedContainer()` call.
/// - precondition: May not be called after a value has been encoded through a previous `self.singleValueContainer()` call.
/// - precondition: May not be called after a value has been encoded through
/// a previous `self.singleValueContainer()` call.
func singleValueContainer() -> SingleValueEncodingContainer {
return DatabaseValueEncodingContainer(encode: encode)
}
@@ -1,9 +1,9 @@
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
// MARK: - Value Types
@@ -500,11 +500,12 @@ extension DatabaseFunction {
/// let nameColumn = Column("name")
/// let request = Player.select(nameColumn.capitalized)
/// let names = try String.fetchAll(dbQueue, request) // [String]
public static let capitalize = DatabaseFunction("swiftCapitalizedString", argumentCount: 1, pure: true) { dbValues in
guard let string = String.fromDatabaseValue(dbValues[0]) else {
return nil
}
return string.capitalized
public static let capitalize =
DatabaseFunction("swiftCapitalizedString", argumentCount: 1, pure: true) { dbValues in
guard let string = String.fromDatabaseValue(dbValues[0]) else {
return nil
}
return string.capitalized
}
/// An SQL function that returns the Swift built-in lowercased
@@ -519,11 +520,12 @@ extension DatabaseFunction {
/// let nameColumn = Column("name")
/// let request = Player.select(nameColumn.lowercased())
/// let names = try String.fetchAll(dbQueue, request) // [String]
public static let lowercase = DatabaseFunction("swiftLowercaseString", argumentCount: 1, pure: true) { dbValues in
guard let string = String.fromDatabaseValue(dbValues[0]) else {
return nil
}
return string.lowercased()
public static let lowercase =
DatabaseFunction("swiftLowercaseString", argumentCount: 1, pure: true) { dbValues in
guard let string = String.fromDatabaseValue(dbValues[0]) else {
return nil
}
return string.lowercased()
}
/// An SQL function that returns the Swift built-in uppercased
@@ -538,11 +540,12 @@ extension DatabaseFunction {
/// let nameColumn = Column("name")
/// let request = Player.select(nameColumn.uppercased())
/// let names = try String.fetchAll(dbQueue, request) // [String]
public static let uppercase = DatabaseFunction("swiftUppercaseString", argumentCount: 1, pure: true) { dbValues in
guard let string = String.fromDatabaseValue(dbValues[0]) else {
return nil
}
return string.uppercased()
public static let uppercase =
DatabaseFunction("swiftUppercaseString", argumentCount: 1, pure: true) { dbValues in
guard let string = String.fromDatabaseValue(dbValues[0]) else {
return nil
}
return string.uppercased()
}
}
@@ -560,11 +563,12 @@ extension DatabaseFunction {
/// let request = Player.select(nameColumn.localizedCapitalized)
/// let names = try String.fetchAll(dbQueue, request) // [String]
@available(iOS 9.0, OSX 10.11, watchOS 3.0, *)
public static let localizedCapitalize = DatabaseFunction("swiftLocalizedCapitalizedString", argumentCount: 1, pure: true) { dbValues in
guard let string = String.fromDatabaseValue(dbValues[0]) else {
return nil
}
return string.localizedCapitalized
public static let localizedCapitalize =
DatabaseFunction("swiftLocalizedCapitalizedString", argumentCount: 1, pure: true) { dbValues in
guard let string = String.fromDatabaseValue(dbValues[0]) else {
return nil
}
return string.localizedCapitalized
}
/// An SQL function that returns the Swift built-in
@@ -580,11 +584,12 @@ extension DatabaseFunction {
/// let request = Player.select(nameColumn.localizedLowercased)
/// let names = try String.fetchAll(dbQueue, request) // [String]
@available(iOS 9.0, OSX 10.11, watchOS 3.0, *)
public static let localizedLowercase = DatabaseFunction("swiftLocalizedLowercaseString", argumentCount: 1, pure: true) { dbValues in
guard let string = String.fromDatabaseValue(dbValues[0]) else {
return nil
}
return string.localizedLowercase
public static let localizedLowercase =
DatabaseFunction("swiftLocalizedLowercaseString", argumentCount: 1, pure: true) { dbValues in
guard let string = String.fromDatabaseValue(dbValues[0]) else {
return nil
}
return string.localizedLowercase
}
/// An SQL function that returns the Swift built-in
@@ -600,11 +605,12 @@ extension DatabaseFunction {
/// let request = Player.select(nameColumn.localizedUppercased)
/// let names = try String.fetchAll(dbQueue, request) // [String]
@available(iOS 9.0, OSX 10.11, watchOS 3.0, *)
public static let localizedUppercase = DatabaseFunction("swiftLocalizedUppercaseString", argumentCount: 1, pure: true) { dbValues in
guard let string = String.fromDatabaseValue(dbValues[0]) else {
return nil
}
return string.localizedUppercase
public static let localizedUppercase =
DatabaseFunction("swiftLocalizedUppercaseString", argumentCount: 1, pure: true) { dbValues in
guard let string = String.fromDatabaseValue(dbValues[0]) else {
return nil
}
return string.localizedUppercase
}
}
@@ -637,8 +643,9 @@ extension DatabaseCollation {
/// name TEXT COLLATE \(collationName)
/// )
/// """)
public static let unicodeCompare = DatabaseCollation("swiftCompare") { (lhs, rhs) in
return (lhs < rhs) ? .orderedAscending : ((lhs == rhs) ? .orderedSame : .orderedDescending)
public static let unicodeCompare =
DatabaseCollation("swiftCompare") { (lhs, rhs) in
(lhs < rhs) ? .orderedAscending : ((lhs == rhs) ? .orderedSame : .orderedDescending)
}
/// A collation, or SQL string comparison function, that compares strings
@@ -655,8 +662,9 @@ extension DatabaseCollation {
/// name TEXT COLLATE \(collationName)
/// )
/// """)
public static let caseInsensitiveCompare = DatabaseCollation("swiftCaseInsensitiveCompare") { (lhs, rhs) in
return lhs.caseInsensitiveCompare(rhs)
public static let caseInsensitiveCompare =
DatabaseCollation("swiftCaseInsensitiveCompare") { (lhs, rhs) in
lhs.caseInsensitiveCompare(rhs)
}
/// A collation, or SQL string comparison function, that compares strings
@@ -673,8 +681,9 @@ extension DatabaseCollation {
/// name TEXT COLLATE \(collationName)
/// )
/// """)
public static let localizedCaseInsensitiveCompare = DatabaseCollation("swiftLocalizedCaseInsensitiveCompare") { (lhs, rhs) in
return lhs.localizedCaseInsensitiveCompare(rhs)
public static let localizedCaseInsensitiveCompare =
DatabaseCollation("swiftLocalizedCaseInsensitiveCompare") { (lhs, rhs) in
return lhs.localizedCaseInsensitiveCompare(rhs)
}
/// A collation, or SQL string comparison function, that compares strings
@@ -691,8 +700,9 @@ extension DatabaseCollation {
/// name TEXT COLLATE \(collationName)
/// )
/// """)
public static let localizedCompare = DatabaseCollation("swiftLocalizedCompare") { (lhs, rhs) in
return lhs.localizedCompare(rhs)
public static let localizedCompare =
DatabaseCollation("swiftLocalizedCompare") { (lhs, rhs) in
lhs.localizedCompare(rhs)
}
/// A collation, or SQL string comparison function, that compares strings
@@ -709,7 +719,8 @@ extension DatabaseCollation {
/// name TEXT COLLATE \(collationName)
/// )
/// """)
public static let localizedStandardCompare = DatabaseCollation("swiftLocalizedStandardCompare") { (lhs, rhs) in
return lhs.localizedStandardCompare(rhs)
public static let localizedStandardCompare =
DatabaseCollation("swiftLocalizedStandardCompare") { (lhs, rhs) in
lhs.localizedStandardCompare(rhs)
}
}
+347 -288
View File
@@ -1,13 +1,13 @@
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
extension Database {
// MARK: - Database Observation
/// Add a transaction observer, so that it gets notified of
@@ -17,7 +17,10 @@ extension Database {
/// - parameter extent: The duration of the observation. The default is
/// the observer lifetime (observation lasts until observer
/// is deallocated).
public func add(transactionObserver: TransactionObserver, extent: TransactionObservationExtent = .observerLifetime) {
public func add(
transactionObserver: TransactionObserver,
extent: TransactionObservationExtent = .observerLifetime)
{
SchedulingWatchdog.preconditionValidQueue(self)
observationBroker.add(transactionObserver: transactionObserver, extent: extent)
}
@@ -42,11 +45,11 @@ extension Database {
///
/// If the transaction is committed, the closure is executed in a protected
/// dispatch queue, serialized will all database updates.
public func afterNextTransactionCommit(_ closure: @escaping (Database) -> ()) {
class CommitHandler : TransactionObserver {
let closure: (Database) -> ()
public func afterNextTransactionCommit(_ closure: @escaping (Database) -> Void) {
class CommitHandler: TransactionObserver {
let closure: (Database) -> Void
init(_ closure: @escaping (Database) -> ()) {
init(_ closure: @escaping (Database) -> Void) {
self.closure = closure
}
@@ -195,7 +198,7 @@ class DatabaseObservationBroker {
}
func disableUntilNextTransaction(transactionObserver: TransactionObserver) {
if let observation = transactionObservations.first(where: { $0.isWrapping(transactionObserver)}) {
if let observation = transactionObservations.first(where: { $0.isWrapping(transactionObserver) }) {
observation.isDisabled = true
statementObservations.removeFirst { $0.0 === observation }
}
@@ -293,7 +296,7 @@ class DatabaseObservationBroker {
statementObservations = []
database.authorizer = nil
SchedulingWatchdog.current!.databaseObservationBroker = nil
// Reset transactionState before databaseDidRollback eventually
// executes other statements.
let transactionState = self.transactionState
@@ -318,7 +321,7 @@ class DatabaseObservationBroker {
statementObservations = []
database.authorizer = nil
SchedulingWatchdog.current!.databaseObservationBroker = nil
// Has statement any effect on transaction/savepoints?
if let transactionEffect = statement.transactionEffect {
switch transactionEffect {
@@ -379,7 +382,7 @@ class DatabaseObservationBroker {
}
}
#if SQLITE_ENABLE_PREUPDATE_HOOK
#if SQLITE_ENABLE_PREUPDATE_HOOK
// Called from sqlite3_preupdate_hook
private func databaseWillChange(with event: DatabasePreUpdateEvent) {
if savepointStack.isEmpty {
@@ -392,7 +395,7 @@ class DatabaseObservationBroker {
savepointStack.eventsBuffer.append((event: event.copy(), statementObservations: statementObservations))
}
}
#endif
#endif
// Called from sqlite3_update_hook
private func databaseDidChange(with event: DatabaseEvent) {
@@ -597,17 +600,23 @@ class DatabaseObservationBroker {
private func installUpdateHook() {
let brokerPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_update_hook(database.sqliteConnection, { (brokerPointer, updateKind, databaseNameCString, tableNameCString, rowID) in
let broker = Unmanaged<DatabaseObservationBroker>.fromOpaque(brokerPointer!).takeUnretainedValue()
broker.databaseDidChange(with: DatabaseEvent(
kind: DatabaseEvent.Kind(rawValue: updateKind)!,
rowID: rowID,
databaseNameCString: databaseNameCString,
tableNameCString: tableNameCString))
}, brokerPointer)
sqlite3_update_hook(
database.sqliteConnection,
{ (brokerPointer, updateKind, databaseNameCString, tableNameCString, rowID) in
let broker = Unmanaged<DatabaseObservationBroker>.fromOpaque(brokerPointer!).takeUnretainedValue()
broker.databaseDidChange(with: DatabaseEvent(
kind: DatabaseEvent.Kind(rawValue: updateKind)!,
rowID: rowID,
databaseNameCString: databaseNameCString,
tableNameCString: tableNameCString))
},
brokerPointer)
#if SQLITE_ENABLE_PREUPDATE_HOOK
sqlite3_preupdate_hook(database.sqliteConnection, { (brokerPointer, databaseConnection, updateKind, databaseNameCString, tableNameCString, initialRowID, finalRowID) in
sqlite3_preupdate_hook(
database.sqliteConnection,
// swiftlint:disable:next line_length
{ (brokerPointer, databaseConnection, updateKind, databaseNameCString, tableNameCString, initialRowID, finalRowID) in
let broker = Unmanaged<DatabaseObservationBroker>.fromOpaque(brokerPointer!).takeUnretainedValue()
broker.databaseWillChange(with: DatabasePreUpdateEvent(
connection: databaseConnection!,
@@ -616,14 +625,15 @@ class DatabaseObservationBroker {
finalRowID: finalRowID,
databaseNameCString: databaseNameCString,
tableNameCString: tableNameCString))
}, brokerPointer)
},
brokerPointer)
#endif
}
private func uninstallUpdateHook() {
sqlite3_update_hook(database.sqliteConnection, nil, nil)
#if SQLITE_ENABLE_PREUPDATE_HOOK
sqlite3_preupdate_hook(database.sqliteConnection, nil, nil)
sqlite3_preupdate_hook(database.sqliteConnection, nil, nil)
#endif
}
@@ -642,7 +652,7 @@ class DatabaseObservationBroker {
/// or rollbacked on a database.
///
/// Adopting types must be a class.
public protocol TransactionObserver : class {
public protocol TransactionObserver: AnyObject {
/// Filters database changes that should be notified the the
/// databaseDidChange(with:) method.
@@ -713,7 +723,8 @@ public protocol TransactionObserver : class {
///
/// As of OSX 10.11.5, and iOS 9.3.2, the built-in SQLite library
/// does not have this enabled, so you'll need to compile your own
/// copy using GRDBCustomSQLite. See https://github.com/groue/GRDB.swift/blob/master/Documentation/CustomSQLiteBuilds.md
/// copy using GRDBCustomSQLite.
/// See https://github.com/groue/GRDB.swift/blob/master/Documentation/CustomSQLiteBuilds.md
///
/// The databaseDidChangeWithEvent callback is always available,
/// and may provide most/all of what you need.
@@ -726,13 +737,13 @@ extension TransactionObserver {
/// Default implementation does nothing
public func databaseWillCommit() throws {
}
#if SQLITE_ENABLE_PREUPDATE_HOOK
/// Default implementation does nothing
public func databaseWillChange(with event: DatabasePreUpdateEvent) {
}
#endif
/// After this method has been called, the `databaseDidChange(with:)`
/// method won't be called until the next transaction.
///
@@ -756,7 +767,10 @@ extension TransactionObserver {
/// - precondition: This method must be called from `databaseDidChange(with:)`.
public func stopObservingDatabaseChangesUntilNextTransaction() {
guard let broker = SchedulingWatchdog.current?.databaseObservationBroker else {
fatalError("stopObservingDatabaseChangesUntilNextTransaction must be called from the databaseDidChange method")
fatalError("""
stopObservingDatabaseChangesUntilNextTransaction must be called \
from the databaseDidChange method
""")
}
broker.disableUntilNextTransaction(transactionObserver: self)
}
@@ -801,23 +815,23 @@ final class TransactionObservation {
if isDisabled { return false }
return observer?.observes(eventsOfKind: eventKind) ?? false
}
#if SQLITE_ENABLE_PREUPDATE_HOOK
func databaseWillChange(with event: DatabasePreUpdateEvent) {
if isDisabled { return }
observer?.databaseWillChange(with: event)
}
#endif
func databaseDidChange(with event: DatabaseEvent) {
if isDisabled { return }
observer?.databaseDidChange(with: event)
}
func databaseWillCommit() throws {
try observer?.databaseWillCommit()
}
func databaseDidCommit(_ db: Database) {
switch extent {
case .observerLifetime, .databaseLifetime:
@@ -867,11 +881,11 @@ public enum DatabaseEventKind {
var modifiedRegion: DatabaseRegion {
switch self {
case .delete(let tableName):
case let .delete(tableName):
return DatabaseRegion(table: tableName)
case .insert(let tableName):
case let .insert(tableName):
return DatabaseRegion(table: tableName)
case .update(let tableName, let updatedColumnNames):
case let .update(tableName, updatedColumnNames):
return DatabaseRegion(table: tableName, columns: updatedColumnNames)
}
}
@@ -881,9 +895,9 @@ extension DatabaseEventKind {
/// The impacted database table
public var tableName: String {
switch self {
case .insert(tableName: let tableName): return tableName
case .delete(tableName: let tableName): return tableName
case .update(tableName: let tableName, columnNames: _): return tableName
case let .insert(tableName: tableName): return tableName
case let .delete(tableName: tableName): return tableName
case let .update(tableName: tableName, columnNames: _): return tableName
}
}
}
@@ -915,7 +929,7 @@ public struct DatabaseEvent {
/// The database name
public var databaseName: String { return impl.databaseName }
/// The table name
public var tableName: String { return impl.tableName }
@@ -941,11 +955,16 @@ public struct DatabaseEvent {
}
init(kind: Kind, rowID: Int64, databaseNameCString: UnsafePointer<Int8>?, tableNameCString: UnsafePointer<Int8>?) {
self.init(kind: kind, rowID: rowID, impl: MetalDatabaseEventImpl(databaseNameCString: databaseNameCString, tableNameCString: tableNameCString))
self.init(
kind: kind,
rowID: rowID,
impl: MetalDatabaseEventImpl(
databaseNameCString: databaseNameCString,
tableNameCString: tableNameCString))
}
}
extension DatabaseEvent : DatabaseEventProtocol {
extension DatabaseEvent: DatabaseEventProtocol {
func send(to observer: TransactionObservation) {
observer.databaseDidChange(with: self)
}
@@ -970,19 +989,25 @@ private protocol DatabaseEventImpl {
/// Optimization: MetalDatabaseEventImpl does not create Swift strings from raw
/// SQLite char* until actually asked for databaseName or tableName.
private struct MetalDatabaseEventImpl : DatabaseEventImpl {
private struct MetalDatabaseEventImpl: DatabaseEventImpl {
let databaseNameCString: UnsafePointer<Int8>?
let tableNameCString: UnsafePointer<Int8>?
var databaseName: String { return String(cString: databaseNameCString!) }
var tableName: String { return String(cString: tableNameCString!) }
func copy(_ event: DatabaseEvent) -> DatabaseEvent {
return DatabaseEvent(kind: event.kind, rowID: event.rowID, impl: CopiedDatabaseEventImpl(databaseName: databaseName, tableName: tableName))
return DatabaseEvent(
kind: event.kind,
rowID: event.rowID,
impl: CopiedDatabaseEventImpl(
databaseName: databaseName,
tableName: tableName))
}
}
/// Impl for DatabaseEvent that contains copies of event strings.
private struct CopiedDatabaseEventImpl : DatabaseEventImpl {
private struct CopiedDatabaseEventImpl: DatabaseEventImpl {
let databaseName: String
let tableName: String
func copy(_ event: DatabaseEvent) -> DatabaseEvent {
@@ -992,258 +1017,293 @@ private struct CopiedDatabaseEventImpl : DatabaseEventImpl {
#if SQLITE_ENABLE_PREUPDATE_HOOK
public struct DatabasePreUpdateEvent {
public struct DatabasePreUpdateEvent {
/// An event kind
public enum Kind: Int32 {
/// SQLITE_INSERT
case insert = 18
/// An event kind
public enum Kind: Int32 {
/// SQLITE_INSERT
case insert = 18
/// SQLITE_DELETE
case delete = 9
/// SQLITE_UPDATE
case update = 23
}
/// SQLITE_DELETE
case delete = 9
/// The event kind
public let kind: Kind
/// The database name
public var databaseName: String { return impl.databaseName }
/// The table name
public var tableName: String { return impl.tableName }
/// The number of columns in the row that is being inserted, updated, or deleted.
public var count: Int { return Int(impl.columnsCount) }
/// The triggering depth of the row update
/// Returns:
/// 0 if the preupdate callback was invoked as a result of a direct insert,
// update, or delete operation;
/// 1 for inserts, updates, or deletes invoked by top-level triggers;
/// 2 for changes resulting from triggers called by top-level triggers;
/// ... and so forth
public var depth: CInt { return impl.depth }
/// The initial rowID of the row being changed for .Update and .Delete changes,
/// and nil for .Insert changes.
public let initialRowID: Int64?
/// The final rowID of the row being changed for .Update and .Insert changes,
/// and nil for .Delete changes.
public let finalRowID: Int64?
/// The initial database values in the row.
///
/// Values appear in the same order as the columns in the table.
///
/// The result is nil if the event is an .Insert event.
public var initialDatabaseValues: [DatabaseValue]? {
guard (kind == .update || kind == .delete) else { return nil }
return impl.initialDatabaseValues
}
/// Returns the initial `DatabaseValue` at given index.
///
/// Indexes span from 0 for the leftmost column to (row.count - 1) for the
/// righmost column.
///
/// The result is nil if the event is an .Insert event.
public func initialDatabaseValue(atIndex index: Int) -> DatabaseValue? {
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
guard (kind == .update || kind == .delete) else { return nil }
return impl.initialDatabaseValue(atIndex: index)
}
/// The final database values in the row.
///
/// Values appear in the same order as the columns in the table.
///
/// The result is nil if the event is a .Delete event.
public var finalDatabaseValues: [DatabaseValue]? {
guard (kind == .update || kind == .insert) else { return nil }
return impl.finalDatabaseValues
}
/// Returns the final `DatabaseValue` at given index.
///
/// Indexes span from 0 for the leftmost column to (row.count - 1) for the
/// righmost column.
///
/// The result is nil if the event is a .Delete event.
public func finalDatabaseValue(atIndex index: Int) -> DatabaseValue? {
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
guard (kind == .update || kind == .insert) else { return nil }
return impl.finalDatabaseValue(atIndex: index)
}
/// Returns an event that can be stored:
///
/// class MyObserver: TransactionObserver {
/// var events: [DatabasePreUpdateEvent]
/// func databaseWillChange(with event: DatabasePreUpdateEvent) {
/// events.append(event.copy())
/// }
/// }
public func copy() -> DatabasePreUpdateEvent {
return impl.copy(self)
}
fileprivate init(kind: Kind, initialRowID: Int64?, finalRowID: Int64?, impl: DatabasePreUpdateEventImpl) {
self.kind = kind
self.initialRowID = (kind == .update || kind == .delete ) ? initialRowID : nil
self.finalRowID = (kind == .update || kind == .insert ) ? finalRowID : nil
self.impl = impl
}
init(connection: SQLiteConnection, kind: Kind, initialRowID: Int64, finalRowID: Int64, databaseNameCString: UnsafePointer<Int8>?, tableNameCString: UnsafePointer<Int8>?) {
self.init(kind: kind,
initialRowID: (kind == .update || kind == .delete ) ? finalRowID : nil,
finalRowID: (kind == .update || kind == .insert ) ? finalRowID : nil,
impl: MetalDatabasePreUpdateEventImpl(connection: connection, kind: kind, databaseNameCString: databaseNameCString, tableNameCString: tableNameCString))
}
private let impl: DatabasePreUpdateEventImpl
/// SQLITE_UPDATE
case update = 23
}
extension DatabasePreUpdateEvent : DatabaseEventProtocol {
func send(to observer: TransactionObservation) {
observer.databaseWillChange(with: self)
}
func matchesKind(_ databaseEventKind: DatabaseEventKind) -> Bool {
switch (kind, databaseEventKind) {
case (.insert, .insert(let tableName)): return self.tableName == tableName
case (.delete, .delete(let tableName)): return self.tableName == tableName
case (.update, .update(let tableName, _)): return self.tableName == tableName
default:
return false
}
}
/// The event kind
public let kind: Kind
/// The database name
public var databaseName: String { return impl.databaseName }
/// The table name
public var tableName: String { return impl.tableName }
/// The number of columns in the row that is being inserted, updated, or deleted.
public var count: Int { return Int(impl.columnsCount) }
/// The triggering depth of the row update
/// Returns:
/// 0 if the preupdate callback was invoked as a result of a direct insert,
// update, or delete operation;
/// 1 for inserts, updates, or deletes invoked by top-level triggers;
/// 2 for changes resulting from triggers called by top-level triggers;
/// ... and so forth
public var depth: CInt { return impl.depth }
/// The initial rowID of the row being changed for .Update and .Delete changes,
/// and nil for .Insert changes.
public let initialRowID: Int64?
/// The final rowID of the row being changed for .Update and .Insert changes,
/// and nil for .Delete changes.
public let finalRowID: Int64?
/// The initial database values in the row.
///
/// Values appear in the same order as the columns in the table.
///
/// The result is nil if the event is an .Insert event.
public var initialDatabaseValues: [DatabaseValue]? {
guard kind == .update || kind == .delete else { return nil }
return impl.initialDatabaseValues
}
/// Protocol for internal implementation of DatabaseEvent
private protocol DatabasePreUpdateEventImpl {
var databaseName: String { get }
var tableName: String { get }
var columnsCount: CInt { get }
var depth: CInt { get }
var initialDatabaseValues: [DatabaseValue]? { get }
var finalDatabaseValues: [DatabaseValue]? { get }
func initialDatabaseValue(atIndex index: Int) -> DatabaseValue?
func finalDatabaseValue(atIndex index: Int) -> DatabaseValue?
func copy(_ event: DatabasePreUpdateEvent) -> DatabasePreUpdateEvent
/// Returns the initial `DatabaseValue` at given index.
///
/// Indexes span from 0 for the leftmost column to (row.count - 1) for the
/// righmost column.
///
/// The result is nil if the event is an .Insert event.
public func initialDatabaseValue(atIndex index: Int) -> DatabaseValue? {
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
guard kind == .update || kind == .delete else { return nil }
return impl.initialDatabaseValue(atIndex: index)
}
/// Optimization: MetalDatabasePreUpdateEventImpl does not create Swift strings from raw
/// SQLite char* until actually asked for databaseName or tableName,
/// nor does it request other data via the sqlite3_preupdate_* APIs
/// until asked.
private struct MetalDatabasePreUpdateEventImpl : DatabasePreUpdateEventImpl {
let connection: SQLiteConnection
let kind: DatabasePreUpdateEvent.Kind
let databaseNameCString: UnsafePointer<Int8>?
let tableNameCString: UnsafePointer<Int8>?
var databaseName: String { return String(cString: databaseNameCString!) }
var tableName: String { return String(cString: tableNameCString!) }
var columnsCount: CInt { return sqlite3_preupdate_count(connection) }
var depth: CInt { return sqlite3_preupdate_depth(connection) }
var initialDatabaseValues: [DatabaseValue]? {
guard (kind == .update || kind == .delete) else { return nil }
return preupdate_getValues_old(connection)
}
var finalDatabaseValues: [DatabaseValue]? {
guard (kind == .update || kind == .insert) else { return nil }
return preupdate_getValues_new(connection)
}
func initialDatabaseValue(atIndex index: Int) -> DatabaseValue? {
let columnCount = columnsCount
precondition(index >= 0 && index < Int(columnCount), "row index out of range")
return getValue(connection, column: CInt(index), sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in
return sqlite3_preupdate_old(connection, column, &value)
})
}
func finalDatabaseValue(atIndex index: Int) -> DatabaseValue? {
let columnCount = columnsCount
precondition(index >= 0 && index < Int(columnCount), "row index out of range")
return getValue(connection, column: CInt(index), sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in
return sqlite3_preupdate_new(connection, column, &value)
})
}
func copy(_ event: DatabasePreUpdateEvent) -> DatabasePreUpdateEvent {
return DatabasePreUpdateEvent(kind: event.kind, initialRowID: event.initialRowID, finalRowID: event.finalRowID, impl: CopiedDatabasePreUpdateEventImpl(
databaseName: databaseName,
tableName: tableName,
columnsCount: columnsCount,
depth: depth,
initialDatabaseValues: initialDatabaseValues,
finalDatabaseValues: finalDatabaseValues))
}
private func preupdate_getValues(_ connection: SQLiteConnection, sqlite_func: (_ connection: SQLiteConnection, _ column: CInt, _ value: inout SQLiteValue? ) -> CInt ) -> [DatabaseValue]? {
let columnCount = sqlite3_preupdate_count(connection)
guard columnCount > 0 else { return nil }
var columnValues = [DatabaseValue]()
for i in 0..<columnCount {
let value = getValue(connection, column: i, sqlite_func: sqlite_func)!
columnValues.append(value)
}
return columnValues
}
private func getValue(_ connection: SQLiteConnection, column: CInt, sqlite_func: (_ connection: SQLiteConnection, _ column: CInt, _ value: inout SQLiteValue? ) -> CInt ) -> DatabaseValue? {
var value : SQLiteValue? = nil
guard sqlite_func(connection, column, &value) == SQLITE_OK else { return nil }
if let value = value {
return DatabaseValue(sqliteValue: value)
}
return nil
}
private func preupdate_getValues_old(_ connection: SQLiteConnection) -> [DatabaseValue]? {
return preupdate_getValues(connection, sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in
return sqlite3_preupdate_old(connection, column, &value)
})
}
private func preupdate_getValues_new(_ connection: SQLiteConnection) -> [DatabaseValue]? {
return preupdate_getValues(connection, sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in
return sqlite3_preupdate_new(connection, column, &value)
})
}
/// The final database values in the row.
///
/// Values appear in the same order as the columns in the table.
///
/// The result is nil if the event is a .Delete event.
public var finalDatabaseValues: [DatabaseValue]? {
guard kind == .update || kind == .insert else { return nil }
return impl.finalDatabaseValues
}
/// Impl for DatabasePreUpdateEvent that contains copies of all event data.
private struct CopiedDatabasePreUpdateEventImpl : DatabasePreUpdateEventImpl {
let databaseName: String
let tableName: String
let columnsCount: CInt
let depth: CInt
let initialDatabaseValues: [DatabaseValue]?
let finalDatabaseValues: [DatabaseValue]?
func initialDatabaseValue(atIndex index: Int) -> DatabaseValue? { return initialDatabaseValues?[index] }
func finalDatabaseValue(atIndex index: Int) -> DatabaseValue? { return finalDatabaseValues?[index] }
func copy(_ event: DatabasePreUpdateEvent) -> DatabasePreUpdateEvent {
return event
/// Returns the final `DatabaseValue` at given index.
///
/// Indexes span from 0 for the leftmost column to (row.count - 1) for the
/// righmost column.
///
/// The result is nil if the event is a .Delete event.
public func finalDatabaseValue(atIndex index: Int) -> DatabaseValue? {
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
guard kind == .update || kind == .insert else { return nil }
return impl.finalDatabaseValue(atIndex: index)
}
/// Returns an event that can be stored:
///
/// class MyObserver: TransactionObserver {
/// var events: [DatabasePreUpdateEvent]
/// func databaseWillChange(with event: DatabasePreUpdateEvent) {
/// events.append(event.copy())
/// }
/// }
public func copy() -> DatabasePreUpdateEvent {
return impl.copy(self)
}
fileprivate init(kind: Kind, initialRowID: Int64?, finalRowID: Int64?, impl: DatabasePreUpdateEventImpl) {
self.kind = kind
self.initialRowID = (kind == .update || kind == .delete ) ? initialRowID : nil
self.finalRowID = (kind == .update || kind == .insert ) ? finalRowID : nil
self.impl = impl
}
init(
connection: SQLiteConnection,
kind: Kind,
initialRowID: Int64,
finalRowID: Int64,
databaseNameCString: UnsafePointer<Int8>?,
tableNameCString: UnsafePointer<Int8>?)
{
self.init(
kind: kind,
initialRowID: (kind == .update || kind == .delete ) ? finalRowID : nil,
finalRowID: (kind == .update || kind == .insert ) ? finalRowID : nil,
impl: MetalDatabasePreUpdateEventImpl(
connection: connection,
kind: kind,
databaseNameCString: databaseNameCString,
tableNameCString: tableNameCString))
}
private let impl: DatabasePreUpdateEventImpl
}
extension DatabasePreUpdateEvent: DatabaseEventProtocol {
func send(to observer: TransactionObservation) {
observer.databaseWillChange(with: self)
}
func matchesKind(_ databaseEventKind: DatabaseEventKind) -> Bool {
switch (kind, databaseEventKind) {
case (.insert, .insert(let tableName)): return self.tableName == tableName
case (.delete, .delete(let tableName)): return self.tableName == tableName
case (.update, .update(let tableName, _)): return self.tableName == tableName
default:
return false
}
}
}
/// Protocol for internal implementation of DatabaseEvent
private protocol DatabasePreUpdateEventImpl {
var databaseName: String { get }
var tableName: String { get }
var columnsCount: CInt { get }
var depth: CInt { get }
var initialDatabaseValues: [DatabaseValue]? { get }
var finalDatabaseValues: [DatabaseValue]? { get }
func initialDatabaseValue(atIndex index: Int) -> DatabaseValue?
func finalDatabaseValue(atIndex index: Int) -> DatabaseValue?
func copy(_ event: DatabasePreUpdateEvent) -> DatabasePreUpdateEvent
}
/// Optimization: MetalDatabasePreUpdateEventImpl does not create Swift strings from raw
/// SQLite char* until actually asked for databaseName or tableName,
/// nor does it request other data via the sqlite3_preupdate_* APIs
/// until asked.
private struct MetalDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl {
let connection: SQLiteConnection
let kind: DatabasePreUpdateEvent.Kind
let databaseNameCString: UnsafePointer<Int8>?
let tableNameCString: UnsafePointer<Int8>?
var databaseName: String { return String(cString: databaseNameCString!) }
var tableName: String { return String(cString: tableNameCString!) }
var columnsCount: CInt { return sqlite3_preupdate_count(connection) }
var depth: CInt { return sqlite3_preupdate_depth(connection) }
var initialDatabaseValues: [DatabaseValue]? {
guard kind == .update || kind == .delete else { return nil }
return preupdate_getValues_old(connection)
}
var finalDatabaseValues: [DatabaseValue]? {
guard kind == .update || kind == .insert else { return nil }
return preupdate_getValues_new(connection)
}
func initialDatabaseValue(atIndex index: Int) -> DatabaseValue? {
let columnCount = columnsCount
precondition(index >= 0 && index < Int(columnCount), "row index out of range")
return getValue(
connection,
column: CInt(index),
sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in
sqlite3_preupdate_old(connection, column, &value)
})
}
func finalDatabaseValue(atIndex index: Int) -> DatabaseValue? {
let columnCount = columnsCount
precondition(index >= 0 && index < Int(columnCount), "row index out of range")
return getValue(
connection,
column: CInt(index),
sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in
sqlite3_preupdate_new(connection, column, &value)
})
}
func copy(_ event: DatabasePreUpdateEvent) -> DatabasePreUpdateEvent {
return DatabasePreUpdateEvent(
kind: event.kind,
initialRowID: event.initialRowID,
finalRowID: event.finalRowID,
impl: CopiedDatabasePreUpdateEventImpl(
databaseName: databaseName,
tableName: tableName,
columnsCount: columnsCount,
depth: depth,
initialDatabaseValues: initialDatabaseValues,
finalDatabaseValues: finalDatabaseValues))
}
private func preupdate_getValues(
_ connection: SQLiteConnection,
sqlite_func: (_ connection: SQLiteConnection, _ column: CInt, _ value: inout SQLiteValue? ) -> CInt)
-> [DatabaseValue]?
{
let columnCount = sqlite3_preupdate_count(connection)
guard columnCount > 0 else { return nil }
var columnValues = [DatabaseValue]()
for i in 0..<columnCount {
let value = getValue(connection, column: i, sqlite_func: sqlite_func)!
columnValues.append(value)
}
return columnValues
}
private func getValue(
_ connection: SQLiteConnection,
column: CInt,
sqlite_func: (_ connection: SQLiteConnection, _ column: CInt, _ value: inout SQLiteValue? ) -> CInt)
-> DatabaseValue?
{
var value: SQLiteValue? = nil
guard sqlite_func(connection, column, &value) == SQLITE_OK else { return nil }
if let value = value {
return DatabaseValue(sqliteValue: value)
}
return nil
}
private func preupdate_getValues_old(_ connection: SQLiteConnection) -> [DatabaseValue]? {
return preupdate_getValues(
connection,
sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in
sqlite3_preupdate_old(connection, column, &value)
})
}
private func preupdate_getValues_new(_ connection: SQLiteConnection) -> [DatabaseValue]? {
return preupdate_getValues(
connection,
sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in
sqlite3_preupdate_new(connection, column, &value)
})
}
}
/// Impl for DatabasePreUpdateEvent that contains copies of all event data.
private struct CopiedDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl {
let databaseName: String
let tableName: String
let columnsCount: CInt
let depth: CInt
let initialDatabaseValues: [DatabaseValue]?
let finalDatabaseValues: [DatabaseValue]?
func initialDatabaseValue(atIndex index: Int) -> DatabaseValue? { return initialDatabaseValues?[index] }
func finalDatabaseValue(atIndex index: Int) -> DatabaseValue? { return finalDatabaseValues?[index] }
func copy(_ event: DatabasePreUpdateEvent) -> DatabasePreUpdateEvent {
return event
}
}
#endif
@@ -1330,4 +1390,3 @@ class SavepointStack {
}
}
}
+5 -2
View File
@@ -4,7 +4,7 @@
/// try db.create(virtualTable: "document", using: FTS3()) { t in
/// t.column("content")
/// }
public struct FTS3 : VirtualTableModule {
public struct FTS3: VirtualTableModule {
/// Options for Latin script characters. Matches the raw "remove_diacritics"
/// tokenizer argument.
///
@@ -55,7 +55,10 @@ public struct FTS3 : VirtualTableModule {
if tokenizer.arguments.isEmpty {
arguments.append("tokenize=\(tokenizer.name)")
} else {
arguments.append("tokenize=\(tokenizer.name) " + tokenizer.arguments.map { "\"\($0)\"" as String }.joined(separator: " "))
arguments.append(
"tokenize=\(tokenizer.name) " + tokenizer.arguments
.map { "\"\($0)\"" as String }
.joined(separator: " "))
}
}
return arguments
+2 -2
View File
@@ -24,7 +24,7 @@ public struct FTS3Pattern {
}
} catch let error as DatabaseError {
// Remove private SQL & arguments from the thrown error
throw DatabaseError(resultCode: error.extendedResultCode, message: error.message, sql: nil, arguments: nil)
throw DatabaseError(resultCode: error.extendedResultCode, message: error.message)
}
// Pattern is valid
@@ -115,7 +115,7 @@ public struct FTS3Pattern {
#endif
}
extension FTS3Pattern : DatabaseValueConvertible {
extension FTS3Pattern: DatabaseValueConvertible {
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return rawPattern.databaseValue
+34 -11
View File
@@ -48,7 +48,12 @@ public struct FTS3TokenizerDescriptor {
/// these characters as token characters.
///
/// See https://www.sqlite.org/fts3.html#tokenizer
public static func unicode61(diacritics: FTS3.Diacritics = .removeLegacy, separators: Set<Character> = [], tokenCharacters: Set<Character> = []) -> FTS3TokenizerDescriptor {
public static func unicode61(
diacritics: FTS3.Diacritics = .removeLegacy,
separators: Set<Character> = [],
tokenCharacters: Set<Character> = [])
-> FTS3TokenizerDescriptor
{
return _unicode61(diacritics: diacritics, separators: separators, tokenCharacters: tokenCharacters)
}
#else
@@ -68,14 +73,25 @@ public struct FTS3TokenizerDescriptor {
///
/// See https://www.sqlite.org/fts3.html#tokenizer
@available(OSX 10.10, *)
public static func unicode61(diacritics: FTS3.Diacritics = .removeLegacy, separators: Set<Character> = [], tokenCharacters: Set<Character> = []) -> FTS3TokenizerDescriptor {
public static func unicode61(
diacritics: FTS3.Diacritics = .removeLegacy,
separators: Set<Character> = [],
tokenCharacters: Set<Character> = [])
-> FTS3TokenizerDescriptor
{
// query_only pragma was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
// It is available from iOS 8.2 and OS X 10.10
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
return _unicode61(diacritics: diacritics, separators: separators, tokenCharacters: tokenCharacters)
}
#endif
private static func _unicode61(diacritics: FTS3.Diacritics, separators: Set<Character> = [], tokenCharacters: Set<Character> = []) -> FTS3TokenizerDescriptor {
private static func _unicode61(
diacritics: FTS3.Diacritics,
separators: Set<Character> = [],
tokenCharacters: Set<Character> = [])
-> FTS3TokenizerDescriptor
{
var arguments: [String] = []
switch diacritics {
case .removeLegacy:
@@ -88,12 +104,16 @@ public struct FTS3TokenizerDescriptor {
#endif
}
if !separators.isEmpty {
// TODO: test "=" and "\"", "(" and ")" as separators, with both FTS3Pattern(matchingAnyTokenIn:tokenizer:) and Database.create(virtualTable:using:)
arguments.append("separators=" + separators.sorted().map { String($0) }.joined(separator: ""))
// TODO: test "=" and "\"", "(" and ")" as separators, with
// both FTS3Pattern(matchingAnyTokenIn:tokenizer:)
// and Database.create(virtualTable:using:)
arguments.append("separators=" + separators.sorted().map { String($0) }.joined())
}
if !tokenCharacters.isEmpty {
// TODO: test "=" and "\"", "(" and ")" as tokenCharacters, with both FTS3Pattern(matchingAnyTokenIn:tokenizer:) and Database.create(virtualTable:using:)
arguments.append("tokenchars=" + tokenCharacters.sorted().map { String($0) }.joined(separator: ""))
// TODO: test "=" and "\"", "(" and ")" as tokenCharacters, with
// both FTS3Pattern(matchingAnyTokenIn:tokenizer:)
// and Database.create(virtualTable:using:)
arguments.append("tokenchars=" + tokenCharacters.sorted().map { String($0) }.joined())
}
return FTS3TokenizerDescriptor("unicode61", arguments: arguments)
}
@@ -108,13 +128,14 @@ public struct FTS3TokenizerDescriptor {
return _tokenize(string)
}
#endif
/// Returns an array of tokens found in the string argument.
///
/// FTS3TokenizerDescriptor.simple.tokenize("foo bar") // ["foo", "bar"]
private func _tokenize(_ string: String) -> [String] {
// fts3tokenize was introduced in SQLite 3.7.17 https://www.sqlite.org/changes.html#version_3_7_17
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
// It is available from iOS 8.2 and OS X 10.10
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
return DatabaseQueue().inDatabase { db in
var tokenizerChunks: [String] = []
tokenizerChunks.append(name)
@@ -124,7 +145,9 @@ public struct FTS3TokenizerDescriptor {
let tokenizerSQL = tokenizerChunks.joined(separator: ", ")
// Assume fts3tokenize virtual table in an in-memory database always succeeds
try! db.execute(sql: "CREATE VIRTUAL TABLE tokens USING fts3tokenize(\(tokenizerSQL))")
return try! String.fetchAll(db, sql: "SELECT token FROM tokens WHERE input = ? ORDER BY position", arguments: [string])
return try! String.fetchAll(db, sql: """
SELECT token FROM tokens WHERE input = ? ORDER BY position
""", arguments: [string])
}
}
}
+9 -4
View File
@@ -6,7 +6,7 @@
/// }
///
/// See https://www.sqlite.org/fts3.html
public struct FTS4 : VirtualTableModule {
public struct FTS4: VirtualTableModule {
/// Creates a FTS4 module suitable for the Database
/// `create(virtualTable:using:)` method.
@@ -53,7 +53,10 @@ public struct FTS4 : VirtualTableModule {
if tokenizer.arguments.isEmpty {
arguments.append("tokenize=\(tokenizer.name)")
} else {
arguments.append("tokenize=\(tokenizer.name) " + tokenizer.arguments.map { "\"\($0)\"" as String }.joined(separator: " "))
arguments.append(
"tokenize=\(tokenizer.name) " + tokenizer.arguments
.map { "\"\($0)\"" as String }
.joined(separator: " "))
}
}
@@ -273,7 +276,8 @@ public final class FTS4ColumnDefinition {
@discardableResult
public func notIndexed() -> Self {
// notindexed FTS4 option was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
// It is available from iOS 8.2 and OS X 10.10
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
self.isIndexed = false
return self
}
@@ -292,7 +296,8 @@ public final class FTS4ColumnDefinition {
@discardableResult
public func notIndexed() -> Self {
// notindexed FTS4 option was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
// It is available from iOS 8.2 and OS X 10.10
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
self.isIndexed = false
return self
}
+31 -18
View File
@@ -1,10 +1,10 @@
#if SQLITE_ENABLE_FTS5
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
/// FTS5 lets you define "fts5" virtual tables.
@@ -15,7 +15,7 @@
/// }
///
/// See https://www.sqlite.org/fts5.html
public struct FTS5 : VirtualTableModule {
public struct FTS5: VirtualTableModule {
/// Options for Latin script characters. Matches the raw "remove_diacritics"
/// tokenizer argument.
///
@@ -34,7 +34,7 @@ public struct FTS5 : VirtualTableModule {
case remove
#endif
}
/// Creates a FTS5 module suitable for the Database
/// `create(virtualTable:using:)` method.
///
@@ -75,30 +75,41 @@ public struct FTS5 : VirtualTableModule {
}
if let tokenizer = definition.tokenizer {
arguments.append("tokenize=\(tokenizer.components.joined(separator: " ").sqlExpression.quotedSQL(wrappedInParenthesis: false))")
let tokenizerSQL = tokenizer
.components
.joined(separator: " ")
.sqlExpression
.quotedSQL()
arguments.append("tokenize=\(tokenizerSQL)")
}
switch definition.contentMode {
case .raw(let content, let contentRowID):
case let .raw(content, contentRowID):
if let content = content {
let quotedContent = content.sqlExpression.quotedSQL(wrappedInParenthesis: false)
let quotedContent = content.sqlExpression.quotedSQL()
arguments.append("content=\(quotedContent)")
}
if let contentRowID = contentRowID {
let quotedContentRowID = contentRowID.sqlExpression.quotedSQL(wrappedInParenthesis: false)
let quotedContentRowID = contentRowID.sqlExpression.quotedSQL()
arguments.append("content_rowid=\(quotedContentRowID)")
}
case .synchronized(let contentTable):
arguments.append("content=\(contentTable.sqlExpression.quotedSQL(wrappedInParenthesis: false))")
case let .synchronized(contentTable):
arguments.append("content=\(contentTable.sqlExpression.quotedSQL())")
if let rowIDColumn = try db.primaryKey(contentTable).rowIDColumn {
let quotedRowID = rowIDColumn.sqlExpression.quotedSQL(wrappedInParenthesis: false)
let quotedRowID = rowIDColumn.sqlExpression.quotedSQL()
arguments.append("content_rowid=\(quotedRowID)")
}
}
if let prefixes = definition.prefixes {
arguments.append("prefix=\(prefixes.sorted().map { "\($0)" }.joined(separator: " ").sqlExpression.quotedSQL(wrappedInParenthesis: false))")
let prefix = prefixes
.sorted()
.map { "\($0)" }
.joined(separator: " ")
.sqlExpression
.quotedSQL()
arguments.append("prefix=\(prefix)")
}
if let columnSize = definition.columnSize {
@@ -141,14 +152,14 @@ public struct FTS5 : VirtualTableModule {
try db.execute(sql: """
CREATE TRIGGER \("__\(tableName)_ai".quotedDatabaseIdentifier) AFTER INSERT ON \(content) BEGIN
INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns));
INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns));
END;
CREATE TRIGGER \("__\(tableName)_ad".quotedDatabaseIdentifier) AFTER DELETE ON \(content) BEGIN
INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns));
INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns));
END;
CREATE TRIGGER \("__\(tableName)_au".quotedDatabaseIdentifier) AFTER UPDATE ON \(content) BEGIN
INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns));
INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns));
INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns));
INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns));
END;
""")
@@ -190,7 +201,7 @@ public struct FTS5 : VirtualTableModule {
}
#if swift(>=5.0)
return data.withUnsafeBytes {
$0.bindMemory(to: UnsafePointer<fts5_api>.self).first!
$0.bindMemory(to: UnsafePointer<fts5_api>.self).first!
}
#else
return data.withUnsafeBytes {
@@ -203,7 +214,9 @@ public struct FTS5 : VirtualTableModule {
// https://forums.swift.org/t/c-interoperability-combinations-of-library-and-os-versions/14029/4
private static func api_v2(
_ db: Database,
// swiftlint:disable:next line_length
_ sqlite3_prepare_v3: @convention(c) (OpaquePointer?, UnsafePointer<Int8>?, Int32, UInt32, UnsafeMutablePointer<OpaquePointer?>?, UnsafeMutablePointer<UnsafePointer<Int8>?>?) -> Int32,
// swiftlint:disable:next line_length
_ sqlite3_bind_pointer: @convention(c) (OpaquePointer?, Int32, UnsafeMutableRawPointer?, UnsafePointer<Int8>?, (@convention(c) (UnsafeMutableRawPointer?) -> Void)?) -> Int32)
-> UnsafePointer<fts5_api>
{
+40 -11
View File
@@ -1,14 +1,14 @@
#if SQLITE_ENABLE_FTS5
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
/// The protocol for custom FTS5 tokenizers.
public protocol FTS5CustomTokenizer : FTS5Tokenizer {
public protocol FTS5CustomTokenizer: FTS5Tokenizer {
/// The name of the tokenizer; should uniquely identify your custom
/// tokenizer.
static var name: String { get }
@@ -41,7 +41,6 @@ extension FTS5CustomTokenizer {
public static func tokenizerDescriptor(arguments: [String] = []) -> FTS5TokenizerDescriptor {
return FTS5TokenizerDescriptor(components: [name] + arguments)
}
}
extension Database {
@@ -52,7 +51,10 @@ extension Database {
let db: Database
let constructor: (Database, [String], UnsafeMutablePointer<OpaquePointer?>?) -> Int32
init(db: Database, constructor: @escaping (Database, [String], UnsafeMutablePointer<OpaquePointer?>?) -> Int32) {
init(
db: Database,
constructor: @escaping (Database, [String], UnsafeMutablePointer<OpaquePointer?>?) -> Int32)
{
self.db = db
self.constructor = constructor
}
@@ -101,7 +103,13 @@ extension Database {
Unmanaged<AnyObject>.fromOpaque(constructorPointer).release()
}
func xCreateTokenizer(constructorPointer: UnsafeMutableRawPointer?, azArg: UnsafeMutablePointer<UnsafePointer<Int8>?>?, nArg: Int32, tokenizerHandle: UnsafeMutablePointer<OpaquePointer?>?) -> Int32 {
func xCreateTokenizer(
constructorPointer: UnsafeMutableRawPointer?,
azArg: UnsafeMutablePointer<UnsafePointer<Int8>?>?,
nArg: Int32,
tokenizerHandle: UnsafeMutablePointer<OpaquePointer?>?)
-> Int32
{
guard let constructorPointer = constructorPointer else {
return SQLITE_ERROR
}
@@ -122,20 +130,41 @@ extension Database {
Unmanaged<AnyObject>.fromOpaque(UnsafeMutableRawPointer(tokenizerPointer)).release()
}
func xTokenize(tokenizerPointer: OpaquePointer?, context: UnsafeMutableRawPointer?, flags: Int32, pText: UnsafePointer<Int8>?, nText: Int32, tokenCallback: (@convention(c) (UnsafeMutableRawPointer?, Int32, UnsafePointer<Int8>?, Int32, Int32, Int32) -> Int32)?) -> Int32 {
func xTokenize(
tokenizerPointer: OpaquePointer?,
context: UnsafeMutableRawPointer?,
flags: Int32,
pText: UnsafePointer<Int8>?,
nText: Int32,
// swiftlint:disable:next line_length
tokenCallback: (@convention(c) (UnsafeMutableRawPointer?, Int32, UnsafePointer<Int8>?, Int32, Int32, Int32) -> Int32)?)
-> Int32
{
guard let tokenizerPointer = tokenizerPointer else {
return SQLITE_ERROR
}
let object = Unmanaged<AnyObject>.fromOpaque(UnsafeMutableRawPointer(tokenizerPointer)).takeUnretainedValue()
let object = Unmanaged<AnyObject>
.fromOpaque(UnsafeMutableRawPointer(tokenizerPointer))
.takeUnretainedValue()
guard let tokenizer = object as? FTS5Tokenizer else {
return SQLITE_ERROR
}
return tokenizer.tokenize(context: context, tokenization: FTS5Tokenization(rawValue: flags), pText: pText, nText: nText, tokenCallback: tokenCallback!)
return tokenizer.tokenize(
context: context,
tokenization: FTS5Tokenization(rawValue: flags),
pText: pText,
nText: nText,
tokenCallback: tokenCallback!)
}
var xTokenizer = fts5_tokenizer(xCreate: xCreateTokenizer, xDelete: xDeleteTokenizer, xTokenize: xTokenize)
let code = withUnsafeMutablePointer(to: &xTokenizer) { xTokenizerPointer in
api.pointee.xCreateTokenizer(UnsafeMutablePointer(mutating: api), Tokenizer.name, constructorPointer, xTokenizerPointer, deleteConstructor)
api.pointee.xCreateTokenizer(
UnsafeMutablePointer(mutating: api),
Tokenizer.name,
constructorPointer,
xTokenizerPointer,
deleteConstructor)
}
guard code == SQLITE_OK else {
// Assume a GRDB bug: there is no point throwing any error.
+34 -6
View File
@@ -13,7 +13,14 @@ public struct FTS5Pattern {
///
/// - parameter string: The string to turn into an FTS5 pattern
public init?(matchingAnyTokenIn string: String) {
guard let tokens = try? DatabaseQueue().inDatabase({ db in try db.makeTokenizer(.ascii()).nonSynonymTokens(in: string, for: .query) }) else { return nil }
guard
let tokens = try? DatabaseQueue().inDatabase({ db in
try db
.makeTokenizer(.ascii())
.nonSynonymTokens(in: string, for: .query) })
else {
return nil
}
guard !tokens.isEmpty else { return nil }
try? self.init(rawPattern: tokens.joined(separator: " OR "))
}
@@ -26,7 +33,14 @@ public struct FTS5Pattern {
///
/// - parameter string: The string to turn into an FTS5 pattern
public init?(matchingAllTokensIn string: String) {
guard let tokens = try? DatabaseQueue().inDatabase({ db in try db.makeTokenizer(.ascii()).nonSynonymTokens(in: string, for: .query) }) else { return nil }
guard
let tokens = try? DatabaseQueue().inDatabase({ db in
try db
.makeTokenizer(.ascii())
.nonSynonymTokens(in: string, for: .query) })
else {
return nil
}
guard !tokens.isEmpty else { return nil }
try? self.init(rawPattern: tokens.joined(separator: " "))
}
@@ -39,7 +53,14 @@ public struct FTS5Pattern {
///
/// - parameter string: The string to turn into an FTS5 pattern
public init?(matchingPhrase string: String) {
guard let tokens = try? DatabaseQueue().inDatabase({ db in try db.makeTokenizer(.ascii()).nonSynonymTokens(in: string, for: .query) }) else { return nil }
guard
let tokens = try? DatabaseQueue().inDatabase({ db in
try db
.makeTokenizer(.ascii())
.nonSynonymTokens(in: string, for: .query) })
else {
return nil
}
guard !tokens.isEmpty else { return nil }
try? self.init(rawPattern: "\"" + tokens.joined(separator: " ") + "\"")
}
@@ -52,7 +73,14 @@ public struct FTS5Pattern {
///
/// - parameter string: The string to turn into an FTS5 pattern
public init?(matchingPrefixPhrase string: String) {
guard let tokens = try? DatabaseQueue().inDatabase({ db in try db.makeTokenizer(.ascii()).nonSynonymTokens(in: string, for: .query) }) else { return nil }
guard
let tokens = try? DatabaseQueue().inDatabase({ db in
try db
.makeTokenizer(.ascii())
.nonSynonymTokens(in: string, for: .query) })
else {
return nil
}
guard !tokens.isEmpty else { return nil }
try? self.init(rawPattern: "^\"" + tokens.joined(separator: " ") + "\"")
}
@@ -80,7 +108,7 @@ public struct FTS5Pattern {
}
} catch let error as DatabaseError {
// Remove private SQL & arguments from the thrown error
throw DatabaseError(resultCode: error.extendedResultCode, message: error.message, sql: nil, arguments: nil)
throw DatabaseError(resultCode: error.extendedResultCode, message: error.message)
}
// Pattern is valid
@@ -104,7 +132,7 @@ extension Database {
}
}
extension FTS5Pattern : DatabaseValueConvertible {
extension FTS5Pattern: DatabaseValueConvertible {
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return rawPattern.databaseValue
+72 -25
View File
@@ -1,21 +1,28 @@
#if SQLITE_ENABLE_FTS5
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
/// A low-level SQLite function that lets FTS5Tokenizer notify tokens.
///
/// See FTS5Tokenizer.tokenize(context:flags:pText:nText:tokenCallback:)
public typealias FTS5TokenCallback = @convention(c) (_ context: UnsafeMutableRawPointer?, _ flags: Int32, _ pToken: UnsafePointer<Int8>?, _ nToken: Int32, _ iStart: Int32, _ iEnd: Int32) -> Int32
public typealias FTS5TokenCallback = @convention(c) (
_ context: UnsafeMutableRawPointer?,
_ flags: Int32,
_ pToken: UnsafePointer<Int8>?,
_ nToken: Int32,
_ iStart: Int32,
_ iEnd: Int32)
-> Int32
/// The reason why FTS5 is requesting tokenization.
///
/// See https://www.sqlite.org/fts5.html#custom_tokenizers
public struct FTS5Tokenization : OptionSet {
public struct FTS5Tokenization: OptionSet {
public let rawValue: Int32
public init(rawValue: Int32) {
@@ -36,7 +43,7 @@ public struct FTS5Tokenization : OptionSet {
}
/// The protocol for FTS5 tokenizers
public protocol FTS5Tokenizer : class {
public protocol FTS5Tokenizer: AnyObject {
/// Tokenizes the text described by `pText` and `nText`, and
/// notifies found tokens to the `tokenCallback` function.
///
@@ -51,7 +58,13 @@ public protocol FTS5Tokenizer : class {
/// - nText: The number of bytes in the tokenized text.
/// - tokenCallback: The function to call for each found token.
/// It matches the `xToken` callback at https://www.sqlite.org/fts5.html#custom_tokenizers
func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer<Int8>?, nText: Int32, tokenCallback: @escaping FTS5TokenCallback) -> Int32
func tokenize(
context: UnsafeMutableRawPointer?,
tokenization: FTS5Tokenization,
pText: UnsafePointer<Int8>?,
nText: Int32,
tokenCallback: @escaping FTS5TokenCallback)
-> Int32
}
private class TokenizeContext {
@@ -81,20 +94,34 @@ extension FTS5Tokenizer {
var context = TokenizeContext()
try withUnsafeMutablePointer(to: &context) { contextPointer in
let code = tokenize(context: UnsafeMutableRawPointer(contextPointer), tokenization: tokenization, pText: pText, nText: nText, tokenCallback: { (contextPointer, flags, pToken, nToken, iStart, iEnd) -> Int32 in
guard let contextPointer = contextPointer else { return SQLITE_ERROR }
// Extract token
guard let token = pToken.flatMap({ String(data: Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: $0), count: Int(nToken), deallocator: .none), encoding: .utf8) }) else {
let code = tokenize(
context: UnsafeMutableRawPointer(contextPointer),
tokenization: tokenization,
pText: pText,
nText: nText,
tokenCallback: { (contextPointer, flags, pToken, nToken, _ /* iStart */, _ /* iEnd */) -> Int32 in
guard let contextPointer = contextPointer else {
return SQLITE_ERROR
}
// Extract token
guard
let token = pToken.flatMap({
String(
data: Data(
bytesNoCopy: UnsafeMutableRawPointer(mutating: $0),
count: Int(nToken),
deallocator: .none),
encoding: .utf8) })
else {
return SQLITE_OK
}
let context = contextPointer.assumingMemoryBound(to: TokenizeContext.self).pointee
context.tokens.append((token, FTS5TokenFlags(rawValue: flags)))
return SQLITE_OK
}
let context = contextPointer.assumingMemoryBound(to: TokenizeContext.self).pointee
context.tokens.append((token, FTS5TokenFlags(rawValue: flags)))
return SQLITE_OK
})
if (code != SQLITE_OK) {
if code != SQLITE_OK {
throw DatabaseError(resultCode: code)
}
}
@@ -119,13 +146,13 @@ extension Database {
/// Private type that makes a pre-registered FTS5 tokenizer available
/// through the FTS5Tokenizer protocol.
private final class FTS5RegisteredTokenizer : FTS5Tokenizer {
private final class FTS5RegisteredTokenizer: FTS5Tokenizer {
let xTokenizer: fts5_tokenizer
let tokenizerPointer: OpaquePointer
init(xTokenizer: fts5_tokenizer, contextPointer: UnsafeMutableRawPointer?, arguments: [String]) throws {
guard let xCreate = xTokenizer.xCreate else {
throw DatabaseError(resultCode: .SQLITE_ERROR, message: "nil fts5_tokenizer.xCreate")
throw DatabaseError(message: "nil fts5_tokenizer.xCreate")
}
self.xTokenizer = xTokenizer
@@ -135,7 +162,13 @@ extension Database {
if let argument = arguments.first {
// Turn [String] into ContiguousArray<UnsafePointer<Int8>>
// (for an alternative implementation see https://oleb.net/blog/2016/10/swift-array-of-c-strings/)
func convertArguments<Result>(_ array: inout ContiguousArray<UnsafePointer<Int8>>, _ car: String, _ cdr: [String], _ body: (ContiguousArray<UnsafePointer<Int8>>) -> Result) -> Result {
func convertArguments<Result>(
_ array: inout ContiguousArray<UnsafePointer<Int8>>,
_ car: String,
_ cdr: [String],
_ body: (ContiguousArray<UnsafePointer<Int8>>) -> Result)
-> Result
{
return car.withCString { cString in
if let car = cdr.first {
array.append(cString)
@@ -148,7 +181,11 @@ extension Database {
var cStrings = ContiguousArray<UnsafePointer<Int8>>()
code = convertArguments(&cStrings, argument, Array(arguments.suffix(from: 1))) { cStrings in
cStrings.withUnsafeBufferPointer { azArg in
xCreate(contextPointer, UnsafeMutablePointer(OpaquePointer(azArg.baseAddress!)), Int32(cStrings.count), &tokenizerPointer)
xCreate(
contextPointer,
UnsafeMutablePointer(OpaquePointer(azArg.baseAddress!)),
Int32(cStrings.count),
&tokenizerPointer)
}
}
} else {
@@ -172,7 +209,14 @@ extension Database {
}
}
func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer<Int8>?, nText: Int32, tokenCallback: @escaping FTS5TokenCallback) -> Int32 {
func tokenize(
context: UnsafeMutableRawPointer?,
tokenization: FTS5Tokenization,
pText: UnsafePointer<Int8>?,
nText: Int32,
tokenCallback: @escaping FTS5TokenCallback)
-> Int32
{
guard let xTokenize = xTokenizer.xTokenize else {
return SQLITE_ERROR
}
@@ -216,7 +260,10 @@ extension Database {
}
let contextPointer = contextHandle.pointee
return try FTS5RegisteredTokenizer(xTokenizer: xTokenizerPointer.pointee, contextPointer: contextPointer, arguments: descriptor.arguments)
return try FTS5RegisteredTokenizer(
xTokenizer: xTokenizerPointer.pointee,
contextPointer: contextPointer,
arguments: descriptor.arguments)
}
}
#endif
+29 -9
View File
@@ -57,11 +57,20 @@ public struct FTS5TokenizerDescriptor {
///
/// See https://www.sqlite.org/fts5.html#ascii_tokenizer
public static func ascii(separators: Set<Character> = []) -> FTS5TokenizerDescriptor {
let components: [String]
if separators.isEmpty {
return FTS5TokenizerDescriptor(components: ["ascii"])
components = ["ascii"]
} else {
return FTS5TokenizerDescriptor(components: ["ascii", "separators", separators.map { String($0) }.joined(separator: "").sqlExpression.quotedSQL(wrappedInParenthesis: false)])
components = [
"ascii",
"separators",
separators
.map { String($0) }
.joined()
.sqlExpression
.quotedSQL()]
}
return FTS5TokenizerDescriptor(components: components)
}
/// The "porter" tokenizer
@@ -98,7 +107,12 @@ public struct FTS5TokenizerDescriptor {
/// consider these characters as token characters.
///
/// See https://www.sqlite.org/fts5.html#unicode61_tokenizer
public static func unicode61(diacritics: FTS5.Diacritics = .removeLegacy, separators: Set<Character> = [], tokenCharacters: Set<Character> = []) -> FTS5TokenizerDescriptor {
public static func unicode61(
diacritics: FTS5.Diacritics = .removeLegacy,
separators: Set<Character> = [],
tokenCharacters: Set<Character> = [])
-> FTS5TokenizerDescriptor
{
var components: [String] = ["unicode61"]
switch diacritics {
case .removeLegacy:
@@ -111,26 +125,32 @@ public struct FTS5TokenizerDescriptor {
#endif
}
if !separators.isEmpty {
// TODO: test "=" and "\"", "(" and ")" as separators, with both FTS3Pattern(matchingAnyTokenIn:tokenizer:) and Database.create(virtualTable:using:)
// TODO: test "=" and "\"", "(" and ")" as separators, with
// both FTS3Pattern(matchingAnyTokenIn:tokenizer:)
// and Database.create(virtualTable:using:)
components.append(contentsOf: [
"separators",
separators
.sorted()
.map { String($0) }
.joined(separator: "")
.joined()
.sqlExpression
.quotedSQL(wrappedInParenthesis: false)])
.quotedSQL()
])
}
if !tokenCharacters.isEmpty {
// TODO: test "=" and "\"", "(" and ")" as tokenCharacters, with both FTS3Pattern(matchingAnyTokenIn:tokenizer:) and Database.create(virtualTable:using:)
// TODO: test "=" and "\"", "(" and ")" as tokenCharacters, with
// both FTS3Pattern(matchingAnyTokenIn:tokenizer:)
// and Database.create(virtualTable:using:)
components.append(contentsOf: [
"tokenchars",
tokenCharacters
.sorted()
.map { String($0) }
.joined(separator: "")
.joined()
.sqlExpression
.quotedSQL(wrappedInParenthesis: false)])
.quotedSQL()
])
}
return FTS5TokenizerDescriptor(components: components)
}
+89 -52
View File
@@ -1,16 +1,16 @@
#if SQLITE_ENABLE_FTS5
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
/// Flags that tell SQLite how to register a token.
///
/// See https://www.sqlite.org/fts5.html#custom_tokenizers
public struct FTS5TokenFlags : OptionSet {
public struct FTS5TokenFlags: OptionSet {
public let rawValue: Int32
public init(rawValue: Int32) {
@@ -24,7 +24,7 @@ public struct FTS5TokenFlags : OptionSet {
/// A function that lets FTS5WrapperTokenizer notify tokens.
///
/// See FTS5WrapperTokenizer.accept(token:flags:tokenCallback:)
public typealias FTS5WrapperTokenCallback = (_ token: String, _ flags: FTS5TokenFlags) throws -> ()
public typealias FTS5WrapperTokenCallback = (_ token: String, _ flags: FTS5TokenFlags) throws -> Void
/// The protocol for custom FTS5 tokenizers that wrap another tokenizer.
///
@@ -44,11 +44,17 @@ public typealias FTS5WrapperTokenCallback = (_ token: String, _ flags: FTS5Token
/// wrappedTokenizer = try db.makeTokenizer(.ascii())
/// }
///
/// func accept(token: String, flags: FTS5TokenFlags, for tokenization: FTS5Tokenization, tokenCallback: FTS5WrapperTokenCallback) throws {
/// func accept(
/// token: String,
/// flags: FTS5TokenFlags,
/// for tokenization: FTS5Tokenization,
/// tokenCallback: FTS5WrapperTokenCallback)
/// throws
/// {
/// try tokenCallback(token, flags)
/// }
/// }
public protocol FTS5WrapperTokenizer : FTS5CustomTokenizer {
public protocol FTS5WrapperTokenizer: FTS5CustomTokenizer {
/// The wrapped tokenizer
var wrappedTokenizer: FTS5Tokenizer { get }
@@ -57,7 +63,13 @@ public protocol FTS5WrapperTokenizer : FTS5CustomTokenizer {
///
/// For example:
///
/// func accept(token: String, flags: FTS5TokenFlags, for tokenization: FTS5Tokenization, tokenCallback: FTS5WrapperTokenCallback) throws {
/// func accept(
/// token: String,
/// flags: FTS5TokenFlags,
/// for tokenization: FTS5Tokenization,
/// tokenCallback: FTS5WrapperTokenCallback)
/// throws
/// {
/// // pass through:
/// try tokenCallback(token, flags)
/// }
@@ -77,7 +89,12 @@ public protocol FTS5WrapperTokenizer : FTS5CustomTokenizer {
/// - flags: Flags that tell SQLite how to register a token.
/// - tokenization: The reason why FTS5 is requesting tokenization.
/// - tokenCallback: The function to call for each customized token.
func accept(token: String, flags: FTS5TokenFlags, for tokenization: FTS5Tokenization, tokenCallback: FTS5WrapperTokenCallback) throws
func accept(
token: String,
flags: FTS5TokenFlags,
for tokenization: FTS5Tokenization,
tokenCallback: FTS5WrapperTokenCallback)
throws
}
private struct FTS5WrapperContext {
@@ -89,7 +106,14 @@ private struct FTS5WrapperContext {
extension FTS5WrapperTokenizer {
/// Default implementation
public func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer<Int8>?, nText: Int32, tokenCallback: @escaping FTS5TokenCallback) -> Int32 {
public func tokenize(
context: UnsafeMutableRawPointer?,
tokenization: FTS5Tokenization,
pText: UnsafePointer<Int8>?,
nText: Int32,
tokenCallback: @escaping FTS5TokenCallback)
-> Int32
{
// `tokenCallback` is @convention(c). This requires a little setup
// in order to transfer context.
var customContext = FTS5WrapperContext(
@@ -99,49 +123,62 @@ extension FTS5WrapperTokenizer {
tokenCallback: tokenCallback)
return withUnsafeMutablePointer(to: &customContext) { customContextPointer in
// Invoke wrappedTokenizer
return wrappedTokenizer.tokenize(context: customContextPointer, tokenization: tokenization, pText: pText, nText: nText) { (customContextPointer, tokenFlags, pToken, nToken, iStart, iEnd) in
// Extract token produced by wrapped tokenizer
guard let token = pToken.flatMap({ String(data: Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: $0), count: Int(nToken), deallocator: .none), encoding: .utf8) }) else {
return 0 // SQLITE_OK
}
// Extract context
let customContext = customContextPointer!.assumingMemoryBound(to: FTS5WrapperContext.self).pointee
let tokenizer = customContext.tokenizer
let context = customContext.context
let tokenization = customContext.tokenization
let tokenCallback = customContext.tokenCallback
// Process token produced by wrapped tokenizer
do {
try tokenizer.accept(
token: token,
flags: FTS5TokenFlags(rawValue: tokenFlags),
for: tokenization,
tokenCallback: { (token, flags) in
// Turn token into bytes
return try ContiguousArray(token.utf8).withUnsafeBufferPointer { buffer in
guard let addr = buffer.baseAddress else {
return
}
let pToken = UnsafeMutableRawPointer(mutating: addr).assumingMemoryBound(to: Int8.self)
let nToken = Int32(buffer.count)
// Inject token bytes into SQLite
let code = tokenCallback(context, flags.rawValue, pToken, nToken, iStart, iEnd)
guard code == SQLITE_OK else {
throw DatabaseError(resultCode: code, message: "token callback failed")
}
}
})
return wrappedTokenizer.tokenize(
context: customContextPointer,
tokenization: tokenization,
pText: pText,
nText: nText) { (customContextPointer, tokenFlags, pToken, nToken, iStart, iEnd) in
return SQLITE_OK
} catch let error as DatabaseError {
return error.extendedResultCode.rawValue
} catch {
return SQLITE_ERROR
}
// Extract token produced by wrapped tokenizer
guard
let token = pToken.flatMap({
String(
data: Data(
bytesNoCopy: UnsafeMutableRawPointer(mutating: $0),
count: Int(nToken),
deallocator: .none),
encoding: .utf8) })
else {
return SQLITE_OK // 0 // SQLITE_OK
}
// Extract context
let customContext = customContextPointer!.assumingMemoryBound(to: FTS5WrapperContext.self).pointee
let tokenizer = customContext.tokenizer
let context = customContext.context
let tokenization = customContext.tokenization
let tokenCallback = customContext.tokenCallback
// Process token produced by wrapped tokenizer
do {
try tokenizer.accept(
token: token,
flags: FTS5TokenFlags(rawValue: tokenFlags),
for: tokenization,
tokenCallback: { (token, flags) in
// Turn token into bytes
return try ContiguousArray(token.utf8).withUnsafeBufferPointer { buffer in
guard let addr = buffer.baseAddress else {
return
}
let pToken = UnsafeMutableRawPointer(mutating: addr)
.assumingMemoryBound(to: Int8.self)
let nToken = Int32(buffer.count)
// Inject token bytes into SQLite
let code = tokenCallback(context, flags.rawValue, pToken, nToken, iStart, iEnd)
guard code == SQLITE_OK else {
throw DatabaseError(resultCode: code, message: "token callback failed")
}
}
})
return SQLITE_OK
} catch let error as DatabaseError {
return error.extendedResultCode.rawValue
} catch {
return SQLITE_ERROR
}
}
}
}
+138 -24
View File
@@ -4,7 +4,10 @@ import Dispatch
extension Cursor {
@available(*, unavailable, renamed: "compactMap")
public func flatMap<ElementOfResult>(_ transform: @escaping (Element) throws -> ElementOfResult?) -> MapCursor<FilterCursor<MapCursor<Self, ElementOfResult?>>, ElementOfResult> { preconditionFailure() }
public func flatMap<ElementOfResult>(
_ transform: @escaping (Element) throws -> ElementOfResult?)
-> MapCursor<FilterCursor<MapCursor<Self, ElementOfResult?>>, ElementOfResult>
{ preconditionFailure() }
}
extension DatabaseWriter {
@@ -14,17 +17,26 @@ extension DatabaseWriter {
extension ValueObservation {
@available(*, unavailable, message: "Provide the reducer in a (Database) -> Reducer closure")
public static func tracking(_ regions: DatabaseRegionConvertible..., reducer: Reducer) -> ValueObservation { preconditionFailure() }
public static func tracking(_ regions: DatabaseRegionConvertible..., reducer: Reducer)
-> ValueObservation
{ preconditionFailure() }
@available(*, unavailable, message: "Use removeDuplicates() instead")
public static func tracking<Value>(_ regions: DatabaseRegionConvertible..., fetchDistinct fetch: @escaping (Database) throws -> Value) -> ValueObservation<ValueReducers.RemoveDuplicates<ValueReducers.Fetch<Value>>> where Value: Equatable { preconditionFailure() }
public static func tracking<Value>(
_ regions: DatabaseRegionConvertible...,
fetchDistinct fetch: @escaping (Database) throws -> Value)
-> ValueObservation<ValueReducers.RemoveDuplicates<ValueReducers.Fetch<Value>>>
where Value: Equatable
{ preconditionFailure() }
}
@available(*, unavailable, renamed: "FastDatabaseValueCursor")
public typealias ColumnCursor<Value: DatabaseValueConvertible & StatementColumnConvertible> = FastDatabaseValueCursor<Value>
public typealias ColumnCursor<Value> = FastDatabaseValueCursor<Value>
where Value: DatabaseValueConvertible & StatementColumnConvertible
@available(*, unavailable, renamed: "FastNullableDatabaseValueCursor")
public typealias NullableColumnCursor<Value: DatabaseValueConvertible & StatementColumnConvertible> = FastNullableDatabaseValueCursor<Value>
public typealias NullableColumnCursor<Value> = FastNullableDatabaseValueCursor<Value>
where Value: DatabaseValueConvertible & StatementColumnConvertible
extension Database {
@available(*, unavailable, renamed: "execute(sql:arguments:)")
@@ -45,58 +57,141 @@ extension Database {
extension DatabaseValueConvertible {
@available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)")
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseValueCursor<Self> { preconditionFailure() }
public static func fetchCursor(
_ db: Database,
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> DatabaseValueCursor<Self>
{ preconditionFailure() }
@available(*, unavailable, renamed: "fetchAll(_:sql:arguments:adapter:)")
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] { preconditionFailure() }
public static func fetchAll(
_ db: Database,
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> [Self]
{ preconditionFailure() }
@available(*, unavailable, renamed: "fetchOne(_:sql:arguments:adapter:)")
public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? { preconditionFailure() }
public static func fetchOne(
_ db: Database,
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> Self?
{ preconditionFailure() }
}
extension Optional where Wrapped: DatabaseValueConvertible {
@available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)")
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor<Wrapped> { preconditionFailure() }
public static func fetchCursor(
_ db: Database,
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> NullableDatabaseValueCursor<Wrapped>
{ preconditionFailure() }
@available(*, unavailable, renamed: "fetchAll(_:sql:arguments:adapter:)")
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] { preconditionFailure() }
public static func fetchAll(
_ db: Database,
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> [Wrapped?]
{ preconditionFailure() }
}
extension Row {
@available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)")
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RowCursor { preconditionFailure() }
public static func fetchCursor(
_ db: Database,
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> RowCursor
{ preconditionFailure() }
@available(*, unavailable, renamed: "fetchAll(_:sql:arguments:adapter:)")
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Row] { preconditionFailure() }
public static func fetchAll(
_ db: Database,
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> [Row]
{ preconditionFailure() }
@available(*, unavailable, renamed: "fetchOne(_:sql:arguments:adapter:)")
public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Row? { preconditionFailure() }
public static func fetchOne(
_ db: Database,
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> Row?
{ preconditionFailure() }
}
extension DatabaseValueConvertible where Self: StatementColumnConvertible {
@available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)")
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> FastDatabaseValueCursor<Self> { preconditionFailure() }
public static func fetchCursor(
_ db: Database,
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> FastDatabaseValueCursor<Self>
{ preconditionFailure() }
}
extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConvertible {
@available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)")
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> FastNullableDatabaseValueCursor<Wrapped> { preconditionFailure() }
public static func fetchCursor(
_ db: Database,
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> FastNullableDatabaseValueCursor<Wrapped>
{ preconditionFailure() }
}
extension FetchableRecord {
@available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)")
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RecordCursor<Self> { preconditionFailure() }
public static func fetchCursor(
_ db: Database,
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> RecordCursor<Self>
{ preconditionFailure() }
@available(*, unavailable, renamed: "fetchAll(_:sql:arguments:adapter:)")
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] { preconditionFailure() }
public static func fetchAll(
_ db: Database,
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> [Self]
{ preconditionFailure() }
@available(*, unavailable, renamed: "fetchOne(_:sql:arguments:adapter:)")
public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? { preconditionFailure() }
public static func fetchOne(
_ db: Database,
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> Self?
{ preconditionFailure() }
}
extension SQLRequest {
@available(*, unavailable, renamed: "init(sql:arguments:adapter:cached:)")
public init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, cached: Bool = false) { preconditionFailure() }
public init(
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil,
cached: Bool = false)
{ preconditionFailure() }
}
extension SQLExpressionLiteral {
@@ -111,30 +206,49 @@ extension SQLExpression {
extension FTS3TokenizerDescriptor {
@available(*, unavailable, renamed: "unicode61(diacritics:separators:tokenCharacters:)")
public static func unicode61(removeDiacritics: Bool, separators: Set<Character> = [], tokenCharacters: Set<Character> = []) -> FTS3TokenizerDescriptor { preconditionFailure() }
public static func unicode61(
removeDiacritics: Bool,
separators: Set<Character> = [],
tokenCharacters: Set<Character> = [])
-> FTS3TokenizerDescriptor
{ preconditionFailure() }
}
#if SQLITE_ENABLE_FTS5
extension FTS5TokenizerDescriptor {
@available(*, unavailable, renamed: "unicode61(diacritics:separators:tokenCharacters:)")
public static func unicode61(removeDiacritics: Bool = true, separators: Set<Character> = [], tokenCharacters: Set<Character> = []) -> FTS5TokenizerDescriptor { preconditionFailure() }
public static func unicode61(
removeDiacritics: Bool = true,
separators: Set<Character> = [],
tokenCharacters: Set<Character> = [])
-> FTS5TokenizerDescriptor
{ preconditionFailure() }
}
#endif
extension DatabaseValue {
@available(*, unavailable)
public func losslessConvert<T>(sql: String? = nil, arguments: StatementArguments? = nil) -> T where T: DatabaseValueConvertible { preconditionFailure() }
public func losslessConvert<T>(sql: String? = nil, arguments: StatementArguments? = nil)
-> T
where T: DatabaseValueConvertible
{ preconditionFailure() }
@available(*, unavailable)
public func losslessConvert<T>(sql: String? = nil, arguments: StatementArguments? = nil) -> T? where T: DatabaseValueConvertible { preconditionFailure() }
public func losslessConvert<T>(sql: String? = nil, arguments: StatementArguments? = nil)
-> T?
where T: DatabaseValueConvertible
{ preconditionFailure() }
}
extension ValueScheduling {
@available(*, unavailable, renamed: "async(onQueue:startImmediately:)")
public static func onQueue(_ queue: DispatchQueue, startImmediately: Bool) -> ValueScheduling { preconditionFailure() }
public static func onQueue(_ queue: DispatchQueue, startImmediately: Bool)
-> ValueScheduling
{ preconditionFailure() }
}
extension ValueObservation {
// swiftlint:disable:next line_length
@available(*, unavailable, message: "Observation extent is controlled by the lifetime of observers returned by the start() method.")
public var extent: Database.TransactionObservationExtent {
get { preconditionFailure() }
+67 -55
View File
@@ -68,7 +68,7 @@ public struct DatabaseMigrator {
/// for some downloaded data.
public var eraseDatabaseOnSchemaChange = false
private var migrations: [Migration] = []
/// A new migrator.
public init() {
}
@@ -92,58 +92,64 @@ public struct DatabaseMigrator {
}
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// Registers an advanced migration, as described at https://www.sqlite.org/lang_altertable.html#otheralter
///
/// // Add a NOT NULL constraint on players.name:
/// migrator.registerMigrationWithDeferredForeignKeyCheck("AddNotNullCheckOnName") { db in
/// try db.create(table: "new_player") { t in
/// t.autoIncrementedPrimaryKey("id")
/// t.column("name", .text).notNull()
/// }
/// try db.execute(sql: "INSERT INTO new_player SELECT * FROM player")
/// try db.drop(table: "player")
/// try db.rename(table: "new_player", to: "player")
/// }
///
/// While your migration code runs with disabled foreign key checks, those
/// are re-enabled and checked at the end of the migration, regardless of
/// eventual errors.
///
/// - parameters:
/// - identifier: The migration identifier.
/// - block: The migration block that performs SQL statements.
/// - precondition: No migration with the same same as already been registered.
///
/// :nodoc:
public mutating func registerMigrationWithDeferredForeignKeyCheck(_ identifier: String, migrate: @escaping (Database) throws -> Void) {
registerMigration(Migration(identifier: identifier, disabledForeignKeyChecks: true, migrate: migrate))
}
/// Registers an advanced migration, as described at https://www.sqlite.org/lang_altertable.html#otheralter
///
/// // Add a NOT NULL constraint on players.name:
/// migrator.registerMigrationWithDeferredForeignKeyCheck("AddNotNullCheckOnName") { db in
/// try db.create(table: "new_player") { t in
/// t.autoIncrementedPrimaryKey("id")
/// t.column("name", .text).notNull()
/// }
/// try db.execute(sql: "INSERT INTO new_player SELECT * FROM player")
/// try db.drop(table: "player")
/// try db.rename(table: "new_player", to: "player")
/// }
///
/// While your migration code runs with disabled foreign key checks, those
/// are re-enabled and checked at the end of the migration, regardless of
/// eventual errors.
///
/// - parameters:
/// - identifier: The migration identifier.
/// - block: The migration block that performs SQL statements.
/// - precondition: No migration with the same same as already been registered.
///
/// :nodoc:
public mutating func registerMigrationWithDeferredForeignKeyCheck(
_ identifier: String,
migrate: @escaping (Database) throws -> Void)
{
registerMigration(Migration(identifier: identifier, disabledForeignKeyChecks: true, migrate: migrate))
}
#else
@available(OSX 10.10, *)
/// Registers an advanced migration, as described at https://www.sqlite.org/lang_altertable.html#otheralter
///
/// // Add a NOT NULL constraint on players.name:
/// migrator.registerMigrationWithDeferredForeignKeyCheck("AddNotNullCheckOnName") { db in
/// try db.create(table: "new_player") { t in
/// t.autoIncrementedPrimaryKey("id")
/// t.column("name", .text).notNull()
/// }
/// try db.execute(sql: "INSERT INTO new_player SELECT * FROM player")
/// try db.drop(table: "player")
/// try db.rename(table: "new_player", to: "player")
/// }
///
/// While your migration code runs with disabled foreign key checks, those
/// are re-enabled and checked at the end of the migration, regardless of
/// eventual errors.
///
/// - parameters:
/// - identifier: The migration identifier.
/// - block: The migration block that performs SQL statements.
/// - precondition: No migration with the same same as already been registered.
public mutating func registerMigrationWithDeferredForeignKeyCheck(_ identifier: String, migrate: @escaping (Database) throws -> Void) {
registerMigration(Migration(identifier: identifier, disabledForeignKeyChecks: true, migrate: migrate))
}
@available(OSX 10.10, *)
/// Registers an advanced migration, as described at https://www.sqlite.org/lang_altertable.html#otheralter
///
/// // Add a NOT NULL constraint on players.name:
/// migrator.registerMigrationWithDeferredForeignKeyCheck("AddNotNullCheckOnName") { db in
/// try db.create(table: "new_player") { t in
/// t.autoIncrementedPrimaryKey("id")
/// t.column("name", .text).notNull()
/// }
/// try db.execute(sql: "INSERT INTO new_player SELECT * FROM player")
/// try db.drop(table: "player")
/// try db.rename(table: "new_player", to: "player")
/// }
///
/// While your migration code runs with disabled foreign key checks, those
/// are re-enabled and checked at the end of the migration, regardless of
/// eventual errors.
///
/// - parameters:
/// - identifier: The migration identifier.
/// - block: The migration block that performs SQL statements.
/// - precondition: No migration with the same same as already been registered.
public mutating func registerMigrationWithDeferredForeignKeyCheck(
_ identifier: String,
migrate: @escaping (Database) throws -> Void)
{
registerMigration(Migration(identifier: identifier, disabledForeignKeyChecks: true, migrate: migrate))
}
#endif
/// Iterate migrations in the same order as they were registered. If a
@@ -232,7 +238,9 @@ public struct DatabaseMigrator {
// MARK: - Non public
private mutating func registerMigration(_ migration: Migration) {
GRDBPrecondition(!migrations.map({ $0.identifier }).contains(migration.identifier), "already registered migration: \(String(reflecting: migration.identifier))")
GRDBPrecondition(
!migrations.map({ $0.identifier }).contains(migration.identifier),
"already registered migration: \(String(reflecting: migration.identifier))")
migrations.append(migration)
}
@@ -254,13 +262,17 @@ public struct DatabaseMigrator {
}
// targetIdentifier must refer to a registered migration
GRDBPrecondition(prefixMigrations.last?.identifier == targetIdentifier, "undefined migration: \(String(reflecting: targetIdentifier))")
GRDBPrecondition(
prefixMigrations.last?.identifier == targetIdentifier,
"undefined migration: \(String(reflecting: targetIdentifier))")
// Subsequent migration must not be applied
let appliedIdentifiers = try self.appliedIdentifiers(db)
if prefixMigrations.count < migrations.count {
let nextIdentifier = migrations[prefixMigrations.count].identifier
GRDBPrecondition(!appliedIdentifiers.contains(nextIdentifier), "database is already migrated beyond migration \(String(reflecting: targetIdentifier))")
GRDBPrecondition(
!appliedIdentifiers.contains(nextIdentifier),
"database is already migrated beyond migration \(String(reflecting: targetIdentifier))")
}
for migration in prefixMigrations where !appliedIdentifiers.contains(migration.identifier) {
+19 -18
View File
@@ -5,26 +5,27 @@ struct Migration {
let migrate: (Database) throws -> Void
#if GRDBCUSTOMSQLITE || GRDBCIPHER
init(identifier: String, disabledForeignKeyChecks: Bool = false, migrate: @escaping (Database) throws -> Void) {
self.identifier = identifier
self.disabledForeignKeyChecks = disabledForeignKeyChecks
self.migrate = migrate
}
init(identifier: String, disabledForeignKeyChecks: Bool = false, migrate: @escaping (Database) throws -> Void) {
self.identifier = identifier
self.disabledForeignKeyChecks = disabledForeignKeyChecks
self.migrate = migrate
}
#else
init(identifier: String, migrate: @escaping (Database) throws -> Void) {
self.identifier = identifier
self.disabledForeignKeyChecks = false
self.migrate = migrate
}
init(identifier: String, migrate: @escaping (Database) throws -> Void) {
self.identifier = identifier
self.disabledForeignKeyChecks = false
self.migrate = migrate
}
@available(OSX 10.10, *)
// PRAGMA foreign_key_check was introduced in SQLite 3.7.16 http://www.sqlite.org/changes.html#version_3_7_16
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
init(identifier: String, disabledForeignKeyChecks: Bool, migrate: @escaping (Database) throws -> Void) {
self.identifier = identifier
self.disabledForeignKeyChecks = disabledForeignKeyChecks
self.migrate = migrate
}
@available(OSX 10.10, *)
// PRAGMA foreign_key_check was introduced in SQLite 3.7.16 http://www.sqlite.org/changes.html#version_3_7_16
// It is available from iOS 8.2 and OS X 10.10
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
init(identifier: String, disabledForeignKeyChecks: Bool, migrate: @escaping (Database) throws -> Void) {
self.identifier = identifier
self.disabledForeignKeyChecks = disabledForeignKeyChecks
self.migrate = migrate
}
#endif
func run(_ db: Database) throws {
+39 -39
View File
@@ -1,44 +1,44 @@
#if SQLITE_ENABLE_FTS5
extension QueryInterfaceRequest {
// MARK: Full Text Search
/// Creates a request with a full-text predicate added to the eventual
/// set of already applied predicates.
///
/// // SELECT * FROM book WHERE book MATCH '...'
/// var request = Book.all()
/// request = request.matching(pattern)
///
/// If the search pattern is nil, the request does not match any
/// database row.
///
/// The selection defaults to all columns. This default can be changed for
/// all requests by the `TableRecord.databaseSelection` property, or
/// for individual requests with the `TableRecord.select` method.
public func matching(_ pattern: FTS5Pattern?) -> QueryInterfaceRequest<T> {
guard let pattern = pattern else {
return none()
}
let alias = TableAlias()
let matchExpression = TableMatchExpression(alias: alias, pattern: pattern.databaseValue)
return self.aliased(alias).filter(matchExpression)
}
}
extension QueryInterfaceRequest {
extension TableRecord {
// MARK: Full Text Search
/// Returns a QueryInterfaceRequest with a matching predicate.
///
/// // SELECT * FROM book WHERE book MATCH '...'
/// var request = Book.matching(pattern)
///
/// If the search pattern is nil, the request does not match any
/// database row.
public static func matching(_ pattern: FTS5Pattern?) -> QueryInterfaceRequest<Self> {
return all().matching(pattern)
// MARK: Full Text Search
/// Creates a request with a full-text predicate added to the eventual
/// set of already applied predicates.
///
/// // SELECT * FROM book WHERE book MATCH '...'
/// var request = Book.all()
/// request = request.matching(pattern)
///
/// If the search pattern is nil, the request does not match any
/// database row.
///
/// The selection defaults to all columns. This default can be changed for
/// all requests by the `TableRecord.databaseSelection` property, or
/// for individual requests with the `TableRecord.select` method.
public func matching(_ pattern: FTS5Pattern?) -> QueryInterfaceRequest<T> {
guard let pattern = pattern else {
return none()
}
let alias = TableAlias()
let matchExpression = TableMatchExpression(alias: alias, pattern: pattern.databaseValue)
return self.aliased(alias).filter(matchExpression)
}
}
extension TableRecord {
// MARK: Full Text Search
/// Returns a QueryInterfaceRequest with a matching predicate.
///
/// // SELECT * FROM book WHERE book MATCH '...'
/// var request = Book.matching(pattern)
///
/// If the search pattern is nil, the request does not match any
/// database row.
public static func matching(_ pattern: FTS5Pattern?) -> QueryInterfaceRequest<Self> {
return all().matching(pattern)
}
}
#endif
@@ -72,12 +72,12 @@ extension Association {
extension Association {
private func mapDestinationRelation(_ transform: (SQLRelation) -> SQLRelation) -> Self {
return Self.init(sqlAssociation: sqlAssociation.mapDestinationRelation(transform))
return .init(sqlAssociation: sqlAssociation.mapDestinationRelation(transform))
}
}
extension Association {
/// The association key defines how rows fetched from this association
/// should be consumed.
///
@@ -306,7 +306,7 @@ public protocol AssociationToOne: Association { }
extension AssociationToOne {
public func forKey(_ key: String) -> Self {
let associationKey = SQLAssociationKey.fixedSingular(key)
return Self.init(sqlAssociation: sqlAssociation.forDestinationKey(associationKey))
return .init(sqlAssociation: sqlAssociation.forDestinationKey(associationKey))
}
}
@@ -320,7 +320,7 @@ public protocol AssociationToMany: Association { }
extension AssociationToMany {
public func forKey(_ key: String) -> Self {
let associationKey = SQLAssociationKey.fixedPlural(key)
return Self.init(sqlAssociation: sqlAssociation.forDestinationKey(associationKey))
return .init(sqlAssociation: sqlAssociation.forDestinationKey(associationKey))
}
}
@@ -1,5 +1,9 @@
import Foundation
typealias AssociationAggregatePreparation<RowDecoder> =
(QueryInterfaceRequest<RowDecoder>)
-> (request: QueryInterfaceRequest<RowDecoder>, expression: SQLExpression)
/// An AssociationAggregate is able to compute aggregated values from a
/// population of associated records.
///
@@ -56,12 +60,12 @@ public struct AssociationAggregate<RowDecoder> {
/// - We don't know yet if the aggregated value will be used in the
/// SQL selection, or in the HAVING clause.
/// - It helps implementing aggregate operators such as `&&`, `+`, etc.
let prepare: (QueryInterfaceRequest<RowDecoder>) -> (request: QueryInterfaceRequest<RowDecoder>, expression: SQLExpression)
let prepare: AssociationAggregatePreparation<RowDecoder>
/// The SQL alias for the value of this aggregate. See aliased(_:).
var alias: String?
init(_ prepare: @escaping (QueryInterfaceRequest<RowDecoder>) -> (request: QueryInterfaceRequest<RowDecoder>, expression: SQLExpression)) {
init(_ prepare: @escaping AssociationAggregatePreparation<RowDecoder>) {
self.prepare = prepare
}
}
@@ -121,7 +125,11 @@ public prefix func ! <RowDecoder>(aggregate: AssociationAggregate<RowDecoder>) -
/// For example:
///
/// Author.having(Author.books.isEmpty && Author.paintings.isEmpty)
public func && <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func && <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
@@ -131,7 +139,11 @@ public func && <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Associat
// TODO: test
/// :nodoc:
public func && <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
public func && <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression && rhs)
@@ -140,7 +152,11 @@ public func && <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpre
// TODO: test
/// :nodoc:
public func && <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func && <RowDecoder>(
lhs: SQLExpressible,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs && expression)
@@ -153,7 +169,11 @@ public func && <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDe
/// For example:
///
/// Author.having(!Author.books.isEmpty || !Author.paintings.isEmpty)
public func || <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func || <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
@@ -163,7 +183,11 @@ public func || <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Associat
// TODO: test
/// :nodoc:
public func || <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
public func || <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression || rhs)
@@ -172,7 +196,11 @@ public func || <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpre
// TODO: test
/// :nodoc:
public func || <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func || <RowDecoder>(
lhs: SQLExpressible,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs || expression)
@@ -186,7 +214,11 @@ public func || <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDe
/// For example:
///
/// Author.having(Author.books.count == Author.paintings.count)
public func == <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func == <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
@@ -199,7 +231,11 @@ public func == <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Associat
/// For example:
///
/// Author.having(Author.books.count == 3)
public func == <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
public func == <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression == rhs)
@@ -211,7 +247,11 @@ public func == <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpre
/// For example:
///
/// Author.having(3 == Author.books.count)
public func == <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func == <RowDecoder>(
lhs: SQLExpressible,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs == expression)
@@ -247,7 +287,11 @@ public func == <RowDecoder>(lhs: Bool, rhs: AssociationAggregate<RowDecoder>) ->
/// For example:
///
/// Author.having(Author.books.count != Author.paintings.count)
public func != <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func != <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
@@ -260,7 +304,11 @@ public func != <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Associat
/// For example:
///
/// Author.having(Author.books.count != 3)
public func != <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
public func != <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression != rhs)
@@ -272,7 +320,11 @@ public func != <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpre
/// For example:
///
/// Author.having(3 != Author.books.count)
public func != <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func != <RowDecoder>(
lhs: SQLExpressible,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs != expression)
@@ -308,7 +360,11 @@ public func != <RowDecoder>(lhs: Bool, rhs: AssociationAggregate<RowDecoder>) ->
/// For example:
///
/// Author.having(Author.books.count === Author.paintings.count)
public func === <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func === <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
@@ -321,7 +377,11 @@ public func === <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Associa
/// For example:
///
/// Author.having(Author.books.count === 3)
public func === <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
public func === <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression === rhs)
@@ -333,7 +393,11 @@ public func === <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpr
/// For example:
///
/// Author.having(3 === Author.books.count)
public func === <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func === <RowDecoder>(
lhs: SQLExpressible,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs === expression)
@@ -345,7 +409,11 @@ public func === <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowD
/// For example:
///
/// Author.having(Author.books.count !== Author.paintings.count)
public func !== <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func !== <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
@@ -358,7 +426,11 @@ public func !== <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Associa
/// For example:
///
/// Author.having(Author.books.count !== 3)
public func !== <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
public func !== <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression !== rhs)
@@ -370,7 +442,11 @@ public func !== <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpr
/// For example:
///
/// Author.having(3 !== Author.books.count)
public func !== <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func !== <RowDecoder>(
lhs: SQLExpressible,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs !== expression)
@@ -384,7 +460,11 @@ public func !== <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowD
/// For example:
///
/// Author.having(Author.books.count <= Author.paintings.count)
public func <= <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func <= <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
@@ -397,7 +477,11 @@ public func <= <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Associat
/// For example:
///
/// Author.having(Author.books.count <= 3)
public func <= <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
public func <= <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression <= rhs)
@@ -409,7 +493,11 @@ public func <= <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpre
/// For example:
///
/// Author.having(3 <= Author.books.count)
public func <= <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func <= <RowDecoder>(
lhs: SQLExpressible,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs <= expression)
@@ -421,7 +509,11 @@ public func <= <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDe
/// For example:
///
/// Author.having(Author.books.count < Author.paintings.count)
public func < <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func < <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
@@ -434,7 +526,11 @@ public func < <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Associati
/// For example:
///
/// Author.having(Author.books.count < 3)
public func < <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
public func < <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression < rhs)
@@ -446,7 +542,11 @@ public func < <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpres
/// For example:
///
/// Author.having(3 < Author.books.count)
public func < <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func < <RowDecoder>(
lhs: SQLExpressible,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs < expression)
@@ -458,7 +558,11 @@ public func < <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDec
/// For example:
///
/// Author.having(Author.books.count > Author.paintings.count)
public func > <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func > <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
@@ -471,7 +575,11 @@ public func > <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Associati
/// For example:
///
/// Author.having(Author.books.count > 3)
public func > <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
public func > <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression > rhs)
@@ -483,7 +591,11 @@ public func > <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpres
/// For example:
///
/// Author.having(3 > Author.books.count)
public func > <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func > <RowDecoder>(
lhs: SQLExpressible,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs > expression)
@@ -495,7 +607,11 @@ public func > <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDec
/// For example:
///
/// Author.having(Author.books.count >= Author.paintings.count)
public func >= <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func >= <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
@@ -508,7 +624,11 @@ public func >= <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Associat
/// For example:
///
/// Author.having(Author.books.count >= 3)
public func >= <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
public func >= <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression >= rhs)
@@ -520,7 +640,11 @@ public func >= <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpre
/// For example:
///
/// Author.having(3 >= Author.books.count)
public func >= <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func >= <RowDecoder>(
lhs: SQLExpressible,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs >= expression)
@@ -546,7 +670,11 @@ public prefix func - <RowDecoder>(aggregate: AssociationAggregate<RowDecoder>) -
/// For example:
///
/// Author.annotated(with: Author.books.count + Author.paintings.count)
public func + <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func + <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
@@ -559,7 +687,11 @@ public func + <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Associati
/// For example:
///
/// Author.annotated(with: Author.books.count + 1)
public func + <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
public func + <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression + rhs)
@@ -571,7 +703,11 @@ public func + <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpres
/// For example:
///
/// Author.annotated(with: 1 + Author.books.count)
public func + <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func + <RowDecoder>(
lhs: SQLExpressible,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs + expression)
@@ -583,7 +719,11 @@ public func + <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDec
/// For example:
///
/// Author.annotated(with: Author.books.count - Author.paintings.count)
public func - <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func - <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
@@ -596,7 +736,11 @@ public func - <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Associati
/// For example:
///
/// Author.annotated(with: Author.books.count - 1)
public func - <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
public func - <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression - rhs)
@@ -608,7 +752,11 @@ public func - <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpres
/// For example:
///
/// Author.annotated(with: 1 - Author.books.count)
public func - <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func - <RowDecoder>(
lhs: SQLExpressible,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs - expression)
@@ -620,7 +768,11 @@ public func - <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDec
/// For example:
///
/// Author.annotated(with: Author.books.count * Author.paintings.count)
public func * <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func * <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
@@ -633,7 +785,11 @@ public func * <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Associati
/// For example:
///
/// Author.annotated(with: Author.books.count * 2)
public func * <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
public func * <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression * rhs)
@@ -645,7 +801,11 @@ public func * <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpres
/// For example:
///
/// Author.annotated(with: 2 * Author.books.count)
public func * <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func * <RowDecoder>(
lhs: SQLExpressible,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs * expression)
@@ -657,7 +817,11 @@ public func * <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDec
/// For example:
///
/// Author.annotated(with: Author.books.count / Author.paintings.count)
public func / <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func / <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
@@ -670,7 +834,11 @@ public func / <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Associati
/// For example:
///
/// Author.annotated(with: Author.books.count / 2)
public func / <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
public func / <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression / rhs)
@@ -682,7 +850,11 @@ public func / <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpres
/// For example:
///
/// Author.annotated(with: 2 / Author.books.count)
public func / <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func / <RowDecoder>(
lhs: SQLExpressible,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs / expression)
@@ -694,7 +866,11 @@ public func / <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDec
/// Returns an aggregate that evaluates the `IFNULL` SQL function.
///
/// Team.annotated(with: Team.players.min(Column("score")) ?? 0)
public func ?? <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
public func ?? <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
var aggregate = AssociationAggregate<RowDecoder> { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression ?? rhs)
@@ -20,7 +20,7 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord {
public func annotated(with aggregates: AssociationAggregate<RowDecoder>...) -> QueryInterfaceRequest {
return annotated(with: aggregates)
}
/// Creates a request which appends *aggregates* to the current selection.
///
/// // SELECT player.*, COUNT(DISTINCT book.rowid) AS bookCount
@@ -143,7 +143,9 @@ extension QueryInterfaceRequest: SelectionRequest {
/// let request = Player.all().select([max(Column("score"))], as: Int.self)
/// let maxScore: Int? = try request.fetchOne(db)
/// }
public func select<RowDecoder>(_ selection: [SQLSelectable], as type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder> {
public func select<RowDecoder>(_ selection: [SQLSelectable], as type: RowDecoder.Type)
-> QueryInterfaceRequest<RowDecoder>
{
return mapQuery { $0.select(selection) }.asRequest(of: RowDecoder.self)
}
@@ -155,7 +157,9 @@ extension QueryInterfaceRequest: SelectionRequest {
/// let request = Player.all().select(max(Column("score")), as: Int.self)
/// let maxScore: Int? = try request.fetchOne(db)
/// }
public func select<RowDecoder>(_ selection: SQLSelectable..., as type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder> {
public func select<RowDecoder>(_ selection: SQLSelectable..., as type: RowDecoder.Type)
-> QueryInterfaceRequest<RowDecoder>
{
return select(selection, as: type)
}
@@ -167,7 +171,12 @@ extension QueryInterfaceRequest: SelectionRequest {
/// let request = Player.all().select(sql: "max(score)", as: Int.self)
/// let maxScore: Int? = try request.fetchOne(db)
/// }
public func select<RowDecoder>(sql: String, arguments: StatementArguments = StatementArguments(), as type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder> {
public func select<RowDecoder>(
sql: String,
arguments: StatementArguments = StatementArguments(),
as type: RowDecoder.Type)
-> QueryInterfaceRequest<RowDecoder>
{
return select(literal: SQLLiteral(sql: sql, arguments: arguments), as: type)
}
@@ -198,7 +207,11 @@ extension QueryInterfaceRequest: SelectionRequest {
/// as: String.self)
/// let name: String? = try request.fetchOne(db)
/// }
public func select<RowDecoder>(literal sqlLiteral: SQLLiteral, as type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder> {
public func select<RowDecoder>(
literal sqlLiteral: SQLLiteral,
as type: RowDecoder.Type)
-> QueryInterfaceRequest<RowDecoder>
{
return select(SQLSelectionLiteral(literal: sqlLiteral), as: type)
}
@@ -225,7 +238,7 @@ extension QueryInterfaceRequest: SelectionRequest {
extension QueryInterfaceRequest: FilteredRequest {
// MARK: Request Derivation
/// Creates a request with the provided *predicate promise* added to the
/// eventual set of already applied predicates.
///
@@ -235,7 +248,6 @@ extension QueryInterfaceRequest: FilteredRequest {
public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> QueryInterfaceRequest {
return mapQuery { $0.filter(predicate) }
}
}
extension QueryInterfaceRequest: OrderedRequest {
@@ -328,7 +340,7 @@ extension QueryInterfaceRequest: JoinableRequest {
extension QueryInterfaceRequest {
// MARK: Request Derivation
/// Creates a request which returns distinct rows.
///
/// // SELECT DISTINCT * FROM player
@@ -479,7 +491,7 @@ extension QueryInterfaceRequest where T: MutablePersistableRecord {
// MARK: - Eager loading of hasMany associations
/// Append rows from prefetched associations into the argument rows.
fileprivate func prefetch(_ db: Database, associations: [SQLAssociation], in rows: [Row]) throws {
private func prefetch(_ db: Database, associations: [SQLAssociation], in rows: [Row]) throws {
guard let firstRow = rows.first else {
// No rows -> no prefetch
return
@@ -176,7 +176,7 @@ extension FilteredRequest {
// NOT TESTED
return filter(SQLExpressionLiteral(literal: sqlLiteral))
}
/// Creates a request that matches nothing.
///
/// // SELECT * FROM player WHERE 0
@@ -230,7 +230,10 @@ extension TableRequest where Self: FilteredRequest {
}
/// Creates a request with the provided primary key *predicate*.
public func filter<Sequence: Swift.Sequence>(keys: Sequence) -> Self where Sequence.Element: DatabaseValueConvertible {
public func filter<Sequence: Swift.Sequence>(keys: Sequence)
-> Self
where Sequence.Element: DatabaseValueConvertible
{
var request = self
let keys = Array(keys)
switch keys.count {
@@ -241,7 +244,7 @@ extension TableRequest where Self: FilteredRequest {
default:
break
}
let databaseTableName = self.databaseTableName
return request.filter { db in
let primaryKey = try db.primaryKey(databaseTableName)
@@ -286,7 +289,10 @@ extension TableRequest where Self: FilteredRequest {
// ("foo", "bar") is not a unique key (primary key or columns of a
// unique index)
guard let columns = try db.columnsForUniqueKey(key.keys, in: databaseTableName) else {
fatalError("table \(databaseTableName) has no unique index on column(s) \(key.keys.sorted().joined(separator: ", "))")
fatalError("""
table \(databaseTableName) has no unique index on column(s) \
\(key.keys.sorted().joined(separator: ", "))
""")
}
let lowercaseColumns = columns.map { $0.lowercased() }
@@ -365,13 +371,13 @@ extension AggregatingRequest {
// NOT TESTED
return group(SQLExpressionLiteral(literal: sqlLiteral))
}
/// Creates a request with the provided *sql* added to the
/// eventual set of already applied predicates.
public func having(sql: String, arguments: StatementArguments = StatementArguments()) -> Self {
return having(literal: SQLLiteral(sql: sql, arguments: arguments))
}
/// Creates a request with the provided *sql* added to the
/// eventual set of already applied predicates.
public func having(literal sqlLiteral: SQLLiteral) -> Self {
@@ -51,7 +51,7 @@ public struct SQLCollatedExpression {
}
/// :nodoc:
extension SQLCollatedExpression : SQLOrderingTerm {
extension SQLCollatedExpression: SQLOrderingTerm {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
+5 -3
View File
@@ -37,15 +37,17 @@ extension SQLCollection {
/// SQLExpressionsArray wraps an array of expressions
///
/// SQLExpressionsArray([1, 2, 3])
struct SQLExpressionsArray : SQLCollection {
struct SQLExpressionsArray: SQLCollection {
let expressions: [SQLExpression]
init<S: Sequence>(_ expressions: S) where S.Iterator.Element : SQLExpressible {
init<S: Sequence>(_ expressions: S) where S.Iterator.Element: SQLExpressible {
self.expressions = expressions.map { $0.sqlExpression }
}
func collectionSQL(_ context: inout SQLGenerationContext) -> String {
return (expressions.map { $0.expressionSQL(&context, wrappedInParenthesis: false) } as [String]).joined(separator: ", ")
return expressions
.map { $0.expressionSQL(&context, wrappedInParenthesis: false) }
.joined(separator: ", ")
}
func contains(_ value: SQLExpressible) -> SQLExpression {
+1 -1
View File
@@ -31,7 +31,7 @@ public protocol SQLExpressible {
/// On the other side, Int adopts SQLExpressible (via DatabaseValueConvertible).
///
/// :nodoc:
public protocol SQLSpecificExpressible : SQLExpressible {
public protocol SQLSpecificExpressible: SQLExpressible {
// SQLExpressible can be adopted by Swift standard types, and user
// types, through the DatabaseValueConvertible protocol which inherits
// from SQLExpressible.
@@ -14,10 +14,10 @@ extension SQLExpression {
/// The expression as a quoted SQL literal (not public in order to avoid abuses)
///
/// "foo'bar".databaseValue.quotedSQL(wrappedInParenthesis: true) // "'foo''bar'""
func quotedSQL(wrappedInParenthesis: Bool) -> String {
/// "foo'bar".databaseValue.quotedSQL() // "'foo''bar'""
func quotedSQL() -> String {
var context = SQLGenerationContext.literalGenerationContext(withArguments: false)
return expressionSQL(&context, wrappedInParenthesis: wrappedInParenthesis)
return expressionSQL(&context, wrappedInParenthesis: false)
}
}
@@ -33,7 +33,7 @@ extension SQLExpression {
///
/// SQLExpressionLiteral(sql: "? + ?", arguments: [1, 2])
/// SQLExpressionLiteral(sql: ":one + :two", arguments: ["one": 1, "two": 2])
public struct SQLExpressionLiteral : SQLExpression {
public struct SQLExpressionLiteral: SQLExpression {
private let sqlLiteral: SQLLiteral
public var sql: String { return sqlLiteral.sql }
public var arguments: StatementArguments { return sqlLiteral.arguments }
@@ -93,7 +93,7 @@ public struct SQLExpressionLiteral : SQLExpression {
/// SQLUnaryOperator is a SQLite unary operator.
///
/// :nodoc:
public struct SQLUnaryOperator : Hashable {
public struct SQLUnaryOperator: Hashable {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// The SQL operator
@@ -121,7 +121,7 @@ public struct SQLUnaryOperator : Hashable {
/// an operand expression.
///
/// :nodoc:
public struct SQLExpressionUnary : SQLExpression {
public struct SQLExpressionUnary: SQLExpression {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// The unary operator
@@ -167,7 +167,7 @@ public struct SQLExpressionUnary : SQLExpression {
/// SQLBinaryOperator is a SQLite binary operator.
///
/// :nodoc:
public struct SQLBinaryOperator : Hashable {
public struct SQLBinaryOperator: Hashable {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// The SQL operator
@@ -211,7 +211,7 @@ public struct SQLBinaryOperator : Hashable {
/// SQLExpressionBinary(.multiply, Column("length"), Column("width"))
///
/// :nodoc:
public struct SQLExpressionBinary : SQLExpression {
public struct SQLExpressionBinary: SQLExpression {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// The left operand
@@ -252,17 +252,17 @@ public struct SQLExpressionBinary : SQLExpression {
\(rhs.expressionSQL(&context, wrappedInParenthesis: true))
"""
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public var negated: SQLExpression {
if let negatedOp = op.negated {
return SQLExpressionBinary(negatedOp, lhs, rhs)
return SQLExpressionBinary(negatedOp, lhs, rhs)
} else {
return SQLExpressionNot(self)
}
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
@@ -272,7 +272,7 @@ public struct SQLExpressionBinary : SQLExpression {
// MARK: - SQLExpressionAnd
struct SQLExpressionAnd : SQLExpression {
struct SQLExpressionAnd: SQLExpression {
let expressions: [SQLExpression]
init(_ expressions: [SQLExpression]) {
@@ -312,7 +312,7 @@ struct SQLExpressionAnd : SQLExpression {
// MARK: - SQLExpressionOr
struct SQLExpressionOr : SQLExpression {
struct SQLExpressionOr: SQLExpression {
let expressions: [SQLExpression]
init(_ expressions: [SQLExpression]) {
@@ -422,9 +422,9 @@ struct SQLExpressionEqual: SQLExpression {
}
}
switch (lhs, rhs) {
case (let column as ColumnExpression, let dbValue as DatabaseValue):
case let (column as ColumnExpression, dbValue as DatabaseValue):
return matchedRowIds(column: column, dbValue: dbValue)
case (let dbValue as DatabaseValue, let column as ColumnExpression):
case let (dbValue as DatabaseValue, column as ColumnExpression):
return matchedRowIds(column: column, dbValue: dbValue)
default:
return nil
@@ -443,7 +443,7 @@ struct SQLExpressionEqual: SQLExpression {
///
/// // id IN (1,2,3)
/// SQLExpressionContains(Column("id"), SQLExpressionsArray([1,2,3]))
struct SQLExpressionContains : SQLExpression {
struct SQLExpressionContains: SQLExpression {
let expression: SQLExpression
let collection: SQLCollection
let isNegated: Bool
@@ -509,7 +509,7 @@ struct SQLExpressionContains : SQLExpression {
///
/// // id BETWEEN 1 AND 3
/// SQLExpressionBetween(Column("id"), 1.databaseValue, 3.databaseValue)
struct SQLExpressionBetween : SQLExpression {
struct SQLExpressionBetween: SQLExpression {
let expression: SQLExpression
let lowerBound: SQLExpression
let upperBound: SQLExpression
@@ -534,7 +534,7 @@ struct SQLExpressionBetween : SQLExpression {
\(upperBound.expressionSQL(&context, wrappedInParenthesis: true))
"""
}
var negated: SQLExpression {
return SQLExpressionBetween(expression, lowerBound, upperBound, negated: !isNegated)
}
@@ -553,7 +553,7 @@ struct SQLExpressionBetween : SQLExpression {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// SQLFunctionName is an SQL function name.
public struct SQLFunctionName : Hashable {
public struct SQLFunctionName: Hashable {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// The SQL function name
@@ -581,7 +581,7 @@ public struct SQLFunctionName : Hashable {
/// SQLExpressionFunction(.abs, [-1.databaseValue])
///
/// :nodoc:
public struct SQLExpressionFunction : SQLExpression {
public struct SQLExpressionFunction: SQLExpression {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// The function name
@@ -616,11 +616,13 @@ public struct SQLExpressionFunction : SQLExpression {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
return """
\(functionName.sql)(\
\((arguments.map { $0.expressionSQL(&context, wrappedInParenthesis: false) } as [String]).joined(separator: ", "))\
)
"""
var sql = functionName.sql
sql += "("
sql += arguments
.map { $0.expressionSQL(&context, wrappedInParenthesis: false) }
.joined(separator: ", ")
sql += ")"
return sql
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
@@ -636,7 +638,7 @@ public struct SQLExpressionFunction : SQLExpression {
///
/// // COUNT(name)
/// SQLExpressionCount(Column("name"))
struct SQLExpressionCount : SQLExpression {
struct SQLExpressionCount: SQLExpression {
/// The counted value
let counted: SQLSelectable
@@ -659,7 +661,7 @@ struct SQLExpressionCount : SQLExpression {
///
/// // COUNT(DISTINCT name)
/// SQLExpressionCountDistinct(Column("name"))
struct SQLExpressionCountDistinct : SQLExpression {
struct SQLExpressionCountDistinct: SQLExpression {
let counted: SQLExpression
init(_ counted: SQLExpression) {
@@ -680,7 +682,7 @@ struct SQLExpressionCountDistinct : SQLExpression {
/// This one helps generating `COUNT(...) = 0` or `COUNT(...) > 0` while letting
/// the user using the not `!` logical operator, or comparisons with booleans
/// such as `== true` or `== false`.
struct SQLExpressionIsEmpty : SQLExpression {
struct SQLExpressionIsEmpty: SQLExpression {
var countExpression: SQLExpression
var isEmpty: Bool
@@ -739,7 +741,7 @@ struct TableMatchExpression: SQLExpression {
///
/// // email = 'arthur@example.com' COLLATE NOCASE
/// SQLExpressionCollate(Column("email") == "arthur@example.com", "NOCASE")
struct SQLExpressionCollate : SQLExpression {
struct SQLExpressionCollate: SQLExpression {
let expression: SQLExpression
let collationName: Database.CollationName
@@ -752,9 +754,8 @@ struct SQLExpressionCollate : SQLExpression {
if wrappedInParenthesis {
return "(\(expressionSQL(&context, wrappedInParenthesis: false)))"
}
let sql = expression.expressionSQL(&context, wrappedInParenthesis: false)
return """
\(sql) \
\(expression.expressionSQL(&context, wrappedInParenthesis: false)) \
COLLATE \
\(collationName.rawValue)
"""
+2 -14
View File
@@ -5,20 +5,8 @@
/// SQLExpression is the protocol for types that represent an SQL expression, as
/// described at https://www.sqlite.org/lang_expr.html
///
/// GRDB ships with a variety of types that already adopt this protocol, and
/// allow to represent many SQLite expressions:
///
/// - Column
/// - DatabaseValue
/// - SQLExpressionLiteral
/// - SQLExpressionUnary
/// - SQLExpressionBinary
/// - SQLExpressionExists
/// - SQLExpressionFunction
/// - SQLExpressionCollate
///
/// :nodoc:
public protocol SQLExpression : SQLSpecificExpressible, SQLSelectable, SQLOrderingTerm {
public protocol SQLExpression: SQLSpecificExpressible, SQLSelectable, SQLOrderingTerm {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
@@ -131,7 +119,7 @@ extension SQLExpression {
// MARK: - SQLExpressionNot
struct SQLExpressionNot : SQLExpression {
struct SQLExpressionNot: SQLExpression {
let expression: SQLExpression
init(_ expression: SQLExpression) {
@@ -67,7 +67,7 @@ struct SQLForeignKeyRequest: Equatable {
// No matching foreign key found: use the destination primary key
if let originColumns = originColumns {
let destinationColumns = try db.primaryKey(destinationTable).columns
if (originColumns.count == destinationColumns.count) {
if originColumns.count == destinationColumns.count {
let mapping = zip(originColumns, destinationColumns).map {
(origin: $0, destination: $1)
}
+2 -2
View File
@@ -158,7 +158,7 @@ extension SQLSpecificExpressible {
public var capitalized: SQLExpression {
return DatabaseFunction.capitalize.apply(sqlExpression)
}
/// Returns an SQL expression that applies the Swift's built-in
/// lowercased String property. It is NULL for non-String arguments.
///
@@ -168,7 +168,7 @@ extension SQLSpecificExpressible {
public var lowercased: SQLExpression {
return DatabaseFunction.lowercase.apply(sqlExpression)
}
/// Returns an SQL expression that applies the Swift's built-in
/// uppercased String property. It is NULL for non-String arguments.
///
+2 -2
View File
@@ -3,14 +3,14 @@
// Outputs "x = y" or "x IS NULL"
private func isEqual(_ lhs: SQLExpression, _ rhs: SQLExpression) -> SQLExpression {
switch (lhs, rhs) {
case (let lhs, let rhs as DatabaseValue):
case let (lhs, rhs as DatabaseValue):
switch rhs.storage {
case .null:
return SQLExpressionEqual(.is, lhs, rhs)
default:
return SQLExpressionEqual(.equal, lhs, rhs)
}
case (let lhs as DatabaseValue, let rhs):
case let (lhs as DatabaseValue, rhs):
switch lhs.storage {
case .null:
return SQLExpressionEqual(.is, rhs, lhs)
+1 -1
View File
@@ -23,7 +23,7 @@ public protocol SQLOrderingTerm {
// MARK: - SQLOrdering
enum SQLOrdering : SQLOrderingTerm {
enum SQLOrdering: SQLOrderingTerm {
case asc(SQLExpression)
case desc(SQLExpression)
+1 -1
View File
@@ -11,7 +11,7 @@ struct SQLQuery {
// `(a AND b AND c)` instead of `((a AND b) AND c)`.
var havingExpressions: [SQLExpression]
var limit: SQLLimit?
init(
relation: SQLRelation,
isDistinct: Bool = false,
+12 -8
View File
@@ -1,4 +1,5 @@
/// A "relation", as defined by the [relational terminology](https://en.wikipedia.org/wiki/Relational_database#Terminology),
/// A "relation", as defined by the [relational
/// terminology](https://en.wikipedia.org/wiki/Relational_database#Terminology),
/// is "a set of tuples sharing the same attributes; a set of columns and rows."
///
/// SQLRelation is defined with a selection, a source table of query, and an
@@ -200,7 +201,7 @@ extension SQLRelation {
relation.selection.append(contentsOf: selection)
return relation
}
func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> SQLRelation {
var relation = self
relation.filtersPromise = relation.filtersPromise.flatMap { filters in
@@ -277,10 +278,10 @@ extension SQLRelation {
/// as HasManyThrough, which have any number of pivot relations between the
/// origin and the destination.
func appendingChild(for association: SQLAssociation, kind: SQLRelation.Child.Kind) -> SQLRelation {
// Preserve association cardinality in intermediate steps of
// including(all:), and force desired cardinality otherwize
let childCardinality = (kind == .allNotPrefetched)
// preserve association cardinality in intermediate steps of including(all:)
? association.destination.cardinality
// force desired cardinality otherwize
: kind.cardinality
let childKey = association.destination.key.name(for: childCardinality)
let child = SQLRelation.Child(
@@ -347,7 +348,10 @@ extension SQLRelation {
if let existingChild = relation.children.removeValue(forKey: key) {
guard let mergedChild = existingChild.merged(with: child) else {
// can't merge
fatalError("The association key \"\(key)\" is ambiguous. Use the Association.forKey(_:) method is order to disambiguate.")
fatalError("""
The association key \"\(key)\" is ambiguous. \
Use the Association.forKey(_:) method is order to disambiguate.
""")
}
relation.children.appendValue(mergedChild, forKey: key)
} else {
@@ -387,7 +391,7 @@ enum SQLSource {
func qualified(with alias: TableAlias) -> SQLSource {
switch self {
case .table(let tableName, let sourceAlias):
case let .table(tableName, sourceAlias):
if let sourceAlias = sourceAlias {
alias.becomeProxy(of: sourceAlias)
return self
@@ -395,7 +399,7 @@ enum SQLSource {
alias.setTableName(tableName)
return .table(tableName: tableName, alias: alias)
}
case .query(let query):
case let .query(query):
return .query(query.qualified(with: alias))
}
}
@@ -774,7 +778,7 @@ extension SQLRelation.Child.Kind {
// .including(all: associationToDestinationThroughPivot)
// .including(all: associationToPivot)
fatalError("Not implemented: merging a direct association and an indirect one with including(all:)")
case (.allNotPrefetched, .allNotPrefetched):
// Equivalent to Record.including(all: association)
//
@@ -18,7 +18,7 @@ public struct AllColumns {
public init() { }
}
extension AllColumns : SQLSelectable {
extension AllColumns: SQLSelectable {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func resultColumnSQL(_ context: inout SQLGenerationContext) -> String {
@@ -69,7 +69,7 @@ struct QualifiedAllColumns {
}
}
extension QualifiedAllColumns : SQLSelectable {
extension QualifiedAllColumns: SQLSelectable {
func resultColumnSQL(_ context: inout SQLGenerationContext) -> String {
if let qualifier = context.qualifier(for: alias) {
return qualifier.quotedDatabaseIdentifier + ".*"
@@ -94,10 +94,10 @@ extension QualifiedAllColumns : SQLSelectable {
//
// So let's always return `*`, and fix this later.
// if context.qualifier(for: alias) != nil {
// // SELECT COUNT(t.*) is invalid SQL
// fatalError("Not implemented, or invalid query")
// }
// if context.qualifier(for: alias) != nil {
// // SELECT COUNT(t.*) is invalid SQL
// fatalError("Not implemented, or invalid query")
// }
return "*"
}
@@ -118,7 +118,7 @@ extension QualifiedAllColumns : SQLSelectable {
// MARK: - SQLAliasedExpression
struct SQLAliasedExpression : SQLSelectable {
struct SQLAliasedExpression: SQLSelectable {
let expression: SQLExpression
let name: String
+13 -4
View File
@@ -25,7 +25,7 @@ public protocol SQLSelectable {
// MARK: - SQLSelectionLiteral
struct SQLSelectionLiteral : SQLSelectable {
struct SQLSelectionLiteral: SQLSelectable {
private let sqlLiteral: SQLLiteral
init(literal sqlLiteral: SQLLiteral) {
@@ -42,15 +42,24 @@ struct SQLSelectionLiteral : SQLSelectable {
}
func countedSQL(_ context: inout SQLGenerationContext) -> String {
fatalError("Selection literals can't be counted. To resolve this error, select one or several SQLExpressionLiteral instead.")
fatalError("""
Selection literals can't be counted. \
To resolve this error, select one or several SQLExpressionLiteral instead.
""")
}
func count(distinct: Bool) -> SQLCount? {
fatalError("Selection literals can't be counted. To resolve this error, select one or several SQLExpressionLiteral instead.")
fatalError("""
Selection literals can't be counted. \
To resolve this error, select one or several SQLExpressionLiteral instead.
""")
}
func columnCount(_ db: Database) throws -> Int {
fatalError("Selection literals don't known how many columns they contain. To resolve this error, select one or several SQLExpressionLiteral instead.")
fatalError("""
Selection literals don't known how many columns they contain. \
To resolve this error, select one or several SQLExpressionLiteral instead.
""")
}
func qualifiedSelectable(with alias: TableAlias) -> SQLSelectable {
@@ -63,4 +63,3 @@ extension SQLSpecificExpressible {
return SQLCollatedExpression(sqlExpression, collationName: Database.CollationName(collation.name))
}
}
@@ -96,7 +96,6 @@ public struct SQLGenerationContext {
///
/// A TableAlias identifies a table in a request.
public class TableAlias: Hashable {
private var impl: Impl
private enum Impl {
/// A TableAlias is undefined when it is created by the GRDB user:
///
@@ -144,6 +143,8 @@ public class TableAlias: Hashable {
case proxy(TableAlias)
}
private var impl: Impl
/// Resolve all proxies
private var root: TableAlias {
if case .proxy(let base) = impl {
@@ -221,7 +222,8 @@ public class TableAlias: Hashable {
let root = self.root
let otherRoot = other.root
switch (root.impl, otherRoot.impl) {
case let (.table(tableName: tableName, userName: userName), .table(tableName: otherTableName, userName: otherUserName)):
case let (.table(tableName: tableName, userName: userName),
.table(tableName: otherTableName, userName: otherUserName)):
guard tableName == otherTableName else {
// can't merge
return nil
@@ -54,32 +54,43 @@ struct SQLQueryGenerator {
GRDBPrecondition(!selection.isEmpty, "Can't generate SQL with empty selection")
sql += " " + selection.map { $0.resultColumnSQL(&context) }.joined(separator: ", ")
sql += try " FROM " + relation.source.sql(db, &context)
sql += " FROM "
sql += try relation.source.sql(db, &context)
for (_, join) in relation.joins {
sql += try " " + join.sql(db, &context, leftAlias: relation.alias)
sql += " "
sql += try join.sql(db, &context, leftAlias: relation.alias)
}
let filters = try relation.filtersPromise.resolve(db)
if filters.isEmpty == false {
sql += " WHERE " + SQLExpressionAnd(filters).expressionSQL(&context, wrappedInParenthesis: false)
sql += " WHERE "
sql += SQLExpressionAnd(filters).expressionSQL(&context, wrappedInParenthesis: false)
}
if let groupExpressions = try groupPromise?.resolve(db), !groupExpressions.isEmpty {
sql += " GROUP BY " + groupExpressions.map { $0.expressionSQL(&context, wrappedInParenthesis: false) }.joined(separator: ", ")
sql += " GROUP BY "
sql += groupExpressions
.map { $0.expressionSQL(&context, wrappedInParenthesis: false) }
.joined(separator: ", ")
}
if havingExpressions.isEmpty == false {
sql += " HAVING " + SQLExpressionAnd(havingExpressions).expressionSQL(&context, wrappedInParenthesis: false)
sql += " HAVING "
sql += SQLExpressionAnd(havingExpressions).expressionSQL(&context, wrappedInParenthesis: false)
}
let orderings = try relation.ordering.resolve(db)
if !orderings.isEmpty {
sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&context) }.joined(separator: ", ")
sql += " ORDER BY "
sql += orderings
.map { $0.orderingTermSQL(&context) }
.joined(separator: ", ")
}
if let limit = limit {
sql += " LIMIT " + limit.sql
sql += " LIMIT "
sql += limit.sql
}
return sql
@@ -409,23 +420,23 @@ private enum SQLQualifiedSource {
init(_ source: SQLSource) {
switch source {
case .table(let tableName, let alias):
case let .table(tableName, alias):
let alias = alias ?? TableAlias(tableName: tableName)
self = .table(tableName: tableName, alias: alias)
case .query(let query):
case let .query(query):
self = .query(SQLQueryGenerator(query))
}
}
func sql(_ db: Database, _ context: inout SQLGenerationContext) throws -> String {
switch self {
case .table(let tableName, let alias):
case let .table(tableName, alias):
if let aliasName = context.aliasName(for: alias) {
return "\(tableName.quotedDatabaseIdentifier) \(aliasName.quotedDatabaseIdentifier)"
} else {
return "\(tableName.quotedDatabaseIdentifier)"
}
case .query(let query):
case let .query(query):
return try "(\(query.sql(db, &context)))"
}
}
@@ -437,15 +448,22 @@ private struct SQLQualifiedJoin {
case leftJoin = "LEFT JOIN"
case innerJoin = "JOIN"
}
let kind: Kind
let condition: SQLAssociationCondition
let relation: SQLQualifiedRelation
func sql(_ db: Database,_ context: inout SQLGenerationContext, leftAlias: TableAlias) throws -> String {
func sql(_ db: Database, _ context: inout SQLGenerationContext, leftAlias: TableAlias) throws -> String {
return try sql(db, &context, leftAlias: leftAlias, allowingInnerJoin: true)
}
private func sql(_ db: Database,_ context: inout SQLGenerationContext, leftAlias: TableAlias, allowingInnerJoin allowsInnerJoin: Bool) throws -> String {
private func sql(
_ db: Database,
_ context: inout SQLGenerationContext,
leftAlias: TableAlias,
allowingInnerJoin allowsInnerJoin: Bool)
throws -> String
{
var allowsInnerJoin = allowsInnerJoin
var sql = ""
@@ -44,7 +44,9 @@ extension SQLInterpolation {
/// let request: SQLRequest<String> = "
/// SELECT \(CodingKey.name) FROM player
/// """
public mutating func appendInterpolation(_ codingKey: SQLExpressible & SQLSelectable & SQLOrderingTerm & CodingKey) {
public mutating func appendInterpolation(
_ codingKey: SQLExpressible & SQLSelectable & SQLOrderingTerm & CodingKey)
{
sql += codingKey.sqlExpression.expressionSQL(&context, wrappedInParenthesis: false)
}
@@ -133,7 +135,7 @@ extension SQLInterpolation {
public mutating func appendInterpolation(_ ordering: SQLOrderingTerm) {
sql += ordering.orderingTermSQL(&context)
}
/// Appends the request SQL, wrapped in parentheses
///
/// // SELECT name FROM player WHERE score = (SELECT MAX(score) FROM player)
+212 -57
View File
@@ -25,8 +25,19 @@ extension Database {
/// - withoutRowID: If true, uses WITHOUT ROWID optimization.
/// - body: A closure that defines table columns and constraints.
/// - throws: A DatabaseError whenever an SQLite error occurs.
public func create(table name: String, temporary: Bool = false, ifNotExists: Bool = false, withoutRowID: Bool = false, body: (TableDefinition) -> Void) throws {
let definition = TableDefinition(name: name, temporary: temporary, ifNotExists: ifNotExists, withoutRowID: withoutRowID)
public func create(
table name: String,
temporary: Bool = false,
ifNotExists: Bool = false,
withoutRowID: Bool = false,
body: (TableDefinition) -> Void)
throws
{
let definition = TableDefinition(
name: name,
temporary: temporary,
ifNotExists: ifNotExists,
withoutRowID: withoutRowID)
body(definition)
let sql = try definition.sql(self)
try execute(sql: sql)
@@ -55,10 +66,22 @@ extension Database {
/// - body: A closure that defines table columns and constraints.
/// - throws: A DatabaseError whenever an SQLite error occurs.
@available(OSX 10.10, *)
public func create(table name: String, temporary: Bool = false, ifNotExists: Bool = false, withoutRowID: Bool, body: (TableDefinition) -> Void) throws {
public func create(
table name: String,
temporary: Bool = false,
ifNotExists: Bool = false,
withoutRowID: Bool,
body: (TableDefinition) -> Void)
throws
{
// WITHOUT ROWID was added in SQLite 3.8.2 http://www.sqlite.org/changes.html#version_3_8_2
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
let definition = TableDefinition(name: name, temporary: temporary, ifNotExists: ifNotExists, withoutRowID: withoutRowID)
// It is available from iOS 8.2 and OS X 10.10
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
let definition = TableDefinition(
name: name,
temporary: temporary,
ifNotExists: ifNotExists,
withoutRowID: withoutRowID)
body(definition)
let sql = try definition.sql(self)
try execute(sql: sql)
@@ -84,14 +107,24 @@ extension Database {
/// already exists.
/// - body: A closure that defines table columns and constraints.
/// - throws: A DatabaseError whenever an SQLite error occurs.
public func create(table name: String, temporary: Bool = false, ifNotExists: Bool = false, body: (TableDefinition) -> Void) throws {
let definition = TableDefinition(name: name, temporary: temporary, ifNotExists: ifNotExists, withoutRowID: false)
public func create(
table name: String,
temporary: Bool = false,
ifNotExists: Bool = false,
body: (TableDefinition) -> Void)
throws
{
let definition = TableDefinition(
name: name,
temporary: temporary,
ifNotExists: ifNotExists,
withoutRowID: false)
body(definition)
let sql = try definition.sql(self)
try execute(sql: sql)
}
#endif
/// Renames a database table.
///
/// See https://www.sqlite.org/lang_altertable.html
@@ -150,10 +183,25 @@ extension Database {
/// - ifNotExists: If false, no error is thrown if index already exists.
/// - condition: If not nil, creates a partial index
/// (see https://www.sqlite.org/partialindex.html).
public func create(index name: String, on table: String, columns: [String], unique: Bool = false, ifNotExists: Bool = false, condition: SQLExpressible? = nil) throws {
public func create(
index name: String,
on table: String,
columns: [String],
unique: Bool = false,
ifNotExists: Bool = false,
condition: SQLExpressible? = nil)
throws
{
// Partial indexes were introduced in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
let definition = IndexDefinition(name: name, table: table, columns: columns, unique: unique, ifNotExists: ifNotExists, condition: condition?.sqlExpression)
// It is available from iOS 8.2 and OS X 10.10
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
let definition = IndexDefinition(
name: name,
table: table,
columns: columns,
unique: unique,
ifNotExists: ifNotExists,
condition: condition?.sqlExpression)
let sql = definition.sql()
try execute(sql: sql)
}
@@ -176,10 +224,24 @@ extension Database {
/// - columns: The indexed columns.
/// - unique: If true, creates a unique index.
/// - ifNotExists: If false, no error is thrown if index already exists.
public func create(index name: String, on table: String, columns: [String], unique: Bool = false, ifNotExists: Bool = false) throws {
public func create(
index name: String,
on table: String,
columns: [String],
unique: Bool = false,
ifNotExists: Bool = false)
throws
{
// Partial indexes were introduced in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
let definition = IndexDefinition(name: name, table: table, columns: columns, unique: unique, ifNotExists: ifNotExists, condition: nil)
// It is available from iOS 8.2 and OS X 10.10
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
let definition = IndexDefinition(
name: name,
table: table,
columns: columns,
unique: unique,
ifNotExists: ifNotExists,
condition: nil)
let sql = definition.sql()
try execute(sql: sql)
}
@@ -199,10 +261,25 @@ extension Database {
/// - ifNotExists: If false, no error is thrown if index already exists.
/// - condition: The condition that indexed rows must verify.
@available(OSX 10.10, *)
public func create(index name: String, on table: String, columns: [String], unique: Bool = false, ifNotExists: Bool = false, condition: SQLExpressible) throws {
public func create(
index name: String,
on table: String,
columns: [String],
unique: Bool = false,
ifNotExists: Bool = false,
condition: SQLExpressible)
throws
{
// Partial indexes were introduced in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
let definition = IndexDefinition(name: name, table: table, columns: columns, unique: unique, ifNotExists: ifNotExists, condition: condition.sqlExpression)
// It is available from iOS 8.2 and OS X 10.10
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
let definition = IndexDefinition(
name: name,
table: table,
columns: columns,
unique: unique,
ifNotExists: ifNotExists,
condition: condition.sqlExpression)
let sql = definition.sql()
try execute(sql: sql)
}
@@ -253,7 +330,18 @@ extension Database {
///
/// See https://www.sqlite.org/lang_createtable.html
public final class TableDefinition {
private typealias KeyConstraint = (columns: [String], conflictResolution: Database.ConflictResolution?)
private typealias KeyConstraint = (
columns: [String],
conflictResolution: Database.ConflictResolution?)
private struct ForeignKeyConstraint {
var columns: [String]
var table: String
var destinationColumns: [String]?
var deleteAction: Database.ForeignKeyAction?
var updateAction: Database.ForeignKeyAction?
var deferred: Bool
}
private let name: String
private let temporary: Bool
@@ -262,7 +350,7 @@ public final class TableDefinition {
private var columns: [ColumnDefinition] = []
private var primaryKeyConstraint: KeyConstraint?
private var uniqueKeyConstraints: [KeyConstraint] = []
private var foreignKeyConstraints: [(columns: [String], table: String, destinationColumns: [String]?, deleteAction: Database.ForeignKeyAction?, updateAction: Database.ForeignKeyAction?, deferred: Bool)] = []
private var foreignKeyConstraints: [ForeignKeyConstraint] = []
private var checkConstraints: [SQLExpression] = []
init(name: String, temporary: Bool, ifNotExists: Bool, withoutRowID: Bool) {
@@ -300,10 +388,14 @@ public final class TableDefinition {
/// (see https://www.sqlite.org/lang_conflict.html).
/// - returns: Self so that you can further refine the column definition.
@discardableResult
public func autoIncrementedPrimaryKey(_ name: String, onConflict conflictResolution: Database.ConflictResolution? = nil) -> ColumnDefinition {
public func autoIncrementedPrimaryKey(
_ name: String,
onConflict conflictResolution: Database.ConflictResolution? = nil)
-> ColumnDefinition
{
return column(name, .integer).primaryKey(onConflict: conflictResolution, autoincrement: true)
}
/// Appends a table column.
///
/// try db.create(table: "player") { t in
@@ -383,8 +475,21 @@ public final class TableDefinition {
/// - updateAction: Optional action when the referenced row is updated.
/// - deferred: If true, defines a deferred foreign key constraint.
/// See https://www.sqlite.org/foreignkeys.html#fk_deferred.
public func foreignKey(_ columns: [String], references table: String, columns destinationColumns: [String]? = nil, onDelete deleteAction: Database.ForeignKeyAction? = nil, onUpdate updateAction: Database.ForeignKeyAction? = nil, deferred: Bool = false) {
foreignKeyConstraints.append((columns: columns, table: table, destinationColumns: destinationColumns, deleteAction: deleteAction, updateAction: updateAction, deferred: deferred))
public func foreignKey(
_ columns: [String],
references table: String,
columns destinationColumns: [String]? = nil,
onDelete deleteAction: Database.ForeignKeyAction? = nil,
onUpdate updateAction: Database.ForeignKeyAction? = nil,
deferred: Bool = false)
{
foreignKeyConstraints.append(ForeignKeyConstraint(
columns: columns,
table: table,
destinationColumns: destinationColumns,
deleteAction: deleteAction,
updateAction: updateAction,
deferred: deferred))
}
/// Adds a CHECK constraint.
@@ -451,12 +556,14 @@ public final class TableDefinition {
do {
var items: [String] = []
try items.append(contentsOf: columns.map { try $0.sql(db, tableName: name, primaryKeyColumns: primaryKeyColumns) })
try items.append(contentsOf: columns.map {
try $0.sql(db, tableName: name, primaryKeyColumns: primaryKeyColumns)
})
if let (columns, conflictResolution) = primaryKeyConstraint {
var chunks: [String] = []
chunks.append("PRIMARY KEY")
chunks.append("(\((columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
chunks.append("(\(columns.map { $0.quotedDatabaseIdentifier }.joined(separator: ", ")))")
if let conflictResolution = conflictResolution {
chunks.append("ON CONFLICT")
chunks.append(conflictResolution.rawValue)
@@ -467,7 +574,7 @@ public final class TableDefinition {
for (columns, conflictResolution) in uniqueKeyConstraints {
var chunks: [String] = []
chunks.append("UNIQUE")
chunks.append("(\((columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
chunks.append("(\(columns.map { $0.quotedDatabaseIdentifier }.joined(separator: ", ")))")
if let conflictResolution = conflictResolution {
chunks.append("ON CONFLICT")
chunks.append(conflictResolution.rawValue)
@@ -475,28 +582,40 @@ public final class TableDefinition {
items.append(chunks.joined(separator: " "))
}
for (columns, table, destinationColumns, deleteAction, updateAction, deferred) in foreignKeyConstraints {
for constraint in foreignKeyConstraints {
var chunks: [String] = []
chunks.append("FOREIGN KEY")
chunks.append("(\((columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
chunks.append("(\(constraint.columns.map { $0.quotedDatabaseIdentifier }.joined(separator: ", ")))")
chunks.append("REFERENCES")
if let destinationColumns = destinationColumns {
chunks.append("\(table.quotedDatabaseIdentifier)(\((destinationColumns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
} else if table == name {
chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKeyColumns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
if let destinationColumns = constraint.destinationColumns {
chunks.append("""
\(constraint.table.quotedDatabaseIdentifier)(\
\(destinationColumns.map { $0.quotedDatabaseIdentifier }.joined(separator: ", "))\
)
""")
} else if constraint.table == name {
chunks.append("""
\(constraint.table.quotedDatabaseIdentifier)(\
\(primaryKeyColumns.map { $0.quotedDatabaseIdentifier }.joined(separator: ", "))\
)
""")
} else {
let primaryKey = try db.primaryKey(table)
chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKey.columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
let primaryKey = try db.primaryKey(constraint.table)
chunks.append("""
\(constraint.table.quotedDatabaseIdentifier)(\
\(primaryKey.columns.map { $0.quotedDatabaseIdentifier }.joined(separator: ", "))\
)
""")
}
if let deleteAction = deleteAction {
if let deleteAction = constraint.deleteAction {
chunks.append("ON DELETE")
chunks.append(deleteAction.rawValue)
}
if let updateAction = updateAction {
if let updateAction = constraint.updateAction {
chunks.append("ON UPDATE")
chunks.append(updateAction.rawValue)
}
if deferred {
if constraint.deferred {
chunks.append("DEFERRABLE INITIALLY DEFERRED")
}
items.append(chunks.joined(separator: " "))
@@ -504,7 +623,7 @@ public final class TableDefinition {
for checkExpression in checkConstraints {
var chunks: [String] = []
chunks.append("CHECK (\(checkExpression.quotedSQL(wrappedInParenthesis: false)))")
chunks.append("CHECK (\(checkExpression.quotedSQL()))")
items.append(chunks.joined(separator: " "))
}
@@ -603,13 +722,22 @@ public final class ColumnDefinition {
case index
case unique(Database.ConflictResolution)
}
private struct ForeignKeyConstraint {
var table: String
var column: String?
var deleteAction: Database.ForeignKeyAction?
var updateAction: Database.ForeignKeyAction?
var deferred: Bool
}
fileprivate let name: String
private let type: Database.ColumnType?
fileprivate var primaryKey: (conflictResolution: Database.ConflictResolution?, autoincrement: Bool)?
private var index: Index = .none
private var notNullConflictResolution: Database.ConflictResolution?
private var checkConstraints: [SQLExpression] = []
private var foreignKeyConstraints: [(table: String, column: String?, deleteAction: Database.ForeignKeyAction?, updateAction: Database.ForeignKeyAction?, deferred: Bool)] = []
private var foreignKeyConstraints: [ForeignKeyConstraint] = []
private var defaultExpression: SQLExpression?
private var collationName: String?
@@ -633,7 +761,11 @@ public final class ColumnDefinition {
/// - autoincrement: If true, the primary key is autoincremented.
/// - returns: Self so that you can further refine the column definition.
@discardableResult
public func primaryKey(onConflict conflictResolution: Database.ConflictResolution? = nil, autoincrement: Bool = false) -> Self {
public func primaryKey(
onConflict conflictResolution: Database.ConflictResolution? = nil,
autoincrement: Bool = false)
-> Self
{
primaryKey = (conflictResolution: conflictResolution, autoincrement: autoincrement)
return self
}
@@ -804,8 +936,19 @@ public final class ColumnDefinition {
/// See https://www.sqlite.org/foreignkeys.html#fk_deferred.
/// - returns: Self so that you can further refine the column definition.
@discardableResult
public func references(_ table: String, column: String? = nil, onDelete deleteAction: Database.ForeignKeyAction? = nil, onUpdate updateAction: Database.ForeignKeyAction? = nil, deferred: Bool = false) -> Self {
foreignKeyConstraints.append((table: table, column: column, deleteAction: deleteAction, updateAction: updateAction, deferred: deferred))
public func references(
_ table: String,
column: String? = nil,
onDelete deleteAction: Database.ForeignKeyAction? = nil,
onUpdate updateAction: Database.ForeignKeyAction? = nil,
deferred: Bool = false) -> Self
{
foreignKeyConstraints.append(ForeignKeyConstraint(
table: table,
column: column,
deleteAction: deleteAction,
updateAction: updateAction,
deferred: deferred))
return self
}
@@ -853,11 +996,11 @@ public final class ColumnDefinition {
}
for checkConstraint in checkConstraints {
chunks.append("CHECK (\(checkConstraint.quotedSQL(wrappedInParenthesis: false)))")
chunks.append("CHECK (\(checkConstraint.quotedSQL()))")
}
if let defaultExpression = defaultExpression {
chunks.append("DEFAULT \(defaultExpression.quotedSQL(wrappedInParenthesis: false))")
chunks.append("DEFAULT \(defaultExpression.quotedSQL())")
}
if let collationName = collationName {
@@ -865,29 +1008,37 @@ public final class ColumnDefinition {
chunks.append(collationName)
}
for (table, column, deleteAction, updateAction, deferred) in foreignKeyConstraints {
for constraint in foreignKeyConstraints {
chunks.append("REFERENCES")
if let column = column {
if let column = constraint.column {
// explicit reference
chunks.append("\(table.quotedDatabaseIdentifier)(\(column.quotedDatabaseIdentifier))")
} else if table.lowercased() == tableName.lowercased() {
chunks.append("\(constraint.table.quotedDatabaseIdentifier)(\(column.quotedDatabaseIdentifier))")
} else if constraint.table.lowercased() == tableName.lowercased() {
// implicit autoreference
let primaryKeyColumns = try primaryKeyColumns ?? db.primaryKey(table).columns
chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKeyColumns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
let primaryKeyColumns = try primaryKeyColumns ?? db.primaryKey(constraint.table).columns
chunks.append("""
\(constraint.table.quotedDatabaseIdentifier)(\
\(primaryKeyColumns.map { $0.quotedDatabaseIdentifier }.joined(separator: ", "))\
)
""")
} else {
// implicit external reference
let primaryKeyColumns = try db.primaryKey(table).columns
chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKeyColumns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
let primaryKeyColumns = try db.primaryKey(constraint.table).columns
chunks.append("""
\(constraint.table.quotedDatabaseIdentifier)(\
\(primaryKeyColumns.map { $0.quotedDatabaseIdentifier }.joined(separator: ", "))\
)
""")
}
if let deleteAction = deleteAction {
if let deleteAction = constraint.deleteAction {
chunks.append("ON DELETE")
chunks.append(deleteAction.rawValue)
}
if let updateAction = updateAction {
if let updateAction = constraint.updateAction {
chunks.append("ON UPDATE")
chunks.append(updateAction.rawValue)
}
if deferred {
if constraint.deferred {
chunks.append("DEFERRABLE INITIALLY DEFERRED")
}
}
@@ -931,9 +1082,13 @@ private struct IndexDefinition {
}
chunks.append(name.quotedDatabaseIdentifier)
chunks.append("ON")
chunks.append("\(table.quotedDatabaseIdentifier)(\((columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
chunks.append("""
\(table.quotedDatabaseIdentifier)(\
\(columns.map { $0.quotedDatabaseIdentifier }.joined(separator: ", "))\
)
""")
if let condition = condition {
chunks.append("WHERE \(condition.quotedSQL(wrappedInParenthesis: false))")
chunks.append("WHERE \(condition.quotedSQL())")
}
return chunks.joined(separator: " ")
}
@@ -96,7 +96,13 @@ extension Database {
/// - module: a VirtualTableModule
/// - body: An optional closure that defines the virtual table.
/// - throws: A DatabaseError whenever an SQLite error occurs.
public func create<Module: VirtualTableModule>(virtualTable tableName: String, ifNotExists: Bool = false, using module: Module, _ body: ((Module.TableDefinition) -> Void)? = nil) throws {
public func create<Module: VirtualTableModule>(
virtualTable tableName: String,
ifNotExists: Bool = false,
using module: Module,
_ body: ((Module.TableDefinition) -> Void)? = nil)
throws
{
// Define virtual table
let definition = module.makeTableDefinition()
if let body = body {
@@ -545,7 +545,10 @@ extension TableRecord where Self: EncodableRecord {
///
/// let team: Team = ...
/// let players = try team.players.fetchAll(db) // [Player]
public func request<A: Association>(for association: A) -> QueryInterfaceRequest<A.RowDecoder> where A.OriginRowDecoder == Self {
public func request<A: Association>(for association: A)
-> QueryInterfaceRequest<A.RowDecoder>
where A.OriginRowDecoder == Self
{
let destinationRelation = association.sqlAssociation.destinationRelation(fromOriginRows: { db in
try [Row(PersistenceContainer(db, self))]
})
@@ -558,35 +561,50 @@ extension TableRecord {
// MARK: - Associations
/// Creates a request that prefetches an association.
public static func including<A: AssociationToMany>(all association: A) -> QueryInterfaceRequest<Self> where A.OriginRowDecoder == Self {
public static func including<A: AssociationToMany>(all association: A)
-> QueryInterfaceRequest<Self>
where A.OriginRowDecoder == Self
{
return all().including(all: association)
}
/// Creates a request that includes an association. The columns of the
/// associated record are selected. The returned association does not
/// require that the associated database table contains a matching row.
public static func including<A: Association>(optional association: A) -> QueryInterfaceRequest<Self> where A.OriginRowDecoder == Self {
public static func including<A: Association>(optional association: A)
-> QueryInterfaceRequest<Self>
where A.OriginRowDecoder == Self
{
return all().including(optional: association)
}
/// Creates a request that includes an association. The columns of the
/// associated record are selected. The returned association requires
/// that the associated database table contains a matching row.
public static func including<A: Association>(required association: A) -> QueryInterfaceRequest<Self> where A.OriginRowDecoder == Self {
public static func including<A: Association>(required association: A)
-> QueryInterfaceRequest<Self>
where A.OriginRowDecoder == Self
{
return all().including(required: association)
}
/// Creates a request that includes an association. The columns of the
/// associated record are not selected. The returned association does not
/// require that the associated database table contains a matching row.
public static func joining<A: Association>(optional association: A) -> QueryInterfaceRequest<Self> where A.OriginRowDecoder == Self {
public static func joining<A: Association>(optional association: A)
-> QueryInterfaceRequest<Self>
where A.OriginRowDecoder == Self
{
return all().joining(optional: association)
}
/// Creates a request that includes an association. The columns of the
/// associated record are not selected. The returned association requires
/// that the associated database table contains a matching row.
public static func joining<A: Association>(required association: A) -> QueryInterfaceRequest<Self> where A.OriginRowDecoder == Self {
public static func joining<A: Association>(required association: A)
-> QueryInterfaceRequest<Self>
where A.OriginRowDecoder == Self
{
return all().joining(required: association)
}
@@ -52,7 +52,11 @@ extension TableRecord {
///
/// // SELECT id, email FROM player
/// let request = Player.select(sql: "id, email")
public static func select(sql: String, arguments: StatementArguments = StatementArguments()) -> QueryInterfaceRequest<Self> {
public static func select(
sql: String,
arguments: StatementArguments = StatementArguments())
-> QueryInterfaceRequest<Self>
{
return select(literal: SQLLiteral(sql: sql, arguments: arguments))
}
@@ -72,7 +76,11 @@ extension TableRecord {
/// let request = Player.select([max(Column("score"))], as: Int.self)
/// let maxScore: Int? = try request.fetchOne(db)
/// }
public static func select<RowDecoder>(_ selection: [SQLSelectable], as type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder> {
public static func select<RowDecoder>(
_ selection: [SQLSelectable],
as type: RowDecoder.Type)
-> QueryInterfaceRequest<RowDecoder>
{
return all().select(selection, as: type)
}
@@ -84,7 +92,11 @@ extension TableRecord {
/// let request = Player.select(max(Column("score")), as: Int.self)
/// let maxScore: Int? = try request.fetchOne(db)
/// }
public static func select<RowDecoder>(_ selection: SQLSelectable..., as type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder> {
public static func select<RowDecoder>(
_ selection: SQLSelectable...,
as type: RowDecoder.Type)
-> QueryInterfaceRequest<RowDecoder>
{
return all().select(selection, as: type)
}
@@ -96,7 +108,12 @@ extension TableRecord {
/// let request = Player.select(sql: "max(score)", as: Int.self)
/// let maxScore: Int? = try request.fetchOne(db)
/// }
public static func select<RowDecoder>(sql: String, arguments: StatementArguments = StatementArguments(), as type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder> {
public static func select<RowDecoder>(
sql: String,
arguments: StatementArguments = StatementArguments(),
as type: RowDecoder.Type)
-> QueryInterfaceRequest<RowDecoder>
{
return all().select(literal: SQLLiteral(sql: sql, arguments: arguments), as: type)
}
@@ -108,7 +125,11 @@ extension TableRecord {
/// let request = Player.select(literal: SQLLiteral(sql: "max(score)"), as: Int.self)
/// let maxScore: Int? = try request.fetchOne(db)
/// }
public static func select<RowDecoder>(literal sqlLiteral: SQLLiteral, as type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder> {
public static func select<RowDecoder>(
literal sqlLiteral: SQLLiteral,
as type: RowDecoder.Type)
-> QueryInterfaceRequest<RowDecoder>
{
return all().select(literal: sqlLiteral, as: type)
}
@@ -152,7 +173,10 @@ extension TableRecord {
/// The selection defaults to all columns. This default can be changed for
/// all requests by the `TableRecord.databaseSelection` property, or
/// for individual requests with the `TableRecord.select` method.
public static func filter<PrimaryKeyType: DatabaseValueConvertible>(key: PrimaryKeyType?) -> QueryInterfaceRequest<Self> {
public static func filter<PrimaryKeyType>(key: PrimaryKeyType?)
-> QueryInterfaceRequest<Self>
where PrimaryKeyType: DatabaseValueConvertible
{
return all().filter(key: key)
}
@@ -164,7 +188,10 @@ extension TableRecord {
/// The selection defaults to all columns. This default can be changed for
/// all requests by the `TableRecord.databaseSelection` property, or
/// for individual requests with the `TableRecord.select` method.
public static func filter<Sequence: Swift.Sequence>(keys: Sequence) -> QueryInterfaceRequest<Self> where Sequence.Element: DatabaseValueConvertible {
public static func filter<Sequence>(keys: Sequence)
-> QueryInterfaceRequest<Self>
where Sequence: Swift.Sequence, Sequence.Element: DatabaseValueConvertible
{
return all().filter(keys: keys)
}
@@ -206,7 +233,11 @@ extension TableRecord {
/// The selection defaults to all columns. This default can be changed for
/// all requests by the `TableRecord.databaseSelection` property, or
/// for individual requests with the `TableRecord.select` method.
public static func filter(sql: String, arguments: StatementArguments = StatementArguments()) -> QueryInterfaceRequest<Self> {
public static func filter(
sql: String,
arguments: StatementArguments = StatementArguments())
-> QueryInterfaceRequest<Self>
{
return filter(literal: SQLLiteral(sql: sql, arguments: arguments))
}
@@ -277,7 +308,11 @@ extension TableRecord {
/// The selection defaults to all columns. This default can be changed for
/// all requests by the `TableRecord.databaseSelection` property, or
/// for individual requests with the `TableRecord.select` method.
public static func order(sql: String, arguments: StatementArguments = StatementArguments()) -> QueryInterfaceRequest<Self> {
public static func order(
sql: String,
arguments: StatementArguments = StatementArguments())
-> QueryInterfaceRequest<Self>
{
return all().order(literal: SQLLiteral(sql: sql, arguments: arguments))
}
+35 -18
View File
@@ -45,7 +45,7 @@ private class RecordEncoder<Record: EncodableRecord>: Encoder {
fatalError("single value encoding is not supported")
}
private struct KeyedContainer<Key: CodingKey> : KeyedEncodingContainerProtocol {
private struct KeyedContainer<Key: CodingKey>: KeyedEncodingContainerProtocol {
var recordEncoder: RecordEncoder
var userInfo: [CodingUserInfoKey: Any] { return Record.databaseEncodingUserInfo }
@@ -55,6 +55,7 @@ private class RecordEncoder<Record: EncodableRecord>: Encoder {
var codingPath: [CodingKey] { return [] }
// swiftlint:disable comma
func encode(_ value: Bool, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) }
func encode(_ value: Int, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) }
func encode(_ value: Int8, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) }
@@ -69,13 +70,15 @@ private class RecordEncoder<Record: EncodableRecord>: Encoder {
func encode(_ value: Float, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) }
func encode(_ value: Double, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) }
func encode(_ value: String, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) }
// swiftlint:enable comma
func encode<T>(_ value: T, forKey key: Key) throws where T : Encodable {
func encode<T>(_ value: T, forKey key: Key) throws where T: Encodable {
try recordEncoder.encode(value, forKey: key)
}
func encodeNil(forKey key: Key) throws { recordEncoder.persist(nil, forKey: key) }
// swiftlint:disable comma
func encodeIfPresent(_ value: Bool?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) }
func encodeIfPresent(_ value: Int?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) }
func encodeIfPresent(_ value: Int8?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) }
@@ -90,8 +93,9 @@ private class RecordEncoder<Record: EncodableRecord>: Encoder {
func encodeIfPresent(_ value: Float?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) }
func encodeIfPresent(_ value: Double?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) }
func encodeIfPresent(_ value: String?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) }
// swiftlint:disable comma
func encodeIfPresent<T>(_ value: T?, forKey key: Key) throws where T : Encodable {
func encodeIfPresent<T>(_ value: T?, forKey key: Key) throws where T: Encodable {
if let value = value {
try recordEncoder.encode(value, forKey: key)
} else {
@@ -99,7 +103,11 @@ private class RecordEncoder<Record: EncodableRecord>: Encoder {
}
}
func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey> {
func nestedContainer<NestedKey>(
keyedBy keyType: NestedKey.Type,
forKey key: Key)
-> KeyedEncodingContainer<NestedKey>
{
fatalError("Not implemented")
}
@@ -123,7 +131,7 @@ private class RecordEncoder<Record: EncodableRecord>: Encoder {
}
@inline(__always)
fileprivate func encode<T>(_ value: T, forKey key: CodingKey) throws where T : Encodable {
fileprivate func encode<T>(_ value: T, forKey key: CodingKey) throws where T: Encodable {
if let date = value as? Date {
persist(Record.databaseDateEncodingStrategy.encode(date), forKey: key)
} else if let uuid = value as? UUID {
@@ -151,8 +159,9 @@ private class RecordEncoder<Record: EncodableRecord>: Encoder {
// database inspection. Thanks to SQLite weak typing, we won't
// have any trouble decoding this string into data when we
// eventually perform JSON decoding.
// TODO: possible optimization: avoid this conversion to string, and store raw data bytes as an SQLite string
let jsonString = String(data: jsonData, encoding: .utf8)! // force unwrap because json data is guaranteed to convert to String
// TODO: possible optimization: avoid this conversion to string,
// and store raw data bytes as an SQLite string
let jsonString = String(data: jsonData, encoding: .utf8)!
persist(jsonString, forKey: key)
}
}
@@ -174,7 +183,7 @@ private class ColumnEncoder<Record: EncodableRecord>: Encoder {
self.key = key
}
func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> where Key : CodingKey {
func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> where Key: CodingKey {
// Keyed values require JSON encoding: we need to throw
// JSONRequiredError. Since we can't throw right from here, let's
// delegate the job to a dedicated container.
@@ -214,7 +223,7 @@ extension ColumnEncoder: SingleValueEncodingContainer {
func encode(_ value: Double) throws { recordEncoder.persist(value, forKey: key) }
func encode(_ value: String) throws { recordEncoder.persist(value, forKey: key) }
func encode<T>(_ value: T) throws where T : Encodable {
func encode<T>(_ value: T) throws where T: Encodable {
try recordEncoder.encode(value, forKey: key)
}
}
@@ -233,7 +242,7 @@ private struct JSONRequiredEncoder<Record: EncodableRecord>: Encoder {
self.codingPath = codingPath
}
func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> where Key : CodingKey {
func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> where Key: CodingKey {
let container = KeyedContainer<Key>(codingPath: codingPath)
return KeyedEncodingContainer(container)
}
@@ -265,9 +274,14 @@ private struct JSONRequiredEncoder<Record: EncodableRecord>: Encoder {
func encode(_ value: Float, forKey key: KeyType) throws { throw JSONRequiredError() }
func encode(_ value: Double, forKey key: KeyType) throws { throw JSONRequiredError() }
func encode(_ value: String, forKey key: KeyType) throws { throw JSONRequiredError() }
func encode<T>(_ value: T, forKey key: KeyType) throws where T : Encodable { throw JSONRequiredError() }
func encode<T>(_ value: T, forKey key: KeyType) throws where T: Encodable { throw JSONRequiredError() }
func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: KeyType) -> KeyedEncodingContainer<NestedKey> where NestedKey : CodingKey {
func nestedContainer<NestedKey>(
keyedBy keyType: NestedKey.Type,
forKey key: KeyType)
-> KeyedEncodingContainer<NestedKey>
where NestedKey: CodingKey
{
let container = KeyedContainer<NestedKey>(codingPath: codingPath + [key])
return KeyedEncodingContainer(container)
}
@@ -302,13 +316,16 @@ extension JSONRequiredEncoder: SingleValueEncodingContainer {
func encode(_ value: Float ) throws { throw JSONRequiredError() }
func encode(_ value: Double) throws { throw JSONRequiredError() }
func encode(_ value: String) throws { throw JSONRequiredError() }
func encode<T>(_ value: T) throws where T : Encodable { throw JSONRequiredError() }
func encode<T>(_ value: T) throws where T: Encodable { throw JSONRequiredError() }
}
extension JSONRequiredEncoder: UnkeyedEncodingContainer {
var count: Int { return 0 }
mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer<NestedKey> where NestedKey : CodingKey {
mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type)
-> KeyedEncodingContainer<NestedKey>
where NestedKey: CodingKey
{
let container = KeyedContainer<NestedKey>(codingPath: codingPath)
return KeyedEncodingContainer(container)
}
@@ -329,9 +346,9 @@ fileprivate var iso8601Formatter: ISO8601DateFormatter = {
return formatter
}()
private extension DatabaseDateEncodingStrategy {
extension DatabaseDateEncodingStrategy {
@inline(__always)
func encode(_ date: Date) -> DatabaseValueConvertible? {
fileprivate func encode(_ date: Date) -> DatabaseValueConvertible? {
switch self {
case .deferredToDate:
return date.databaseValue
@@ -357,9 +374,9 @@ private extension DatabaseDateEncodingStrategy {
}
}
private extension DatabaseUUIDEncodingStrategy {
extension DatabaseUUIDEncodingStrategy {
@inline(__always)
func encode(_ uuid: UUID) -> DatabaseValueConvertible? {
fileprivate func encode(_ uuid: UUID) -> DatabaseValueConvertible? {
switch self {
case .deferredToUUID:
return uuid.databaseValue
+2 -1
View File
@@ -171,7 +171,8 @@ extension EncodableRecord {
/// same set of columns in their `encode(to:)` method, only the columns
/// defined by the receiver record are considered.
public func databaseChanges<Record: EncodableRecord>(from record: Record) -> [String: DatabaseValue] {
return Dictionary(uniqueKeysWithValues: PersistenceContainer(self).changesIterator(from: PersistenceContainer(record)))
let changes = PersistenceContainer(self).changesIterator(from: PersistenceContainer(record))
return Dictionary(uniqueKeysWithValues: changes)
}
}
+52 -21
View File
@@ -1,10 +1,10 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
extension FetchableRecord where Self: Decodable {
@@ -85,6 +85,7 @@ private struct RowDecoder<R: FetchableRecord>: Decoder {
return row[key.stringValue] == nil && (row.scopesTree[key.stringValue] == nil)
}
// swiftlint:disable comma
func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { return decoder.row[key.stringValue] }
func decode(_ type: Int.Type, forKey key: Key) throws -> Int { return decoder.row[key.stringValue] }
func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { return decoder.row[key.stringValue] }
@@ -99,8 +100,9 @@ private struct RowDecoder<R: FetchableRecord>: Decoder {
func decode(_ type: Float.Type, forKey key: Key) throws -> Float { return decoder.row[key.stringValue] }
func decode(_ type: Double.Type, forKey key: Key) throws -> Double { return decoder.row[key.stringValue] }
func decode(_ type: String.Type, forKey key: Key) throws -> String { return decoder.row[key.stringValue] }
// swiftlint:enable comma
func decodeIfPresent<T>(_ type: T.Type, forKey key: Key) throws -> T? where T : Decodable {
func decodeIfPresent<T>(_ type: T.Type, forKey key: Key) throws -> T? where T: Decodable {
let row = decoder.row
let keyName = key.stringValue
@@ -130,7 +132,7 @@ private struct RowDecoder<R: FetchableRecord>: Decoder {
return nil
}
func decode<T>(_ type: T.Type, forKey key: Key) throws -> T where T : Decodable {
func decode<T>(_ type: T.Type, forKey key: Key) throws -> T where T: Decodable {
let row = decoder.row
let keyName = key.stringValue
@@ -159,7 +161,7 @@ private struct RowDecoder<R: FetchableRecord>: Decoder {
let decoder = PrefetchedRowsDecoder<R>(rows: prefetchedRows, codingPath: codingPath)
return try T(from: decoder)
}
// Key is not a column, and not a scope.
//
// Should be throw an error? Well... The use case is the following:
@@ -193,7 +195,9 @@ private struct RowDecoder<R: FetchableRecord>: Decoder {
return try decode(type, fromRow: row, codingPath: codingPath + [key])
}
func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> where NestedKey : CodingKey {
func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key)
throws -> KeyedDecodingContainer<NestedKey> where NestedKey: CodingKey
{
fatalError("not implemented")
}
@@ -215,7 +219,13 @@ private struct RowDecoder<R: FetchableRecord>: Decoder {
// Helper methods
@inline(__always)
private func decode<T>(_ type: T.Type, fromRow row: Row, codingPath: [CodingKey]) throws -> T where T: Decodable {
private func decode<T>(
_ type: T.Type,
fromRow row: Row,
codingPath: [CodingKey])
throws -> T
where T: Decodable
{
if let type = T.self as? FetchableRecord.Type {
// Prefer FetchableRecord decoding over Decodable.
return type.init(row: row) as! T
@@ -234,7 +244,14 @@ private struct RowDecoder<R: FetchableRecord>: Decoder {
}
@inline(__always)
private func decode<T>(_ type: T.Type, fromRow row: Row, columnAtIndex index: Int, key: Key) throws -> T where T: Decodable {
private func decode<T>(
_ type: T.Type,
fromRow row: Row,
columnAtIndex index: Int,
key: Key)
throws -> T
where T: Decodable
{
do {
// This decoding will fail for types that decode from keyed
// or unkeyed containers, because we're decoding a single
@@ -248,7 +265,10 @@ private struct RowDecoder<R: FetchableRecord>: Decoder {
} catch is JSONRequiredError {
// Decode from JSON
guard let data = row.dataNoCopy(atIndex: index) else {
fatalConversionError(to: T.self, from: row[index], conversionContext: ValueConversionContext(row).atColumn(index))
fatalConversionError(
to: T.self,
from: row[index],
conversionContext: ValueConversionContext(row).atColumn(index))
}
return try R
.databaseJSONDecoder(for: key.stringValue)
@@ -272,7 +292,7 @@ private struct PrefetchedRowsDecoder<R: FetchableRecord>: Decoder {
self.currentIndex = 0
}
func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> where Key : CodingKey {
func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> where Key: CodingKey {
fatalError("keyed decoding from prefetched rows is not supported")
}
@@ -298,13 +318,16 @@ extension PrefetchedRowsDecoder: UnkeyedDecodingContainer {
return false
}
mutating func decode<T>(_ type: T.Type) throws -> T where T : Decodable {
mutating func decode<T>(_ type: T.Type) throws -> T where T: Decodable {
defer { currentIndex += 1 }
let decoder = RowDecoder<R>(row: rows[currentIndex], codingPath: codingPath)
return try T(from: decoder)
}
mutating func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer<NestedKey> where NestedKey : CodingKey {
mutating func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type)
throws -> KeyedDecodingContainer<NestedKey>
where NestedKey: CodingKey
{
fatalError("not implemented")
}
@@ -361,7 +384,7 @@ extension ColumnDecoder: SingleValueDecodingContainer {
func decode(_ type: Double.Type) throws -> Double { return row[columnIndex] }
func decode(_ type: String.Type) throws -> String { return row[columnIndex] }
func decode<T>(_ type: T.Type) throws -> T where T : Decodable {
func decode<T>(_ type: T.Type) throws -> T where T: Decodable {
// Prefer DatabaseValueConvertible decoding over Decodable.
// This allows decoding Date from String, or DatabaseValue from NULL.
if type == Date.self {
@@ -391,9 +414,9 @@ fileprivate var iso8601Formatter: ISO8601DateFormatter = {
return formatter
}()
private extension DatabaseDateDecodingStrategy {
extension DatabaseDateDecodingStrategy {
@inline(__always)
func decodeIfPresent(fromRow row: Row, columnAtIndex index: Int) -> Date? {
fileprivate func decodeIfPresent(fromRow row: Row, columnAtIndex index: Int) -> Date? {
if let sqliteStatement = row.sqliteStatement {
return decodeIfPresent(
sqliteStatement: sqliteStatement,
@@ -406,7 +429,7 @@ private extension DatabaseDateDecodingStrategy {
}
@inline(__always)
func decode(fromRow row: Row, columnAtIndex index: Int) -> Date {
fileprivate func decode(fromRow row: Row, columnAtIndex index: Int) -> Date {
if let sqliteStatement = row.sqliteStatement {
return decode(
sqliteStatement: sqliteStatement,
@@ -419,7 +442,7 @@ private extension DatabaseDateDecodingStrategy {
}
@inline(__always)
func decode(sqliteStatement: SQLiteStatement, index: Int32) -> Date {
fileprivate func decode(sqliteStatement: SQLiteStatement, index: Int32) -> Date {
switch self {
case .deferredToDate:
return Date(sqliteStatement: sqliteStatement, index: index)
@@ -458,7 +481,7 @@ private extension DatabaseDateDecodingStrategy {
}
@inline(__always)
func decodeIfPresent(sqliteStatement: SQLiteStatement, index: Int32) -> Date? {
fileprivate func decodeIfPresent(sqliteStatement: SQLiteStatement, index: Int32) -> Date? {
if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL {
return nil
}
@@ -466,7 +489,11 @@ private extension DatabaseDateDecodingStrategy {
}
@inline(__always)
func decode(from dbValue: DatabaseValue, conversionContext: @autoclosure () -> ValueConversionContext?) -> Date {
fileprivate func decode(
from dbValue: DatabaseValue,
conversionContext: @autoclosure () -> ValueConversionContext?)
-> Date
{
if let date = dateFromDatabaseValue(dbValue) {
return date
} else {
@@ -475,7 +502,11 @@ private extension DatabaseDateDecodingStrategy {
}
@inline(__always)
func decodeIfPresent(from dbValue: DatabaseValue, conversionContext: @autoclosure () -> ValueConversionContext?) -> Date? {
fileprivate func decodeIfPresent(
from dbValue: DatabaseValue,
conversionContext: @autoclosure () -> ValueConversionContext?)
-> Date?
{
if dbValue.isNull {
return nil
} else if let date = dateFromDatabaseValue(dbValue) {
+22 -6
View File
@@ -77,7 +77,10 @@ extension FetchableRecord where Self: TableRecord {
/// - keys: A sequence of primary keys.
/// - returns: A cursor over fetched records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) throws -> RecordCursor<Self> where Sequence.Element: DatabaseValueConvertible {
public static func fetchCursor<Sequence>(_ db: Database, keys: Sequence)
throws -> RecordCursor<Self>
where Sequence: Swift.Sequence, Sequence.Element: DatabaseValueConvertible
{
return try filter(keys: keys).fetchCursor(db)
}
@@ -92,7 +95,9 @@ extension FetchableRecord where Self: TableRecord {
/// - keys: A sequence of primary keys.
/// - returns: An array of records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) throws -> [Self] where Sequence.Element: DatabaseValueConvertible {
public static func fetchAll<Sequence>(_ db: Database, keys: Sequence)
throws -> [Self]
where Sequence: Swift.Sequence, Sequence.Element: DatabaseValueConvertible {
let keys = Array(keys)
if keys.isEmpty {
// Avoid hitting the database
@@ -110,7 +115,10 @@ extension FetchableRecord where Self: TableRecord {
/// - key: A primary key value.
/// - returns: An optional record.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne<PrimaryKeyType: DatabaseValueConvertible>(_ db: Database, key: PrimaryKeyType?) throws -> Self? {
public static func fetchOne<PrimaryKeyType>(_ db: Database, key: PrimaryKeyType?)
throws -> Self?
where PrimaryKeyType: DatabaseValueConvertible
{
guard let key = key else {
// Avoid hitting the database
return nil
@@ -126,7 +134,10 @@ extension FetchableRecord where Self: TableRecord {
/// Returns a cursor over records identified by the provided unique keys
/// (primary key or any key with a unique index on it).
///
/// let players = try Player.fetchCursor(db, keys: [["email": "a@example.com"], ["email": "b@example.com"]]) // Cursor of Player
/// // Cursor of Player
/// let players = try Player.fetchCursor(db, keys: [
/// ["email": "a@example.com"],
/// ["email": "b@example.com"]])
/// while let player = try players.next() { // Player
/// ...
/// }
@@ -138,14 +149,19 @@ extension FetchableRecord where Self: TableRecord {
/// - keys: An array of key dictionaries.
/// - returns: A cursor over fetched records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> RecordCursor<Self> {
public static func fetchCursor(_ db: Database, keys: [[String: DatabaseValueConvertible?]])
throws -> RecordCursor<Self>
{
return try filter(keys: keys).fetchCursor(db)
}
/// Returns an array of records identified by the provided unique keys
/// (primary key or any key with a unique index on it).
///
/// let players = try Player.fetchAll(db, keys: [["email": "a@example.com"], ["email": "b@example.com"]]) // [Player]
/// // [Player]
/// let players = try Player.fetchAll(db, keys: [
/// ["email": "a@example.com"],
/// ["email": "b@example.com"]])
///
/// The order of records in the returned array is undefined.
///
+44 -11
View File
@@ -1,10 +1,10 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
/// Types that adopt FetchableRecord can be initialized from a database Row.
@@ -160,7 +160,12 @@ extension FetchableRecord {
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RecordCursor<Self> {
public static func fetchCursor(
_ statement: SelectStatement,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> RecordCursor<Self>
{
return try RecordCursor(statement: statement, arguments: arguments, adapter: adapter)
}
@@ -175,7 +180,12 @@ extension FetchableRecord {
/// - adapter: Optional RowAdapter
/// - returns: An array of records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] {
public static func fetchAll(
_ statement: SelectStatement,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> [Self]
{
return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
}
@@ -190,7 +200,12 @@ extension FetchableRecord {
/// - adapter: Optional RowAdapter
/// - returns: An optional record.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? {
public static func fetchOne(
_ statement: SelectStatement,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> Self?
{
return try fetchCursor(statement, arguments: arguments, adapter: adapter).next()
}
}
@@ -218,7 +233,13 @@ extension FetchableRecord {
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> RecordCursor<Self> {
public static func fetchCursor(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: RowAdapter? = nil)
throws -> RecordCursor<Self>
{
return try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
@@ -233,7 +254,13 @@ extension FetchableRecord {
/// - adapter: Optional RowAdapter
/// - returns: An array of records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Self] {
public static func fetchAll(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: RowAdapter? = nil)
throws -> [Self]
{
return try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
@@ -248,7 +275,13 @@ extension FetchableRecord {
/// - adapter: Optional RowAdapter
/// - returns: An optional record.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> Self? {
public static func fetchOne(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: RowAdapter? = nil)
throws -> Self?
{
return try fetchOne(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
}
@@ -319,7 +352,7 @@ extension FetchableRecord {
return nil
}
try supplementaryFetch([row])
return Self.init(row: row)
return .init(row: row)
} else {
return try fetchOne(request.statement, adapter: request.adapter)
}
@@ -385,7 +418,7 @@ extension FetchRequest where RowDecoder: FetchableRecord {
/// try dbQueue.read { db in
/// let players: RecordCursor<Player> = try Player.fetchCursor(db, sql: "SELECT * FROM player")
/// }
public final class RecordCursor<Record: FetchableRecord> : Cursor {
public final class RecordCursor<Record: FetchableRecord>: Cursor {
@usableFromInline let _statement: SelectStatement
@usableFromInline let _row: Row // Reused for performance
@usableFromInline let _sqliteStatement: SQLiteStatement
Loaded 100 of 122 files, more files were not shown because too many files have changed in this diff. Show more