diff --git a/CHANGELOG.md b/CHANGELOG.md index 6b54eba56..15a50c726 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,14 +1,52 @@ Release Notes ============= -## Next version +## 0.78.0 + +Released August 6, 2016 **New** - Upgrade sqlcipher to v3.4.0 ([announcement](https://discuss.zetetic.net/t/sqlcipher-3-4-0-release/1273), [changelog](https://github.com/sqlcipher/sqlcipher/blob/master/CHANGELOG.md)) -- Row adopts DictionaryLiteralConvertible +- Row adopts DictionaryLiteralConvertible: + + ```swift + let row: Row = ["name": "foo", "date": NSDate()] + ``` + +- DSL for table creation and updates (closes [#83](https://github.com/groue/GRDB.swift/issues/83), [documentation](https://github.com/groue/GRDB.swift#database-schema)): + + ```swift + db.create(table: "pointOfInterests") { t in + t.column("id", .Integer).primaryKey() + t.column("title", .Text) + t.column("favorite", .Boolean).notNull() + t.column("longitude", .Double).notNull() + t.column("latitude", .Double).notNull() + } + ``` + +- Support for the `length` SQLite built-in function: + ```swift + db.create(table: "persons") { t in + t.column("name", .Text).check { length($0) > 0 } + } + ``` + + +**Breaking Changes** + +- Built-in SQLite collations used to be named by string: "NOCASE", etc. Now use the SQLCollation enum: `.Nocase`, etc. + +- PrimaryKey has been renamed PrimaryKeyInfo: + + ```swift + let pk = db.primaryKey("persons") + pk.columns // ["id"] + ``` + ## 0.77.0 diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index 09e21b62e..be6de65c9 100644 --- a/GRDB.swift.podspec +++ b/GRDB.swift.podspec @@ -1,8 +1,8 @@ Pod::Spec.new do |s| s.name = 'GRDB.swift' - s.version = '0.77.0' + s.version = '0.78.0' s.license = { :type => 'MIT', :file => 'LICENSE' } - s.summary = 'A versatile SQLite toolkit for Swift, with WAL mode support.' + s.summary = 'A Swift application toolkit for SQLite databases.' s.homepage = 'https://github.com/groue/GRDB.swift' s.author = { 'Gwendal Roué' => 'gr@pierlis.com' } s.source = { :git => 'https://github.com/groue/GRDB.swift.git', :tag => "v#{s.version}" } diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index be2cb737b..3b2b8b278 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -350,6 +350,20 @@ 565F03C31CE5D3AA00DE108F /* AdapterRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565F03C11CE5D3AA00DE108F /* AdapterRowTests.swift */; }; 565F03C41CE5D3AA00DE108F /* AdapterRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565F03C11CE5D3AA00DE108F /* AdapterRowTests.swift */; }; 565F03C71CE5D3AA00DE108F /* AdapterRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565F03C11CE5D3AA00DE108F /* AdapterRowTests.swift */; }; + 566AD8B21D5318F4002EC1A8 /* SQLTableBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* SQLTableBuilder.swift */; }; + 566AD8B31D5318F4002EC1A8 /* SQLTableBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* SQLTableBuilder.swift */; }; + 566AD8B41D5318F4002EC1A8 /* SQLTableBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* SQLTableBuilder.swift */; }; + 566AD8B51D5318F4002EC1A8 /* SQLTableBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* SQLTableBuilder.swift */; }; + 566AD8B61D5318F4002EC1A8 /* SQLTableBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* SQLTableBuilder.swift */; }; + 566AD8B71D5318F4002EC1A8 /* SQLTableBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* SQLTableBuilder.swift */; }; + 566AD8C61D531BE4002EC1A8 /* SQLTableBuilderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8C51D531BE4002EC1A8 /* SQLTableBuilderTests.swift */; }; + 566AD8C71D531BEA002EC1A8 /* SQLTableBuilderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8C51D531BE4002EC1A8 /* SQLTableBuilderTests.swift */; }; + 566AD8C81D531BEB002EC1A8 /* SQLTableBuilderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8C51D531BE4002EC1A8 /* SQLTableBuilderTests.swift */; }; + 566AD8C91D531BEB002EC1A8 /* SQLTableBuilderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8C51D531BE4002EC1A8 /* SQLTableBuilderTests.swift */; }; + 566AD8CA1D531BEC002EC1A8 /* SQLTableBuilderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8C51D531BE4002EC1A8 /* SQLTableBuilderTests.swift */; }; + 566AD8CB1D531BED002EC1A8 /* SQLTableBuilderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8C51D531BE4002EC1A8 /* SQLTableBuilderTests.swift */; }; + 566AD8CC1D531BEE002EC1A8 /* SQLTableBuilderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8C51D531BE4002EC1A8 /* SQLTableBuilderTests.swift */; }; + 566AD8CD1D531BEE002EC1A8 /* SQLTableBuilderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8C51D531BE4002EC1A8 /* SQLTableBuilderTests.swift */; }; 567156141CB141D0007DC145 /* InMemoryDatabaseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238141B9C74A90082EB20 /* InMemoryDatabaseTests.swift */; }; 567156161CB142AA007DC145 /* ReadOnlyDatabaseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156151CB142AA007DC145 /* ReadOnlyDatabaseTests.swift */; }; 567156171CB142AA007DC145 /* ReadOnlyDatabaseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156151CB142AA007DC145 /* ReadOnlyDatabaseTests.swift */; }; @@ -1445,6 +1459,8 @@ 565D5D731BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "StatementArguments+FoundationTests.swift"; sourceTree = ""; }; 565EFAED1D0436CE00A8FA9D /* NumericOverflowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NumericOverflowTests.swift; sourceTree = ""; }; 565F03C11CE5D3AA00DE108F /* AdapterRowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AdapterRowTests.swift; sourceTree = ""; }; + 566AD8B11D5318F4002EC1A8 /* SQLTableBuilder.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLTableBuilder.swift; sourceTree = ""; }; + 566AD8C51D531BE4002EC1A8 /* SQLTableBuilderTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLTableBuilderTests.swift; sourceTree = ""; }; 567156151CB142AA007DC145 /* ReadOnlyDatabaseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ReadOnlyDatabaseTests.swift; sourceTree = ""; }; 5671566C1CB16729007DC145 /* GRDBCipherOSXEncryptedTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBCipherOSXEncryptedTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 567156701CB18050007DC145 /* EncryptionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EncryptionTests.swift; sourceTree = ""; }; @@ -1881,6 +1897,7 @@ 5605F18A1C6B1A8700235C62 /* SQLFunction.swift */, 5605F18B1C6B1A8700235C62 /* SQLOperator.swift */, 5605F18C1C6B1A8700235C62 /* SQLSelectQuery.swift */, + 566AD8B11D5318F4002EC1A8 /* SQLTableBuilder.swift */, ); path = QueryInterface; sourceTree = ""; @@ -1913,6 +1930,14 @@ path = Collation; sourceTree = ""; }; + 566AD8C41D531BD0002EC1A8 /* SQLTableBuilder */ = { + isa = PBXGroup; + children = ( + 566AD8C51D531BE4002EC1A8 /* SQLTableBuilderTests.swift */, + ); + path = SQLTableBuilder; + sourceTree = ""; + }; 5671566F1CB18039007DC145 /* Encryption */ = { isa = PBXGroup; children = ( @@ -1980,6 +2005,7 @@ 56A238231B9C74A90082EB20 /* Migrations */, 56300B5C1C53C38F005A543B /* QueryInterfaceRequest */, 56A238251B9C74A90082EB20 /* Record */, + 566AD8C41D531BD0002EC1A8 /* SQLTableBuilder */, ); path = Public; sourceTree = ""; @@ -3187,6 +3213,7 @@ 5657AAAB1D106E39006283EF /* NSDate.swift in Sources */, 560FC53A1CB003810014AA8E /* NSNull.swift in Sources */, 560FC53B1CB003810014AA8E /* Database.swift in Sources */, + 566AD8B31D5318F4002EC1A8 /* SQLTableBuilder.swift in Sources */, 560FC53C1CB003810014AA8E /* DatabaseQueue.swift in Sources */, 560FC53D1CB003810014AA8E /* NSNumber.swift in Sources */, 560FC53E1CB003810014AA8E /* DatabaseValue+Foundation.swift in Sources */, @@ -3233,6 +3260,7 @@ 560FC5771CB00B880014AA8E /* DatabaseQueueSchemaCacheTests.swift in Sources */, 56AF746C1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */, 56B14E801D4DAE54000BF4A3 /* RowAsDictionaryLiteralConvertibleTests.swift in Sources */, + 566AD8C71D531BEA002EC1A8 /* SQLTableBuilderTests.swift in Sources */, 560FC5781CB00B880014AA8E /* MetalRowTests.swift in Sources */, 5672DE681CDB751D0022BA81 /* DatabasePoolBackupTests.swift in Sources */, 560FC5791CB00B880014AA8E /* PrimaryKeyMultipleTests.swift in Sources */, @@ -3347,6 +3375,7 @@ 56C3F7551CF9F12400F6A361 /* SavepointTests.swift in Sources */, 5672DE5B1CDB72520022BA81 /* DatabaseQueueBackupTests.swift in Sources */, 56B14E811D4DAE54000BF4A3 /* RowAsDictionaryLiteralConvertibleTests.swift in Sources */, + 566AD8C81D531BEB002EC1A8 /* SQLTableBuilderTests.swift in Sources */, 567156311CB16729007DC145 /* RecordFetchTests.swift in Sources */, 567156321CB16729007DC145 /* DatabasePoolFunctionTests.swift in Sources */, 567156341CB16729007DC145 /* DetachedRowTests.swift in Sources */, @@ -3466,6 +3495,7 @@ 5657AAAE1D106E39006283EF /* NSDate.swift in Sources */, 56AFCA101CB1A8BB00F48B96 /* DatabaseQueue.swift in Sources */, 56AFCA111CB1A8BB00F48B96 /* DatabaseError.swift in Sources */, + 566AD8B61D5318F4002EC1A8 /* SQLTableBuilder.swift in Sources */, 56AFCA121CB1A8BB00F48B96 /* NSNumber.swift in Sources */, 56AFCA131CB1A8BB00F48B96 /* DatabaseValue+Foundation.swift in Sources */, 56AFCA141CB1A8BB00F48B96 /* StandardLibrary.swift in Sources */, @@ -3514,6 +3544,7 @@ 5672DE6B1CDB751D0022BA81 /* DatabasePoolBackupTests.swift in Sources */, 56B15D0C1CD4C35100A24C8B /* FetchedRecordsControlleriOSTests.swift in Sources */, 56AFCA4A1CB1AA9900F48B96 /* RecordInitializersTests.swift in Sources */, + 566AD8CB1D531BED002EC1A8 /* SQLTableBuilderTests.swift in Sources */, 56AFCA4B1CB1AA9900F48B96 /* MutablePersistableTests.swift in Sources */, 5657AB431D108BA9006283EF /* NSDataTests.swift in Sources */, 56AFCA4C1CB1AA9900F48B96 /* RowConvertible+QueryInterfaceRequestTests.swift in Sources */, @@ -3623,6 +3654,7 @@ 5690C32C1D23E6D800E59934 /* DateComponentsTests.swift in Sources */, 56AFCAA21CB1ABC800F48B96 /* StatementArgumentsTests.swift in Sources */, 56AFCAA31CB1ABC800F48B96 /* RecordInitializersTests.swift in Sources */, + 566AD8CC1D531BEE002EC1A8 /* SQLTableBuilderTests.swift in Sources */, 56AFCAA41CB1ABC800F48B96 /* MutablePersistableTests.swift in Sources */, 56AFCAA51CB1ABC800F48B96 /* RowConvertible+QueryInterfaceRequestTests.swift in Sources */, 56AFCAA61CB1ABC800F48B96 /* DatabasePoolReadOnlyTests.swift in Sources */, @@ -3731,6 +3763,7 @@ 5657AAAD1D106E39006283EF /* NSDate.swift in Sources */, 56A238841B9C75030082EB20 /* DatabaseQueue.swift in Sources */, 56A238821B9C75030082EB20 /* DatabaseError.swift in Sources */, + 566AD8B51D5318F4002EC1A8 /* SQLTableBuilder.swift in Sources */, 5605F1681C672E4000235C62 /* NSNumber.swift in Sources */, 5605F1601C672E4000235C62 /* DatabaseValue+Foundation.swift in Sources */, 5605F1741C672E4000235C62 /* StandardLibrary.swift in Sources */, @@ -3773,6 +3806,7 @@ 56C3F7561CF9F12400F6A361 /* SavepointTests.swift in Sources */, 569531271C9087B700CF1A2B /* DatabaseQueueSchemaCacheTests.swift in Sources */, 56B14E831D4DAE54000BF4A3 /* RowAsDictionaryLiteralConvertibleTests.swift in Sources */, + 566AD8CA1D531BEC002EC1A8 /* SQLTableBuilderTests.swift in Sources */, 56A238541B9C74A90082EB20 /* PrimaryKeyMultipleTests.swift in Sources */, 56FDECE31BB32DFD009AD709 /* MetalRowTests.swift in Sources */, 56DE7B121C3D93ED00861EB8 /* StatementArgumentsTests.swift in Sources */, @@ -3862,6 +3896,7 @@ 561667011D08A49900ADD404 /* NSDecimalNumberTests.swift in Sources */, 569C1EB21CF07DDD0042627B /* DatabaseSchedulerTests.swift in Sources */, 56A238451B9C74A90082EB20 /* DictionaryRowTests.swift in Sources */, + 566AD8C61D531BE4002EC1A8 /* SQLTableBuilderTests.swift in Sources */, 56A238491B9C74A90082EB20 /* SelectStatementTests.swift in Sources */, 56B7F4371BE4C11200E39BBF /* DatabaseCoderTests.swift in Sources */, 56A8C2401D1918ED0096E9D4 /* UUIDTests.swift in Sources */, @@ -3993,6 +4028,7 @@ 5657AAAA1D106E39006283EF /* NSDate.swift in Sources */, 5605F1651C672E4000235C62 /* NSNull.swift in Sources */, 56A2387D1B9C75030082EB20 /* Database.swift in Sources */, + 566AD8B21D5318F4002EC1A8 /* SQLTableBuilder.swift in Sources */, 56A238831B9C75030082EB20 /* DatabaseQueue.swift in Sources */, 5605F1671C672E4000235C62 /* NSNumber.swift in Sources */, 5605F15F1C672E4000235C62 /* DatabaseValue+Foundation.swift in Sources */, @@ -4050,6 +4086,7 @@ F3BA80251CFB288C003DC1BA /* Row+Foundation.swift in Sources */, F3BA80211CFB288C003DC1BA /* NSNull.swift in Sources */, F3BA80141CFB2876003DC1BA /* DatabaseValueConvertible.swift in Sources */, + 566AD8B71D5318F4002EC1A8 /* SQLTableBuilder.swift in Sources */, F3BA80121CFB2876003DC1BA /* DatabaseStore.swift in Sources */, F3BA802C1CFB289B003DC1BA /* SQLCollation.swift in Sources */, F3BA80241CFB288C003DC1BA /* NSURL.swift in Sources */, @@ -4091,6 +4128,7 @@ F3BA80F81CFB3021003DC1BA /* StatementArgumentsTests.swift in Sources */, F3BA80E91CFB3016003DC1BA /* AdapterRowTests.swift in Sources */, 56B14E861D4DAE54000BF4A3 /* RowAsDictionaryLiteralConvertibleTests.swift in Sources */, + 566AD8CD1D531BEE002EC1A8 /* SQLTableBuilderTests.swift in Sources */, F3BA80D11CFB2FF3003DC1BA /* MutablePersistableTests.swift in Sources */, F3BA80CF1CFB2FEA003DC1BA /* DatabaseSchedulerTests.swift in Sources */, F3BA80E71CFB3016003DC1BA /* DetachedRowTests.swift in Sources */, @@ -4210,6 +4248,7 @@ F3BA80811CFB2E61003DC1BA /* Row+Foundation.swift in Sources */, F3BA807D1CFB2E61003DC1BA /* NSNull.swift in Sources */, F3BA80701CFB2E55003DC1BA /* DatabaseValueConvertible.swift in Sources */, + 566AD8B41D5318F4002EC1A8 /* SQLTableBuilder.swift in Sources */, F3BA806E1CFB2E55003DC1BA /* DatabaseStore.swift in Sources */, F3BA80881CFB2E70003DC1BA /* SQLCollation.swift in Sources */, F3BA80801CFB2E61003DC1BA /* NSURL.swift in Sources */, @@ -4238,6 +4277,7 @@ 561667041D08A49900ADD404 /* NSDecimalNumberTests.swift in Sources */, F3BA80BF1CFB2FD2003DC1BA /* DatabasePoolBackupTests.swift in Sources */, F3BA80E31CFB300F003DC1BA /* DatabaseValueConvertibleSubclassTests.swift in Sources */, + 566AD8C91D531BEB002EC1A8 /* SQLTableBuilderTests.swift in Sources */, F3BA81361CFB3064003DC1BA /* RecordFetchTests.swift in Sources */, F3BA80AC1CFB2FA6003DC1BA /* DatabaseQueueSchemaCacheTests.swift in Sources */, 56A8C2461D1918EF0096E9D4 /* UUIDTests.swift in Sources */, diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index f49c74bb9..11a9c2024 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -800,7 +800,7 @@ extension Database { /// primary key. /// /// - throws: A DatabaseError if table does not exist. - public func primaryKey(_ tableName: String) throws -> PrimaryKey? { + public func primaryKey(_ tableName: String) throws -> PrimaryKeyInfo? { SchedulingWatchdog.preconditionValidQueue(self) if let primaryKey = schemaCache.primaryKey(tableName) { @@ -833,7 +833,7 @@ extension Database { let columns = try self.columns(in: tableName) - let primaryKey: PrimaryKey? + let primaryKey: PrimaryKeyInfo? let pkColumns = columns .filter { $0.primaryKeyIndex > 0 } .sorted { $0.primaryKeyIndex < $1.primaryKeyIndex } @@ -1057,7 +1057,7 @@ public struct IndexInfo { /// let citizenshipsPk = db.primaryKey("citizenships")! /// citizenshipsPk.columns // ["personID", "countryIsoCode"] /// citizenshipsPk.rowIDColumn // nil -public struct PrimaryKey { +public struct PrimaryKeyInfo { private enum Impl { /// An INTEGER PRIMARY KEY column that aliases the Row ID. /// Associated string is the column name. @@ -1070,13 +1070,13 @@ public struct PrimaryKey { private let impl: Impl - static func rowID(_ column: String) -> PrimaryKey { - return PrimaryKey(impl: .rowID(column)) + static func rowID(_ column: String) -> PrimaryKeyInfo { + return PrimaryKeyInfo(impl: .rowID(column)) } - static func regular(_ columns: [String]) -> PrimaryKey { + static func regular(_ columns: [String]) -> PrimaryKeyInfo { assert(!columns.isEmpty) - return PrimaryKey(impl: .regular(columns)) + return PrimaryKeyInfo(impl: .regular(columns)) } /// The columns in the primary key; this array is never empty. diff --git a/GRDB/Core/DatabaseSchemaCache.swift b/GRDB/Core/DatabaseSchemaCache.swift index 152ec3df8..f6eed5569 100644 --- a/GRDB/Core/DatabaseSchemaCache.swift +++ b/GRDB/Core/DatabaseSchemaCache.swift @@ -7,8 +7,8 @@ protocol DatabaseSchemaCache { mutating func clear() - func primaryKey(_ tableName: String) -> PrimaryKey?? - mutating func set(primaryKey: PrimaryKey?, for tableName: String) + func primaryKey(_ tableName: String) -> PrimaryKeyInfo?? + mutating func set(primaryKey: PrimaryKeyInfo?, for tableName: String) func columns(in tableName: String) -> [ColumnInfo]? mutating func set(columns: [ColumnInfo], forTableName tableName: String) @@ -19,7 +19,7 @@ protocol DatabaseSchemaCache { /// A thread-unsafe database schema cache final class SimpleDatabaseSchemaCache: DatabaseSchemaCache { - private var primaryKeys: [String: PrimaryKey?] = [:] + private var primaryKeys: [String: PrimaryKeyInfo?] = [:] private var columns: [String: [ColumnInfo]] = [:] private var indexes: [String: [IndexInfo]] = [:] @@ -29,11 +29,11 @@ final class SimpleDatabaseSchemaCache: DatabaseSchemaCache { indexes = [:] } - func primaryKey(_ tableName: String) -> PrimaryKey?? { + func primaryKey(_ tableName: String) -> PrimaryKeyInfo?? { return primaryKeys[tableName] } - func set(primaryKey: PrimaryKey?, for tableName: String) { + func set(primaryKey: PrimaryKeyInfo?, for tableName: String) { primaryKeys[tableName] = primaryKey } @@ -62,11 +62,11 @@ final class SharedDatabaseSchemaCache: DatabaseSchemaCache { cache.write { $0.clear() } } - func primaryKey(_ tableName: String) -> PrimaryKey?? { + func primaryKey(_ tableName: String) -> PrimaryKeyInfo?? { return cache.read { $0.primaryKey(tableName) } } - func set(primaryKey: PrimaryKey?, for tableName: String) { + func set(primaryKey: PrimaryKeyInfo?, for tableName: String) { cache.write { $0.set(primaryKey: primaryKey, for: tableName) } } diff --git a/GRDB/QueryInterface/QueryInterfaceRequest.swift b/GRDB/QueryInterface/QueryInterfaceRequest.swift index 751714dfe..a5a5b6a99 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest.swift @@ -100,7 +100,7 @@ extension QueryInterfaceRequest { /// Returns a new QueryInterfaceRequest with a new net of selected columns. public func select(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest { - return select(_SQLExpression.SQLLiteral(sql, arguments)) + return select(_SQLExpression.sqlLiteral(sql, arguments)) } /// Returns a new QueryInterfaceRequest which returns distinct rows. @@ -125,7 +125,7 @@ extension QueryInterfaceRequest { /// Returns a new QueryInterfaceRequest with the provided *predicate* added to the /// eventual set of already applied predicates. public func filter(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest { - return filter(_SQLExpression.SQLLiteral(sql, arguments)) + return filter(_SQLExpression.sqlLiteral(sql, arguments)) } /// Returns a new QueryInterfaceRequest grouped according to *expressions*. @@ -142,7 +142,7 @@ extension QueryInterfaceRequest { /// Returns a new QueryInterfaceRequest with a new grouping. public func group(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest { - return group(_SQLExpression.SQLLiteral(sql, arguments)) + return group(_SQLExpression.sqlLiteral(sql, arguments)) } /// Returns a new QueryInterfaceRequest with the provided *predicate* added to the @@ -160,7 +160,7 @@ extension QueryInterfaceRequest { /// Returns a new QueryInterfaceRequest with the provided *sql* added to /// the eventual set of already applied predicates. public func having(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest { - return having(_SQLExpression.SQLLiteral(sql, arguments)) + return having(_SQLExpression.sqlLiteral(sql, arguments)) } /// Returns a new QueryInterfaceRequest with the provided *orderings* added to @@ -180,7 +180,7 @@ extension QueryInterfaceRequest { /// Returns a new QueryInterfaceRequest with the provided *sql* added to the /// eventual set of already applied orderings. public func order(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest { - return order([_SQLExpression.SQLLiteral(sql, arguments)]) + return order([_SQLExpression.sqlLiteral(sql, arguments)]) } /// Returns a new QueryInterfaceRequest sorted in reversed order. diff --git a/GRDB/QueryInterface/SQLCollation.swift b/GRDB/QueryInterface/SQLCollation.swift index d74f2b764..eeb1a6008 100644 --- a/GRDB/QueryInterface/SQLCollation.swift +++ b/GRDB/QueryInterface/SQLCollation.swift @@ -53,12 +53,16 @@ extension _SQLCollatedExpression : _SQLOrdering { extension _SpecificSQLExpressible { + public func collating(_ collationName: String) -> _SQLCollatedExpression { + return _SQLCollatedExpression(baseExpression: sqlExpression, collationName: collationName) + } + /// This method is an implementation detail of the query interface. /// Do not use it directly. /// /// See https://github.com/groue/GRDB.swift/#the-query-interface - public func collating(_ collationName: String) -> _SQLCollatedExpression { - return _SQLCollatedExpression(baseExpression: sqlExpression, collationName: collationName) + public func collating(_ collation: SQLCollation) -> _SQLCollatedExpression { + return collating(collation.rawValue) } /// This method is an implementation detail of the query interface. diff --git a/GRDB/QueryInterface/SQLFunction.swift b/GRDB/QueryInterface/SQLFunction.swift index 63f540579..dd46fc869 100644 --- a/GRDB/QueryInterface/SQLFunction.swift +++ b/GRDB/QueryInterface/SQLFunction.swift @@ -71,6 +71,16 @@ public func ?? (lhs: _SQLExpressible?, rhs: _SpecificSQLExpressible) -> _SQLExpr } +// MARK: - LENGTH(...) + +/// Returns an SQL expression. +/// +/// See https://github.com/groue/GRDB.swift/#sql-functions +public func length(_ value: _SpecificSQLExpressible) -> _SQLExpression { + return .function("LENGTH", [value.sqlExpression]) +} + + // MARK: - MAX(...) /// Returns an SQL expression. diff --git a/GRDB/QueryInterface/SQLSelectQuery.swift b/GRDB/QueryInterface/SQLSelectQuery.swift index 65f7376bf..0352b371d 100644 --- a/GRDB/QueryInterface/SQLSelectQuery.swift +++ b/GRDB/QueryInterface/SQLSelectQuery.swift @@ -410,7 +410,7 @@ extension _SpecificSQLExpressible { /// See https://github.com/groue/GRDB.swift/#the-query-interface public indirect enum _SQLExpression { /// For example: `name || 'rrr' AS pirateName` - case SQLLiteral(String, StatementArguments?) + case sqlLiteral(String, StatementArguments?) /// For example: `1` or `'foo'` case value(DatabaseValueConvertible?) // TODO: switch to DatabaseValue? @@ -466,7 +466,7 @@ public indirect enum _SQLExpression { /// func sql(_ arguments: inout StatementArguments?) -> String { switch self { - case .SQLLiteral(let sql, let literalArguments): + case .sqlLiteral(let sql, let literalArguments): if let literalArguments = literalArguments { guard arguments != nil else { fatalError("Not implemented") diff --git a/GRDB/QueryInterface/SQLTableBuilder.swift b/GRDB/QueryInterface/SQLTableBuilder.swift new file mode 100644 index 000000000..5893ee8ff --- /dev/null +++ b/GRDB/QueryInterface/SQLTableBuilder.swift @@ -0,0 +1,761 @@ +extension Database { + + // MARK: - Database Schema + + /// Creates a database table. + /// + /// try db.create(table: "pointOfInterests") { t in + /// t.column("id", .Integer).primaryKey() + /// t.column("title", .Text) + /// t.column("favorite", .Boolean).notNull().default(false) + /// t.column("longitude", .Double).notNull() + /// t.column("latitude", .Double).notNull() + /// } + /// + /// See https://www.sqlite.org/lang_createtable.html and + /// https://www.sqlite.org/withoutrowid.html + /// + /// - parameters: + /// - name: The table name. + /// - temporary: If true, creates a temporary table. + /// - ifNotExists: If false, no error is thrown if table already exists. + /// - withoutRowID: If true, uses WITHOUT ROWID optimization. + /// - body: A closure that defines table columns and constraints. + /// - throws: A DatabaseError whenever an SQLite error occurs. + @available(iOS 8.2, OSX 10.10, *) + 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) + body(definition) + let sql = try definition.sql(self) + try execute(sql) + } + + /// Creates a database table. + /// + /// try db.create(table: "pointOfInterests") { t in + /// t.column("id", .Integer).primaryKey() + /// t.column("title", .Text) + /// t.column("favorite", .Boolean).notNull().default(false) + /// t.column("longitude", .Double).notNull() + /// t.column("latitude", .Double).notNull() + /// } + /// + /// See https://www.sqlite.org/lang_createtable.html + /// + /// - parameters: + /// - name: The table name. + /// - temporary: If true, creates a temporary table. + /// - ifNotExists: If false, no error is thrown if table 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) + body(definition) + let sql = try definition.sql(self) + try execute(sql) + } + + /// Renames a database table. + /// + /// See https://www.sqlite.org/lang_altertable.html + /// + /// - throws: A DatabaseError whenever an SQLite error occurs. + public func rename(table name: String, to newName: String) throws { + try execute("ALTER TABLE \(name.quotedDatabaseIdentifier) RENAME TO \(newName.quotedDatabaseIdentifier)") + } + + /// Modifies a database table. + /// + /// try db.alter(table: "persons") { t in + /// t.add(column: "url", .Text) + /// } + /// + /// See https://www.sqlite.org/lang_altertable.html + /// + /// - parameters: + /// - name: The table name. + /// - body: A closure that defines table alterations. + /// - throws: A DatabaseError whenever an SQLite error occurs. + public func alter(table name: String, body: (TableAlteration) -> Void) throws { + let alteration = TableAlteration(name: name) + body(alteration) + let sql = try alteration.sql(self) + try execute(sql) + } + + /// Deletes a database table. + /// + /// See https://www.sqlite.org/lang_droptable.html + /// + /// - throws: A DatabaseError whenever an SQLite error occurs. + public func drop(table name: String) throws { + try execute("DROP TABLE \(name.quotedDatabaseIdentifier)") + } + + /// Creates a database index. + /// + /// try db.create(index: "personByEmail", on: "person", columns: ["email"]) + /// + /// SQLite can also index expressions (https://www.sqlite.org/expridx.html) + /// and use specific collations. To create such an index, use a raw SQL + /// query. + /// + /// try db.execute("CREATE INDEX ...") + /// + /// See https://www.sqlite.org/lang_createindex.html + /// + /// - parameters: + /// - name: The index name. + /// - table: The name of the indexed table. + /// - columns: The indexed columns. + /// - unique: If true, creates a unique index. + /// - 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 { + let definition = IndexDefinition(name: name, table: table, columns: columns, unique: unique, ifNotExists: ifNotExists, condition: condition?.sqlExpression) + let sql = definition.sql() + try execute(sql) + } + + /// Deletes a database index. + /// + /// See https://www.sqlite.org/lang_dropindex.html + /// + /// - throws: A DatabaseError whenever an SQLite error occurs. + public func drop(index name: String) throws { + try execute("DROP INDEX \(name.quotedDatabaseIdentifier)") + } +} + +/// The TableDefinition class lets you define table columns and constraints. +/// +/// You don't create instances of this class. Instead, you use the Database +/// `create(table:)` method: +/// +/// try db.create(table: "persons") { t in // t is TableDefinition +/// t.column(...) +/// } +/// +/// See https://www.sqlite.org/lang_createtable.html +public final class TableDefinition { + private typealias KeyConstraint = (columns: [String], conflictResolution: SQLConflictResolution?) + + private let name: String + private let temporary: Bool + private let ifNotExists: Bool + private let withoutRowID: Bool + private var columns: [ColumnDefinition] = [] + private var primaryKeyConstraint: KeyConstraint? + private var uniqueKeyConstraints: [KeyConstraint] = [] + private var foreignKeyConstraints: [(columns: [String], table: String, destinationColumns: [String]?, deleteAction: SQLForeignKeyAction?, updateAction: SQLForeignKeyAction?, deferred: Bool)] = [] + private var checkConstraints: [_SQLExpression] = [] + + init(name: String, temporary: Bool, ifNotExists: Bool, withoutRowID: Bool) { + self.name = name + self.temporary = temporary + self.ifNotExists = ifNotExists + self.withoutRowID = withoutRowID + } + + /// Appends a table column. + /// + /// try db.create(table: "persons") { t in + /// t.column("name", .Text) + /// } + /// + /// See https://www.sqlite.org/lang_createtable.html#tablecoldef + /// + /// - parameter name: the column name. + /// - parameter type: the column type. + /// - returns: An ColumnDefinition that allows you to refine the + /// column definition. + @discardableResult public func column(_ name: String, _ type: SQLColumnType) -> ColumnDefinition { + let column = ColumnDefinition(name: name, type: type) + columns.append(column) + return column + } + + /// Defines the table primary key. + /// + /// try db.create(table: "citizenships") { t in + /// t.column("personID", .Integer) + /// t.column("countryCode", .Text) + /// t.primaryKey(["personID", "countryCode"]) + /// } + /// + /// See https://www.sqlite.org/lang_createtable.html#primkeyconst and + /// https://www.sqlite.org/lang_createtable.html#rowid + /// + /// - parameter columns: The primary key columns. + /// - parameter conflitResolution: An optional conflict resolution + /// (see https://www.sqlite.org/lang_conflict.html). + public func primaryKey(_ columns: [String], onConflict conflictResolution: SQLConflictResolution? = nil) { + guard primaryKeyConstraint == nil else { + fatalError("can't define several primary keys") + } + primaryKeyConstraint = (columns: columns, conflictResolution: conflictResolution) + } + + /// Adds a unique key. + /// + /// try db.create(table: "pointOfInterests") { t in + /// t.column("latitude", .Double) + /// t.column("longitude", .Double) + /// t.uniqueKey(["latitude", "longitude"]) + /// } + /// + /// See https://www.sqlite.org/lang_createtable.html#uniqueconst + /// + /// - parameter columns: The unique key columns. + /// - parameter conflitResolution: An optional conflict resolution + /// (see https://www.sqlite.org/lang_conflict.html). + public func uniqueKey(_ columns: [String], onConflict conflictResolution: SQLConflictResolution? = nil) { + uniqueKeyConstraints.append((columns: columns, conflictResolution: conflictResolution)) + } + + /// Adds a foreign key. + /// + /// try db.create(table: "passport") { t in + /// t.column("issueDate", .Date) + /// t.column("personID", .Integer) + /// t.column("countryCode", .Text) + /// t.foreignKey(["personID", "countryCode"], references: "citizenships", onDelete: .cascade) + /// } + /// + /// See https://www.sqlite.org/foreignkeys.html + /// + /// - parameters: + /// - columns: The foreign key columns. + /// - table: The referenced table. + /// - destinationColumns: The columns in the referenced table. If not + /// specified, the columns of the primary key of the referenced table + /// are used. + /// - deleteAction: Optional action when the referenced row is deleted. + /// - 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: SQLForeignKeyAction? = nil, onUpdate updateAction: SQLForeignKeyAction? = nil, deferred: Bool = false) { + foreignKeyConstraints.append((columns: columns, table: table, destinationColumns: destinationColumns, deleteAction: deleteAction, updateAction: updateAction, deferred: deferred)) + } + + /// Adds a CHECK constraint. + /// + /// try db.create(table: "persons") { t in + /// t.column("personalPhone", .Text) + /// t.column("workPhone", .Text) + /// let personalPhone = SQLColumn("personalPhone") + /// let workPhone = SQLColumn("workPhone") + /// t.check(personalPhone != nil || workPhone != nil) + /// } + /// + /// See https://www.sqlite.org/lang_createtable.html#ckconst + /// + /// - parameter condition: The checked condition + public func check(_ condition: _SQLExpressible) { + checkConstraints.append(condition.sqlExpression) + } + + /// Adds a CHECK constraint. + /// + /// try db.create(table: "persons") { t in + /// t.column("personalPhone", .Text) + /// t.column("workPhone", .Text) + /// t.check(sql: "personalPhone IS NOT NULL OR workPhone IS NOT NULL") + /// } + /// + /// See https://www.sqlite.org/lang_createtable.html#ckconst + /// + /// - parameter sql: An SQL snippet + public func check(sql: String) { + checkConstraints.append(_SQLExpression.sqlLiteral(sql, nil)) + } + + private func sql(_ db: Database) throws -> String { + var chunks: [String] = [] + chunks.append("CREATE") + if temporary { + chunks.append("TEMPORARY") + } + chunks.append("TABLE") + if ifNotExists { + chunks.append("IF NOT EXISTS") + } + chunks.append(name.quotedDatabaseIdentifier) + + do { + var items: [String] = [] + try items.append(contentsOf: columns.map { try $0.sql(db) }) + + if let (columns, conflictResolution) = primaryKeyConstraint { + var chunks: [String] = [] + chunks.append("PRIMARY KEY") + chunks.append("(\((columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))") + if let conflictResolution = conflictResolution { + chunks.append("ON CONFLICT") + chunks.append(conflictResolution.rawValue) + } + items.append(chunks.joined(separator: " ")) + } + + for (columns, conflictResolution) in uniqueKeyConstraints { + var chunks: [String] = [] + chunks.append("UNIQUE") + chunks.append("(\((columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))") + if let conflictResolution = conflictResolution { + chunks.append("ON CONFLICT") + chunks.append(conflictResolution.rawValue) + } + items.append(chunks.joined(separator: " ")) + } + + for (columns, table, destinationColumns, deleteAction, updateAction, deferred) in foreignKeyConstraints { + var chunks: [String] = [] + chunks.append("FOREIGN KEY") + chunks.append("(\((columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))") + chunks.append("REFERENCES") + if let destinationColumns = destinationColumns { + chunks.append("\(table.quotedDatabaseIdentifier)(\((destinationColumns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))") + } else if let primaryKey = try db.primaryKey(table) { + chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKey.columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))") + } else { + fatalError("explicit referenced column(s) required, since table \(table) has no primary key") + } + if let deleteAction = deleteAction { + chunks.append("ON DELETE") + chunks.append(deleteAction.rawValue) + } + if let updateAction = updateAction { + chunks.append("ON UPDATE") + chunks.append(updateAction.rawValue) + } + if deferred { + chunks.append("DEFERRABLE INITIALLY DEFERRED") + } + items.append(chunks.joined(separator: " ")) + } + + for checkExpression in checkConstraints { + var chunks: [String] = [] + chunks.append("CHECK") + var arguments: StatementArguments? = nil // nil so that checkExpression.sql(&arguments) embeds literals + chunks.append("(" + checkExpression.sql(&arguments) + ")") + items.append(chunks.joined(separator: " ")) + } + + chunks.append("(\(items.joined(separator: ", ")))") + } + + if withoutRowID { + chunks.append("WITHOUT ROWID") + } + return chunks.joined(separator: " ") + } +} + +/// The TableAlteration class lets you alter database tables. +/// +/// You don't create instances of this class. Instead, you use the Database +/// `alter(table:)` method: +/// +/// try db.alter(table: "persons") { t in // t is TableAlteration +/// t.add(column: ...) +/// } +/// +/// See https://www.sqlite.org/lang_altertable.html +public final class TableAlteration { + private let name: String + private var addedColumns: [ColumnDefinition] = [] + + init(name: String) { + self.name = name + } + + /// Appends a column to the table. + /// + /// try db.alter(table: "persons") { t in + /// t.add(column: "url", .Text) + /// } + /// + /// See https://www.sqlite.org/lang_altertable.html + /// + /// - parameter name: the column name. + /// - parameter type: the column type. + /// - returns: An ColumnDefinition that allows you to refine the + /// column definition. + @discardableResult public func add(column name: String, _ type: SQLColumnType) -> ColumnDefinition { + let column = ColumnDefinition(name: name, type: type) + addedColumns.append(column) + return column + } + + private func sql(_ db: Database) throws -> String { + var statements: [String] = [] + + for column in addedColumns { + var chunks: [String] = [] + chunks.append("ALTER TABLE") + chunks.append(name.quotedDatabaseIdentifier) + chunks.append("ADD COLUMN") + try chunks.append(column.sql(db)) + let statement = chunks.joined(separator: " ") + statements.append(statement) + } + + return statements.joined(separator: "; ") + } +} + +/// The ColumnDefinition class lets you refine a table column. +/// +/// You get instances of this class when you create or alter a database table: +/// +/// try db.create(table: "persons") { t in +/// t.column(...) // ColumnDefinition +/// } +/// +/// try db.alter(table: "persons") { t in +/// t.add(column: ...) // ColumnDefinition +/// } +/// +/// See https://www.sqlite.org/lang_createtable.html and +/// https://www.sqlite.org/lang_altertable.html +public final class ColumnDefinition { + private let name: String + private let type: SQLColumnType + private var primaryKey: (conflictResolution: SQLConflictResolution?, autoincrement: Bool)? + private var notNullConflictResolution: SQLConflictResolution? + private var uniqueConflictResolution: SQLConflictResolution? + private var checkExpression: _SQLExpression? + private var defaultExpression: _SQLExpression? + private var collationName: String? + private var reference: (table: String, column: String?, deleteAction: SQLForeignKeyAction?, updateAction: SQLForeignKeyAction?, deferred: Bool)? + + init(name: String, type: SQLColumnType) { + self.name = name + self.type = type + } + + /// Adds a primary key constraint on the column. + /// + /// try db.create(table: "persons") { t in + /// t.column("id", .Integer).primaryKey() + /// } + /// + /// See https://www.sqlite.org/lang_createtable.html#primkeyconst and + /// https://www.sqlite.org/lang_createtable.html#rowid + /// + /// - parameters: + /// - conflitResolution: An optional conflict resolution + /// (see https://www.sqlite.org/lang_conflict.html). + /// - 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: SQLConflictResolution? = nil, autoincrement: Bool = false) -> Self { + primaryKey = (conflictResolution: conflictResolution, autoincrement: autoincrement) + return self + } + + /// Adds a NOT NULL constraint on the column. + /// + /// try db.create(table: "persons") { t in + /// t.column("name", .Text).notNull() + /// } + /// + /// See https://www.sqlite.org/lang_createtable.html#notnullconst + /// + /// - parameter conflitResolution: An optional conflict resolution + /// (see https://www.sqlite.org/lang_conflict.html). + /// - returns: Self so that you can further refine the column definition. + @discardableResult public func notNull(onConflict conflictResolution: SQLConflictResolution? = nil) -> Self { + notNullConflictResolution = conflictResolution ?? .abort + return self + } + + /// Adds a UNIQUE constraint on the column. + /// + /// try db.create(table: "persons") { t in + /// t.column("email", .Text).unique() + /// } + /// + /// See https://www.sqlite.org/lang_createtable.html#uniqueconst + /// + /// - parameter conflitResolution: An optional conflict resolution + /// (see https://www.sqlite.org/lang_conflict.html). + /// - returns: Self so that you can further refine the column definition. + @discardableResult public func unique(onConflict conflictResolution: SQLConflictResolution? = nil) -> Self { + uniqueConflictResolution = conflictResolution ?? .abort + return self + } + + /// Adds a CHECK constraint on the column. + /// + /// try db.create(table: "persons") { t in + /// t.column("name", .Text).check { length($0) > 0 } + /// } + /// + /// See https://www.sqlite.org/lang_createtable.html#ckconst + /// + /// - parameter condition: A closure whose argument is an SQLColumn that + /// represents the defined column, and returns the expression to check. + /// - returns: Self so that you can further refine the column definition. + @discardableResult public func check(_ condition: @noescape (SQLColumn) -> _SQLExpressible) -> Self { + checkExpression = condition(SQLColumn(name)).sqlExpression + return self + } + + /// Adds a CHECK constraint on the column. + /// + /// try db.create(table: "persons") { t in + /// t.column("name", .Text).check(sql: "LENGTH(name) > 0") + /// } + /// + /// See https://www.sqlite.org/lang_createtable.html#ckconst + /// + /// - parameter sql: An SQL snippet. + /// - returns: Self so that you can further refine the column definition. + @discardableResult public func check(sql: String) -> Self { + checkExpression = _SQLExpression.sqlLiteral(sql, nil) + return self + } + + /// Defines the default column value. + /// + /// try db.create(table: "persons") { t in + /// t.column("name", .Text).defaults("Anonymous") + /// } + /// + /// See https://www.sqlite.org/lang_createtable.html#dfltval + /// + /// - parameter value: A DatabaseValueConvertible value. + /// - returns: Self so that you can further refine the column definition. + @discardableResult public func defaults(_ value: DatabaseValueConvertible) -> Self { + defaultExpression = value.sqlExpression + return self + } + + /// Defines the default column value. + /// + /// try db.create(table: "persons") { t in + /// t.column("creationDate", .DateTime).defaults(sql: "CURRENT_TIMESTAMP") + /// } + /// + /// See https://www.sqlite.org/lang_createtable.html#dfltval + /// + /// - parameter sql: An SQL snippet. + /// - returns: Self so that you can further refine the column definition. + @discardableResult public func defaults(sql: String) -> Self { + defaultExpression = _SQLExpression.sqlLiteral(sql, nil) + return self + } + + // Defines the default column collation. + /// + /// try db.create(table: "persons") { t in + /// t.column("email", .Text).collate(.nocase) + /// } + /// + /// See https://www.sqlite.org/datatype3.html#collation + /// + /// - parameter collation: An SQLCollation. + /// - returns: Self so that you can further refine the column definition. + @discardableResult public func collate(_ collation: SQLCollation) -> Self { + collationName = collation.rawValue + return self + } + + // Defines the default column collation. + /// + /// try db.create(table: "persons") { t in + /// t.column("name", .Text).collate(.localizedCaseInsensitiveCompare) + /// } + /// + /// See https://www.sqlite.org/datatype3.html#collation + /// + /// - parameter collation: A custom DatabaseCollation. + /// - returns: Self so that you can further refine the column definition. + @discardableResult public func collate(_ collation: DatabaseCollation) -> Self { + collationName = collation.name + return self + } + + /// Defines a foreign key. + /// + /// try db.create(table: "books") { t in + /// t.column("authorId", .Integer).references("authors", onDelete: .cascade) + /// } + /// + /// See https://www.sqlite.org/foreignkeys.html + /// + /// - parameters + /// - table: The referenced table. + /// - column: The column in the referenced table. If not specified, the + /// column of the primary key of the referenced table is used. + /// - deleteAction: Optional action when the referenced row is deleted. + /// - 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. + /// - returns: Self so that you can further refine the column definition. + @discardableResult public func references(_ table: String, column: String? = nil, onDelete deleteAction: SQLForeignKeyAction? = nil, onUpdate updateAction: SQLForeignKeyAction? = nil, deferred: Bool = false) -> Self { + reference = (table: table, column: column, deleteAction: deleteAction, updateAction: updateAction, deferred: deferred) + return self + } + + private func sql(_ db: Database) throws -> String { + var chunks: [String] = [] + chunks.append(name.quotedDatabaseIdentifier) + chunks.append(type.rawValue) + + if let (conflictResolution, autoincrement) = primaryKey { + chunks.append("PRIMARY KEY") + if let conflictResolution = conflictResolution { + chunks.append("ON CONFLICT") + chunks.append(conflictResolution.rawValue) + } + if autoincrement { + chunks.append("AUTOINCREMENT") + } + } + + switch notNullConflictResolution { + case .none: + break + case .abort?: + chunks.append("NOT NULL") + case let conflictResolution?: + chunks.append("NOT NULL ON CONFLICT") + chunks.append(conflictResolution.rawValue) + } + + switch uniqueConflictResolution { + case .none: + break + case .abort?: + chunks.append("UNIQUE") + case let conflictResolution?: + chunks.append("UNIQUE ON CONFLICT") + chunks.append(conflictResolution.rawValue) + } + + if let checkExpression = checkExpression { + chunks.append("CHECK") + var arguments: StatementArguments? = nil // nil so that checkExpression.sql(&arguments) embeds literals + chunks.append("(" + checkExpression.sql(&arguments) + ")") + } + + if let defaultExpression = defaultExpression { + var arguments: StatementArguments? = nil // nil so that defaultExpression.sql(&arguments) embeds literals + chunks.append("DEFAULT") + chunks.append(defaultExpression.sql(&arguments)) + } + + if let collationName = collationName { + chunks.append("COLLATE") + chunks.append(collationName) + } + + if let (table, column, deleteAction, updateAction, deferred) = reference { + chunks.append("REFERENCES") + if let column = column { + chunks.append("\(table.quotedDatabaseIdentifier)(\(column.quotedDatabaseIdentifier))") + } else if let primaryKey = try db.primaryKey(table) { + chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKey.columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))") + } else { + fatalError("explicit referenced column required, since table \(table) has no primary key") + } + if let deleteAction = deleteAction { + chunks.append("ON DELETE") + chunks.append(deleteAction.rawValue) + } + if let updateAction = updateAction { + chunks.append("ON UPDATE") + chunks.append(updateAction.rawValue) + } + if deferred { + chunks.append("DEFERRABLE INITIALLY DEFERRED") + } + } + + return chunks.joined(separator: " ") + } +} + +private struct IndexDefinition { + let name: String + let table: String + let columns: [String] + let unique: Bool + let ifNotExists: Bool + let condition: _SQLExpression? + + func sql() -> String { + var chunks: [String] = [] + chunks.append("CREATE") + if unique { + chunks.append("UNIQUE") + } + chunks.append("INDEX") + if ifNotExists { + chunks.append("IF NOT EXISTS") + } + chunks.append(name.quotedDatabaseIdentifier) + chunks.append("ON") + chunks.append("\(table.quotedDatabaseIdentifier)(\((columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))") + if let condition = condition { + chunks.append("WHERE") + var arguments: StatementArguments? = nil // nil so that checkExpression.sql(&arguments) embeds literals + chunks.append(condition.sql(&arguments)) + } + return chunks.joined(separator: " ") + } +} + +/// A built-in SQLite collation. +/// +/// See https://www.sqlite.org/datatype3.html#collation +public enum SQLCollation : String { + case binary = "BINARY" + case nocase = "NOCASE" + case rtrim = "RTRIM" +} + +/// An SQLite conflict resolution. +/// +/// See https://www.sqlite.org/lang_conflict.html. +public enum SQLConflictResolution : String { + case rollback = "ROLLBACK" + case abort = "ABORT" + case fail = "FAIL" + case ignore = "IGNORE" + case replace = "REPLACE" +} + +/// An SQL column type. +/// +/// try db.create(table: "persons") { t in +/// t.column("id", .Integer).primaryKey() +/// t.column("title", .Text) +/// } +/// +/// See https://www.sqlite.org/datatype3.html +public enum SQLColumnType : String { + case text = "TEXT" + case integer = "INTEGER" + case double = "DOUBLE" + case numeric = "NUMERIC" + case boolean = "BOOLEAN" + case blob = "BLOB" + case date = "DATE" + case datetime = "DATETIME" +} + +/// A foreign key action. +/// +/// See https://www.sqlite.org/foreignkeys.html +public enum SQLForeignKeyAction : String { + case cascade = "CASCADE" + case restrict = "RESTRICT" + case setNull = "SET NULL" + case setDefault = "SET DEFAULT" +} diff --git a/GRDB/Record/Persistable.swift b/GRDB/Record/Persistable.swift index deb588f79..394245332 100644 --- a/GRDB/Record/Persistable.swift +++ b/GRDB/Record/Persistable.swift @@ -517,7 +517,7 @@ final class DataMapper { let databaseTableName: String /// The table primary key - let primaryKey: PrimaryKey? + let primaryKey: PrimaryKeyInfo? init(_ db: Database, _ persistable: MutablePersistable) { // Fail early if database table does not exist. diff --git a/README.md b/README.md index 4571c2475..01f005426 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,29 @@ GRDB.swift [![Swift](https://img.shields.io/badge/swift-3-orange.svg?style=flat)](https://developer.apple.com/swift/) [![Platforms](https://img.shields.io/cocoapods/p/GRDB.swift.svg)](https://developer.apple.com/swift/) [![License](https://img.shields.io/github/license/groue/GRDB.swift.svg?maxAge=2592000)](/LICENSE) ========== -GRDB.swift is a Swift application toolkit that provides access to SQLite databases. +### A Swift application toolkit for SQLite databases. -It targets Swift 3.0 Preview 4 (August 1, 2016). +**Requirements**: iOS 8.0+ / OSX 10.9+ • Xcode Version 8.0 beta 4 (8S188o) • Swift 3. -It ships with a **low-level SQLite API**, and high-level tools that help dealing with databases: +The Swift3 branch has no version. It is currently synced with v0.78.0 of the Swift 2.2 [main branch](https://github.com/groue/GRDB.swift). + +Follow [@groue](http://twitter.com/groue) on Twitter for release announcements and usage tips. + +--- + +

+ Features • + Usage • + Installation • + Documentation • + FAQ +

+ +--- + +## Features + +GRDB ships with a **low-level SQLite API**, and high-level tools that help dealing with databases: - **Records**: fetching and persistence methods for your custom structs and class hierarchies - **Query Interface**: a swift way to avoid the SQL language @@ -22,19 +40,10 @@ More than a set of tools that leverage SQLite abilities, GRDB is also: - **Faster**: see [Comparing the Performances of Swift SQLite libraries](https://github.com/groue/GRDB.swift/wiki/Performance) - Well documented & tested -For a general overview of how a protocol-oriented library impacts database acesses, have a look at [How to build an iOS application with SQLite and GRDB.swift](https://medium.com/@gwendal.roue/how-to-build-an-ios-application-with-sqlite-and-grdb-swift-d023a06c29b3). +For a general overview of how a protocol-oriented library impacts database accesses, have a look at [How to build an iOS application with SQLite and GRDB.swift](https://medium.com/@gwendal.roue/how-to-build-an-ios-application-with-sqlite-and-grdb-swift-d023a06c29b3). ---- - -The Swift3 branch has no version. It is currently synced with v0.77.0 of the Swift 2.2 [main branch](https://github.com/groue/GRDB.swift). - -Follow [@groue](http://twitter.com/groue) on Twitter for release announcements and usage tips. - -**Requirements**: iOS 8.0+ / OSX 10.9+, Xcode Version 8.0 beta 4 (8S188o) - - -### Usage +## Usage Open a [connection](#database-connections) to the database: @@ -50,8 +59,8 @@ try dbQueue.inDatabase { db in try db.execute( "CREATE TABLE pointOfInterests (" + "id INTEGER PRIMARY KEY, " + - "title TEXT, " + - "favorite BOOLEAN NOT NULL, " + + "title TEXT NOT NULL, " + + "favorite BOOLEAN NOT NULL DEFAULT 0, " + "latitude DOUBLE NOT NULL, " + "longitude DOUBLE NOT NULL" + ")") @@ -92,7 +101,7 @@ Insert and fetch [records](#records): ```swift struct PointOfInterest { var id: Int64? - var title: String? + var title: String var isFavorite: Bool var coordinate: CLLocationCoordinate2D } @@ -121,17 +130,24 @@ try dbQueue.inDatabase { db in Avoid SQL with the [query interface](#the-query-interface): ```swift -let titleColumn = SQLColumn("title") -let favoriteColumn = SQLColumn("favorite") - dbQueue.inDatabase { db in + try db.create(table: "pointOfInterests") { t in + t.column("id", .integer).primaryKey() + t.column("title", .text).notNull() + t.column("favorite", .boolean).notNull().defaults(false) + t.column("longitude", .double).notNull() + t.column("latitude", .double).notNull() + } + // PointOfInterest? let paris = PointOfInterest.fetchOne(db, key: 1) // PointOfInterest? + let titleColumn = SQLColumn("title") let berlin = PointOfInterest.filter(titleColumn == "Berlin").fetchOne(db) // [PointOfInterest] + let favoriteColumn = SQLColumn("favorite") let favoritePois = PointOfInterest .filter(favoriteColumn) .order(titleColumn) @@ -145,26 +161,26 @@ Documentation **GRDB runs on top of SQLite**: you should get familiar with the [SQLite FAQ](http://www.sqlite.org/faq.html). For general and detailed information, jump to the [SQLite Documentation](http://www.sqlite.org/docs.html). -**Getting started** +**Getting Started** - [Installation](#installation) - [Database Connections](#database-connections): Connect to SQLite databases **SQLite and SQL** -- [SQLite API](#sqlite-api) +- [SQLite API](#sqlite-api): The low-level SQLite API • [executing updates](#executing-updates) • [fetch queries](#fetch-queries) -**Application tools** +**Application Tools** - [Records](#records): Fetching and persistence methods for your custom structs and class hierarchies. -- [Query Interface](#the-query-interface): A swift way to generate SQL. +- [Query Interface](#the-query-interface): A swift way to generate SQL • [table creation](#database-schema) • [fetch requests](#requests) - [Migrations](#migrations): Transform your database as your application evolves. - [Database Changes Observation](#database-changes-observation): Perform post-commit and post-rollback actions. - [FetchedRecordsController](#fetchedrecordscontroller): Automatic database changes tracking, plus UITableView animations. - [Encryption](#encryption): Encrypt your database with SQLCipher. - [Backup](#backup): Dump the content of a database to another. -**Good to know** +**Good to Know** - [Avoiding SQL Injection](#avoiding-sql-injection) - [Error Handling](#error-handling) @@ -239,7 +255,7 @@ SQLite creates the database file if it does not already exist. The connection is ```swift // Execute database statements: try dbQueue.inDatabase { db in - try db.execute("CREATE TABLE pointOfInterests (...)") + try db.create(table: "pointOfInterests") { ... } try PointOfInterest(...).insert(db) } @@ -283,7 +299,7 @@ let dbQueue = try DatabaseQueue( configuration: config) ``` -See [Configuration](http://cocoadocs.org/docsets/GRDB.swift/0.77.0/Structs/Configuration.html) for more details. +See [Configuration](http://cocoadocs.org/docsets/GRDB.swift/0.78.0/Structs/Configuration.html) for more details. ## Database Pools @@ -307,7 +323,7 @@ SQLite creates the database file if it does not already exist. The connection is ```swift // Execute database statements: try dbPool.write { db in - try db.execute("CREATE TABLE pointOfInterests (...)") + try db.create(table: "pointOfInterests") { ... } try PointOfInterest(...).insert(db) } @@ -363,7 +379,7 @@ let dbPool = try DatabasePool( configuration: config) ``` -See [Configuration](http://cocoadocs.org/docsets/GRDB.swift/0.77.0/Structs/Configuration.html) for more details. +See [Configuration](http://cocoadocs.org/docsets/GRDB.swift/0.78.0/Structs/Configuration.html) for more details. Database pools are more memory-hungry than database queues. See [Memory Management](#memory-management) for more information. @@ -600,18 +616,18 @@ row.value(...) as Int row.value(...) as Int? ``` -> :warning: **Warning**: avoid the `as!` and `as?` operators (see [rdar://21676393](http://openradar.appspot.com/radar?id=4951414862249984)): +> :warning: **Warning**: avoid the `as!` and `as?` operators, because they misbehave in the context of type inference (see [rdar://21676393](http://openradar.appspot.com/radar?id=4951414862249984)): > > ```swift -> row.value(...) as! Int // NO NO NO DON'T DO THAT! -> row.value(...) as? Int // NO NO NO DON'T DO THAT! +> if let int = row.value(...) as? Int { ... } // BAD - doesn't work +> if let int = row.value(...) as Int? { ... } // GOOD > ``` Generally speaking, you can extract the type you need, *provided it can be converted from the underlying SQLite value*: - **Successful conversions include:** - - Numeric SQLite values to numeric Swift types, and Bool (zero is the only false boolean). + - All numeric SQLite values to all numeric Swift types, and Bool (zero is the only false boolean). - Text SQLite values to Swift String. - Blob SQLite values to Foundation Data. @@ -800,11 +816,11 @@ Use values in [Records](#records): ```swift class Link : Record { var url: URL - var verified: Bool + var isVerified: Bool required init(row: Row) { - url = row.value("url") - verified = row.value("verified") + url = row.value(named: "url") + isVerified = row.value(named: "verified") super.init(row: row) } @@ -990,7 +1006,7 @@ enum Grape : String { case chardonnay, merlot, riesling } -// Declare DatabaseValueConvertible adoption +// Declare empty DatabaseValueConvertible adoption extension Color : DatabaseValueConvertible { } extension Grape : DatabaseValueConvertible { } @@ -1282,7 +1298,10 @@ Person.select(reverseString.apply(nameColumn)) **SQLite provides database schema introspection tools**, such as the [sqlite_master](https://www.sqlite.org/faq.html#q7) table, and the pragma [table_info](https://www.sqlite.org/pragma.html#pragma_table_info): ```swift -try db.execute("CREATE TABLE persons(id INTEGER PRIMARY KEY, name TEXT)") +try db.create(table: "persons") { t in + t.column("id", .integer).primaryKey() + t.column("name", .text) +} // @@ -1303,7 +1322,7 @@ GRDB provides four high-level methods as well: db.tableExists("persons") // Bool, true if the table exists db.indexes(on: "persons") // [IndexInfo], the indexes defined on the table try db.table("persons", hasUniqueKey: ["email"]) // Bool, true if column(s) is a unique key -try db.primaryKey("persons") // PrimaryKey? +try db.primaryKey("persons") // PrimaryKeyInfo? ``` Primary key is nil when table has no primary key: @@ -1448,10 +1467,10 @@ for person in Person.fetch(db, sql, adapter: adapter) { For more information about row adapters, see the documentation of: -- [RowAdapter](http://cocoadocs.org/docsets/GRDB.swift/0.77.0/Protocols/RowAdapter.html): the protocol that lets you define your custom row adapters -- [ColumnMapping](http://cocoadocs.org/docsets/GRDB.swift/0.77.0/Structs/ColumnMapping.html): a row adapter that renames row columns -- [SuffixRowAdapter](http://cocoadocs.org/docsets/GRDB.swift/0.77.0/Structs/SuffixRowAdapter.html): a row adapter that hides the first columns of a row -- [ScopeAdapter](http://cocoadocs.org/docsets/GRDB.swift/0.77.0/Structs/ScopeAdapter.html): the row adapter that groups several adapters together to define scopes +- [RowAdapter](http://cocoadocs.org/docsets/GRDB.swift/0.78.0/Protocols/RowAdapter.html): the protocol that lets you define your custom row adapters +- [ColumnMapping](http://cocoadocs.org/docsets/GRDB.swift/0.78.0/Structs/ColumnMapping.html): a row adapter that renames row columns +- [SuffixRowAdapter](http://cocoadocs.org/docsets/GRDB.swift/0.78.0/Structs/SuffixRowAdapter.html): a row adapter that hides the first columns of a row +- [ScopeAdapter](http://cocoadocs.org/docsets/GRDB.swift/0.78.0/Structs/ScopeAdapter.html): the row adapter that groups several adapters together to define scopes ## Raw SQLite Pointers @@ -1547,7 +1566,7 @@ let person = Person(name: "Arthur", email: "arthur@example.com") try person.insert(db) ``` -Of course, you need to open a [database connection](#database-connections), and [create a database table](#executing-updates) first. +Of course, you need to open a [database connection](#database-connections), and [create a database table](#database-schema) first. #### Fetching Records @@ -1660,7 +1679,7 @@ public protocol RowConvertible { ```swift struct PointOfInterest { var id: Int64? - var title: String? + var title: String var coordinate: CLLocationCoordinate2D } @@ -1872,11 +1891,11 @@ When you subclass [Record](#record-class), you simply have to override the custo ```swift class Person : Record { - var uuid: String? + var uuid: NSUUID? override func insert(_ db: Database) throws { if uuid == nil { - uuid = NSUUID().UUIDString + uuid = NSUUID() } try super.insert(db) } @@ -1944,7 +1963,7 @@ For example, here is a fully functional Record subclass: ```swift class PointOfInterest : Record { var id: Int64? - var title: String? + var title: String var coordinate: CLLocationCoordinate2D /// The table name @@ -2058,6 +2077,7 @@ For an efficient algorithm which synchronizes the content of a database table wi **The query interface lets you write pure Swift instead of SQL:** ```swift +try db.create(table: "wines") { t in ... } let count = Wine.filter(color == Color.red).fetchCount(db) let wines = Wine.filter(origin == "Burgundy").order(price).fetchAll(db) ``` @@ -2065,12 +2085,14 @@ let wines = Wine.filter(origin == "Burgundy").order(price).fetchAll(db) Please bear in mind that the query interface can not generate all possible SQL queries. You may also *prefer* writing SQL, and this is just OK. From little snippets to full queries, your SQL skills are welcome: ```swift +try db.execute("CREATE TABLE wines (...)") let count = Wine.filter(sql: "color = ?", arguments: [Color.Red]).fetchCount(db) let wines = Wine.fetchAll(db, "SELECT * FROM wines WHERE origin = ? ORDER BY price", arguments: ["Burgundy"]) ``` So don't miss the [SQL API](#sqlite-api). +- [Database Schema](#database-schema) - [Requests](#requests) - [Expressions](#expressions) - [SQL Operators](#sql-operators) @@ -2080,12 +2102,171 @@ So don't miss the [SQL API](#sqlite-api). - [Fetching Aggregated Values](#fetching-aggregated-values) -### Requests +### Database Schema -Everything starts from **a type** that adopts the `TableMapping` protocol, such as a `Record` subclass (see [Records](#records)): +Once granted with a [database connection](#database-connections), you can setup your database schema without writing SQL: + +- [Create Tables](#create-tables) +- [Modify Tables](#modify-tables) +- [Drop Tables](#drop-tables) +- [Create Indexes](#create-indexes) + + +#### Create Tables ```swift -class Person: Record { ... } +// CREATE TABLE pointOfInterests ( +// id INTEGER PRIMARY KEY, +// title TEXT, +// favorite BOOLEAN NOT NULL DEFAULT 0, +// latitude DOUBLE NOT NULL, +// longitude DOUBLE NOT NULL +// ) +try db.create(table: "pointOfInterests") { t in + t.column("id", .integer).primaryKey() + t.column("title", .text) + t.column("favorite", .boolean).notNull().defaults(false) + t.column("longitude", .double).notNull() + t.column("latitude", .double).notNull() +} +``` + +The `create(table:)` method covers nearly all SQLite table creation features. + +Relevant SQLite documentation: + +- [CREATE TABLE](https://www.sqlite.org/lang_createtable.html) +- [Datatypes In SQLite Version 3](https://www.sqlite.org/datatype3.html) +- [SQLite Foreign Key Support](https://www.sqlite.org/foreignkeys.html) +- [ON CONFLICT](https://www.sqlite.org/lang_conflict.html) +- [The WITHOUT ROWID Optimization](https://www.sqlite.org/withoutrowid.html) + +**Configure table creation**: + +```swift +// CREATE TABLE example ( ... ) +try db.create(table: "example") { t in ... } + +// CREATE TEMPORARY TABLE example IF NOT EXISTS ( +try db.create(table: "example", temporary: true, ifNotExists: true) { t in +``` + +**Add regular columns** with their name and type (text, integer, double, numeric, boolean, blob, date and datetime) - see [SQLite data types](https://www.sqlite.org/datatype3.html): + +```swift + // name TEXT, + // creationDate DATETIME, + t.column("name", .text) + t.column("creationDate", .datetime) +``` + +Define **not null** columns, and set **default** values: + +```swift + // email TEXT NOT NULL, + t.column("email", .text).notNull() + + // name TEXT NOT NULL DEFAULT 'Anonymous', + t.column("name", .text).notNull().defaults("Anonymous") +``` + +Use an individual column as **primary**, **unique**, or **foreign key**. When defining a foreign key, the referenced column is the primary key of the referenced table (unless you specify otherwise): + +```swift + // id INTEGER PRIMARY KEY, + t.column("id", .integer).primaryKey() + + // email TEXT UNIQUE, + t.column("email", .text).unique() + + // countryCode TEXT REFERENCES countries(code) ON DELETE CASCADE, + t.column("countryCode", .text).references("countries", onDelete: .cascade) +``` + +**Perform integrity checks** on individual columns, and SQLite will only let conforming rows in. In the example below, the `$0` closure variable is a column which lets you build any SQL [expression](#expressions). + +```swift + // name TEXT CHECK (LENGTH(name) > 0) + // age INTEGER CHECK (age > 0) + t.column("name", .text).check { length($0) > 0 } + t.column("age", .integer).check(sql: "age > 0") +``` + +Other **table constraints** can involve several columns: + +```swift + // PRIMARY KEY (a, b), + t.primaryKey(["a", "b"]) + + // UNIQUE (a, b) ON CONFLICT REPLACE, + t.uniqueKey(["a", "b"], onConfict: .replace) + + // FOREIGN KEY (c, d) REFERENCES parents(a, b), + t.foreignKey(["c", "d"], references: "parent") + + // CHECK (a + b < 10), + t.check(SQLColumn("a") + SQLColumn("b") < 10) + + // CHECK (a + b < 10) + t.check(sql: "a + b < 10") +} +``` + +#### Modify Tables + +SQLite lets you rename tables, and add columns to existing tables: + +```swift +// ALTER TABLE referers RENAME TO referrers +try db.rename(table: "referers", to: "referrers") + +// ALTER TABLE persons ADD COLUMN url TEXT +try db.alter(table: "persons") { t in + t.add(column: "url", .text) +} +``` + +> :point_up: **Note**: SQLite restricts the possible table alterations, and may require you to recreate dependent triggers or views. See the documentation of the [ALTER TABLE](https://www.sqlite.org/lang_altertable.html) for details. See [Advanced Database Schema Changes](#advanced-database-schema-changes) for a way to lift restrictions. + + +#### Drop Tables + +Drop tables with the `drop(table:)` method: + +```swift +try db.drop(table: "obsolete") +``` + +#### Create Indexes + +Create indexes with the `create(index:)` method: + +```swift +// CREATE UNIQUE INDEX byEmail ON users(email) +try db.create(index: "byEmail", on: "users", columns: ["email"], unique: true) +``` + +Relevant SQLite documentation: + +- [CREATE INDEX](https://www.sqlite.org/lang_createindex.html) +- [Indexes On Expressions](https://www.sqlite.org/expridx.html) +- [Partial Indexes](https://www.sqlite.org/partialindex.html) + + +### Requests + +**The query interface requests** let you fetch values from the database: + +```swift +let request = Person.filter(emailColumn != nil).order(nameColumn) +let persons = request.fetchAll(db) // [Person] +let count = request.fetchCount(db) // Int +``` + +All requests start from **a type** that adopts the `TableMapping` protocol, such as a `Record` subclass (see [Records](#records)): + +```swift +class Person : Record { ... } ``` Declare the table **columns** that you want to use for filtering, or sorting: @@ -2112,41 +2293,41 @@ All the methods above return another request, which you can further refine by ap - `all()`: the request for all rows. ```swift - // SELECT * FROM "persons" + // SELECT * FROM persons Person.all() ``` - `select(expression, ...)` defines the selected columns. ```swift - // SELECT "id", "name" FROM "persons" + // SELECT id, name FROM persons Person.select(idColumn, nameColumn) - // SELECT MAX("age") AS "maxAge" FROM "persons" + // SELECT MAX(age) AS maxAge FROM persons Person.select(max(ageColumn).aliased("maxAge")) ``` - `distinct()` performs uniquing: ```swift - // SELECT DISTINCT "name" FROM "persons" + // SELECT DISTINCT name FROM persons Person.select(nameColumn).distinct() ``` - `filter(expression)` applies conditions. ```swift - // SELECT * FROM "persons" WHERE ("id" IN (1, 2, 3)) + // SELECT * FROM persons WHERE id IN (1, 2, 3) Person.filter([1,2,3].contains(idColumn)) - // SELECT * FROM "persons" WHERE (("name" IS NOT NULL) AND ("height" > 1.75)) + // SELECT * FROM persons WHERE (name IS NOT NULL) AND (height > 1.75) Person.filter(nameColumn != nil && heightColumn > 1.75) ``` - `group(expression, ...)` groups rows. ```swift - // SELECT "name", MAX("age") FROM "persons" GROUP BY "name" + // SELECT name, MAX(age) FROM persons GROUP BY name Person .select(nameColumn, max(ageColumn)) .group(nameColumn) @@ -2155,7 +2336,7 @@ All the methods above return another request, which you can further refine by ap - `having(expression)` applies conditions on grouped rows. ```swift - // SELECT "name", MAX("age") FROM "persons" GROUP BY "name" HAVING MIN("age") >= 18 + // SELECT name, MAX(age) FROM persons GROUP BY name HAVING MIN(age) >= 18 Person .select(nameColumn, max(ageColumn)) .group(nameColumn) @@ -2165,59 +2346,59 @@ All the methods above return another request, which you can further refine by ap - `order(ordering, ...)` sorts. ```swift - // SELECT * FROM "persons" ORDER BY "name" + // SELECT * FROM persons ORDER BY name Person.order(nameColumn) - // SELECT * FROM "persons" ORDER BY "score" DESC, "name" + // SELECT * FROM persons ORDER BY score DESC, name Person.order(scoreColumn.desc, nameColumn) ``` Each `order` call clears any previous ordering: ```swift - // SELECT * FROM "persons" ORDER BY "name" + // SELECT * FROM persons ORDER BY name Person.order(scoreColumn).order(nameColumn) ``` - `reversed()` reverses the eventual orderings. ```swift - // SELECT * FROM "persons" ORDER BY "score" ASC, "name" DESC + // SELECT * FROM persons ORDER BY score ASC, name DESC Person.order(scoreColumn.desc, nameColumn).reversed() ``` If no ordering was specified, the result is ordered by rowID in reverse order. ```swift - // SELECT * FROM "persons" ORDER BY "_rowid_" DESC + // SELECT * FROM persons ORDER BY _rowid_ DESC Person.all().reversed() ``` - `limit(limit, offset: offset)` limits and pages results. ```swift - // SELECT * FROM "persons" LIMIT 5 + // SELECT * FROM persons LIMIT 5 Person.limit(5) - // SELECT * FROM "persons" LIMIT 5 OFFSET 10 + // SELECT * FROM persons LIMIT 5 OFFSET 10 Person.limit(5, offset: 10) ``` You can refine requests by chaining those methods: ```swift -// SELECT * FROM "persons" WHERE ("email" IS NOT NULL) ORDER BY "name" +// SELECT * FROM persons WHERE (email IS NOT NULL) ORDER BY name Person.order(nameColumn).filter(emailColumn != nil) ``` The `select`, `order`, `group`, and `limit` methods ignore and replace previously applied selection, orderings, grouping, and limits. On the opposite, `filter`, and `having` methods extend the query: ```swift -Person // SELECT * FROM "persons" - .filter(nameColumn != nil) // WHERE (("name" IS NOT NULL) - .filter(emailColumn != nil) // AND ("email IS NOT NULL")) +Person // SELECT * FROM persons + .filter(nameColumn != nil) // WHERE (name IS NOT NULL) + .filter(emailColumn != nil) // AND (email IS NOT NULL) .order(nameColumn) // - ignored - - .order(ageColumn) // ORDER BY "age" + .order(ageColumn) // ORDER BY age .limit(20, offset: 40) // - ignored - .limit(10) // LIMIT 10 ``` @@ -2226,7 +2407,7 @@ Person // SELECT * FROM "persons" Raw SQL snippets are also accepted, with eventual arguments: ```swift -// SELECT DATE(creationDate), COUNT(*) FROM "persons" WHERE name = 'Arthur' GROUP BY date(creationDate) +// SELECT DATE(creationDate), COUNT(*) FROM persons WHERE name = 'Arthur' GROUP BY date(creationDate) Person .select(sql: "DATE(creationDate), COUNT(*)") .filter(sql: "name = ?", arguments: ["Arthur"]) @@ -2246,19 +2427,19 @@ Feed [requests](#requests) with SQL expressions built from your Swift code: Comparison operators are based on the Swift operators `==`, `!=`, `===`, `!==`, `<`, `<=`, `>`, `>=`: ```swift - // SELECT * FROM "persons" WHERE ("name" = 'Arthur') + // SELECT * FROM persons WHERE (name = 'Arthur') Person.filter(nameColumn == "Arthur") - // SELECT * FROM "persons" WHERE ("name" IS NULL) + // SELECT * FROM persons WHERE (name IS NULL) Person.filter(nameColumn == nil) - // SELECT * FROM "persons" WHERE ("age" <> 18) + // SELECT * FROM persons WHERE (age <> 18) Person.filter(ageColumn != 18) - // SELECT * FROM "persons" WHERE ("age" IS NOT 18) + // SELECT * FROM persons WHERE (age IS NOT 18) Person.filter(ageColumn !== 18) - // SELECT * FROM "rectangles" WHERE ("width" < "height") + // SELECT * FROM rectangles WHERE width < height Rectangle.filter(widthColumn < heightColumn) ``` @@ -2270,7 +2451,7 @@ Feed [requests](#requests) with SQL expressions built from your Swift code: SQLite arithmetic operators are derived from their Swift equivalent: ```swift - // SELECT (("temperature" * 1.8) + 32) AS "farenheit" FROM "persons" + // SELECT ((temperature * 1.8) + 32) AS farenheit FROM persons Planet.select((temperatureColumn * 1.8 + 32).aliased("farenheit")) ``` @@ -2281,7 +2462,7 @@ Feed [requests](#requests) with SQL expressions built from your Swift code: The SQL logical operators are derived from the Swift `&&`, `||` and `!`: ```swift - // SELECT * FROM "persons" WHERE ((NOT "verified") OR ("age" < 18)) + // SELECT * FROM persons WHERE ((NOT verified) OR (age < 18)) Person.filter(!verifiedColumn || ageColumn < 18) ``` @@ -2290,22 +2471,22 @@ Feed [requests](#requests) with SQL expressions built from your Swift code: To check inclusion in a collection, call the `contains` method on any Swift sequence: ```swift - // SELECT * FROM "persons" WHERE ("id" IN (1, 2, 3)) + // SELECT * FROM persons WHERE id IN (1, 2, 3) Person.filter([1, 2, 3].contains(idColumn)) - // SELECT * FROM "persons" WHERE ("id" NOT IN (1, 2, 3)) + // SELECT * FROM persons WHERE id NOT IN (1, 2, 3) Person.filter(![1, 2, 3].contains(idColumn)) - // SELECT * FROM "persons" WHERE ("age" BETWEEN 0 AND 17) + // SELECT * FROM persons WHERE age BETWEEN 0 AND 17 Person.filter((0..<18).contains(ageColumn)) - // SELECT * FROM "persons" WHERE ("age" BETWEEN 0 AND 17) + // SELECT * FROM persons WHERE age BETWEEN 0 AND 17 Person.filter((0...17).contains(ageColumn)) - // SELECT * FROM "persons" WHERE ("name" BETWEEN 'A' AND 'z') + // SELECT * FROM persons WHERE name BETWEEN 'A' AND 'z' Person.filter(("A"..."z").contains(nameColumn)) - // SELECT * FROM "persons" WHERE (("name" >= 'A') AND ("name" < 'z')) + // SELECT * FROM persons WHERE (name >= 'A') AND (name < 'z') Person.filter(("A"..<"z").contains(nameColumn)) ``` @@ -2314,8 +2495,8 @@ Feed [requests](#requests) with SQL expressions built from your Swift code: To check inclusion in a subquery, call the `contains` method on another request: ```swift - // SELECT * FROM "events" - // WHERE ("userId" IN (SELECT "id" FROM "persons" WHERE "verified")) + // SELECT * FROM events + // WHERE userId IN (SELECT id FROM persons WHERE verified) let verifiedUserIds = User.select(idColumn).filter(verifiedColumn) Event.filter(verifiedUserIds.contains(userIdColumn)) ``` @@ -2325,8 +2506,8 @@ Feed [requests](#requests) with SQL expressions built from your Swift code: To check is a subquery would return any row, use the `exists` property on another request: ```swift - // SELECT * FROM "persons" - // WHERE EXISTS (SELECT * FROM "books" + // SELECT * FROM persons + // WHERE EXISTS (SELECT * FROM books // WHERE books.ownerId = persons.id) Person.filter(Book.filter(sql: "books.ownerId = persons.id").exists) ``` @@ -2334,18 +2515,18 @@ Feed [requests](#requests) with SQL expressions built from your Swift code: #### SQL Functions -- `ABS`, `AVG`, `COUNT`, `MAX`, `MIN`, `SUM`: +- `ABS`, `AVG`, `COUNT`, `LENGTH`, `MAX`, `MIN`, `SUM`: - Those are based on the `abs`, `average`, `count`, `max`, `min` and `sum` Swift functions: + Those are based on the `abs`, `average`, `count`, `length`, `max`, `min` and `sum` Swift functions: ```swift - // SELECT MIN("age"), MAX("age") FROM persons + // SELECT MIN(age), MAX(age) FROM persons Person.select(min(ageColumn), max(ageColumn)) - // SELECT COUNT("name") FROM persons + // SELECT COUNT(name) FROM persons Person.select(count(nameColumn)) - // SELECT COUNT(DISTINCT "name") FROM persons + // SELECT COUNT(DISTINCT name) FROM persons Person.select(count(distinct: nameColumn)) ``` @@ -2354,10 +2535,10 @@ Feed [requests](#requests) with SQL expressions built from your Swift code: Use the Swift `??` operator: ```swift - // SELECT IFNULL("name", 'Anonymous') FROM persons + // SELECT IFNULL(name, 'Anonymous') FROM persons Person.select(nameColumn ?? "Anonymous") - // SELECT IFNULL("name", "email") FROM persons + // SELECT IFNULL(name, email) FROM persons Person.select(nameColumn ?? emailColumn) ``` @@ -2380,7 +2561,7 @@ Feed [requests](#requests) with SQL expressions built from your Swift code: ```swift let f = DatabaseFunction("f", ...) - // SELECT f("name") FROM persons + // SELECT f(name) FROM persons Person.select(f.apply(nameColumn)) ``` @@ -2449,22 +2630,28 @@ For multiple-column primary keys, provide a dictionary: Citizenship.fetchOne(db, key: ["personID": 1, "countryISOCode": "FR"]) // Citizenship? ``` +You can use generally use a dictionary for any **unique key** (primary key and columns involved in a unique index): + +```swift +Person.fetchOne(db, key: ["email": "arthur@example.com"]) // Person? +``` + ### Fetching Aggregated Values **Requests can count.** The `fetchCount()` method returns the number of rows that would be returned by a fetch request: ```swift -// SELECT COUNT(*) FROM "persons" +// SELECT COUNT(*) FROM persons let count = Person.fetchCount(db) // Int -// SELECT COUNT(*) FROM "persons" WHERE "email" IS NOT NULL +// SELECT COUNT(*) FROM persons WHERE email IS NOT NULL let count = Person.filter(emailColumn != nil).fetchCount(db) -// SELECT COUNT(DISTINCT "name") FROM "persons" +// SELECT COUNT(DISTINCT name) FROM persons let count = Person.select(nameColumn).distinct().fetchCount(db) -// SELECT COUNT(*) FROM (SELECT DISTINCT "name", "age" FROM "persons") +// SELECT COUNT(*) FROM (SELECT DISTINCT name, age FROM persons) let count = Person.select(nameColumn, ageColumn).distinct().fetchCount(db) ``` @@ -2488,28 +2675,28 @@ let maxHeight = row.value(atIndex: 1) as Double? Migrations run in order, once and only once. When a user upgrades your application, only non-applied migrations are run. +Inside each migration, you typically [define and update your database tables](#database-schema) according to your evolving application needs: + ```swift var migrator = DatabaseMigrator() -// v1.0 database -migrator.registerMigration("createTables") { db in - try db.execute( - "CREATE TABLE persons (...); " + - "CREATE TABLE books (...)") +// v1 database +migrator.registerMigration("v1") { db in + try db.create(table: "persons") { t in ... } + try db.create(table: "books") { t in ... } + try db.create(index: ...) } -// v2.0 database -migrator.registerMigration("AddBirthDateToPersons") { db in - try db.execute( - "ALTER TABLE persons ADD COLUMN birthDate DATE") +// v2 database +migrator.registerMigration("v2") { db in + try db.alter(table: "persons") { t in ... } } // Migrations for future versions will be inserted here: // -// // v3.0 database -// migrator.registerMigration("AddYearAgeToBooks") { db in -// try db.execute( -// "ALTER TABLE books ADD COLUMN year INT") +// // v3 database +// migrator.registerMigration("v3") { db in +// ... // } try migrator.migrate(dbQueue) // or migrator.migrate(dbPool) @@ -2529,11 +2716,13 @@ Yet any kind of schema change is still possible. The SQLite documentation explai ```swift // Add a NOT NULL constraint on persons.name: migrator.registerMigrationWithDisabledForeignKeyChecks("AddNotNullCheckOnName") { db in - try db.execute( - "CREATE TABLE new_persons (id INTEGER PRIMARY KEY, name TEXT NOT NULL);" + - "INSERT INTO new_persons SELECT * FROM persons;" + - "DROP TABLE persons;" + - "ALTER TABLE new_persons RENAME TO persons;") + try db.create(table: "new_persons") { t in + t.column("id", .Integer).primaryKey() + t.column("name", .Text).notNull() + } + try db.execute("INSERT INTO new_persons SELECT * FROM persons") + try db.drop(table: "persons") + try db.rename(table: "new_persons", to: "persons") } ``` @@ -2653,7 +2842,7 @@ At first sight, this looks somewhat redundant with the checks that observers can ```swift // BAD: An inefficient way to track the "persons" table: -class PersonObserver: TransactionObserverType { +class PersonObserver: TransactionObserver { func databaseDidChange(with event: DatabaseEvent) { guard event.tableName == "persons" else { return @@ -3115,9 +3304,14 @@ See [Executing Updates](#executing-updates) for more information on statement ar ## Error Handling -**No SQLite error goes unnoticed.** +GRDB can throw [DatabaseError](#databaseerror), [PersistenceError](#persistenceerror), or crash your program with a [fatal error](#fatal-errors). -Some GRDB functions throw a DatabaseError (see [the list of SQLite error codes](https://www.sqlite.org/rescode.html)): +Considering that a local database is not some JSON loaded from a remote server, GRDB focuses on **trusted databases**. Dealing with [untrusted databases](#how-to-deal-with-untrusted-inputs) requires extra care. + + +### DatabaseError + +**DatabaseError** are thrown on SQLite errors (see [the list of SQLite error codes](https://www.sqlite.org/rescode.html)): ```swift do { @@ -3142,31 +3336,93 @@ do { } ``` -Fatal errors uncover programmer errors, false assumptions, and prevent misuses: + +### PersistenceError + +**PersistenceError** is thrown by the [Persistable](#persistable-protocol) protocol, in a single case: when the `update` method could not find any row to update: ```swift -// fatal error: -// SQLite error 1 with statement `SELECT * FROM boooks`: -// no such table: boooks -Row.fetchAll(db, "SELECT * FROM boooks") -// solution: fix the SQL query: -Row.fetchAll(db, "SELECT * FROM books") - -// fatal error: could not convert NULL to String. -let name: String = row.value(named: "name") -// solution: fix the contents of the database, or load an optional: -let name: String? = row.value(named: "name") - -// fatal error: Database methods are not reentrant. -dbQueue.inDatabase { db in - dbQueue.inDatabase { db in - ... - } +do { + try person.update(db) +} catch PersistenceError.NotFound { + // There was nothing to update } -// solution: avoid reentrancy, and instead pass a database connection along. ``` -**Fatal errors can be avoided**. For example, let's consider the code below: + +### Fatal Errors + +**Fatal errors notify that the program, or the database, has to be changed.** + +They uncover programmer errors, false assumptions, and prevent misuses. Here are a few examples: + +- The code contains a wrong SQL query: + + ```swift + // fatal error: + // SQLite error 1 with statement `SELECT * FROM boooks`: + // no such table: boooks + Row.fetchAll(db, "SELECT * FROM boooks") + ``` + + Solution: fix the SQL query. + + ```swift + Row.fetchAll(db, "SELECT * FROM books") + ``` + + If you do have to run untrusted SQL queries, jump to [untrusted databases](#how-to-deal-with-untrusted-inputs). + +- The code asks for a non-optional values, when the database contains NULL: + + ```swift + // fatal error: could not convert NULL to String. + let name: String = row.value(named: "name") + ``` + + Solution: fix the contents of the database, use [NOT NULL constraints](#create-tables), or load an optional: + + ```swift + let name: String? = row.value(named: "name") + ``` + +- The code asks for an NSDate, when the database contains garbage: + + ```swift + // fatal error: could not convert "Mom's birthday" to NSDate. + let date: NSDate? = row.value(named: "date") + ``` + + Solution: fix the contents of the database, or use [DatabaseValue](#databasevalue) to handle all possible cases: + + ```swift + let dbv = row.databaseValue(named: "date") + if dbv.isNull { + // Handle NULL + if let date = NSDate.fromDatabaseValue(dbv) { + // Handle valid date + } else { + // Handle invalid date + } + ``` + +- Database connections are not reentrant: + + ```swift + // fatal error: Database methods are not reentrant. + dbQueue.inDatabase { db in + dbQueue.inDatabase { db in + ... + } + } + ``` + + Solution: avoid reentrancy, and instead pass a database connection along. + + +### How to Deal with Untrusted Inputs + +Let's consider the code below: ```swift // Some untrusted SQL query @@ -3251,11 +3507,11 @@ Person.select(nameColumn.uppercased) SQLite compares strings in many occasions: when you sort rows according to a string column, or when you use a comparison operator such as `=` and `<=`. -The comparison result comes from a *collating function*, or *collation*. SQLite comes with [three built-in collations](https://www.sqlite.org/datatype3.html#collation) that do not support Unicode. +The comparison result comes from a *collating function*, or *collation*. SQLite comes with [three built-in collations](https://www.sqlite.org/datatype3.html#collation) that do not support Unicode: binary, nocase, and rtrim. GRDB comes with five extra collations that leverage unicode-aware comparisons based on the standard Swift String comparison functions and operators: -- `unicodeCompare` (uses the built-in `<=` and `==` operators) +- `unicodeCompare` (uses the built-in `<=` and `==` Swift operators) - `caseInsensitiveCompare` - `localizedCaseInsensitiveCompare` - `localizedCompare` @@ -3264,24 +3520,27 @@ GRDB comes with five extra collations that leverage unicode-aware comparisons ba A collation can be applied to a table column. All comparisons involving this column will then automatically trigger the comparison function: ```swift -let collation = DatabaseCollation.localizedCaseInsensitiveCompare -try db.execute( - "CREATE TABLE persons (" + - "name TEXT COLLATE \(collation.name)" + - ")") +try db.create(table: "persons") { t in + // Guarantees case-insensitive email unicity + t.column("email", .Text).unique().collate(.nocase) + + // Sort names in a localized case insensitive way + t.column("name", .Text).collate(.localizedCaseInsensitiveCompare) +} // Persons are sorted in a localized case insensitive way: let persons = Person.order(nameColumn).fetchAll(db) ``` -If you can't or don't want to define the comparison behavior of a column, you can still use an explicit collation in SQL requests and in the [query interface](#the-query-interface): +> :warning: **Warning**: SQLite *requires* host applications to provide the definition of any collation other than binary, nocase and rtrim. When a database file has to be shared or migrated to another SQLite library of platform (such as the Android version of your application), make sure you provide a compatible collation. + +If you can't or don't want to define the comparison behavior of a column (see warning above), you can still use an explicit collation in SQL requests and in the [query interface](#the-query-interface): ```swift let collation = DatabaseCollation.localizedCaseInsensitiveCompare let persons = Person.fetchAll(db, "SELECT * FROM persons ORDER BY name COLLATE \(collation.name))") let persons = Person.order(nameColumn.collating(collation)).fetchAll(db) -let persons = Person.filter(uuidColumn.collating("NOCASE") == uuid).fetchAll(db) ``` @@ -3373,7 +3632,7 @@ let count2 = dbQueue.inDatabase { db in SQLite concurrency is a wiiide topic. -First have a detailed look at the full API of [DatabaseQueue](http://cocoadocs.org/docsets/GRDB.swift/0.77.0/Classes/DatabaseQueue.html) and [DatabasePool](http://cocoadocs.org/docsets/GRDB.swift/0.77.0/Classes/DatabasePool.html). Both adopt the [DatabaseReader](http://cocoadocs.org/docsets/GRDB.swift/0.77.0/Protocols/DatabaseReader.html) and [DatabaseWriter](http://cocoadocs.org/docsets/GRDB.swift/0.77.0/Protocols/DatabaseWriter.html) protocols, so that you can write code that targets both classes. +First have a detailed look at the full API of [DatabaseQueue](http://cocoadocs.org/docsets/GRDB.swift/0.78.0/Classes/DatabaseQueue.html) and [DatabasePool](http://cocoadocs.org/docsets/GRDB.swift/0.78.0/Classes/DatabasePool.html). Both adopt the [DatabaseReader](http://cocoadocs.org/docsets/GRDB.swift/0.78.0/Protocols/DatabaseReader.html) and [DatabaseWriter](http://cocoadocs.org/docsets/GRDB.swift/0.78.0/Protocols/DatabaseWriter.html) protocols, so that you can write code that targets both classes. If the built-in queues and pools do not fit your needs, or if you can not guarantee that a single queue or pool is accessing your database file, you may have a look at: @@ -3533,8 +3792,7 @@ Instead, perform *a single query*: let sql = "SELECT authors.*, COUNT(books.id) AS bookCount " + "FROM authors " + "LEFT JOIN books ON books.authorId = authors.id " + - "GROUP BY authors.id " + - "ORDER BY authors.name" + "GROUP BY authors.id" let authors = Author.fetchAll(db, sql) ``` @@ -3586,7 +3844,7 @@ for person in Person.fetch(db) { // Column indexes // SELECT id, name, email FROM persons let request = Person.select(idColumn, nameColumn, emailColumn) -for row in Row.fetch(db, request).map { +for row in Row.fetch(db, request) { let id: Int64 = row.value(atIndex: 0) let name: String = row.value(atIndex: 1) let email: String = row.value(atIndex: 2) @@ -3595,7 +3853,7 @@ for row in Row.fetch(db, request).map { } ``` -When inserting values, use [prepared statements](#prepared-statements), and set statements values with an array: +When inserting values, use reusable [prepared statements](#prepared-statements), and set statements values with an *array*: ```swift // Strings & dictionaries @@ -3618,40 +3876,6 @@ for person in persons { FAQ === -- **Generic parameter 'T' could not be inferred** - - You may get this error when using DatabaseQueue.inDatabase, DatabasePool.read, or DatabasePool.write: - - ```swift - // Generic parameter 'T' could not be inferred - let x = dbQueue.inDatabase { db in - let result = String.fetchOne(db, ...) - return result - } - ``` - - This is a Swift compiler issue (see [SR-1570](https://bugs.swift.org/browse/SR-1570)). - - The general workaround is to explicitly declare the type of the closure result: - - ```swift - // General Workaround - let x = dbQueue.inDatabase { db -> String? in - let result = String.fetchOne(db, ...) - return result - } - ``` - - You can also, when possible, write a single-line closure: - - ```swift - // Single-line closure workaround: - let x = dbQueue.inDatabase { db in - String.fetchOne(db, ...) - } - ``` - - - **How do I close a database connection?** The short answer is: @@ -3693,6 +3917,39 @@ FAQ let dbQueue = try DatabaseQueue(path: dbPath) ``` +- **Generic parameter 'T' could not be inferred** + + You may get this error when using DatabaseQueue.inDatabase, DatabasePool.read, or DatabasePool.write: + + ```swift + // Generic parameter 'T' could not be inferred + let x = dbQueue.inDatabase { db in + let result = String.fetchOne(db, ...) + return result + } + ``` + + This is a Swift compiler issue (see [SR-1570](https://bugs.swift.org/browse/SR-1570)). + + The general workaround is to explicitly declare the type of the closure result: + + ```swift + // General Workaround + let x = dbQueue.inDatabase { db -> String? in + let result = String.fetchOne(db, ...) + return result + } + ``` + + You can also, when possible, write a single-line closure: + + ```swift + // Single-line closure workaround: + let x = dbQueue.inDatabase { db in + String.fetchOne(db, ...) + } + ``` + Sample Code =========== diff --git a/Support/Info.plist b/Support/Info.plist index 0564988c3..1aa3d9217 100644 --- a/Support/Info.plist +++ b/Support/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 0.77.0 + 0.78.0 CFBundleSignature ???? CFBundleVersion diff --git a/TODO.md b/TODO.md index f9dc28a65..12349458c 100644 --- a/TODO.md +++ b/TODO.md @@ -3,9 +3,7 @@ - [ ] Swift3: move more top-level enums inside an owner type. Foundation uses lowercase for those enum *types* (besides the lowercase *values*) - [ ] Swift3: check .autoreleaseWorkItem option in GCD Queue creation - [ ] Swift3: move database event filtering into the TransactionObserver protocol -- [ ] Document Statement.unsafeSetArguments - [ ] What is the behavior inTransaction and inSavepoint behaviors in case of commit error? Code looks like we do not rollback, leaving the app in a weird state (out of Swift transaction block with a SQLite transaction that may still be opened). ->>>>>>> c49506e588760f4bdfac649ac02ceffe484a1edb - [ ] GRDBCipher: remove limitations on iOS or OS X versions - [ ] FetchedRecordsController: take inspiration from https://github.com/jflinter/Dwifft - [ ] File protection: Read https://github.com/ccgus/fmdb/issues/262 and understand https://lists.apple.com/archives/cocoa-dev/2012/Aug/msg00527.html diff --git a/Tests/Performance/Realm b/Tests/Performance/Realm index 2a909e944..10ef693b9 160000 --- a/Tests/Performance/Realm +++ b/Tests/Performance/Realm @@ -1 +1 @@ -Subproject commit 2a909e9445d12117997bd5797c86cf496ccce752 +Subproject commit 10ef693b9935694f58f49b264008f6cf3ccccf61 diff --git a/Tests/Private/SQLExpressionLiteralTests.swift b/Tests/Private/SQLExpressionLiteralTests.swift index 36ae482e4..888fa8bc1 100644 --- a/Tests/Private/SQLExpressionLiteralTests.swift +++ b/Tests/Private/SQLExpressionLiteralTests.swift @@ -11,20 +11,20 @@ import XCTest class SQLExpressionLiteralTests: GRDBTestCase { func testWithArguments() { - let expression = SQLColumn("foo").collating("NOCASE") == "'bar'" && SQLColumn("baz") >= 1 + let expression = SQLColumn("foo").collating("NOCASE") == "'fooéı👨👨🏿🇫🇷🇨🇮'" && SQLColumn("baz") >= 1 var arguments: StatementArguments? = StatementArguments() let sql = expression.sql(&arguments) XCTAssertEqual(sql, "((\"foo\" = ? COLLATE NOCASE) AND (\"baz\" >= ?))") let values = arguments!.values XCTAssertEqual(values.count, 2) - XCTAssertEqual((values[0] as! String), "'bar'") + XCTAssertEqual((values[0] as! String), "'fooéı👨👨🏿🇫🇷🇨🇮'") XCTAssertEqual((values[1] as! Int), 1) } func testWithoutArguments() { - let expression = SQLColumn("foo").collating("NOCASE") == "'bar'" && SQLColumn("baz") >= 1 + let expression = SQLColumn("foo").collating("NOCASE") == "'fooéı👨👨🏿🇫🇷🇨🇮'" && SQLColumn("baz") >= 1 var arguments: StatementArguments? = nil let sql = expression.sql(&arguments) - XCTAssertEqual(sql, "((\"foo\" = '''bar''' COLLATE NOCASE) AND (\"baz\" >= 1))") + XCTAssertEqual(sql, "((\"foo\" = '''fooéı👨👨🏿🇫🇷🇨🇮''' COLLATE NOCASE) AND (\"baz\" >= 1))") } } diff --git a/Tests/Public/Core/DatabaseValueConvertible/DatabaseValueConversionTests.swift b/Tests/Public/Core/DatabaseValueConvertible/DatabaseValueConversionTests.swift index af3c1b3a9..9ee4ff3d2 100644 --- a/Tests/Public/Core/DatabaseValueConvertible/DatabaseValueConversionTests.swift +++ b/Tests/Public/Core/DatabaseValueConvertible/DatabaseValueConversionTests.swift @@ -172,10 +172,10 @@ class DatabaseValueConversionTests : GRDBTestCase { return .rollback } - // "fooéı👨👨🏿🇫🇷🇨🇮" is turned to Text + // "'fooéı👨👨🏿🇫🇷🇨🇮'" is turned to Text try dbQueue.inTransaction { db in - try db.execute("INSERT INTO `values` (textAffinity) VALUES (?)", arguments: ["fooéı👨👨🏿🇫🇷🇨🇮"]) + try db.execute("INSERT INTO `values` (textAffinity) VALUES (?)", arguments: ["'fooéı👨👨🏿🇫🇷🇨🇮'"]) let dbv = Row.fetchOne(db, "SELECT textAffinity FROM `values`")!.first!.1 // first is (columnName, dbv) XCTAssertEqual(dbv.storageClass, SQLiteStorageClass.text) @@ -185,11 +185,11 @@ class DatabaseValueConversionTests : GRDBTestCase { XCTAssertTrue(Int32.fromDatabaseValue(dbv) == nil) XCTAssertTrue(Int64.fromDatabaseValue(dbv) == nil) XCTAssertTrue(Double.fromDatabaseValue(dbv) == nil) - XCTAssertEqual(String.fromDatabaseValue(dbv)!, "fooéı👨👨🏿🇫🇷🇨🇮") + XCTAssertEqual(String.fromDatabaseValue(dbv)!, "'fooéı👨👨🏿🇫🇷🇨🇮'") XCTAssertTrue(Data.fromDatabaseValue(dbv) == nil) - XCTAssertEqual((dbv.value() as String?)!, "fooéı👨👨🏿🇫🇷🇨🇮") - XCTAssertEqual((dbv.value() as String), "fooéı👨👨🏿🇫🇷🇨🇮") + XCTAssertEqual((dbv.value() as String?)!, "'fooéı👨👨🏿🇫🇷🇨🇮'") + XCTAssertEqual((dbv.value() as String), "'fooéı👨👨🏿🇫🇷🇨🇮'") return .rollback } @@ -197,7 +197,7 @@ class DatabaseValueConversionTests : GRDBTestCase { // Blob is turned to Blob try dbQueue.inTransaction { db in - try db.execute("INSERT INTO `values` (textAffinity) VALUES (?)", arguments: ["fooéı👨👨🏿🇫🇷🇨🇮".data(using: .utf8)]) + try db.execute("INSERT INTO `values` (textAffinity) VALUES (?)", arguments: ["'fooéı👨👨🏿🇫🇷🇨🇮'".data(using: .utf8)]) let dbv = Row.fetchOne(db, "SELECT textAffinity FROM `values`")!.first!.1 // first is (columnName, dbv) XCTAssertEqual(dbv.storageClass, SQLiteStorageClass.blob) @@ -208,10 +208,10 @@ class DatabaseValueConversionTests : GRDBTestCase { XCTAssertTrue(Int64.fromDatabaseValue(dbv) == nil) XCTAssertTrue(Double.fromDatabaseValue(dbv) == nil) XCTAssertTrue(String.fromDatabaseValue(dbv) == nil) - XCTAssertEqual(Data.fromDatabaseValue(dbv), "fooéı👨👨🏿🇫🇷🇨🇮".data(using: .utf8)) + XCTAssertEqual(Data.fromDatabaseValue(dbv), "'fooéı👨👨🏿🇫🇷🇨🇮'".data(using: .utf8)) - XCTAssertEqual((dbv.value() as Data?)!, "fooéı👨👨🏿🇫🇷🇨🇮".data(using: .utf8)) - XCTAssertEqual((dbv.value() as Data), "fooéı👨👨🏿🇫🇷🇨🇮".data(using: .utf8)) + XCTAssertEqual((dbv.value() as Data?)!, "'fooéı👨👨🏿🇫🇷🇨🇮'".data(using: .utf8)) + XCTAssertEqual((dbv.value() as Data), "'fooéı👨👨🏿🇫🇷🇨🇮'".data(using: .utf8)) return .rollback } @@ -460,10 +460,10 @@ class DatabaseValueConversionTests : GRDBTestCase { return .rollback } - // "fooéı👨👨🏿🇫🇷🇨🇮" is turned to Text + // "'fooéı👨👨🏿🇫🇷🇨🇮'" is turned to Text try dbQueue.inTransaction { db in - try db.execute("INSERT INTO `values` (realAffinity) VALUES (?)", arguments: ["fooéı👨👨🏿🇫🇷🇨🇮"]) + try db.execute("INSERT INTO `values` (realAffinity) VALUES (?)", arguments: ["'fooéı👨👨🏿🇫🇷🇨🇮'"]) let dbv = Row.fetchOne(db, "SELECT realAffinity FROM `values`")!.first!.1 // first is (columnName, dbv) XCTAssertEqual(dbv.storageClass, SQLiteStorageClass.text) @@ -473,11 +473,11 @@ class DatabaseValueConversionTests : GRDBTestCase { XCTAssertTrue(Int32.fromDatabaseValue(dbv) == nil) XCTAssertTrue(Int64.fromDatabaseValue(dbv) == nil) XCTAssertTrue(Double.fromDatabaseValue(dbv) == nil) - XCTAssertEqual(String.fromDatabaseValue(dbv)!, "fooéı👨👨🏿🇫🇷🇨🇮") + XCTAssertEqual(String.fromDatabaseValue(dbv)!, "'fooéı👨👨🏿🇫🇷🇨🇮'") XCTAssertTrue(Data.fromDatabaseValue(dbv) == nil) - XCTAssertEqual((dbv.value() as String?)!, "fooéı👨👨🏿🇫🇷🇨🇮") - XCTAssertEqual((dbv.value() as String), "fooéı👨👨🏿🇫🇷🇨🇮") + XCTAssertEqual((dbv.value() as String?)!, "'fooéı👨👨🏿🇫🇷🇨🇮'") + XCTAssertEqual((dbv.value() as String), "'fooéı👨👨🏿🇫🇷🇨🇮'") return .rollback } @@ -485,7 +485,7 @@ class DatabaseValueConversionTests : GRDBTestCase { // Blob is turned to Blob try dbQueue.inTransaction { db in - try db.execute("INSERT INTO `values` (realAffinity) VALUES (?)", arguments: ["fooéı👨👨🏿🇫🇷🇨🇮".data(using: .utf8)]) + try db.execute("INSERT INTO `values` (realAffinity) VALUES (?)", arguments: ["'fooéı👨👨🏿🇫🇷🇨🇮'".data(using: .utf8)]) let dbv = Row.fetchOne(db, "SELECT realAffinity FROM `values`")!.first!.1 // first is (columnName, dbv) XCTAssertEqual(dbv.storageClass, SQLiteStorageClass.blob) @@ -496,10 +496,10 @@ class DatabaseValueConversionTests : GRDBTestCase { XCTAssertTrue(Int64.fromDatabaseValue(dbv) == nil) XCTAssertTrue(Double.fromDatabaseValue(dbv) == nil) XCTAssertTrue(String.fromDatabaseValue(dbv) == nil) - XCTAssertEqual(Data.fromDatabaseValue(dbv), "fooéı👨👨🏿🇫🇷🇨🇮".data(using: .utf8)) + XCTAssertEqual(Data.fromDatabaseValue(dbv), "'fooéı👨👨🏿🇫🇷🇨🇮'".data(using: .utf8)) - XCTAssertEqual((dbv.value() as Data?)!, "fooéı👨👨🏿🇫🇷🇨🇮".data(using: .utf8)) - XCTAssertEqual((dbv.value() as Data), "fooéı👨👨🏿🇫🇷🇨🇮".data(using: .utf8)) + XCTAssertEqual((dbv.value() as Data?)!, "'fooéı👨👨🏿🇫🇷🇨🇮'".data(using: .utf8)) + XCTAssertEqual((dbv.value() as Data), "'fooéı👨👨🏿🇫🇷🇨🇮'".data(using: .utf8)) return .rollback } @@ -661,7 +661,7 @@ class DatabaseValueConversionTests : GRDBTestCase { // Blob is turned to Blob try dbQueue.inTransaction { db in - try db.execute("INSERT INTO `values` (noneAffinity) VALUES (?)", arguments: ["fooéı👨👨🏿🇫🇷🇨🇮".data(using: .utf8)]) + try db.execute("INSERT INTO `values` (noneAffinity) VALUES (?)", arguments: ["'fooéı👨👨🏿🇫🇷🇨🇮'".data(using: .utf8)]) let dbv = Row.fetchOne(db, "SELECT noneAffinity FROM `values`")!.first!.1 // first is (columnName, dbv) XCTAssertEqual(dbv.storageClass, SQLiteStorageClass.blob) @@ -672,10 +672,10 @@ class DatabaseValueConversionTests : GRDBTestCase { XCTAssertTrue(Int64.fromDatabaseValue(dbv) == nil) XCTAssertTrue(Double.fromDatabaseValue(dbv) == nil) XCTAssertTrue(String.fromDatabaseValue(dbv) == nil) - XCTAssertEqual(Data.fromDatabaseValue(dbv), "fooéı👨👨🏿🇫🇷🇨🇮".data(using: .utf8)) + XCTAssertEqual(Data.fromDatabaseValue(dbv), "'fooéı👨👨🏿🇫🇷🇨🇮'".data(using: .utf8)) - XCTAssertEqual((dbv.value() as Data?)!, "fooéı👨👨🏿🇫🇷🇨🇮".data(using: .utf8)) - XCTAssertEqual((dbv.value() as Data), "fooéı👨👨🏿🇫🇷🇨🇮".data(using: .utf8)) + XCTAssertEqual((dbv.value() as Data?)!, "'fooéı👨👨🏿🇫🇷🇨🇮'".data(using: .utf8)) + XCTAssertEqual((dbv.value() as Data), "'fooéı👨👨🏿🇫🇷🇨🇮'".data(using: .utf8)) return .rollback } @@ -898,10 +898,10 @@ class DatabaseValueConversionTests : GRDBTestCase { return .rollback } - // "fooéı👨👨🏿🇫🇷🇨🇮" is turned to Text + // "'fooéı👨👨🏿🇫🇷🇨🇮'" is turned to Text try dbQueue.inTransaction { db in - try db.execute("INSERT INTO `values` (\(columnName)) VALUES (?)", arguments: ["fooéı👨👨🏿🇫🇷🇨🇮"]) + try db.execute("INSERT INTO `values` (\(columnName)) VALUES (?)", arguments: ["'fooéı👨👨🏿🇫🇷🇨🇮'"]) let dbv = Row.fetchOne(db, "SELECT \(columnName) FROM `values`")!.first!.1 // first is (columnName, dbv) XCTAssertEqual(dbv.storageClass, SQLiteStorageClass.text) @@ -911,11 +911,11 @@ class DatabaseValueConversionTests : GRDBTestCase { XCTAssertTrue(Int32.fromDatabaseValue(dbv) == nil) XCTAssertTrue(Int64.fromDatabaseValue(dbv) == nil) XCTAssertTrue(Double.fromDatabaseValue(dbv) == nil) - XCTAssertEqual(String.fromDatabaseValue(dbv)!, "fooéı👨👨🏿🇫🇷🇨🇮") + XCTAssertEqual(String.fromDatabaseValue(dbv)!, "'fooéı👨👨🏿🇫🇷🇨🇮'") XCTAssertTrue(Data.fromDatabaseValue(dbv) == nil) - XCTAssertEqual((dbv.value() as String?)!, "fooéı👨👨🏿🇫🇷🇨🇮") - XCTAssertEqual((dbv.value() as String), "fooéı👨👨🏿🇫🇷🇨🇮") + XCTAssertEqual((dbv.value() as String?)!, "'fooéı👨👨🏿🇫🇷🇨🇮'") + XCTAssertEqual((dbv.value() as String), "'fooéı👨👨🏿🇫🇷🇨🇮'") return .rollback } @@ -923,7 +923,7 @@ class DatabaseValueConversionTests : GRDBTestCase { // Blob is turned to Blob try dbQueue.inTransaction { db in - try db.execute("INSERT INTO `values` (\(columnName)) VALUES (?)", arguments: ["fooéı👨👨🏿🇫🇷🇨🇮".data(using: .utf8)]) + try db.execute("INSERT INTO `values` (\(columnName)) VALUES (?)", arguments: ["'fooéı👨👨🏿🇫🇷🇨🇮'".data(using: .utf8)]) let dbv = Row.fetchOne(db, "SELECT \(columnName) FROM `values`")!.first!.1 // first is (columnName, dbv) XCTAssertEqual(dbv.storageClass, SQLiteStorageClass.blob) @@ -934,10 +934,10 @@ class DatabaseValueConversionTests : GRDBTestCase { XCTAssertTrue(Int64.fromDatabaseValue(dbv) == nil) XCTAssertTrue(Double.fromDatabaseValue(dbv) == nil) XCTAssertTrue(String.fromDatabaseValue(dbv) == nil) - XCTAssertEqual(Data.fromDatabaseValue(dbv), "fooéı👨👨🏿🇫🇷🇨🇮".data(using: .utf8)) + XCTAssertEqual(Data.fromDatabaseValue(dbv), "'fooéı👨👨🏿🇫🇷🇨🇮'".data(using: .utf8)) - XCTAssertEqual((dbv.value() as Data?)!, "fooéı👨👨🏿🇫🇷🇨🇮".data(using: .utf8)) - XCTAssertEqual((dbv.value() as Data), "fooéı👨👨🏿🇫🇷🇨🇮".data(using: .utf8)) + XCTAssertEqual((dbv.value() as Data?)!, "'fooéı👨👨🏿🇫🇷🇨🇮'".data(using: .utf8)) + XCTAssertEqual((dbv.value() as Data), "'fooéı👨👨🏿🇫🇷🇨🇮'".data(using: .utf8)) return .rollback } diff --git a/Tests/Public/Core/StatementColumnConvertible/StatementColumnConvertibleTests.swift b/Tests/Public/Core/StatementColumnConvertible/StatementColumnConvertibleTests.swift index 970d32daa..4d2531fff 100644 --- a/Tests/Public/Core/StatementColumnConvertible/StatementColumnConvertibleTests.swift +++ b/Tests/Public/Core/StatementColumnConvertible/StatementColumnConvertibleTests.swift @@ -202,10 +202,10 @@ class StatementColumnConvertibleTests : GRDBTestCase { return .rollback } - // "fooéı👨👨🏿🇫🇷🇨🇮" is turned to Text + // "'fooéı👨👨🏿🇫🇷🇨🇮'" is turned to Text try dbQueue.inTransaction { db in - try db.execute("INSERT INTO `values` (textAffinity) VALUES (?)", arguments: ["fooéı👨👨🏿🇫🇷🇨🇮"]) + try db.execute("INSERT INTO `values` (textAffinity) VALUES (?)", arguments: ["'fooéı👨👨🏿🇫🇷🇨🇮'"]) // Check SQLite conversions from Text storage: for row in Row.fetch(db, "SELECT textAffinity FROM `values`") { XCTAssertEqual((row.value(atIndex: 0) as Bool?), false) // incompatible with DatabaseValue conversion @@ -223,12 +223,12 @@ class StatementColumnConvertibleTests : GRDBTestCase { XCTAssertEqual((row.value(atIndex: 0) as Double?), 0.0) // incompatible with DatabaseValue conversion } for row in Row.fetch(db, "SELECT textAffinity FROM `values`") { - XCTAssertEqual((row.value(atIndex: 0) as String?)!, "fooéı👨👨🏿🇫🇷🇨🇮") + XCTAssertEqual((row.value(atIndex: 0) as String?)!, "'fooéı👨👨🏿🇫🇷🇨🇮'") } for row in Row.fetch(db, "SELECT textAffinity FROM `values`") { - XCTAssertEqual((row.value(atIndex: 0) as String), "fooéı👨👨🏿🇫🇷🇨🇮") + XCTAssertEqual((row.value(atIndex: 0) as String), "'fooéı👨👨🏿🇫🇷🇨🇮'") } - // Data extraction: precondition failed: could not convert "fooéı👨👨🏿🇫🇷🇨🇮" to Data + // Data extraction: precondition failed: could not convert "'fooéı👨👨🏿🇫🇷🇨🇮'" to Data // for row in Row.fetch(db, "SELECT textAffinity FROM `values`") { // XCTAssertTrue((row.value(atIndex: 0) as Data?) == nil) // } @@ -238,7 +238,7 @@ class StatementColumnConvertibleTests : GRDBTestCase { // Blob is turned to Blob try dbQueue.inTransaction { db in - try db.execute("INSERT INTO `values` (textAffinity) VALUES (?)", arguments: ["fooéı👨👨🏿🇫🇷🇨🇮".data(using: .utf8)]) + try db.execute("INSERT INTO `values` (textAffinity) VALUES (?)", arguments: ["'fooéı👨👨🏿🇫🇷🇨🇮'".data(using: .utf8)]) // Check SQLite conversions from Blob storage: for row in Row.fetch(db, "SELECT textAffinity FROM `values`") { XCTAssertEqual((row.value(atIndex: 0) as Bool?), false) // incompatible with DatabaseValue conversion @@ -256,10 +256,10 @@ class StatementColumnConvertibleTests : GRDBTestCase { XCTAssertEqual((row.value(atIndex: 0) as Double?), 0.0) // incompatible with DatabaseValue conversion } for row in Row.fetch(db, "SELECT textAffinity FROM `values`") { - XCTAssertEqual((row.value(atIndex: 0) as String?), "fooéı👨👨🏿🇫🇷🇨🇮") // incompatible with DatabaseValue conversion + XCTAssertEqual((row.value(atIndex: 0) as String?), "'fooéı👨👨🏿🇫🇷🇨🇮'") // incompatible with DatabaseValue conversion } for row in Row.fetch(db, "SELECT textAffinity FROM `values`") { - XCTAssertEqual((row.value(atIndex: 0) as Data?), "fooéı👨👨🏿🇫🇷🇨🇮".data(using: .utf8)) + XCTAssertEqual((row.value(atIndex: 0) as Data?), "'fooéı👨👨🏿🇫🇷🇨🇮'".data(using: .utf8)) } return .rollback } @@ -595,10 +595,10 @@ class StatementColumnConvertibleTests : GRDBTestCase { return .rollback } - // "fooéı👨👨🏿🇫🇷🇨🇮" is turned to Text + // "'fooéı👨👨🏿🇫🇷🇨🇮'" is turned to Text try dbQueue.inTransaction { db in - try db.execute("INSERT INTO `values` (realAffinity) VALUES (?)", arguments: ["fooéı👨👨🏿🇫🇷🇨🇮"]) + try db.execute("INSERT INTO `values` (realAffinity) VALUES (?)", arguments: ["'fooéı👨👨🏿🇫🇷🇨🇮'"]) // Check SQLite conversions from Text storage: for row in Row.fetch(db, "SELECT realAffinity FROM `values`") { XCTAssertEqual((row.value(atIndex: 0) as Bool?), false) // incompatible with DatabaseValue conversion @@ -616,12 +616,12 @@ class StatementColumnConvertibleTests : GRDBTestCase { XCTAssertEqual((row.value(atIndex: 0) as Double?), 0.0) // incompatible with DatabaseValue conversion } for row in Row.fetch(db, "SELECT realAffinity FROM `values`") { - XCTAssertEqual((row.value(atIndex: 0) as String?)!, "fooéı👨👨🏿🇫🇷🇨🇮") + XCTAssertEqual((row.value(atIndex: 0) as String?)!, "'fooéı👨👨🏿🇫🇷🇨🇮'") } for row in Row.fetch(db, "SELECT realAffinity FROM `values`") { - XCTAssertEqual((row.value(atIndex: 0) as String), "fooéı👨👨🏿🇫🇷🇨🇮") + XCTAssertEqual((row.value(atIndex: 0) as String), "'fooéı👨👨🏿🇫🇷🇨🇮'") } - // Data extraction: precondition failed: could not convert "fooéı👨👨🏿🇫🇷🇨🇮" to Data + // Data extraction: precondition failed: could not convert "'fooéı👨👨🏿🇫🇷🇨🇮'" to Data // for row in Row.fetch(db, "SELECT realAffinity FROM `values`") { // XCTAssertTrue((row.value(atIndex: 0) as Data?) == nil) // } @@ -631,7 +631,7 @@ class StatementColumnConvertibleTests : GRDBTestCase { // Blob is turned to Blob try dbQueue.inTransaction { db in - try db.execute("INSERT INTO `values` (realAffinity) VALUES (?)", arguments: ["fooéı👨👨🏿🇫🇷🇨🇮".data(using: .utf8)]) + try db.execute("INSERT INTO `values` (realAffinity) VALUES (?)", arguments: ["'fooéı👨👨🏿🇫🇷🇨🇮'".data(using: .utf8)]) // Check SQLite conversions from Blob storage: for row in Row.fetch(db, "SELECT realAffinity FROM `values`") { XCTAssertEqual((row.value(atIndex: 0) as Bool?), false) // incompatible with DatabaseValue conversion @@ -649,10 +649,10 @@ class StatementColumnConvertibleTests : GRDBTestCase { XCTAssertEqual((row.value(atIndex: 0) as Double?), 0.0) // incompatible with DatabaseValue conversion } for row in Row.fetch(db, "SELECT realAffinity FROM `values`") { - XCTAssertEqual((row.value(atIndex: 0) as String?), "fooéı👨👨🏿🇫🇷🇨🇮") // incompatible with DatabaseValue conversion + XCTAssertEqual((row.value(atIndex: 0) as String?), "'fooéı👨👨🏿🇫🇷🇨🇮'") // incompatible with DatabaseValue conversion } for row in Row.fetch(db, "SELECT realAffinity FROM `values`") { - XCTAssertEqual((row.value(atIndex: 0) as Data?), "fooéı👨👨🏿🇫🇷🇨🇮".data(using: .utf8)) + XCTAssertEqual((row.value(atIndex: 0) as Data?), "'fooéı👨👨🏿🇫🇷🇨🇮'".data(using: .utf8)) } return .rollback } @@ -885,7 +885,7 @@ class StatementColumnConvertibleTests : GRDBTestCase { // Blob is turned to Blob try dbQueue.inTransaction { db in - try db.execute("INSERT INTO `values` (noneAffinity) VALUES (?)", arguments: ["fooéı👨👨🏿🇫🇷🇨🇮".data(using: .utf8)]) + try db.execute("INSERT INTO `values` (noneAffinity) VALUES (?)", arguments: ["'fooéı👨👨🏿🇫🇷🇨🇮'".data(using: .utf8)]) // Check SQLite conversions from Blob storage for row in Row.fetch(db, "SELECT noneAffinity FROM `values`") { XCTAssertEqual((row.value(atIndex: 0) as Bool?), false) // incompatible with DatabaseValue conversion @@ -903,10 +903,10 @@ class StatementColumnConvertibleTests : GRDBTestCase { XCTAssertEqual((row.value(atIndex: 0) as Double?), 0.0) // incompatible with DatabaseValue conversion } for row in Row.fetch(db, "SELECT noneAffinity FROM `values`") { - XCTAssertEqual((row.value(atIndex: 0) as String?), "fooéı👨👨🏿🇫🇷🇨🇮") // incompatible with DatabaseValue conversion + XCTAssertEqual((row.value(atIndex: 0) as String?), "'fooéı👨👨🏿🇫🇷🇨🇮'") // incompatible with DatabaseValue conversion } for row in Row.fetch(db, "SELECT noneAffinity FROM `values`") { - XCTAssertEqual((row.value(atIndex: 0) as Data?), "fooéı👨👨🏿🇫🇷🇨🇮".data(using: .utf8)) + XCTAssertEqual((row.value(atIndex: 0) as Data?), "'fooéı👨👨🏿🇫🇷🇨🇮'".data(using: .utf8)) } return .rollback } @@ -1216,10 +1216,10 @@ class StatementColumnConvertibleTests : GRDBTestCase { return .rollback } - // "fooéı👨👨🏿🇫🇷🇨🇮" is turned to Text + // "'fooéı👨👨🏿🇫🇷🇨🇮'" is turned to Text try dbQueue.inTransaction { db in - try db.execute("INSERT INTO `values` (\(columnName)) VALUES (?)", arguments: ["fooéı👨👨🏿🇫🇷🇨🇮"]) + try db.execute("INSERT INTO `values` (\(columnName)) VALUES (?)", arguments: ["'fooéı👨👨🏿🇫🇷🇨🇮'"]) // Check SQLite conversions from Text storage: for row in Row.fetch(db, "SELECT \(columnName) FROM `values`") { XCTAssertEqual((row.value(atIndex: 0) as Bool?), false) // incompatible with DatabaseValue conversion @@ -1237,12 +1237,12 @@ class StatementColumnConvertibleTests : GRDBTestCase { XCTAssertEqual((row.value(atIndex: 0) as Double?), 0.0) // incompatible with DatabaseValue conversion } for row in Row.fetch(db, "SELECT \(columnName) FROM `values`") { - XCTAssertEqual((row.value(atIndex: 0) as String?)!, "fooéı👨👨🏿🇫🇷🇨🇮") + XCTAssertEqual((row.value(atIndex: 0) as String?)!, "'fooéı👨👨🏿🇫🇷🇨🇮'") } for row in Row.fetch(db, "SELECT \(columnName) FROM `values`") { - XCTAssertEqual((row.value(atIndex: 0) as String), "fooéı👨👨🏿🇫🇷🇨🇮") + XCTAssertEqual((row.value(atIndex: 0) as String), "'fooéı👨👨🏿🇫🇷🇨🇮'") } - // Data extraction: precondition failed: could not convert "fooéı👨👨🏿🇫🇷🇨🇮" to Data + // Data extraction: precondition failed: could not convert "'fooéı👨👨🏿🇫🇷🇨🇮'" to Data // for row in Row.fetch(db, "SELECT \(columnName) FROM `values`") { // XCTAssertTrue((row.value(atIndex: 0) as Data?) == nil) // } @@ -1252,7 +1252,7 @@ class StatementColumnConvertibleTests : GRDBTestCase { // Blob is turned to Blob try dbQueue.inTransaction { db in - try db.execute("INSERT INTO `values` (\(columnName)) VALUES (?)", arguments: ["fooéı👨👨🏿🇫🇷🇨🇮".data(using: .utf8)]) + try db.execute("INSERT INTO `values` (\(columnName)) VALUES (?)", arguments: ["'fooéı👨👨🏿🇫🇷🇨🇮'".data(using: .utf8)]) // Check SQLite conversions from Blob storage: for row in Row.fetch(db, "SELECT \(columnName) FROM `values`") { XCTAssertEqual((row.value(atIndex: 0) as Bool?), false) // incompatible with DatabaseValue conversion @@ -1270,10 +1270,10 @@ class StatementColumnConvertibleTests : GRDBTestCase { XCTAssertEqual((row.value(atIndex: 0) as Double?), 0.0) // incompatible with DatabaseValue conversion } for row in Row.fetch(db, "SELECT \(columnName) FROM `values`") { - XCTAssertEqual((row.value(atIndex: 0) as String?), "fooéı👨👨🏿🇫🇷🇨🇮") // incompatible with DatabaseValue conversion + XCTAssertEqual((row.value(atIndex: 0) as String?), "'fooéı👨👨🏿🇫🇷🇨🇮'") // incompatible with DatabaseValue conversion } for row in Row.fetch(db, "SELECT \(columnName) FROM `values`") { - XCTAssertEqual((row.value(atIndex: 0) as Data?), "fooéı👨👨🏿🇫🇷🇨🇮".data(using: .utf8)) + XCTAssertEqual((row.value(atIndex: 0) as Data?), "'fooéı👨👨🏿🇫🇷🇨🇮'".data(using: .utf8)) } return .rollback } diff --git a/Tests/Public/QueryInterfaceRequest/QueryInterfaceRequestTests.swift b/Tests/Public/QueryInterfaceRequest/QueryInterfaceRequestTests.swift index fb7f6fd60..98a36a9b3 100644 --- a/Tests/Public/QueryInterfaceRequest/QueryInterfaceRequestTests.swift +++ b/Tests/Public/QueryInterfaceRequest/QueryInterfaceRequestTests.swift @@ -401,10 +401,10 @@ class QueryInterfaceRequestTests: GRDBTestCase { func testSortWithCollation() { let dbQueue = try! makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.order(Col.name.collating("NOCASE"))), + sql(dbQueue, tableRequest.order(Col.name.collating(.nocase))), "SELECT * FROM \"readers\" ORDER BY \"name\" COLLATE NOCASE") XCTAssertEqual( - sql(dbQueue, tableRequest.order(Col.name.collating("NOCASE").asc)), + sql(dbQueue, tableRequest.order(Col.name.collating(.nocase).asc)), "SELECT * FROM \"readers\" ORDER BY \"name\" COLLATE NOCASE ASC") XCTAssertEqual( sql(dbQueue, tableRequest.order(Col.name.collating(collation))), @@ -446,10 +446,10 @@ class QueryInterfaceRequestTests: GRDBTestCase { func testReverseWithCollation() { let dbQueue = try! makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.order(Col.name.collating("NOCASE")).reversed()), + sql(dbQueue, tableRequest.order(Col.name.collating(.nocase)).reversed()), "SELECT * FROM \"readers\" ORDER BY \"name\" COLLATE NOCASE DESC") XCTAssertEqual( - sql(dbQueue, tableRequest.order(Col.name.collating("NOCASE").asc).reversed()), + sql(dbQueue, tableRequest.order(Col.name.collating(.nocase).asc).reversed()), "SELECT * FROM \"readers\" ORDER BY \"name\" COLLATE NOCASE DESC") XCTAssertEqual( sql(dbQueue, tableRequest.order(Col.name.collating(collation)).reversed()), diff --git a/Tests/Public/QueryInterfaceRequest/SQLSupportTests.swift b/Tests/Public/QueryInterfaceRequest/SQLSupportTests.swift index 0327b5fdb..4e51c59ba 100644 --- a/Tests/Public/QueryInterfaceRequest/SQLSupportTests.swift +++ b/Tests/Public/QueryInterfaceRequest/SQLSupportTests.swift @@ -134,29 +134,29 @@ class SQLSupportTests: GRDBTestCase { // Array.contains(): IN operator XCTAssertEqual( - sql(dbQueue, tableRequest.filter(["arthur", "barbara"].contains(Col.name.collating("NOCASE")))), + sql(dbQueue, tableRequest.filter(["arthur", "barbara"].contains(Col.name.collating(.nocase)))), "SELECT * FROM \"readers\" WHERE (\"name\" IN ('arthur', 'barbara') COLLATE NOCASE)") // Sequence.contains(): IN operator XCTAssertEqual( - sql(dbQueue, tableRequest.filter(AnySequence(["arthur", "barbara"]).contains(Col.name.collating("NOCASE")))), + sql(dbQueue, tableRequest.filter(AnySequence(["arthur", "barbara"]).contains(Col.name.collating(.nocase)))), "SELECT * FROM \"readers\" WHERE (\"name\" IN ('arthur', 'barbara') COLLATE NOCASE)") // Sequence.contains(): IN operator XCTAssertEqual( - sql(dbQueue, tableRequest.filter(AnySequence([Col.name]).contains(Col.name.collating("NOCASE")))), + sql(dbQueue, tableRequest.filter(AnySequence([Col.name]).contains(Col.name.collating(.nocase)))), "SELECT * FROM \"readers\" WHERE (\"name\" IN (\"name\") COLLATE NOCASE)") // ClosedInterval: BETWEEN operator let closedInterval = "A"..."z" XCTAssertEqual( - sql(dbQueue, tableRequest.filter(closedInterval.contains(Col.name.collating("NOCASE")))), + sql(dbQueue, tableRequest.filter(closedInterval.contains(Col.name.collating(.nocase)))), "SELECT * FROM \"readers\" WHERE (\"name\" BETWEEN 'A' AND 'z' COLLATE NOCASE)") // HalfOpenInterval: min <= x < max let halfOpenInterval = "A"..<"z" XCTAssertEqual( - sql(dbQueue, tableRequest.filter(halfOpenInterval.contains(Col.name.collating("NOCASE")))), + sql(dbQueue, tableRequest.filter(halfOpenInterval.contains(Col.name.collating(.nocase)))), "SELECT * FROM \"readers\" WHERE ((\"name\" >= 'A' COLLATE NOCASE) AND (\"name\" < 'z' COLLATE NOCASE))") } @@ -198,7 +198,7 @@ class SQLSupportTests: GRDBTestCase { let dbQueue = try! makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name.collating("NOCASE") > "fOo")), + sql(dbQueue, tableRequest.filter(Col.name.collating(.nocase) > "fOo")), "SELECT * FROM \"readers\" WHERE (\"name\" > 'fOo' COLLATE NOCASE)") XCTAssertEqual( sql(dbQueue, tableRequest.filter(Col.name.collating(collation) > "fOo")), @@ -243,7 +243,7 @@ class SQLSupportTests: GRDBTestCase { let dbQueue = try! makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name.collating("NOCASE") >= "fOo")), + sql(dbQueue, tableRequest.filter(Col.name.collating(.nocase) >= "fOo")), "SELECT * FROM \"readers\" WHERE (\"name\" >= 'fOo' COLLATE NOCASE)") XCTAssertEqual( sql(dbQueue, tableRequest.filter(Col.name.collating(collation) >= "fOo")), @@ -288,7 +288,7 @@ class SQLSupportTests: GRDBTestCase { let dbQueue = try! makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name.collating("NOCASE") < "fOo")), + sql(dbQueue, tableRequest.filter(Col.name.collating(.nocase) < "fOo")), "SELECT * FROM \"readers\" WHERE (\"name\" < 'fOo' COLLATE NOCASE)") XCTAssertEqual( sql(dbQueue, tableRequest.filter(Col.name.collating(collation) < "fOo")), @@ -333,7 +333,7 @@ class SQLSupportTests: GRDBTestCase { let dbQueue = try! makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name.collating("NOCASE") <= "fOo")), + sql(dbQueue, tableRequest.filter(Col.name.collating(.nocase) <= "fOo")), "SELECT * FROM \"readers\" WHERE (\"name\" <= 'fOo' COLLATE NOCASE)") XCTAssertEqual( sql(dbQueue, tableRequest.filter(Col.name.collating(collation) <= "fOo")), @@ -412,13 +412,13 @@ class SQLSupportTests: GRDBTestCase { let dbQueue = try! makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name.collating("NOCASE") == "fOo")), + sql(dbQueue, tableRequest.filter(Col.name.collating(.nocase) == "fOo")), "SELECT * FROM \"readers\" WHERE (\"name\" = 'fOo' COLLATE NOCASE)") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name.collating("NOCASE") == ("fOo" as String?))), + sql(dbQueue, tableRequest.filter(Col.name.collating(.nocase) == ("fOo" as String?))), "SELECT * FROM \"readers\" WHERE (\"name\" = 'fOo' COLLATE NOCASE)") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name.collating("NOCASE") == nil)), + sql(dbQueue, tableRequest.filter(Col.name.collating(.nocase) == nil)), "SELECT * FROM \"readers\" WHERE (\"name\" IS NULL COLLATE NOCASE)") XCTAssertEqual( sql(dbQueue, tableRequest.filter(Col.name.collating(collation) == "fOo")), @@ -497,13 +497,13 @@ class SQLSupportTests: GRDBTestCase { let dbQueue = try! makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name.collating("NOCASE") != "fOo")), + sql(dbQueue, tableRequest.filter(Col.name.collating(.nocase) != "fOo")), "SELECT * FROM \"readers\" WHERE (\"name\" <> 'fOo' COLLATE NOCASE)") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name.collating("NOCASE") != ("fOo" as String?))), + sql(dbQueue, tableRequest.filter(Col.name.collating(.nocase) != ("fOo" as String?))), "SELECT * FROM \"readers\" WHERE (\"name\" <> 'fOo' COLLATE NOCASE)") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name.collating("NOCASE") != nil)), + sql(dbQueue, tableRequest.filter(Col.name.collating(.nocase) != nil)), "SELECT * FROM \"readers\" WHERE (\"name\" IS NOT NULL COLLATE NOCASE)") XCTAssertEqual( sql(dbQueue, tableRequest.filter(Col.name.collating(collation) != "fOo")), @@ -581,7 +581,7 @@ class SQLSupportTests: GRDBTestCase { let dbQueue = try! makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name.collating("NOCASE") === "fOo")), + sql(dbQueue, tableRequest.filter(Col.name.collating(.nocase) === "fOo")), "SELECT * FROM \"readers\" WHERE (\"name\" IS 'fOo' COLLATE NOCASE)") XCTAssertEqual( sql(dbQueue, tableRequest.filter(Col.name.collating(collation) === "fOo")), @@ -632,7 +632,7 @@ class SQLSupportTests: GRDBTestCase { let dbQueue = try! makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name.collating("NOCASE") !== "fOo")), + sql(dbQueue, tableRequest.filter(Col.name.collating(.nocase) !== "fOo")), "SELECT * FROM \"readers\" WHERE (\"name\" IS NOT 'fOo' COLLATE NOCASE)") XCTAssertEqual( sql(dbQueue, tableRequest.filter(Col.name.collating(collation) !== "fOo")), @@ -893,6 +893,14 @@ class SQLSupportTests: GRDBTestCase { "SELECT AVG((\"age\" / 2)) FROM \"readers\"") } + func testLengthExpression() { + let dbQueue = try! makeDatabaseQueue() + + XCTAssertEqual( + sql(dbQueue, tableRequest.select(length(Col.name))), + "SELECT LENGTH(\"name\") FROM \"readers\"") + } + func testMinExpression() { let dbQueue = try! makeDatabaseQueue() diff --git a/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift b/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift new file mode 100644 index 000000000..27acbe2e6 --- /dev/null +++ b/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift @@ -0,0 +1,432 @@ +import XCTest +#if USING_SQLCIPHER + import GRDBCipher +#elseif USING_CUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +class SQLTableBuilderTests: GRDBTestCase { + + func testCreateTable() { + assertNoError { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + // Simple table creation + try db.create(table: "test") { t in + t.column("id", .integer).primaryKey() + t.column("name", .text) + } + XCTAssertEqual(self.lastSQLQuery, + "CREATE TABLE \"test\" (" + + "\"id\" INTEGER PRIMARY KEY, " + + "\"name\" TEXT" + + ")") + } + } + } + + func testTableCreationOptions() { + assertNoError { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "test", temporary: true, ifNotExists: true, withoutRowID: true) { t in + t.column("id", .integer).primaryKey() + } + XCTAssertEqual(self.lastSQLQuery, + "CREATE TEMPORARY TABLE IF NOT EXISTS \"test\" (" + + "\"id\" INTEGER PRIMARY KEY" + + ") WITHOUT ROWID") + } + } + } + + func testColumnPrimaryKeyOptions() { + assertNoError { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inTransaction { db in + try db.create(table: "test") { t in + t.column("id", .integer).primaryKey(onConflict: .fail) + } + XCTAssertEqual(self.lastSQLQuery, + "CREATE TABLE \"test\" (" + + "\"id\" INTEGER PRIMARY KEY ON CONFLICT FAIL" + + ")") + return .rollback + } + try dbQueue.inTransaction { db in + try db.create(table: "test") { t in + t.column("id", .integer).primaryKey(autoincrement: true) + } + XCTAssertEqual(self.lastSQLQuery, + "CREATE TABLE \"test\" (" + + "\"id\" INTEGER PRIMARY KEY AUTOINCREMENT" + + ")") + return .rollback + } + } + } + + func testColumnNotNull() { + assertNoError { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "test") { t in + t.column("a", .integer).notNull() + t.column("b", .integer).notNull(onConflict: .abort) + t.column("c", .integer).notNull(onConflict: .rollback) + t.column("d", .integer).notNull(onConflict: .fail) + t.column("e", .integer).notNull(onConflict: .ignore) + t.column("f", .integer).notNull(onConflict: .replace) + } + XCTAssertEqual(self.lastSQLQuery, + "CREATE TABLE \"test\" (" + + "\"a\" INTEGER NOT NULL, " + + "\"b\" INTEGER NOT NULL, " + + "\"c\" INTEGER NOT NULL ON CONFLICT ROLLBACK, " + + "\"d\" INTEGER NOT NULL ON CONFLICT FAIL, " + + "\"e\" INTEGER NOT NULL ON CONFLICT IGNORE, " + + "\"f\" INTEGER NOT NULL ON CONFLICT REPLACE" + + ")") + } + } + } + + func testColumnUnique() { + assertNoError { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "test") { t in + t.column("a", .integer).unique() + t.column("b", .integer).unique(onConflict: .abort) + t.column("c", .integer).unique(onConflict: .rollback) + t.column("d", .integer).unique(onConflict: .fail) + t.column("e", .integer).unique(onConflict: .ignore) + t.column("f", .integer).unique(onConflict: .replace) + } + XCTAssertEqual(self.lastSQLQuery, + "CREATE TABLE \"test\" (" + + "\"a\" INTEGER UNIQUE, " + + "\"b\" INTEGER UNIQUE, " + + "\"c\" INTEGER UNIQUE ON CONFLICT ROLLBACK, " + + "\"d\" INTEGER UNIQUE ON CONFLICT FAIL, " + + "\"e\" INTEGER UNIQUE ON CONFLICT IGNORE, " + + "\"f\" INTEGER UNIQUE ON CONFLICT REPLACE" + + ")") + } + } + } + + func testColumnCheck() { + assertNoError { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "test") { t in + t.column("a", .integer).check { $0 > 0 } + t.column("b", .integer).check(sql: "b <> 2") + } + XCTAssertEqual(self.lastSQLQuery, + "CREATE TABLE \"test\" (" + + "\"a\" INTEGER CHECK ((\"a\" > 0)), " + + "\"b\" INTEGER CHECK (b <> 2)" + + ")") + + // Sanity check + try db.execute("INSERT INTO test (a, b) VALUES (1, 0)") + do { + try db.execute("INSERT INTO test (a, b) VALUES (0, 0)") + XCTFail() + } catch { + } + } + } + } + + func testColumnDefault() { + assertNoError { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "test") { t in + t.column("a", .integer).defaults(1) + t.column("b", .integer).defaults(1.0) + t.column("c", .integer).defaults("'fooéı👨👨🏿🇫🇷🇨🇮'") + t.column("d", .integer).defaults("foo".data(using: .utf8)!) + t.column("e", .integer).defaults(sql: "NULL") + } + XCTAssertEqual(self.lastSQLQuery, + "CREATE TABLE \"test\" (" + + "\"a\" INTEGER DEFAULT 1, " + + "\"b\" INTEGER DEFAULT 1.0, " + + "\"c\" INTEGER DEFAULT '''fooéı👨👨🏿🇫🇷🇨🇮''', " + + "\"d\" INTEGER DEFAULT x'666f6f', " + + "\"e\" INTEGER DEFAULT NULL" + + ")") + + // Sanity check + try db.execute("INSERT INTO test DEFAULT VALUES") + XCTAssertEqual(Int.fetchOne(db, "SELECT a FROM test")!, 1) + XCTAssertEqual(String.fetchOne(db, "SELECT c FROM test")!, "'fooéı👨👨🏿🇫🇷🇨🇮'") + } + } + } + + func testColumnCollation() { + assertNoError { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inTransaction { db in + try db.create(table: "test") { t in + t.column("name", .text).collate(.nocase) + } + XCTAssertEqual(self.lastSQLQuery, + "CREATE TABLE \"test\" (" + + "\"name\" TEXT COLLATE NOCASE" + + ")") + return .rollback + } + + let collation = DatabaseCollation("foo") { (lhs, rhs) in .orderedSame } + dbQueue.add(collation: collation) + try dbQueue.inTransaction { db in + try db.create(table: "test") { t in + t.column("name", .text).collate(collation) + } + XCTAssertEqual(self.lastSQLQuery, + "CREATE TABLE \"test\" (" + + "\"name\" TEXT COLLATE foo" + + ")") + return .rollback + } + } + } + + func testColumnReference() { + assertNoError { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parent") { t in + t.column("name", .text).primaryKey() + t.column("email", .text).unique() + } + try db.create(table: "child") { t in + t.column("parentName", .text).references("parent", onDelete: .cascade, onUpdate: .cascade) + t.column("parentEmail", .text).references("parent", column: "email", onDelete: .restrict, deferred: true) + } + XCTAssertEqual(self.lastSQLQuery, + "CREATE TABLE \"child\" (" + + "\"parentName\" TEXT REFERENCES \"parent\"(\"name\") ON DELETE CASCADE ON UPDATE CASCADE, " + + "\"parentEmail\" TEXT REFERENCES \"parent\"(\"email\") ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED" + + ")") + } + } + } + + func testTablePrimaryKey() { + assertNoError { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inTransaction { db in + try db.create(table: "test") { t in + t.primaryKey(["a", "b"]) + t.column("a", .text) + t.column("b", .text) + } + XCTAssertEqual(self.lastSQLQuery, + "CREATE TABLE \"test\" (" + + "\"a\" TEXT, " + + "\"b\" TEXT, " + + "PRIMARY KEY (\"a\", \"b\")" + + ")") + return .rollback + } + try dbQueue.inTransaction { db in + try db.create(table: "test") { t in + t.primaryKey(["a", "b"], onConflict: .fail) + t.column("a", .text) + t.column("b", .text) + } + XCTAssertEqual(self.lastSQLQuery, + "CREATE TABLE \"test\" (" + + "\"a\" TEXT, " + + "\"b\" TEXT, " + + "PRIMARY KEY (\"a\", \"b\") ON CONFLICT FAIL" + + ")") + return .rollback + } + } + } + + func testTableUniqueKey() { + assertNoError { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "test") { t in + t.uniqueKey(["a"]) + t.uniqueKey(["b", "c"], onConflict: .fail) + t.column("a", .text) + t.column("b", .text) + t.column("c", .text) + } + XCTAssertEqual(self.lastSQLQuery, + "CREATE TABLE \"test\" (" + + "\"a\" TEXT, " + + "\"b\" TEXT, " + + "\"c\" TEXT, " + + "UNIQUE (\"a\"), " + + "UNIQUE (\"b\", \"c\") ON CONFLICT FAIL" + + ")") + } + } + } + + func testTableForeignKey() { + assertNoError { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parent") { t in + t.primaryKey(["a", "b"]) + t.column("a", .text) + t.column("b", .text) + } + try db.create(table: "child") { t in + t.foreignKey(["c", "d"], references: "parent", onDelete: .cascade, onUpdate: .cascade) + t.foreignKey(["d", "e"], references: "parent", columns: ["b", "a"], onDelete: .restrict, deferred: true) + t.column("c", .text) + t.column("d", .text) + t.column("e", .text) + } + XCTAssertEqual(self.lastSQLQuery, + "CREATE TABLE \"child\" (" + + "\"c\" TEXT, " + + "\"d\" TEXT, " + + "\"e\" TEXT, " + + "FOREIGN KEY (\"c\", \"d\") REFERENCES \"parent\"(\"a\", \"b\") ON DELETE CASCADE ON UPDATE CASCADE, " + + "FOREIGN KEY (\"d\", \"e\") REFERENCES \"parent\"(\"b\", \"a\") ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED" + + ")") + } + } + } + + func testTableCheck() { + assertNoError { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "test") { t in + t.check(SQLColumn("a") + SQLColumn("b") < 10) + t.check(sql: "a + b < 10") + t.column("a", .integer) + t.column("b", .integer) + } + XCTAssertEqual(self.lastSQLQuery, + "CREATE TABLE \"test\" (" + + "\"a\" INTEGER, " + + "\"b\" INTEGER, " + + "CHECK (((\"a\" + \"b\") < 10)), " + + "CHECK (a + b < 10)" + + ")") + + // Sanity check + try db.execute("INSERT INTO test (a, b) VALUES (1, 0)") + do { + try db.execute("INSERT INTO test (a, b) VALUES (5, 5)") + XCTFail() + } catch { + } + } + } + } + + func testRenameTable() { + assertNoError { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "test") { t in + t.column("a", .text) + } + XCTAssertTrue(db.tableExists("test")) + + try db.rename(table: "test", to: "foo") + XCTAssertEqual(self.lastSQLQuery, "ALTER TABLE \"test\" RENAME TO \"foo\"") + XCTAssertFalse(db.tableExists("test")) + XCTAssertTrue(db.tableExists("foo")) + } + } + } + + func testAlterTable() { + assertNoError { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "test") { t in + t.column("a", .text) + } + + self.sqlQueries.removeAll() + try db.alter(table: "test") { t in + t.add(column: "b", .text) + t.add(column: "c", .integer).notNull().defaults(1) + } + + XCTAssertEqual(self.sqlQueries[0], "ALTER TABLE \"test\" ADD COLUMN \"b\" TEXT;") + XCTAssertEqual(self.sqlQueries[1], " ALTER TABLE \"test\" ADD COLUMN \"c\" INTEGER NOT NULL DEFAULT 1") + } + } + } + + func testDropTable() { + assertNoError { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "test") { t in + t.column("id", .integer).primaryKey() + t.column("name", .text) + } + XCTAssertTrue(db.tableExists("test")) + + try db.drop(table: "test") + XCTAssertEqual(self.lastSQLQuery, "DROP TABLE \"test\"") + XCTAssertFalse(db.tableExists("test")) + } + } + } + + func testCreateIndex() { + assertNoError { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "test") { t in + t.column("id", .integer).primaryKey() + t.column("a", .text) + t.column("b", .text) + } + + try db.create(index: "test_on_a", on: "test", columns: ["a"]) + XCTAssertEqual(self.lastSQLQuery, "CREATE INDEX \"test_on_a\" ON \"test\"(\"a\")") + + try db.create(index: "test_on_a_b", on: "test", columns: ["a", "b"], unique: true, ifNotExists: true, condition: SQLColumn("a") == 1) + XCTAssertEqual(self.lastSQLQuery, "CREATE UNIQUE INDEX IF NOT EXISTS \"test_on_a_b\" ON \"test\"(\"a\", \"b\") WHERE (\"a\" = 1)") + + // Sanity check + XCTAssertEqual(Set(db.indexes(on: "test").map { $0.name }), ["test_on_a", "test_on_a_b"]) + } + } + } + + func testDropIndex() { + assertNoError { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "test") { t in + t.column("id", .integer).primaryKey() + t.column("name", .text) + } + try db.create(index: "test_on_name", on: "test", columns: ["name"]) + + try db.drop(index: "test_on_name") + XCTAssertEqual(self.lastSQLQuery, "DROP INDEX \"test_on_name\"") + + // Sanity check + XCTAssertTrue(db.indexes(on: "test").isEmpty) + } + } + } +}