Merge branch 'development'

This commit is contained in:
Gwendal Roué committed 2023-07-09 18:32:52 +02:00
commit e83f3eb25e
78 files changed
+4789 -2032

No files matched your search

+38 -22
View File
@@ -13,6 +13,7 @@ on:
- '.github/workflows/**'
- 'Makefile'
- 'Package.swift'
- 'SQLiteCustom/src'
pull_request:
paths:
- 'GRDB/**'
@@ -20,6 +21,7 @@ on:
- '.github/workflows/**'
- 'Makefile'
- 'Package.swift'
- 'SQLiteCustom/src'
concurrency:
group: ${{ github.ref_name }}
@@ -38,24 +40,32 @@ jobs:
fail-fast: false
matrix:
include:
- xcode: "Xcode_14.3.1.app"
runsOn: macOS-13
destination: "platform=macOS"
name: "macOS"
- xcode: "Xcode_14.3.1.app"
runsOn: macOS-13
destination: "OS=16.4,name=iPhone 14 Pro"
name: "iOS"
- xcode: "Xcode_14.3.1.app"
runsOn: macOS-13
destination: "OS=16.4,name=Apple TV"
name: "tvOS"
- xcode: "Xcode_14.2.app"
runsOn: macOS-12
runsOn: macOS-13
destination: "platform=macOS"
name: "macOS"
- xcode: "Xcode_14.2.app"
runsOn: macOS-12
runsOn: macOS-13
destination: "OS=16.2,name=iPhone 14"
name: "iOS"
- xcode: "Xcode_14.2.app"
runsOn: macOS-12
destination: "OS=16.1,name=Apple TV"
name: "tvOS"
- xcode: "Xcode_14.1.app"
runsOn: macOS-12
runsOn: macOS-13
destination: "platform=macOS"
name: "macOS"
- xcode: "Xcode_14.1.app"
runsOn: macOS-12
runsOn: macOS-13
destination: "OS=16.1,name=iPhone 14"
name: "iOS"
- xcode: "Xcode_14.0.1.app"
@@ -80,11 +90,14 @@ jobs:
fail-fast: false
matrix:
include:
- xcode: "Xcode_14.3.1.app"
runsOn: macOS-13
name: "Xcode 14.3.1"
- xcode: "Xcode_14.2.app"
runsOn: macOS-12
runsOn: macOS-13
name: "Xcode 14.2"
- xcode: "Xcode_14.1.app"
runsOn: macOS-12
runsOn: macOS-13
name: "Xcode 14.1"
- xcode: "Xcode_14.0.1.app"
runsOn: macOS-12
@@ -103,9 +116,12 @@ jobs:
fail-fast: false
matrix:
include:
- xcode: "Xcode_14.2.app"
- xcode: "Xcode_14.3.1.app"
runsOn: macOS-13
name: "Xcode 14.3.1"
- xcode: "Xcode_14.0.1.app"
runsOn: macOS-12
name: "Xcode 14.2"
name: "Xcode 14.0.1"
steps:
- uses: actions/checkout@v3
- name: ${{ matrix.name }}
@@ -120,9 +136,9 @@ jobs:
fail-fast: false
matrix:
include:
- xcode: "Xcode_14.2.app"
runsOn: macOS-12
name: "Xcode 14.2"
- xcode: "Xcode_14.3.1.app"
runsOn: macOS-13
name: "Xcode 14.3.1"
- xcode: "Xcode_14.0.1.app"
runsOn: macOS-12
name: "Xcode 14.0.1"
@@ -140,9 +156,9 @@ jobs:
fail-fast: false
matrix:
include:
- xcode: "Xcode_14.2.app"
runsOn: macOS-12
name: "Xcode 14.2"
- xcode: "Xcode_14.3.1.app"
runsOn: macOS-13
name: "Xcode 14.3.1"
- xcode: "Xcode_14.0.1.app"
runsOn: macOS-12
name: "Xcode 14.0.1"
@@ -160,14 +176,14 @@ jobs:
fail-fast: false
matrix:
include:
- xcode: "Xcode_14.2.app"
runsOn: macOS-12
name: "Xcode 14.2"
- xcode: "Xcode_14.3.1.app"
runsOn: macOS-13
name: "Xcode 14.3.1"
- xcode: "Xcode_14.0.1.app"
runsOn: macOS-12
name: "Xcode 14.0.1"
steps:
- uses: actions/checkout@v3
- name: ${{ matrix.name }}
run: make test_archive_GRDBOSX_xcframework
run: make test_universal_xcframework
+21
View File
@@ -7,6 +7,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
#### 6.x Releases
- `6.16.x` Releases - [6.16.0](#6160)
- `6.15.x` Releases - [6.15.0](#6150) - [6.15.1](#6151)
- `6.14.x` Releases - [6.14.0](#6140)
- `6.13.x` Releases - [6.13.0](#6130)
@@ -113,6 +114,26 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
---
## 6.16.0
Released July 9, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.15.1...v6.16.0)
- **New**: [#1397](https://github.com/groue/GRDB.swift/pull/1397) by [@groue](https://github.com/groue): Swift API for creating database views
- **New**: [#1401](https://github.com/groue/GRDB.swift/pull/1401) by [@kustra](https://github.com/kustra): Linux compilation fixes
- **New**: [#1402](https://github.com/groue/GRDB.swift/pull/1402) by [@groue](https://github.com/groue): Upgrade custom SQLite builds to 3.42.0
- **New**: [#1403](https://github.com/groue/GRDB.swift/pull/1403) by [@groue](https://github.com/groue): GitHub CI: test Xcode 14.3.1, macOS 13
- **New**: :star: [#1405](https://github.com/groue/GRDB.swift/pull/1405) Simplify the declaration of BelongsTo associations in the database schema
- **Documentation Update**: The documentation was updated for the new recommended way to declare associations in the database schema, with the `belongsTo()` method introduced by [#1405](https://github.com/groue/GRDB.swift/pull/1405):
- [`belongsTo(_:inTable:onDelete:onUpdate:deferred:indexed:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/tabledefinition/belongsto(_:intable:ondelete:onupdate:deferred:indexed:))
- [The Database Schema](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema)
- [Migrations](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations)
- [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices)
- [Associations](Documentation/AssociationsBasics.md)
- [`BelongsToAssociation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/belongstoassociation)
- [`HasManyAssociation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/hasmanyassociation)
- [`HasOneAssociation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/hasoneassociation)
## 6.15.1
Released June 17, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.15.0...v6.15.1)
+24 -20
View File
@@ -429,15 +429,13 @@ The matching [migration] would look like:
migrator.registerMigration("Employees") { db in
try db.create(table: "employee") { t in
t.autoIncrementedPrimaryKey("id")
t.column("managerId", .integer)
.indexed()
.references("employee", onDelete: .restrict)
t.belongsTo("manager", inTable: "employee", onDelete: .setNull)
t.column("name", .text)
}
}
```
Note that both sides of the self-join use a customized **[association key](#the-structure-of-a-joined-request)**. This helps consuming this association. For example:
Note that the associations on both sides of the self-join use a customized **[association key](#the-structure-of-a-joined-request)**. This helps consuming this association. For example:
```swift
struct EmployeeInfo: FetchableRecord, Decodable {
@@ -536,20 +534,16 @@ migrator.registerMigration("Books and Authors") { db in
}
try db.create(table: "book") { t in
t.autoIncrementedPrimaryKey("id")
t.column("authorId", .integer) // (2)
t.belongsTo("author", onDelete: .cascade) // (2)
.notNull() // (3)
.indexed() // (4)
.references("author", onDelete: .cascade) // (5)
t.column("title", .text)
}
}
```
1. The `author` table has a primary key.
2. The `book.authorId` column is used to link a book to the author it belongs to.
2. The `book.authorId` column is used to link a book to the author it belongs to. This column is indexed in order to ease the selection of an author's books. A foreign key is defined from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book refers to a missing author. The `onDelete: .cascade` option has SQLite automatically delete all of an author's books when that author is deleted. See [Foreign Key Actions] for more information.
3. Make the `book.authorId` column not null if you want SQLite to guarantee that all books have an author.
4. Create an index on the `book.authorId` column in order to ease the selection of an author's books.
5. Create a foreign key from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book refers to a missing author. The `onDelete: .cascade` option has SQLite automatically delete all of an author's books when that author is deleted. See [Foreign Key Actions] for more information.
The example above uses auto-incremented primary keys. But generally speaking, all primary keys are supported, including composite primary keys that span several columns.
@@ -595,20 +589,16 @@ migrator.registerMigration("Books and Authors") { db in
}
try db.create(table: "book") { t in
t.autoIncrementedPrimaryKey("id")
t.column("authorId", .integer) // (2)
t.belongsTo("author", onDelete: .cascade) // (2)
.notNull() // (3)
.indexed() // (4)
.references("author", onDelete: .cascade) // (5)
t.column("title", .text)
}
}
```
1. The `author` table has a primary key.
2. The `book.authorId` column is used to link a book to the author it belongs to.
2. The `book.authorId` column is used to link a book to the author it belongs to. This column is indexed in order to ease the selection of an author's books. A foreign key is defined from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book refers to a missing author. The `onDelete: .cascade` option has SQLite automatically delete all of an author's books when that author is deleted. See [Foreign Key Actions] for more information.
3. Make the `book.authorId` column not null if you want SQLite to guarantee that all books have an author.
4. Create an index on the `book.authorId` column in order to ease the selection of an author's books.
5. Create a foreign key from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book refers to a missing author. The `onDelete: .cascade` option has SQLite automatically delete all of an author's books when that author is deleted. See [Foreign Key Actions] for more information.
The example above uses auto-incremented primary keys. But generally speaking, all primary keys are supported, including composite primary keys that span several columns.
@@ -654,10 +644,9 @@ migrator.registerMigration("Countries") { db in
}
try db.create(table: "demographics") { t in
t.autoIncrementedPrimaryKey("id")
t.column("countryCode", .text) // (2)
t.belongsTo("country", onDelete: .cascade) // (2)
.notNull() // (3)
.unique() // (4)
.references("country", onDelete: .cascade) // (5)
t.column("population", .integer)
t.column("density", .double)
}
@@ -665,10 +654,9 @@ migrator.registerMigration("Countries") { db in
```
1. The `country` table has a primary key.
2. The `demographics.countryCode` column is used to link a demographic profile to the country it belongs to.
2. The `demographics.countryCode` column is used to link a demographic profile to the country it belongs to. This column is indexed in order to ease the selection of the demographics of a country. A foreign key is defined from `demographics.countryCode` column to `country.code`, so that SQLite guarantees that no profile refers to a missing country. The `onDelete: .cascade` option has SQLite automatically delete a profile when its country is deleted. See [Foreign Key Actions] for more information.
3. Make the `demographics.countryCode` column not null if you want SQLite to guarantee that all profiles are linked to a country.
4. Create a unique index on the `demographics.countryCode` column in order to guarantee the unicity of any country's profile.
5. Create a foreign key from `demographics.countryCode` column to `country.code`, so that SQLite guarantees that no profile refers to a missing country. The `onDelete: .cascade` option has SQLite automatically delete a profile when its country is deleted. See [Foreign Key Actions] for more information.
The example above uses a string primary key for the "country" table. But generally speaking, all primary keys are supported, including composite primary keys that span several columns.
@@ -720,6 +708,22 @@ Sometimes the database schema does not define any foreign key. And sometimes, th
![AmbiguousForeignKeys](https://cdn.rawgit.com/groue/GRDB.swift/master/Documentation/Images/Associations2/AmbiguousForeignKeys.svg)
```swift
// The migration that has created the above schema
migrator.registerMigration("Library") { db in
try db.create(table: "person") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text)
}
try db.create(table: "book") { t in
t.autoIncrementedPrimaryKey("id")
t.belongsTo("author", inTable: "person")
t.belongsTo("translator", inTable: "person")
t.column("title", .text)
}
}
```
When this happens, associations can't be automatically inferred from the database schema. GRDB will complain with a fatal error such as "Ambiguous foreign key from book to person", or "Could not infer foreign key from book to person".
Your help is needed. You have to instruct GRDB which foreign key to use:
+1 -1
View File
@@ -3,7 +3,7 @@ Custom SQLite Builds
By default, GRDB uses the version of SQLite that ships with the target operating system.
**You can build GRDB with a custom build of [SQLite 3.39.3](https://www.sqlite.org/changes.html).**
**You can build GRDB with a custom build of [SQLite 3.42.0](https://www.sqlite.org/changes.html).**
A custom SQLite build can activate extra SQLite features, and extra GRDB features as well, such as support for the [FTS5 full-text search engine](../../../#full-text-search), and [SQLite Pre-Update Hooks](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactionobserver).
@@ -29,10 +29,7 @@ migrator.registerMigration("createLibrary") { db in
try db.create(table: "book") { t in
t.autoIncrementedPrimaryKey("id")
t.column("title", .text).notNull()
t.column("authorId", .integer)
.notNull()
.indexed()
.references("author", onDelete: .cascade)
t.belongsTo("author", onDelete: .cascade).notNull()
}
}
@@ -23,7 +23,7 @@ migrator.registerMigration("createPet") { db in
try db.create(table: "pet") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
t.column("ownerId", .integer).references("person", onDelete: .cascade)
t.belongsTo("owner", inTable: "person", onDelete: .cascade)
}
}
try! migrator.migrate(dbQueue)
+1 -1
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '6.15.1'
s.version = '6.16.0'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
+40
View File
@@ -94,6 +94,7 @@
563B8FB524A1D029007A48C9 /* ReceiveValuesOn.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FB424A1D029007A48C9 /* ReceiveValuesOn.swift */; };
563B8FC524A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FC424A1D3B9007A48C9 /* OnDemandFuture.swift */; };
563C67B324628BEA00E94EDC /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563C67B224628BEA00E94EDC /* DatabasePoolTests.swift */; };
563CBBE12A595131008905CE /* SQLIndexGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563CBBE02A595131008905CE /* SQLIndexGenerator.swift */; };
563DE4F3231A91E2005081B7 /* DatabaseConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563DE4EC231A91E2005081B7 /* DatabaseConfigurationTests.swift */; };
563EF415215F87EB007DAACD /* OrderedDictionary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF414215F87EB007DAACD /* OrderedDictionary.swift */; };
563EF42D2161180D007DAACD /* AssociationAggregate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF42C2161180D007DAACD /* AssociationAggregate.swift */; };
@@ -202,6 +203,7 @@
56848973242DE36F002F9702 /* ValueObservationScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56848972242DE36F002F9702 /* ValueObservationScheduler.swift */; };
56894F752606576600268F4D /* FoundationDecimalTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F742606576600268F4D /* FoundationDecimalTests.swift */; };
56894FB72606589700268F4D /* Decimal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F94260657D600268F4D /* Decimal.swift */; };
568C3F7A2A5AB2C300A2309D /* ForeignKeyDefinitionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F792A5AB2C300A2309D /* ForeignKeyDefinitionTests.swift */; };
568D131F2207213E00674B58 /* SQLQueryGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568D13182207213E00674B58 /* SQLQueryGenerator.swift */; };
568EB71929211E0800E59445 /* DatabaseSnapshotPool.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568EB71829211E0700E59445 /* DatabaseSnapshotPool.swift */; };
568EB71E2921234800E59445 /* DatabaseSnapshotPoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568EB71D2921234800E59445 /* DatabaseSnapshotPoolTests.swift */; };
@@ -379,6 +381,14 @@
56F34FC224B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FC124B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift */; };
56F3E7491E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; };
56F61DD5283D344E00AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DD4283D344E00AF9884 /* getThreadsCount.c */; };
56F89DF72A57EAA9002FE2AA /* ColumnDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89DF62A57EAA9002FE2AA /* ColumnDefinition.swift */; };
56F89DFC2A57EAEA002FE2AA /* ForeignKeyDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89DFB2A57EAEA002FE2AA /* ForeignKeyDefinition.swift */; };
56F89DFE2A57EB19002FE2AA /* IndexDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89DFD2A57EB19002FE2AA /* IndexDefinition.swift */; };
56F89E002A57EB5C002FE2AA /* TableAlteration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89DFF2A57EB5C002FE2AA /* TableAlteration.swift */; };
56F89E022A57EB87002FE2AA /* Database+SchemaDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89E012A57EB87002FE2AA /* Database+SchemaDefinition.swift */; };
56F89E0C2A57EC16002FE2AA /* SQLTableGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89E0B2A57EC16002FE2AA /* SQLTableGenerator.swift */; };
56F89E0E2A57EC2B002FE2AA /* SQLColumnGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89E0D2A57EC2B002FE2AA /* SQLColumnGenerator.swift */; };
56F89E152A585C0B002FE2AA /* SQLTableAlterationGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89E142A585C0B002FE2AA /* SQLTableAlterationGenerator.swift */; };
56FA0C3028B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FA0C2F28B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift */; };
56FA0C3928B20ABE00B2DFF7 /* PersistableRecord+Upsert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FA0C3828B20ABE00B2DFF7 /* PersistableRecord+Upsert.swift */; };
56FBFEDA2210731A00945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED82210731A00945324 /* SQLRequest.swift */; };
@@ -493,6 +503,7 @@
563B8FB424A1D029007A48C9 /* ReceiveValuesOn.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ReceiveValuesOn.swift; sourceTree = "<group>"; };
563B8FC424A1D3B9007A48C9 /* OnDemandFuture.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OnDemandFuture.swift; sourceTree = "<group>"; };
563C67B224628BEA00E94EDC /* DatabasePoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolTests.swift; sourceTree = "<group>"; };
563CBBE02A595131008905CE /* SQLIndexGenerator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLIndexGenerator.swift; sourceTree = "<group>"; };
563DE4EC231A91E2005081B7 /* DatabaseConfigurationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseConfigurationTests.swift; sourceTree = "<group>"; };
563EF414215F87EB007DAACD /* OrderedDictionary.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OrderedDictionary.swift; sourceTree = "<group>"; };
563EF42C2161180D007DAACD /* AssociationAggregate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AssociationAggregate.swift; sourceTree = "<group>"; };
@@ -621,6 +632,7 @@
5687359E1CEDE16C009B9116 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = "<group>"; };
56894F742606576600268F4D /* FoundationDecimalTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDecimalTests.swift; sourceTree = "<group>"; };
56894F94260657D600268F4D /* Decimal.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Decimal.swift; sourceTree = "<group>"; };
568C3F792A5AB2C300A2309D /* ForeignKeyDefinitionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ForeignKeyDefinitionTests.swift; sourceTree = "<group>"; };
568D13182207213E00674B58 /* SQLQueryGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLQueryGenerator.swift; sourceTree = "<group>"; };
568EB71829211E0700E59445 /* DatabaseSnapshotPool.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotPool.swift; sourceTree = "<group>"; };
568EB71D2921234800E59445 /* DatabaseSnapshotPoolTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotPoolTests.swift; sourceTree = "<group>"; };
@@ -785,6 +797,14 @@
56F61DD0283D344D00AF9884 /* GRDBTests-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = "GRDBTests-Bridging-Header.h"; path = "GRDBTests/GRDBTests-Bridging-Header.h"; sourceTree = "<group>"; };
56F61DD3283D344E00AF9884 /* getThreadsCount.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = getThreadsCount.h; sourceTree = "<group>"; };
56F61DD4283D344E00AF9884 /* getThreadsCount.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = getThreadsCount.c; sourceTree = "<group>"; };
56F89DF62A57EAA9002FE2AA /* ColumnDefinition.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ColumnDefinition.swift; sourceTree = "<group>"; };
56F89DFB2A57EAEA002FE2AA /* ForeignKeyDefinition.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ForeignKeyDefinition.swift; sourceTree = "<group>"; };
56F89DFD2A57EB19002FE2AA /* IndexDefinition.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IndexDefinition.swift; sourceTree = "<group>"; };
56F89DFF2A57EB5C002FE2AA /* TableAlteration.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableAlteration.swift; sourceTree = "<group>"; };
56F89E012A57EB87002FE2AA /* Database+SchemaDefinition.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Database+SchemaDefinition.swift"; sourceTree = "<group>"; };
56F89E0B2A57EC16002FE2AA /* SQLTableGenerator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLTableGenerator.swift; sourceTree = "<group>"; };
56F89E0D2A57EC2B002FE2AA /* SQLColumnGenerator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLColumnGenerator.swift; sourceTree = "<group>"; };
56F89E142A585C0B002FE2AA /* SQLTableAlterationGenerator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLTableAlterationGenerator.swift; sourceTree = "<group>"; };
56FA0C2F28B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+Upsert.swift"; sourceTree = "<group>"; };
56FA0C3828B20ABE00B2DFF7 /* PersistableRecord+Upsert.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "PersistableRecord+Upsert.swift"; sourceTree = "<group>"; };
56FBFED82210731A00945324 /* SQLRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLRequest.swift; sourceTree = "<group>"; };
@@ -1009,6 +1029,7 @@
56012B542573EED000B4925B /* CommonTableExpressionTests.swift */,
56EA63C4209C7CE3009715B8 /* DerivableRequestTests.swift */,
56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */,
568C3F792A5AB2C300A2309D /* ForeignKeyDefinitionTests.swift */,
56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */,
5698AC021D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift */,
563EF45221631E21007DAACD /* QueryInterfacePromiseTests.swift */,
@@ -1172,6 +1193,11 @@
5656A8142295AF75001FF3FF /* Schema */ = {
isa = PBXGroup;
children = (
56F89DF62A57EAA9002FE2AA /* ColumnDefinition.swift */,
56F89E012A57EB87002FE2AA /* Database+SchemaDefinition.swift */,
56F89DFB2A57EAEA002FE2AA /* ForeignKeyDefinition.swift */,
56F89DFD2A57EB19002FE2AA /* IndexDefinition.swift */,
56F89DFF2A57EB5C002FE2AA /* TableAlteration.swift */,
566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */,
5698AC771DA37DCB0056AF8C /* VirtualTableModule.swift */,
);
@@ -1181,8 +1207,12 @@
5656A8162295AFD6001FF3FF /* SQLGeneration */ = {
isa = PBXGroup;
children = (
56F89E0D2A57EC2B002FE2AA /* SQLColumnGenerator.swift */,
5653EC0B2098738B00F46237 /* SQLGenerationContext.swift */,
563CBBE02A595131008905CE /* SQLIndexGenerator.swift */,
568D13182207213E00674B58 /* SQLQueryGenerator.swift */,
56F89E142A585C0B002FE2AA /* SQLTableAlterationGenerator.swift */,
56F89E0B2A57EC16002FE2AA /* SQLTableGenerator.swift */,
);
path = SQLGeneration;
sourceTree = "<group>";
@@ -1963,6 +1993,7 @@
56D496C11D81373A008276D7 /* DatabaseQueueBackupTests.swift in Sources */,
562393721DEE104400A6B01F /* MapCursorTests.swift in Sources */,
56D496571D81303E008276D7 /* FoundationDateComponentsTests.swift in Sources */,
568C3F7A2A5AB2C300A2309D /* ForeignKeyDefinitionTests.swift in Sources */,
56D496701D81309E008276D7 /* RecordPrimaryKeyRowIDTests.swift in Sources */,
5622060C1E420EB3005860AC /* DatabaseQueueConcurrencyTests.swift in Sources */,
56E5D8041B4D424400430942 /* GRDBTestCase.swift in Sources */,
@@ -2051,6 +2082,7 @@
563082E42430B6BE00C14A05 /* DatabaseCancellable.swift in Sources */,
564CE59D21B7A8B500652B19 /* RemoveDuplicates.swift in Sources */,
5698AD351DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */,
56F89DFE2A57EB19002FE2AA /* IndexDefinition.swift in Sources */,
566B91131FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */,
5605F1591C672E4000235C62 /* CGFloat.swift in Sources */,
5674A7031F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */,
@@ -2070,6 +2102,7 @@
5674A6F41F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */,
5664759A1D97D8A000FF74B8 /* SQLCollection.swift in Sources */,
56D110DD28AFC8B400E64463 /* PersistableRecord+Save.swift in Sources */,
56F89E022A57EB87002FE2AA /* Database+SchemaDefinition.swift in Sources */,
567404881CEF84C8003ED5CC /* RowAdapter.swift in Sources */,
5653EB0320944C7C00F46237 /* BelongsToAssociation.swift in Sources */,
563363C41C942C37000BE133 /* DatabaseWriter.swift in Sources */,
@@ -2083,6 +2116,8 @@
4E13D2F32769B87F0037588C /* DatabaseBackupProgress.swift in Sources */,
560A37A71C8FF6E500949E71 /* SerializedDatabase.swift in Sources */,
563B8FAC24A1CE43007A48C9 /* DatabasePublishers.swift in Sources */,
56F89E0C2A57EC16002FE2AA /* SQLTableGenerator.swift in Sources */,
56F89DFC2A57EAEA002FE2AA /* ForeignKeyDefinition.swift in Sources */,
56FA0C3028B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift in Sources */,
5605F1691C672E4000235C62 /* NSString.swift in Sources */,
560D92401C672C3E00F4F92B /* DatabaseValueConvertible.swift in Sources */,
@@ -2102,6 +2137,7 @@
5657AB0F1D10899D006283EF /* URL.swift in Sources */,
560D924B1C672C4B00F4F92B /* TableRecord.swift in Sources */,
56DAA2DB1DE9C827006E10C8 /* Cursor.swift in Sources */,
56F89E152A585C0B002FE2AA /* SQLTableAlterationGenerator.swift in Sources */,
56AFEF2F29969F6E00CA1E51 /* TransactionClock.swift in Sources */,
5674A6EB1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */,
56D91AA92205F2F100770D8D /* DatabasePromise.swift in Sources */,
@@ -2117,6 +2153,7 @@
5659F4881EA8D94E004A4992 /* Utils.swift in Sources */,
566BE71E2342542F00A8254B /* LockedBox.swift in Sources */,
56A238931B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */,
56F89DF72A57EAA9002FE2AA /* ColumnDefinition.swift in Sources */,
5611620825757583007AAF99 /* JoinAssociation.swift in Sources */,
5695311F1C907A8C00CF1A2B /* DatabaseSchemaCache.swift in Sources */,
560233C42724234F00529DF3 /* SharedValueObservation.swift in Sources */,
@@ -2124,8 +2161,10 @@
568D131F2207213E00674B58 /* SQLQueryGenerator.swift in Sources */,
5605F15D1C672E4000235C62 /* DatabaseDateComponents.swift in Sources */,
56894FB72606589700268F4D /* Decimal.swift in Sources */,
56F89E002A57EB5C002FE2AA /* TableAlteration.swift in Sources */,
56B964B91DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */,
56FBFEDA2210731A00945324 /* SQLRequest.swift in Sources */,
56F89E0E2A57EC2B002FE2AA /* SQLColumnGenerator.swift in Sources */,
563363C01C942C04000BE133 /* DatabaseReader.swift in Sources */,
564CE43121AA901800652B19 /* ValueConcurrentObserver.swift in Sources */,
5605F1651C672E4000235C62 /* NSNull.swift in Sources */,
@@ -2146,6 +2185,7 @@
5605F1671C672E4000235C62 /* NSNumber.swift in Sources */,
56E9FADA221053DD00C703A8 /* SQL.swift in Sources */,
56717271261C68E900423B6F /* CaseInsensitiveIdentifier.swift in Sources */,
563CBBE12A595131008905CE /* SQLIndexGenerator.swift in Sources */,
C96C0F2B2084A442006B2981 /* SQLiteDateParser.swift in Sources */,
56781B0B243F86E600650A83 /* Refinable.swift in Sources */,
56A238871B9C75030082EB20 /* Row.swift in Sources */,
+44 -17
View File
@@ -354,13 +354,13 @@ extension Database {
// FIXME: We ignore the exception, and consider all INTEGER primary
// keys as aliases for the rowid:
if pkColumn.type.uppercased() == "INTEGER" {
primaryKey = .rowID(pkColumn.name)
primaryKey = .rowID(pkColumn)
} else {
primaryKey = try .regular([pkColumn.name], tableHasRowID: tableHasRowID(table))
primaryKey = try .regular([pkColumn], tableHasRowID: tableHasRowID(table))
}
default:
// Multi-columns primary key
primaryKey = try .regular(pkColumns.map(\.name), tableHasRowID: tableHasRowID(table))
primaryKey = try .regular(pkColumns, tableHasRowID: tableHasRowID(table))
}
schemaCache[table.schemaID].set(primaryKey: .value(primaryKey), forTable: table.name)
@@ -858,8 +858,22 @@ public struct ColumnInfo: FetchableRecord {
///
/// The casing of this string depends on the SQLite version: make sure you
/// process this string in a case-insensitive way.
///
/// The type is the empty string when the column has no declared type.
public let type: String
/// The column data type (nil when the column has no declared type).
///
/// The casing of the raw value depends on the SQLite version: make sure
/// you process the result in a case-insensitive way.
var columnType: Database.ColumnType? {
if type.isEmpty {
return nil
} else {
return Database.ColumnType(rawValue: type)
}
}
/// A boolean value indicating if the column is constrained to be not null.
public let isNotNull: Bool
@@ -1150,22 +1164,22 @@ public struct PrimaryKeyInfo {
/// An INTEGER PRIMARY KEY column that aliases the Row ID.
/// Associated string is the column name.
case rowID(String)
case rowID(ColumnInfo)
/// Any primary key, but INTEGER PRIMARY KEY.
/// Associated strings are column names.
case regular(columns: [String], tableHasRowID: Bool)
case regular(columnInfos: [ColumnInfo], tableHasRowID: Bool)
}
private let impl: Impl
static func rowID(_ column: String) -> PrimaryKeyInfo {
PrimaryKeyInfo(impl: .rowID(column))
static func rowID(_ columnInfo: ColumnInfo) -> PrimaryKeyInfo {
PrimaryKeyInfo(impl: .rowID(columnInfo))
}
static func regular(_ columns: [String], tableHasRowID: Bool) -> PrimaryKeyInfo {
assert(!columns.isEmpty)
return PrimaryKeyInfo(impl: .regular(columns: columns, tableHasRowID: tableHasRowID))
static func regular(_ columnInfos: [ColumnInfo], tableHasRowID: Bool) -> PrimaryKeyInfo {
assert(!columnInfos.isEmpty)
return PrimaryKeyInfo(impl: .regular(columnInfos: columnInfos, tableHasRowID: tableHasRowID))
}
static let hiddenRowID = PrimaryKeyInfo(impl: .hiddenRowID)
@@ -1175,21 +1189,34 @@ public struct PrimaryKeyInfo {
switch impl {
case .hiddenRowID:
return [Column.rowID.name]
case let .rowID(column):
return [column]
case let .regular(columns: columns, tableHasRowID: _):
return columns
case let .rowID(columnInfo):
return [columnInfo.name]
case let .regular(columnInfos: columnInfos, tableHasRowID: _):
return columnInfos.map(\.name)
}
}
/// The columns in the primary key. Nil if the primary key is the
/// hidden rowID. Never empty otherwise.
var columnInfos: [ColumnInfo]? {
switch impl {
case .hiddenRowID:
return nil
case let .rowID(columnInfo):
return [columnInfo]
case let .regular(columnInfos: columnInfos, tableHasRowID: _):
return columnInfos
}
}
/// When not nil, the name of the column that contains the
/// `INTEGER PRIMARY KEY`.
public var rowIDColumn: String? {
switch impl {
case .hiddenRowID:
return nil
case .rowID(let column):
return column
case .rowID(let columnInfo):
return columnInfo.name
case .regular:
return nil
}
@@ -1216,7 +1243,7 @@ public struct PrimaryKeyInfo {
return true
case .rowID:
return true
case let .regular(columns: _, tableHasRowID: tableHasRowID):
case let .regular(columnInfos: _, tableHasRowID: tableHasRowID):
return tableHasRowID
}
}
+25 -73
View File
@@ -860,31 +860,16 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
self.trace = trace
if options.isEmpty || trace == nil {
#if os(Linux)
sqlite3_trace(sqliteConnection, nil)
#else
sqlite3_trace_v2(sqliteConnection, 0, nil, nil)
#endif
return
}
// sqlite3_trace_v2 and sqlite3_expanded_sql were introduced in SQLite 3.14.0
// http://www.sqlite.org/changes.html#version_3_14
#if os(Linux)
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_trace(sqliteConnection, { (dbPointer, sql) in
guard let sql = sql.map(String.init(cString:)) else { return }
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
db.trace?(Database.TraceEvent.statement(TraceEvent.Statement(impl: .trace_v1(sql))))
}, dbPointer)
#else
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_trace_v2(sqliteConnection, CUnsignedInt(bitPattern: options.rawValue), { (mask, dbPointer, p, x) in
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
db.trace_v2(CInt(bitPattern: mask), p, x, sqlite3_expanded_sql)
return SQLITE_OK
}, dbPointer)
#endif
}
// Precondition: configuration.trace != nil
@@ -900,26 +885,22 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
case SQLITE_TRACE_STMT:
if let sqliteStatement = p, let unexpandedSQL = x {
let statement = TraceEvent.Statement(
impl: .trace_v2(
sqliteStatement: OpaquePointer(sqliteStatement),
unexpandedSQL: UnsafePointer(unexpandedSQL.assumingMemoryBound(to: CChar.self)),
sqlite3_expanded_sql: sqlite3_expanded_sql,
publicStatementArguments: configuration.publicStatementArguments))
sqliteStatement: OpaquePointer(sqliteStatement),
unexpandedSQL: UnsafePointer(unexpandedSQL.assumingMemoryBound(to: CChar.self)),
sqlite3_expanded_sql: sqlite3_expanded_sql,
publicStatementArguments: configuration.publicStatementArguments)
trace(TraceEvent.statement(statement))
}
case SQLITE_TRACE_PROFILE:
if let sqliteStatement = p, let durationP = x?.assumingMemoryBound(to: Int64.self) {
let statement = TraceEvent.Statement(
impl: .trace_v2(
sqliteStatement: OpaquePointer(sqliteStatement),
unexpandedSQL: nil,
sqlite3_expanded_sql: sqlite3_expanded_sql,
publicStatementArguments: configuration.publicStatementArguments))
sqliteStatement: OpaquePointer(sqliteStatement),
unexpandedSQL: nil,
sqlite3_expanded_sql: sqlite3_expanded_sql,
publicStatementArguments: configuration.publicStatementArguments)
let duration = TimeInterval(durationP.pointee) / 1.0e9
#if !os(Linux)
trace(TraceEvent.profile(statement: statement, duration: duration))
#endif
}
default:
break
@@ -1801,6 +1782,7 @@ extension Database {
/// The SQL for the column type (`"TEXT"`, `"BLOB"`, etc.)
public let rawValue: String
// TODO: GRDB7 make it an failable initializer that returns nil when rawValue is empty (or blank).
/// Creates an SQL column type.
public init(rawValue: String) {
self.rawValue = rawValue
@@ -1897,13 +1879,11 @@ extension Database {
/// Trace event code: `SQLITE_TRACE_STMT`.
public static let statement = TracingOptions(rawValue: SQLITE_TRACE_STMT)
#if !os(Linux)
/// The option that reports executed statements and the estimated
/// duration that the statement took to run.
///
/// Trace event code: `SQLITE_TRACE_PROFILE`.
public static let profile = TracingOptions(rawValue: SQLITE_TRACE_PROFILE)
#endif
}
/// A trace event.
@@ -1914,17 +1894,11 @@ extension Database {
/// Information about an executed statement.
public struct Statement: CustomStringConvertible {
enum Impl {
case trace_v1(String)
case trace_v2(
sqliteStatement: SQLiteStatement,
unexpandedSQL: UnsafePointer<CChar>?,
sqlite3_expanded_sql: @convention(c) (OpaquePointer?) -> UnsafeMutablePointer<Int8>?,
publicStatementArguments: Bool) // See Configuration.publicStatementArguments
}
var impl: Impl
var sqliteStatement: SQLiteStatement
var unexpandedSQL: UnsafePointer<CChar>?
var sqlite3_expanded_sql: @convention(c) (OpaquePointer?) -> UnsafeMutablePointer<Int8>?
var publicStatementArguments: Bool // See Configuration.publicStatementArguments
#if !os(Linux)
/// The executed SQL, where bound parameters are not expanded.
///
/// For example:
@@ -1932,21 +1906,11 @@ extension Database {
/// ```sql
/// SELECT * FROM player WHERE email = ?
/// ```
public var sql: String { _sql }
#endif
var _sql: String {
switch impl {
case .trace_v1:
// Likely a GRDB bug: this api is not supposed to be available
fatalError("Unavailable statement SQL")
case let .trace_v2(sqliteStatement, unexpandedSQL, _, _):
if let unexpandedSQL {
return String(cString: unexpandedSQL).trimmedSQLStatement
} else {
return String(cString: sqlite3_sql(sqliteStatement)).trimmedSQLStatement
}
public var sql: String {
if let unexpandedSQL {
return String(cString: unexpandedSQL).trimmedSQLStatement
} else {
return String(cString: sqlite3_sql(sqliteStatement)).trimmedSQLStatement
}
}
@@ -1962,30 +1926,18 @@ extension Database {
/// information from leaking in unexpected locations, so use this
/// property with care.
public var expandedSQL: String {
switch impl {
case let .trace_v1(expandedSQL):
return expandedSQL
case let .trace_v2(sqliteStatement, _, sqlite3_expanded_sql, _):
guard let cString = sqlite3_expanded_sql(sqliteStatement) else {
return ""
}
defer { sqlite3_free(cString) }
return String(cString: cString).trimmedSQLStatement
guard let cString = sqlite3_expanded_sql(sqliteStatement) else {
return ""
}
defer { sqlite3_free(cString) }
return String(cString: cString).trimmedSQLStatement
}
public var description: String {
switch impl {
case let .trace_v1(expandedSQL):
if publicStatementArguments {
return expandedSQL
case let .trace_v2(_, _, _, publicStatementArguments):
if publicStatementArguments {
return expandedSQL
} else {
return _sql
}
} else {
return sql
}
}
}
+19 -21
View File
@@ -13,6 +13,9 @@ public final class DatabasePool {
@LockedBox var databaseSnapshotCount = 0
/// If Database Suspension is enabled, this array contains the necessary `NotificationCenter` observers.
private var suspensionObservers: [NSObjectProtocol] = []
// MARK: - Database Information
public var configuration: Configuration {
@@ -121,6 +124,9 @@ public final class DatabasePool {
}
deinit {
// Remove block-based Notification observers.
suspensionObservers.forEach(NotificationCenter.default.removeObserver(_:))
// Undo job done in setupMemoryManagement()
//
// https://developer.apple.com/library/mac/releasenotes/Foundation/RN-Foundation/index.html#10_11Error
@@ -169,7 +175,7 @@ public final class DatabasePool {
}
}
// @unchecked because of databaseSnapshotCount and readerPool
// @unchecked because of databaseSnapshotCount, readerPool and suspensionObservers
extension DatabasePool: @unchecked Sendable { }
extension DatabasePool {
@@ -345,29 +351,21 @@ extension DatabasePool: DatabaseReader {
private func setupSuspension() {
if configuration.observesSuspensionNotifications {
let center = NotificationCenter.default
center.addObserver(
self,
selector: #selector(DatabasePool.suspend(_:)),
name: Database.suspendNotification,
object: nil)
center.addObserver(
self,
selector: #selector(DatabasePool.resume(_:)),
name: Database.resumeNotification,
object: nil)
suspensionObservers.append(center.addObserver(
forName: Database.suspendNotification,
object: nil,
queue: nil,
using: { [weak self] _ in self?.suspend() }
))
suspensionObservers.append(center.addObserver(
forName: Database.resumeNotification,
object: nil,
queue: nil,
using: { [weak self] _ in self?.resume() }
))
}
}
@objc
private func suspend(_ notification: Notification) {
suspend()
}
@objc
private func resume(_ notification: Notification) {
resume()
}
// MARK: - Reading from Database
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
+21 -20
View File
@@ -7,6 +7,9 @@ import UIKit
public final class DatabaseQueue {
private let writer: SerializedDatabase
/// If Database Suspension is enabled, this array contains the necessary `NotificationCenter` observers.
private var suspensionObservers: [NSObjectProtocol] = []
// MARK: - Configuration
public var configuration: Configuration {
@@ -100,6 +103,9 @@ public final class DatabaseQueue {
}
deinit {
// Remove block-based Notification observers.
suspensionObservers.forEach(NotificationCenter.default.removeObserver(_:))
// Undo job done in setupMemoryManagement()
//
// https://developer.apple.com/library/mac/releasenotes/Foundation/RN-Foundation/index.html#10_11Error
@@ -108,6 +114,9 @@ public final class DatabaseQueue {
}
}
// @unchecked because of suspensionObservers
extension DatabaseQueue: @unchecked Sendable { }
extension DatabaseQueue {
// MARK: - Memory management
@@ -189,29 +198,21 @@ extension DatabaseQueue: DatabaseReader {
private func setupSuspension() {
if configuration.observesSuspensionNotifications {
let center = NotificationCenter.default
center.addObserver(
self,
selector: #selector(DatabaseQueue.suspend(_:)),
name: Database.suspendNotification,
object: nil)
center.addObserver(
self,
selector: #selector(DatabaseQueue.resume(_:)),
name: Database.resumeNotification,
object: nil)
suspensionObservers.append(center.addObserver(
forName: Database.suspendNotification,
object: nil,
queue: nil,
using: { [weak self] _ in self?.suspend() }
))
suspensionObservers.append(center.addObserver(
forName: Database.resumeNotification,
object: nil,
queue: nil,
using: { [weak self] _ in self?.resume() }
))
}
}
@objc
private func suspend(_ notification: Notification) {
suspend()
}
@objc
private func resume(_ notification: Notification) {
resume()
}
// MARK: - Reading from Database
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
+4 -2
View File
@@ -778,7 +778,8 @@ public protocol TransactionObserver: AnyObject {
/// - note: The event is only valid for the duration of this method call.
/// If you need to keep it longer, store a copy: `event.copy()`.
///
/// - precondition: This method must not access the database.
/// - precondition: This method must not access the observed writer
/// database connection.
func databaseDidChange(with event: DatabaseEvent)
/// Called when a transaction is about to be committed.
@@ -786,7 +787,8 @@ public protocol TransactionObserver: AnyObject {
/// The transaction observer has an opportunity to rollback pending changes
/// by throwing an error from this method.
///
/// - precondition: This method must not access the database.
/// - precondition: This method must not access the observed writer
/// database connection.
/// - throws: The eventual error that rollbacks pending changes.
func databaseWillCommit() throws
+15 -6
View File
@@ -16,7 +16,7 @@ try db.create(table: "player") { t in
When you plan to evolve the schema as new versions of your application ship, wrap all schema changes in <doc:Migrations>.
Prefer Swift methods over raw SQL queries. They allow the compiler to check if a schema change is available on the target operating system. Only use a raw SQL query when no Swift method exist (when creating views or triggers, for example).
Prefer Swift methods over raw SQL queries. They allow the compiler to check if a schema change is available on the target operating system. Only use a raw SQL query when no Swift method exist (when creating triggers, for example).
When a schema change is not directly supported by SQLite, or not available on the target operating system, database tables have to be recreated. See <doc:Migrations> for the detailed procedure.
@@ -135,8 +135,8 @@ try db.create(table: "team") { t in
try db.create(table: "membership") { t in
// Composite primary key
t.primaryKey {
t.column("playerId", .integer).references("player")
t.column("teamId", .text).references("team")
t.belongsTo("player")
t.belongsTo("team")
}
t.column("role", .text).notNull()
}
@@ -241,10 +241,10 @@ Unique indexes makes sure SQLite prevents the insertion of conflicting rows:
// RECOMMENDED
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.belongsTo("team").notNull()
t.column("position", .integer).notNull()
// Players must have distinct names
t.column("name", .text).unique()
t.column("teamId", .integer).notNull().references("team")
t.column("position", .integer).notNull()
}
// One single player at any given position in a team
@@ -307,7 +307,7 @@ try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
// A player must refer to an existing team
t.column("teamId", .integer).notNull().references("team")
t.belongsTo("team").notNull()
}
// REQUIRES EXTRA CONFIGURATION
@@ -319,6 +319,8 @@ try db.create(table: "player") { t in
}
```
See ``TableDefinition/belongsTo(_:inTable:onDelete:onUpdate:deferred:indexed:)`` for more information about the creation of foreign keys.
GRDB [Associations](https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md) are automatically configured from foreign keys declared in the database schema:
```swift
@@ -372,6 +374,13 @@ extension Team: TableRecord {
- ``TableOptions``
- ``VirtualTableModule``
### Database Views
- ``Database/create(view:options:columns:as:)``
- ``Database/create(view:options:columns:asLiteral:)``
- ``Database/drop(view:)``
- ``ViewOptions``
### Database Indexes
- ``Database/create(indexOn:columns:options:condition:)``
@@ -97,7 +97,7 @@ do {
- Note: All callbacks are called in the writer dispatch queue, and serialized with all database updates.
- Note: The `databaseDidChange` and `databaseWillCommit` callbacks must not touch the SQLite database. This limitation does not apply to `databaseDidCommit` and `databaseDidRollback` which can use their database argument.
- Note: The `databaseDidChange` and `databaseWillCommit` callbacks must not access the observed writer database connection in any way. This limitation does not apply to `databaseDidCommit` and `databaseDidRollback` which can use their database argument.
## Filtering Database Events
+1 -4
View File
@@ -26,10 +26,7 @@ migrator.registerMigration("Create authors") { db in
migrator.registerMigration("Add books and author.birthYear") { db in
try db.create(table: "book") { t in
t.autoIncrementedPrimaryKey("id")
t.column("authorId", .integer)
.notNull()
.indexed()
.references("author", onDelete: .cascade)
t.belongsTo("author").notNull()
t.column("title", .text).notNull()
}
@@ -31,10 +31,8 @@ migrator.registerMigration("createLibrary") { db in
try db.create(table: "book") { t in
t.autoIncrementedPrimaryKey("id")
t.column("title", .text).notNull() // (5)
t.column("authorId", .integer) // (6)
t.belongsTo("author", onDelete: .cascade) // (6)
.notNull() // (7)
.indexed() // (8)
.references("author", onDelete: .cascade) // (9)
}
}
@@ -46,10 +44,8 @@ try migrator.migrate(dbQueue)
3. An author must have a name.
4. The country of an author is not always known.
5. A book must have a title.
6. The `book.authorId` column is used to link a book to the author it belongs to.
6. The `book.authorId` column is used to link a book to the author it belongs to. This column is indexed in order to ease the selection of an author's books. A foreign key is defined from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book refers to a missing author. The `onDelete: .cascade` option has SQLite automatically delete all of an author's books when that author is deleted. See [Foreign Key Actions](https://sqlite.org/foreignkeys.html#fk_actions) for more information.
7. The `book.authorId` column is not null so that SQLite guarantees that all books have an author.
8. The `book.authorId` column is indexed in order to ease the selection of an author's books.
9. We define a foreign key from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book can refer to a missing author. On top of that, the `onDelete: .cascade` option has SQLite automatically delete all of an author's books when that author is deleted. See [Foreign Key Actions](https://sqlite.org/foreignkeys.html#fk_actions) for more information.
Thanks to this database schema, the application will always process *consistent data*, no matter how wrong the Swift code can get. Even after a hard crash, all books will have an author, a non-nil title, etc.
+1 -1
View File
@@ -446,7 +446,7 @@ public struct DatabaseMigrator {
//
// So let's create a "regular" temporary database:
let tmpURL = URL(fileURLWithPath: NSTemporaryDirectory())
.appendingPathComponent(ProcessInfo().globallyUniqueString)
.appendingPathComponent(ProcessInfo.processInfo.globallyUniqueString)
defer {
try? FileManager().removeItem(at: tmpURL)
}
@@ -28,26 +28,23 @@
/// }
/// try db.create(table: "book") { t in
/// t.autoIncrementedPrimaryKey("id")
/// t.column("authorId", .integer) // (2)
/// t.belongsTo("author", onDelete: .cascade) // (2)
/// .notNull() // (3)
/// .indexed() // (4)
/// .references("author", onDelete: .cascade) // (5)
/// t.column("title", .text)
/// }
/// ```
///
/// 1. The author table has a primary key.
/// 2. The `book.authorId` column is used to link a book to the author it
/// belongs to.
/// belongs to. This column is indexed in order to ease the selection of
/// an author's books. A foreign key is defined from `book.authorId`
/// column to `authors.id`, so that SQLite guarantees that no book refers
/// to a missing author. The `onDelete: .cascade` option has SQLite
/// automatically delete all of an author's books when that author is
/// deleted. See <https://sqlite.org/foreignkeys.html#fk_actions> for
/// more information.
/// 3. Make the `book.authorId` column not null if you want SQLite to guarantee
/// that all books have an author.
/// 4. Create an index on the `book.authorId` column in order to ease the
/// selection of an author's books.
/// 5. Create a foreign key from `book.authorId` column to `author.id`, so that
/// SQLite guarantees that no book refers to a missing author. The
/// `onDelete: .cascade` option has SQLite automatically delete all of an
/// author's books when that author is deleted.
/// See <https://sqlite.org/foreignkeys.html#fk_actions> for more information.
///
/// The example above uses auto-incremented primary keys. But generally
/// speaking, all primary keys are supported.
@@ -28,26 +28,22 @@
/// }
/// try db.create(table: "book") { t in
/// t.autoIncrementedPrimaryKey("id")
/// t.column("authorId", .integer) // (2)
/// t.belongsTo("author", onDelete: .cascade) // (2)
/// .notNull() // (3)
/// .indexed() // (4)
/// .references("author", onDelete: .cascade) // (5)
/// t.column("title", .text)
/// }
/// ```
///
/// 1. The author table has a primary key.
/// 2. The `book.authorId` column is used to link a book to the author it
/// belongs to.
/// belongs to. This column is indexed in order to ease the selection of
/// an author's books. A foreign key is defined from `book.authorId`
/// column to `authors.id`, so that SQLite guarantees that no book refers
/// to a missing author. The `onDelete: .cascade` option has SQLite
/// automatically delete all of an author's books when that author is
/// deleted. See <https://sqlite.org/foreignkeys.html#fk_actions> for
/// more information.
/// 3. Make the `book.authorId` column not null if you want SQLite to guarantee
/// that all books have an author.
/// 4. Create an index on the `book.authorId` column in order to ease the
/// selection of an author's books.
/// 5. Create a foreign key from `book.authorId` column to `author.id`, so that
/// SQLite guarantees that no book refers to a missing author. The
/// `onDelete: .cascade` option has SQLite automatically delete all of an
/// author's books when that author is deleted.
/// See <https://sqlite.org/foreignkeys.html#fk_actions> for more information.
///
/// The example above uses auto-incremented primary keys. But generally
/// speaking, all primary keys are supported.
@@ -29,10 +29,9 @@
/// }
/// try db.create(table: "demographics") { t in
/// t.autoIncrementedPrimaryKey("id")
/// t.column("countryCode", .text) // (2)
/// t.belongsTo("country", onDelete: .cascade) // (2)
/// .notNull() // (3)
/// .unique() // (4)
/// .references("country", onDelete: .cascade) // (5)
/// t.column("population", .integer)
/// t.column("density", .double)
/// }
@@ -40,16 +39,17 @@
///
/// 1. The country table has a primary key.
/// 2. The `demographics.countryCode` column is used to link a demographic
/// profile to the country it belongs to.
/// profile to the country it belongs to. This column is indexed in order
/// to ease the selection of the demographics of a country. A foreign key
/// is defined from `demographics.countryCode` column to `country.code`,
/// so that SQLite guarantees that no profile refers to a missing
/// country. The `onDelete: .cascade` option has SQLite automatically
/// delete a profile when its country is deleted. See
/// <https://sqlite.org/foreignkeys.html#fk_actions> for more information.
/// 3. Make the `demographics.countryCode` column not null if you want SQLite to
/// guarantee that all profiles are linked to a country.
/// 4. Create a unique index on the `demographics.countryCode` column in order
/// to guarantee the unicity of any country's demographics.
/// 5. Create a foreign key from `demographics.countryCode` column to
/// `country.code`, so that SQLite guarantees that no profile refers to a
/// missing country. The `onDelete: .cascade` option has SQLite automatically
/// delete a profile when its country is deleted.
/// See <https://sqlite.org/foreignkeys.html#fk_actions> for more information.
///
/// The example above uses a string primary for the country table. But generally
/// speaking, all primary keys are supported.
+1 -1
View File
@@ -848,7 +848,7 @@ extension SQLExpression {
///
/// try "foo'bar".databaseValue.quotedSQL(db) // "'foo''bar'""
func quotedSQL(_ db: Database) throws -> String {
let context = SQLGenerationContext(db, argumentsSink: .forRawSQL)
let context = SQLGenerationContext(db, argumentsSink: .literalValues)
return try sql(context)
}
@@ -0,0 +1,145 @@
enum SQLColumnGenerator {
case columnDefinition(ColumnDefinition)
case columnLiteral(SQL)
/// - parameter tableName: The name of the table that contains
/// the column.
/// - parameter primaryKeyColumns: A closure that returns the
/// primary key columns in the table that contains the column. If
/// the result is nil, the primary key is the hidden rowID.
func sql(
_ db: Database,
tableName: String,
primaryKeyColumns: () throws -> [SQLColumnDescriptor]?)
throws -> String
{
switch self {
case let .columnDefinition(column):
return try columnSQL(
db, column: column,
tableName: tableName,
primaryKeyColumns: primaryKeyColumns)
case let .columnLiteral(sqlLiteral):
let context = SQLGenerationContext(db, argumentsSink: .literalValues)
return try sqlLiteral.sql(context)
}
}
private func columnSQL(
_ db: Database,
column: ColumnDefinition,
tableName: String,
primaryKeyColumns: () throws -> [SQLColumnDescriptor]?)
throws -> String
{
var chunks: [String] = []
chunks.append(column.name.quotedDatabaseIdentifier)
if let type = column.type {
chunks.append(type.rawValue)
}
if let (conflictResolution, autoincrement) = column.primaryKey {
chunks.append("PRIMARY KEY")
if let conflictResolution {
chunks.append("ON CONFLICT")
chunks.append(conflictResolution.rawValue)
}
if autoincrement {
chunks.append("AUTOINCREMENT")
}
}
switch column.notNullConflictResolution {
case .none:
break
case .abort:
chunks.append("NOT NULL")
case let conflictResolution?:
chunks.append("NOT NULL ON CONFLICT")
chunks.append(conflictResolution.rawValue)
}
switch column.indexing {
case .none:
break
case .unique(let conflictResolution):
switch conflictResolution {
case .abort:
chunks.append("UNIQUE")
default:
chunks.append("UNIQUE ON CONFLICT")
chunks.append(conflictResolution.rawValue)
}
case .index:
break
}
for checkConstraint in column.checkConstraints {
try chunks.append("CHECK (\(checkConstraint.quotedSQL(db)))")
}
if let defaultExpression = column.defaultExpression {
try chunks.append("DEFAULT \(defaultExpression.quotedSQL(db))")
}
if let collationName = column.collationName {
chunks.append("COLLATE")
chunks.append(collationName)
}
for constraint in column.foreignKeyConstraints {
chunks.append("REFERENCES")
if let column = constraint.destinationColumn {
// explicit referenced column names
chunks.append("""
\(constraint.destinationTable.quotedDatabaseIdentifier)\
(\(column.quotedDatabaseIdentifier))
""")
} else {
// implicit reference to primary key
let pkColumns: [String]
if constraint.destinationTable.lowercased() == tableName.lowercased() {
// autoreference
let primaryKeyColumns = try primaryKeyColumns() ?? [.rowID]
pkColumns = primaryKeyColumns.map(\.name)
} else {
pkColumns = try db.primaryKey(constraint.destinationTable).columns
}
chunks.append("""
\(constraint.destinationTable.quotedDatabaseIdentifier)\
(\(pkColumns.map(\.quotedDatabaseIdentifier).joined(separator: ", ")))
""")
}
if let deleteAction = constraint.deleteAction {
chunks.append("ON DELETE")
chunks.append(deleteAction.rawValue)
}
if let updateAction = constraint.updateAction {
chunks.append("ON UPDATE")
chunks.append(updateAction.rawValue)
}
if constraint.isDeferred {
chunks.append("DEFERRABLE INITIALLY DEFERRED")
}
}
if let constraint = column.generatedColumnConstraint {
try chunks.append("GENERATED ALWAYS AS (\(constraint.expression.quotedSQL(db)))")
let qualificationLiteral: String
switch constraint.qualification {
case .stored:
qualificationLiteral = "STORED"
case .virtual:
qualificationLiteral = "VIRTUAL"
}
chunks.append(qualificationLiteral)
}
return chunks.joined(separator: " ")
}
}
@@ -172,15 +172,21 @@ class StatementArgumentsSink {
private(set) var arguments: StatementArguments
private let rawSQL: Bool
/// A sink which does not accept any arguments.
static let forRawSQL = StatementArgumentsSink(rawSQL: true)
/// A sink which turns all argument values into SQL literals.
///
/// The `"WHERE name = \("O'Brien")"` SQL literal is turned into the
/// `WHERE name = 'O''Brien'` SQL.
static let literalValues = StatementArgumentsSink(rawSQL: true)
private init(rawSQL: Bool) {
self.arguments = []
self.rawSQL = rawSQL
}
/// A sink which accepts arguments
/// A sink which turns all argument values into `?` SQL parameters.
///
/// The `"WHERE name = \("O'Brien")"` SQL literal is turned into the
/// `WHERE name = ?` SQL.
convenience init() {
self.init(rawSQL: false)
}
@@ -0,0 +1,40 @@
struct SQLIndexGenerator {
let name: String
let table: String
let columns: [String]
let options: IndexOptions
let condition: SQLExpression?
func sql(_ db: Database) throws -> String {
var chunks: [String] = []
chunks.append("CREATE")
if options.contains(.unique) {
chunks.append("UNIQUE")
}
chunks.append("INDEX")
if options.contains(.ifNotExists) {
chunks.append("IF NOT EXISTS")
}
chunks.append(name.quotedDatabaseIdentifier)
chunks.append("ON")
chunks.append("""
\(table.quotedDatabaseIdentifier)(\
\(columns.map(\.quotedDatabaseIdentifier).joined(separator: ", "))\
)
""")
if let condition {
try chunks.append("WHERE \(condition.quotedSQL(db))")
}
return chunks.joined(separator: " ")
}
}
extension SQLIndexGenerator {
init(index: IndexDefinition) {
name = index.name
table = index.table
columns = index.columns
options = index.options
condition = index.condition
}
}
@@ -0,0 +1,84 @@
struct SQLTableAlterationGenerator {
private enum TableAlterationKind {
case addColumn(SQLColumnGenerator)
case addIndex(SQLIndexGenerator)
case renameColumn(old: String, new: String)
case dropColumn(String)
}
private var name: String
private var alterations: [TableAlterationKind] = []
func sql(_ db: Database) throws -> String {
var statements: [String] = []
for alteration in alterations {
switch alteration {
case let .addColumn(column):
var chunks: [String] = []
chunks.append("ALTER TABLE")
chunks.append(name.quotedDatabaseIdentifier)
chunks.append("ADD COLUMN")
let sql = try column.sql(db, tableName: name, primaryKeyColumns: {
try db.primaryKey(name).columnInfos.map { columnInfos in
columnInfos.map { SQLColumnDescriptor($0) }
}
})
chunks.append(sql)
let statement = chunks.joined(separator: " ")
statements.append(statement)
case let .addIndex(index):
try statements.append(index.sql(db))
case let .renameColumn(oldName, newName):
var chunks: [String] = []
chunks.append("ALTER TABLE")
chunks.append(name.quotedDatabaseIdentifier)
chunks.append("RENAME COLUMN")
chunks.append(oldName.quotedDatabaseIdentifier)
chunks.append("TO")
chunks.append(newName.quotedDatabaseIdentifier)
let statement = chunks.joined(separator: " ")
statements.append(statement)
case let .dropColumn(column):
var chunks: [String] = []
chunks.append("ALTER TABLE")
chunks.append(name.quotedDatabaseIdentifier)
chunks.append("DROP COLUMN")
chunks.append(column.quotedDatabaseIdentifier)
let statement = chunks.joined(separator: " ")
statements.append(statement)
}
}
return statements.joined(separator: "; ")
}
}
extension SQLTableAlterationGenerator {
init(_ tableAlteration: TableAlteration) {
self.name = tableAlteration.name
self.alterations = []
for alteration in tableAlteration.alterations {
switch alteration {
case let .add(column):
alterations.append(.addColumn(.columnDefinition(column)))
if let indexDefinition = column.indexDefinition(in: name) {
alterations.append(.addIndex(SQLIndexGenerator(index: indexDefinition)))
}
case let .addColumnLiteral(sql):
alterations.append(.addColumn(.columnLiteral(sql)))
case let .rename(old: oldName, new: newName):
alterations.append(.renameColumn(old: oldName, new: newName))
case let .drop(column):
alterations.append(.dropColumn(column))
}
}
}
}
@@ -0,0 +1,476 @@
struct SQLTableGenerator {
var name: String
var options: TableOptions
var columnGenerators: [SQLColumnGenerator]
/// Used for auto-referencing foreign keys: we need to know the columns
/// of the primary key before they exist in the database schema, hence
/// the name of "forward" primary key columns.
///
/// If nil, the primary key is the hidden rowID.
var forwardPrimaryKeyColumns: [SQLColumnDescriptor]?
var primaryKeyConstraint: KeyConstraint?
var uniqueKeyConstraints: [KeyConstraint]
var foreignKeyConstraints: [SQLForeignKeyConstraint]
var checkConstraints: [SQLExpression]
var literalConstraints: [SQL]
var indexGenerators: [SQLIndexGenerator]
struct KeyConstraint {
var columns: [String]
var conflictResolution: Database.ConflictResolution?
}
func sql(_ db: Database) throws -> String {
var statements: [String] = []
do {
var chunks: [String] = []
chunks.append("CREATE")
if options.contains(.temporary) {
chunks.append("TEMPORARY")
}
chunks.append("TABLE")
if options.contains(.ifNotExists) {
chunks.append("IF NOT EXISTS")
}
chunks.append(name.quotedDatabaseIdentifier)
do {
var items: [String] = []
try items.append(contentsOf: columnGenerators.map {
try $0.sql(db, tableName: name, primaryKeyColumns: { forwardPrimaryKeyColumns })
})
if let constraint = primaryKeyConstraint {
var chunks: [String] = []
chunks.append("PRIMARY KEY")
chunks.append("(\(constraint.columns.map(\.quotedDatabaseIdentifier).joined(separator: ", ")))")
if let conflictResolution = constraint.conflictResolution {
chunks.append("ON CONFLICT")
chunks.append(conflictResolution.rawValue)
}
items.append(chunks.joined(separator: " "))
}
for constraint in uniqueKeyConstraints {
var chunks: [String] = []
chunks.append("UNIQUE")
chunks.append("(\(constraint.columns.map(\.quotedDatabaseIdentifier).joined(separator: ", ")))")
if let conflictResolution = constraint.conflictResolution {
chunks.append("ON CONFLICT")
chunks.append(conflictResolution.rawValue)
}
items.append(chunks.joined(separator: " "))
}
for constraint in foreignKeyConstraints {
var chunks: [String] = []
chunks.append("FOREIGN KEY")
chunks.append("(\(constraint.columns.map(\.quotedDatabaseIdentifier).joined(separator: ", ")))")
chunks.append("REFERENCES")
if let destinationColumns = constraint.destinationColumns {
chunks.append("""
\(constraint.destinationTable.quotedDatabaseIdentifier)(\
\(destinationColumns.map(\.quotedDatabaseIdentifier).joined(separator: ", "))\
)
""")
} else if constraint.destinationTable.lowercased() == name.lowercased() {
// autoreference
let forwardPrimaryKeyColumns = forwardPrimaryKeyColumns ?? [.rowID]
chunks.append("""
\(constraint.destinationTable.quotedDatabaseIdentifier)(\
\(forwardPrimaryKeyColumns.map(\.name.quotedDatabaseIdentifier).joined(separator: ", "))\
)
""")
} else {
let primaryKey = try db.primaryKey(constraint.destinationTable)
chunks.append("""
\(constraint.destinationTable.quotedDatabaseIdentifier)(\
\(primaryKey.columns.map(\.quotedDatabaseIdentifier).joined(separator: ", "))\
)
""")
}
if let deleteAction = constraint.deleteAction {
chunks.append("ON DELETE")
chunks.append(deleteAction.rawValue)
}
if let updateAction = constraint.updateAction {
chunks.append("ON UPDATE")
chunks.append(updateAction.rawValue)
}
if constraint.isDeferred {
chunks.append("DEFERRABLE INITIALLY DEFERRED")
}
items.append(chunks.joined(separator: " "))
}
for checkExpression in checkConstraints {
var chunks: [String] = []
try chunks.append("CHECK (\(checkExpression.quotedSQL(db)))")
items.append(chunks.joined(separator: " "))
}
for literal in literalConstraints {
let context = SQLGenerationContext(db, argumentsSink: .literalValues)
try items.append(literal.sql(context))
}
chunks.append("(\(items.joined(separator: ", ")))")
}
var tableOptions: [String] = []
#if GRDBCUSTOMSQLITE || GRDBCIPHER
if options.contains(.strict) {
tableOptions.append("STRICT")
}
#else
if #available(iOS 15.4, macOS 12.4, tvOS 15.4, watchOS 8.5, *) { // SQLite 3.37+
if options.contains(.strict) {
tableOptions.append("STRICT")
}
}
#endif
if options.contains(.withoutRowID) {
tableOptions.append("WITHOUT ROWID")
}
if !tableOptions.isEmpty {
chunks.append(tableOptions.joined(separator: ", "))
}
statements.append(chunks.joined(separator: " "))
}
let indexStatements = try indexGenerators.map { try $0.sql(db) }
statements.append(contentsOf: indexStatements)
return statements.joined(separator: "; ")
}
private struct ForeignKeyGenerator {
var columnNames: [String]
var columnGenerators: [SQLColumnGenerator]
var foreignKeyConstraint: SQLForeignKeyConstraint?
var indexGenerator: SQLIndexGenerator?
}
}
extension SQLTableGenerator {
init(_ db: Database, table: TableDefinition) throws {
var indexOptions: IndexOptions = []
if table.options.contains(.ifNotExists) { indexOptions.insert(.ifNotExists) }
func makeKeyConstraint(
_ db: Database,
constraint: TableDefinition.KeyConstraint,
forwardPrimaryKey: SQLPrimaryKeyDescriptor)
throws -> SQLTableGenerator.KeyConstraint
{
try SQLTableGenerator.KeyConstraint(
columns: constraint.components.flatMap { component -> [String] in
switch component {
case let .columnName(columnName):
return [columnName]
case let .columnDefinition(column):
return [column.name]
case let .foreignKeyDefinition(foreignKey):
return try Self.makeForeignKeyGenerator(
db, foreignKey: foreignKey,
originTable: table.name,
forwardPrimaryKey: forwardPrimaryKey,
indexOptions: indexOptions).columnNames
}
},
conflictResolution: constraint.conflictResolution)
}
var forwardPrimaryKeyColumns: [SQLColumnDescriptor]?
if let primaryKeyConstraint = table.primaryKeyConstraint {
forwardPrimaryKeyColumns = try Self.forwardPrimaryKeyColumns(
db, primaryKeyConstraint: primaryKeyConstraint,
originTable: table.name)
} else {
for component in table.columnComponents {
if case let .columnDefinition(column) = component, column.primaryKey != nil {
forwardPrimaryKeyColumns = [SQLColumnDescriptor(column)]
break
}
}
}
let forwardPrimaryKey = SQLPrimaryKeyDescriptor(
tableName: table.name,
primaryKeyColumns: forwardPrimaryKeyColumns)
var columnGenerators: [SQLColumnGenerator] = []
var foreignKeyConstraints: [SQLForeignKeyConstraint] = []
var indexGenerators: [SQLIndexGenerator] = []
for component in table.columnComponents {
switch component {
case let .columnDefinition(column):
columnGenerators.append(.columnDefinition(column))
case let .columnLiteral(sql):
columnGenerators.append(.columnLiteral(sql))
case let .foreignKeyDefinition(foreignKey):
let fkGenerator = try Self.makeForeignKeyGenerator(
db, foreignKey: foreignKey,
originTable: table.name,
forwardPrimaryKey: forwardPrimaryKey,
indexOptions: indexOptions)
columnGenerators.append(contentsOf: fkGenerator.columnGenerators)
if let indexGenerator = fkGenerator.indexGenerator {
indexGenerators.append(indexGenerator)
}
if let foreignKeyConstraint = fkGenerator.foreignKeyConstraint {
foreignKeyConstraints.append(foreignKeyConstraint)
}
case let .foreignKeyConstraint(constraint):
foreignKeyConstraints.append(constraint)
}
}
for columnGenerator in columnGenerators {
if case let .columnDefinition(column) = columnGenerator,
let index = column.indexDefinition(in: table.name, options: indexOptions)
{
indexGenerators.append(SQLIndexGenerator(index: index))
}
}
try self.init(
name: table.name,
options: table.options,
columnGenerators: columnGenerators,
forwardPrimaryKeyColumns: forwardPrimaryKeyColumns,
primaryKeyConstraint: table.primaryKeyConstraint.map {
try makeKeyConstraint(db, constraint: $0, forwardPrimaryKey: forwardPrimaryKey)
},
uniqueKeyConstraints: table.uniqueKeyConstraints.map {
try makeKeyConstraint(db, constraint: $0, forwardPrimaryKey: forwardPrimaryKey)
},
foreignKeyConstraints: foreignKeyConstraints,
checkConstraints: table.checkConstraints,
literalConstraints: table.literalConstraints,
indexGenerators: indexGenerators)
}
private static func forwardPrimaryKeyColumns(
_ db: Database,
primaryKeyConstraint: TableDefinition.KeyConstraint,
originTable: String)
throws -> [SQLColumnDescriptor]?
{
var forwardPrimaryKeyColumns: [SQLColumnDescriptor] = []
for component in primaryKeyConstraint.components {
switch component {
case let .columnDefinition(column):
forwardPrimaryKeyColumns.append(SQLColumnDescriptor(column))
case let .foreignKeyDefinition(foreignKey):
let fkGenerator = try makeForeignKeyGenerator(
db, foreignKey: foreignKey,
originTable: originTable,
forwardPrimaryKey: nil, // not known yet, since we're building it
indexOptions: [])
for columnGenerator in fkGenerator.columnGenerators {
switch columnGenerator {
case let .columnDefinition(column):
forwardPrimaryKeyColumns.append(SQLColumnDescriptor(column))
case .columnLiteral:
// Unknown column name
return nil
}
}
case let .columnName(name):
forwardPrimaryKeyColumns.append(SQLColumnDescriptor(name: name, type: nil))
}
}
return forwardPrimaryKeyColumns
}
private static func makeForeignKeyGenerator(
_ db: Database,
foreignKey: ForeignKeyDefinition,
originTable: String,
forwardPrimaryKey: SQLPrimaryKeyDescriptor?,
indexOptions: IndexOptions)
throws -> ForeignKeyGenerator
{
let destinationPrimaryKey: SQLPrimaryKeyDescriptor
if let table = foreignKey.table {
if let forwardPrimaryKey,
originTable.lowercased() == table.lowercased()
{
// autoreference
destinationPrimaryKey = forwardPrimaryKey
} else {
destinationPrimaryKey = try foreignKey.primaryKey(db)
}
} else {
if let forwardPrimaryKey,
originTable.singularized.lowercased() == foreignKey.name.singularized.lowercased()
{
// autoreference
destinationPrimaryKey = forwardPrimaryKey
} else {
destinationPrimaryKey = try foreignKey.primaryKey(db)
}
}
guard let primaryKeyColumns = destinationPrimaryKey.primaryKeyColumns else {
// Destination table has an hidden rowID primary key
let columnName = foreignKey.name + "Id"
let column = ColumnDefinition(name: columnName, type: .integer).references(
destinationPrimaryKey.tableName,
onDelete: foreignKey.deleteAction,
onUpdate: foreignKey.updateAction,
deferred: foreignKey.isDeferred)
if let notNullConflictResolution = foreignKey.notNullConflictResolution {
column.notNull(onConflict: notNullConflictResolution)
}
switch foreignKey.indexing {
case nil:
break
case .index:
column.indexed()
case .unique:
column.unique()
}
return ForeignKeyGenerator(
columnNames: [columnName],
columnGenerators: [SQLColumnGenerator.columnDefinition(column)],
foreignKeyConstraint: nil,
indexGenerator: nil)
}
assert(!primaryKeyColumns.isEmpty)
let columnNames = primaryKeyColumns.map {
foreignKey.name + $0.name.uppercasingFirstCharacter
}
if primaryKeyColumns.count == 1 {
// Destination table has a single column primary key
let pkColumn = primaryKeyColumns[0]
let columnName = columnNames[0]
let column = ColumnDefinition(name: columnName, type: pkColumn.type).references(
destinationPrimaryKey.tableName,
column: pkColumn.name,
onDelete: foreignKey.deleteAction,
onUpdate: foreignKey.updateAction,
deferred: foreignKey.isDeferred)
if let notNullConflictResolution = foreignKey.notNullConflictResolution {
column.notNull(onConflict: notNullConflictResolution)
}
switch foreignKey.indexing {
case nil:
break
case .index:
column.indexed()
case .unique:
column.unique()
}
return ForeignKeyGenerator(
columnNames: [columnName],
columnGenerators: [SQLColumnGenerator.columnDefinition(column)],
foreignKeyConstraint: nil,
indexGenerator: nil)
} else {
// Destination table has a composite primary key
let columnGenerators = zip(primaryKeyColumns, columnNames).map { pkColumn, columnName in
let column = ColumnDefinition(name: columnName, type: pkColumn.type)
if let notNullConflictResolution = foreignKey.notNullConflictResolution {
column.notNull(onConflict: notNullConflictResolution)
}
return SQLColumnGenerator.columnDefinition(column)
}
let foreignKeyConstraint = SQLForeignKeyConstraint(
columns: columnNames,
destinationTable: destinationPrimaryKey.tableName,
destinationColumns: nil,
deleteAction: foreignKey.deleteAction,
updateAction: foreignKey.updateAction,
isDeferred: foreignKey.isDeferred)
let indexGenerator: SQLIndexGenerator?
switch foreignKey.indexing {
case nil:
indexGenerator = nil
case .index:
indexGenerator = SQLIndexGenerator(
name: Database.defaultIndexName(on: originTable, columns: columnNames),
table: originTable,
columns: columnNames,
options: indexOptions,
condition: nil)
case .unique:
indexGenerator = SQLIndexGenerator(
name: Database.defaultIndexName(on: originTable, columns: columnNames),
table: originTable,
columns: columnNames,
options: indexOptions.union([.unique]),
condition: nil)
}
return ForeignKeyGenerator(
columnNames: columnNames,
columnGenerators: columnGenerators,
foreignKeyConstraint: foreignKeyConstraint,
indexGenerator: indexGenerator)
}
}
}
struct SQLColumnDescriptor {
static let rowID = SQLColumnDescriptor(name: Column.rowID.name, type: .integer)
var name: String
var type: Database.ColumnType?
}
extension SQLColumnDescriptor {
init(_ column: ColumnInfo) {
self.init(
name: column.name,
type: column.columnType)
}
init(_ column: ColumnDefinition) {
self.init(name: column.name, type: column.type)
}
}
struct SQLForeignKeyConstraint {
var columns: [String]
var destinationTable: String
var destinationColumns: [String]?
var deleteAction: Database.ForeignKeyAction?
var updateAction: Database.ForeignKeyAction?
var isDeferred: Bool
}
struct SQLPrimaryKeyDescriptor {
/// The name of the forward-declared table
var tableName: String
/// If nil, the primary key is the hidden rowID.
var primaryKeyColumns: [SQLColumnDescriptor]?
}
extension SQLPrimaryKeyDescriptor {
static func find(_ db: Database, table: String) throws -> Self {
let columnInfos = try db.primaryKey(table).columnInfos
return SQLPrimaryKeyDescriptor(
tableName: table,
primaryKeyColumns: columnInfos.map { columnInfos in
columnInfos.map { SQLColumnDescriptor($0) }
})
}
}
@@ -38,6 +38,15 @@ extension SQLInterpolation {
appendInterpolation(type(of: record))
}
/// Appends a quoted identifier.
///
/// // INSERT INTO "group" ...
/// let tableName = "group"
/// let request: SQLRequest<Player> = "INSERT INTO \(identifier: tableName) ..."
public mutating func appendInterpolation(identifier: String) {
appendLiteral(identifier.quotedDatabaseIdentifier)
}
/// Appends the table name of the record.
///
/// // INSERT INTO player ...
@@ -0,0 +1,567 @@
/// Describes a database column.
///
/// You get instances of `ColumnDefinition` when you create or alter a database
/// tables. For example:
///
/// ```swift
/// try db.create(table: "player") { t in
/// t.column("name", .text) // ColumnDefinition
/// }
///
/// try db.alter(table: "player") { t in
/// t.add(column: "score", .integer) // ColumnDefinition
/// }
/// ```
///
/// See ``TableDefinition/column(_:_:)`` and ``TableAlteration/add(column:_:)``.
///
/// Related SQLite documentation:
///
/// - <https://www.sqlite.org/lang_createtable.html>
/// - <https://www.sqlite.org/lang_altertable.html>
///
/// ## Topics
///
/// ### Foreign Keys
///
/// - ``references(_:column:onDelete:onUpdate:deferred:)``
///
/// ### Indexes
///
/// - ``indexed()``
/// - ``unique(onConflict:)``
///
/// ### Default value
///
/// - ``defaults(to:)``
/// - ``defaults(sql:)``
///
/// ### Collations
///
/// - ``collate(_:)-4dljx``
/// - ``collate(_:)-9ywza``
///
/// ### Generated Columns
///
/// - ``generatedAs(_:_:)``
/// - ``generatedAs(sql:_:)``
/// - ``GeneratedColumnQualification``
///
/// ### Other Constraints
///
/// - ``check(_:)``
/// - ``check(sql:)``
/// - ``notNull(onConflict:)``
///
/// ### Sunsetted Methods
///
/// Those are legacy interfaces that are preserved for backwards compatibility.
/// Their use is not recommended.
///
/// - ``primaryKey(onConflict:autoincrement:)``
public final class ColumnDefinition {
enum Indexing {
case index
case unique(Database.ConflictResolution)
}
struct ForeignKeyConstraint {
var destinationTable: String
var destinationColumn: String?
var deleteAction: Database.ForeignKeyAction?
var updateAction: Database.ForeignKeyAction?
var isDeferred: Bool
}
/// The kind of a generated column.
///
/// Related SQLite documentation: <https://sqlite.org/gencol.html#virtual_versus_stored_columns>
public enum GeneratedColumnQualification {
/// A `VIRTUAL` generated column.
case virtual
/// A `STORED` generated column.
case stored
}
struct GeneratedColumnConstraint {
var expression: SQLExpression
var qualification: GeneratedColumnQualification
}
let name: String
let type: Database.ColumnType?
var primaryKey: (conflictResolution: Database.ConflictResolution?, autoincrement: Bool)?
var indexing: Indexing?
var notNullConflictResolution: Database.ConflictResolution?
var checkConstraints: [SQLExpression] = []
var foreignKeyConstraints: [ForeignKeyConstraint] = []
var defaultExpression: SQLExpression?
var collationName: String?
var generatedColumnConstraint: GeneratedColumnConstraint?
init(name: String, type: Database.ColumnType?) {
self.name = name
self.type = type
}
/// Adds a primary key constraint.
///
/// For example:
///
/// ```swift
/// // CREATE TABLE player(
/// // id TEXT NOT NULL PRIMARY KEY
/// // )
/// try db.create(table: "player") { t in
/// t.primaryKey("id", .text)
/// }
/// ```
///
/// - important: Make sure you add a not null constraint on your primary key
/// column, as in the above example, or SQLite will allow null values.
/// See <https://www.sqlite.org/quirks.html#primary_keys_can_sometimes_contain_nulls>
/// for more information.
///
/// - warning: This is a legacy interface that is preserved for backwards
/// compatibility. Use of this interface is not recommended: prefer
/// ``TableDefinition/primaryKey(_:_:onConflict:)``
/// instead.
///
/// - parameters:
/// - conflictResolution: An optional ``Database/ConflictResolution``.
/// - autoincrement: If true, the primary key is autoincremented.
/// - returns: `self` so that you can further refine the column definition.
@discardableResult
public func primaryKey(
onConflict conflictResolution: Database.ConflictResolution? = nil,
autoincrement: Bool = false)
-> Self
{
primaryKey = (conflictResolution: conflictResolution, autoincrement: autoincrement)
return self
}
/// Adds a not null constraint.
///
/// For example:
///
/// ```swift
/// // CREATE TABLE player(
/// // name TEXT NOT NULL
/// // )
/// try db.create(table: "player") { t in
/// t.column("name", .text).notNull()
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_createtable.html#notnullconst>
///
/// - parameter conflictResolution: An optional ``Database/ConflictResolution``.
/// - returns: `self` so that you can further refine the column definition.
@discardableResult
public func notNull(onConflict conflictResolution: Database.ConflictResolution? = nil) -> Self {
notNullConflictResolution = conflictResolution ?? .abort
return self
}
/// Adds a unique constraint.
///
/// For example:
///
/// ```swift
/// // CREATE TABLE player(
/// // email TEXT UNIQUE
/// // )
/// try db.create(table: "player") { t in
/// t.column("email", .text).unique()
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_createtable.html#uniqueconst>
///
/// - parameter conflictResolution: An optional ``Database/ConflictResolution``.
/// - returns: `self` so that you can further refine the column definition.
@discardableResult
public func unique(onConflict conflictResolution: Database.ConflictResolution? = nil) -> Self {
indexing = .unique(conflictResolution ?? .abort)
return self
}
/// Adds an index.
///
/// For example:
///
/// ```swift
/// // CREATE TABLE player(email TEXT);
/// // CREATE INDEX player_on_email ON player(email);
/// try db.create(table: "player") { t in
/// t.column("email", .text).indexed()
/// }
/// ```
///
/// The name of the created index is `<table>_on_<column>`, where `table`
/// and `column` are the names of the table and the column. See the
/// example above.
///
/// See also ``unique(onConflict:)``.
///
/// - returns: `self` so that you can further refine the column definition.
@discardableResult
public func indexed() -> Self {
if case .none = indexing {
self.indexing = .index
}
return self
}
/// Adds a check constraint.
///
/// For example:
///
/// ```swift
/// // CREATE TABLE player(
/// // name TEXT CHECK (LENGTH(name) > 0)
/// // )
/// try db.create(table: "player") { t in
/// t.column("name", .text).check { length($0) > 0 }
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_createtable.html#ckconst>
///
/// - parameter condition: A closure whose argument is a ``Column`` that
/// represents the defined column, and returns the expression to check.
/// - returns: `self` so that you can further refine the column definition.
@discardableResult
public func check(_ condition: (Column) -> any SQLExpressible) -> Self {
checkConstraints.append(condition(Column(name)).sqlExpression)
return self
}
/// Adds a check constraint.
///
/// For example:
///
/// ```swift
/// // CREATE TABLE player(
/// // name TEXT CHECK (LENGTH(name) > 0)
/// // )
/// try db.create(table: "player") { t in
/// t.column("name", .text).check(sql: "LENGTH(name) > 0")
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_createtable.html#ckconst>
///
/// - parameter sql: An SQL snippet.
/// - returns: `self` so that you can further refine the column definition.
@discardableResult
public func check(sql: String) -> Self {
checkConstraints.append(SQL(sql: sql).sqlExpression)
return self
}
/// Defines the default value.
///
/// For example:
///
/// ```swift
/// // CREATE TABLE player(
/// // email TEXT DEFAULT 'Anonymous'
/// // )
/// try db.create(table: "player") { t in
/// t.column("name", .text).defaults(to: "Anonymous")
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_createtable.html#dfltval>
///
/// - parameter value: A ``DatabaseValueConvertible`` value.
/// - returns: `self` so that you can further refine the column definition.
@discardableResult
public func defaults(to value: some DatabaseValueConvertible) -> Self {
defaultExpression = value.sqlExpression
return self
}
/// Defines the default value.
///
/// For example:
///
/// ```swift
/// // CREATE TABLE player(
/// // creationDate DATETIME DEFAULT CURRENT_TIMESTAMP
/// // )
/// try db.create(table: "player") { t in
/// t.column("creationDate", .DateTime).defaults(sql: "CURRENT_TIMESTAMP")
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_createtable.html#dfltval>
///
/// - parameter sql: An SQL snippet.
/// - returns: `self` so that you can further refine the column definition.
@discardableResult
public func defaults(sql: String) -> Self {
defaultExpression = SQL(sql: sql).sqlExpression
return self
}
/// Defines the default collation.
///
/// For example:
///
/// ```swift
/// // CREATE TABLE player(
/// // email TEXT COLLATE NOCASE
/// // )
/// try db.create(table: "player") { t in
/// t.column("email", .text).collate(.nocase)
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/datatype3.html#collation>
///
/// - parameter collation: A ``Database/CollationName``.
/// - returns: `self` so that you can further refine the column definition.
@discardableResult
public func collate(_ collation: Database.CollationName) -> Self {
collationName = collation.rawValue
return self
}
/// Defines the default collation.
///
/// For example:
///
/// ```swift
/// try db.create(table: "player") { t in
/// t.column("name", .text).collate(.localizedCaseInsensitiveCompare)
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/datatype3.html#collation>
///
/// - parameter collation: A ``DatabaseCollation``.
/// - returns: `self` so that you can further refine the column definition.
@discardableResult
public func collate(_ collation: DatabaseCollation) -> Self {
collationName = collation.name
return self
}
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// Defines the column as a generated column.
///
/// For example:
///
/// ```swift
/// // CREATE TABLE player(
/// // id INTEGER PRIMARY KEY AUTOINCREMENT,
/// // score INTEGER NOT NULL,
/// // bonus INTEGER NOT NULL,
/// // totalScore INTEGER GENERATED ALWAYS AS (score + bonus) VIRTUAL
/// // )
/// try db.create(table: "player") { t in
/// t.autoIncrementedPrimaryKey("id")
/// t.column("score", .integer).notNull()
/// t.column("bonus", .integer).notNull()
/// t.column("totalScore", .integer).generatedAs(sql: "score + bonus")
/// }
/// ```
///
/// Related SQLite documentation: <https://sqlite.org/gencol.html>
///
/// - parameters:
/// - sql: An SQL expression.
/// - qualification: The generated column's qualification, which
/// defaults to ``GeneratedColumnQualification/virtual``.
/// - returns: `self` so that you can further refine the column definition.
@discardableResult
public func generatedAs(
sql: String,
_ qualification: GeneratedColumnQualification = .virtual)
-> Self
{
let expression = SQL(sql: sql).sqlExpression
generatedColumnConstraint = GeneratedColumnConstraint(
expression: expression,
qualification: qualification)
return self
}
/// Defines the column as a generated column.
///
/// For example:
///
/// ```swift
/// // CREATE TABLE player(
/// // id INTEGER PRIMARY KEY AUTOINCREMENT,
/// // score INTEGER NOT NULL,
/// // bonus INTEGER NOT NULL,
/// // totalScore INTEGER GENERATED ALWAYS AS (score + bonus) VIRTUAL
/// // )
/// try db.create(table: "player") { t in
/// t.autoIncrementedPrimaryKey("id")
/// t.column("score", .integer).notNull()
/// t.column("bonus", .integer).notNull()
/// t.column("totalScore", .integer).generatedAs(Column("score") + Column("bonus"))
/// }
/// ```
///
/// Related SQLite documentation: <https://sqlite.org/gencol.html>
///
/// - parameters:
/// - expression: The generated expression.
/// - qualification: The generated column's qualification, which
/// defaults to ``GeneratedColumnQualification/virtual``.
/// - returns: `self` so that you can further refine the column definition.
@discardableResult
public func generatedAs(
_ expression: some SQLExpressible,
_ qualification: GeneratedColumnQualification = .virtual)
-> Self
{
generatedColumnConstraint = GeneratedColumnConstraint(
expression: expression.sqlExpression,
qualification: qualification)
return self
}
#else
/// Defines the column as a generated column.
///
/// For example:
///
/// ```swift
/// // CREATE TABLE player(
/// // id INTEGER PRIMARY KEY AUTOINCREMENT,
/// // score INTEGER NOT NULL,
/// // bonus INTEGER NOT NULL,
/// // totalScore INTEGER GENERATED ALWAYS AS (score + bonus) VIRTUAL
/// // )
/// try db.create(table: "player") { t in
/// t.autoIncrementedPrimaryKey("id")
/// t.column("score", .integer).notNull()
/// t.column("bonus", .integer).notNull()
/// t.column("totalScore", .integer).generatedAs(sql: "score + bonus")
/// }
/// ```
///
/// Related SQLite documentation: <https://sqlite.org/gencol.html>
///
/// - parameters:
/// - sql: An SQL expression.
/// - qualification: The generated column's qualification, which
/// defaults to ``GeneratedColumnQualification/virtual``.
/// - returns: `self` so that you can further refine the column definition.
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ (3.31 actually)
@discardableResult
public func generatedAs(
sql: String,
_ qualification: GeneratedColumnQualification = .virtual)
-> Self
{
let expression = SQL(sql: sql).sqlExpression
generatedColumnConstraint = GeneratedColumnConstraint(
expression: expression,
qualification: qualification)
return self
}
/// Defines the column as a generated column.
///
/// For example:
///
/// ```swift
/// // CREATE TABLE player(
/// // id INTEGER PRIMARY KEY AUTOINCREMENT,
/// // score INTEGER NOT NULL,
/// // bonus INTEGER NOT NULL,
/// // totalScore INTEGER GENERATED ALWAYS AS (score + bonus) VIRTUAL
/// // )
/// try db.create(table: "player") { t in
/// t.autoIncrementedPrimaryKey("id")
/// t.column("score", .integer).notNull()
/// t.column("bonus", .integer).notNull()
/// t.column("totalScore", .integer).generatedAs(Column("score") + Column("bonus"))
/// }
/// ```
///
/// Related SQLite documentation: <https://sqlite.org/gencol.html>
///
/// - parameters:
/// - expression: The generated expression.
/// - qualification: The generated column's qualification, which
/// defaults to ``GeneratedColumnQualification/virtual``.
/// - returns: `self` so that you can further refine the column definition.
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ (3.31 actually)
@discardableResult
public func generatedAs(
_ expression: some SQLExpressible,
_ qualification: GeneratedColumnQualification = .virtual)
-> Self
{
generatedColumnConstraint = GeneratedColumnConstraint(
expression: expression.sqlExpression,
qualification: qualification)
return self
}
#endif
/// Adds a foreign key constraint.
///
/// For example:
///
/// ```swift
/// // CREATE TABLE book(
/// // authorId INTEGER REFERENCES author(id) ON DELETE CASCADE
/// // )
/// try db.create(table: "book") { t in
/// t.column("authorId", .integer).references("author", onDelete: .cascade)
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/foreignkeys.html>
///
/// - parameters:
/// - table: The referenced table.
/// - column: The referenced 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.
/// - isDeferred: A boolean value indicating whether the foreign key
/// constraint is deferred.
/// See <https://www.sqlite.org/foreignkeys.html#fk_deferred>.
/// - returns: `self` so that you can further refine the column definition.
@discardableResult
public func references(
_ table: String,
column: String? = nil,
onDelete deleteAction: Database.ForeignKeyAction? = nil,
onUpdate updateAction: Database.ForeignKeyAction? = nil,
deferred isDeferred: Bool = false) -> Self
{
foreignKeyConstraints.append(ForeignKeyConstraint(
destinationTable: table,
destinationColumn: column,
deleteAction: deleteAction,
updateAction: updateAction,
isDeferred: isDeferred))
return self
}
func indexDefinition(in table: String, options: IndexOptions = []) -> IndexDefinition? {
switch indexing {
case .none: return nil
case .unique: return nil
case .index:
return IndexDefinition(
name: "\(table)_on_\(name)",
table: table,
columns: [name],
options: options,
condition: nil)
}
}
}
@@ -0,0 +1,651 @@
extension Database {
// MARK: - Database Schema
/// Creates a database table.
///
/// For example:
///
/// ```swift
/// try db.create(table: "place") { t in
/// t.autoIncrementedPrimaryKey("id")
/// t.column("title", .text)
/// t.column("favorite", .boolean).notNull().default(false)
/// t.column("longitude", .double).notNull()
/// t.column("latitude", .double).notNull()
/// }
/// ```
///
/// Related SQLite documentation:
/// - <https://www.sqlite.org/lang_createtable.html>
/// - <https://www.sqlite.org/withoutrowid.html>
///
/// - warning: This is a legacy interface that is preserved for backwards
/// compatibility. Use of this interface is not recommended: prefer
/// ``create(table:options:body:)`` instead.
///
/// - parameters:
/// - name: The table name.
/// - temporary: If true, creates a temporary table.
/// - ifNotExists: If false (the default), an error is thrown if the
/// table already exists. Otherwise, the table is created unless it
/// 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.
@_disfavoredOverload
public func create(
table name: String,
temporary: Bool = false,
ifNotExists: Bool = false,
withoutRowID: Bool = false,
body: (TableDefinition) throws -> Void)
throws
{
var options: TableOptions = []
if temporary { options.insert(.temporary) }
if ifNotExists { options.insert(.ifNotExists) }
if withoutRowID { options.insert(.withoutRowID) }
try create(table: name, options: options, body: body)
}
/// Creates a database table.
///
/// ### Reference documentation
///
/// SQLite has many reference documents about table creation. They are a
/// great learning material:
///
/// - [CREATE TABLE](https://www.sqlite.org/lang_createtable.html)
/// - [Datatypes In SQLite](https://www.sqlite.org/datatype3.html)
/// - [SQLite Foreign Key Support](https://www.sqlite.org/foreignkeys.html)
/// - [The ON CONFLICT Clause](https://www.sqlite.org/lang_conflict.html)
/// - [Rowid Tables](https://www.sqlite.org/rowidtable.html)
/// - [The WITHOUT ROWID Optimization](https://www.sqlite.org/withoutrowid.html)
/// - [STRICT Tables](https://www.sqlite.org/stricttables.html)
///
/// ### Usage
///
/// ```swift
/// // CREATE TABLE place (
/// // id INTEGER PRIMARY KEY AUTOINCREMENT,
/// // title TEXT,
/// // isFavorite BOOLEAN NOT NULL DEFAULT 0,
/// // latitude DOUBLE NOT NULL,
/// // longitude DOUBLE NOT NULL
/// // )
/// try db.create(table: "place") { t in
/// t.autoIncrementedPrimaryKey("id")
/// t.column("title", .text)
/// t.column("isFavorite", .boolean).notNull().default(false)
/// t.column("longitude", .double).notNull()
/// t.column("latitude", .double).notNull()
/// }
/// ```
///
/// ### Configure table creation
///
/// Use the `options` parameter to configure table creation
/// (see ``TableOptions``):
///
/// ```swift
/// // CREATE TABLE player ( ... )
/// try db.create(table: "player") { t in ... }
///
/// // CREATE TEMPORARY TABLE player IF NOT EXISTS (
/// try db.create(table: "player", options: [.temporary, .ifNotExists]) { t in ... }
/// ```
///
/// ### Add columns
///
/// Add columns with their name and eventual type (`text`, `integer`,
/// `double`, `real`, `numeric`, `boolean`, `blob`, `date`, `datetime`
/// and `any`) - see ``Database/ColumnType``:
///
/// ```swift
/// // CREATE TABLE example (
/// // a,
/// // name TEXT,
/// // creationDate DATETIME,
/// try db.create(table: "example") { t in
/// t.column("a")
/// t.column("name", .text)
/// t.column("creationDate", .datetime)
/// ```
///
/// The `column()` method returns a ``ColumnDefinition`` that you can
/// further configure:
///
/// ### Not null constraints, default values
///
/// ```swift
/// // email TEXT NOT NULL,
/// t.column("email", .text).notNull()
///
/// // name TEXT DEFAULT 'O''Reilly',
/// t.column("name", .text).defaults(to: "O'Reilly")
///
/// // flag BOOLEAN NOT NULL DEFAULT 0,
/// t.column("flag", .boolean).notNull().defaults(to: false)
///
/// // creationDate DATETIME DEFAULT CURRENT_TIMESTAMP,
/// t.column("creationDate", .datetime).defaults(sql: "CURRENT_TIMESTAMP")
/// ```
///
/// ### Primary, unique, and foreign keys
///
/// 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 AUTOINCREMENT,
/// t.autoIncrementedPrimaryKey("id")
///
/// // uuid TEXT NOT NULL PRIMARY KEY,
/// t.primaryKey("uuid", .text)
///
/// // email TEXT UNIQUE,
/// t.column("email", .text)
/// .unique()
///
/// // countryCode TEXT REFERENCES country(code) ON DELETE CASCADE,
/// t.column("countryCode", .text)
/// .references("country", onDelete: .cascade)
/// ```
///
/// Primary, unique and foreign keys can also be added on several columns:
///
/// ```swift
/// // a INTEGER NOT NULL,
/// // b TEXT NOT NULL,
/// // PRIMARY KEY (a, b)
/// t.primaryKey {
/// t.column("a", .integer)
/// t.column("b", .text)
/// }
///
/// // a INTEGER NOT NULL,
/// // b TEXT NOT NULL,
/// // PRIMARY KEY (a, b)
/// t.column("a", .integer).notNull()
/// t.column("b", .text).notNull()
/// t.primaryKey(["a", "b"])
///
/// // a INTEGER,
/// // b TEXT,
/// // UNIQUE (a, b) ON CONFLICT REPLACE
/// t.column("a", .integer)
/// t.column("b", .text)
/// t.uniqueKey(["a", "b"], onConflict: .replace)
///
/// // a INTEGER,
/// // b TEXT,
/// // FOREIGN KEY (a, b) REFERENCES parents(c, d)
/// t.column("a", .integer)
/// t.column("b", .text)
/// t.foreignKey(["a", "b"], references: "parents")
/// ```
///
/// > Tip: when you need an integer primary key that automatically generates
/// unique values, it is recommended that you use the
/// ``TableDefinition/autoIncrementedPrimaryKey(_:onConflict:)`` method:
/// >
/// > ```swift
/// > try db.create(table: "example") { t in
/// > t.autoIncrementedPrimaryKey("id")
/// > ...
/// > }
/// > ```
/// >
/// > The reason for this recommendation is that auto-incremented primary
/// > keys forbid the reuse of ids. This prevents your app or
/// > <doc:DatabaseObservation> to think that a row was updated, when it was
/// > actually deleted and replaced. Depending on your application needs,
/// > this may be acceptable. But usually it is not.
///
/// ### Indexed columns
///
/// ```swift
/// t.column("score", .integer).indexed()
/// ```
///
/// For extra index options, see ``create(indexOn:columns:options:condition:)``.
///
/// ### Generated columns
///
/// See [Generated columns](https://sqlite.org/gencol.html) for
/// more information:
///
/// ```swift
/// t.column("totalScore", .integer).generatedAs(sql: "score + bonus")
/// t.column("totalScore", .integer).generatedAs(Column("score") + Column("bonus"))
/// ```
///
/// ### Integrity checks
///
/// SQLite will only let conforming rows in:
///
/// ```swift
/// // name TEXT CHECK (LENGTH(name) > 0)
/// t.column("name", .text).check { length($0) > 0 }
///
/// // score INTEGER CHECK (score > 0)
/// t.column("score", .integer).check(sql: "score > 0")
///
/// // CHECK (a + b < 10),
/// t.check(Column("a") + Column("b") < 10)
///
/// // CHECK (a + b < 10)
/// t.check(sql: "a + b < 10")
/// ```
///
/// ### Raw SQL columns and constraints
///
/// Columns and constraints can be defined with raw sql:
///
/// ```swift
/// t.column(sql: "name TEXT")
/// t.constraint(sql: "CHECK (a + b < 10)")
/// ```
///
/// ``SQL`` literals allow you to safely embed raw values in your SQL,
/// without any risk of syntax errors or SQL injection:
///
/// ```swift
/// let defaultName = "O'Reilly"
/// t.column(literal: "name TEXT DEFAULT \(defaultName)")
///
/// let forbiddenName = "admin"
/// t.constraint(literal: "CHECK (name <> \(forbiddenName))")
/// ```
///
/// - parameters:
/// - name: The table name.
/// - options: Table creation options.
/// - body: A closure that defines table columns and constraints.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func create(
table name: String,
options: TableOptions = [],
body: (TableDefinition) throws -> Void)
throws
{
let table = TableDefinition(
name: name,
options: options)
try body(table)
let generator = try SQLTableGenerator(self, table: table)
let sql = try generator.sql(self)
try execute(sql: sql)
}
/// Renames a database table.
///
/// Related SQLite documentation: <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(sql: "ALTER TABLE \(name.quotedDatabaseIdentifier) RENAME TO \(newName.quotedDatabaseIdentifier)")
}
/// Modifies a database table.
///
/// For example:
///
/// ```swift
/// try db.alter(table: "player") { t in
/// t.add(column: "url", .text)
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_altertable.html>
///
/// - parameters:
/// - name: The table name.
/// - body: A closure that defines table alterations.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func alter(table name: String, body: (TableAlteration) -> Void) throws {
let alteration = TableAlteration(name: name)
body(alteration)
let generator = SQLTableAlterationGenerator(alteration)
let sql = try generator.sql(self)
try execute(sql: sql)
}
/// Deletes a database table.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_droptable.html>
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func drop(table name: String) throws {
try execute(sql: "DROP TABLE \(name.quotedDatabaseIdentifier)")
}
/// Creates a database view.
///
/// You can create a view with an ``SQLRequest``:
///
/// ```swift
/// // CREATE VIEW hero AS SELECT * FROM player WHERE isHero == 1
/// try db.create(view: "hero", as: SQLRequest(literal: """
/// SELECT * FROM player WHERE isHero == 1
/// """)
/// ```
///
/// You can also create a view with a ``QueryInterfaceRequest``:
///
/// ```swift
/// // CREATE VIEW hero AS SELECT * FROM player WHERE isHero == 1
/// try db.create(
/// view: "hero",
/// as: Player.filter(Column("isHero") == true))
/// ```
///
/// When creating views in <doc:Migrations>, it is not recommended to
/// use record types defined in the application. Instead of the `Player`
/// record type, prefer `Table("player")`:
///
/// ```swift
/// // RECOMMENDED IN MIGRATIONS
/// try db.create(
/// view: "hero",
/// as: Table("player").filter(Column("isHero") == true))
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_createview.html>
///
/// - parameters:
/// - view: The view name.
/// - options: View creation options.
/// - columns: The columns of the view. If nil, the columns are the
/// columns of the request.
/// - request: The request that feeds the view.
public func create(
view name: String,
options: ViewOptions = [],
columns: [String]? = nil,
as request: SQLSubqueryable)
throws {
var literal: SQL = "CREATE "
if options.contains(.temporary) {
literal += "TEMPORARY "
}
literal += "VIEW "
if options.contains(.ifNotExists) {
literal += "IF NOT EXISTS "
}
literal += "\(identifier: name) "
if let columns {
literal += "("
literal += columns.map { "\(identifier: $0)" }.joined(separator: ", ")
literal += ") "
}
literal += "AS \(request)"
// CREATE VIEW does not support arguments, so make sure we use
// literal values.
let context = SQLGenerationContext(self, argumentsSink: .literalValues)
let sql = try literal.sql(context)
try execute(sql: sql)
}
/// Creates a database view.
///
/// For example:
///
/// ```swift
/// // CREATE VIEW hero AS SELECT * FROM player WHERE isHero == 1
/// try db.create(view: "hero", asLiteral: """
/// SELECT * FROM player WHERE isHero == 1
/// """)
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_createview.html>
///
/// - parameters:
/// - view: The view name.
/// - options: View creation options.
/// - columns: The columns of the view. If nil, the columns are the
/// columns of the request.
/// - sqlLiteral: An `SQL` literal.
public func create(
view name: String,
options: ViewOptions = [],
columns: [String]? = nil,
asLiteral sqlLiteral: SQL)
throws {
try create(view: name, options: options, columns: columns, as: SQLRequest(literal: sqlLiteral))
}
/// Deletes a database view.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_dropview.html>
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func drop(view name: String) throws {
try execute(sql: "DROP VIEW \(name.quotedDatabaseIdentifier)")
}
/// Creates an index.
///
/// For example:
///
/// ```swift
/// // CREATE INDEX index_player_on_email ON player(email)
/// try db.create(index: "index_player_on_email", on: "player", 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:
///
/// ```swift
/// try db.execute(sql: "CREATE INDEX ...")
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_createindex.html>
///
/// - warning: This is a legacy interface that is preserved for backwards
/// compatibility. Use of this interface is not recommended: prefer
/// ``create(indexOn:columns:options:condition:)`` instead.
///
/// - 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 true, no error is thrown if index already exists.
/// - condition: If not nil, creates a partial index
/// (see <https://www.sqlite.org/partialindex.html>).
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
@_disfavoredOverload
public func create(
index name: String,
on table: String,
columns: [String],
unique: Bool = false,
ifNotExists: Bool = false,
condition: (any SQLExpressible)? = nil)
throws
{
var options: IndexOptions = []
if ifNotExists { options.insert(.ifNotExists) }
if unique { options.insert(.unique) }
try create(index: name, on: table, columns: columns, options: options, condition: condition)
}
/// Creates an index.
///
/// For example:
///
/// ```swift
/// // CREATE INDEX index_player_on_email ON player(email)
/// try db.create(index: "index_player_on_email", on: "player", columns: ["email"])
/// ```
///
/// To create a unique index, specify the `.unique` option:
///
/// ```swift
/// // CREATE UNIQUE INDEX index_player_on_email ON player(email)
/// try db.create(index: "index_player_on_email", on: "player", columns: ["email"], options: .unique)
/// ```
///
/// 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:
///
/// ```swift
/// try db.execute(sql: "CREATE INDEX ...")
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_createindex.html>
///
/// - parameters:
/// - name: The index name.
/// - table: The name of the indexed table.
/// - columns: The indexed columns.
/// - options: Index creation options.
/// - condition: If not nil, creates a partial index
/// (see <https://www.sqlite.org/partialindex.html>).
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func create(
index name: String,
on table: String,
columns: [String],
options: IndexOptions = [],
condition: (any SQLExpressible)? = nil)
throws
{
let index = IndexDefinition(
name: name,
table: table,
columns: columns,
options: options,
condition: condition?.sqlExpression)
let generator = SQLIndexGenerator(index: index)
let sql = try generator.sql(self)
try execute(sql: sql)
}
/// Creates an index on the specified table and columns.
///
/// The created index is named after the table and the column name(s):
///
/// ```swift
/// // CREATE INDEX index_player_on_email ON player(email)
/// try db.create(indexOn: "player", columns: ["email"])
/// ```
///
/// To create a unique index, specify the `.unique` option:
///
/// ```swift
/// // CREATE UNIQUE INDEX index_player_on_email ON player(email)
/// try db.create(indexOn: "player", columns: ["email"], options: .unique)
/// ```
///
/// In order to specify the index name, use
/// ``create(index:on:columns:options:condition:)`` instead.
///
/// 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:
///
/// ```swift
/// try db.execute(sql: "CREATE INDEX ...")
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_createindex.html>
///
/// - parameters:
/// - table: The name of the indexed table.
/// - columns: The indexed columns.
/// - options: Index creation options.
/// - condition: If not nil, creates a partial index
/// (see <https://www.sqlite.org/partialindex.html>).
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func create(
indexOn table: String,
columns: [String],
options: IndexOptions = [],
condition: (any SQLExpressible)? = nil)
throws
{
try create(
index: Database.defaultIndexName(on: table, columns: columns),
on: table,
columns: columns,
options: options,
condition: condition)
}
/// Deletes a database index.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_dropindex.html>
///
/// - parameter name: The index name.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func drop(index name: String) throws {
try execute(sql: "DROP INDEX \(name.quotedDatabaseIdentifier)")
}
/// Deletes the database index on the specified table and columns
/// if exactly one such index exists.
///
/// - parameters:
/// - table: The name of the indexed table.
/// - columns: The indexed columns.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func drop(indexOn table: String, columns: [String]) throws {
let lowercasedColumns = columns.map { $0.lowercased() }
let indexes = try indexes(on: table).filter { index in
index.columns.map({ $0.lowercased() }) == lowercasedColumns
}
if let index = indexes.first, indexes.count == 1 {
try drop(index: index.name)
}
}
/// Deletes and recreates from scratch all indices that use this collation.
///
/// This method is useful when the definition of a collation sequence
/// has changed.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_reindex.html>
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func reindex(collation: Database.CollationName) throws {
try execute(sql: "REINDEX \(collation.rawValue)")
}
/// Deletes and recreates from scratch all indices that use this collation.
///
/// This method is useful when the definition of a collation sequence
/// has changed.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_reindex.html>
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func reindex(collation: DatabaseCollation) throws {
try reindex(collation: Database.CollationName(rawValue: collation.name))
}
}
/// View creation options
public struct ViewOptions: OptionSet {
public let rawValue: Int
public init(rawValue: Int) { self.rawValue = rawValue }
/// Only creates the view if it does not already exist.
public static let ifNotExists = ViewOptions(rawValue: 1 << 0)
/// Creates a temporary view.
public static let temporary = ViewOptions(rawValue: 1 << 1)
}
@@ -0,0 +1,106 @@
/// Describes an association in the database schema.
///
/// You get instances of `ForeignKeyDefinition` when you create a database
/// tables. For example:
///
/// ```swift
/// try db.create(table: "player") { t in
/// t.belongsTo("team") // ForeignKeyDefinition
/// }
/// ```
///
/// See ``TableDefinition/belongsTo(_:inTable:onDelete:onUpdate:deferred:indexed:)``.
public final class ForeignKeyDefinition {
enum Indexing {
case index
case unique
}
var name: String
var table: String?
var deleteAction: Database.ForeignKeyAction?
var updateAction: Database.ForeignKeyAction?
var indexing: Indexing?
var isDeferred: Bool
var notNullConflictResolution: Database.ConflictResolution?
init(
name: String,
table: String?,
deleteAction: Database.ForeignKeyAction?,
updateAction: Database.ForeignKeyAction?,
isIndexed: Bool,
isDeferred: Bool)
{
self.name = name
self.table = table
self.deleteAction = deleteAction
self.updateAction = updateAction
self.indexing = isIndexed ? .index : nil
self.isDeferred = isDeferred
}
/// Adds a not null constraint.
///
/// For example:
///
/// ```swift
/// // CREATE TABLE player(
/// // teamId INTEGER NOT NULL REFERENCES team(id)
/// // )
/// try db.create(table: "player") { t in
/// t.belongsTo("team").notNull()
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_createtable.html#notnullconst>
///
/// - parameter conflictResolution: An optional ``Database/ConflictResolution``.
/// - returns: `self` so that you can further refine the definition of
/// the association.
@discardableResult
public func notNull(onConflict conflictResolution: Database.ConflictResolution? = nil) -> Self {
notNullConflictResolution = conflictResolution ?? .abort
return self
}
/// Adds a unique constraint.
///
/// For example:
///
/// ```swift
/// // CREATE TABLE player(
/// // teamId INTEGER UNIQUE REFERENCES team(id)
/// // )
/// try db.create(table: "player") { t in
/// t.belongsTo("team").unique()
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_createtable.html#uniqueconst>
///
/// - returns: `self` so that you can further refine the definition of
/// the association.
@discardableResult
public func unique() -> Self {
indexing = .unique
return self
}
func primaryKey(_ db: Database) throws -> SQLPrimaryKeyDescriptor {
if let table {
return try SQLPrimaryKeyDescriptor.find(db, table: table)
}
if try db.tableExists(name) {
return try SQLPrimaryKeyDescriptor.find(db, table: name)
}
let pluralizedName = name.pluralized
if try db.tableExists(pluralizedName) {
return try SQLPrimaryKeyDescriptor.find(db, table: pluralizedName)
}
throw DatabaseError.noSuchTable(name)
}
}
@@ -0,0 +1,26 @@
struct IndexDefinition {
let name: String
let table: String
let columns: [String]
let options: IndexOptions
let condition: SQLExpression?
}
/// Index creation options
public struct IndexOptions: OptionSet {
public let rawValue: Int
public init(rawValue: Int) { self.rawValue = rawValue }
/// Only creates the index if it does not already exist.
public static let ifNotExists = IndexOptions(rawValue: 1 << 0)
/// Creates a unique index.
public static let unique = IndexOptions(rawValue: 1 << 1)
}
extension Database {
static func defaultIndexName(on table: String, columns: [String]) -> String {
"index_\(table)_on_\(columns.joined(separator: "_"))"
}
}
@@ -0,0 +1,163 @@
/// A `TableDefinition` lets you modify the components of a database table.
///
/// You don't create instances of this class. Instead, you use the `Database`
/// ``Database/alter(table:body:)`` method:
///
/// ```swift
/// try db.alter(table: "player") { t in // t is TableAlteration
/// t.add(column: "bonus", .integer)
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_altertable.html>
public final class TableAlteration {
let name: String
enum TableAlterationKind {
case add(ColumnDefinition)
case addColumnLiteral(SQL)
case rename(old: String, new: String)
case drop(String)
}
var alterations: [TableAlterationKind] = []
init(name: String) {
self.name = name
}
/// Appends a column.
///
/// For example:
///
/// ```swift
/// // ALTER TABLE player ADD COLUMN bonus integer
/// try db.alter(table: "player") { t in
/// t.add(column: "bonus", .integer)
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_altertable.html>
///
/// - parameter name: the column name.
/// - parameter type: the column type.
/// - returns: An ColumnDefinition that allows you to refine the
/// column definition.
@discardableResult
public func add(column name: String, _ type: Database.ColumnType? = nil) -> ColumnDefinition {
let column = ColumnDefinition(name: name, type: type)
alterations.append(.add(column))
return column
}
/// Appends a column.
///
/// For example:
///
/// ```swift
/// // ALTER TABLE player ADD COLUMN bonus integer
/// try db.alter(table: "player") { t in
/// t.addColumn(sql: "bonus integer")
/// }
/// ```
public func addColumn(sql: String) {
alterations.append(.addColumnLiteral(SQL(sql: sql)))
}
/// Appends a column.
///
/// ``SQL`` literals allow you to safely embed raw values in your SQL,
/// without any risk of syntax errors or SQL injection:
///
/// ```swift
/// // ALTER TABLE player ADD COLUMN name TEXT DEFAULT 'Anonymous'
/// try db.alter(table: "player") { t in
/// t.addColumn(literal: "name TEXT DEFAULT \(defaultName)")
/// }
/// ```
public func addColumn(literal: SQL) {
alterations.append(.addColumnLiteral(literal))
}
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// Renames a column.
///
/// For example:
///
/// ```swift
/// try db.alter(table: "player") { t in
/// t.rename(column: "url", to: "homeURL")
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_altertable.html>
///
/// - parameter name: the old name of the column.
/// - parameter newName: the new name of the column.
public func rename(column name: String, to newName: String) {
_rename(column: name, to: newName)
}
/// Drops a column.
///
/// For example:
///
/// ```swift
/// try db.alter(table: "player") { t in
/// t.drop(column: "age")
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_altertable.html>
///
/// - Parameter name: the name of the column to drop.
public func drop(column name: String) {
_drop(column: name)
}
#else
/// Renames a column.
///
/// For example:
///
/// ```swift
/// try db.alter(table: "player") { t in
/// t.rename(column: "url", to: "homeURL")
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_altertable.html>
///
/// - parameter name: the old name of the column.
/// - parameter newName: the new name of the column.
@available(iOS 13, tvOS 13, watchOS 6, *) // SQLite 3.25+
public func rename(column name: String, to newName: String) {
_rename(column: name, to: newName)
}
/// Drops a column.
///
/// For example:
///
/// ```swift
/// try db.alter(table: "player") { t in
/// t.drop(column: "age")
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_altertable.html>
///
/// - Parameter name: the name of the column to drop.
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func drop(column name: String) {
_drop(column: name)
}
#endif
private func _rename(column name: String, to newName: String) {
alterations.append(.rename(old: name, new: newName))
}
private func _drop(column name: String) {
alterations.append(.drop(name))
}
}
File diff suppressed because it is too large. Load diff
+4
View File
@@ -190,3 +190,7 @@ extension NSLocking {
sideEffect?()
}
}
#if !canImport(ObjectiveC)
@inlinable func autoreleasepool<Result>(invoking body: () throws -> Result) rethrows -> Result { try body() }
#endif
+40
View File
@@ -69,6 +69,7 @@
563B8FBB24A1D036007A48C9 /* ReceiveValuesOn.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FB924A1D036007A48C9 /* ReceiveValuesOn.swift */; };
563B8FBD24A1D388007A48C9 /* OnDemandFuture.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FBC24A1D388007A48C9 /* OnDemandFuture.swift */; };
563C67B824628C0C00E94EDC /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563C67B624628C0C00E94EDC /* DatabasePoolTests.swift */; };
563CBBE42A595141008905CE /* SQLIndexGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563CBBE22A595141008905CE /* SQLIndexGenerator.swift */; };
563DE4F8231A91F6005081B7 /* DatabaseConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563DE4F6231A91F6005081B7 /* DatabaseConfigurationTests.swift */; };
563EF420215F8A76007DAACD /* OrderedDictionary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF41E215F8A76007DAACD /* OrderedDictionary.swift */; };
563EF442216131F5007DAACD /* AssociationAggregateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF441216131F5007DAACD /* AssociationAggregateTests.swift */; };
@@ -200,6 +201,7 @@
56894F332604FC1E00268F4D /* Table.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F322604FC1E00268F4D /* Table.swift */; };
56894FE3260658A400268F4D /* Decimal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894FA0260657F600268F4D /* Decimal.swift */; };
56894FF2260658E600268F4D /* FoundationDecimalTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894FF1260658E600268F4D /* FoundationDecimalTests.swift */; };
568C3F7D2A5AB2D500A2309D /* ForeignKeyDefinitionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F7B2A5AB2D500A2309D /* ForeignKeyDefinitionTests.swift */; };
568EB71C2921232200E59445 /* DatabaseSnapshotPool.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568EB71A2921232200E59445 /* DatabaseSnapshotPool.swift */; };
568EB7202921235E00E59445 /* DatabaseSnapshotPoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568EB71F2921235E00E59445 /* DatabaseSnapshotPoolTests.swift */; };
568ECB0D25D904CA00B71526 /* SQLSelection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECB0C25D904CA00B71526 /* SQLSelection.swift */; };
@@ -294,6 +296,14 @@
56F34FC624B0A0C9007513FC /* SQLIdentifyingColumnsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FC524B0A0C8007513FC /* SQLIdentifyingColumnsTests.swift */; };
56F3E74C1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; };
56F61DEA283D469F00AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DE8283D469F00AF9884 /* getThreadsCount.c */; };
56F89DFA2A57EAB9002FE2AA /* ColumnDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89DF82A57EAB9002FE2AA /* ColumnDefinition.swift */; };
56F89E072A57EBA7002FE2AA /* TableAlteration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89E032A57EBA7002FE2AA /* TableAlteration.swift */; };
56F89E082A57EBA7002FE2AA /* Database+SchemaDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89E042A57EBA7002FE2AA /* Database+SchemaDefinition.swift */; };
56F89E092A57EBA7002FE2AA /* ForeignKeyDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89E052A57EBA7002FE2AA /* ForeignKeyDefinition.swift */; };
56F89E0A2A57EBA7002FE2AA /* IndexDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89E062A57EBA7002FE2AA /* IndexDefinition.swift */; };
56F89E1A2A585E0D002FE2AA /* SQLColumnGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89E162A585E0D002FE2AA /* SQLColumnGenerator.swift */; };
56F89E1B2A585E0D002FE2AA /* SQLTableAlterationGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89E182A585E0D002FE2AA /* SQLTableAlterationGenerator.swift */; };
56F89E1C2A585E0D002FE2AA /* SQLTableGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89E192A585E0D002FE2AA /* SQLTableGenerator.swift */; };
56FA0C3728B1F2EB00B2DFF7 /* MutablePersistableRecord+Upsert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FA0C3428B1F2EB00B2DFF7 /* MutablePersistableRecord+Upsert.swift */; };
56FA0C4128B20ADB00B2DFF7 /* PersistableRecord+Upsert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FA0C4028B20ADB00B2DFF7 /* PersistableRecord+Upsert.swift */; };
56FBFED62210731100945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED52210731000945324 /* SQLRequest.swift */; };
@@ -503,6 +513,7 @@
563B8FB924A1D036007A48C9 /* ReceiveValuesOn.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ReceiveValuesOn.swift; sourceTree = "<group>"; };
563B8FBC24A1D388007A48C9 /* OnDemandFuture.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OnDemandFuture.swift; sourceTree = "<group>"; };
563C67B624628C0C00E94EDC /* DatabasePoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolTests.swift; sourceTree = "<group>"; };
563CBBE22A595141008905CE /* SQLIndexGenerator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLIndexGenerator.swift; sourceTree = "<group>"; };
563DE4F6231A91F6005081B7 /* DatabaseConfigurationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseConfigurationTests.swift; sourceTree = "<group>"; };
563EF41E215F8A76007DAACD /* OrderedDictionary.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OrderedDictionary.swift; sourceTree = "<group>"; };
563EF441216131F5007DAACD /* AssociationAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationAggregateTests.swift; sourceTree = "<group>"; };
@@ -645,6 +656,7 @@
56894F322604FC1E00268F4D /* Table.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Table.swift; sourceTree = "<group>"; };
56894FA0260657F600268F4D /* Decimal.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Decimal.swift; sourceTree = "<group>"; };
56894FF1260658E600268F4D /* FoundationDecimalTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDecimalTests.swift; sourceTree = "<group>"; };
568C3F7B2A5AB2D500A2309D /* ForeignKeyDefinitionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ForeignKeyDefinitionTests.swift; sourceTree = "<group>"; };
568EB71A2921232200E59445 /* DatabaseSnapshotPool.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotPool.swift; sourceTree = "<group>"; };
568EB71F2921235E00E59445 /* DatabaseSnapshotPoolTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotPoolTests.swift; sourceTree = "<group>"; };
568ECB0C25D904CA00B71526 /* SQLSelection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLSelection.swift; sourceTree = "<group>"; };
@@ -790,6 +802,14 @@
56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ResultCodeTests.swift; sourceTree = "<group>"; };
56F61DE8283D469F00AF9884 /* getThreadsCount.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = getThreadsCount.c; sourceTree = "<group>"; };
56F61DE9283D469F00AF9884 /* getThreadsCount.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = getThreadsCount.h; sourceTree = "<group>"; };
56F89DF82A57EAB9002FE2AA /* ColumnDefinition.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ColumnDefinition.swift; sourceTree = "<group>"; };
56F89E032A57EBA7002FE2AA /* TableAlteration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableAlteration.swift; sourceTree = "<group>"; };
56F89E042A57EBA7002FE2AA /* Database+SchemaDefinition.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Database+SchemaDefinition.swift"; sourceTree = "<group>"; };
56F89E052A57EBA7002FE2AA /* ForeignKeyDefinition.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKeyDefinition.swift; sourceTree = "<group>"; };
56F89E062A57EBA7002FE2AA /* IndexDefinition.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexDefinition.swift; sourceTree = "<group>"; };
56F89E162A585E0D002FE2AA /* SQLColumnGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLColumnGenerator.swift; sourceTree = "<group>"; };
56F89E182A585E0D002FE2AA /* SQLTableAlterationGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLTableAlterationGenerator.swift; sourceTree = "<group>"; };
56F89E192A585E0D002FE2AA /* SQLTableGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLTableGenerator.swift; sourceTree = "<group>"; };
56FA0C3428B1F2EB00B2DFF7 /* MutablePersistableRecord+Upsert.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+Upsert.swift"; sourceTree = "<group>"; };
56FA0C4028B20ADB00B2DFF7 /* PersistableRecord+Upsert.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "PersistableRecord+Upsert.swift"; sourceTree = "<group>"; };
56FBFED52210731000945324 /* SQLRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLRequest.swift; sourceTree = "<group>"; };
@@ -1027,6 +1047,7 @@
56012B682573FAE600B4925B /* CommonTableExpressionTests.swift */,
56EA63C7209C7F1E009715B8 /* DerivableRequestTests.swift */,
56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */,
568C3F7B2A5AB2D500A2309D /* ForeignKeyDefinitionTests.swift */,
56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */,
5698AC021D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift */,
563EF45521631E3E007DAACD /* QueryInterfacePromiseTests.swift */,
@@ -1175,8 +1196,12 @@
5656A8292295BD56001FF3FF /* SQLGeneration */ = {
isa = PBXGroup;
children = (
56F89E162A585E0D002FE2AA /* SQLColumnGenerator.swift */,
5656A82B2295BD56001FF3FF /* SQLGenerationContext.swift */,
563CBBE22A595141008905CE /* SQLIndexGenerator.swift */,
5656A82A2295BD56001FF3FF /* SQLQueryGenerator.swift */,
56F89E182A585E0D002FE2AA /* SQLTableAlterationGenerator.swift */,
56F89E192A585E0D002FE2AA /* SQLTableGenerator.swift */,
);
path = SQLGeneration;
sourceTree = "<group>";
@@ -1184,6 +1209,11 @@
5656A82C2295BD56001FF3FF /* Schema */ = {
isa = PBXGroup;
children = (
56F89DF82A57EAB9002FE2AA /* ColumnDefinition.swift */,
56F89E042A57EBA7002FE2AA /* Database+SchemaDefinition.swift */,
56F89E052A57EBA7002FE2AA /* ForeignKeyDefinition.swift */,
56F89E062A57EBA7002FE2AA /* IndexDefinition.swift */,
56F89E032A57EBA7002FE2AA /* TableAlteration.swift */,
5656A82D2295BD56001FF3FF /* TableDefinition.swift */,
5656A82E2295BD56001FF3FF /* VirtualTableModule.swift */,
);
@@ -1857,6 +1887,7 @@
563B8FBD24A1D388007A48C9 /* OnDemandFuture.swift in Sources */,
5656A85D2295BD56001FF3FF /* VirtualTableModule.swift in Sources */,
5656A8872295BD56001FF3FF /* SQLOperators.swift in Sources */,
56F89E092A57EBA7002FE2AA /* ForeignKeyDefinition.swift in Sources */,
566DDE12288D76400000DCFB /* Fixits.swift in Sources */,
563EF44D2161F196007DAACD /* Inflections.swift in Sources */,
566B910B1FA4C3970012D5B0 /* Database+Statements.swift in Sources */,
@@ -1871,6 +1902,7 @@
56CEB4F31EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */,
5656A8512295BD56001FF3FF /* SQLInterpolation+QueryInterface.swift in Sources */,
56BB6EAB1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */,
56F89E1A2A585E0D002FE2AA /* SQLColumnGenerator.swift in Sources */,
56894F332604FC1E00268F4D /* Table.swift in Sources */,
F3BA80761CFB2E55003DC1BA /* StatementColumnConvertible.swift in Sources */,
566B91351FA4D3810012D5B0 /* TransactionObserver.swift in Sources */,
@@ -1922,6 +1954,7 @@
563B8FB224A1CE9E007A48C9 /* DatabasePublishers.swift in Sources */,
56C0539D22ACEECD0029D27D /* RemoveDuplicates.swift in Sources */,
F3BA807C1CFB2E61003DC1BA /* Date.swift in Sources */,
56F89E1B2A585E0D002FE2AA /* SQLTableAlterationGenerator.swift in Sources */,
56A8C2321D1914540096E9D4 /* UUID.swift in Sources */,
5656A8812295BD56001FF3FF /* SQLCollection.swift in Sources */,
56D51D021EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */,
@@ -1949,6 +1982,8 @@
5656A8832295BD56001FF3FF /* SQLExpression.swift in Sources */,
5659F48A1EA8D94E004A4992 /* Utils.swift in Sources */,
F3BA807F1CFB2E61003DC1BA /* NSString.swift in Sources */,
56F89DFA2A57EAB9002FE2AA /* ColumnDefinition.swift in Sources */,
56F89E1C2A585E0D002FE2AA /* SQLTableGenerator.swift in Sources */,
560233D127243A9200529DF3 /* SharedValueObservation.swift in Sources */,
5656A8592295BD56001FF3FF /* SQLGenerationContext.swift in Sources */,
5690C3421D23E82A00E59934 /* Data.swift in Sources */,
@@ -1962,6 +1997,7 @@
5656A87F2295BD56001FF3FF /* SQLForeignKeyRequest.swift in Sources */,
56B964BB1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */,
F3BA807D1CFB2E61003DC1BA /* NSNull.swift in Sources */,
56F89E072A57EBA7002FE2AA /* TableAlteration.swift in Sources */,
56FBFED62210731100945324 /* SQLRequest.swift in Sources */,
5674A6FC1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */,
F3BA80701CFB2E55003DC1BA /* DatabaseValueConvertible.swift in Sources */,
@@ -1980,10 +2016,13 @@
564CE5B721B8FBEB00652B19 /* DatabaseRegionObservation.swift in Sources */,
5656A8612295BD56001FF3FF /* TableRecord+Association.swift in Sources */,
F3BA808C1CFB2E75003DC1BA /* DatabaseMigrator.swift in Sources */,
563CBBE42A595141008905CE /* SQLIndexGenerator.swift in Sources */,
5613ED6121A95E6100DC7A68 /* ValueObservation.swift in Sources */,
F3BA80921CFB2E7A003DC1BA /* TableRecord.swift in Sources */,
56F89E0A2A57EBA7002FE2AA /* IndexDefinition.swift in Sources */,
567071F4208A00BE006AD95A /* SQLiteDateParser.swift in Sources */,
56D110F328AFC90800E64463 /* MutablePersistableRecord.swift in Sources */,
56F89E082A57EBA7002FE2AA /* Database+SchemaDefinition.swift in Sources */,
F3BA80831CFB2E67003DC1BA /* DatabaseValueConvertible+RawRepresentable.swift in Sources */,
5657AABB1D107001006283EF /* NSData.swift in Sources */,
56D3332329C38D7B00430680 /* WALSnapshotTransaction.swift in Sources */,
@@ -2224,6 +2263,7 @@
56419C8124A51D6E004967E1 /* DatabaseRegionObservationPublisherTests.swift in Sources */,
561CFAA42376EF59000C8BAA /* AssociationHasManyThroughOrderingTests.swift in Sources */,
56ED8A7F1DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift in Sources */,
568C3F7D2A5AB2D500A2309D /* ForeignKeyDefinitionTests.swift in Sources */,
5698AD011DAA8ACB0056AF8C /* FTS5CustomTokenizerTests.swift in Sources */,
F3BA80B51CFB2FCA003DC1BA /* DatabaseQueueInMemoryTests.swift in Sources */,
56A4CDB31D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */,
+35 -6
View File
@@ -75,7 +75,7 @@ test_framework_darwin: test_framework_GRDB test_framework_GRDBCustom test_framew
test_framework_GRDB: test_framework_GRDBOSX test_framework_GRDBiOS test_framework_GRDBtvOS
test_framework_GRDBCustom: test_framework_GRDBCustomSQLiteOSX test_framework_GRDBCustomSQLiteiOS
test_framework_SQLCipher: test_framework_SQLCipher3 test_framework_SQLCipher3Encrypted test_framework_SQLCipher4 test_framework_SQLCipher4Encrypted
test_archive: test_archive_GRDBOSX_xcframework
test_archive: test_universal_xcframework
test_install: test_install_manual test_install_SPM test_install_customSQLite test_install_GRDB_CocoaPods test_CocoaPodsLint
test_CocoaPodsLint: test_CocoaPodsLint_GRDB
test_demo_apps: test_GRDBDemoiOS test_GRDBCombineDemo test_GRDBAsyncDemo
@@ -219,22 +219,51 @@ test_SPM:
$(SWIFT) build -c release
set -o pipefail && $(SWIFT) test --parallel
test_archive_GRDBOSX_xcframework:
test_universal_xcframework:
rm -rf Tests/products
mkdir Tests/products
$(XCODEBUILD) archive \
-project GRDB.xcodeproj \
-scheme GRDB \
-configuration Release \
-destination "generic/platform=iOS" \
OTHER_SWIFT_FLAGS=$(OTHER_SWIFT_FLAGS) \
GCC_PREPROCESSOR_DEFINITIONS=$(GCC_PREPROCESSOR_DEFINITIONS) \
-archivePath "$(PWD)/Tests/products/GRDB-iOS.xcarchive" \
SKIP_INSTALL=NO \
BUILD_LIBRARY_FOR_DISTRIBUTION=YES
$(XCODEBUILD) archive \
-project GRDB.xcodeproj \
-scheme GRDB \
-destination "generic/platform=iOS Simulator" \
OTHER_SWIFT_FLAGS=$(OTHER_SWIFT_FLAGS) \
GCC_PREPROCESSOR_DEFINITIONS=$(GCC_PREPROCESSOR_DEFINITIONS) \
-archivePath "$(PWD)/Tests/products/GRDB-iOS_Simulator.xcarchive" \
SKIP_INSTALL=NO \
BUILD_LIBRARY_FOR_DISTRIBUTION=YES
$(XCODEBUILD) archive \
-project GRDB.xcodeproj \
-scheme GRDB \
-destination "generic/platform=macOS" \
OTHER_SWIFT_FLAGS=$(OTHER_SWIFT_FLAGS) \
GCC_PREPROCESSOR_DEFINITIONS=$(GCC_PREPROCESSOR_DEFINITIONS) \
-archivePath "$(PWD)/Tests/products/GRDB.xcarchive" \
-archivePath "$(PWD)/Tests/products/GRDB-macOS.xcarchive" \
SKIP_INSTALL=NO \
BUILD_LIBRARY_FOR_DISTRIBUTION=YES
$(XCODEBUILD) archive \
-project GRDB.xcodeproj \
-scheme GRDB \
-destination "generic/platform=macOS,variant=Mac Catalyst" \
OTHER_SWIFT_FLAGS=$(OTHER_SWIFT_FLAGS) \
GCC_PREPROCESSOR_DEFINITIONS=$(GCC_PREPROCESSOR_DEFINITIONS) \
-archivePath "$(PWD)/Tests/products/GRDB-Mac_Catalyst.xcarchive" \
SKIP_INSTALL=NO \
BUILD_LIBRARY_FOR_DISTRIBUTION=YES
$(XCODEBUILD) -create-xcframework \
-framework '$(PWD)/Tests/products/GRDB.xcarchive/Products/Library/Frameworks/GRDB.framework' \
-output '$(PWD)/Tests/products/GRDB.xcframework'
-archive '$(PWD)/Tests/products/GRDB-iOS.xcarchive' -framework GRDB.framework \
-archive '$(PWD)/Tests/products/GRDB-iOS_Simulator.xcarchive' -framework GRDB.framework \
-archive '$(PWD)/Tests/products/GRDB-macOS.xcarchive' -framework GRDB.framework \
-archive '$(PWD)/Tests/products/GRDB-Mac_Catalyst.xcarchive' -framework GRDB.framework \
-output '$(PWD)/Tests/products/GRDB.xcframework'
test_install_manual:
$(XCODEBUILD) \
+1 -1
View File
@@ -15,7 +15,7 @@
<a href="https://github.com/groue/GRDB.swift/actions/workflows/CI.yml"><img alt="CI Status" src="https://github.com/groue/GRDB.swift/actions/workflows/CI.yml/badge.svg?branch=master"></a>
</p>
**Latest release**: June 17, 2023 • [version 6.15.1](https://github.com/groue/GRDB.swift/tree/v6.15.1) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md)
**Latest release**: July 9, 2023 • [version 6.16.0](https://github.com/groue/GRDB.swift/tree/v6.16.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md)
**Requirements**: iOS 11.0+ / macOS 10.13+ / tvOS 11.0+ / watchOS 4.0+ &bull; SQLite 3.19.3+ &bull; Swift 5.7+ / Xcode 14+
+1 -1
View File
@@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>6.15.1</string>
<string>6.16.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
@@ -445,6 +445,8 @@
565A27CD27871FFF00659A62 /* BackupTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565A27CB27871FFF00659A62 /* BackupTestCase.swift */; };
567B23172A29BFA400C61174 /* Issue1383.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = 567B23162A29BFA400C61174 /* Issue1383.sqlite */; };
567B23182A29BFA500C61174 /* Issue1383.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = 567B23162A29BFA400C61174 /* Issue1383.sqlite */; };
568C3F7F2A5AB36900A2309D /* ForeignKeyDefinitionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F7E2A5AB36900A2309D /* ForeignKeyDefinitionTests.swift */; };
568C3F802A5AB36900A2309D /* ForeignKeyDefinitionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F7E2A5AB36900A2309D /* ForeignKeyDefinitionTests.swift */; };
5691D97527257CE40021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97427257CE40021D540 /* AvailableElements.swift */; };
5691D97627257CE40021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97427257CE40021D540 /* AvailableElements.swift */; };
56F61DF0283D484700AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DEE283D484700AF9884 /* getThreadsCount.c */; };
@@ -679,6 +681,7 @@
564A2156226B8E18001F64F1 /* GRDBTestsEncrypted.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBTestsEncrypted.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
565A27CB27871FFF00659A62 /* BackupTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BackupTestCase.swift; sourceTree = "<group>"; };
567B23162A29BFA400C61174 /* Issue1383.sqlite */ = {isa = PBXFileReference; lastKnownFileType = file; path = Issue1383.sqlite; sourceTree = "<group>"; };
568C3F7E2A5AB36900A2309D /* ForeignKeyDefinitionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKeyDefinitionTests.swift; sourceTree = "<group>"; };
5691D97427257CE40021D540 /* AvailableElements.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AvailableElements.swift; sourceTree = "<group>"; };
56F61DEC283D484700AF9884 /* GRDBTests-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "GRDBTests-Bridging-Header.h"; sourceTree = "<group>"; };
56F61DEE283D484700AF9884 /* getThreadsCount.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = getThreadsCount.c; sourceTree = "<group>"; };
@@ -877,6 +880,7 @@
56419CB724A54055004967E1 /* FetchRequestTests.swift */,
56419D5B24A54061004967E1 /* FilterCursorTests.swift */,
56419D4B24A54060004967E1 /* FlattenCursorTests.swift */,
568C3F7E2A5AB36900A2309D /* ForeignKeyDefinitionTests.swift */,
56419CF124A54059004967E1 /* ForeignKeyInfoTests.swift */,
56419D2E24A5405E004967E1 /* FoundationDataTests.swift */,
56419D6624A54062004967E1 /* FoundationDateComponentsTests.swift */,
@@ -1209,6 +1213,7 @@
56419DC124A54062004967E1 /* FoundationNSDateTests.swift in Sources */,
56419EC524A54063004967E1 /* FlattenCursorTests.swift in Sources */,
56419E9D24A54063004967E1 /* StatementArgumentsTests.swift in Sources */,
568C3F7F2A5AB36900A2309D /* ForeignKeyDefinitionTests.swift in Sources */,
5641A1AA24A540D6004967E1 /* Recorder.swift in Sources */,
56419D7B24A54062004967E1 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */,
56419D6B24A54062004967E1 /* DatabaseQueueTests.swift in Sources */,
@@ -1434,6 +1439,7 @@
56419DC224A54062004967E1 /* FoundationNSDateTests.swift in Sources */,
56419EC624A54063004967E1 /* FlattenCursorTests.swift in Sources */,
56419E9E24A54063004967E1 /* StatementArgumentsTests.swift in Sources */,
568C3F802A5AB36900A2309D /* ForeignKeyDefinitionTests.swift in Sources */,
5641A1AB24A540D6004967E1 /* Recorder.swift in Sources */,
56419D7C24A54062004967E1 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */,
56419D6C24A54062004967E1 /* DatabaseQueueTests.swift in Sources */,
+3
View File
@@ -17,6 +17,9 @@ end
post_install do |installer|
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
# Workaround for Xcode 14.3+
# https://github.com/CocoaPods/CocoaPods/issues/11839
config.build_settings['MACOSX_DEPLOYMENT_TARGET'] = '10.13'
config.build_settings['GCC_OPTIMIZATION_LEVEL'] = '3'
end
end
@@ -447,6 +447,22 @@
565A27CA27871FE500659A62 /* BackupTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565A27C827871FE500659A62 /* BackupTestCase.swift */; };
567B231A2A29BFE100C61174 /* Issue1383.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = 567B23192A29BFE100C61174 /* Issue1383.sqlite */; };
567B231B2A29BFE100C61174 /* Issue1383.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = 567B23192A29BFE100C61174 /* Issue1383.sqlite */; };
568C3F822A5AB38300A2309D /* ForeignKeyDefinitionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F812A5AB38300A2309D /* ForeignKeyDefinitionTests.swift */; };
568C3F832A5AB38300A2309D /* ForeignKeyDefinitionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F812A5AB38300A2309D /* ForeignKeyDefinitionTests.swift */; };
568C3F8B2A5AB3A800A2309D /* AssociationPrefetchingRelationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F842A5AB3A800A2309D /* AssociationPrefetchingRelationTests.swift */; };
568C3F8C2A5AB3A800A2309D /* AssociationPrefetchingRelationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F842A5AB3A800A2309D /* AssociationPrefetchingRelationTests.swift */; };
568C3F8D2A5AB3A800A2309D /* DatabaseColumnEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F852A5AB3A800A2309D /* DatabaseColumnEncodingStrategyTests.swift */; };
568C3F8E2A5AB3A800A2309D /* DatabaseColumnEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F852A5AB3A800A2309D /* DatabaseColumnEncodingStrategyTests.swift */; };
568C3F8F2A5AB3A800A2309D /* FoundationDecimalTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F862A5AB3A800A2309D /* FoundationDecimalTests.swift */; };
568C3F902A5AB3A800A2309D /* FoundationDecimalTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F862A5AB3A800A2309D /* FoundationDecimalTests.swift */; };
568C3F912A5AB3A800A2309D /* CommonTableExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F872A5AB3A800A2309D /* CommonTableExpressionTests.swift */; };
568C3F922A5AB3A800A2309D /* CommonTableExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F872A5AB3A800A2309D /* CommonTableExpressionTests.swift */; };
568C3F932A5AB3A800A2309D /* CaseInsensitiveIdentifierTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F882A5AB3A800A2309D /* CaseInsensitiveIdentifierTests.swift */; };
568C3F942A5AB3A800A2309D /* CaseInsensitiveIdentifierTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F882A5AB3A800A2309D /* CaseInsensitiveIdentifierTests.swift */; };
568C3F952A5AB3A800A2309D /* DatabaseSnapshotPoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F892A5AB3A800A2309D /* DatabaseSnapshotPoolTests.swift */; };
568C3F962A5AB3A800A2309D /* DatabaseSnapshotPoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F892A5AB3A800A2309D /* DatabaseSnapshotPoolTests.swift */; };
568C3F972A5AB3A800A2309D /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F8A2A5AB3A800A2309D /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift */; };
568C3F982A5AB3A800A2309D /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F8A2A5AB3A800A2309D /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift */; };
5691D97227257C930021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97127257C930021D540 /* AvailableElements.swift */; };
5691D97327257C930021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97127257C930021D540 /* AvailableElements.swift */; };
56F61DF6283D4AB100AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DF4283D4AB100AF9884 /* getThreadsCount.c */; };
@@ -682,6 +698,14 @@
564A2158226C8F24001F64F1 /* db.SQLCipher3 */ = {isa = PBXFileReference; lastKnownFileType = file; path = db.SQLCipher3; sourceTree = SOURCE_ROOT; };
565A27C827871FE500659A62 /* BackupTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BackupTestCase.swift; sourceTree = "<group>"; };
567B23192A29BFE100C61174 /* Issue1383.sqlite */ = {isa = PBXFileReference; lastKnownFileType = file; path = Issue1383.sqlite; sourceTree = "<group>"; };
568C3F812A5AB38300A2309D /* ForeignKeyDefinitionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKeyDefinitionTests.swift; sourceTree = "<group>"; };
568C3F842A5AB3A800A2309D /* AssociationPrefetchingRelationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingRelationTests.swift; sourceTree = "<group>"; };
568C3F852A5AB3A800A2309D /* DatabaseColumnEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseColumnEncodingStrategyTests.swift; sourceTree = "<group>"; };
568C3F862A5AB3A800A2309D /* FoundationDecimalTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDecimalTests.swift; sourceTree = "<group>"; };
568C3F872A5AB3A800A2309D /* CommonTableExpressionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CommonTableExpressionTests.swift; sourceTree = "<group>"; };
568C3F882A5AB3A800A2309D /* CaseInsensitiveIdentifierTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CaseInsensitiveIdentifierTests.swift; sourceTree = "<group>"; };
568C3F892A5AB3A800A2309D /* DatabaseSnapshotPoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotPoolTests.swift; sourceTree = "<group>"; };
568C3F8A2A5AB3A800A2309D /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordMinimalNonOptionalPrimaryKeySingleTests.swift; sourceTree = "<group>"; };
5691D97127257C930021D540 /* AvailableElements.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AvailableElements.swift; sourceTree = "<group>"; };
56F61DF2283D4AB100AF9884 /* GRDBTests-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "GRDBTests-Bridging-Header.h"; sourceTree = "<group>"; };
56F61DF4283D4AB100AF9884 /* getThreadsCount.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = getThreadsCount.c; sourceTree = "<group>"; };
@@ -811,14 +835,17 @@
56419F9A24A5409D004967E1 /* AssociationPrefetchingCodableRecordTests.swift */,
56419F2224A54095004967E1 /* AssociationPrefetchingFetchableRecordTests.swift */,
56419F8F24A5409C004967E1 /* AssociationPrefetchingObservationTests.swift */,
568C3F842A5AB3A800A2309D /* AssociationPrefetchingRelationTests.swift */,
56419F1E24A54094004967E1 /* AssociationPrefetchingRowTests.swift */,
56419F4424A54097004967E1 /* AssociationPrefetchingSQLTests.swift */,
56419F5024A54098004967E1 /* AssociationRowScopeSearchTests.swift */,
56419F9E24A5409D004967E1 /* AssociationTableAliasTestsSQLTests.swift */,
565A27C827871FE500659A62 /* BackupTestCase.swift */,
568C3F882A5AB3A800A2309D /* CaseInsensitiveIdentifierTests.swift */,
56419F6B24A5409A004967E1 /* CGFloatTests.swift */,
56419F6524A54099004967E1 /* ColumnExpressionTests.swift */,
56419F9324A5409D004967E1 /* ColumnInfoTests.swift */,
568C3F872A5AB3A800A2309D /* CommonTableExpressionTests.swift */,
56419F5424A54098004967E1 /* CompilationProtocolTests.swift */,
56419F8024A5409B004967E1 /* CompilationSubClassTests.swift */,
56419FBF24A540A0004967E1 /* CursorTests.swift */,
@@ -826,6 +853,7 @@
56419F9D24A5409D004967E1 /* DatabaseAfterNextTransactionCommitTests.swift */,
56419F8A24A5409C004967E1 /* DatabaseAggregateTests.swift */,
56419FBB24A540A0004967E1 /* DatabaseCollationTests.swift */,
568C3F852A5AB3A800A2309D /* DatabaseColumnEncodingStrategyTests.swift */,
56419F7024A5409A004967E1 /* DatabaseConfigurationTests.swift */,
56419F2324A54095004967E1 /* DatabaseCursorTests.swift */,
56419FBE24A540A0004967E1 /* DatabaseDateDecodingStrategyTests.swift */,
@@ -853,6 +881,7 @@
56419F0524A54093004967E1 /* DatabaseRegionObservationTests.swift */,
56419F0424A54093004967E1 /* DatabaseRegionTests.swift */,
56419F0D24A54093004967E1 /* DatabaseSavepointTests.swift */,
568C3F892A5AB3A800A2309D /* DatabaseSnapshotPoolTests.swift */,
56419FB424A5409F004967E1 /* DatabaseSnapshotTests.swift */,
56419F1D24A54094004967E1 /* DatabaseSuspensionTests.swift */,
56419F7324A5409A004967E1 /* DatabaseTests.swift */,
@@ -881,10 +910,12 @@
56419EFD24A54093004967E1 /* FetchRequestTests.swift */,
56419FAD24A5409F004967E1 /* FilterCursorTests.swift */,
56419FAE24A5409F004967E1 /* FlattenCursorTests.swift */,
568C3F812A5AB38300A2309D /* ForeignKeyDefinitionTests.swift */,
56419F7224A5409A004967E1 /* ForeignKeyInfoTests.swift */,
56419FC524A540A1004967E1 /* FoundationDataTests.swift */,
56419F2524A54095004967E1 /* FoundationDateComponentsTests.swift */,
56419F1124A54093004967E1 /* FoundationDateTests.swift */,
568C3F862A5AB3A800A2309D /* FoundationDecimalTests.swift */,
56419F9F24A5409E004967E1 /* FoundationNSDataTests.swift */,
56419FB224A5409F004967E1 /* FoundationNSDateTests.swift */,
56419F8124A5409B004967E1 /* FoundationNSDecimalNumberTests.swift */,
@@ -931,6 +962,7 @@
56419F0724A54093004967E1 /* Record+QueryInterfaceRequestTests.swift */,
56419F2124A54094004967E1 /* RecordEditedTests.swift */,
56419F4824A54097004967E1 /* RecordInitializersTests.swift */,
568C3F8A2A5AB3A800A2309D /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift */,
56419F0C24A54093004967E1 /* RecordMinimalPrimaryKeyRowIDTests.swift */,
56419F6124A54099004967E1 /* RecordMinimalPrimaryKeySingleTests.swift */,
56419F5124A54098004967E1 /* RecordPersistenceConflictPolicy.swift */,
@@ -1203,6 +1235,7 @@
5641A0A424A540A1004967E1 /* CGFloatTests.swift in Sources */,
5641A0F824A540A1004967E1 /* RecordPrimaryKeyNoneTests.swift in Sources */,
5641A01C24A540A1004967E1 /* PrefixCursorTests.swift in Sources */,
568C3F8D2A5AB3A800A2309D /* DatabaseColumnEncodingStrategyTests.swift in Sources */,
56419FEE24A540A1004967E1 /* DatabasePoolCollationTests.swift in Sources */,
5641A15424A540A2004967E1 /* DataMemoryTests.swift in Sources */,
5641A0D224A540A1004967E1 /* AssociationHasOneThroughSQLTests.swift in Sources */,
@@ -1212,9 +1245,11 @@
5641A17C24A540C7004967E1 /* Prefix.swift in Sources */,
5641A17E24A540C7004967E1 /* Map.swift in Sources */,
5641A0F024A540A1004967E1 /* FTS4RecordTests.swift in Sources */,
568C3F972A5AB3A800A2309D /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift in Sources */,
5641A0BA24A540A1004967E1 /* PrefixWhileCursorTests.swift in Sources */,
5641A0B624A540A1004967E1 /* DatabasePoolTests.swift in Sources */,
5641A0B424A540A1004967E1 /* DatabaseTests.swift in Sources */,
568C3F822A5AB38300A2309D /* ForeignKeyDefinitionTests.swift in Sources */,
5641A06024A540A1004967E1 /* AssociationChainRowScopesTests.swift in Sources */,
5641A0C624A540A1004967E1 /* FetchableRecordDecodableTests.swift in Sources */,
5641A03424A540A1004967E1 /* RowFromDictionaryTests.swift in Sources */,
@@ -1264,14 +1299,17 @@
5641A02224A540A1004967E1 /* ValueObservationFetchTests.swift in Sources */,
5641A12624A540A1004967E1 /* DatabasePoolSchemaCacheTests.swift in Sources */,
5641A13024A540A1004967E1 /* AssociationBelongsToFetchableRecordTests.swift in Sources */,
568C3F8F2A5AB3A800A2309D /* FoundationDecimalTests.swift in Sources */,
56419FFE24A540A1004967E1 /* FTS5TokenizerTests.swift in Sources */,
5641A0FA24A540A1004967E1 /* FetchableRecordTests.swift in Sources */,
5641A09424A540A1004967E1 /* ValueObservationCountTests.swift in Sources */,
5641A0EA24A540A1004967E1 /* RowFromDictionaryLiteralTests.swift in Sources */,
5641A09224A540A1004967E1 /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */,
5641A04E24A540A1004967E1 /* RecordUniqueIndexTests.swift in Sources */,
568C3F912A5AB3A800A2309D /* CommonTableExpressionTests.swift in Sources */,
5641A12824A540A1004967E1 /* FilterCursorTests.swift in Sources */,
5641A0CE24A540A1004967E1 /* CompilationSubClassTests.swift in Sources */,
568C3F952A5AB3A800A2309D /* DatabaseSnapshotPoolTests.swift in Sources */,
5641A0DE24A540A1004967E1 /* QueryInterfaceExpressionsTests.swift in Sources */,
5641A0C424A540A1004967E1 /* MapCursorTests.swift in Sources */,
5641A06E24A540A1004967E1 /* AssociationRowScopeSearchTests.swift in Sources */,
@@ -1326,6 +1364,7 @@
5641A05024A540A1004967E1 /* FTS3PatternTests.swift in Sources */,
5641A17024A540C7004967E1 /* Recorder.swift in Sources */,
5641A11024A540A1004967E1 /* Row+FoundationTests.swift in Sources */,
568C3F932A5AB3A800A2309D /* CaseInsensitiveIdentifierTests.swift in Sources */,
56419FC824A540A1004967E1 /* FetchRequestTests.swift in Sources */,
56419FDC24A540A1004967E1 /* Record+QueryInterfaceRequestTests.swift in Sources */,
5641A0B224A540A1004967E1 /* ForeignKeyInfoTests.swift in Sources */,
@@ -1352,6 +1391,7 @@
5641A0B024A540A1004967E1 /* AssociationHasOneThroughRowScopeTests.swift in Sources */,
5641A00A24A540A1004967E1 /* AssociationPrefetchingRowTests.swift in Sources */,
5641A0B824A540A1004967E1 /* FTS5CustomTokenizerTests.swift in Sources */,
568C3F8B2A5AB3A800A2309D /* AssociationPrefetchingRelationTests.swift in Sources */,
5641A04824A540A1004967E1 /* DatabaseValueConversionTests.swift in Sources */,
5641A07824A540A1004967E1 /* DropFirstCursorTests.swift in Sources */,
5641A13224A540A1004967E1 /* FoundationNSDateTests.swift in Sources */,
@@ -1428,6 +1468,7 @@
5641A0A524A540A1004967E1 /* CGFloatTests.swift in Sources */,
5641A0F924A540A1004967E1 /* RecordPrimaryKeyNoneTests.swift in Sources */,
5641A01D24A540A1004967E1 /* PrefixCursorTests.swift in Sources */,
568C3F8E2A5AB3A800A2309D /* DatabaseColumnEncodingStrategyTests.swift in Sources */,
56419FEF24A540A1004967E1 /* DatabasePoolCollationTests.swift in Sources */,
5641A15524A540A2004967E1 /* DataMemoryTests.swift in Sources */,
5641A0D324A540A1004967E1 /* AssociationHasOneThroughSQLTests.swift in Sources */,
@@ -1437,9 +1478,11 @@
5641A17D24A540C7004967E1 /* Prefix.swift in Sources */,
5641A17F24A540C7004967E1 /* Map.swift in Sources */,
5641A0F124A540A1004967E1 /* FTS4RecordTests.swift in Sources */,
568C3F982A5AB3A800A2309D /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift in Sources */,
5641A0BB24A540A1004967E1 /* PrefixWhileCursorTests.swift in Sources */,
5641A0B724A540A1004967E1 /* DatabasePoolTests.swift in Sources */,
5641A0B524A540A1004967E1 /* DatabaseTests.swift in Sources */,
568C3F832A5AB38300A2309D /* ForeignKeyDefinitionTests.swift in Sources */,
5641A06124A540A1004967E1 /* AssociationChainRowScopesTests.swift in Sources */,
5641A0C724A540A1004967E1 /* FetchableRecordDecodableTests.swift in Sources */,
5641A03524A540A1004967E1 /* RowFromDictionaryTests.swift in Sources */,
@@ -1489,14 +1532,17 @@
5641A02324A540A1004967E1 /* ValueObservationFetchTests.swift in Sources */,
5641A12724A540A1004967E1 /* DatabasePoolSchemaCacheTests.swift in Sources */,
5641A13124A540A1004967E1 /* AssociationBelongsToFetchableRecordTests.swift in Sources */,
568C3F902A5AB3A800A2309D /* FoundationDecimalTests.swift in Sources */,
56419FFF24A540A1004967E1 /* FTS5TokenizerTests.swift in Sources */,
5641A0FB24A540A1004967E1 /* FetchableRecordTests.swift in Sources */,
5641A09524A540A1004967E1 /* ValueObservationCountTests.swift in Sources */,
5641A0EB24A540A1004967E1 /* RowFromDictionaryLiteralTests.swift in Sources */,
5641A09324A540A1004967E1 /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */,
5641A04F24A540A1004967E1 /* RecordUniqueIndexTests.swift in Sources */,
568C3F922A5AB3A800A2309D /* CommonTableExpressionTests.swift in Sources */,
5641A12924A540A1004967E1 /* FilterCursorTests.swift in Sources */,
5641A0CF24A540A1004967E1 /* CompilationSubClassTests.swift in Sources */,
568C3F962A5AB3A800A2309D /* DatabaseSnapshotPoolTests.swift in Sources */,
5641A0DF24A540A1004967E1 /* QueryInterfaceExpressionsTests.swift in Sources */,
5641A0C524A540A1004967E1 /* MapCursorTests.swift in Sources */,
5641A06F24A540A1004967E1 /* AssociationRowScopeSearchTests.swift in Sources */,
@@ -1551,6 +1597,7 @@
5641A05124A540A1004967E1 /* FTS3PatternTests.swift in Sources */,
5641A17124A540C7004967E1 /* Recorder.swift in Sources */,
5641A11124A540A1004967E1 /* Row+FoundationTests.swift in Sources */,
568C3F942A5AB3A800A2309D /* CaseInsensitiveIdentifierTests.swift in Sources */,
56419FC924A540A1004967E1 /* FetchRequestTests.swift in Sources */,
56419FDD24A540A1004967E1 /* Record+QueryInterfaceRequestTests.swift in Sources */,
5641A0B324A540A1004967E1 /* ForeignKeyInfoTests.swift in Sources */,
@@ -1577,6 +1624,7 @@
5641A0B124A540A1004967E1 /* AssociationHasOneThroughRowScopeTests.swift in Sources */,
5641A00B24A540A1004967E1 /* AssociationPrefetchingRowTests.swift in Sources */,
5641A0B924A540A1004967E1 /* FTS5CustomTokenizerTests.swift in Sources */,
568C3F8C2A5AB3A800A2309D /* AssociationPrefetchingRelationTests.swift in Sources */,
5641A04924A540A1004967E1 /* DatabaseValueConversionTests.swift in Sources */,
5641A07924A540A1004967E1 /* DropFirstCursorTests.swift in Sources */,
5641A13324A540A1004967E1 /* FoundationNSDateTests.swift in Sources */,
+3
View File
@@ -17,6 +17,9 @@ end
post_install do |installer|
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
# Workaround for Xcode 14.3+
# https://github.com/CocoaPods/CocoaPods/issues/11839
config.build_settings['MACOSX_DEPLOYMENT_TARGET'] = '10.13'
config.build_settings['GCC_OPTIMIZATION_LEVEL'] = '3'
end
end
@@ -51,13 +51,13 @@ class AssociationAggregateTests: GRDBTestCase {
}
try db.create(table: "player") { t in
t.primaryKey("id", .integer)
t.column("teamId", .integer).references("team")
t.belongsTo("team")
t.column("name", .text)
t.column("score", .integer)
}
try db.create(table: "award") { t in
t.primaryKey("customPrimaryKey", .integer)
t.column("teamId", .integer).references("team")
t.belongsTo("team")
t.column("name", .text)
}
@@ -55,7 +55,7 @@ class AssociationBelongsToDecodableRecordTests: GRDBTestCase {
}
try db.create(table: "players") { t in
t.primaryKey("id", .integer)
t.column("teamId", .integer).references("teams")
t.belongsTo("team")
t.column("name", .text)
}
@@ -57,7 +57,7 @@ class AssociationBelongsToFetchableRecordTests: GRDBTestCase {
}
try db.create(table: "players") { t in
t.primaryKey("id", .integer)
t.column("teamId", .integer).references("teams")
t.belongsTo("team")
t.column("name", .text)
}
@@ -27,7 +27,7 @@ class AssociationBelongsToRowScopeTests: GRDBTestCase {
}
try db.create(table: "players") { t in
t.primaryKey("id", .integer)
t.column("teamId", .integer).references("teams")
t.belongsTo("team")
t.column("name", .text)
}
@@ -330,7 +330,7 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
t.column("name", .text)
}
try db.create(table: "children") { t in
t.column("parentId", .integer).references("parents")
t.belongsTo("parent")
}
}
@@ -546,8 +546,8 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
t.column("name", .text)
}
try db.create(table: "children") { t in
t.column("parent1Id", .integer).references("parents")
t.column("parent2Id", .integer).references("parents")
t.belongsTo("parent1", inTable: "parents")
t.belongsTo("parent2", inTable: "parents")
}
}
@@ -1742,7 +1742,7 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
}
try db.create(table: "b") { t in
t.autoIncrementedPrimaryKey("id")
t.column("aId", .integer).references("a")
t.belongsTo("a")
}
struct A: TableRecord { }
struct B: TableRecord { }
@@ -1771,7 +1771,7 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
t.column("name", .text)
}
try db.create(table: "children") { t in
t.column("parentId", .integer).references("parents")
t.belongsTo("parent")
}
}
@@ -36,7 +36,7 @@ class AssociationHasManyOrderingTests: GRDBTestCase {
}
try db.create(table: "player") { t in
t.primaryKey("id", .integer)
t.column("teamId", .integer).notNull().references("team")
t.belongsTo("team").notNull()
t.column("name", .text).notNull()
t.column("position", .integer).notNull()
}
@@ -18,7 +18,7 @@ class AssociationHasManyRowScopeTests: GRDBTestCase {
}
try db.create(table: "child") { t in
t.autoIncrementedPrimaryKey("id")
t.column("parentId", .integer).references("parent")
t.belongsTo("parent")
}
try db.execute(sql: """
INSERT INTO parent (id) VALUES (1);
@@ -49,7 +49,7 @@ class AssociationHasManyRowScopeTests: GRDBTestCase {
}
try db.create(table: "children") { t in
t.autoIncrementedPrimaryKey("id")
t.column("parentId", .integer).references("parents")
t.belongsTo("parent")
}
try db.execute(sql: """
INSERT INTO parents (id) VALUES (1);
@@ -79,7 +79,7 @@ class AssociationHasManyRowScopeTests: GRDBTestCase {
}
try db.create(table: "child") { t in
t.autoIncrementedPrimaryKey("id")
t.column("parentId", .integer).references("parent")
t.belongsTo("parent")
}
try db.execute(sql: """
INSERT INTO parent (id) VALUES (1);
@@ -217,7 +217,7 @@ class AssociationHasManySQLTests: GRDBTestCase {
t.primaryKey("id", .integer)
}
try db.create(table: "children") { t in
t.column("parentId", .integer).references("parents")
t.belongsTo("parent")
}
}
@@ -346,8 +346,8 @@ class AssociationHasManySQLTests: GRDBTestCase {
t.primaryKey("id", .integer)
}
try db.create(table: "children") { t in
t.column("parent1Id", .integer).references("parents")
t.column("parent2Id", .integer).references("parents")
t.belongsTo("parent1", inTable: "parents")
t.belongsTo("parent2", inTable: "parents")
}
}
@@ -1074,10 +1074,10 @@ class AssociationHasManySQLTests: GRDBTestCase {
}
try db.create(table: "child") { t in
t.autoIncrementedPrimaryKey("id")
t.column("parentId", .integer).references("parent")
t.belongsTo("parent")
}
try db.create(table: "toy") { t in
t.column("childId", .integer).references("child")
t.belongsTo("child")
}
}
@@ -40,8 +40,8 @@ class AssociationHasManyThroughOrderingTests: GRDBTestCase {
t.column("name", .text).notNull()
}
try db.create(table: "playerRole") { t in
t.column("teamId", .integer).notNull().references("team")
t.column("playerId", .integer).notNull().references("player")
t.belongsTo("team").notNull()
t.belongsTo("player").notNull()
t.column("position", .integer).notNull()
t.primaryKey(["teamId", "playerId"])
}
@@ -23,11 +23,11 @@ class AssociationHasManyThroughRowScopeTests: GRDBTestCase {
}
try db.create(table: "parent") { t in
t.autoIncrementedPrimaryKey("id")
t.column("childId").references("child")
t.belongsTo("child")
}
try db.create(table: "grandChild") { t in
t.autoIncrementedPrimaryKey("id")
t.column("childId").references("child")
t.belongsTo("child")
}
try db.execute(sql: """
INSERT INTO child (id) VALUES (1);
@@ -64,11 +64,11 @@ class AssociationHasManyThroughRowScopeTests: GRDBTestCase {
}
try db.create(table: "parents") { t in
t.autoIncrementedPrimaryKey("id")
t.column("childId").references("children")
t.belongsTo("child")
}
try db.create(table: "grandChildren") { t in
t.autoIncrementedPrimaryKey("id")
t.column("childId").references("children")
t.belongsTo("child")
}
try db.execute(sql: """
INSERT INTO children (id) VALUES (1);
@@ -106,11 +106,11 @@ class AssociationHasManyThroughRowScopeTests: GRDBTestCase {
}
try db.create(table: "parents") { t in
t.autoIncrementedPrimaryKey("id")
t.column("childId").references("children")
t.belongsTo("child")
}
try db.create(table: "grandChildren") { t in
t.autoIncrementedPrimaryKey("id")
t.column("childId").references("children")
t.belongsTo("child")
}
try db.execute(sql: """
INSERT INTO children (id) VALUES (1);
@@ -157,8 +157,8 @@ class AssociationHasManyThroughRowScopeTests: GRDBTestCase {
}
try db.create(table: "child") { t in
t.autoIncrementedPrimaryKey("id")
t.column("parentId").references("parent")
t.column("grandChildId").references("grandChild")
t.belongsTo("parent")
t.belongsTo("grandChild")
}
try db.execute(sql: """
INSERT INTO parent (id) VALUES (1);
@@ -198,8 +198,8 @@ class AssociationHasManyThroughRowScopeTests: GRDBTestCase {
}
try db.create(table: "children") { t in
t.autoIncrementedPrimaryKey("id")
t.column("parentId").references("parents")
t.column("grandChildId").references("grandChildren")
t.belongsTo("parent")
t.belongsTo("grandChild")
}
try db.execute(sql: """
INSERT INTO parents (id) VALUES (1);
@@ -237,8 +237,8 @@ class AssociationHasManyThroughRowScopeTests: GRDBTestCase {
}
try db.create(table: "child") { t in
t.autoIncrementedPrimaryKey("id")
t.column("parentId").references("parent")
t.column("grandChildId").references("grandChild")
t.belongsTo("parent")
t.belongsTo("grandChild")
}
try db.execute(sql: """
INSERT INTO parent (id) VALUES (1);
@@ -26,11 +26,11 @@ class AssociationHasManyThroughSQLTests: GRDBTestCase {
}
try db.create(table: "a") { t in
t.autoIncrementedPrimaryKey("id")
t.column("bId").references("b")
t.belongsTo("b")
}
try db.create(table: "c") { t in
t.autoIncrementedPrimaryKey("id")
t.column("bId").references("b")
t.belongsTo("b")
}
try testHasManyWithTwoSteps(
@@ -66,11 +66,11 @@ class AssociationHasManyThroughSQLTests: GRDBTestCase {
}
try db.create(table: "b") { t in
t.autoIncrementedPrimaryKey("id")
t.column("aId").references("a")
t.belongsTo("a")
}
try db.create(table: "c") { t in
t.autoIncrementedPrimaryKey("id")
t.column("bId").references("b")
t.belongsTo("b")
}
try testHasManyWithTwoSteps(
@@ -109,8 +109,8 @@ class AssociationHasManyThroughSQLTests: GRDBTestCase {
}
try db.create(table: "b") { t in
t.autoIncrementedPrimaryKey("id")
t.column("cId").references("c")
t.column("aId").references("a")
t.belongsTo("c")
t.belongsTo("a")
}
try testHasManyWithTwoSteps(
@@ -146,11 +146,11 @@ class AssociationHasManyThroughSQLTests: GRDBTestCase {
}
try db.create(table: "b") { t in
t.autoIncrementedPrimaryKey("id")
t.column("aId").references("a")
t.belongsTo("a")
}
try db.create(table: "c") { t in
t.autoIncrementedPrimaryKey("id")
t.column("bId").references("b")
t.belongsTo("b")
}
try testHasManyWithTwoSteps(
@@ -334,13 +334,13 @@ class AssociationHasManyThroughSQLTests: GRDBTestCase {
}
try db.create(table: "child") { t in
t.autoIncrementedPrimaryKey("id")
t.column("parentId", .integer).references("parent")
t.belongsTo("parent")
}
try db.create(table: "toy") { t in
t.column("childId", .integer).references("child")
t.belongsTo("child")
}
try db.create(table: "pet") { t in
t.column("childId", .integer).references("child")
t.belongsTo("child")
}
}
@@ -462,15 +462,15 @@ class AssociationHasManyThroughSQLTests: GRDBTestCase {
}
try db.create(table: "b") { t in
t.autoIncrementedPrimaryKey("id")
t.column("aId").references("a")
t.belongsTo("a")
}
try db.create(table: "c") { t in
t.autoIncrementedPrimaryKey("id")
t.column("bId").references("b")
t.belongsTo("b")
}
try db.create(table: "d") { t in
t.autoIncrementedPrimaryKey("id")
t.column("cId").references("c")
t.belongsTo("c")
}
try testHasManyWithThreeSteps(
@@ -521,15 +521,15 @@ class AssociationHasManyThroughSQLTests: GRDBTestCase {
}
try db.create(table: "c") { t in
t.autoIncrementedPrimaryKey("id")
t.column("bId").references("b")
t.belongsTo("b")
}
try db.create(table: "d") { t in
t.autoIncrementedPrimaryKey("id")
t.column("cId").references("c")
t.belongsTo("c")
}
try db.create(table: "a") { t in
t.autoIncrementedPrimaryKey("id")
t.column("bId").references("b")
t.belongsTo("b")
}
try testHasManyWithThreeSteps(
@@ -581,12 +581,12 @@ class AssociationHasManyThroughSQLTests: GRDBTestCase {
}
try db.create(table: "b") { t in
t.autoIncrementedPrimaryKey("id")
t.column("aId").references("a")
t.belongsTo("a")
}
try db.create(table: "c") { t in
t.autoIncrementedPrimaryKey("id")
t.column("bId").references("b")
t.column("dId").references("d")
t.belongsTo("b")
t.belongsTo("d")
}
try testHasManyWithThreeSteps(
@@ -189,7 +189,7 @@ class AssociationHasOneSQLTests: GRDBTestCase {
t.primaryKey("id", .integer)
}
try db.create(table: "children") { t in
t.column("parentId", .integer).references("parents")
t.belongsTo("parent")
}
}
@@ -299,8 +299,8 @@ class AssociationHasOneSQLTests: GRDBTestCase {
t.primaryKey("id", .integer)
}
try db.create(table: "children") { t in
t.column("parent1Id", .integer).references("parents")
t.column("parent2Id", .integer).references("parents")
t.belongsTo("parent1", inTable: "parents")
t.belongsTo("parent2", inTable: "parents")
}
}
@@ -49,12 +49,12 @@ class AssociationHasOneThroughDecodableRecordTests: GRDBTestCase {
}
try db.create(table: "b") { t in
t.autoIncrementedPrimaryKey("id")
t.column("cId").references("c")
t.belongsTo("c")
t.column("name", .text)
}
try db.create(table: "a") { t in
t.autoIncrementedPrimaryKey("id")
t.column("bId").references("b")
t.belongsTo("b")
t.column("name", .text)
}
@@ -86,12 +86,12 @@ class AssociationHasOneThroughFetchableRecordTests: GRDBTestCase {
}
try db.create(table: "b") { t in
t.autoIncrementedPrimaryKey("id")
t.column("cId").references("c")
t.belongsTo("c")
t.column("name", .text)
}
try db.create(table: "a") { t in
t.autoIncrementedPrimaryKey("id")
t.column("bId").references("b")
t.belongsTo("b")
t.column("name", .text)
}
@@ -35,12 +35,12 @@ class AssociationHasOneThroughRowscopeTests: GRDBTestCase {
}
try db.create(table: "b") { t in
t.autoIncrementedPrimaryKey("id")
t.column("cId").references("c")
t.belongsTo("c")
t.column("name", .text)
}
try db.create(table: "a") { t in
t.autoIncrementedPrimaryKey("id")
t.column("bId").references("b")
t.belongsTo("b")
t.column("name", .text)
}
@@ -38,11 +38,11 @@ class AssociationHasOneThroughSQLDerivationTests: GRDBTestCase {
}
try db.create(table: "b") { t in
t.autoIncrementedPrimaryKey("id")
t.column("cId").references("c")
t.belongsTo("c")
}
try db.create(table: "a") { t in
t.autoIncrementedPrimaryKey("id")
t.column("bId").references("b")
t.belongsTo("b")
}
}
}
@@ -28,11 +28,11 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase {
}
try db.create(table: "b") { t in
t.autoIncrementedPrimaryKey("id")
t.column("cId").references("c")
t.belongsTo("c")
}
try db.create(table: "a") { t in
t.autoIncrementedPrimaryKey("id")
t.column("bId").references("b")
t.belongsTo("b")
}
try testHasOneWithTwoSteps(
@@ -68,11 +68,11 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase {
}
try db.create(table: "a") { t in
t.autoIncrementedPrimaryKey("id")
t.column("bId").references("b")
t.belongsTo("b")
}
try db.create(table: "c") { t in
t.autoIncrementedPrimaryKey("id")
t.column("bId").references("b")
t.belongsTo("b")
}
try testHasOneWithTwoSteps(
@@ -111,8 +111,8 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase {
}
try db.create(table: "b") { t in
t.autoIncrementedPrimaryKey("id")
t.column("cId").references("c")
t.column("aId").references("a")
t.belongsTo("c")
t.belongsTo("a")
}
try testHasOneWithTwoSteps(
@@ -148,11 +148,11 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase {
}
try db.create(table: "b") { t in
t.autoIncrementedPrimaryKey("id")
t.column("aId").references("a")
t.belongsTo("a")
}
try db.create(table: "c") { t in
t.autoIncrementedPrimaryKey("id")
t.column("bId").references("b")
t.belongsTo("b")
}
try testHasOneWithTwoSteps(
@@ -437,15 +437,15 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase {
}
try db.create(table: "c") { t in
t.autoIncrementedPrimaryKey("id")
t.column("dId").references("d")
t.belongsTo("d")
}
try db.create(table: "b") { t in
t.autoIncrementedPrimaryKey("id")
t.column("cId").references("c")
t.belongsTo("c")
}
try db.create(table: "a") { t in
t.autoIncrementedPrimaryKey("id")
t.column("bId").references("b")
t.belongsTo("b")
}
try testHasOneWithThreeSteps(
@@ -494,15 +494,15 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase {
}
try db.create(table: "d") { t in
t.autoIncrementedPrimaryKey("id")
t.column("cId").references("c")
t.belongsTo("c")
}
try db.create(table: "b") { t in
t.autoIncrementedPrimaryKey("id")
t.column("cId").references("c")
t.belongsTo("c")
}
try db.create(table: "a") { t in
t.autoIncrementedPrimaryKey("id")
t.column("bId").references("b")
t.belongsTo("b")
}
try testHasOneWithThreeSteps(
@@ -554,12 +554,12 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase {
}
try db.create(table: "c") { t in
t.autoIncrementedPrimaryKey("id")
t.column("bId").references("b")
t.column("dId").references("d")
t.belongsTo("b")
t.belongsTo("d")
}
try db.create(table: "a") { t in
t.autoIncrementedPrimaryKey("id")
t.column("bId").references("b")
t.belongsTo("b")
}
try testHasOneWithThreeSteps(
@@ -608,15 +608,15 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase {
}
try db.create(table: "c") { t in
t.autoIncrementedPrimaryKey("id")
t.column("bId").references("b")
t.belongsTo("b")
}
try db.create(table: "d") { t in
t.autoIncrementedPrimaryKey("id")
t.column("cId").references("c")
t.belongsTo("c")
}
try db.create(table: "a") { t in
t.autoIncrementedPrimaryKey("id")
t.column("bId").references("b")
t.belongsTo("b")
}
try testHasOneWithThreeSteps(
@@ -668,12 +668,12 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase {
}
try db.create(table: "c") { t in
t.autoIncrementedPrimaryKey("id")
t.column("dId").references("d")
t.belongsTo("d")
}
try db.create(table: "b") { t in
t.autoIncrementedPrimaryKey("id")
t.column("aId").references("a")
t.column("cId").references("c")
t.belongsTo("a")
t.belongsTo("c")
}
try testHasOneWithThreeSteps(
@@ -725,12 +725,12 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase {
}
try db.create(table: "d") { t in
t.autoIncrementedPrimaryKey("id")
t.column("cId").references("c")
t.belongsTo("c")
}
try db.create(table: "b") { t in
t.autoIncrementedPrimaryKey("id")
t.column("aId").references("a")
t.column("cId").references("c")
t.belongsTo("a")
t.belongsTo("c")
}
try testHasOneWithThreeSteps(
@@ -782,12 +782,12 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase {
}
try db.create(table: "b") { t in
t.autoIncrementedPrimaryKey("id")
t.column("aId").references("a")
t.belongsTo("a")
}
try db.create(table: "c") { t in
t.autoIncrementedPrimaryKey("id")
t.column("bId").references("b")
t.column("dId").references("d")
t.belongsTo("b")
t.belongsTo("d")
}
try testHasOneWithThreeSteps(
@@ -836,15 +836,15 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase {
}
try db.create(table: "b") { t in
t.autoIncrementedPrimaryKey("id")
t.column("aId").references("a")
t.belongsTo("a")
}
try db.create(table: "c") { t in
t.autoIncrementedPrimaryKey("id")
t.column("bId").references("b")
t.belongsTo("b")
}
try db.create(table: "d") { t in
t.autoIncrementedPrimaryKey("id")
t.column("cId").references("c")
t.belongsTo("c")
}
try testHasOneWithThreeSteps(
@@ -1724,19 +1724,19 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase {
}
try db.create(table: "d") { t in
t.autoIncrementedPrimaryKey("id")
t.column("eId").references("e")
t.belongsTo("e")
}
try db.create(table: "c") { t in
t.autoIncrementedPrimaryKey("id")
t.column("dId").references("d")
t.belongsTo("d")
}
try db.create(table: "b") { t in
t.autoIncrementedPrimaryKey("id")
t.column("cId").references("c")
t.belongsTo("c")
}
try db.create(table: "a") { t in
t.autoIncrementedPrimaryKey("id")
t.column("bId").references("b")
t.belongsTo("b")
}
let associations = [
@@ -1350,9 +1350,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
try dbQueue.write { db in
try db.create(table: "employee") { t in
t.autoIncrementedPrimaryKey("id")
t.column("managerId", .integer)
.indexed()
.references("employee", onDelete: .restrict)
t.belongsTo("manager", inTable: "employee", onDelete: .restrict)
t.column("name", .text)
}
try db.execute(sql: """
+20 -1
View File
@@ -19,77 +19,96 @@ class ColumnInfoTests: GRDBTestCase {
i DATETIME DEFAULT CURRENT_TIMESTAMP,
j DATE DEFAULT (DATETIME('now', 'localtime')),
"" fooéı👨👨🏿🇫🇷🇨🇮,
untyped,
PRIMARY KEY(c, a)
)
""")
let columns = try db.columns(in: "t")
XCTAssertEqual(columns.count, 11)
XCTAssertEqual(columns.count, 12)
XCTAssertEqual(columns[0].name, "a")
XCTAssertEqual(columns[0].isNotNull, false)
XCTAssertEqual(columns[0].type, "INT")
XCTAssertEqual(columns[0].columnType?.rawValue, "INT")
XCTAssertEqual(columns[0].primaryKeyIndex, 2)
XCTAssertNil(columns[0].defaultValueSQL)
XCTAssertEqual(columns[1].name, "b")
XCTAssertEqual(columns[1].isNotNull, false)
XCTAssertEqual(columns[1].type, "TEXT")
XCTAssertEqual(columns[1].columnType?.rawValue, "TEXT")
XCTAssertEqual(columns[1].primaryKeyIndex, 0)
XCTAssertNil(columns[1].defaultValueSQL)
XCTAssertEqual(columns[2].name, "c")
XCTAssertEqual(columns[2].isNotNull, false)
XCTAssertEqual(columns[2].type, "VARCHAR(10)")
XCTAssertEqual(columns[2].columnType?.rawValue, "VARCHAR(10)")
XCTAssertEqual(columns[2].primaryKeyIndex, 1)
XCTAssertNil(columns[2].defaultValueSQL)
XCTAssertEqual(columns[3].name, "d")
XCTAssertEqual(columns[3].isNotNull, false)
XCTAssertEqual(columns[3].type.uppercased(), "INT") // "int" or "INT" depending of SQLite version
XCTAssertEqual(columns[3].columnType?.rawValue.uppercased(), "INT") // "int" or "INT" depending of SQLite version
XCTAssertEqual(columns[3].primaryKeyIndex, 0)
XCTAssertEqual(columns[3].defaultValueSQL, "NULL")
XCTAssertEqual(columns[4].name, "e")
XCTAssertEqual(columns[4].isNotNull, true)
XCTAssertEqual(columns[4].type.uppercased(), "TEXT") // "Text" or "TEXT" depending of SQLite version
XCTAssertEqual(columns[4].columnType?.rawValue.uppercased(), "TEXT") // "Text" or "TEXT" depending of SQLite version
XCTAssertEqual(columns[4].primaryKeyIndex, 0)
XCTAssertEqual(columns[4].defaultValueSQL, "'foo'")
XCTAssertEqual(columns[5].name, "fooéı👨👨🏿🇫🇷🇨🇮")
XCTAssertEqual(columns[5].isNotNull, false)
XCTAssertEqual(columns[5].type, "INT")
XCTAssertEqual(columns[5].columnType?.rawValue, "INT")
XCTAssertEqual(columns[5].primaryKeyIndex, 0)
XCTAssertEqual(columns[5].defaultValueSQL, "0")
XCTAssertEqual(columns[6].name, "g")
XCTAssertEqual(columns[6].isNotNull, false)
XCTAssertEqual(columns[6].type, "INT")
XCTAssertEqual(columns[6].columnType?.rawValue, "INT")
XCTAssertEqual(columns[6].primaryKeyIndex, 0)
XCTAssertEqual(columns[6].defaultValueSQL, "1e6")
XCTAssertEqual(columns[7].name, "h")
XCTAssertEqual(columns[7].isNotNull, false)
XCTAssertEqual(columns[7].type, "REAL")
XCTAssertEqual(columns[7].columnType?.rawValue, "REAL")
XCTAssertEqual(columns[7].primaryKeyIndex, 0)
XCTAssertEqual(columns[7].defaultValueSQL, "1.0")
XCTAssertEqual(columns[8].name, "i")
XCTAssertEqual(columns[8].isNotNull, false)
XCTAssertEqual(columns[8].type, "DATETIME")
XCTAssertEqual(columns[8].columnType?.rawValue, "DATETIME")
XCTAssertEqual(columns[8].primaryKeyIndex, 0)
XCTAssertEqual(columns[8].defaultValueSQL, "CURRENT_TIMESTAMP")
XCTAssertEqual(columns[9].name, "j")
XCTAssertEqual(columns[9].isNotNull, false)
XCTAssertEqual(columns[9].type, "DATE")
XCTAssertEqual(columns[9].columnType?.rawValue, "DATE")
XCTAssertEqual(columns[9].primaryKeyIndex, 0)
XCTAssertEqual(columns[9].defaultValueSQL, "DATETIME('now', 'localtime')")
XCTAssertEqual(columns[10].name, "")
XCTAssertEqual(columns[10].isNotNull, false)
XCTAssertEqual(columns[10].type, "fooéı👨👨🏿🇫🇷🇨🇮")
XCTAssertEqual(columns[10].columnType?.rawValue, "fooéı👨👨🏿🇫🇷🇨🇮")
XCTAssertEqual(columns[10].primaryKeyIndex, 0)
XCTAssertNil(columns[10].defaultValueSQL)
XCTAssertEqual(columns[11].name, "untyped")
XCTAssertEqual(columns[11].isNotNull, false)
XCTAssertEqual(columns[11].type, "")
XCTAssertNil(columns[11].columnType)
XCTAssertEqual(columns[11].primaryKeyIndex, 0)
XCTAssertNil(columns[11].defaultValueSQL)
}
}
@@ -631,11 +631,11 @@ class CommonTableExpressionTests: GRDBTestCase {
}
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("teamId", .integer).references("team")
t.belongsTo("team")
}
try db.create(table: "award") { t in
t.autoIncrementedPrimaryKey("id")
t.column("playerId", .integer).references("player")
t.belongsTo("player")
}
struct Team: TableRecord { }
struct Player: TableRecord {
@@ -36,7 +36,7 @@ private enum StrategyFormatted: StrategyProvider {
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)!
formatter.dateStyle = .full
formatter.timeStyle = .medium
formatter.timeStyle = .none
return formatter
}())
}
@@ -199,10 +199,10 @@ extension DatabaseDateEncodingStrategyTests {
try testNullEncoding(strategy: StrategyFormatted.self)
for (date, value) in zip(testedDates, [
"Saturday, December 20, 1969 at 1:39:05 PM",
"Friday, January 2, 1970 at 10:17:36 AM",
"Monday, January 1, 2001 at 12:00:00 AM",
"Tuesday, January 2, 2001 at 10:17:36 AM",
"Saturday, December 20, 1969",
"Friday, January 2, 1970",
"Monday, January 1, 2001",
"Tuesday, January 2, 2001",
]) { try test(strategy: StrategyFormatted.self, encodesDate: date, as: value) }
}
}
+2 -2
View File
@@ -205,7 +205,7 @@ class DatabaseErrorTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "parents") { $0.column("id", .integer).primaryKey() }
try db.create(table: "children") { $0.column("parentId", .integer).references("parents") }
try db.create(table: "children") { $0.belongsTo("parent") }
do {
try db.execute(sql: "INSERT INTO children (parentId) VALUES (1)")
} catch let error as DatabaseError {
@@ -219,7 +219,7 @@ class DatabaseErrorTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "parents") { $0.column("id", .integer).primaryKey() }
try db.create(table: "children") { $0.column("parentId", .integer).references("parents") }
try db.create(table: "children") { $0.belongsTo("parent") }
do {
try db.execute(sql: "INSERT INTO children (parentId) VALUES (1)")
} catch let error as NSError {
+1 -1
View File
@@ -50,7 +50,7 @@ private var libraryMigrator: DatabaseMigrator = {
}
try db.create(table: "book") { t in
t.autoIncrementedPrimaryKey("id")
t.column("authorId", .integer).notNull().references("author")
t.belongsTo("author").notNull()
t.column("title", .text).notNull()
}
try db.create(virtualTable: "bookFts4", using: FTS4()) { t in
File diff suppressed because it is too large. Load diff
+25
View File
@@ -37,6 +37,7 @@ class PrimaryKeyInfoTests: GRDBTestCase {
try dbQueue.inDatabase { db in
try db.execute(sql: "CREATE TABLE items (name TEXT)")
let primaryKey = try db.primaryKey("items")
XCTAssertNil(primaryKey.columnInfos)
XCTAssertEqual(primaryKey.columns, [Column.rowID.name])
XCTAssertNil(primaryKey.rowIDColumn)
XCTAssertTrue(primaryKey.isRowID)
@@ -49,6 +50,22 @@ class PrimaryKeyInfoTests: GRDBTestCase {
try dbQueue.inDatabase { db in
try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT)")
let primaryKey = try db.primaryKey("items")
XCTAssertEqual(primaryKey.columnInfos?.map(\.name), ["id"])
XCTAssertEqual(primaryKey.columnInfos?.map(\.type), ["INTEGER"])
XCTAssertEqual(primaryKey.columns, ["id"])
XCTAssertEqual(primaryKey.rowIDColumn, "id")
XCTAssertTrue(primaryKey.isRowID)
XCTAssertTrue(primaryKey.tableHasRowID)
}
}
func testIntegerPrimaryKey2() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute(sql: "CREATE TABLE items (id INTEGER, name TEXT, PRIMARY KEY (id))")
let primaryKey = try db.primaryKey("items")
XCTAssertEqual(primaryKey.columnInfos?.map(\.name), ["id"])
XCTAssertEqual(primaryKey.columnInfos?.map(\.type), ["INTEGER"])
XCTAssertEqual(primaryKey.columns, ["id"])
XCTAssertEqual(primaryKey.rowIDColumn, "id")
XCTAssertTrue(primaryKey.isRowID)
@@ -61,6 +78,8 @@ class PrimaryKeyInfoTests: GRDBTestCase {
try dbQueue.inDatabase { db in
try db.execute(sql: "CREATE TABLE items (name TEXT PRIMARY KEY)")
let primaryKey = try db.primaryKey("items")
XCTAssertEqual(primaryKey.columnInfos?.map(\.name), ["name"])
XCTAssertEqual(primaryKey.columnInfos?.map(\.type), ["TEXT"])
XCTAssertEqual(primaryKey.columns, ["name"])
XCTAssertNil(primaryKey.rowIDColumn)
XCTAssertFalse(primaryKey.isRowID)
@@ -73,6 +92,8 @@ class PrimaryKeyInfoTests: GRDBTestCase {
try dbQueue.inDatabase { db in
try db.execute(sql: "CREATE TABLE items (a TEXT, b INTEGER, PRIMARY KEY (a,b))")
let primaryKey = try db.primaryKey("items")
XCTAssertEqual(primaryKey.columnInfos?.map(\.name), ["a", "b"])
XCTAssertEqual(primaryKey.columnInfos?.map(\.type), ["TEXT", "INTEGER"])
XCTAssertEqual(primaryKey.columns, ["a", "b"])
XCTAssertNil(primaryKey.rowIDColumn)
XCTAssertFalse(primaryKey.isRowID)
@@ -85,6 +106,8 @@ class PrimaryKeyInfoTests: GRDBTestCase {
try dbQueue.inDatabase { db in
try db.execute(sql: "CREATE TABLE items (name TEXT PRIMARY KEY) WITHOUT ROWID")
let primaryKey = try db.primaryKey("items")
XCTAssertEqual(primaryKey.columnInfos?.map(\.name), ["name"])
XCTAssertEqual(primaryKey.columnInfos?.map(\.type), ["TEXT"])
XCTAssertEqual(primaryKey.columns, ["name"])
XCTAssertNil(primaryKey.rowIDColumn)
XCTAssertFalse(primaryKey.isRowID)
@@ -97,6 +120,8 @@ class PrimaryKeyInfoTests: GRDBTestCase {
try dbQueue.inDatabase { db in
try db.execute(sql: "CREATE TABLE items (a TEXT, b INTEGER, PRIMARY KEY (a,b)) WITHOUT ROWID")
let primaryKey = try db.primaryKey("items")
XCTAssertEqual(primaryKey.columnInfos?.map(\.name), ["a", "b"])
XCTAssertEqual(primaryKey.columnInfos?.map(\.type), ["TEXT", "INTEGER"])
XCTAssertEqual(primaryKey.columns, ["a", "b"])
XCTAssertNil(primaryKey.rowIDColumn)
XCTAssertFalse(primaryKey.isRowID)
@@ -660,7 +660,7 @@ class QueryInterfaceExpressionsTests: GRDBTestCase {
try dbQueue.write { db in
try db.create(table: "parent") { t in
t.autoIncrementedPrimaryKey("id")
t.column("parentId", .integer).references("parent")
t.belongsTo("parent")
}
try db.create(table: "child") { t in
t.column("childParentId", .integer).references("parent")
@@ -14,7 +14,7 @@ class QueryInterfacePromiseTests: GRDBTestCase {
try dbWriter.write { db in
try db.create(table: "node") { t in
t.autoIncrementedPrimaryKey("id")
t.column("parentId", .integer).references("node")
t.belongsTo("parent", inTable: "node")
}
}
}
@@ -300,7 +300,7 @@ class QueryInterfaceRequestTests: GRDBTestCase {
}
try db.create(table: "book") { t in
t.autoIncrementedPrimaryKey("id")
t.column("authorId", .integer).references("author")
t.belongsTo("author")
}
try db.execute(sql: """
INSERT INTO author(id, name) VALUES (1, 'Arthur');
@@ -20,7 +20,7 @@ class SQLExpressionLiteralTests: GRDBTestCase {
func testWithoutArguments() throws {
try DatabaseQueue().inDatabase { db in
let expression = Column("foo").collating(.nocase) == "'fooéı👨👨🏿🇫🇷🇨🇮'" && Column("baz") >= 1
let context = SQLGenerationContext(db, argumentsSink: .forRawSQL)
let context = SQLGenerationContext(db, argumentsSink: .literalValues)
let sql = try expression.sql(context, wrappedInParenthesis: true)
XCTAssert(context.arguments.isEmpty)
XCTAssertEqual(sql, "((\"foo\" = '''fooéı👨👨🏿🇫🇷🇨🇮''' COLLATE NOCASE) AND (\"baz\" >= 1))")
+1 -1
View File
@@ -614,7 +614,7 @@ extension SQLLiteralTests {
}
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("teamId", .integer).references("team")
t.belongsTo("team")
t.column("score", .integer)
}
struct Player: TableRecord { }
+145 -5
View File
@@ -678,11 +678,22 @@ class TableDefinitionTests: GRDBTestCase {
try db.create(table: "test4") { t in
t.column("parent", .integer).references("test4")
}
assertEqualSQL(
lastSQLQuery!,
("CREATE TABLE \"test4\" (" +
"\"parent\" INTEGER REFERENCES \"test4\"(\"rowid\")" +
")") as String)
assertEqualSQL(lastSQLQuery!, """
CREATE TABLE "test4" (\
"parent" INTEGER REFERENCES "test4"("rowid")\
)
""")
try db.create(table: "test5") { t in
t.column("parent", .integer)
t.foreignKey(["parent"], references: "test5")
}
assertEqualSQL(lastSQLQuery!, """
CREATE TABLE "test5" (\
"parent" INTEGER, \
FOREIGN KEY ("parent") REFERENCES "test5"("rowid")\
)
""")
}
}
@@ -732,6 +743,40 @@ class TableDefinitionTests: GRDBTestCase {
}
}
func testAlterTableAddAutoReferencingForeignKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
do {
try db.create(table: "hiddenRowIdTable") { t in
t.column("a", .text)
}
sqlQueries.removeAll()
try db.alter(table: "hiddenRowIdTable") { t in
t.add(column: "ref").references("hiddenRowIdTable")
}
XCTAssertEqual(lastSQLQuery, """
ALTER TABLE "hiddenRowIdTable" ADD COLUMN "ref" REFERENCES "hiddenRowIdTable"("rowid")
""")
}
do {
try db.create(table: "explicitPrimaryKey") { t in
t.primaryKey("code", .text)
t.column("a", .text)
}
sqlQueries.removeAll()
try db.alter(table: "explicitPrimaryKey") { t in
t.add(column: "ref").references("explicitPrimaryKey")
}
XCTAssertEqual(lastSQLQuery, """
ALTER TABLE "explicitPrimaryKey" ADD COLUMN "ref" REFERENCES "explicitPrimaryKey"("code")
""")
}
}
}
func testAlterTableAddColumnInvalidatesSchemaCache() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -1033,4 +1078,99 @@ class TableDefinitionTests: GRDBTestCase {
assertEqualSQL(lastSQLQuery!, "REINDEX swiftLocalizedCompare")
}
}
func testCreateView() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name")
t.column("score")
}
do {
let request = SQLRequest(literal: """
SELECT * FROM player WHERE name = \("O'Brien")
""")
try db.create(view: "view1", as: request)
assertEqualSQL(lastSQLQuery!, """
CREATE VIEW "view1" AS SELECT * FROM player WHERE name = 'O''Brien'
""")
}
do {
let request = Table("player").filter(Column("name") == "O'Brien")
try db.create(view: "view2", as: request)
assertEqualSQL(lastSQLQuery!, """
CREATE VIEW "view2" AS SELECT * FROM "player" WHERE "name" = 'O''Brien'
""")
}
do {
let sql: SQL = """
SELECT * FROM player WHERE name = \("O'Brien")
"""
try db.create(view: "view3", asLiteral: sql)
assertEqualSQL(lastSQLQuery!, """
CREATE VIEW "view3" AS SELECT * FROM player WHERE name = 'O''Brien'
""")
}
}
}
func testCreateViewOptions() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name")
t.column("score")
}
let request = SQLRequest(literal: """
SELECT * FROM player WHERE name = \("O'Brien")
""")
do {
try db.create(view: "view1", options: .ifNotExists, as: request)
assertEqualSQL(lastSQLQuery!, """
CREATE VIEW IF NOT EXISTS "view1" AS SELECT * FROM player WHERE name = 'O''Brien'
""")
}
do {
try db.create(view: "view2", options: .temporary, as: request)
assertEqualSQL(lastSQLQuery!, """
CREATE TEMPORARY VIEW "view2" AS SELECT * FROM player WHERE name = 'O''Brien'
""")
}
do {
try db.create(view: "view3", options: [.temporary, .ifNotExists], as: request)
assertEqualSQL(lastSQLQuery!, """
CREATE TEMPORARY VIEW IF NOT EXISTS "view3" AS SELECT * FROM player WHERE name = 'O''Brien'
""")
}
do {
try db.create(view: "view4", columns: ["a", "b", "c"], as: request)
assertEqualSQL(lastSQLQuery!, """
CREATE VIEW "view4" ("a", "b", "c") AS SELECT * FROM player WHERE name = 'O''Brien'
""")
}
}
}
func testDropView() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(view: "test", as: SQLRequest(literal: "SELECT 'test', 42"))
XCTAssertTrue(try db.viewExists("test"))
XCTAssertEqual(try db.columns(in: "test").count, 2)
try db.drop(view: "test")
assertEqualSQL(lastSQLQuery!, "DROP VIEW \"test\"")
XCTAssertFalse(try db.viewExists("test"))
}
}
}
+2 -2
View File
@@ -382,7 +382,7 @@ class TableRecordDeleteTests: GRDBTestCase {
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("teamId", .integer).references("team")
t.belongsTo("team")
}
do {
@@ -457,7 +457,7 @@ class TableRecordDeleteTests: GRDBTestCase {
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("teamId", .integer).references("team")
t.belongsTo("team")
}
do {
+1 -1
View File
@@ -674,7 +674,7 @@ class TableRecordUpdateTests: GRDBTestCase {
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("teamId", .integer).references("team")
t.belongsTo("team")
t.column("score", .integer)
}
@@ -26,7 +26,7 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase {
}
try db.create(table: "child") { t in
t.autoIncrementedPrimaryKey("id")
t.column("parentId", .integer).references("parent", onDelete: .cascade)
t.belongsTo("parent", onDelete: .cascade)
t.column("name", .text)
}
}