From e6f9811162c60c111499c8e920783bb0ea8abca2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 2 Aug 2016 09:00:59 +0200 Subject: [PATCH 01/92] Performance tips --- README.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 453b18c96..fabd56d00 100644 --- a/README.md +++ b/README.md @@ -3570,8 +3570,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) ``` @@ -3623,7 +3622,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) From df7d5c6075f53175fd394099728cbb96beb41c17 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 2 Aug 2016 09:03:34 +0200 Subject: [PATCH 02/92] Performance tips --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index fabd56d00..a248804b2 100644 --- a/README.md +++ b/README.md @@ -3631,7 +3631,7 @@ for row in Row.fetch(db, request) { } ``` -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 From a2b0a579715c6194d02f1191d6e60cc14b327ae2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 3 Aug 2016 13:27:50 +0200 Subject: [PATCH 03/92] Realm 1.0.2 --- Tests/Performance/Realm | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 From 4cf6f7bd7c49aa9cf2835f2553dd0c5ebda0b9d2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 4 Aug 2016 08:51:00 +0200 Subject: [PATCH 04/92] SQLTableBuilder: first passing test --- GRDB.xcodeproj/project.pbxproj | 40 +++++++++++ GRDB/QueryInterface/TableBuilder.swift | 67 +++++++++++++++++++ .../SQLTableBuilderTests.swift | 24 +++++++ 3 files changed, 131 insertions(+) create mode 100644 GRDB/QueryInterface/TableBuilder.swift create mode 100644 Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 48f1322a8..b27acb553 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -305,6 +305,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 /* TableBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableBuilder.swift */; }; + 566AD8B31D5318F4002EC1A8 /* TableBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableBuilder.swift */; }; + 566AD8B41D5318F4002EC1A8 /* TableBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableBuilder.swift */; }; + 566AD8B51D5318F4002EC1A8 /* TableBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableBuilder.swift */; }; + 566AD8B61D5318F4002EC1A8 /* TableBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableBuilder.swift */; }; + 566AD8B71D5318F4002EC1A8 /* TableBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableBuilder.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 */; }; @@ -1383,6 +1397,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 /* TableBuilder.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableBuilder.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 = ""; }; @@ -1813,6 +1829,7 @@ 5605F18A1C6B1A8700235C62 /* SQLFunction.swift */, 5605F18B1C6B1A8700235C62 /* SQLOperator.swift */, 5605F18C1C6B1A8700235C62 /* SQLSelectQuery.swift */, + 566AD8B11D5318F4002EC1A8 /* TableBuilder.swift */, ); path = QueryInterface; sourceTree = ""; @@ -1845,6 +1862,14 @@ path = Collation; sourceTree = ""; }; + 566AD8C41D531BD0002EC1A8 /* SQLTableBuilder */ = { + isa = PBXGroup; + children = ( + 566AD8C51D531BE4002EC1A8 /* SQLTableBuilderTests.swift */, + ); + path = SQLTableBuilder; + sourceTree = ""; + }; 5671566F1CB18039007DC145 /* Encryption */ = { isa = PBXGroup; children = ( @@ -1912,6 +1937,7 @@ 56A238231B9C74A90082EB20 /* Migrations */, 56300B5C1C53C38F005A543B /* QueryInterfaceRequest */, 56A238251B9C74A90082EB20 /* Record */, + 566AD8C41D531BD0002EC1A8 /* SQLTableBuilder */, ); path = Public; sourceTree = ""; @@ -3104,6 +3130,7 @@ 560FC5391CB003810014AA8E /* DatabaseReader.swift in Sources */, 560FC53A1CB003810014AA8E /* NSNull.swift in Sources */, 560FC53B1CB003810014AA8E /* Database.swift in Sources */, + 566AD8B31D5318F4002EC1A8 /* TableBuilder.swift in Sources */, 560FC53C1CB003810014AA8E /* DatabaseQueue.swift in Sources */, 560FC53D1CB003810014AA8E /* NSNumber.swift in Sources */, 560FC53E1CB003810014AA8E /* DatabaseValue+Foundation.swift in Sources */, @@ -3146,6 +3173,7 @@ 560FC5761CB00B880014AA8E /* DetachedRowTests.swift in Sources */, 560FC5771CB00B880014AA8E /* DatabaseQueueSchemaCacheTests.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 */, @@ -3261,6 +3289,7 @@ 5672DE5B1CDB72520022BA81 /* DatabaseQueueBackupTests.swift in Sources */, EED6C2E21D00C0DD00F8E701 /* NSNullTests.swift in Sources */, 56B14E811D4DAE54000BF4A3 /* RowAsDictionaryLiteralConvertibleTests.swift in Sources */, + 566AD8C81D531BEB002EC1A8 /* SQLTableBuilderTests.swift in Sources */, 567156311CB16729007DC145 /* RecordFetchTests.swift in Sources */, EED6C2D01D00B6CB00F8E701 /* NSStringTests.swift in Sources */, 567156321CB16729007DC145 /* DatabasePoolFunctionTests.swift in Sources */, @@ -3371,6 +3400,7 @@ 56AFCA0F1CB1A8BB00F48B96 /* NSNull.swift in Sources */, 56AFCA101CB1A8BB00F48B96 /* DatabaseQueue.swift in Sources */, 56AFCA111CB1A8BB00F48B96 /* DatabaseError.swift in Sources */, + 566AD8B61D5318F4002EC1A8 /* TableBuilder.swift in Sources */, 56AFCA121CB1A8BB00F48B96 /* NSNumber.swift in Sources */, 56AFCA131CB1A8BB00F48B96 /* DatabaseValue+Foundation.swift in Sources */, 56AFCA141CB1A8BB00F48B96 /* StandardLibrary.swift in Sources */, @@ -3421,6 +3451,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 */, 56AFCA4C1CB1AA9900F48B96 /* RowConvertible+QueryInterfaceRequestTests.swift in Sources */, 56AFCA4D1CB1AA9900F48B96 /* DatabasePoolReadOnlyTests.swift in Sources */, @@ -3521,6 +3552,7 @@ 56AFCAA01CB1ABC800F48B96 /* MetalRowTests.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 */, @@ -3624,6 +3656,7 @@ 5605F1661C672E4000235C62 /* NSNull.swift in Sources */, 56A238841B9C75030082EB20 /* DatabaseQueue.swift in Sources */, 56A238821B9C75030082EB20 /* DatabaseError.swift in Sources */, + 566AD8B51D5318F4002EC1A8 /* TableBuilder.swift in Sources */, 5605F1681C672E4000235C62 /* NSNumber.swift in Sources */, 5605F1601C672E4000235C62 /* DatabaseValue+Foundation.swift in Sources */, 5605F1741C672E4000235C62 /* StandardLibrary.swift in Sources */, @@ -3666,6 +3699,7 @@ 56C3F7561CF9F12400F6A361 /* SavepointTests.swift in Sources */, 569531271C9087B700CF1A2B /* DatabaseQueueSchemaCacheTests.swift in Sources */, 56B14E831D4DAE54000BF4A3 /* RowAsDictionaryLiteralConvertibleTests.swift in Sources */, + 566AD8CA1D531BEC002EC1A8 /* SQLTableBuilderTests.swift in Sources */, EED6C2E41D00C0DF00F8E701 /* NSNullTests.swift in Sources */, 56A238541B9C74A90082EB20 /* PrimaryKeyMultipleTests.swift in Sources */, EED6C2D21D00B6CC00F8E701 /* NSStringTests.swift in Sources */, @@ -3749,6 +3783,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 */, EED6C2E01D00C0DB00F8E701 /* NSNullTests.swift in Sources */, 56B7F4371BE4C11200E39BBF /* DatabaseCoderTests.swift in Sources */, @@ -3874,6 +3909,7 @@ 563363C01C942C04000BE133 /* DatabaseReader.swift in Sources */, 5605F1651C672E4000235C62 /* NSNull.swift in Sources */, 56A2387D1B9C75030082EB20 /* Database.swift in Sources */, + 566AD8B21D5318F4002EC1A8 /* TableBuilder.swift in Sources */, 56A238831B9C75030082EB20 /* DatabaseQueue.swift in Sources */, 5605F1671C672E4000235C62 /* NSNumber.swift in Sources */, 5605F15F1C672E4000235C62 /* DatabaseValue+Foundation.swift in Sources */, @@ -3927,6 +3963,7 @@ F3BA80251CFB288C003DC1BA /* Row+Foundation.swift in Sources */, F3BA80211CFB288C003DC1BA /* NSNull.swift in Sources */, F3BA80141CFB2876003DC1BA /* DatabaseValueConvertible.swift in Sources */, + 566AD8B71D5318F4002EC1A8 /* TableBuilder.swift in Sources */, F3BA80121CFB2876003DC1BA /* DatabaseStore.swift in Sources */, F3BA802C1CFB289B003DC1BA /* SQLCollation.swift in Sources */, F3BA80241CFB288C003DC1BA /* NSURL.swift in Sources */, @@ -3969,6 +4006,7 @@ F3BA80F81CFB3021003DC1BA /* StatementArgumentsTests.swift in Sources */, F3BA80E91CFB3016003DC1BA /* AdapterRowTests.swift in Sources */, 56B14E861D4DAE54000BF4A3 /* RowAsDictionaryLiteralConvertibleTests.swift in Sources */, + 566AD8CD1D531BEE002EC1A8 /* SQLTableBuilderTests.swift in Sources */, EED6C2E71D00C0E000F8E701 /* NSNullTests.swift in Sources */, F3BA80D11CFB2FF3003DC1BA /* MutablePersistableTests.swift in Sources */, EED6C2D51D00B6CE00F8E701 /* NSStringTests.swift in Sources */, @@ -4079,6 +4117,7 @@ F3BA80811CFB2E61003DC1BA /* Row+Foundation.swift in Sources */, F3BA807D1CFB2E61003DC1BA /* NSNull.swift in Sources */, F3BA80701CFB2E55003DC1BA /* DatabaseValueConvertible.swift in Sources */, + 566AD8B41D5318F4002EC1A8 /* TableBuilder.swift in Sources */, F3BA806E1CFB2E55003DC1BA /* DatabaseStore.swift in Sources */, F3BA80881CFB2E70003DC1BA /* SQLCollation.swift in Sources */, F3BA80801CFB2E61003DC1BA /* NSURL.swift in Sources */, @@ -4105,6 +4144,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 */, EED6C2E31D00C0DE00F8E701 /* NSNullTests.swift in Sources */, F3BA80AC1CFB2FA6003DC1BA /* DatabaseQueueSchemaCacheTests.swift in Sources */, diff --git a/GRDB/QueryInterface/TableBuilder.swift b/GRDB/QueryInterface/TableBuilder.swift new file mode 100644 index 000000000..b32019936 --- /dev/null +++ b/GRDB/QueryInterface/TableBuilder.swift @@ -0,0 +1,67 @@ +public class SQLTableBuilder { + let name: String + var columns: [SQLColumnBuilder] = [] + + init(name: String) { + self.name = name + } + + public func column(name: String, _ type: SQLColumnType) -> SQLColumnBuilder { + let column = SQLColumnBuilder(name: name, type: type) + columns.append(column) + return column + } + + var sql: String { + var chunks: [String] = [] + chunks.append("CREATE") + chunks.append("TABLE") + chunks.append(name.quotedDatabaseIdentifier) + chunks.append("(" + columns.map { $0.sql }.joinWithSeparator(", ") + ")") + return chunks.joinWithSeparator(" ") + } +} + +public class SQLColumnBuilder { + let name: String + let type: SQLColumnType + var isPrimaryKey: Bool = false + + init(name: String, type: SQLColumnType) { + self.name = name + self.type = type + } + + public func primaryKey() { + isPrimaryKey = true + } + + var sql: String { + var chunks: [String] = [] + chunks.append(name.quotedDatabaseIdentifier) + chunks.append(type.rawValue) + if isPrimaryKey { + chunks.append("PRIMARY KEY") + } + return chunks.joinWithSeparator(" ") + } +} + +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" +} + +extension Database { + public func create(table name: String, body: (SQLTableBuilder) -> Void) throws { + let builder = SQLTableBuilder(name: name) + body(builder) + try execute(builder.sql) + } +} diff --git a/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift b/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift new file mode 100644 index 000000000..5f8dec12e --- /dev/null +++ b/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift @@ -0,0 +1,24 @@ +import XCTest +#if USING_SQLCIPHER + import GRDBCipher +#elseif USING_CUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +class SQLTableBuilderTests: GRDBTestCase { + + func testSQLTableBuilder() { + 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) + } + XCTAssertEqual(self.lastSQLQuery, "CREATE TABLE \"test\" (\"id\" INTEGER PRIMARY KEY, \"name\" TEXT)") + } + } + } +} From 3e28fd69b3cb875705ec41405a50ef4a07ff2402 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 4 Aug 2016 09:10:32 +0200 Subject: [PATCH 05/92] SQLTableBuilder: table & column primary key options --- GRDB/QueryInterface/TableBuilder.swift | 75 ++++++++++++++++--- .../SQLTableBuilderTests.swift | 11 +++ 2 files changed, 77 insertions(+), 9 deletions(-) diff --git a/GRDB/QueryInterface/TableBuilder.swift b/GRDB/QueryInterface/TableBuilder.swift index b32019936..ea32bea07 100644 --- a/GRDB/QueryInterface/TableBuilder.swift +++ b/GRDB/QueryInterface/TableBuilder.swift @@ -1,9 +1,15 @@ public class SQLTableBuilder { let name: String + let temporary: Bool + let ifNotExists: Bool + let withoutRowID: Bool var columns: [SQLColumnBuilder] = [] - init(name: String) { + init(name: String, temporary: Bool, ifNotExists: Bool, withoutRowID: Bool) { self.name = name + self.temporary = temporary + self.ifNotExists = ifNotExists + self.withoutRowID = withoutRowID } public func column(name: String, _ type: SQLColumnType) -> SQLColumnBuilder { @@ -15,9 +21,18 @@ public class SQLTableBuilder { var sql: 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) chunks.append("(" + columns.map { $0.sql }.joinWithSeparator(", ") + ")") + if withoutRowID { + chunks.append("WITHOUT ROWID") + } return chunks.joinWithSeparator(" ") } } @@ -25,29 +40,64 @@ public class SQLTableBuilder { public class SQLColumnBuilder { let name: String let type: SQLColumnType - var isPrimaryKey: Bool = false + var primaryKeyBuilder: SQLPrimaryKeyBuilder? init(name: String, type: SQLColumnType) { self.name = name self.type = type } - public func primaryKey() { - isPrimaryKey = true + public func primaryKey(ordering ordering: SQLPrimaryKeyOrdering? = nil, onConflict conflictResolution: SQLConflictResolution? = nil, autoincrement: Bool = false) { + primaryKeyBuilder = SQLPrimaryKeyBuilder(ordering: ordering, conflictResolution: conflictResolution, autoincrement: autoincrement) } var sql: String { var chunks: [String] = [] chunks.append(name.quotedDatabaseIdentifier) chunks.append(type.rawValue) - if isPrimaryKey { - chunks.append("PRIMARY KEY") + if let primaryKeyBuilder = primaryKeyBuilder { + chunks.append(primaryKeyBuilder.sql) } return chunks.joinWithSeparator(" ") } } -public enum SQLColumnType: String { +struct SQLPrimaryKeyBuilder { + let ordering: SQLPrimaryKeyOrdering? + let conflictResolution: SQLConflictResolution? + let autoincrement: Bool + + var sql: String { + var chunks: [String] = [] + chunks.append("PRIMARY KEY") + if let ordering = ordering { + chunks.append(ordering.rawValue) + } + if let conflictResolution = conflictResolution { + chunks.append("ON CONFLICT") + chunks.append(conflictResolution.rawValue) + } + if autoincrement { + chunks.append("AUTOINCREMENT") + } + return chunks.joinWithSeparator(" ") + } +} + +public enum SQLPrimaryKeyOrdering : String { + case Asc = "ASC" + case Desc = "DESC" +} + +public enum SQLConflictResolution : String { + case Rollback = "ROLLBACK" + case Abort = "ABORT" + case Fail = "FAIL" + case Ignore = "IGNORE" + case Replace = "REPLACE" +} + +public enum SQLColumnType : String { case Text = "TEXT" case Integer = "INTEGER" case Double = "DOUBLE" @@ -59,9 +109,16 @@ public enum SQLColumnType: String { } extension Database { - public func create(table name: String, body: (SQLTableBuilder) -> Void) throws { - let builder = SQLTableBuilder(name: name) + // TODO: doc + // TODO: Don't expose withoutRowID if not available + public func create(table name: String, temporary: Bool = false, ifNotExists: Bool = false, withoutRowID: Bool = false, body: (SQLTableBuilder) -> Void) throws { + let builder = SQLTableBuilder(name: name, temporary: temporary, ifNotExists: ifNotExists, withoutRowID: withoutRowID) body(builder) try execute(builder.sql) } + + // TODO: doc + public func drop(table name: String) throws { + try execute("DROP TABLE \(name.quotedDatabaseIdentifier)") + } } diff --git a/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift b/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift index 5f8dec12e..3f67b5fe3 100644 --- a/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift +++ b/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift @@ -13,11 +13,22 @@ class SQLTableBuilderTests: GRDBTestCase { 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)") + + // Drop table + try db.drop(table: "test") + XCTAssertEqual(self.lastSQLQuery, "DROP TABLE \"test\"") + + // Table options and column primary key options + try db.create(table: "test", temporary: true, ifNotExists: true, withoutRowID: true) { t in + t.column("id", .Integer).primaryKey(ordering: .Desc, onConflict: .Fail) + } + XCTAssertEqual(self.lastSQLQuery, "CREATE TEMPORARY TABLE IF NOT EXISTS \"test\" (\"id\" INTEGER PRIMARY KEY DESC ON CONFLICT FAIL) WITHOUT ROWID") } } } From 8332dc188a87617035520700e0d233f25de08723 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 4 Aug 2016 13:34:14 +0200 Subject: [PATCH 06/92] SQLTableBuilder tests --- .../SQLTableBuilderTests.swift | 70 ++++++++++++++++--- 1 file changed, 61 insertions(+), 9 deletions(-) diff --git a/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift b/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift index 3f67b5fe3..0631ca213 100644 --- a/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift +++ b/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift @@ -9,7 +9,7 @@ import XCTest class SQLTableBuilderTests: GRDBTestCase { - func testSQLTableBuilder() { + func testCreateTable() { assertNoError { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -18,17 +18,69 @@ class SQLTableBuilderTests: GRDBTestCase { t.column("id", .Integer).primaryKey() t.column("name", .Text) } - XCTAssertEqual(self.lastSQLQuery, "CREATE TABLE \"test\" (\"id\" INTEGER PRIMARY KEY, \"name\" TEXT)") - - // Drop table - try db.drop(table: "test") - XCTAssertEqual(self.lastSQLQuery, "DROP TABLE \"test\"") - - // Table options and column primary key options + 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(ordering: .Desc, onConflict: .Fail) } - XCTAssertEqual(self.lastSQLQuery, "CREATE TEMPORARY TABLE IF NOT EXISTS \"test\" (\"id\" INTEGER PRIMARY KEY DESC ON CONFLICT FAIL) WITHOUT ROWID") + XCTAssertEqual(self.lastSQLQuery, + "CREATE TABLE \"test\" (" + + "\"id\" INTEGER PRIMARY KEY DESC 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 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")) } } } From 62070c50ff829397d59ab5f6911c4c0d441fcd9a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 4 Aug 2016 13:38:39 +0200 Subject: [PATCH 07/92] SQLTableBuilder WIP --- GRDB/QueryInterface/TableBuilder.swift | 44 ++++++++++---------------- 1 file changed, 16 insertions(+), 28 deletions(-) diff --git a/GRDB/QueryInterface/TableBuilder.swift b/GRDB/QueryInterface/TableBuilder.swift index ea32bea07..4aee922d1 100644 --- a/GRDB/QueryInterface/TableBuilder.swift +++ b/GRDB/QueryInterface/TableBuilder.swift @@ -40,51 +40,39 @@ public class SQLTableBuilder { public class SQLColumnBuilder { let name: String let type: SQLColumnType - var primaryKeyBuilder: SQLPrimaryKeyBuilder? + var primaryKey: (ordering: SQLOrdering?, conflictResolution: SQLConflictResolution?, autoincrement: Bool)? init(name: String, type: SQLColumnType) { self.name = name self.type = type } - public func primaryKey(ordering ordering: SQLPrimaryKeyOrdering? = nil, onConflict conflictResolution: SQLConflictResolution? = nil, autoincrement: Bool = false) { - primaryKeyBuilder = SQLPrimaryKeyBuilder(ordering: ordering, conflictResolution: conflictResolution, autoincrement: autoincrement) + public func primaryKey(ordering ordering: SQLOrdering? = nil, onConflict conflictResolution: SQLConflictResolution? = nil, autoincrement: Bool = false) { + primaryKey = (ordering: ordering, conflictResolution: conflictResolution, autoincrement: autoincrement) } var sql: String { var chunks: [String] = [] chunks.append(name.quotedDatabaseIdentifier) chunks.append(type.rawValue) - if let primaryKeyBuilder = primaryKeyBuilder { - chunks.append(primaryKeyBuilder.sql) + if let (ordering, conflictResolution, autoincrement) = primaryKey { + chunks.append("PRIMARY KEY") + if let ordering = ordering { + chunks.append(ordering.rawValue) + } + if let conflictResolution = conflictResolution { + chunks.append("ON CONFLICT") + chunks.append(conflictResolution.rawValue) + } + if autoincrement { + chunks.append("AUTOINCREMENT") + } } return chunks.joinWithSeparator(" ") } } -struct SQLPrimaryKeyBuilder { - let ordering: SQLPrimaryKeyOrdering? - let conflictResolution: SQLConflictResolution? - let autoincrement: Bool - - var sql: String { - var chunks: [String] = [] - chunks.append("PRIMARY KEY") - if let ordering = ordering { - chunks.append(ordering.rawValue) - } - if let conflictResolution = conflictResolution { - chunks.append("ON CONFLICT") - chunks.append(conflictResolution.rawValue) - } - if autoincrement { - chunks.append("AUTOINCREMENT") - } - return chunks.joinWithSeparator(" ") - } -} - -public enum SQLPrimaryKeyOrdering : String { +public enum SQLOrdering : String { case Asc = "ASC" case Desc = "DESC" } From b1109780edede32120970c82115cb15bc6844336 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 4 Aug 2016 13:48:08 +0200 Subject: [PATCH 08/92] SQLTableBuilder: column.notNull() and unique() --- GRDB/QueryInterface/TableBuilder.swift | 32 ++++++++++++ .../SQLTableBuilderTests.swift | 50 +++++++++++++++++++ 2 files changed, 82 insertions(+) diff --git a/GRDB/QueryInterface/TableBuilder.swift b/GRDB/QueryInterface/TableBuilder.swift index 4aee922d1..f00577cec 100644 --- a/GRDB/QueryInterface/TableBuilder.swift +++ b/GRDB/QueryInterface/TableBuilder.swift @@ -41,6 +41,8 @@ public class SQLColumnBuilder { let name: String let type: SQLColumnType var primaryKey: (ordering: SQLOrdering?, conflictResolution: SQLConflictResolution?, autoincrement: Bool)? + var notNullConflictResolution: SQLConflictResolution? + var uniqueConflictResolution: SQLConflictResolution? init(name: String, type: SQLColumnType) { self.name = name @@ -51,10 +53,19 @@ public class SQLColumnBuilder { primaryKey = (ordering: ordering, conflictResolution: conflictResolution, autoincrement: autoincrement) } + public func notNull(onConflict conflictResolution: SQLConflictResolution? = nil) { + notNullConflictResolution = conflictResolution ?? .Abort + } + + public func unique(onConflict conflictResolution: SQLConflictResolution? = nil) { + uniqueConflictResolution = conflictResolution ?? .Abort + } + var sql: String { var chunks: [String] = [] chunks.append(name.quotedDatabaseIdentifier) chunks.append(type.rawValue) + if let (ordering, conflictResolution, autoincrement) = primaryKey { chunks.append("PRIMARY KEY") if let ordering = ordering { @@ -68,6 +79,27 @@ public class SQLColumnBuilder { 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) + } + return chunks.joinWithSeparator(" ") } } diff --git a/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift b/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift index 0631ca213..14b6d0053 100644 --- a/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift +++ b/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift @@ -68,6 +68,56 @@ class SQLTableBuilderTests: GRDBTestCase { } } + 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 testDropTable() { assertNoError { let dbQueue = try makeDatabaseQueue() From 5edb5276f8baf9bce0dc1cc92cfb9abddb0f287a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 4 Aug 2016 13:57:32 +0200 Subject: [PATCH 09/92] SQLTableBuilder: column.check() --- GRDB/QueryInterface/TableBuilder.swift | 10 ++++++++ .../SQLTableBuilderTests.swift | 23 +++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/GRDB/QueryInterface/TableBuilder.swift b/GRDB/QueryInterface/TableBuilder.swift index f00577cec..5c7728a47 100644 --- a/GRDB/QueryInterface/TableBuilder.swift +++ b/GRDB/QueryInterface/TableBuilder.swift @@ -43,6 +43,7 @@ public class SQLColumnBuilder { var primaryKey: (ordering: SQLOrdering?, conflictResolution: SQLConflictResolution?, autoincrement: Bool)? var notNullConflictResolution: SQLConflictResolution? var uniqueConflictResolution: SQLConflictResolution? + var checkExpression: _SQLExpression? init(name: String, type: SQLColumnType) { self.name = name @@ -61,6 +62,10 @@ public class SQLColumnBuilder { uniqueConflictResolution = conflictResolution ?? .Abort } + public func check(@noescape condition: (SQLColumn) -> _SQLExpressible) { + checkExpression = condition(SQLColumn(name)).sqlExpression + } + var sql: String { var chunks: [String] = [] chunks.append(name.quotedDatabaseIdentifier) @@ -100,6 +105,11 @@ public class SQLColumnBuilder { chunks.append(conflictResolution.rawValue) } + if let checkExpression = checkExpression { + var arguments: StatementArguments? = nil // nil so that checkExpression.sql(&arguments) embeds literals + chunks.append("CHECK(" + checkExpression.sql(&arguments) + ")") + } + return chunks.joinWithSeparator(" ") } } diff --git a/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift b/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift index 14b6d0053..e44b755bc 100644 --- a/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift +++ b/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift @@ -118,6 +118,29 @@ class SQLTableBuilderTests: GRDBTestCase { } } + 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 } + } + XCTAssertEqual(self.lastSQLQuery, + "CREATE TABLE \"test\" (" + + "\"a\" INTEGER CHECK((\"a\" > 0))" + + ")") + + // Sanity check + try db.execute("INSERT INTO test (a) VALUES (1)") + do { + try db.execute("INSERT INTO test (a) VALUES (0)") + XCTFail() + } catch { + } + } + } + } + func testDropTable() { assertNoError { let dbQueue = try makeDatabaseQueue() From 5b6efbbb5f32e643f1aca6bf04ba34990c757582 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 4 Aug 2016 22:57:14 +0200 Subject: [PATCH 10/92] SQLTableBuilder: column.defaults() --- GRDB/QueryInterface/TableBuilder.swift | 14 ++++++++++++- .../SQLTableBuilderTests.swift | 21 ++++++++++++++++++- 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/GRDB/QueryInterface/TableBuilder.swift b/GRDB/QueryInterface/TableBuilder.swift index 5c7728a47..57d40a218 100644 --- a/GRDB/QueryInterface/TableBuilder.swift +++ b/GRDB/QueryInterface/TableBuilder.swift @@ -44,6 +44,7 @@ public class SQLColumnBuilder { var notNullConflictResolution: SQLConflictResolution? var uniqueConflictResolution: SQLConflictResolution? var checkExpression: _SQLExpression? + var defaultExpression: _SQLExpression? init(name: String, type: SQLColumnType) { self.name = name @@ -66,6 +67,10 @@ public class SQLColumnBuilder { checkExpression = condition(SQLColumn(name)).sqlExpression } + public func defaults(value: _SQLExpressible) { + defaultExpression = value.sqlExpression + } + var sql: String { var chunks: [String] = [] chunks.append(name.quotedDatabaseIdentifier) @@ -107,7 +112,14 @@ public class SQLColumnBuilder { if let checkExpression = checkExpression { var arguments: StatementArguments? = nil // nil so that checkExpression.sql(&arguments) embeds literals - chunks.append("CHECK(" + checkExpression.sql(&arguments) + ")") + chunks.append("CHECK") + chunks.append("(" + checkExpression.sql(&arguments) + ")") + } + + if let defaultExpression = defaultExpression { + var arguments: StatementArguments? = nil // nil so that checkExpression.sql(&arguments) embeds literals + chunks.append("DEFAULT") + chunks.append("(" + defaultExpression.sql(&arguments) + ")") } return chunks.joinWithSeparator(" ") diff --git a/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift b/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift index e44b755bc..680f704ff 100644 --- a/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift +++ b/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift @@ -127,7 +127,7 @@ class SQLTableBuilderTests: GRDBTestCase { } XCTAssertEqual(self.lastSQLQuery, "CREATE TABLE \"test\" (" + - "\"a\" INTEGER CHECK((\"a\" > 0))" + + "\"a\" INTEGER CHECK ((\"a\" > 0))" + ")") // Sanity check @@ -141,6 +141,25 @@ class SQLTableBuilderTests: GRDBTestCase { } } + 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) + } + XCTAssertEqual(self.lastSQLQuery, + "CREATE TABLE \"test\" (" + + "\"a\" INTEGER DEFAULT (1)" + + ")") + + // Sanity check + try db.execute("INSERT INTO test DEFAULT VALUES") + XCTAssertEqual(Int.fetchOne(db, "SELECT a FROM test")!, 1) + } + } + } + func testDropTable() { assertNoError { let dbQueue = try makeDatabaseQueue() From 10c32381d496d795af3233a8b4b5aeb5490f4e97 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 4 Aug 2016 23:05:56 +0200 Subject: [PATCH 11/92] SQLTableBuilder: column.collate() --- GRDB/QueryInterface/TableBuilder.swift | 20 +++++++++++++ .../SQLTableBuilderTests.swift | 29 +++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/GRDB/QueryInterface/TableBuilder.swift b/GRDB/QueryInterface/TableBuilder.swift index 57d40a218..414f55b96 100644 --- a/GRDB/QueryInterface/TableBuilder.swift +++ b/GRDB/QueryInterface/TableBuilder.swift @@ -45,6 +45,7 @@ public class SQLColumnBuilder { var uniqueConflictResolution: SQLConflictResolution? var checkExpression: _SQLExpression? var defaultExpression: _SQLExpression? + var collationName: String? init(name: String, type: SQLColumnType) { self.name = name @@ -71,6 +72,14 @@ public class SQLColumnBuilder { defaultExpression = value.sqlExpression } + public func collate(collation: SQLCollation) { + collationName = collation.rawValue + } + + public func collate(collation: DatabaseCollation) { + collationName = collation.name + } + var sql: String { var chunks: [String] = [] chunks.append(name.quotedDatabaseIdentifier) @@ -122,6 +131,11 @@ public class SQLColumnBuilder { chunks.append("(" + defaultExpression.sql(&arguments) + ")") } + if let collationName = collationName { + chunks.append("COLLATE") + chunks.append(collationName) + } + return chunks.joinWithSeparator(" ") } } @@ -131,6 +145,12 @@ public enum SQLOrdering : String { case Desc = "DESC" } +public enum SQLCollation : String { + case Binary = "BINARY" + case Nocase = "NOCASE" + case Rtrim = "RTRIM" +} + public enum SQLConflictResolution : String { case Rollback = "ROLLBACK" case Abort = "ABORT" diff --git a/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift b/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift index 680f704ff..a0404165b 100644 --- a/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift +++ b/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift @@ -160,6 +160,35 @@ class SQLTableBuilderTests: GRDBTestCase { } } + 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.addCollation(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 testDropTable() { assertNoError { let dbQueue = try makeDatabaseQueue() From 8246f1c99049a5c2f311f00a43ac3601a8f05a09 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 5 Aug 2016 08:17:09 +0200 Subject: [PATCH 12/92] SQLTableBuilder: column.references() --- GRDB.xcodeproj/project.pbxproj | 28 ++++++------- ...bleBuilder.swift => SQLTableBuilder.swift} | 42 ++++++++++++++++--- .../SQLTableBuilderTests.swift | 21 ++++++++++ 3 files changed, 72 insertions(+), 19 deletions(-) rename GRDB/QueryInterface/{TableBuilder.swift => SQLTableBuilder.swift} (76%) diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index b27acb553..d85fd0dcc 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -305,12 +305,12 @@ 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 /* TableBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableBuilder.swift */; }; - 566AD8B31D5318F4002EC1A8 /* TableBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableBuilder.swift */; }; - 566AD8B41D5318F4002EC1A8 /* TableBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableBuilder.swift */; }; - 566AD8B51D5318F4002EC1A8 /* TableBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableBuilder.swift */; }; - 566AD8B61D5318F4002EC1A8 /* TableBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableBuilder.swift */; }; - 566AD8B71D5318F4002EC1A8 /* TableBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableBuilder.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 */; }; @@ -1397,7 +1397,7 @@ 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 /* TableBuilder.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableBuilder.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; }; @@ -1829,7 +1829,7 @@ 5605F18A1C6B1A8700235C62 /* SQLFunction.swift */, 5605F18B1C6B1A8700235C62 /* SQLOperator.swift */, 5605F18C1C6B1A8700235C62 /* SQLSelectQuery.swift */, - 566AD8B11D5318F4002EC1A8 /* TableBuilder.swift */, + 566AD8B11D5318F4002EC1A8 /* SQLTableBuilder.swift */, ); path = QueryInterface; sourceTree = ""; @@ -3130,7 +3130,7 @@ 560FC5391CB003810014AA8E /* DatabaseReader.swift in Sources */, 560FC53A1CB003810014AA8E /* NSNull.swift in Sources */, 560FC53B1CB003810014AA8E /* Database.swift in Sources */, - 566AD8B31D5318F4002EC1A8 /* TableBuilder.swift in Sources */, + 566AD8B31D5318F4002EC1A8 /* SQLTableBuilder.swift in Sources */, 560FC53C1CB003810014AA8E /* DatabaseQueue.swift in Sources */, 560FC53D1CB003810014AA8E /* NSNumber.swift in Sources */, 560FC53E1CB003810014AA8E /* DatabaseValue+Foundation.swift in Sources */, @@ -3400,7 +3400,7 @@ 56AFCA0F1CB1A8BB00F48B96 /* NSNull.swift in Sources */, 56AFCA101CB1A8BB00F48B96 /* DatabaseQueue.swift in Sources */, 56AFCA111CB1A8BB00F48B96 /* DatabaseError.swift in Sources */, - 566AD8B61D5318F4002EC1A8 /* TableBuilder.swift in Sources */, + 566AD8B61D5318F4002EC1A8 /* SQLTableBuilder.swift in Sources */, 56AFCA121CB1A8BB00F48B96 /* NSNumber.swift in Sources */, 56AFCA131CB1A8BB00F48B96 /* DatabaseValue+Foundation.swift in Sources */, 56AFCA141CB1A8BB00F48B96 /* StandardLibrary.swift in Sources */, @@ -3656,7 +3656,7 @@ 5605F1661C672E4000235C62 /* NSNull.swift in Sources */, 56A238841B9C75030082EB20 /* DatabaseQueue.swift in Sources */, 56A238821B9C75030082EB20 /* DatabaseError.swift in Sources */, - 566AD8B51D5318F4002EC1A8 /* TableBuilder.swift in Sources */, + 566AD8B51D5318F4002EC1A8 /* SQLTableBuilder.swift in Sources */, 5605F1681C672E4000235C62 /* NSNumber.swift in Sources */, 5605F1601C672E4000235C62 /* DatabaseValue+Foundation.swift in Sources */, 5605F1741C672E4000235C62 /* StandardLibrary.swift in Sources */, @@ -3909,7 +3909,7 @@ 563363C01C942C04000BE133 /* DatabaseReader.swift in Sources */, 5605F1651C672E4000235C62 /* NSNull.swift in Sources */, 56A2387D1B9C75030082EB20 /* Database.swift in Sources */, - 566AD8B21D5318F4002EC1A8 /* TableBuilder.swift in Sources */, + 566AD8B21D5318F4002EC1A8 /* SQLTableBuilder.swift in Sources */, 56A238831B9C75030082EB20 /* DatabaseQueue.swift in Sources */, 5605F1671C672E4000235C62 /* NSNumber.swift in Sources */, 5605F15F1C672E4000235C62 /* DatabaseValue+Foundation.swift in Sources */, @@ -3963,7 +3963,7 @@ F3BA80251CFB288C003DC1BA /* Row+Foundation.swift in Sources */, F3BA80211CFB288C003DC1BA /* NSNull.swift in Sources */, F3BA80141CFB2876003DC1BA /* DatabaseValueConvertible.swift in Sources */, - 566AD8B71D5318F4002EC1A8 /* TableBuilder.swift in Sources */, + 566AD8B71D5318F4002EC1A8 /* SQLTableBuilder.swift in Sources */, F3BA80121CFB2876003DC1BA /* DatabaseStore.swift in Sources */, F3BA802C1CFB289B003DC1BA /* SQLCollation.swift in Sources */, F3BA80241CFB288C003DC1BA /* NSURL.swift in Sources */, @@ -4117,7 +4117,7 @@ F3BA80811CFB2E61003DC1BA /* Row+Foundation.swift in Sources */, F3BA807D1CFB2E61003DC1BA /* NSNull.swift in Sources */, F3BA80701CFB2E55003DC1BA /* DatabaseValueConvertible.swift in Sources */, - 566AD8B41D5318F4002EC1A8 /* TableBuilder.swift in Sources */, + 566AD8B41D5318F4002EC1A8 /* SQLTableBuilder.swift in Sources */, F3BA806E1CFB2E55003DC1BA /* DatabaseStore.swift in Sources */, F3BA80881CFB2E70003DC1BA /* SQLCollation.swift in Sources */, F3BA80801CFB2E61003DC1BA /* NSURL.swift in Sources */, diff --git a/GRDB/QueryInterface/TableBuilder.swift b/GRDB/QueryInterface/SQLTableBuilder.swift similarity index 76% rename from GRDB/QueryInterface/TableBuilder.swift rename to GRDB/QueryInterface/SQLTableBuilder.swift index 414f55b96..d15d09db0 100644 --- a/GRDB/QueryInterface/TableBuilder.swift +++ b/GRDB/QueryInterface/SQLTableBuilder.swift @@ -18,7 +18,7 @@ public class SQLTableBuilder { return column } - var sql: String { + func sql(db: Database) throws -> String { var chunks: [String] = [] chunks.append("CREATE") if temporary { @@ -29,7 +29,7 @@ public class SQLTableBuilder { chunks.append("IF NOT EXISTS") } chunks.append(name.quotedDatabaseIdentifier) - chunks.append("(" + columns.map { $0.sql }.joinWithSeparator(", ") + ")") + try chunks.append("(" + (columns.map { try $0.sql(db) } as [String]).joinWithSeparator(", ") + ")") if withoutRowID { chunks.append("WITHOUT ROWID") } @@ -46,6 +46,7 @@ public class SQLColumnBuilder { var checkExpression: _SQLExpression? var defaultExpression: _SQLExpression? var collationName: String? + var reference: (table: String, column: String?, deleteAction: SQLForeignKeyAction?, updateAction: SQLForeignKeyAction?)? init(name: String, type: SQLColumnType) { self.name = name @@ -80,7 +81,11 @@ public class SQLColumnBuilder { collationName = collation.name } - var sql: String { + public func references(table: String, column: String? = nil, onDelete deleteAction: SQLForeignKeyAction? = nil, onUpdate updateAction: SQLForeignKeyAction? = nil) { + reference = (table: table, column: column, deleteAction: deleteAction, updateAction: updateAction) + } + + func sql(db: Database) throws -> String { var chunks: [String] = [] chunks.append(name.quotedDatabaseIdentifier) chunks.append(type.rawValue) @@ -126,7 +131,7 @@ public class SQLColumnBuilder { } if let defaultExpression = defaultExpression { - var arguments: StatementArguments? = nil // nil so that checkExpression.sql(&arguments) embeds literals + var arguments: StatementArguments? = nil // nil so that defaultExpression.sql(&arguments) embeds literals chunks.append("DEFAULT") chunks.append("(" + defaultExpression.sql(&arguments) + ")") } @@ -136,6 +141,25 @@ public class SQLColumnBuilder { chunks.append(collationName) } + if let (table, column, deleteAction, updateAction) = 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]).joinWithSeparator(", ")))") + } else { + chunks.append("\(table.quotedDatabaseIdentifier)(_rowid_)") + } + if let deleteAction = deleteAction { + chunks.append("ON DELETE") + chunks.append(deleteAction.rawValue) + } + if let updateAction = updateAction { + chunks.append("ON UPDATE") + chunks.append(updateAction.rawValue) + } + } + return chunks.joinWithSeparator(" ") } } @@ -170,13 +194,21 @@ public enum SQLColumnType : String { case Datetime = "DATETIME" } +public enum SQLForeignKeyAction : String { + case Cascade = "CASCADE" + case Restrict = "RESTRICT" + case SetNull = "SET NULL" + case SetDefault = "SET DEFAULT" +} + extension Database { // TODO: doc // TODO: Don't expose withoutRowID if not available public func create(table name: String, temporary: Bool = false, ifNotExists: Bool = false, withoutRowID: Bool = false, body: (SQLTableBuilder) -> Void) throws { let builder = SQLTableBuilder(name: name, temporary: temporary, ifNotExists: ifNotExists, withoutRowID: withoutRowID) body(builder) - try execute(builder.sql) + let sql = try builder.sql(self) + try execute(sql) } // TODO: doc diff --git a/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift b/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift index a0404165b..2b932ce8d 100644 --- a/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift +++ b/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift @@ -189,6 +189,27 @@ class SQLTableBuilderTests: GRDBTestCase { } } + 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) + } + 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" + + ")") + } + } + } + func testDropTable() { assertNoError { let dbQueue = try makeDatabaseQueue() From 39e3cba80e8a4422a17fb5773b7f5602bb8ff5f1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 5 Aug 2016 08:24:00 +0200 Subject: [PATCH 13/92] SQLTableBuilder: column.references(deferred: true) --- GRDB/QueryInterface/SQLTableBuilder.swift | 11 +++++++---- .../Public/SQLTableBuilder/SQLTableBuilderTests.swift | 4 ++-- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/GRDB/QueryInterface/SQLTableBuilder.swift b/GRDB/QueryInterface/SQLTableBuilder.swift index d15d09db0..2306acf5e 100644 --- a/GRDB/QueryInterface/SQLTableBuilder.swift +++ b/GRDB/QueryInterface/SQLTableBuilder.swift @@ -46,7 +46,7 @@ public class SQLColumnBuilder { var checkExpression: _SQLExpression? var defaultExpression: _SQLExpression? var collationName: String? - var reference: (table: String, column: String?, deleteAction: SQLForeignKeyAction?, updateAction: SQLForeignKeyAction?)? + var reference: (table: String, column: String?, deleteAction: SQLForeignKeyAction?, updateAction: SQLForeignKeyAction?, deferred: Bool)? init(name: String, type: SQLColumnType) { self.name = name @@ -81,8 +81,8 @@ public class SQLColumnBuilder { collationName = collation.name } - public func references(table: String, column: String? = nil, onDelete deleteAction: SQLForeignKeyAction? = nil, onUpdate updateAction: SQLForeignKeyAction? = nil) { - reference = (table: table, column: column, deleteAction: deleteAction, updateAction: updateAction) + public func references(table: String, column: String? = nil, onDelete deleteAction: SQLForeignKeyAction? = nil, onUpdate updateAction: SQLForeignKeyAction? = nil, deferred: Bool = false) { + reference = (table: table, column: column, deleteAction: deleteAction, updateAction: updateAction, deferred: deferred) } func sql(db: Database) throws -> String { @@ -141,7 +141,7 @@ public class SQLColumnBuilder { chunks.append(collationName) } - if let (table, column, deleteAction, updateAction) = reference { + if let (table, column, deleteAction, updateAction, deferred) = reference { chunks.append("REFERENCES") if let column = column { chunks.append("\(table.quotedDatabaseIdentifier)(\(column.quotedDatabaseIdentifier))") @@ -158,6 +158,9 @@ public class SQLColumnBuilder { chunks.append("ON UPDATE") chunks.append(updateAction.rawValue) } + if deferred { + chunks.append("DEFERRABLE INITIALLY DEFERRED") + } } return chunks.joinWithSeparator(" ") diff --git a/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift b/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift index 2b932ce8d..410fefbe6 100644 --- a/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift +++ b/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift @@ -199,12 +199,12 @@ class SQLTableBuilderTests: GRDBTestCase { } 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) + 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" + + "\"parentEmail\" TEXT REFERENCES \"parent\"(\"email\") ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED" + ")") } } From 09e409cb79efcbeeecf78f769fc376682be380f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 5 Aug 2016 08:25:46 +0200 Subject: [PATCH 14/92] SQLTableBuilder: documentation --- GRDB/QueryInterface/SQLTableBuilder.swift | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/GRDB/QueryInterface/SQLTableBuilder.swift b/GRDB/QueryInterface/SQLTableBuilder.swift index 2306acf5e..3d7c43a4a 100644 --- a/GRDB/QueryInterface/SQLTableBuilder.swift +++ b/GRDB/QueryInterface/SQLTableBuilder.swift @@ -12,6 +12,7 @@ public class SQLTableBuilder { self.withoutRowID = withoutRowID } + // TODO: doc public func column(name: String, _ type: SQLColumnType) -> SQLColumnBuilder { let column = SQLColumnBuilder(name: name, type: type) columns.append(column) @@ -53,34 +54,42 @@ public class SQLColumnBuilder { self.type = type } + // TODO: doc public func primaryKey(ordering ordering: SQLOrdering? = nil, onConflict conflictResolution: SQLConflictResolution? = nil, autoincrement: Bool = false) { primaryKey = (ordering: ordering, conflictResolution: conflictResolution, autoincrement: autoincrement) } + // TODO: doc public func notNull(onConflict conflictResolution: SQLConflictResolution? = nil) { notNullConflictResolution = conflictResolution ?? .Abort } + // TODO: doc public func unique(onConflict conflictResolution: SQLConflictResolution? = nil) { uniqueConflictResolution = conflictResolution ?? .Abort } + // TODO: doc public func check(@noescape condition: (SQLColumn) -> _SQLExpressible) { checkExpression = condition(SQLColumn(name)).sqlExpression } + // TODO: doc public func defaults(value: _SQLExpressible) { defaultExpression = value.sqlExpression } + // TODO: doc public func collate(collation: SQLCollation) { collationName = collation.rawValue } + // TODO: doc public func collate(collation: DatabaseCollation) { collationName = collation.name } + // TODO: doc public func references(table: String, column: String? = nil, onDelete deleteAction: SQLForeignKeyAction? = nil, onUpdate updateAction: SQLForeignKeyAction? = nil, deferred: Bool = false) { reference = (table: table, column: column, deleteAction: deleteAction, updateAction: updateAction, deferred: deferred) } @@ -167,17 +176,20 @@ public class SQLColumnBuilder { } } +// TODO: doc public enum SQLOrdering : String { case Asc = "ASC" case Desc = "DESC" } +// TODO: doc public enum SQLCollation : String { case Binary = "BINARY" case Nocase = "NOCASE" case Rtrim = "RTRIM" } +// TODO: doc public enum SQLConflictResolution : String { case Rollback = "ROLLBACK" case Abort = "ABORT" @@ -186,6 +198,7 @@ public enum SQLConflictResolution : String { case Replace = "REPLACE" } +// TODO: doc public enum SQLColumnType : String { case Text = "TEXT" case Integer = "INTEGER" @@ -197,6 +210,7 @@ public enum SQLColumnType : String { case Datetime = "DATETIME" } +// TODO: doc public enum SQLForeignKeyAction : String { case Cascade = "CASCADE" case Restrict = "RESTRICT" From f83f5455c22f9c360bba7ec834ed1dcc1106f980 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 5 Aug 2016 08:48:46 +0200 Subject: [PATCH 15/92] SQLTableBuilder: table.primaryKey(), table.uniqueKey() --- GRDB/QueryInterface/SQLTableBuilder.swift | 46 ++++++++++++++- .../SQLTableBuilderTests.swift | 57 +++++++++++++++++++ 2 files changed, 102 insertions(+), 1 deletion(-) diff --git a/GRDB/QueryInterface/SQLTableBuilder.swift b/GRDB/QueryInterface/SQLTableBuilder.swift index 3d7c43a4a..72e67ec16 100644 --- a/GRDB/QueryInterface/SQLTableBuilder.swift +++ b/GRDB/QueryInterface/SQLTableBuilder.swift @@ -4,6 +4,8 @@ public class SQLTableBuilder { let ifNotExists: Bool let withoutRowID: Bool var columns: [SQLColumnBuilder] = [] + var primaryKeyConstraint: (columns: [String], conflictResolution: SQLConflictResolution?)? + var uniqueKeyConstraints: [(columns: [String], conflictResolution: SQLConflictResolution?)] = [] init(name: String, temporary: Bool, ifNotExists: Bool, withoutRowID: Bool) { self.name = name @@ -19,6 +21,19 @@ public class SQLTableBuilder { return column } + // TODO: doc + 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) + } + + // TODO: doc + public func uniqueKey(columns: [String], onConflict conflictResolution: SQLConflictResolution? = nil) { + uniqueKeyConstraints.append((columns: columns, conflictResolution: conflictResolution)) + } + func sql(db: Database) throws -> String { var chunks: [String] = [] chunks.append("CREATE") @@ -30,7 +45,36 @@ public class SQLTableBuilder { chunks.append("IF NOT EXISTS") } chunks.append(name.quotedDatabaseIdentifier) - try chunks.append("(" + (columns.map { try $0.sql(db) } as [String]).joinWithSeparator(", ") + ")") + + do { + var items: [String] = [] + try items.appendContentsOf(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]).joinWithSeparator(", ")))") + if let conflictResolution = conflictResolution { + chunks.append("ON CONFLICT") + chunks.append(conflictResolution.rawValue) + } + items.append(chunks.joinWithSeparator(" ")) + } + + for (columns, conflictResolution) in uniqueKeyConstraints { + var chunks: [String] = [] + chunks.append("UNIQUE") + chunks.append("(\((columns.map { $0.quotedDatabaseIdentifier } as [String]).joinWithSeparator(", ")))") + if let conflictResolution = conflictResolution { + chunks.append("ON CONFLICT") + chunks.append(conflictResolution.rawValue) + } + items.append(chunks.joinWithSeparator(" ")) + } + + chunks.append("(\(items.joinWithSeparator(", ")))") + } + if withoutRowID { chunks.append("WITHOUT ROWID") } diff --git a/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift b/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift index 410fefbe6..24d8d913e 100644 --- a/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift +++ b/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift @@ -210,6 +210,63 @@ class SQLTableBuilderTests: GRDBTestCase { } } + func testTablePrimaryKey() { + assertNoError { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inTransaction { db in + try db.create(table: "test") { t in + t.column("a", .Text) + t.column("b", .Text) + t.primaryKey(["a", "b"]) + } + 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.column("a", .Text) + t.column("b", .Text) + t.primaryKey(["a", "b"], onConflict: .Fail) + } + 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.column("a", .Text) + t.column("b", .Text) + t.column("c", .Text) + t.uniqueKey(["a"]) + t.uniqueKey(["b", "c"], onConflict: .Fail) + } + XCTAssertEqual(self.lastSQLQuery, + "CREATE TABLE \"test\" (" + + "\"a\" TEXT, " + + "\"b\" TEXT, " + + "\"c\" TEXT, " + + "UNIQUE (\"a\"), " + + "UNIQUE (\"b\", \"c\") ON CONFLICT FAIL" + + ")") + } + } + } + func testDropTable() { assertNoError { let dbQueue = try makeDatabaseQueue() From 61cb276b94804f140e61f5d7eeb7c895402499eb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 5 Aug 2016 09:05:32 +0200 Subject: [PATCH 16/92] SQLTableBuilder: table.foreignKey() --- GRDB/QueryInterface/SQLTableBuilder.swift | 34 ++++++++++++++++++- .../SQLTableBuilderTests.swift | 28 +++++++++++++++ 2 files changed, 61 insertions(+), 1 deletion(-) diff --git a/GRDB/QueryInterface/SQLTableBuilder.swift b/GRDB/QueryInterface/SQLTableBuilder.swift index 72e67ec16..a4723b2e3 100644 --- a/GRDB/QueryInterface/SQLTableBuilder.swift +++ b/GRDB/QueryInterface/SQLTableBuilder.swift @@ -6,6 +6,7 @@ public class SQLTableBuilder { var columns: [SQLColumnBuilder] = [] var primaryKeyConstraint: (columns: [String], conflictResolution: SQLConflictResolution?)? var uniqueKeyConstraints: [(columns: [String], conflictResolution: SQLConflictResolution?)] = [] + var foreignKeyConstraints: [(columns: [String], table: String, destinationColumns: [String]?, deleteAction: SQLForeignKeyAction?, updateAction: SQLForeignKeyAction?, deferred: Bool)] = [] init(name: String, temporary: Bool, ifNotExists: Bool, withoutRowID: Bool) { self.name = name @@ -34,6 +35,11 @@ public class SQLTableBuilder { uniqueKeyConstraints.append((columns: columns, conflictResolution: conflictResolution)) } + // TODO: doc + public func foreignKey(columns: [String], to 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)) + } + func sql(db: Database) throws -> String { var chunks: [String] = [] chunks.append("CREATE") @@ -72,6 +78,32 @@ public class SQLTableBuilder { items.append(chunks.joinWithSeparator(" ")) } + for (columns, table, destinationColumns, deleteAction, updateAction, deferred) in foreignKeyConstraints { + var chunks: [String] = [] + chunks.append("FOREIGN KEY") + chunks.append("(\((columns.map { $0.quotedDatabaseIdentifier } as [String]).joinWithSeparator(", ")))") + chunks.append("REFERENCES") + if let destinationColumns = destinationColumns { + chunks.append("\(table.quotedDatabaseIdentifier)(\((destinationColumns.map { $0.quotedDatabaseIdentifier } as [String]).joinWithSeparator(", ")))") + } else if let primaryKey = try db.primaryKey(table) { + chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKey.columns.map { $0.quotedDatabaseIdentifier } as [String]).joinWithSeparator(", ")))") + } 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.joinWithSeparator(" ")) + } + chunks.append("(\(items.joinWithSeparator(", ")))") } @@ -201,7 +233,7 @@ public class SQLColumnBuilder { } else if let primaryKey = try db.primaryKey(table) { chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKey.columns.map { $0.quotedDatabaseIdentifier } as [String]).joinWithSeparator(", ")))") } else { - chunks.append("\(table.quotedDatabaseIdentifier)(_rowid_)") + fatalError("explicit referenced column required, since table \(table) has no primary key") } if let deleteAction = deleteAction { chunks.append("ON DELETE") diff --git a/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift b/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift index 24d8d913e..5598e1d3c 100644 --- a/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift +++ b/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift @@ -267,6 +267,34 @@ class SQLTableBuilderTests: GRDBTestCase { } } + func testTableForeignKey() { + assertNoError { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parent") { t in + t.column("a", .Text) + t.column("b", .Text) + t.primaryKey(["a", "b"]) + } + try db.create(table: "child") { t in + t.column("c", .Text) + t.column("d", .Text) + t.column("e", .Text) + t.foreignKey(["c", "d"], to: "parent", onDelete: .Cascade, onUpdate: .Cascade) + t.foreignKey(["d", "e"], to: "parent", columns: ["b", "a"], onDelete: .Restrict, deferred: true) + } + 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 testDropTable() { assertNoError { let dbQueue = try makeDatabaseQueue() From 88894a6d5464cfe48a787cf7296e3ce261340376 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 5 Aug 2016 09:12:25 +0200 Subject: [PATCH 17/92] SQLTableBuilder: TODO --- GRDB/QueryInterface/SQLTableBuilder.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/GRDB/QueryInterface/SQLTableBuilder.swift b/GRDB/QueryInterface/SQLTableBuilder.swift index a4723b2e3..20af77753 100644 --- a/GRDB/QueryInterface/SQLTableBuilder.swift +++ b/GRDB/QueryInterface/SQLTableBuilder.swift @@ -151,6 +151,7 @@ public class SQLColumnBuilder { } // TODO: doc + // TODO: defaults(sql: "CURRENT_TIMESTAMP") public func defaults(value: _SQLExpressible) { defaultExpression = value.sqlExpression } From ba126f1f1ade0abc714ea9606b3ff97601d889b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 5 Aug 2016 13:24:10 +0200 Subject: [PATCH 18/92] SQLTableBuilder: code organization --- GRDB/QueryInterface/SQLTableBuilder.swift | 240 +++++++++++----------- 1 file changed, 124 insertions(+), 116 deletions(-) diff --git a/GRDB/QueryInterface/SQLTableBuilder.swift b/GRDB/QueryInterface/SQLTableBuilder.swift index 20af77753..78a6f8bbf 100644 --- a/GRDB/QueryInterface/SQLTableBuilder.swift +++ b/GRDB/QueryInterface/SQLTableBuilder.swift @@ -1,4 +1,20 @@ -public class SQLTableBuilder { +extension Database { + // TODO: doc + // TODO: Don't expose withoutRowID if not available + public func create(table name: String, temporary: Bool = false, ifNotExists: Bool = false, withoutRowID: Bool = false, body: (SQLTableBuilder) -> Void) throws { + let builder = SQLTableBuilder(name: name, temporary: temporary, ifNotExists: ifNotExists, withoutRowID: withoutRowID) + body(builder) + let sql = try builder.sql(self) + try execute(sql) + } + + // TODO: doc + public func drop(table name: String) throws { + try execute("DROP TABLE \(name.quotedDatabaseIdentifier)") + } +} + +public final class SQLTableBuilder { let name: String let temporary: Bool let ifNotExists: Bool @@ -39,7 +55,113 @@ public class SQLTableBuilder { public func foreignKey(columns: [String], to 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)) } +} + +public final class SQLColumnBuilder { + let name: String + let type: SQLColumnType + var primaryKey: (ordering: SQLOrdering?, conflictResolution: SQLConflictResolution?, autoincrement: Bool)? + var notNullConflictResolution: SQLConflictResolution? + var uniqueConflictResolution: SQLConflictResolution? + var checkExpression: _SQLExpression? + var defaultExpression: _SQLExpression? + var collationName: String? + var reference: (table: String, column: String?, deleteAction: SQLForeignKeyAction?, updateAction: SQLForeignKeyAction?, deferred: Bool)? + init(name: String, type: SQLColumnType) { + self.name = name + self.type = type + } + + // TODO: doc + public func primaryKey(ordering ordering: SQLOrdering? = nil, onConflict conflictResolution: SQLConflictResolution? = nil, autoincrement: Bool = false) { + primaryKey = (ordering: ordering, conflictResolution: conflictResolution, autoincrement: autoincrement) + } + + // TODO: doc + public func notNull(onConflict conflictResolution: SQLConflictResolution? = nil) { + notNullConflictResolution = conflictResolution ?? .Abort + } + + // TODO: doc + public func unique(onConflict conflictResolution: SQLConflictResolution? = nil) { + uniqueConflictResolution = conflictResolution ?? .Abort + } + + // TODO: doc + public func check(@noescape condition: (SQLColumn) -> _SQLExpressible) { + checkExpression = condition(SQLColumn(name)).sqlExpression + } + + // TODO: doc + // TODO: defaults(sql: "CURRENT_TIMESTAMP") + // TODO: _SQLExpressible or DatabaseValueConvertible? + public func defaults(value: _SQLExpressible) { + defaultExpression = value.sqlExpression + } + + // TODO: doc + public func collate(collation: SQLCollation) { + collationName = collation.rawValue + } + + // TODO: doc + public func collate(collation: DatabaseCollation) { + collationName = collation.name + } + + // TODO: doc + public func references(table: String, column: String? = nil, onDelete deleteAction: SQLForeignKeyAction? = nil, onUpdate updateAction: SQLForeignKeyAction? = nil, deferred: Bool = false) { + reference = (table: table, column: column, deleteAction: deleteAction, updateAction: updateAction, deferred: deferred) + } +} + +// TODO: doc +public enum SQLOrdering : String { + case Asc = "ASC" + case Desc = "DESC" +} + +// TODO: doc +public enum SQLCollation : String { + case Binary = "BINARY" + case Nocase = "NOCASE" + case Rtrim = "RTRIM" +} + +// TODO: doc +public enum SQLConflictResolution : String { + case Rollback = "ROLLBACK" + case Abort = "ABORT" + case Fail = "FAIL" + case Ignore = "IGNORE" + case Replace = "REPLACE" +} + +// TODO: doc +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" +} + +// TODO: doc +public enum SQLForeignKeyAction : String { + case Cascade = "CASCADE" + case Restrict = "RESTRICT" + case SetNull = "SET NULL" + case SetDefault = "SET DEFAULT" +} + + +// MARK: - SQL Generation + +extension SQLTableBuilder { func sql(db: Database) throws -> String { var chunks: [String] = [] chunks.append("CREATE") @@ -114,63 +236,7 @@ public class SQLTableBuilder { } } -public class SQLColumnBuilder { - let name: String - let type: SQLColumnType - var primaryKey: (ordering: SQLOrdering?, conflictResolution: SQLConflictResolution?, autoincrement: Bool)? - var notNullConflictResolution: SQLConflictResolution? - var uniqueConflictResolution: SQLConflictResolution? - var checkExpression: _SQLExpression? - var defaultExpression: _SQLExpression? - var collationName: String? - var reference: (table: String, column: String?, deleteAction: SQLForeignKeyAction?, updateAction: SQLForeignKeyAction?, deferred: Bool)? - - init(name: String, type: SQLColumnType) { - self.name = name - self.type = type - } - - // TODO: doc - public func primaryKey(ordering ordering: SQLOrdering? = nil, onConflict conflictResolution: SQLConflictResolution? = nil, autoincrement: Bool = false) { - primaryKey = (ordering: ordering, conflictResolution: conflictResolution, autoincrement: autoincrement) - } - - // TODO: doc - public func notNull(onConflict conflictResolution: SQLConflictResolution? = nil) { - notNullConflictResolution = conflictResolution ?? .Abort - } - - // TODO: doc - public func unique(onConflict conflictResolution: SQLConflictResolution? = nil) { - uniqueConflictResolution = conflictResolution ?? .Abort - } - - // TODO: doc - public func check(@noescape condition: (SQLColumn) -> _SQLExpressible) { - checkExpression = condition(SQLColumn(name)).sqlExpression - } - - // TODO: doc - // TODO: defaults(sql: "CURRENT_TIMESTAMP") - public func defaults(value: _SQLExpressible) { - defaultExpression = value.sqlExpression - } - - // TODO: doc - public func collate(collation: SQLCollation) { - collationName = collation.rawValue - } - - // TODO: doc - public func collate(collation: DatabaseCollation) { - collationName = collation.name - } - - // TODO: doc - public func references(table: String, column: String? = nil, onDelete deleteAction: SQLForeignKeyAction? = nil, onUpdate updateAction: SQLForeignKeyAction? = nil, deferred: Bool = false) { - reference = (table: table, column: column, deleteAction: deleteAction, updateAction: updateAction, deferred: deferred) - } - +extension SQLColumnBuilder { func sql(db: Database) throws -> String { var chunks: [String] = [] chunks.append(name.quotedDatabaseIdentifier) @@ -252,61 +318,3 @@ public class SQLColumnBuilder { return chunks.joinWithSeparator(" ") } } - -// TODO: doc -public enum SQLOrdering : String { - case Asc = "ASC" - case Desc = "DESC" -} - -// TODO: doc -public enum SQLCollation : String { - case Binary = "BINARY" - case Nocase = "NOCASE" - case Rtrim = "RTRIM" -} - -// TODO: doc -public enum SQLConflictResolution : String { - case Rollback = "ROLLBACK" - case Abort = "ABORT" - case Fail = "FAIL" - case Ignore = "IGNORE" - case Replace = "REPLACE" -} - -// TODO: doc -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" -} - -// TODO: doc -public enum SQLForeignKeyAction : String { - case Cascade = "CASCADE" - case Restrict = "RESTRICT" - case SetNull = "SET NULL" - case SetDefault = "SET DEFAULT" -} - -extension Database { - // TODO: doc - // TODO: Don't expose withoutRowID if not available - public func create(table name: String, temporary: Bool = false, ifNotExists: Bool = false, withoutRowID: Bool = false, body: (SQLTableBuilder) -> Void) throws { - let builder = SQLTableBuilder(name: name, temporary: temporary, ifNotExists: ifNotExists, withoutRowID: withoutRowID) - body(builder) - let sql = try builder.sql(self) - try execute(sql) - } - - // TODO: doc - public func drop(table name: String) throws { - try execute("DROP TABLE \(name.quotedDatabaseIdentifier)") - } -} From 41037eb4252bedbdad7af77a427d95b8271480b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 5 Aug 2016 13:33:47 +0200 Subject: [PATCH 19/92] SQLTableBuilder: column.defaults() requires a constant value (so does SQLite) --- GRDB/QueryInterface/SQLTableBuilder.swift | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/GRDB/QueryInterface/SQLTableBuilder.swift b/GRDB/QueryInterface/SQLTableBuilder.swift index 78a6f8bbf..17c06948f 100644 --- a/GRDB/QueryInterface/SQLTableBuilder.swift +++ b/GRDB/QueryInterface/SQLTableBuilder.swift @@ -64,7 +64,7 @@ public final class SQLColumnBuilder { var notNullConflictResolution: SQLConflictResolution? var uniqueConflictResolution: SQLConflictResolution? var checkExpression: _SQLExpression? - var defaultExpression: _SQLExpression? + var defaultValue: DatabaseValueConvertible? var collationName: String? var reference: (table: String, column: String?, deleteAction: SQLForeignKeyAction?, updateAction: SQLForeignKeyAction?, deferred: Bool)? @@ -95,9 +95,8 @@ public final class SQLColumnBuilder { // TODO: doc // TODO: defaults(sql: "CURRENT_TIMESTAMP") - // TODO: _SQLExpressible or DatabaseValueConvertible? - public func defaults(value: _SQLExpressible) { - defaultExpression = value.sqlExpression + public func defaults(value: DatabaseValueConvertible) { + defaultValue = value } // TODO: doc @@ -282,10 +281,10 @@ extension SQLColumnBuilder { chunks.append("(" + checkExpression.sql(&arguments) + ")") } - if let defaultExpression = defaultExpression { - var arguments: StatementArguments? = nil // nil so that defaultExpression.sql(&arguments) embeds literals + if let defaultValue = defaultValue { + var arguments: StatementArguments? = nil // nil so that defaultValue.sqlExpression.sql(&arguments) embeds literals chunks.append("DEFAULT") - chunks.append("(" + defaultExpression.sql(&arguments) + ")") + chunks.append("(" + defaultValue.sqlExpression.sql(&arguments) + ")") } if let collationName = collationName { From 9b9b4d4bdfac92a5341cc672e82565dde998dc23 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 5 Aug 2016 13:52:09 +0200 Subject: [PATCH 20/92] SQLTableBuilder: column.defaults() and column.check() now accept SQL literal --- GRDB/QueryInterface/SQLTableBuilder.swift | 21 +++++++++++++------ .../SQLTableBuilderTests.swift | 18 ++++++++++++---- 2 files changed, 29 insertions(+), 10 deletions(-) diff --git a/GRDB/QueryInterface/SQLTableBuilder.swift b/GRDB/QueryInterface/SQLTableBuilder.swift index 17c06948f..b7e1cd368 100644 --- a/GRDB/QueryInterface/SQLTableBuilder.swift +++ b/GRDB/QueryInterface/SQLTableBuilder.swift @@ -64,7 +64,7 @@ public final class SQLColumnBuilder { var notNullConflictResolution: SQLConflictResolution? var uniqueConflictResolution: SQLConflictResolution? var checkExpression: _SQLExpression? - var defaultValue: DatabaseValueConvertible? + var defaultExpression: _SQLExpression? var collationName: String? var reference: (table: String, column: String?, deleteAction: SQLForeignKeyAction?, updateAction: SQLForeignKeyAction?, deferred: Bool)? @@ -94,9 +94,18 @@ public final class SQLColumnBuilder { } // TODO: doc - // TODO: defaults(sql: "CURRENT_TIMESTAMP") + public func check(sql sql: String) { + checkExpression = _SQLExpression.Literal(sql, nil) + } + + // TODO: doc public func defaults(value: DatabaseValueConvertible) { - defaultValue = value + defaultExpression = value.sqlExpression + } + + // TODO: doc + public func defaults(sql sql: String) { + defaultExpression = _SQLExpression.Literal(sql, nil) } // TODO: doc @@ -281,10 +290,10 @@ extension SQLColumnBuilder { chunks.append("(" + checkExpression.sql(&arguments) + ")") } - if let defaultValue = defaultValue { - var arguments: StatementArguments? = nil // nil so that defaultValue.sqlExpression.sql(&arguments) embeds literals + if let defaultExpression = defaultExpression { + var arguments: StatementArguments? = nil // nil so that defaultExpression.sql(&arguments) embeds literals chunks.append("DEFAULT") - chunks.append("(" + defaultValue.sqlExpression.sql(&arguments) + ")") + chunks.append("(" + defaultExpression.sql(&arguments) + ")") } if let collationName = collationName { diff --git a/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift b/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift index 5598e1d3c..1f9b54ff4 100644 --- a/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift +++ b/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift @@ -124,16 +124,18 @@ class SQLTableBuilderTests: GRDBTestCase { 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))" + + "\"a\" INTEGER CHECK ((\"a\" > 0)), " + + "\"b\" INTEGER CHECK (b <> 2)" + ")") // Sanity check - try db.execute("INSERT INTO test (a) VALUES (1)") + try db.execute("INSERT INTO test (a, b) VALUES (1, 0)") do { - try db.execute("INSERT INTO test (a) VALUES (0)") + try db.execute("INSERT INTO test (a, b) VALUES (0, 0)") XCTFail() } catch { } @@ -147,10 +149,18 @@ class SQLTableBuilderTests: GRDBTestCase { 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".dataUsingEncoding(NSUTF8StringEncoding)!) + t.column("e", .Integer).defaults(sql: "NULL") } XCTAssertEqual(self.lastSQLQuery, "CREATE TABLE \"test\" (" + - "\"a\" INTEGER DEFAULT (1)" + + "\"a\" INTEGER DEFAULT (1), " + + "\"b\" INTEGER DEFAULT (1.0), " + + "\"c\" INTEGER DEFAULT ('foo'), " + + "\"d\" INTEGER DEFAULT (x'666f6f'), " + + "\"e\" INTEGER DEFAULT (NULL)" + ")") // Sanity check From b88d2fe11124df7eb16b54f9905d5aa2ba9ba7f7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 5 Aug 2016 14:03:50 +0200 Subject: [PATCH 21/92] SQLTableBuilder: table.check() --- GRDB/QueryInterface/SQLTableBuilder.swift | 19 ++++++++++++ .../SQLTableBuilderTests.swift | 29 +++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/GRDB/QueryInterface/SQLTableBuilder.swift b/GRDB/QueryInterface/SQLTableBuilder.swift index b7e1cd368..16993c205 100644 --- a/GRDB/QueryInterface/SQLTableBuilder.swift +++ b/GRDB/QueryInterface/SQLTableBuilder.swift @@ -23,6 +23,7 @@ public final class SQLTableBuilder { var primaryKeyConstraint: (columns: [String], conflictResolution: SQLConflictResolution?)? var uniqueKeyConstraints: [(columns: [String], conflictResolution: SQLConflictResolution?)] = [] var foreignKeyConstraints: [(columns: [String], table: String, destinationColumns: [String]?, deleteAction: SQLForeignKeyAction?, updateAction: SQLForeignKeyAction?, deferred: Bool)] = [] + var checkConstraints: [_SQLExpression] = [] init(name: String, temporary: Bool, ifNotExists: Bool, withoutRowID: Bool) { self.name = name @@ -55,6 +56,16 @@ public final class SQLTableBuilder { public func foreignKey(columns: [String], to 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)) } + + // TODO: doc + public func check(condition: _SQLExpressible) { + checkConstraints.append(condition.sqlExpression) + } + + // TODO: doc + public func check(sql sql: String) { + checkConstraints.append(_SQLExpression.Literal(sql, nil)) + } } public final class SQLColumnBuilder { @@ -234,6 +245,14 @@ extension SQLTableBuilder { items.append(chunks.joinWithSeparator(" ")) } + for checkExpression in checkConstraints { + var chunks: [String] = [] + var arguments: StatementArguments? = nil // nil so that checkExpression.sql(&arguments) embeds literals + chunks.append("CHECK") + chunks.append("(" + checkExpression.sql(&arguments) + ")") + items.append(chunks.joinWithSeparator(" ")) + } + chunks.append("(\(items.joinWithSeparator(", ")))") } diff --git a/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift b/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift index 1f9b54ff4..802244e36 100644 --- a/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift +++ b/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift @@ -305,6 +305,35 @@ class SQLTableBuilderTests: GRDBTestCase { } } + func testTableCheck() { + assertNoError { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "test") { t in + t.column("a", .Integer) + t.column("b", .Integer) + t.check(SQLColumn("a") > SQLColumn("b")) + t.check(sql: "a + b < 10") + } + XCTAssertEqual(self.lastSQLQuery, + "CREATE TABLE \"test\" (" + + "\"a\" INTEGER, " + + "\"b\" INTEGER, " + + "CHECK ((\"a\" > \"b\")), " + + "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 (0, 1)") + XCTFail() + } catch { + } + } + } + } + func testDropTable() { assertNoError { let dbQueue = try makeDatabaseQueue() From f2a7706bdf52ca1b35e2ee449e7440d474188648 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 5 Aug 2016 14:06:11 +0200 Subject: [PATCH 22/92] SQLTableBuilder: test ordering of DSL statements is not the ordering of SQL clauses --- .../SQLTableBuilder/SQLTableBuilderTests.swift | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift b/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift index 802244e36..5312b08b4 100644 --- a/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift +++ b/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift @@ -225,9 +225,9 @@ class SQLTableBuilderTests: GRDBTestCase { 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) - t.primaryKey(["a", "b"]) } XCTAssertEqual(self.lastSQLQuery, "CREATE TABLE \"test\" (" + @@ -239,9 +239,9 @@ class SQLTableBuilderTests: GRDBTestCase { } 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) - t.primaryKey(["a", "b"], onConflict: .Fail) } XCTAssertEqual(self.lastSQLQuery, "CREATE TABLE \"test\" (" + @@ -259,11 +259,11 @@ class SQLTableBuilderTests: GRDBTestCase { 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) - t.uniqueKey(["a"]) - t.uniqueKey(["b", "c"], onConflict: .Fail) } XCTAssertEqual(self.lastSQLQuery, "CREATE TABLE \"test\" (" + @@ -282,16 +282,16 @@ class SQLTableBuilderTests: GRDBTestCase { 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) - t.primaryKey(["a", "b"]) } try db.create(table: "child") { t in + t.foreignKey(["c", "d"], to: "parent", onDelete: .Cascade, onUpdate: .Cascade) + t.foreignKey(["d", "e"], to: "parent", columns: ["b", "a"], onDelete: .Restrict, deferred: true) t.column("c", .Text) t.column("d", .Text) t.column("e", .Text) - t.foreignKey(["c", "d"], to: "parent", onDelete: .Cascade, onUpdate: .Cascade) - t.foreignKey(["d", "e"], to: "parent", columns: ["b", "a"], onDelete: .Restrict, deferred: true) } XCTAssertEqual(self.lastSQLQuery, "CREATE TABLE \"child\" (" + @@ -310,10 +310,10 @@ class SQLTableBuilderTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "test") { t in - t.column("a", .Integer) - t.column("b", .Integer) t.check(SQLColumn("a") > SQLColumn("b")) t.check(sql: "a + b < 10") + t.column("a", .Integer) + t.column("b", .Integer) } XCTAssertEqual(self.lastSQLQuery, "CREATE TABLE \"test\" (" + From ed2ea88cb592c5e7a46baf2686ee466a46c42dba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 5 Aug 2016 14:55:07 +0200 Subject: [PATCH 23/92] TODO.md --- TODO.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/TODO.md b/TODO.md index 4e7c56952..c3b7da225 100644 --- a/TODO.md +++ b/TODO.md @@ -1,4 +1,4 @@ -- [ ] Document Statement.unsafeSetArguments +- [ ] Nice navigation in https://github.com/jcampbell05/xcake - [ ] 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). - [ ] GRDBCipher: remove limitations on iOS or OS X versions - [ ] FetchedRecordsController: take inspiration from https://github.com/jflinter/Dwifft From ac5279fa70be28c0ca7db72d55a94b1fcdc1c310 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 5 Aug 2016 18:51:06 +0200 Subject: [PATCH 24/92] Use SQLCollation instead of String --- CHANGELOG.md | 25 +++++++++++++- GRDB/QueryInterface/SQLCollation.swift | 8 +++-- .../QueryInterfaceRequestTests.swift | 8 ++--- .../SQLSupportTests.swift | 34 +++++++++---------- 4 files changed, 51 insertions(+), 24 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6b54eba56..d1de85b0f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,30 @@ Release Notes - 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 - + +- Database schema DSL (TODO: doc link): + + ```swift + // CREATE TABLE pointOfInterests ( + // id INTEGER PRIMARY KEY, + // title TEXT, + // favorite BOOLEAN NOT NULL, + // latitude DOUBLE NOT NULL, + // longitude DOUBLE NOT NULL + // ) + 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() + } + ``` + +**Breaking Changes** + +- Built-in SQLite collations used to be named by string: "NOCASE", etc. Now use the SQLCollation enum: `.Nocase`, etc. + ## 0.77.0 diff --git a/GRDB/QueryInterface/SQLCollation.swift b/GRDB/QueryInterface/SQLCollation.swift index 640f9857d..a074b1dea 100644 --- a/GRDB/QueryInterface/SQLCollation.swift +++ b/GRDB/QueryInterface/SQLCollation.swift @@ -53,12 +53,16 @@ extension _SQLCollatedExpression : _SQLOrdering { extension _SpecificSQLExpressible { + 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/Tests/Public/QueryInterfaceRequest/QueryInterfaceRequestTests.swift b/Tests/Public/QueryInterfaceRequest/QueryInterfaceRequestTests.swift index 2b80aa505..c98cc1331 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")).reverse()), + sql(dbQueue, tableRequest.order(Col.name.collating(.Nocase)).reverse()), "SELECT * FROM \"readers\" ORDER BY \"name\" COLLATE NOCASE DESC") XCTAssertEqual( - sql(dbQueue, tableRequest.order(Col.name.collating("NOCASE").asc).reverse()), + sql(dbQueue, tableRequest.order(Col.name.collating(.Nocase).asc).reverse()), "SELECT * FROM \"readers\" ORDER BY \"name\" COLLATE NOCASE DESC") XCTAssertEqual( sql(dbQueue, tableRequest.order(Col.name.collating(collation)).reverse()), diff --git a/Tests/Public/QueryInterfaceRequest/SQLSupportTests.swift b/Tests/Public/QueryInterfaceRequest/SQLSupportTests.swift index 1eb09bcce..16c373efb 100644 --- a/Tests/Public/QueryInterfaceRequest/SQLSupportTests.swift +++ b/Tests/Public/QueryInterfaceRequest/SQLSupportTests.swift @@ -126,29 +126,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: 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: 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))") } @@ -190,7 +190,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")), @@ -235,7 +235,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")), @@ -280,7 +280,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")), @@ -325,7 +325,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")), @@ -404,13 +404,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")), @@ -489,13 +489,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")), @@ -573,7 +573,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")), @@ -624,7 +624,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")), From 8b6ac9c736df9e30ac16c7c8ebcc68d678ac57ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 5 Aug 2016 19:58:12 +0200 Subject: [PATCH 25/92] SQLTableBuilder: create(index:), drop(index:) --- GRDB/QueryInterface/SQLTableBuilder.swift | 46 ++++++++++++++++++- .../SQLTableBuilderTests.swift | 41 +++++++++++++++++ 2 files changed, 85 insertions(+), 2 deletions(-) diff --git a/GRDB/QueryInterface/SQLTableBuilder.swift b/GRDB/QueryInterface/SQLTableBuilder.swift index 16993c205..f7ea5c521 100644 --- a/GRDB/QueryInterface/SQLTableBuilder.swift +++ b/GRDB/QueryInterface/SQLTableBuilder.swift @@ -8,10 +8,22 @@ extension Database { try execute(sql) } + // TODO: doc + public func create(index name: String, on table: String, columns: [String], unique: Bool = false, ifNotExists: Bool = false, condition: _SQLExpressible? = nil) throws { + let builder = IndexBuilder(name: name, table: table, columns: columns, unique: unique, ifNotExists: ifNotExists, condition: condition?.sqlExpression) + let sql = builder.sql() + try execute(sql) + } + // TODO: doc public func drop(table name: String) throws { try execute("DROP TABLE \(name.quotedDatabaseIdentifier)") } + + // TODO: doc + public func drop(index name: String) throws { + try execute("DROP INDEX \(name.quotedDatabaseIdentifier)") + } } public final class SQLTableBuilder { @@ -247,8 +259,8 @@ extension SQLTableBuilder { for checkExpression in checkConstraints { var chunks: [String] = [] - var arguments: StatementArguments? = nil // nil so that checkExpression.sql(&arguments) embeds literals chunks.append("CHECK") + var arguments: StatementArguments? = nil // nil so that checkExpression.sql(&arguments) embeds literals chunks.append("(" + checkExpression.sql(&arguments) + ")") items.append(chunks.joinWithSeparator(" ")) } @@ -304,8 +316,8 @@ extension SQLColumnBuilder { } if let checkExpression = checkExpression { - var arguments: StatementArguments? = nil // nil so that checkExpression.sql(&arguments) embeds literals chunks.append("CHECK") + var arguments: StatementArguments? = nil // nil so that checkExpression.sql(&arguments) embeds literals chunks.append("(" + checkExpression.sql(&arguments) + ")") } @@ -345,3 +357,33 @@ extension SQLColumnBuilder { return chunks.joinWithSeparator(" ") } } + +struct IndexBuilder { + 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]).joinWithSeparator(", ")))") + 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.joinWithSeparator(" ") + } +} diff --git a/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift b/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift index 5312b08b4..006227334 100644 --- a/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift +++ b/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift @@ -350,4 +350,45 @@ class SQLTableBuilderTests: GRDBTestCase { } } } + + 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) + } + } + } } From 31a0604341d51f65762a97a42975a0c28d85313e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 5 Aug 2016 20:04:28 +0200 Subject: [PATCH 26/92] SQLTableBuilder: rename(table:to:) --- GRDB/QueryInterface/SQLTableBuilder.swift | 15 ++++++++++----- .../SQLTableBuilder/SQLTableBuilderTests.swift | 17 +++++++++++++++++ 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/GRDB/QueryInterface/SQLTableBuilder.swift b/GRDB/QueryInterface/SQLTableBuilder.swift index f7ea5c521..5a3fe2d0b 100644 --- a/GRDB/QueryInterface/SQLTableBuilder.swift +++ b/GRDB/QueryInterface/SQLTableBuilder.swift @@ -8,17 +8,22 @@ extension Database { try execute(sql) } + // TODO: doc + public func rename(table name: String, to newName: String) throws { + try execute("ALTER TABLE \(name.quotedDatabaseIdentifier) RENAME TO \(newName.quotedDatabaseIdentifier)") + } + + // TODO: doc + public func drop(table name: String) throws { + try execute("DROP TABLE \(name.quotedDatabaseIdentifier)") + } + // TODO: doc public func create(index name: String, on table: String, columns: [String], unique: Bool = false, ifNotExists: Bool = false, condition: _SQLExpressible? = nil) throws { let builder = IndexBuilder(name: name, table: table, columns: columns, unique: unique, ifNotExists: ifNotExists, condition: condition?.sqlExpression) let sql = builder.sql() try execute(sql) } - - // TODO: doc - public func drop(table name: String) throws { - try execute("DROP TABLE \(name.quotedDatabaseIdentifier)") - } // TODO: doc public func drop(index name: String) throws { diff --git a/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift b/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift index 006227334..20f971f3a 100644 --- a/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift +++ b/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift @@ -334,6 +334,23 @@ class SQLTableBuilderTests: GRDBTestCase { } } + 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 testDropTable() { assertNoError { let dbQueue = try makeDatabaseQueue() From 89912326815ad03b20e51895756ed37ceaf784ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 5 Aug 2016 20:31:18 +0200 Subject: [PATCH 27/92] SQLTableBuilder: alter(table:) { $0.add(column:) } --- GRDB/QueryInterface/SQLTableBuilder.swift | 77 ++++++++++++++++--- .../SQLTableBuilderTests.swift | 30 ++++++-- 2 files changed, 91 insertions(+), 16 deletions(-) diff --git a/GRDB/QueryInterface/SQLTableBuilder.swift b/GRDB/QueryInterface/SQLTableBuilder.swift index 5a3fe2d0b..829c994f0 100644 --- a/GRDB/QueryInterface/SQLTableBuilder.swift +++ b/GRDB/QueryInterface/SQLTableBuilder.swift @@ -13,6 +13,14 @@ extension Database { try execute("ALTER TABLE \(name.quotedDatabaseIdentifier) RENAME TO \(newName.quotedDatabaseIdentifier)") } + // TODO: doc + public func alter(table name: String, body: (SQLTableAlterationBuilder) -> Void) throws { + let builder = SQLTableAlterationBuilder(name: name) + body(builder) + let sql = try builder.sql(self) + try execute(sql) + } + // TODO: doc public func drop(table name: String) throws { try execute("DROP TABLE \(name.quotedDatabaseIdentifier)") @@ -31,6 +39,7 @@ extension Database { } } +// TODO: doc public final class SQLTableBuilder { let name: String let temporary: Bool @@ -85,6 +94,24 @@ public final class SQLTableBuilder { } } +// TODO: doc +public final class SQLTableAlterationBuilder { + let name: String + var addedColumns: [SQLColumnBuilder] = [] + + init(name: String) { + self.name = name + } + + // TODO: doc + public func add(column name: String, _ type: SQLColumnType) -> SQLColumnBuilder { + let column = SQLColumnBuilder(name: name, type: type) + addedColumns.append(column) + return column + } +} + +// TODO: doc public final class SQLColumnBuilder { let name: String let type: SQLColumnType @@ -102,53 +129,63 @@ public final class SQLColumnBuilder { } // TODO: doc - public func primaryKey(ordering ordering: SQLOrdering? = nil, onConflict conflictResolution: SQLConflictResolution? = nil, autoincrement: Bool = false) { + public func primaryKey(ordering ordering: SQLOrdering? = nil, onConflict conflictResolution: SQLConflictResolution? = nil, autoincrement: Bool = false) -> SQLColumnBuilder { primaryKey = (ordering: ordering, conflictResolution: conflictResolution, autoincrement: autoincrement) + return self } // TODO: doc - public func notNull(onConflict conflictResolution: SQLConflictResolution? = nil) { + public func notNull(onConflict conflictResolution: SQLConflictResolution? = nil) -> SQLColumnBuilder { notNullConflictResolution = conflictResolution ?? .Abort + return self } // TODO: doc - public func unique(onConflict conflictResolution: SQLConflictResolution? = nil) { + public func unique(onConflict conflictResolution: SQLConflictResolution? = nil) -> SQLColumnBuilder { uniqueConflictResolution = conflictResolution ?? .Abort + return self } // TODO: doc - public func check(@noescape condition: (SQLColumn) -> _SQLExpressible) { + public func check(@noescape condition: (SQLColumn) -> _SQLExpressible) -> SQLColumnBuilder { checkExpression = condition(SQLColumn(name)).sqlExpression + return self } // TODO: doc - public func check(sql sql: String) { + public func check(sql sql: String) -> SQLColumnBuilder { checkExpression = _SQLExpression.Literal(sql, nil) + return self } // TODO: doc - public func defaults(value: DatabaseValueConvertible) { + public func defaults(value: DatabaseValueConvertible) -> SQLColumnBuilder { defaultExpression = value.sqlExpression + return self } // TODO: doc - public func defaults(sql sql: String) { + public func defaults(sql sql: String) -> SQLColumnBuilder { defaultExpression = _SQLExpression.Literal(sql, nil) + return self } // TODO: doc - public func collate(collation: SQLCollation) { + public func collate(collation: SQLCollation) -> SQLColumnBuilder { collationName = collation.rawValue + return self } // TODO: doc - public func collate(collation: DatabaseCollation) { + public func collate(collation: DatabaseCollation) -> SQLColumnBuilder { collationName = collation.name + return self } // TODO: doc - public func references(table: String, column: String? = nil, onDelete deleteAction: SQLForeignKeyAction? = nil, onUpdate updateAction: SQLForeignKeyAction? = nil, deferred: Bool = false) { + public func references(table: String, column: String? = nil, onDelete deleteAction: SQLForeignKeyAction? = nil, onUpdate updateAction: SQLForeignKeyAction? = nil, deferred: Bool = false) -> SQLColumnBuilder { reference = (table: table, column: column, deleteAction: deleteAction, updateAction: updateAction, deferred: deferred) + return self } } @@ -280,6 +317,24 @@ extension SQLTableBuilder { } } +extension SQLTableAlterationBuilder { + 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.joinWithSeparator(" ") + statements.append(statement) + } + + return statements.joinWithSeparator("; ") + } +} + extension SQLColumnBuilder { func sql(db: Database) throws -> String { var chunks: [String] = [] @@ -329,7 +384,7 @@ extension SQLColumnBuilder { if let defaultExpression = defaultExpression { var arguments: StatementArguments? = nil // nil so that defaultExpression.sql(&arguments) embeds literals chunks.append("DEFAULT") - chunks.append("(" + defaultExpression.sql(&arguments) + ")") + chunks.append(defaultExpression.sql(&arguments)) } if let collationName = collationName { diff --git a/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift b/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift index 20f971f3a..ceeb122e2 100644 --- a/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift +++ b/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift @@ -156,11 +156,11 @@ class SQLTableBuilderTests: GRDBTestCase { } 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)" + + "\"a\" INTEGER DEFAULT 1, " + + "\"b\" INTEGER DEFAULT 1.0, " + + "\"c\" INTEGER DEFAULT 'foo', " + + "\"d\" INTEGER DEFAULT x'666f6f', " + + "\"e\" INTEGER DEFAULT NULL" + ")") // Sanity check @@ -351,6 +351,26 @@ class SQLTableBuilderTests: GRDBTestCase { } } + 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() From 03979d8665f9ace8006ba06d85dff9ff40ec020b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 5 Aug 2016 20:45:58 +0200 Subject: [PATCH 28/92] README.md --- README.md | 32 ++++++++++++++++++++++---------- 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index a248804b2..2b1ddcadb 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,30 @@ GRDB.swift [![Swift](https://img.shields.io/badge/swift-2.2-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 that provides access to SQLite databases. + +GRDB provides raw SQLite access and high-level APIs that help building applications. It targets Swift 2.2, and Swift 3 in the [Swift3](https://github.com/groue/GRDB.swift/tree/Swift3) branch. -It ships with a **low-level SQLite API**, and high-level tools that help dealing with databases: +**July 28, 2016: GRDB.swift 0.77.0 is out** ([CHANGELOG](CHANGELOG.md)). Follow [@groue](http://twitter.com/groue) on Twitter for release announcements and usage tips. + +**Requirements**: iOS 8.0+ / OSX 10.9+, Xcode 7.3+ + +--- + +

+ Features • + Usage • + 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 @@ -25,14 +44,7 @@ More than a set of tools that leverage SQLite abilities, GRDB is also: 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). ---- - -**July 28, 2016: GRDB.swift 0.77.0 is out** ([changelog](CHANGELOG.md)). Follow [@groue](http://twitter.com/groue) on Twitter for release announcements and usage tips. - -**Requirements**: iOS 8.0+ / OSX 10.9+, Xcode 7.3+ - - -### Usage +## Usage Open a [connection](#database-connections) to the database: From 6ac63436f703b06c910f5af7129bb0063d28c839 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 5 Aug 2016 20:48:16 +0200 Subject: [PATCH 29/92] README.md --- README.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 2b1ddcadb..efb9de164 100644 --- a/README.md +++ b/README.md @@ -3,21 +3,21 @@ GRDB.swift [![Swift](https://img.shields.io/badge/swift-2.2-orange.svg?style=fla ### A Swift application toolkit that provides access to SQLite databases. -GRDB provides raw SQLite access and high-level APIs that help building applications. - -It targets Swift 2.2, and Swift 3 in the [Swift3](https://github.com/groue/GRDB.swift/tree/Swift3) branch. - -**July 28, 2016: GRDB.swift 0.77.0 is out** ([CHANGELOG](CHANGELOG.md)). Follow [@groue](http://twitter.com/groue) on Twitter for release announcements and usage tips. +GRDB provides raw SQLite access and high-level APIs that help building applications. It targets Swift 2.2, and Swift 3 in the [Swift3](https://github.com/groue/GRDB.swift/tree/Swift3) branch. **Requirements**: iOS 8.0+ / OSX 10.9+, Xcode 7.3+ +**Last release**: July 28, 2016 • version 0.77.0 • [CHANGELOG](CHANGELOG.md). + +Follow [@groue](http://twitter.com/groue) on Twitter for release announcements and usage tips. + ---

Features • Usage • Documentation • - FAQ • + FAQ

--- From dce6d50350faaeac1ee1bc20564598b807943486 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 5 Aug 2016 20:49:32 +0200 Subject: [PATCH 30/92] README.md --- README.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/README.md b/README.md index efb9de164..5dc86cf19 100644 --- a/README.md +++ b/README.md @@ -3,9 +3,7 @@ GRDB.swift [![Swift](https://img.shields.io/badge/swift-2.2-orange.svg?style=fla ### A Swift application toolkit that provides access to SQLite databases. -GRDB provides raw SQLite access and high-level APIs that help building applications. It targets Swift 2.2, and Swift 3 in the [Swift3](https://github.com/groue/GRDB.swift/tree/Swift3) branch. - -**Requirements**: iOS 8.0+ / OSX 10.9+, Xcode 7.3+ +**Requirements**: iOS 8.0+ / OSX 10.9+, Xcode 7.3+, Swift 2.2 (see the [Swift3](https://github.com/groue/GRDB.swift/tree/Swift3) branch for Swift 3). **Last release**: July 28, 2016 • version 0.77.0 • [CHANGELOG](CHANGELOG.md). From 2f3c7eb550ed887d817a92c9d8fda1741c94eed5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 5 Aug 2016 20:49:57 +0200 Subject: [PATCH 31/92] README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 5dc86cf19..8024e8879 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,7 @@ Follow [@groue](http://twitter.com/groue) on Twitter for release announcements a

Features • Usage • + Installation • Documentation • FAQ

From 04ab95ab764333373d9a713464d338403a8b843b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 5 Aug 2016 20:51:15 +0200 Subject: [PATCH 32/92] README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 8024e8879..a75781d58 100644 --- a/README.md +++ b/README.md @@ -3,9 +3,9 @@ GRDB.swift [![Swift](https://img.shields.io/badge/swift-2.2-orange.svg?style=fla ### A Swift application toolkit that provides access to SQLite databases. -**Requirements**: iOS 8.0+ / OSX 10.9+, Xcode 7.3+, Swift 2.2 (see the [Swift3](https://github.com/groue/GRDB.swift/tree/Swift3) branch for Swift 3). +**Requirements**: iOS 8.0+ / OSX 10.9+ • Xcode 7.3+ • Swift 2.2 (see the [Swift3](https://github.com/groue/GRDB.swift/tree/Swift3) branch for Swift 3). -**Last release**: July 28, 2016 • version 0.77.0 • [CHANGELOG](CHANGELOG.md). +**Last release**: July 28, 2016 • version 0.77.0 • [CHANGELOG](CHANGELOG.md) Follow [@groue](http://twitter.com/groue) on Twitter for release announcements and usage tips. From 00a032e6b0dfcd713eb5065a9eea08a89133ca6e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 5 Aug 2016 22:58:03 +0200 Subject: [PATCH 33/92] SQLTableBuilder documentation --- CHANGELOG.md | 7 - README.md | 217 ++++++++++++++---- .../SQLTableBuilderTests.swift | 4 +- 3 files changed, 179 insertions(+), 49 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d1de85b0f..658c37478 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,13 +12,6 @@ Release Notes - Database schema DSL (TODO: doc link): ```swift - // CREATE TABLE pointOfInterests ( - // id INTEGER PRIMARY KEY, - // title TEXT, - // favorite BOOLEAN NOT NULL, - // latitude DOUBLE NOT NULL, - // longitude DOUBLE NOT NULL - // ) db.create(table: "pointOfInterests") { t in t.column("id", .Integer).primaryKey() t.column("title", .Text) diff --git a/README.md b/README.md index a75781d58..f3e447111 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ GRDB.swift [![Swift](https://img.shields.io/badge/swift-2.2-orange.svg?style=fla **Requirements**: iOS 8.0+ / OSX 10.9+ • Xcode 7.3+ • Swift 2.2 (see the [Swift3](https://github.com/groue/GRDB.swift/tree/Swift3) branch for Swift 3). -**Last release**: July 28, 2016 • version 0.77.0 • [CHANGELOG](CHANGELOG.md) +**Latest release**: July 28, 2016 • version 0.77.0 • [CHANGELOG](CHANGELOG.md) Follow [@groue](http://twitter.com/groue) on Twitter for release announcements and usage tips. @@ -130,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) + t.column("favorite", .Boolean).notNull() + 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) @@ -1593,7 +1600,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 @@ -2119,6 +2126,7 @@ let wines = Wine.fetchAll(db, "SELECT * FROM wines WHERE origin = ? ORDER BY pri So don't miss the [SQL API](#sqlite-api). +- [Database Schema](#database-schema) - [Requests](#requests) - [Expressions](#expressions) - [SQL Operators](#sql-operators) @@ -2128,9 +2136,139 @@ So don't miss the [SQL API](#sqlite-api). - [Fetching Aggregated Values](#fetching-aggregated-values) +### Database Schema + +Once granted with a [database connection](#database-connections), you can use the query interface to setup your database schema. + +- [Create Tables](#create-tables) +- [Modify Tables](#alter-tables) +- [Drop Tables](#drop-tables) +- [Create Indexes](#create-indexes) + + +#### Create Tables + +```swift +// 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().default(false) + t.column("longitude", .Double).notNull() + t.column("latitude", .Double).notNull() +} +``` + +The `create(table:)` method covers nearly all [CREATE TABLE](https://www.sqlite.org/lang_createtable.html) SQLite statements: + +```swift +// CREATE TEMPORARY TABLE demo IF NOT EXISTS ( +try db.create(table: "demo", 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, + t.column("name", .Text) + // creationDate DATETIME, + t.column("creationDate", .Datetime) +``` + +Define not null and unique columns, and set default values: + +```swift + // email TEXT NOT NULL UNIQUE, + t.column("email", .Text).notNull().unique() + + // uuid TEXT UNIQUE ON CONFLICT REPLACE, + t.column("uuid", .Text).unique(onConflict: .Replace) + + // flag BOOLEAN NOT NULL DEFAULT 0, + t.column("flag", .Boolean).notNull().default(false) +``` + +Perform integrity checks on individual columns (SQLite will only allow conforming rows): + +```swift + // age INTEGER CHECK (age > 0) + t.column("age", .Integer).check { $0 > 0 } +``` + +Use individual columns as primary or foreign keys. When not specified, the referenced column is the primary key of the referenced table: + +```swift + // id INTEGER PRIMARY KEY, + t.column("id", .Integer).primaryKey() + + // countryCode TEXT REFERENCES countries(code) ON DELETE CASCADE, + t.column("countryCode", .Text).references("countries", onDelete: .Cascade) +``` + +Other 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"], to: "parent", columns: ["a", "b"]) + + // CHECK (a + b < 10), + t.check(SQLColumn("a") + SQLColumn("b") < 10) + + // CHECK (a + b < 10) + t.check(sql: "a + b < 10") +} +``` + +#### Modify Tables + +SQLite let 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 website TEXT +try db.alter(table: "persons") { t in + t.add(column: "website", .Text) +} +``` + +Table alterations are restricted: see the documentation of the [ALTER TABLE](https://www.sqlite.org/lang_altertable.html), and [Migrations](#migrations) for a way to lift those restrictions. + + +#### Drop Tables + +Drop tables with the `drop(table:)` method: + +```swift +try db.drop(table: "obsolete") +``` + +#### Create Indexes + +Create index with the `create(index:)` method: + +```swift +// CREATE UNIQUE INDEX byEmail ON users(email) +try db.create(index: "byEmail", on: "users", columns: ["email"], unique: true) +``` + + ### Requests -Everything starts from **a type** that adopts the `TableMapping` protocol, such as a `Record` subclass (see [Records](#records)): +**All requests** start from a type that adopts the `TableMapping` protocol, such as a `Record` subclass (see [Records](#records)): ```swift class Person: Record { ... } @@ -3665,40 +3803,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: @@ -3740,6 +3844,39 @@ FAQ let dbQueue = 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/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift b/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift index ceeb122e2..d4a804842 100644 --- a/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift +++ b/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift @@ -310,7 +310,7 @@ class SQLTableBuilderTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "test") { t in - t.check(SQLColumn("a") > SQLColumn("b")) + t.check(SQLColumn("a") + SQLColumn("b") < 10) t.check(sql: "a + b < 10") t.column("a", .Integer) t.column("b", .Integer) @@ -319,7 +319,7 @@ class SQLTableBuilderTests: GRDBTestCase { "CREATE TABLE \"test\" (" + "\"a\" INTEGER, " + "\"b\" INTEGER, " + - "CHECK ((\"a\" > \"b\")), " + + "CHECK (((\"a\" + \"b\") < 10)), " + "CHECK (a + b < 10)" + ")") From 2fc25e9b13e0d7bdf032fad829102cd4f2a21aa0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 5 Aug 2016 23:00:23 +0200 Subject: [PATCH 34/92] SQLTableBuilder documentation --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index f3e447111..357af6f1a 100644 --- a/README.md +++ b/README.md @@ -2138,7 +2138,7 @@ So don't miss the [SQL API](#sqlite-api). ### Database Schema -Once granted with a [database connection](#database-connections), you can use the query interface to setup your database schema. +Once granted with a [database connection](#database-connections), you can use the query interface to setup your database schema: - [Create Tables](#create-tables) - [Modify Tables](#alter-tables) @@ -2176,8 +2176,8 @@ Add regular columns with their name and type (text, integer, double, numeric, bo ```swift // name TEXT, - t.column("name", .Text) // creationDate DATETIME, + t.column("name", .Text) t.column("creationDate", .Datetime) ``` From 415aeb1ef5b080fb13800679555a3c9b2dc4e3de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 5 Aug 2016 23:02:39 +0200 Subject: [PATCH 35/92] SQLTableBuilder documentation --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 357af6f1a..b577818c6 100644 --- a/README.md +++ b/README.md @@ -2258,7 +2258,7 @@ try db.drop(table: "obsolete") #### Create Indexes -Create index with the `create(index:)` method: +Create indexes with the `create(index:)` method: ```swift // CREATE UNIQUE INDEX byEmail ON users(email) From 3be6b6966b3ebaf0b52b593a2660ad71a50df826 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 5 Aug 2016 23:04:44 +0200 Subject: [PATCH 36/92] SQLTableBuilder documentation --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index b577818c6..2e6810253 100644 --- a/README.md +++ b/README.md @@ -2268,7 +2268,9 @@ try db.create(index: "byEmail", on: "users", columns: ["email"], unique: true) ### Requests -**All requests** start from a type that adopts the `TableMapping` protocol, such as a `Record` subclass (see [Records](#records)): +**The query interface requests** let you fetch values from the database. + +All requests start from **a type** that adopts the `TableMapping` protocol, such as a `Record` subclass (see [Records](#records)): ```swift class Person: Record { ... } From 2ef26e96816b18ec6669529ee476d3260107677b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 5 Aug 2016 23:06:38 +0200 Subject: [PATCH 37/92] SQLTableBuilder documentation --- README.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 2e6810253..ca02e860e 100644 --- a/README.md +++ b/README.md @@ -2268,7 +2268,12 @@ try db.create(index: "byEmail", on: "users", columns: ["email"], unique: true) ### Requests -**The query interface requests** let you fetch values from the database. +**The query interface requests** let you fetch values from the database: + +```swift +let count = Wine.filter(color == Color.Red).fetchCount(db) +let wines = Wine.filter(origin == "Burgundy").order(price).fetchAll(db) +``` All requests start from **a type** that adopts the `TableMapping` protocol, such as a `Record` subclass (see [Records](#records)): From 0ba002309905457d637cbbe2ed07495be11b3725 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 5 Aug 2016 23:22:47 +0200 Subject: [PATCH 38/92] SQLTableBuilder documentation + support for LENGTH SQLite function --- CHANGELOG.md | 2 ++ GRDB/QueryInterface/SQLFunction.swift | 10 ++++++++++ README.md | 4 +++- .../Public/QueryInterfaceRequest/SQLSupportTests.swift | 8 ++++++++ .../Public/SQLTableBuilder/SQLTableBuilderTests.swift | 2 +- 5 files changed, 24 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 658c37478..343f17f9f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,8 @@ Release Notes } ``` +- Support for the `length` SQLite built-in function. + **Breaking Changes** - Built-in SQLite collations used to be named by string: "NOCASE", etc. Now use the SQLCollation enum: `.Nocase`, etc. diff --git a/GRDB/QueryInterface/SQLFunction.swift b/GRDB/QueryInterface/SQLFunction.swift index 500dd348c..aa228a399 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/README.md b/README.md index ca02e860e..0c56eeccd 100644 --- a/README.md +++ b/README.md @@ -2194,11 +2194,13 @@ Define not null and unique columns, and set default values: t.column("flag", .Boolean).notNull().default(false) ``` -Perform integrity checks on individual columns (SQLite will only allow conforming rows): +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 // age INTEGER CHECK (age > 0) + // name TEXT CHECK (LENGTH(name) > 0) t.column("age", .Integer).check { $0 > 0 } + t.column("name", .Text).check { length($0) > 0 } ``` Use individual columns as primary or foreign keys. When not specified, the referenced column is the primary key of the referenced table: diff --git a/Tests/Public/QueryInterfaceRequest/SQLSupportTests.swift b/Tests/Public/QueryInterfaceRequest/SQLSupportTests.swift index 16c373efb..905009dbc 100644 --- a/Tests/Public/QueryInterfaceRequest/SQLSupportTests.swift +++ b/Tests/Public/QueryInterfaceRequest/SQLSupportTests.swift @@ -885,6 +885,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 index d4a804842..a51e6fdad 100644 --- a/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift +++ b/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift @@ -326,7 +326,7 @@ class SQLTableBuilderTests: GRDBTestCase { // Sanity check try db.execute("INSERT INTO test (a, b) VALUES (1, 0)") do { - try db.execute("INSERT INTO test (a, b) VALUES (0, 1)") + try db.execute("INSERT INTO test (a, b) VALUES (5, 5)") XCTFail() } catch { } From 29d43969562f57907e50e8f6a1241937aebdad61 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 5 Aug 2016 23:35:56 +0200 Subject: [PATCH 39/92] SQLTableBuilder: tests for unicode default strings --- Tests/Private/SQLExpressionLiteralTests.swift | 8 +-- .../DatabaseValueConversionTests.swift | 62 +++++++++---------- .../StatementColumnConvertibleTests.swift | 54 ++++++++-------- .../SQLTableBuilderTests.swift | 5 +- 4 files changed, 65 insertions(+), 64 deletions(-) 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 fe671820d..8cea9eadc 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(NSData.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éı👨👨🏿🇫🇷🇨🇮".dataUsingEncoding(NSUTF8StringEncoding)]) + try db.execute("INSERT INTO `values` (textAffinity) VALUES (?)", arguments: ["'fooéı👨👨🏿🇫🇷🇨🇮'".dataUsingEncoding(NSUTF8StringEncoding)]) 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(NSData.fromDatabaseValue(dbv), "fooéı👨👨🏿🇫🇷🇨🇮".dataUsingEncoding(NSUTF8StringEncoding)) + XCTAssertEqual(NSData.fromDatabaseValue(dbv), "'fooéı👨👨🏿🇫🇷🇨🇮'".dataUsingEncoding(NSUTF8StringEncoding)) - XCTAssertEqual((dbv.value() as NSData?), "fooéı👨👨🏿🇫🇷🇨🇮".dataUsingEncoding(NSUTF8StringEncoding)) - XCTAssertTrue((dbv.value() as NSData).isEqualToData("fooéı👨👨🏿🇫🇷🇨🇮".dataUsingEncoding(NSUTF8StringEncoding)!)) + XCTAssertEqual((dbv.value() as NSData?), "'fooéı👨👨🏿🇫🇷🇨🇮'".dataUsingEncoding(NSUTF8StringEncoding)) + XCTAssertTrue((dbv.value() as NSData).isEqualToData("'fooéı👨👨🏿🇫🇷🇨🇮'".dataUsingEncoding(NSUTF8StringEncoding)!)) 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(NSData.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éı👨👨🏿🇫🇷🇨🇮".dataUsingEncoding(NSUTF8StringEncoding)]) + try db.execute("INSERT INTO `values` (realAffinity) VALUES (?)", arguments: ["'fooéı👨👨🏿🇫🇷🇨🇮'".dataUsingEncoding(NSUTF8StringEncoding)]) 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(NSData.fromDatabaseValue(dbv), "fooéı👨👨🏿🇫🇷🇨🇮".dataUsingEncoding(NSUTF8StringEncoding)) + XCTAssertEqual(NSData.fromDatabaseValue(dbv), "'fooéı👨👨🏿🇫🇷🇨🇮'".dataUsingEncoding(NSUTF8StringEncoding)) - XCTAssertEqual((dbv.value() as NSData?), "fooéı👨👨🏿🇫🇷🇨🇮".dataUsingEncoding(NSUTF8StringEncoding)) - XCTAssertTrue((dbv.value() as NSData).isEqualToData("fooéı👨👨🏿🇫🇷🇨🇮".dataUsingEncoding(NSUTF8StringEncoding)!)) + XCTAssertEqual((dbv.value() as NSData?), "'fooéı👨👨🏿🇫🇷🇨🇮'".dataUsingEncoding(NSUTF8StringEncoding)) + XCTAssertTrue((dbv.value() as NSData).isEqualToData("'fooéı👨👨🏿🇫🇷🇨🇮'".dataUsingEncoding(NSUTF8StringEncoding)!)) 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éı👨👨🏿🇫🇷🇨🇮".dataUsingEncoding(NSUTF8StringEncoding)]) + try db.execute("INSERT INTO `values` (noneAffinity) VALUES (?)", arguments: ["'fooéı👨👨🏿🇫🇷🇨🇮'".dataUsingEncoding(NSUTF8StringEncoding)]) 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(NSData.fromDatabaseValue(dbv), "fooéı👨👨🏿🇫🇷🇨🇮".dataUsingEncoding(NSUTF8StringEncoding)) + XCTAssertEqual(NSData.fromDatabaseValue(dbv), "'fooéı👨👨🏿🇫🇷🇨🇮'".dataUsingEncoding(NSUTF8StringEncoding)) - XCTAssertEqual((dbv.value() as NSData?), "fooéı👨👨🏿🇫🇷🇨🇮".dataUsingEncoding(NSUTF8StringEncoding)) - XCTAssertTrue((dbv.value() as NSData).isEqualToData("fooéı👨👨🏿🇫🇷🇨🇮".dataUsingEncoding(NSUTF8StringEncoding)!)) + XCTAssertEqual((dbv.value() as NSData?), "'fooéı👨👨🏿🇫🇷🇨🇮'".dataUsingEncoding(NSUTF8StringEncoding)) + XCTAssertTrue((dbv.value() as NSData).isEqualToData("'fooéı👨👨🏿🇫🇷🇨🇮'".dataUsingEncoding(NSUTF8StringEncoding)!)) 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(NSData.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éı👨👨🏿🇫🇷🇨🇮".dataUsingEncoding(NSUTF8StringEncoding)]) + try db.execute("INSERT INTO `values` (\(columnName)) VALUES (?)", arguments: ["'fooéı👨👨🏿🇫🇷🇨🇮'".dataUsingEncoding(NSUTF8StringEncoding)]) 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(NSData.fromDatabaseValue(dbv), "fooéı👨👨🏿🇫🇷🇨🇮".dataUsingEncoding(NSUTF8StringEncoding)) + XCTAssertEqual(NSData.fromDatabaseValue(dbv), "'fooéı👨👨🏿🇫🇷🇨🇮'".dataUsingEncoding(NSUTF8StringEncoding)) - XCTAssertEqual((dbv.value() as NSData?), "fooéı👨👨🏿🇫🇷🇨🇮".dataUsingEncoding(NSUTF8StringEncoding)) - XCTAssertTrue((dbv.value() as NSData).isEqualToData("fooéı👨👨🏿🇫🇷🇨🇮".dataUsingEncoding(NSUTF8StringEncoding)!)) + XCTAssertEqual((dbv.value() as NSData?), "'fooéı👨👨🏿🇫🇷🇨🇮'".dataUsingEncoding(NSUTF8StringEncoding)) + XCTAssertTrue((dbv.value() as NSData).isEqualToData("'fooéı👨👨🏿🇫🇷🇨🇮'".dataUsingEncoding(NSUTF8StringEncoding)!)) return .Rollback } diff --git a/Tests/Public/Core/StatementColumnConvertible/StatementColumnConvertibleTests.swift b/Tests/Public/Core/StatementColumnConvertible/StatementColumnConvertibleTests.swift index b87245bab..30dac2f4f 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éı👨👨🏿🇫🇷🇨🇮'") } - // NSData extraction: precondition failed: could not convert "fooéı👨👨🏿🇫🇷🇨🇮" to NSData + // NSData extraction: precondition failed: could not convert "'fooéı👨👨🏿🇫🇷🇨🇮'" to NSData // for row in Row.fetch(db, "SELECT textAffinity FROM `values`") { // XCTAssertTrue((row.value(atIndex: 0) as NSData?) == 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éı👨👨🏿🇫🇷🇨🇮".dataUsingEncoding(NSUTF8StringEncoding)]) + try db.execute("INSERT INTO `values` (textAffinity) VALUES (?)", arguments: ["'fooéı👨👨🏿🇫🇷🇨🇮'".dataUsingEncoding(NSUTF8StringEncoding)]) // 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 NSData?), "fooéı👨👨🏿🇫🇷🇨🇮".dataUsingEncoding(NSUTF8StringEncoding)) + XCTAssertEqual((row.value(atIndex: 0) as NSData?), "'fooéı👨👨🏿🇫🇷🇨🇮'".dataUsingEncoding(NSUTF8StringEncoding)) } 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éı👨👨🏿🇫🇷🇨🇮'") } - // NSData extraction: precondition failed: could not convert "fooéı👨👨🏿🇫🇷🇨🇮" to NSData + // NSData extraction: precondition failed: could not convert "'fooéı👨👨🏿🇫🇷🇨🇮'" to NSData // for row in Row.fetch(db, "SELECT realAffinity FROM `values`") { // XCTAssertTrue((row.value(atIndex: 0) as NSData?) == 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éı👨👨🏿🇫🇷🇨🇮".dataUsingEncoding(NSUTF8StringEncoding)]) + try db.execute("INSERT INTO `values` (realAffinity) VALUES (?)", arguments: ["'fooéı👨👨🏿🇫🇷🇨🇮'".dataUsingEncoding(NSUTF8StringEncoding)]) // 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 NSData?), "fooéı👨👨🏿🇫🇷🇨🇮".dataUsingEncoding(NSUTF8StringEncoding)) + XCTAssertEqual((row.value(atIndex: 0) as NSData?), "'fooéı👨👨🏿🇫🇷🇨🇮'".dataUsingEncoding(NSUTF8StringEncoding)) } 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éı👨👨🏿🇫🇷🇨🇮".dataUsingEncoding(NSUTF8StringEncoding)]) + try db.execute("INSERT INTO `values` (noneAffinity) VALUES (?)", arguments: ["'fooéı👨👨🏿🇫🇷🇨🇮'".dataUsingEncoding(NSUTF8StringEncoding)]) // 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 NSData?), "fooéı👨👨🏿🇫🇷🇨🇮".dataUsingEncoding(NSUTF8StringEncoding)) + XCTAssertEqual((row.value(atIndex: 0) as NSData?), "'fooéı👨👨🏿🇫🇷🇨🇮'".dataUsingEncoding(NSUTF8StringEncoding)) } 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éı👨👨🏿🇫🇷🇨🇮'") } - // NSData extraction: precondition failed: could not convert "fooéı👨👨🏿🇫🇷🇨🇮" to NSData + // NSData extraction: precondition failed: could not convert "'fooéı👨👨🏿🇫🇷🇨🇮'" to NSData // for row in Row.fetch(db, "SELECT \(columnName) FROM `values`") { // XCTAssertTrue((row.value(atIndex: 0) as NSData?) == 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éı👨👨🏿🇫🇷🇨🇮".dataUsingEncoding(NSUTF8StringEncoding)]) + try db.execute("INSERT INTO `values` (\(columnName)) VALUES (?)", arguments: ["'fooéı👨👨🏿🇫🇷🇨🇮'".dataUsingEncoding(NSUTF8StringEncoding)]) // 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 NSData?), "fooéı👨👨🏿🇫🇷🇨🇮".dataUsingEncoding(NSUTF8StringEncoding)) + XCTAssertEqual((row.value(atIndex: 0) as NSData?), "'fooéı👨👨🏿🇫🇷🇨🇮'".dataUsingEncoding(NSUTF8StringEncoding)) } return .Rollback } diff --git a/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift b/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift index a51e6fdad..2fbf80539 100644 --- a/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift +++ b/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift @@ -150,7 +150,7 @@ class SQLTableBuilderTests: GRDBTestCase { 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("c", .Integer).defaults("'fooéı👨👨🏿🇫🇷🇨🇮'") t.column("d", .Integer).defaults("foo".dataUsingEncoding(NSUTF8StringEncoding)!) t.column("e", .Integer).defaults(sql: "NULL") } @@ -158,7 +158,7 @@ class SQLTableBuilderTests: GRDBTestCase { "CREATE TABLE \"test\" (" + "\"a\" INTEGER DEFAULT 1, " + "\"b\" INTEGER DEFAULT 1.0, " + - "\"c\" INTEGER DEFAULT 'foo', " + + "\"c\" INTEGER DEFAULT '''fooéı👨👨🏿🇫🇷🇨🇮''', " + "\"d\" INTEGER DEFAULT x'666f6f', " + "\"e\" INTEGER DEFAULT NULL" + ")") @@ -166,6 +166,7 @@ class SQLTableBuilderTests: GRDBTestCase { // 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éı👨👨🏿🇫🇷🇨🇮'") } } } From 8d2984c572748f6c075b29060b22f4aa39d14a46 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 5 Aug 2016 23:36:54 +0200 Subject: [PATCH 40/92] SQLTableBuilder documentation --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 0c56eeccd..5fd342ef5 100644 --- a/README.md +++ b/README.md @@ -2190,8 +2190,8 @@ Define not null and unique columns, and set default values: // uuid TEXT UNIQUE ON CONFLICT REPLACE, t.column("uuid", .Text).unique(onConflict: .Replace) - // flag BOOLEAN NOT NULL DEFAULT 0, - t.column("flag", .Boolean).notNull().default(false) + // name TEXT NOT NULL DEFAULT 'Anonymous', + t.column("name", .Text).notNull().default("Anonymous") ``` 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). From cc624f9ed20e7e205bde914507496c99556c731e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 5 Aug 2016 23:39:28 +0200 Subject: [PATCH 41/92] SQLTableBuilder documentation --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 5fd342ef5..83f150e69 100644 --- a/README.md +++ b/README.md @@ -2172,7 +2172,7 @@ The `create(table:)` method covers nearly all [CREATE TABLE](https://www.sqlite. try db.create(table: "demo", 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): +**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, @@ -2181,7 +2181,7 @@ Add regular columns with their name and type (text, integer, double, numeric, bo t.column("creationDate", .Datetime) ``` -Define not null and unique columns, and set default values: +Define **not null** and **unique** columns, and set **default** values: ```swift // email TEXT NOT NULL UNIQUE, @@ -2194,7 +2194,7 @@ Define not null and unique columns, and set default values: t.column("name", .Text).notNull().default("Anonymous") ``` -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). +**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 // age INTEGER CHECK (age > 0) @@ -2203,7 +2203,7 @@ Perform integrity checks on individual columns, and SQLite will only let conform t.column("name", .Text).check { length($0) > 0 } ``` -Use individual columns as primary or foreign keys. When not specified, the referenced column is the primary key of the referenced table: +Use an individual columns as a **primary** or **foreign key**. When not specified, the referenced column is the primary key of the referenced table: ```swift // id INTEGER PRIMARY KEY, @@ -2213,7 +2213,7 @@ Use individual columns as primary or foreign keys. When not specified, the refer t.column("countryCode", .Text).references("countries", onDelete: .Cascade) ``` -Other constraints can involve several columns: +Other **table constraints** can involve several columns. Integrity checks accept any [expression](#expressions), or a raw SQL snippet: ```swift // PRIMARY KEY (a, b), From 988ac8e60b6bb186f1cbc1a8b58b8a3992542933 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 5 Aug 2016 23:45:27 +0200 Subject: [PATCH 42/92] SQLTableBuilder polish --- GRDB/QueryInterface/SQLTableBuilder.swift | 2 +- README.md | 2 +- Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/GRDB/QueryInterface/SQLTableBuilder.swift b/GRDB/QueryInterface/SQLTableBuilder.swift index 829c994f0..140757e48 100644 --- a/GRDB/QueryInterface/SQLTableBuilder.swift +++ b/GRDB/QueryInterface/SQLTableBuilder.swift @@ -79,7 +79,7 @@ public final class SQLTableBuilder { } // TODO: doc - public func foreignKey(columns: [String], to table: String, columns destinationColumns: [String]? = nil, onDelete deleteAction: SQLForeignKeyAction? = nil, onUpdate updateAction: SQLForeignKeyAction? = nil, deferred: Bool = false) { + 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)) } diff --git a/README.md b/README.md index 83f150e69..cc9f1b289 100644 --- a/README.md +++ b/README.md @@ -2223,7 +2223,7 @@ Other **table constraints** can involve several columns. Integrity checks accept t.uniqueKey(["a", "b"], onConfict: .Replace) // FOREIGN KEY (c, d) REFERENCES parents(a, b), - t.foreignKey(["c", "d"], to: "parent", columns: ["a", "b"]) + t.foreignKey(["c", "d"], references: "parent", columns: ["a", "b"]) // CHECK (a + b < 10), t.check(SQLColumn("a") + SQLColumn("b") < 10) diff --git a/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift b/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift index 2fbf80539..7f00ea944 100644 --- a/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift +++ b/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift @@ -288,8 +288,8 @@ class SQLTableBuilderTests: GRDBTestCase { t.column("b", .Text) } try db.create(table: "child") { t in - t.foreignKey(["c", "d"], to: "parent", onDelete: .Cascade, onUpdate: .Cascade) - t.foreignKey(["d", "e"], to: "parent", columns: ["b", "a"], onDelete: .Restrict, deferred: true) + 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) From 81e1d86047a8a59030b7d41fc1b77c9f2c5d1368 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 5 Aug 2016 23:51:01 +0200 Subject: [PATCH 43/92] SQLTableBuilder documentation --- README.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index cc9f1b289..3ef3fdff1 100644 --- a/README.md +++ b/README.md @@ -2141,7 +2141,7 @@ So don't miss the [SQL API](#sqlite-api). Once granted with a [database connection](#database-connections), you can use the query interface to setup your database schema: - [Create Tables](#create-tables) -- [Modify Tables](#alter-tables) +- [Modify Tables](#modify-tables) - [Drop Tables](#drop-tables) - [Create Indexes](#create-indexes) @@ -2273,8 +2273,7 @@ try db.create(index: "byEmail", on: "users", columns: ["email"], unique: true) **The query interface requests** let you fetch values from the database: ```swift -let count = Wine.filter(color == Color.Red).fetchCount(db) -let wines = Wine.filter(origin == "Burgundy").order(price).fetchAll(db) +let persons = Person.filter(email != nil).order(name).fetchAll(db) ``` All requests start from **a type** that adopts the `TableMapping` protocol, such as a `Record` subclass (see [Records](#records)): From f6260087c3c51631a0271ccfc877fe01aec02f5c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 5 Aug 2016 23:51:58 +0200 Subject: [PATCH 44/92] SQLTableBuilder documentation --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 3ef3fdff1..80fa66b20 100644 --- a/README.md +++ b/README.md @@ -2273,7 +2273,9 @@ try db.create(index: "byEmail", on: "users", columns: ["email"], unique: true) **The query interface requests** let you fetch values from the database: ```swift -let persons = Person.filter(email != nil).order(name).fetchAll(db) +let request = Person.filter(email != nil).order(name) +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)): From a00ca647f52e7b4851a8be8a5ce929113f305005 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 5 Aug 2016 23:53:05 +0200 Subject: [PATCH 45/92] SQLTableBuilder documentation --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 80fa66b20..e7d8592cf 100644 --- a/README.md +++ b/README.md @@ -2273,7 +2273,7 @@ try db.create(index: "byEmail", on: "users", columns: ["email"], unique: true) **The query interface requests** let you fetch values from the database: ```swift -let request = Person.filter(email != nil).order(name) +let request = Person.filter(emailColumn != nil).order(nameColumn) let persons = request.fetchAll(db) // [Person] let count = request.fetchCount(db) // Int ``` From ea30075602de9cd33f5d0a1525ade6c8471b9bae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 6 Aug 2016 00:10:15 +0200 Subject: [PATCH 46/92] SQLTableBuilder documentation --- README.md | 113 ++++++++++++++++++++++++++---------------------------- 1 file changed, 55 insertions(+), 58 deletions(-) diff --git a/README.md b/README.md index e7d8592cf..6cf41fd1b 100644 --- a/README.md +++ b/README.md @@ -2308,41 +2308,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) @@ -2351,7 +2351,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) @@ -2361,59 +2361,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) ``` - `reverse()` 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).reverse() ``` 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().reverse() ``` - `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 ``` @@ -2422,7 +2422,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"]) @@ -2442,19 +2442,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) ``` @@ -2466,7 +2466,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")) ``` @@ -2477,7 +2477,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) ``` @@ -2486,22 +2486,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)) ``` @@ -2510,8 +2510,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)) ``` @@ -2521,8 +2521,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) ``` @@ -2535,13 +2535,13 @@ Feed [requests](#requests) with SQL expressions built from your Swift code: Those are based on the `abs`, `average`, `count`, `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)) ``` @@ -2550,10 +2550,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) ``` @@ -2576,7 +2576,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)) ``` @@ -2651,16 +2651,16 @@ Citizenship.fetchOne(db, key: ["personID": 1, "countryISOCode": "FR"]) // Citize **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) ``` @@ -2688,24 +2688,21 @@ Migrations run in order, once and only once. When a user upgrades your applicati var migrator = DatabaseMigrator() // v1.0 database -migrator.registerMigration("createTables") { db in - try db.execute( - "CREATE TABLE persons (...); " + - "CREATE TABLE books (...)") +migrator.registerMigration("v1") { db in + try db.create(table: "persons") { t in ... } + try db.create(table: "books") { t in ... } } // v2.0 database -migrator.registerMigration("AddBirthDateToPersons") { db in - try db.execute( - "ALTER TABLE persons ADD COLUMN birthDate DATE") +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") +// migrator.registerMigration("v3") { db in +// ... // } try migrator.migrate(dbQueue) // or migrator.migrate(dbPool) From 91d68802188626b11f7b505597c3571fb0f42a37 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 6 Aug 2016 00:13:56 +0200 Subject: [PATCH 47/92] SQLTableBuilder documentation --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 6cf41fd1b..e6e5c6d06 100644 --- a/README.md +++ b/README.md @@ -2241,9 +2241,9 @@ SQLite let you rename tables, and add columns to existing tables: // ALTER TABLE referers RENAME TO referrers try db.rename(table: "referers", to: "referrers") -// ALTER TABLE persons ADD COLUMN website TEXT +// ALTER TABLE persons ADD COLUMN url TEXT try db.alter(table: "persons") { t in - t.add(column: "website", .Text) + t.add(column: "url", .Text) } ``` From d918f0fb033c8cc29457c122cd3a56da0fc3223f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 6 Aug 2016 07:08:59 +0200 Subject: [PATCH 48/92] SQLTableBuilder: limit WITHOUT ROWID availability --- GRDB/QueryInterface/SQLTableBuilder.swift | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/GRDB/QueryInterface/SQLTableBuilder.swift b/GRDB/QueryInterface/SQLTableBuilder.swift index 140757e48..f01e2374e 100644 --- a/GRDB/QueryInterface/SQLTableBuilder.swift +++ b/GRDB/QueryInterface/SQLTableBuilder.swift @@ -1,12 +1,22 @@ extension Database { // TODO: doc - // TODO: Don't expose withoutRowID if not available - public func create(table name: String, temporary: Bool = false, ifNotExists: Bool = false, withoutRowID: Bool = false, body: (SQLTableBuilder) -> Void) throws { + @available(iOS 8.2, OSX 10.10, *) + public func create(table name: String, temporary: Bool = false, ifNotExists: Bool = false, withoutRowID: Bool, body: (SQLTableBuilder) -> 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 builder = SQLTableBuilder(name: name, temporary: temporary, ifNotExists: ifNotExists, withoutRowID: withoutRowID) body(builder) let sql = try builder.sql(self) try execute(sql) } + + // TODO: doc + public func create(table name: String, temporary: Bool = false, ifNotExists: Bool = false, body: (SQLTableBuilder) -> Void) throws { + let builder = SQLTableBuilder(name: name, temporary: temporary, ifNotExists: ifNotExists, withoutRowID: false) + body(builder) + let sql = try builder.sql(self) + try execute(sql) + } // TODO: doc public func rename(table name: String, to newName: String) throws { From b8c1c1ef1eb578a3256b79e1c734416a0cc484b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 6 Aug 2016 09:51:35 +0200 Subject: [PATCH 49/92] Length function documentation --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index e6e5c6d06..6463c881c 100644 --- a/README.md +++ b/README.md @@ -2530,9 +2530,9 @@ 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 From 6e60ff2062eb1f1875ff5103b472a4ca222d221b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 6 Aug 2016 09:53:34 +0200 Subject: [PATCH 50/92] SQLTableBuilder documentation --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 6463c881c..d39c6c8b3 100644 --- a/README.md +++ b/README.md @@ -2159,7 +2159,7 @@ Once granted with a [database connection](#database-connections), you can use th 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("favorite", .Boolean).notNull().defaults(false) t.column("longitude", .Double).notNull() t.column("latitude", .Double).notNull() } @@ -2191,7 +2191,7 @@ Define **not null** and **unique** columns, and set **default** values: t.column("uuid", .Text).unique(onConflict: .Replace) // name TEXT NOT NULL DEFAULT 'Anonymous', - t.column("name", .Text).notNull().default("Anonymous") + t.column("name", .Text).notNull().defaults("Anonymous") ``` **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). From d78784e45e1f9040ad96c879e37e9e27f53fc038 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 6 Aug 2016 09:54:30 +0200 Subject: [PATCH 51/92] SQLTableBuilder documentation --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d39c6c8b3..6ba97105f 100644 --- a/README.md +++ b/README.md @@ -2203,7 +2203,7 @@ Define **not null** and **unique** columns, and set **default** values: t.column("name", .Text).check { length($0) > 0 } ``` -Use an individual columns as a **primary** or **foreign key**. When not specified, the referenced column is the primary key of the referenced table: +Use an individual column as **primary** or **foreign key**. When not specified, the referenced column is the primary key of the referenced table: ```swift // id INTEGER PRIMARY KEY, From 4745eb190afcd1fcdee233e160bc67be7d12b422 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 6 Aug 2016 10:00:13 +0200 Subject: [PATCH 52/92] Query Interface Request documentation --- README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/README.md b/README.md index 6ba97105f..28c704dcf 100644 --- a/README.md +++ b/README.md @@ -2645,6 +2645,12 @@ 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 From e1f3adafb7d296d8c706317b2fbf283006fa0a0f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 6 Aug 2016 10:02:24 +0200 Subject: [PATCH 53/92] Typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 28c704dcf..ca23a4834 100644 --- a/README.md +++ b/README.md @@ -40,7 +40,7 @@ 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). ## Usage From c936000d6215e9b5cd18ea9bebcdcc12ab270c6d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 6 Aug 2016 10:08:00 +0200 Subject: [PATCH 54/92] SQLTableBuilder documentation --- README.md | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index ca23a4834..5e8708fae 100644 --- a/README.md +++ b/README.md @@ -2181,19 +2181,29 @@ try db.create(table: "demo", temporary: true, ifNotExists: true) { t in t.column("creationDate", .Datetime) ``` -Define **not null** and **unique** columns, and set **default** values: +Define **not null** columns, and set **default** values: ```swift - // email TEXT NOT NULL UNIQUE, - t.column("email", .Text).notNull().unique() - - // uuid TEXT UNIQUE ON CONFLICT REPLACE, - t.column("uuid", .Text).unique(onConflict: .Replace) + // 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 not specified, the referenced column is the primary key of the referenced table: + +```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 @@ -2203,16 +2213,6 @@ Define **not null** and **unique** columns, and set **default** values: t.column("name", .Text).check { length($0) > 0 } ``` -Use an individual column as **primary** or **foreign key**. When not specified, the referenced column is the primary key of the referenced table: - -```swift - // id INTEGER PRIMARY KEY, - t.column("id", .Integer).primaryKey() - - // countryCode TEXT REFERENCES countries(code) ON DELETE CASCADE, - t.column("countryCode", .Text).references("countries", onDelete: .Cascade) -``` - Other **table constraints** can involve several columns. Integrity checks accept any [expression](#expressions), or a raw SQL snippet: ```swift From a25b914085ecd87f4998b7f135cfadc549ccd215 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 6 Aug 2016 10:11:56 +0200 Subject: [PATCH 55/92] SQLTableBuilder documentation --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5e8708fae..afbc147ac 100644 --- a/README.md +++ b/README.md @@ -2138,7 +2138,7 @@ So don't miss the [SQL API](#sqlite-api). ### Database Schema -Once granted with a [database connection](#database-connections), you can use the query interface to setup your database schema: +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) From 980b3234d536c1b2ef9d9d74673ea353da4f6496 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 6 Aug 2016 10:14:04 +0200 Subject: [PATCH 56/92] SQLTableBuilder documentation --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index afbc147ac..231bcbb34 100644 --- a/README.md +++ b/README.md @@ -2213,7 +2213,7 @@ Use an individual column as **primary**, **unique**, or **foreign key**. When no t.column("name", .Text).check { length($0) > 0 } ``` -Other **table constraints** can involve several columns. Integrity checks accept any [expression](#expressions), or a raw SQL snippet: +Other **table constraints** can involve several columns: ```swift // PRIMARY KEY (a, b), From ebfcc2e23a7c7fa75f949e8b16dfcf83b90c8678 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 6 Aug 2016 10:16:43 +0200 Subject: [PATCH 57/92] SQLTableBuilder documentation --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 231bcbb34..35d1f2c4b 100644 --- a/README.md +++ b/README.md @@ -2223,7 +2223,7 @@ Other **table constraints** can involve several columns: t.uniqueKey(["a", "b"], onConfict: .Replace) // FOREIGN KEY (c, d) REFERENCES parents(a, b), - t.foreignKey(["c", "d"], references: "parent", columns: ["a", "b"]) + t.foreignKey(["c", "d"], references: "parent") // CHECK (a + b < 10), t.check(SQLColumn("a") + SQLColumn("b") < 10) From 57b51cec9cb9bebaaafdac908722f0d0e909ffea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 6 Aug 2016 11:11:06 +0200 Subject: [PATCH 58/92] TODO.md --- TODO.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/TODO.md b/TODO.md index 4e7c56952..a781c49de 100644 --- a/TODO.md +++ b/TODO.md @@ -1,4 +1,4 @@ -- [ ] Document Statement.unsafeSetArguments +- [ ] Rename PrimaryKey to PrimaryKeyInfo - [ ] 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). - [ ] GRDBCipher: remove limitations on iOS or OS X versions - [ ] FetchedRecordsController: take inspiration from https://github.com/jflinter/Dwifft From 926b9b1d1a8d66ab68b0703e387a52418ba9ab6d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 6 Aug 2016 11:11:38 +0200 Subject: [PATCH 59/92] Error handling documentation --- README.md | 85 +++++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 76 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 35d1f2c4b..5e625adc9 100644 --- a/README.md +++ b/README.md @@ -3314,9 +3314,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 { @@ -3341,31 +3346,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 +do { + try person.update(db) +} catch PersistenceError.NotFound { + // There was nothing to update +} +``` + + +### Fatal Errors + +**Fatal errors notify that the program, or the database, has to be changed.** + +- [Programming Errors](#programming-errors) +- [False Assumptions](#false-assumptions) +- [Misuses](#misuses) + + +#### Programming Errors + +For example, 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: -Row.fetchAll(db, "SELECT * FROM books") +``` +**Solution**: fix the SQL query. + +```swift +Row.fetchAll(db, "SELECT * FROM books") +``` + +If you have to run untrusted SQL queries, jump to [untrusted databases](#how-to-deal-with-untrusted-inputs). + + +#### False Assumptions + +For example, 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, or load an optional: -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") +``` + +Second example: 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 jump to [untrusted databases](#how-to-deal-with-untrusted-inputs). + + +#### Misuses + +For example, did you know that 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. ``` -**Fatal errors can be avoided**. For example, let's consider the code below: +Well, now you know. 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 From c2e32c0bf2d8ebda70f12e25c63b7c935f48e6af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 6 Aug 2016 11:13:27 +0200 Subject: [PATCH 60/92] Error handling documentation --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 5e625adc9..596694ab6 100644 --- a/README.md +++ b/README.md @@ -3380,7 +3380,7 @@ For example, the code contains a wrong SQL query: Row.fetchAll(db, "SELECT * FROM boooks") ``` -**Solution**: fix the SQL query. +Solution: fix the SQL query. ```swift Row.fetchAll(db, "SELECT * FROM books") @@ -3398,7 +3398,7 @@ For example, the code asks for a non-optional values, when the database contains let name: String = row.value(named: "name") ``` -**Solution**: fix the contents of the database, use [NOT NULL constraints](#create-tables), or load an optional: +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") @@ -3411,12 +3411,12 @@ Second example: the code asks for an NSDate, when the database contains garbage: let date: NSDate? = row.value(named: "date") ``` -**Solution**: fix the contents of the database, or jump to [untrusted databases](#how-to-deal-with-untrusted-inputs). +Solution: fix the contents of the database, or jump to [untrusted databases](#how-to-deal-with-untrusted-inputs). #### Misuses -For example, did you know that database connections are not reentrant? +For example, database connections are not reentrant: ```swift // fatal error: Database methods are not reentrant. @@ -3427,7 +3427,7 @@ dbQueue.inDatabase { db in } ``` -Well, now you know. Avoid reentrancy, and instead pass a database connection along. +Solution: Avoid reentrancy, and instead pass a database connection along. ### How to Deal with Untrusted Inputs From b45d6945b1ae57d04dd2debefc195fa8753b36f5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 6 Aug 2016 11:15:41 +0200 Subject: [PATCH 61/92] Error handling documentation --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 596694ab6..fc50ad9f4 100644 --- a/README.md +++ b/README.md @@ -3386,7 +3386,7 @@ Solution: fix the SQL query. Row.fetchAll(db, "SELECT * FROM books") ``` -If you have to run untrusted SQL queries, jump to [untrusted databases](#how-to-deal-with-untrusted-inputs). +If you do have to run untrusted SQL queries, jump to [untrusted databases](#how-to-deal-with-untrusted-inputs). #### False Assumptions @@ -3427,7 +3427,7 @@ dbQueue.inDatabase { db in } ``` -Solution: Avoid reentrancy, and instead pass a database connection along. +Solution: avoid reentrancy, and instead pass a database connection along. ### How to Deal with Untrusted Inputs From 0e83f0b2177bb2e6cb6d641a4f60f8714de43248 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 6 Aug 2016 12:05:45 +0200 Subject: [PATCH 62/92] Error handling documentation --- README.md | 105 ++++++++++++++++++++++++------------------------------ 1 file changed, 47 insertions(+), 58 deletions(-) diff --git a/README.md b/README.md index fc50ad9f4..908927998 100644 --- a/README.md +++ b/README.md @@ -3364,70 +3364,59 @@ do { **Fatal errors notify that the program, or the database, has to be changed.** -- [Programming Errors](#programming-errors) -- [False Assumptions](#false-assumptions) -- [Misuses](#misuses) +They uncover programmer errors, false assumptions, and prevent misuses. +1. For example, 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). -#### Programming Errors +2. 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") + ``` -For example, the code contains a wrong SQL query: +3. 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 jump to [untrusted databases](#how-to-deal-with-untrusted-inputs). -```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). - - -#### False Assumptions - -For example, 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") -``` - -Second example: 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 jump to [untrusted databases](#how-to-deal-with-untrusted-inputs). - - -#### Misuses - -For example, database connections are not reentrant: - -```swift -// fatal error: Database methods are not reentrant. -dbQueue.inDatabase { db in +4. 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. + ``` + + Solution: avoid reentrancy, and instead pass a database connection along. ### How to Deal with Untrusted Inputs From 6554a027d760b6b8a53e48c28f78f936253f2a3d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 6 Aug 2016 12:07:12 +0200 Subject: [PATCH 63/92] Error handling documentation --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 908927998..6f6adc52a 100644 --- a/README.md +++ b/README.md @@ -3364,9 +3364,9 @@ do { **Fatal errors notify that the program, or the database, has to be changed.** -They uncover programmer errors, false assumptions, and prevent misuses. +They uncover programmer errors, false assumptions, and prevent misuses. Here are a few examples: -1. For example, the code contains a wrong SQL query: +- The code contains a wrong SQL query: ```swift // fatal error: @@ -3383,7 +3383,7 @@ They uncover programmer errors, false assumptions, and prevent misuses. If you do have to run untrusted SQL queries, jump to [untrusted databases](#how-to-deal-with-untrusted-inputs). -2. The code asks for a non-optional values, when the database contains NULL: +- The code asks for a non-optional values, when the database contains NULL: ```swift // fatal error: could not convert NULL to String. @@ -3396,7 +3396,7 @@ They uncover programmer errors, false assumptions, and prevent misuses. let name: String? = row.value(named: "name") ``` -3. The code asks for an NSDate, when the database contains garbage: +- The code asks for an NSDate, when the database contains garbage: ```swift // fatal error: could not convert "Mom's birthday" to NSDate. @@ -3405,7 +3405,7 @@ They uncover programmer errors, false assumptions, and prevent misuses. Solution: fix the contents of the database, or jump to [untrusted databases](#how-to-deal-with-untrusted-inputs). -4. Database connections are not reentrant: +- Database connections are not reentrant: ```swift // fatal error: Database methods are not reentrant. From eb18f474c8511f6a8ac6bb1363a8ed11a536ec87 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 6 Aug 2016 12:12:04 +0200 Subject: [PATCH 64/92] Error handling documentation --- README.md | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 6f6adc52a..e7ee73d5d 100644 --- a/README.md +++ b/README.md @@ -3403,7 +3403,18 @@ They uncover programmer errors, false assumptions, and prevent misuses. Here are let date: NSDate? = row.value(named: "date") ``` - Solution: fix the contents of the database, or jump to [untrusted databases](#how-to-deal-with-untrusted-inputs). + 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: From cfa091dbc417f3322793f4e4530016d77b9000e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 6 Aug 2016 13:40:04 +0200 Subject: [PATCH 65/92] SQLTableBuilder documentation + drop support for explicit primary key ordering until someone asks for it. --- GRDB/QueryInterface/SQLTableBuilder.swift | 629 +++++++++++++----- .../SQLTableBuilderTests.swift | 4 +- 2 files changed, 465 insertions(+), 168 deletions(-) diff --git a/GRDB/QueryInterface/SQLTableBuilder.swift b/GRDB/QueryInterface/SQLTableBuilder.swift index f01e2374e..d794cb55a 100644 --- a/GRDB/QueryInterface/SQLTableBuilder.swift +++ b/GRDB/QueryInterface/SQLTableBuilder.swift @@ -1,5 +1,24 @@ extension Database { - // TODO: doc + /// 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: (SQLTableBuilder) -> Void) throws { // WITHOUT ROWID was added in SQLite 3.8.2 http://www.sqlite.org/changes.html#version_3_8_2 @@ -10,7 +29,24 @@ extension Database { try execute(sql) } - // TODO: doc + /// 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: (SQLTableBuilder) -> Void) throws { let builder = SQLTableBuilder(name: name, temporary: temporary, ifNotExists: ifNotExists, withoutRowID: false) body(builder) @@ -18,12 +54,27 @@ extension Database { try execute(sql) } - // TODO: doc + /// 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)") } - // TODO: doc + /// 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: (SQLTableAlterationBuilder) -> Void) throws { let builder = SQLTableAlterationBuilder(name: name) body(builder) @@ -31,25 +82,61 @@ extension Database { try execute(sql) } - // TODO: doc + /// 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)") } - // TODO: doc + /// 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 builder = IndexBuilder(name: name, table: table, columns: columns, unique: unique, ifNotExists: ifNotExists, condition: condition?.sqlExpression) let sql = builder.sql() try execute(sql) } - // TODO: doc + /// 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)") } } -// TODO: doc +/// The SQLTableBuilder 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 SQLTableBuilder +/// t.column(...) +/// } +/// +/// See https://www.sqlite.org/lang_createtable.html public final class SQLTableBuilder { let name: String let temporary: Bool @@ -68,14 +155,38 @@ public final class SQLTableBuilder { self.withoutRowID = withoutRowID } - // TODO: doc + /// 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 SQLColumnBuilder that allows you to refine the + /// column definition. public func column(name: String, _ type: SQLColumnType) -> SQLColumnBuilder { let column = SQLColumnBuilder(name: name, type: type) columns.append(column) return column } - // TODO: doc + /// 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") @@ -83,169 +194,81 @@ public final class SQLTableBuilder { primaryKeyConstraint = (columns: columns, conflictResolution: conflictResolution) } - // TODO: doc + /// 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)) } - // TODO: doc + /// 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)) } - // TODO: doc + /// 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) } - // TODO: doc + /// 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 sql: String) { checkConstraints.append(_SQLExpression.Literal(sql, nil)) } -} - -// TODO: doc -public final class SQLTableAlterationBuilder { - let name: String - var addedColumns: [SQLColumnBuilder] = [] - init(name: String) { - self.name = name - } - - // TODO: doc - public func add(column name: String, _ type: SQLColumnType) -> SQLColumnBuilder { - let column = SQLColumnBuilder(name: name, type: type) - addedColumns.append(column) - return column - } -} - -// TODO: doc -public final class SQLColumnBuilder { - let name: String - let type: SQLColumnType - var primaryKey: (ordering: SQLOrdering?, conflictResolution: SQLConflictResolution?, autoincrement: Bool)? - var notNullConflictResolution: SQLConflictResolution? - var uniqueConflictResolution: SQLConflictResolution? - var checkExpression: _SQLExpression? - var defaultExpression: _SQLExpression? - var collationName: String? - var reference: (table: String, column: String?, deleteAction: SQLForeignKeyAction?, updateAction: SQLForeignKeyAction?, deferred: Bool)? - - init(name: String, type: SQLColumnType) { - self.name = name - self.type = type - } - - // TODO: doc - public func primaryKey(ordering ordering: SQLOrdering? = nil, onConflict conflictResolution: SQLConflictResolution? = nil, autoincrement: Bool = false) -> SQLColumnBuilder { - primaryKey = (ordering: ordering, conflictResolution: conflictResolution, autoincrement: autoincrement) - return self - } - - // TODO: doc - public func notNull(onConflict conflictResolution: SQLConflictResolution? = nil) -> SQLColumnBuilder { - notNullConflictResolution = conflictResolution ?? .Abort - return self - } - - // TODO: doc - public func unique(onConflict conflictResolution: SQLConflictResolution? = nil) -> SQLColumnBuilder { - uniqueConflictResolution = conflictResolution ?? .Abort - return self - } - - // TODO: doc - public func check(@noescape condition: (SQLColumn) -> _SQLExpressible) -> SQLColumnBuilder { - checkExpression = condition(SQLColumn(name)).sqlExpression - return self - } - - // TODO: doc - public func check(sql sql: String) -> SQLColumnBuilder { - checkExpression = _SQLExpression.Literal(sql, nil) - return self - } - - // TODO: doc - public func defaults(value: DatabaseValueConvertible) -> SQLColumnBuilder { - defaultExpression = value.sqlExpression - return self - } - - // TODO: doc - public func defaults(sql sql: String) -> SQLColumnBuilder { - defaultExpression = _SQLExpression.Literal(sql, nil) - return self - } - - // TODO: doc - public func collate(collation: SQLCollation) -> SQLColumnBuilder { - collationName = collation.rawValue - return self - } - - // TODO: doc - public func collate(collation: DatabaseCollation) -> SQLColumnBuilder { - collationName = collation.name - return self - } - - // TODO: doc - public func references(table: String, column: String? = nil, onDelete deleteAction: SQLForeignKeyAction? = nil, onUpdate updateAction: SQLForeignKeyAction? = nil, deferred: Bool = false) -> SQLColumnBuilder { - reference = (table: table, column: column, deleteAction: deleteAction, updateAction: updateAction, deferred: deferred) - return self - } -} - -// TODO: doc -public enum SQLOrdering : String { - case Asc = "ASC" - case Desc = "DESC" -} - -// TODO: doc -public enum SQLCollation : String { - case Binary = "BINARY" - case Nocase = "NOCASE" - case Rtrim = "RTRIM" -} - -// TODO: doc -public enum SQLConflictResolution : String { - case Rollback = "ROLLBACK" - case Abort = "ABORT" - case Fail = "FAIL" - case Ignore = "IGNORE" - case Replace = "REPLACE" -} - -// TODO: doc -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" -} - -// TODO: doc -public enum SQLForeignKeyAction : String { - case Cascade = "CASCADE" - case Restrict = "RESTRICT" - case SetNull = "SET NULL" - case SetDefault = "SET DEFAULT" -} - - -// MARK: - SQL Generation - -extension SQLTableBuilder { - func sql(db: Database) throws -> String { + private func sql(db: Database) throws -> String { var chunks: [String] = [] chunks.append("CREATE") if temporary { @@ -327,8 +350,43 @@ extension SQLTableBuilder { } } -extension SQLTableAlterationBuilder { - func sql(db: Database) throws -> String { +/// The SQLTableAlterationBuilder 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 SQLTableAlterationBuilder +/// t.add(column: ...) +/// } +/// +/// See https://www.sqlite.org/lang_altertable.html +public final class SQLTableAlterationBuilder { + let name: String + var addedColumns: [SQLColumnBuilder] = [] + + 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 SQLColumnBuilder that allows you to refine the + /// column definition. + public func add(column name: String, _ type: SQLColumnType) -> SQLColumnBuilder { + let column = SQLColumnBuilder(name: name, type: type) + addedColumns.append(column) + return column + } + + private func sql(db: Database) throws -> String { var statements: [String] = [] for column in addedColumns { @@ -345,17 +403,207 @@ extension SQLTableAlterationBuilder { } } -extension SQLColumnBuilder { - func sql(db: Database) throws -> String { +/// The SQLColumnBuilder 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(...) // SQLColumnBuilder +/// } +/// +/// try db.alter(table: "persons") { t in +/// t.add(column: ...) // SQLColumnBuilder +/// } +/// +/// See https://www.sqlite.org/lang_createtable.html and +/// https://www.sqlite.org/lang_altertable.html +public final class SQLColumnBuilder { + let name: String + let type: SQLColumnType + var primaryKey: (conflictResolution: SQLConflictResolution?, autoincrement: Bool)? + var notNullConflictResolution: SQLConflictResolution? + var uniqueConflictResolution: SQLConflictResolution? + var checkExpression: _SQLExpression? + var defaultExpression: _SQLExpression? + var collationName: String? + 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. + public func primaryKey(onConflict conflictResolution: SQLConflictResolution? = nil, autoincrement: Bool = false) -> SQLColumnBuilder { + 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. + public func notNull(onConflict conflictResolution: SQLConflictResolution? = nil) -> SQLColumnBuilder { + 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. + public func unique(onConflict conflictResolution: SQLConflictResolution? = nil) -> SQLColumnBuilder { + 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. + public func check(@noescape condition: (SQLColumn) -> _SQLExpressible) -> SQLColumnBuilder { + 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. + public func check(sql sql: String) -> SQLColumnBuilder { + checkExpression = _SQLExpression.Literal(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. + public func defaults(value: DatabaseValueConvertible) -> SQLColumnBuilder { + 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. + public func defaults(sql sql: String) -> SQLColumnBuilder { + defaultExpression = _SQLExpression.Literal(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. + public func collate(collation: SQLCollation) -> SQLColumnBuilder { + 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. + public func collate(collation: DatabaseCollation) -> SQLColumnBuilder { + 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. + public func references(table: String, column: String? = nil, onDelete deleteAction: SQLForeignKeyAction? = nil, onUpdate updateAction: SQLForeignKeyAction? = nil, deferred: Bool = false) -> SQLColumnBuilder { + 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 (ordering, conflictResolution, autoincrement) = primaryKey { + if let (conflictResolution, autoincrement) = primaryKey { chunks.append("PRIMARY KEY") - if let ordering = ordering { - chunks.append(ordering.rawValue) - } if let conflictResolution = conflictResolution { chunks.append("ON CONFLICT") chunks.append(conflictResolution.rawValue) @@ -428,7 +676,7 @@ extension SQLColumnBuilder { } } -struct IndexBuilder { +private struct IndexBuilder { let name: String let table: String let columns: [String] @@ -457,3 +705,52 @@ struct IndexBuilder { return chunks.joinWithSeparator(" ") } } + +/// 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/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift b/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift index 7f00ea944..43bbfa6d2 100644 --- a/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift +++ b/Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift @@ -47,11 +47,11 @@ class SQLTableBuilderTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inTransaction { db in try db.create(table: "test") { t in - t.column("id", .Integer).primaryKey(ordering: .Desc, onConflict: .Fail) + t.column("id", .Integer).primaryKey(onConflict: .Fail) } XCTAssertEqual(self.lastSQLQuery, "CREATE TABLE \"test\" (" + - "\"id\" INTEGER PRIMARY KEY DESC ON CONFLICT FAIL" + + "\"id\" INTEGER PRIMARY KEY ON CONFLICT FAIL" + ")") return .Rollback } From 30259c4360a433d7e93fefb5ec556b75a8bec46f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 6 Aug 2016 13:49:46 +0200 Subject: [PATCH 66/92] SQLTableBuilder polish --- GRDB/QueryInterface/SQLTableBuilder.swift | 124 +++++++++++----------- 1 file changed, 63 insertions(+), 61 deletions(-) diff --git a/GRDB/QueryInterface/SQLTableBuilder.swift b/GRDB/QueryInterface/SQLTableBuilder.swift index d794cb55a..52f0e10ab 100644 --- a/GRDB/QueryInterface/SQLTableBuilder.swift +++ b/GRDB/QueryInterface/SQLTableBuilder.swift @@ -20,12 +20,12 @@ extension Database { /// - 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: (SQLTableBuilder) -> Void) throws { + public func create(table name: String, temporary: Bool = false, ifNotExists: Bool = false, withoutRowID: Bool, body: (TableDefinition) -> Void) throws { // WITHOUT ROWID was added in SQLite 3.8.2 http://www.sqlite.org/changes.html#version_3_8_2 // It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) - let builder = SQLTableBuilder(name: name, temporary: temporary, ifNotExists: ifNotExists, withoutRowID: withoutRowID) - body(builder) - let sql = try builder.sql(self) + let definition = TableDefinition(name: name, temporary: temporary, ifNotExists: ifNotExists, withoutRowID: withoutRowID) + body(definition) + let sql = try definition.sql(self) try execute(sql) } @@ -47,10 +47,10 @@ extension Database { /// - 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: (SQLTableBuilder) -> Void) throws { - let builder = SQLTableBuilder(name: name, temporary: temporary, ifNotExists: ifNotExists, withoutRowID: false) - body(builder) - let sql = try builder.sql(self) + 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) } @@ -75,10 +75,10 @@ extension Database { /// - 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: (SQLTableAlterationBuilder) -> Void) throws { - let builder = SQLTableAlterationBuilder(name: name) - body(builder) - let sql = try builder.sql(self) + 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) } @@ -112,8 +112,8 @@ extension Database { /// - 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 builder = IndexBuilder(name: name, table: table, columns: columns, unique: unique, ifNotExists: ifNotExists, condition: condition?.sqlExpression) - let sql = builder.sql() + let definition = IndexDefinition(name: name, table: table, columns: columns, unique: unique, ifNotExists: ifNotExists, condition: condition?.sqlExpression) + let sql = definition.sql() try execute(sql) } @@ -127,26 +127,28 @@ extension Database { } } -/// The SQLTableBuilder class lets you define table columns and constraints. +/// 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 SQLTableBuilder +/// try db.create(table: "persons") { t in // t is TableDefinition /// t.column(...) /// } /// /// See https://www.sqlite.org/lang_createtable.html -public final class SQLTableBuilder { - let name: String - let temporary: Bool - let ifNotExists: Bool - let withoutRowID: Bool - var columns: [SQLColumnBuilder] = [] - var primaryKeyConstraint: (columns: [String], conflictResolution: SQLConflictResolution?)? - var uniqueKeyConstraints: [(columns: [String], conflictResolution: SQLConflictResolution?)] = [] - var foreignKeyConstraints: [(columns: [String], table: String, destinationColumns: [String]?, deleteAction: SQLForeignKeyAction?, updateAction: SQLForeignKeyAction?, deferred: Bool)] = [] - var checkConstraints: [_SQLExpression] = [] +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 @@ -165,10 +167,10 @@ public final class SQLTableBuilder { /// /// - parameter name: the column name. /// - parameter type: the column type. - /// - returns: An SQLColumnBuilder that allows you to refine the + /// - returns: An ColumnDefinition that allows you to refine the /// column definition. - public func column(name: String, _ type: SQLColumnType) -> SQLColumnBuilder { - let column = SQLColumnBuilder(name: name, type: type) + public func column(name: String, _ type: SQLColumnType) -> ColumnDefinition { + let column = ColumnDefinition(name: name, type: type) columns.append(column) return column } @@ -350,19 +352,19 @@ public final class SQLTableBuilder { } } -/// The SQLTableAlterationBuilder class lets you alter database tables. +/// 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 SQLTableAlterationBuilder +/// try db.alter(table: "persons") { t in // t is TableAlteration /// t.add(column: ...) /// } /// /// See https://www.sqlite.org/lang_altertable.html -public final class SQLTableAlterationBuilder { - let name: String - var addedColumns: [SQLColumnBuilder] = [] +public final class TableAlteration { + private let name: String + private var addedColumns: [ColumnDefinition] = [] init(name: String) { self.name = name @@ -378,10 +380,10 @@ public final class SQLTableAlterationBuilder { /// /// - parameter name: the column name. /// - parameter type: the column type. - /// - returns: An SQLColumnBuilder that allows you to refine the + /// - returns: An ColumnDefinition that allows you to refine the /// column definition. - public func add(column name: String, _ type: SQLColumnType) -> SQLColumnBuilder { - let column = SQLColumnBuilder(name: name, type: type) + public func add(column name: String, _ type: SQLColumnType) -> ColumnDefinition { + let column = ColumnDefinition(name: name, type: type) addedColumns.append(column) return column } @@ -403,30 +405,30 @@ public final class SQLTableAlterationBuilder { } } -/// The SQLColumnBuilder class lets you refine a table column. +/// 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(...) // SQLColumnBuilder +/// t.column(...) // ColumnDefinition /// } /// /// try db.alter(table: "persons") { t in -/// t.add(column: ...) // SQLColumnBuilder +/// t.add(column: ...) // ColumnDefinition /// } /// /// See https://www.sqlite.org/lang_createtable.html and /// https://www.sqlite.org/lang_altertable.html -public final class SQLColumnBuilder { - let name: String - let type: SQLColumnType - var primaryKey: (conflictResolution: SQLConflictResolution?, autoincrement: Bool)? - var notNullConflictResolution: SQLConflictResolution? - var uniqueConflictResolution: SQLConflictResolution? - var checkExpression: _SQLExpression? - var defaultExpression: _SQLExpression? - var collationName: String? - var reference: (table: String, column: String?, deleteAction: SQLForeignKeyAction?, updateAction: SQLForeignKeyAction?, deferred: Bool)? +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 @@ -447,7 +449,7 @@ public final class SQLColumnBuilder { /// (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. - public func primaryKey(onConflict conflictResolution: SQLConflictResolution? = nil, autoincrement: Bool = false) -> SQLColumnBuilder { + public func primaryKey(onConflict conflictResolution: SQLConflictResolution? = nil, autoincrement: Bool = false) -> ColumnDefinition { primaryKey = (conflictResolution: conflictResolution, autoincrement: autoincrement) return self } @@ -463,7 +465,7 @@ public final class SQLColumnBuilder { /// - 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. - public func notNull(onConflict conflictResolution: SQLConflictResolution? = nil) -> SQLColumnBuilder { + public func notNull(onConflict conflictResolution: SQLConflictResolution? = nil) -> ColumnDefinition { notNullConflictResolution = conflictResolution ?? .Abort return self } @@ -479,7 +481,7 @@ public final class SQLColumnBuilder { /// - 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. - public func unique(onConflict conflictResolution: SQLConflictResolution? = nil) -> SQLColumnBuilder { + public func unique(onConflict conflictResolution: SQLConflictResolution? = nil) -> ColumnDefinition { uniqueConflictResolution = conflictResolution ?? .Abort return self } @@ -495,7 +497,7 @@ public final class SQLColumnBuilder { /// - 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. - public func check(@noescape condition: (SQLColumn) -> _SQLExpressible) -> SQLColumnBuilder { + public func check(@noescape condition: (SQLColumn) -> _SQLExpressible) -> ColumnDefinition { checkExpression = condition(SQLColumn(name)).sqlExpression return self } @@ -510,7 +512,7 @@ public final class SQLColumnBuilder { /// /// - parameter sql: An SQL snippet. /// - returns: Self so that you can further refine the column definition. - public func check(sql sql: String) -> SQLColumnBuilder { + public func check(sql sql: String) -> ColumnDefinition { checkExpression = _SQLExpression.Literal(sql, nil) return self } @@ -525,7 +527,7 @@ public final class SQLColumnBuilder { /// /// - parameter value: A DatabaseValueConvertible value. /// - returns: Self so that you can further refine the column definition. - public func defaults(value: DatabaseValueConvertible) -> SQLColumnBuilder { + public func defaults(value: DatabaseValueConvertible) -> ColumnDefinition { defaultExpression = value.sqlExpression return self } @@ -540,7 +542,7 @@ public final class SQLColumnBuilder { /// /// - parameter sql: An SQL snippet. /// - returns: Self so that you can further refine the column definition. - public func defaults(sql sql: String) -> SQLColumnBuilder { + public func defaults(sql sql: String) -> ColumnDefinition { defaultExpression = _SQLExpression.Literal(sql, nil) return self } @@ -555,7 +557,7 @@ public final class SQLColumnBuilder { /// /// - parameter collation: An SQLCollation. /// - returns: Self so that you can further refine the column definition. - public func collate(collation: SQLCollation) -> SQLColumnBuilder { + public func collate(collation: SQLCollation) -> ColumnDefinition { collationName = collation.rawValue return self } @@ -570,7 +572,7 @@ public final class SQLColumnBuilder { /// /// - parameter collation: A custom DatabaseCollation. /// - returns: Self so that you can further refine the column definition. - public func collate(collation: DatabaseCollation) -> SQLColumnBuilder { + public func collate(collation: DatabaseCollation) -> ColumnDefinition { collationName = collation.name return self } @@ -592,7 +594,7 @@ public final class SQLColumnBuilder { /// - 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. - public func references(table: String, column: String? = nil, onDelete deleteAction: SQLForeignKeyAction? = nil, onUpdate updateAction: SQLForeignKeyAction? = nil, deferred: Bool = false) -> SQLColumnBuilder { + public func references(table: String, column: String? = nil, onDelete deleteAction: SQLForeignKeyAction? = nil, onUpdate updateAction: SQLForeignKeyAction? = nil, deferred: Bool = false) -> ColumnDefinition { reference = (table: table, column: column, deleteAction: deleteAction, updateAction: updateAction, deferred: deferred) return self } @@ -676,7 +678,7 @@ public final class SQLColumnBuilder { } } -private struct IndexBuilder { +private struct IndexDefinition { let name: String let table: String let columns: [String] From 2d3f45bad5b8cf3ab0e484961e5606fa7f060d69 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 6 Aug 2016 13:57:03 +0200 Subject: [PATCH 67/92] README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index e7ee73d5d..ec1e3e287 100644 --- a/README.md +++ b/README.md @@ -172,12 +172,12 @@ Documentation **SQLite and SQL** -- [SQLite API](#sqlite-api) +- [SQLite API](#sqlite-api): The low-level SQLite API • [executing updates](#executing-updates), [fetch queries](#fetch-queries), etc. **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), [requests](#requests), etc. - [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. From f276ab830a9aa881b8cb18575590850b55af6698 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 6 Aug 2016 14:02:00 +0200 Subject: [PATCH 68/92] README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index ec1e3e287..a787b391b 100644 --- a/README.md +++ b/README.md @@ -172,12 +172,12 @@ Documentation **SQLite and SQL** -- [SQLite API](#sqlite-api): The low-level SQLite API • [executing updates](#executing-updates), [fetch queries](#fetch-queries), etc. +- [SQLite API](#sqlite-api): The low-level SQLite API • [executing updates](#executing-updates) • [fetch queries](#fetch-queries) **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 • [table creation](#database-schema), [requests](#requests), etc. +- [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. From 6cca2fd991e94670bb8457dc7b3f81d5b83e4884 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 6 Aug 2016 14:21:39 +0200 Subject: [PATCH 69/92] Rename PrimaryKey to PrimaryKeyInfo --- CHANGELOG.md | 19 ++++++++++++++++--- GRDB/Core/Database.swift | 14 +++++++------- GRDB/Core/DatabaseSchemaCache.swift | 14 +++++++------- GRDB/QueryInterface/SQLTableBuilder.swift | 3 +++ GRDB/Record/Persistable.swift | 2 +- 5 files changed, 34 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 343f17f9f..4e6566ba3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,9 +7,13 @@ Release Notes - 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: -- Database schema DSL (TODO: doc link): + ```swift + let row: Row = ["name": "foo", "date": NSDate()] + ``` + +- Create, and alter tables ([documentation](https://github.com/groue/GRDB.swift#database-schema)): ```swift db.create(table: "pointOfInterests") { t in @@ -21,12 +25,21 @@ Release Notes } ``` -- Support for the `length` SQLite built-in function. +- 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. + ## 0.77.0 diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 8e71f2bbe..0e8827f69 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -803,7 +803,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: tableName) { @@ -836,7 +836,7 @@ extension Database { let columns = try self.columns(in: tableName) - let primaryKey: PrimaryKey? + let primaryKey: PrimaryKeyInfo? let pkColumns = columns .filter { $0.primaryKeyIndex > 0 } .sort { $0.primaryKeyIndex < $1.primaryKeyIndex } @@ -1059,7 +1059,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. @@ -1072,13 +1072,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 7605f8998..5c7718d88 100644 --- a/GRDB/Core/DatabaseSchemaCache.swift +++ b/GRDB/Core/DatabaseSchemaCache.swift @@ -7,8 +7,8 @@ protocol DatabaseSchemaCacheType { mutating func clear() - func primaryKey(tableName tableName: String) -> PrimaryKey?? - mutating func setPrimaryKey(primaryKey: PrimaryKey?, forTableName tableName: String) + func primaryKey(tableName tableName: String) -> PrimaryKeyInfo?? + mutating func setPrimaryKey(primaryKey: PrimaryKeyInfo?, forTableName tableName: String) func columns(in tableName: String) -> [ColumnInfo]? mutating func setColumns(columns: [ColumnInfo], forTableName tableName: String) @@ -19,7 +19,7 @@ protocol DatabaseSchemaCacheType { /// A thread-unsafe database schema cache final class DatabaseSchemaCache: DatabaseSchemaCacheType { - 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 DatabaseSchemaCache: DatabaseSchemaCacheType { indexes = [:] } - func primaryKey(tableName tableName: String) -> PrimaryKey?? { + func primaryKey(tableName tableName: String) -> PrimaryKeyInfo?? { return primaryKeys[tableName] } - func setPrimaryKey(primaryKey: PrimaryKey?, forTableName tableName: String) { + func setPrimaryKey(primaryKey: PrimaryKeyInfo?, forTableName tableName: String) { primaryKeys[tableName] = primaryKey } @@ -62,11 +62,11 @@ final class SharedDatabaseSchemaCache: DatabaseSchemaCacheType { cache.write { $0.clear() } } - func primaryKey(tableName tableName: String) -> PrimaryKey?? { + func primaryKey(tableName tableName: String) -> PrimaryKeyInfo?? { return cache.read { $0.primaryKey(tableName: tableName) } } - func setPrimaryKey(primaryKey: PrimaryKey?, forTableName tableName: String) { + func setPrimaryKey(primaryKey: PrimaryKeyInfo?, forTableName tableName: String) { cache.write { $0.setPrimaryKey(primaryKey, forTableName: tableName) } } diff --git a/GRDB/QueryInterface/SQLTableBuilder.swift b/GRDB/QueryInterface/SQLTableBuilder.swift index 52f0e10ab..b2df7033c 100644 --- a/GRDB/QueryInterface/SQLTableBuilder.swift +++ b/GRDB/QueryInterface/SQLTableBuilder.swift @@ -1,4 +1,7 @@ extension Database { + + // MARK: - Database Schema + /// Creates a database table. /// /// try db.create(table: "pointOfInterests") { t in diff --git a/GRDB/Record/Persistable.swift b/GRDB/Record/Persistable.swift index b79498df9..dece528bf 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. From 1eb00401269961f0a6fee3be97a52cd626138eb9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 6 Aug 2016 14:21:57 +0200 Subject: [PATCH 70/92] SQLTableBuilder documentation --- README.md | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index a787b391b..f49bc4a16 100644 --- a/README.md +++ b/README.md @@ -1356,7 +1356,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: @@ -2165,9 +2165,22 @@ try db.create(table: "pointOfInterests") { t in } ``` -The `create(table:)` method covers nearly all [CREATE TABLE](https://www.sqlite.org/lang_createtable.html) SQLite statements: +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 demo ( +try db.create(table: "demo") { t in ... } + // CREATE TEMPORARY TABLE demo IF NOT EXISTS ( try db.create(table: "demo", temporary: true, ifNotExists: true) { t in ``` @@ -2247,7 +2260,7 @@ try db.alter(table: "persons") { t in } ``` -Table alterations are restricted: see the documentation of the [ALTER TABLE](https://www.sqlite.org/lang_altertable.html), and [Migrations](#migrations) for a way to lift those restrictions. +> :point_up: **Note**: Table alterations are restricted, and may require you to recreate triggers or views: see the documentation of the [ALTER TABLE](https://www.sqlite.org/lang_altertable.html), and [migrations](#migrations) for a way to lift those restrictions. #### Drop Tables @@ -2267,6 +2280,12 @@ Create indexes with the `create(index:)` method: 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 From 68403ee1429431d1eede99b55e3a8116dc36cf3a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 6 Aug 2016 14:33:31 +0200 Subject: [PATCH 71/92] SQLTableBuilder documentation --- README.md | 43 ++++++++++++++++++++++++------------------- 1 file changed, 24 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index f49bc4a16..76bee6059 100644 --- a/README.md +++ b/README.md @@ -288,7 +288,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) } @@ -356,7 +356,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) } @@ -1335,7 +1335,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) +} // @@ -2178,11 +2181,11 @@ Relevant SQLite documentation: **Configure table creation**: ```swift -// CREATE TABLE demo ( -try db.create(table: "demo") { t in ... } +// CREATE TABLE example ( +try db.create(table: "example") { t in ... } -// CREATE TEMPORARY TABLE demo IF NOT EXISTS ( -try db.create(table: "demo", temporary: true, ifNotExists: true) { 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): @@ -2747,11 +2750,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") } ``` @@ -3549,24 +3554,24 @@ 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 + 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**: defining collations in the table definition *requires* the application to provide the collation. This means that the database file becomes uneasy to share with other SQLite libraries or platforms (such as the Android version of your application). + +If you can't or don't want (see warning above) 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): ```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) +let persons = Person.filter(uuidColumn.collating(.Nocase) == uuid).fetchAll(db) ``` From adaabcb8e52c851cc89704f65097f5a6ab9bad2a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 6 Aug 2016 14:38:20 +0200 Subject: [PATCH 72/92] SQLTableBuilder documentation --- README.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 76bee6059..daf1b9435 100644 --- a/README.md +++ b/README.md @@ -2712,23 +2712,26 @@ 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 +// 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 +// 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 +// // v3 database // migrator.registerMigration("v3") { db in // ... // } From 0ab4df99b704a03b54bdf820e9a2f15cea6b497f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 6 Aug 2016 14:43:43 +0200 Subject: [PATCH 73/92] SQLTableBuilder documentation --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index daf1b9435..77502d1ad 100644 --- a/README.md +++ b/README.md @@ -2207,7 +2207,7 @@ Define **not null** columns, and set **default** values: t.column("name", .Text).notNull().defaults("Anonymous") ``` -Use an individual column as **primary**, **unique**, or **foreign key**. When not specified, the referenced column is the primary key of the referenced table: +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 it): ```swift // id INTEGER PRIMARY KEY, @@ -2223,10 +2223,10 @@ Use an individual column as **primary**, **unique**, or **foreign key**. When no **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 - // age INTEGER CHECK (age > 0) // name TEXT CHECK (LENGTH(name) > 0) - t.column("age", .Integer).check { $0 > 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: From 3de49203855faa8563bd24ea54c778b7949fe891 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 6 Aug 2016 14:54:53 +0200 Subject: [PATCH 74/92] SQLTableBuilder documentation --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 77502d1ad..08bb82b23 100644 --- a/README.md +++ b/README.md @@ -2116,6 +2116,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) ``` @@ -2123,6 +2124,7 @@ 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"]) ``` From b45939ed26a5fbb21dedb687f26e9e72637c37c9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 6 Aug 2016 14:57:01 +0200 Subject: [PATCH 75/92] SQLTableBuilder documentation --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 08bb82b23..caf4751f0 100644 --- a/README.md +++ b/README.md @@ -2265,7 +2265,7 @@ try db.alter(table: "persons") { t in } ``` -> :point_up: **Note**: Table alterations are restricted, and may require you to recreate triggers or views: see the documentation of the [ALTER TABLE](https://www.sqlite.org/lang_altertable.html), and [migrations](#migrations) for a way to lift those restrictions. +> :point_up: **Note**: Table alterations are restricted, and may require you to recreate triggers or views: see the documentation of the [ALTER TABLE](https://www.sqlite.org/lang_altertable.html), and [Advanced Database Schema Changes](#advanced-database-schema-changes) for a way to lift those restrictions. #### Drop Tables From adde65f7577d1c3d13bb669c0a65bbceb27746e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 6 Aug 2016 14:58:21 +0200 Subject: [PATCH 76/92] SQLTableBuilder documentation --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index caf4751f0..eddc3f6b2 100644 --- a/README.md +++ b/README.md @@ -2265,7 +2265,7 @@ try db.alter(table: "persons") { t in } ``` -> :point_up: **Note**: Table alterations are restricted, and may require you to recreate triggers or views: see the documentation of the [ALTER TABLE](https://www.sqlite.org/lang_altertable.html), and [Advanced Database Schema Changes](#advanced-database-schema-changes) for a way to lift those restrictions. +> :point_up: **Note**: Table alterations are restricted, and may require you to recreate 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 From e58ed7a3dc8b6a0516698f761aa3945e784aaaa2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 6 Aug 2016 14:59:01 +0200 Subject: [PATCH 77/92] SQLTableBuilder documentation --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index eddc3f6b2..8f2cf1b42 100644 --- a/README.md +++ b/README.md @@ -2265,7 +2265,7 @@ try db.alter(table: "persons") { t in } ``` -> :point_up: **Note**: Table alterations are restricted, and may require you to recreate 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. +> :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 From 0c9c17622349d6c61c1796b29e8d61eda575bddd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 6 Aug 2016 15:00:38 +0200 Subject: [PATCH 78/92] SQLTableBuilder documentation --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8f2cf1b42..ee2254170 100644 --- a/README.md +++ b/README.md @@ -2253,7 +2253,7 @@ Other **table constraints** can involve several columns: #### Modify Tables -SQLite let you rename tables, and add columns to existing tables: +SQLite lets you rename tables, and add columns to existing tables: ```swift // ALTER TABLE referers RENAME TO referrers From 1534e1a1ee3c2d43b3edc87355d33af1965c9338 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 6 Aug 2016 15:05:16 +0200 Subject: [PATCH 79/92] Documentation tweaks --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index ee2254170..d7f907203 100644 --- a/README.md +++ b/README.md @@ -660,7 +660,7 @@ Generally speaking, you can extract the type you need, *provided it can be conve - **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 NSData. @@ -1043,7 +1043,7 @@ enum Grape : String { case Chardonnay, Merlot, Riesling } -// Declare DatabaseValueConvertible adoption +// Declare empty DatabaseValueConvertible adoption extension Color : DatabaseValueConvertible { } extension Grape : DatabaseValueConvertible { } @@ -2305,7 +2305,7 @@ 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 { ... } +class Person : Record { ... } ``` Declare the table **columns** that you want to use for filtering, or sorting: @@ -2881,7 +2881,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 : TransactionObserverType { func databaseDidChangeWithEvent(event: DatabaseEvent) { guard event.tableName == "persons" else { return From f51bbd8a39bcc8dc02a2223040ca6d9d17710395 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 6 Aug 2016 15:07:07 +0200 Subject: [PATCH 80/92] Documentation tweaks --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index d7f907203..6692a607c 100644 --- a/README.md +++ b/README.md @@ -165,7 +165,7 @@ Documentation - [GRDB Reference](http://cocoadocs.org/docsets/GRDB.swift/0.77.0/index.html) (on cocoadocs.org) -**Getting started** +**Getting Started** - [Installation](#installation) - [Database Connections](#database-connections): Connect to SQLite databases @@ -174,7 +174,7 @@ Documentation - [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 • [table creation](#database-schema) • [fetch requests](#requests) @@ -184,7 +184,7 @@ Documentation - [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) From 9274864a838e55925f3abd45ac589a674d6991ac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 6 Aug 2016 15:09:47 +0200 Subject: [PATCH 81/92] Identity --- GRDB.swift.podspec | 2 +- README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index 09e21b62e..1fbca02e1 100644 --- a/GRDB.swift.podspec +++ b/GRDB.swift.podspec @@ -2,7 +2,7 @@ Pod::Spec.new do |s| s.name = 'GRDB.swift' s.version = '0.77.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/README.md b/README.md index 6692a607c..9279ffeb3 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ GRDB.swift [![Swift](https://img.shields.io/badge/swift-2.2-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) ========== -### A Swift application toolkit that provides access to SQLite databases. +### A Swift application toolkit for SQLite databases. **Requirements**: iOS 8.0+ / OSX 10.9+ • Xcode 7.3+ • Swift 2.2 (see the [Swift3](https://github.com/groue/GRDB.swift/tree/Swift3) branch for Swift 3). From a7f80ef144ee1f4310e169d51f6ec2e7f32ec813 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 6 Aug 2016 15:27:32 +0200 Subject: [PATCH 82/92] CHANGELOG.md --- CHANGELOG.md | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4e6566ba3..3d907576a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,7 +13,7 @@ Release Notes let row: Row = ["name": "foo", "date": NSDate()] ``` -- Create, and alter tables ([documentation](https://github.com/groue/GRDB.swift#database-schema)): +- 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 @@ -38,7 +38,12 @@ Release Notes - Built-in SQLite collations used to be named by string: "NOCASE", etc. Now use the SQLCollation enum: `.Nocase`, etc. -- PrimaryKey has been renamed PrimaryKeyInfo. +- PrimaryKey has been renamed PrimaryKeyInfo: + + ```swift + let pk = db.primaryKey("persons") + pk.columns // ["id"] + ``` ## 0.77.0 From a820a96996aeb80819f23a1f0cab1440fd962ca6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 6 Aug 2016 15:40:11 +0200 Subject: [PATCH 83/92] v0.78.0 --- CHANGELOG.md | 2 +- GRDB.swift.podspec | 2 +- README.md | 2 +- Support/Info.plist | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3d907576a..f5c857aa0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,7 +1,7 @@ Release Notes ============= -## Next version +## 0.78.0 **New** diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index 1fbca02e1..be6de65c9 100644 --- a/GRDB.swift.podspec +++ b/GRDB.swift.podspec @@ -1,6 +1,6 @@ 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 Swift application toolkit for SQLite databases.' s.homepage = 'https://github.com/groue/GRDB.swift' diff --git a/README.md b/README.md index 9279ffeb3..7d4e393d9 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ GRDB.swift [![Swift](https://img.shields.io/badge/swift-2.2-orange.svg?style=fla **Requirements**: iOS 8.0+ / OSX 10.9+ • Xcode 7.3+ • Swift 2.2 (see the [Swift3](https://github.com/groue/GRDB.swift/tree/Swift3) branch for Swift 3). -**Latest release**: July 28, 2016 • version 0.77.0 • [CHANGELOG](CHANGELOG.md) +**Latest release**: August 6, 2016 • version 0.78.0 • [CHANGELOG](CHANGELOG.md) Follow [@groue](http://twitter.com/groue) on Twitter for release announcements and usage tips. 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 From 714f56c17c6f9e470fbec3b5a026eaf9459897d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 6 Aug 2016 20:50:38 +0200 Subject: [PATCH 84/92] Fix version links --- CHANGELOG.md | 2 ++ README.md | 20 ++++++++++---------- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f5c857aa0..15a50c726 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,8 @@ Release Notes ## 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)) diff --git a/README.md b/README.md index 7d4e393d9..d0a7a5097 100644 --- a/README.md +++ b/README.md @@ -163,7 +163,7 @@ Documentation **Reference** -- [GRDB Reference](http://cocoadocs.org/docsets/GRDB.swift/0.77.0/index.html) (on cocoadocs.org) +- [GRDB Reference](http://cocoadocs.org/docsets/GRDB.swift/0.78.0/index.html) (on cocoadocs.org) **Getting Started** @@ -210,7 +210,7 @@ To use GRDB with CocoaPods, specify in your Podfile: source 'https://github.com/CocoaPods/Specs.git' use_frameworks! -pod 'GRDB.swift', '~> 0.77.0' +pod 'GRDB.swift', '~> 0.78.0' ``` > :point_up: **Note**: [SQLCipher](#encryption) and [custom SQLite builds](#custom-sqlite-builds) are not available via CocoaPods. @@ -223,7 +223,7 @@ pod 'GRDB.swift', '~> 0.77.0' To use GRDB with Carthage, specify in your Cartfile: ``` -github "groue/GRDB.swift" ~> 0.77.0 +github "groue/GRDB.swift" ~> 0.78.0 ``` > :point_up: **Note**: [custom SQLite builds](#custom-sqlite-builds) are not available via Carthage. @@ -332,7 +332,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 @@ -412,7 +412,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. @@ -1504,10 +1504,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 @@ -3668,7 +3668,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: From ccd58d2909532448d678380ed9b88c43213404a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 7 Aug 2016 03:41:18 +0200 Subject: [PATCH 85/92] Documentation --- README.md | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index d0a7a5097..773fa18cd 100644 --- a/README.md +++ b/README.md @@ -2209,7 +2209,7 @@ Define **not null** columns, and set **default** values: 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 it): +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, @@ -3546,11 +3546,11 @@ Person.select(nameColumn.uppercaseString) 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` @@ -3560,6 +3560,10 @@ A collation can be applied to a table column. All comparisons involving this col ```swift 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) } @@ -3567,16 +3571,15 @@ try db.create(table: "persons") { t in let persons = Person.order(nameColumn).fetchAll(db) ``` -> :warning: **Warning**: defining collations in the table definition *requires* the application to provide the collation. This means that the database file becomes uneasy to share with other SQLite libraries or platforms (such as the Android version of your application). +> :warning: **Warning**: using a custom collation in a table definition *requires* the host application to provide the collation definition. This means that any the database file becomes uneasy to share with other SQLite libraries or platforms (such as the Android version of your application). -If you can't or don't want (see warning above) 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): +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) ``` From 5b65279a0a9d40fdc6f3aea3a48cf0baace48868 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 7 Aug 2016 04:00:57 +0200 Subject: [PATCH 86/92] Documentation --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 773fa18cd..f8e03dfa2 100644 --- a/README.md +++ b/README.md @@ -3571,7 +3571,7 @@ try db.create(table: "persons") { t in let persons = Person.order(nameColumn).fetchAll(db) ``` -> :warning: **Warning**: using a custom collation in a table definition *requires* the host application to provide the collation definition. This means that any the database file becomes uneasy to share with other SQLite libraries or platforms (such as the Android version of your application). +> :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): From f9e875a7cc38c8ff622c36abbe5fcf7817b1d977 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 7 Aug 2016 04:11:37 +0200 Subject: [PATCH 87/92] Documentation --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index f8e03dfa2..ef2860e1d 100644 --- a/README.md +++ b/README.md @@ -101,7 +101,7 @@ Insert and fetch [records](#records): ```swift struct PointOfInterest { var id: Int64? - var title: String? + var title: String var favorite: Bool var coordinate: CLLocationCoordinate2D } @@ -1716,7 +1716,7 @@ public protocol RowConvertible { ```swift struct PointOfInterest { var id: Int64? - var title: String? + var title: String var coordinate: CLLocationCoordinate2D } @@ -2002,7 +2002,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 From 1549affd5c5d901ddc8f569d12773fef54d168fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 7 Aug 2016 04:14:29 +0200 Subject: [PATCH 88/92] Documentation --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index ef2860e1d..e873aac11 100644 --- a/README.md +++ b/README.md @@ -59,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" + ")") @@ -133,8 +133,8 @@ Avoid SQL with the [query interface](#the-query-interface): dbQueue.inDatabase { db in try db.create(table: "pointOfInterests") { t in t.column("id", .Integer).primaryKey() - t.column("title", .Text) - t.column("favorite", .Boolean).notNull() + t.column("title", .Text).notNull() + t.column("favorite", .Boolean).notNull().defaults(false) t.column("longitude", .Double).notNull() t.column("latitude", .Double).notNull() } From d3c901678cf002bdb90576e015c15e0fa582f4e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 7 Aug 2016 04:18:44 +0200 Subject: [PATCH 89/92] Documentation --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e873aac11..8cd7e11e1 100644 --- a/README.md +++ b/README.md @@ -2183,7 +2183,7 @@ Relevant SQLite documentation: **Configure table creation**: ```swift -// CREATE TABLE example ( +// CREATE TABLE example ( ... ) try db.create(table: "example") { t in ... } // CREATE TEMPORARY TABLE example IF NOT EXISTS ( From c8445b9b5fff2c9b719b5ce8f0e9e132252d8f68 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 7 Aug 2016 04:35:31 +0200 Subject: [PATCH 90/92] Documentation --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 8cd7e11e1..52a91a91a 100644 --- a/README.md +++ b/README.md @@ -649,11 +649,11 @@ 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*: From 949d706eaacae6376e370de44d726f954b779819 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 7 Aug 2016 04:41:43 +0200 Subject: [PATCH 91/92] Documentation --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 52a91a91a..4d9a74c07 100644 --- a/README.md +++ b/README.md @@ -852,8 +852,8 @@ class Link : Record { var verified: Bool required init(_ row: Row) { - url = row.value("url") - verified = row.value("verified") + url = row.value(named: "url") + verified = row.value(named: "verified") super.init(row) } From 7d21772f878813df7e0781cf996db75bdf3e08b8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 7 Aug 2016 05:01:27 +0200 Subject: [PATCH 92/92] Documentation --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 4d9a74c07..42ef8dadf 100644 --- a/README.md +++ b/README.md @@ -1930,11 +1930,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) }