mirror of
https://github.com/groue/GRDB.swift
synced 2026-12-05 05:18:44 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
60beb7cd9c |
No files matched your search
+22
-38
@@ -13,7 +13,6 @@ on:
|
||||
- '.github/workflows/**'
|
||||
- 'Makefile'
|
||||
- 'Package.swift'
|
||||
- 'SQLiteCustom/src'
|
||||
pull_request:
|
||||
paths:
|
||||
- 'GRDB/**'
|
||||
@@ -21,7 +20,6 @@ on:
|
||||
- '.github/workflows/**'
|
||||
- 'Makefile'
|
||||
- 'Package.swift'
|
||||
- 'SQLiteCustom/src'
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.ref_name }}
|
||||
@@ -40,32 +38,24 @@ 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-13
|
||||
runsOn: macOS-12
|
||||
destination: "platform=macOS"
|
||||
name: "macOS"
|
||||
- xcode: "Xcode_14.2.app"
|
||||
runsOn: macOS-13
|
||||
runsOn: macOS-12
|
||||
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-13
|
||||
runsOn: macOS-12
|
||||
destination: "platform=macOS"
|
||||
name: "macOS"
|
||||
- xcode: "Xcode_14.1.app"
|
||||
runsOn: macOS-13
|
||||
runsOn: macOS-12
|
||||
destination: "OS=16.1,name=iPhone 14"
|
||||
name: "iOS"
|
||||
- xcode: "Xcode_14.0.1.app"
|
||||
@@ -90,14 +80,11 @@ 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-13
|
||||
runsOn: macOS-12
|
||||
name: "Xcode 14.2"
|
||||
- xcode: "Xcode_14.1.app"
|
||||
runsOn: macOS-13
|
||||
runsOn: macOS-12
|
||||
name: "Xcode 14.1"
|
||||
- xcode: "Xcode_14.0.1.app"
|
||||
runsOn: macOS-12
|
||||
@@ -116,12 +103,9 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_14.3.1.app"
|
||||
runsOn: macOS-13
|
||||
name: "Xcode 14.3.1"
|
||||
- xcode: "Xcode_14.0.1.app"
|
||||
- xcode: "Xcode_14.2.app"
|
||||
runsOn: macOS-12
|
||||
name: "Xcode 14.0.1"
|
||||
name: "Xcode 14.2"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: ${{ matrix.name }}
|
||||
@@ -136,9 +120,9 @@ 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
|
||||
name: "Xcode 14.2"
|
||||
- xcode: "Xcode_14.0.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "Xcode 14.0.1"
|
||||
@@ -156,9 +140,9 @@ 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
|
||||
name: "Xcode 14.2"
|
||||
- xcode: "Xcode_14.0.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "Xcode 14.0.1"
|
||||
@@ -176,14 +160,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
|
||||
name: "Xcode 14.2"
|
||||
- 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_universal_xcframework
|
||||
run: make test_archive_GRDBOSX_xcframework
|
||||
|
||||
@@ -7,9 +7,6 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
#### 6.x Releases
|
||||
|
||||
- `6.18.x` Releases - [6.18.0](#6180)
|
||||
- `6.17.x` Releases - [6.17.0](#6170)
|
||||
- `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)
|
||||
@@ -116,38 +113,6 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
---
|
||||
|
||||
## 6.18.0
|
||||
|
||||
Released September 1, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.17.0...v6.18.0)
|
||||
|
||||
- **New**: Expose the database path from `DatabaseReader`.
|
||||
|
||||
## 6.17.0
|
||||
|
||||
Released August 26, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.16.0...v6.17.0)
|
||||
|
||||
- **New**: [#1421](https://github.com/groue/GRDB.swift/pull/1421) by [@groue](https://github.com/groue): Make it possible to open a DatabaseQueue in the WAL mode
|
||||
|
||||
## 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)
|
||||
|
||||
+1
-1
@@ -69,7 +69,7 @@ How you can Contribute
|
||||
|
||||
GRDB documentation is provided as a DocC reference, and guides ([README.md](README.md) and the [Documentation](Documentation) folder).
|
||||
|
||||
Please keep the reference and the guides up-to-date. To control the quality of your DocC reference documentation, close the workspace, open `Package.swift` in Xcode, and use Product > Build Documentation.
|
||||
Please keep the reference and the guides up-to-date. Use Xcode > Product > Build Documentation in order to control the quality of your reference documentation.
|
||||
|
||||
GRDB is "documentation-driven", which means that nothing ships until it is supported by documentation that makes sense. Documentation makes sense when someone who is not you is able to figure out what is the purpose of your contribution, how to use it, and what are its eventual caveats and corner cases. When the documentation is hard to write, or reveals too many caveats, it is the sign that the api needs to be fixed.
|
||||
|
||||
|
||||
@@ -429,13 +429,15 @@ The matching [migration] would look like:
|
||||
migrator.registerMigration("Employees") { db in
|
||||
try db.create(table: "employee") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("manager", inTable: "employee", onDelete: .setNull)
|
||||
t.column("managerId", .integer)
|
||||
.indexed()
|
||||
.references("employee", onDelete: .restrict)
|
||||
t.column("name", .text)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
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:
|
||||
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:
|
||||
|
||||
```swift
|
||||
struct EmployeeInfo: FetchableRecord, Decodable {
|
||||
@@ -534,16 +536,20 @@ migrator.registerMigration("Books and Authors") { db in
|
||||
}
|
||||
try db.create(table: "book") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("author", onDelete: .cascade) // (2)
|
||||
t.column("authorId", .integer) // (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. 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.
|
||||
2. The `book.authorId` column is used to link a book to the author it belongs to.
|
||||
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.
|
||||
|
||||
@@ -589,16 +595,20 @@ migrator.registerMigration("Books and Authors") { db in
|
||||
}
|
||||
try db.create(table: "book") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("author", onDelete: .cascade) // (2)
|
||||
t.column("authorId", .integer) // (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. 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.
|
||||
2. The `book.authorId` column is used to link a book to the author it belongs to.
|
||||
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.
|
||||
|
||||
@@ -644,9 +654,10 @@ migrator.registerMigration("Countries") { db in
|
||||
}
|
||||
try db.create(table: "demographics") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("country", onDelete: .cascade) // (2)
|
||||
t.column("countryCode", .text) // (2)
|
||||
.notNull() // (3)
|
||||
.unique() // (4)
|
||||
.references("country", onDelete: .cascade) // (5)
|
||||
t.column("population", .integer)
|
||||
t.column("density", .double)
|
||||
}
|
||||
@@ -654,9 +665,10 @@ 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. 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.
|
||||
2. The `demographics.countryCode` column is used to link a demographic profile to the country it belongs to.
|
||||
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.
|
||||
|
||||
@@ -708,22 +720,6 @@ Sometimes the database schema does not define any foreign key. And sometimes, th
|
||||
|
||||

|
||||
|
||||
```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:
|
||||
|
||||
@@ -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.42.0](https://www.sqlite.org/changes.html).**
|
||||
**You can build GRDB with a custom build of [SQLite 3.39.3](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,7 +29,10 @@ migrator.registerMigration("createLibrary") { db in
|
||||
try db.create(table: "book") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("title", .text).notNull()
|
||||
t.belongsTo("author", onDelete: .cascade).notNull()
|
||||
t.column("authorId", .integer)
|
||||
.notNull()
|
||||
.indexed()
|
||||
.references("author", onDelete: .cascade)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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.belongsTo("owner", inTable: "person", onDelete: .cascade)
|
||||
t.column("ownerId", .integer).references("person", onDelete: .cascade)
|
||||
}
|
||||
}
|
||||
try! migrator.migrate(dbQueue)
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '6.18.0'
|
||||
s.version = '6.15.1'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
|
||||
|
||||
@@ -94,7 +94,6 @@
|
||||
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 */; };
|
||||
@@ -203,7 +202,6 @@
|
||||
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 */; };
|
||||
@@ -381,14 +379,6 @@
|
||||
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 */; };
|
||||
@@ -503,7 +493,6 @@
|
||||
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>"; };
|
||||
@@ -632,7 +621,6 @@
|
||||
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>"; };
|
||||
@@ -797,14 +785,6 @@
|
||||
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>"; };
|
||||
@@ -1029,7 +1009,6 @@
|
||||
56012B542573EED000B4925B /* CommonTableExpressionTests.swift */,
|
||||
56EA63C4209C7CE3009715B8 /* DerivableRequestTests.swift */,
|
||||
56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */,
|
||||
568C3F792A5AB2C300A2309D /* ForeignKeyDefinitionTests.swift */,
|
||||
56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */,
|
||||
5698AC021D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift */,
|
||||
563EF45221631E21007DAACD /* QueryInterfacePromiseTests.swift */,
|
||||
@@ -1193,11 +1172,6 @@
|
||||
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 */,
|
||||
);
|
||||
@@ -1207,12 +1181,8 @@
|
||||
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>";
|
||||
@@ -1993,7 +1963,6 @@
|
||||
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 */,
|
||||
@@ -2082,7 +2051,6 @@
|
||||
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 */,
|
||||
@@ -2102,7 +2070,6 @@
|
||||
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 */,
|
||||
@@ -2116,8 +2083,6 @@
|
||||
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 */,
|
||||
@@ -2137,7 +2102,6 @@
|
||||
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 */,
|
||||
@@ -2153,7 +2117,6 @@
|
||||
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 */,
|
||||
@@ -2161,10 +2124,8 @@
|
||||
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 */,
|
||||
@@ -2185,7 +2146,6 @@
|
||||
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 */,
|
||||
|
||||
@@ -288,46 +288,6 @@ public struct Configuration {
|
||||
/// of a read access.
|
||||
public var allowsUnsafeTransactions = false
|
||||
|
||||
// MARK: - Journal Mode
|
||||
|
||||
/// Defines how the journal mode is configured when the database
|
||||
/// connection is opened.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/pragma.html#pragma_journal_mode>
|
||||
public enum JournalModeConfiguration {
|
||||
/// The default setup has ``DatabaseQueue`` perform no specific
|
||||
/// configuration of the journal mode, and ``DatabasePool``
|
||||
/// configure the database for the WAL mode (just like the
|
||||
/// ``wal`` case).
|
||||
case `default`
|
||||
|
||||
/// The journal mode is set to WAL (plus extra configurations that
|
||||
/// make life easier with WAL databases).
|
||||
case wal
|
||||
}
|
||||
|
||||
/// Defines how the journal mode is configured when the database
|
||||
/// connection is opened.
|
||||
///
|
||||
/// This configuration is ignored when ``readonly`` is true.
|
||||
///
|
||||
/// The default value has ``DatabaseQueue`` perform no specific
|
||||
/// configuration of the journal mode, and ``DatabasePool`` configure
|
||||
/// the database for the WAL mode.
|
||||
///
|
||||
/// Applications that need to open a WAL database with a
|
||||
/// ``DatabaseQueue`` should set the `journalMode` to `wal`:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Open a WAL database with DatabaseQueue
|
||||
/// var config = Configuration()
|
||||
/// config.journalMode = .wal
|
||||
/// let dbQueue = try DatabaseQueue(path: "...", configuration: config)
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/pragma.html#pragma_journal_mode>
|
||||
public var journalMode = JournalModeConfiguration.default
|
||||
|
||||
// MARK: - Concurrency
|
||||
|
||||
/// Defines the how `SQLITE_BUSY` errors are handled.
|
||||
|
||||
+188
-77
@@ -14,9 +14,14 @@
|
||||
extension RangeReplaceableCollection {
|
||||
/// Creates a collection containing the elements of a cursor.
|
||||
///
|
||||
/// // [String]
|
||||
/// let cursor = try String.fetchCursor(db, ...)
|
||||
/// let strings = try Array(cursor)
|
||||
/// For example, you can turn a cursor of strings into an array
|
||||
/// of strings:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Create a [String]
|
||||
/// let cursor = try String.fetchCursor(db, ...)
|
||||
/// let strings = try Array(cursor)
|
||||
/// ```
|
||||
///
|
||||
/// - parameter cursor: The cursor whose elements feed the collection.
|
||||
public init(_ cursor: some Cursor<Element>) throws {
|
||||
@@ -26,9 +31,14 @@ extension RangeReplaceableCollection {
|
||||
|
||||
/// Creates a collection containing the elements of a cursor.
|
||||
///
|
||||
/// // [String]
|
||||
/// let cursor = try String.fetchCursor(db, ...)
|
||||
/// let strings = try Array(cursor, minimumCapacity: 100)
|
||||
/// For example, you can turn a cursor of strings into an array
|
||||
/// of strings:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Create a [String]
|
||||
/// let cursor = try String.fetchCursor(db, ...)
|
||||
/// let strings = try Array(cursor, minimumCapacity: 100)
|
||||
/// ```
|
||||
///
|
||||
/// - parameter cursor: The cursor whose elements feed the collection.
|
||||
/// - parameter minimumCapacity: Prepares the returned collection to store
|
||||
@@ -41,8 +51,8 @@ extension RangeReplaceableCollection {
|
||||
|
||||
/// Adds the elements of a cursor to the end of this collection.
|
||||
///
|
||||
/// In case of error, an unspecified amount of elements have been added to
|
||||
/// the collection.
|
||||
/// - Important: If an error is thrown, an unspecified amount of
|
||||
/// elements have been added to the collection.
|
||||
///
|
||||
/// - parameter newElements: The elements to append to the collection.
|
||||
public mutating func append(contentsOf newElements: some Cursor<Element>) throws {
|
||||
@@ -58,9 +68,13 @@ extension Dictionary {
|
||||
/// given closure and whose values are arrays of the elements that returned
|
||||
/// each key.
|
||||
///
|
||||
/// // [Int64: [Player]]
|
||||
/// let cursor = try Player.fetchCursor(db)
|
||||
/// let dictionary = try Dictionary(grouping: cursor, by: { $0.teamID })
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Create a [Int64: [Player]]
|
||||
/// let cursor = try Player.fetchCursor(db)
|
||||
/// let dictionary = try Dictionary(grouping: cursor, by: { $0.teamID })
|
||||
/// ```
|
||||
///
|
||||
/// - parameter cursor: A cursor of values to group into a dictionary.
|
||||
/// - parameter keyForValue: A closure that returns a key for each element
|
||||
@@ -81,12 +95,16 @@ extension Dictionary {
|
||||
/// given closure and whose values are arrays of the elements that returned
|
||||
/// each key.
|
||||
///
|
||||
/// // [Int64: [Player]]
|
||||
/// let cursor = try Player.fetchCursor(db)
|
||||
/// let dictionary = try Dictionary(
|
||||
/// minimumCapacity: 100,
|
||||
/// grouping: cursor,
|
||||
/// by: { $0.teamID })
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Create a [Int64: [Player]]
|
||||
/// let cursor = try Player.fetchCursor(db)
|
||||
/// let dictionary = try Dictionary(
|
||||
/// minimumCapacity: 100,
|
||||
/// grouping: cursor,
|
||||
/// by: { $0.teamID })
|
||||
/// ```
|
||||
///
|
||||
/// - parameter minimumCapacity: The minimum number of key-value pairs that
|
||||
/// the newly created dictionary should be able to store without
|
||||
@@ -112,9 +130,13 @@ extension Dictionary {
|
||||
/// of key-value tuples with unique keys. Passing a cursor with duplicate
|
||||
/// keys to this initializer results in a fatal error.
|
||||
///
|
||||
/// // [Int64: Player]
|
||||
/// let cursor = try Player.fetchCursor(db).map { ($0.id, $0) }
|
||||
/// let playerByID = try Dictionary(uniqueKeysWithValues: cursor)
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Create a [Int64: [Player]]
|
||||
/// let cursor = try Player.fetchCursor(db).map { ($0.id, $0) }
|
||||
/// let playerByID = try Dictionary(uniqueKeysWithValues: cursor)
|
||||
/// ```
|
||||
///
|
||||
/// - parameter keysAndValues: A cursor of key-value pairs to use for the
|
||||
/// new dictionary. Every key in `keysAndValues` must be unique.
|
||||
@@ -137,11 +159,15 @@ extension Dictionary {
|
||||
/// of key-value tuples with unique keys. Passing a cursor with duplicate
|
||||
/// keys to this initializer results in a fatal error.
|
||||
///
|
||||
/// // [Int64: Player]
|
||||
/// let cursor = try Player.fetchCursor(db).map { ($0.id, $0) }
|
||||
/// let playerByID = try Dictionary(
|
||||
/// minimumCapacity: 100,
|
||||
/// uniqueKeysWithValues: cursor)
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Create a [Int64: [Player]]
|
||||
/// let cursor = try Player.fetchCursor(db).map { ($0.id, $0) }
|
||||
/// let playerByID = try Dictionary(
|
||||
/// minimumCapacity: 100,
|
||||
/// uniqueKeysWithValues: cursor)
|
||||
/// ```
|
||||
///
|
||||
/// - parameter minimumCapacity: The minimum number of key-value pairs that
|
||||
/// the newly created dictionary should be able to store without
|
||||
@@ -165,9 +191,13 @@ extension Dictionary {
|
||||
extension Set {
|
||||
/// Creates a set containing the elements of a cursor.
|
||||
///
|
||||
/// // Set<String>
|
||||
/// let cursor = try String.fetchCursor(db, ...)
|
||||
/// let strings = try Set(cursor)
|
||||
/// For example, you can turn a cursor of strings into a set of strings:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Create a Set<String>
|
||||
/// let cursor = try String.fetchCursor(db, ...)
|
||||
/// let strings = try Set(cursor)
|
||||
/// ```
|
||||
///
|
||||
/// - parameter cursor: A cursor of values to gather into a set.
|
||||
public init(_ cursor: some Cursor<Element>) throws {
|
||||
@@ -180,9 +210,13 @@ extension Set {
|
||||
|
||||
/// Creates a set containing the elements of a cursor.
|
||||
///
|
||||
/// // Set<String>
|
||||
/// let cursor = try String.fetchCursor(db, ...)
|
||||
/// let strings = try Set(cursor, minimumCapacity: 100)
|
||||
/// For example, you can turn a cursor of strings into a set of strings:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Create a Set<String>
|
||||
/// let cursor = try String.fetchCursor(db, ...)
|
||||
/// let strings = try Set(cursor, minimumCapacity: 100)
|
||||
/// ```
|
||||
///
|
||||
/// - parameter cursor: A cursor of values to gather into a set.
|
||||
/// - parameter minimumCapacity: The minimum number of elements that the
|
||||
@@ -240,6 +274,75 @@ extension Sequence {
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Iterating Over a Cursor’s Elements
|
||||
///
|
||||
/// - ``next()``
|
||||
/// - ``forEach(_:)-4ib2m``
|
||||
/// - ``enumerated()``
|
||||
/// - ``isEmpty``
|
||||
///
|
||||
/// ### Finding Elements
|
||||
///
|
||||
/// - ``contains(_:)``
|
||||
/// - ``contains(where:)``
|
||||
/// - ``first(where:)``
|
||||
/// - ``min()``
|
||||
/// - ``min(by:)``
|
||||
/// - ``max()``
|
||||
/// - ``max(by:)``
|
||||
///
|
||||
/// ### Selecting Elements
|
||||
///
|
||||
/// - ``prefix(_:)``
|
||||
/// - ``prefix(while:)``
|
||||
/// - ``suffix(_:)``
|
||||
///
|
||||
/// ### Excluding Elements
|
||||
///
|
||||
/// - ``dropFirst()``
|
||||
/// - ``dropFirst(_:)``
|
||||
/// - ``dropLast()``
|
||||
/// - ``dropLast(_:)``
|
||||
/// - ``drop(while:)``
|
||||
/// - ``filter(_:)``
|
||||
///
|
||||
/// ### Transforming a Cursor
|
||||
///
|
||||
/// - ``map(_:)``
|
||||
/// - ``compactMap(_:)``
|
||||
/// - ``flatMap(_:)-5ci2v``
|
||||
/// - ``flatMap(_:)-8jxlj``
|
||||
/// - ``reduce(_:_:)``
|
||||
/// - ``reduce(into:_:)``
|
||||
///
|
||||
/// ### Transforming a Sequence into a Cursor
|
||||
///
|
||||
/// - ``Swift/Sequence/flatMap(_:)``
|
||||
///
|
||||
/// ### Joining Elements
|
||||
///
|
||||
/// - ``joined()-5r5ja``
|
||||
/// - ``joined()-7bnrx``
|
||||
/// - ``joined(separator:)``
|
||||
///
|
||||
/// ### Filling RangeReplaceableCollection with the contents of a Cursor
|
||||
///
|
||||
/// - ``Swift/RangeReplaceableCollection/init(_:)``
|
||||
/// - ``Swift/RangeReplaceableCollection/init(_:minimumCapacity:)``
|
||||
/// - ``Swift/RangeReplaceableCollection/append(contentsOf:)``
|
||||
///
|
||||
/// ### Creating a Dictionary from the contents of a Cursor
|
||||
///
|
||||
/// - ``Swift/Dictionary/init(grouping:by:)``
|
||||
/// - ``Swift/Dictionary/init(minimumCapacity:grouping:by:)``
|
||||
/// - ``Swift/Dictionary/init(uniqueKeysWithValues:)``
|
||||
/// - ``Swift/Dictionary/init(minimumCapacity:uniqueKeysWithValues:)``
|
||||
///
|
||||
/// ### Creating a Set from the contents of a Cursor
|
||||
///
|
||||
/// - ``Swift/Set/init(_:)``
|
||||
/// - ``Swift/Set/init(_:minimumCapacity:)``
|
||||
///
|
||||
/// ### Supporting Types
|
||||
///
|
||||
/// - ``AnyCursor``
|
||||
@@ -269,7 +372,7 @@ extension Cursor {
|
||||
/// Returns a Boolean value indicating whether the cursor does not contain
|
||||
/// any element.
|
||||
///
|
||||
/// - important: This property may consume elements.
|
||||
/// - important: This property consumes an element.
|
||||
public var isEmpty: Bool {
|
||||
get throws { try next() == nil }
|
||||
}
|
||||
@@ -294,13 +397,17 @@ extension Cursor {
|
||||
/// Returns a cursor of pairs (n, x), where n represents a consecutive
|
||||
/// integer starting at zero, and x represents an element of the cursor.
|
||||
///
|
||||
/// let cursor = try String.fetchCursor(db, sql: "SELECT 'foo' UNION ALL SELECT 'bar'")
|
||||
/// let c = cursor.enumerated()
|
||||
/// while let (n, x) = c.next() {
|
||||
/// print("\(n): \(x)")
|
||||
/// }
|
||||
/// // Prints: "0: foo"
|
||||
/// // Prints: "1: bar"
|
||||
/// ```swift
|
||||
/// let cursor = try String.fetchCursor(db, sql: """
|
||||
/// SELECT 'foo' UNION ALL SELECT 'bar'
|
||||
/// """)
|
||||
/// let c = cursor.enumerated()
|
||||
/// while let (n, x) = c.next() {
|
||||
/// print("\(n): \(x)")
|
||||
/// }
|
||||
/// // Prints: "0: foo"
|
||||
/// // Prints: "1: bar"
|
||||
/// ```
|
||||
public func enumerated() -> EnumeratedCursor<Self> {
|
||||
EnumeratedCursor(self)
|
||||
}
|
||||
@@ -346,11 +453,13 @@ extension Cursor {
|
||||
/// If the number of elements to drop exceeds the number of elements in
|
||||
/// the cursor, the result is an empty cursor.
|
||||
///
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.dropFirst(2))
|
||||
/// // Prints "[3, 4, 5]"
|
||||
/// try print(numbers.dropFirst(10))
|
||||
/// // Prints "[]"
|
||||
/// ```swift
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.dropFirst(2))
|
||||
/// // Prints "[3, 4, 5]"
|
||||
/// try print(numbers.dropFirst(10))
|
||||
/// // Prints "[]"
|
||||
/// ```
|
||||
///
|
||||
/// - Parameter n: The number of elements to drop from the beginning of
|
||||
/// the cursor. `n` must be greater than or equal to zero.
|
||||
@@ -364,9 +473,11 @@ extension Cursor {
|
||||
///
|
||||
/// The following example drops the first element from a cursor of integers.
|
||||
///
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.dropFirst())
|
||||
/// // Prints "[2, 3, 4, 5]"
|
||||
/// ```swift
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.dropFirst())
|
||||
/// // Prints "[2, 3, 4, 5]"
|
||||
/// ```
|
||||
///
|
||||
/// If the cursor has no elements, the result is an empty cursor.
|
||||
///
|
||||
@@ -381,11 +492,13 @@ extension Cursor {
|
||||
/// The cursor must be finite. If the number of elements to drop exceeds
|
||||
/// the number of elements in the cursor, the result is an empty array.
|
||||
///
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.dropLast(2))
|
||||
/// // Prints "[1, 2, 3]"
|
||||
/// try print(numbers.dropLast(10))
|
||||
/// // Prints "[]"
|
||||
/// ```swift
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.dropLast(2))
|
||||
/// // Prints "[1, 2, 3]"
|
||||
/// try print(numbers.dropLast(10))
|
||||
/// // Prints "[]"
|
||||
/// ```
|
||||
///
|
||||
/// - Parameter n: The number of elements to drop off the end of the
|
||||
/// cursor. `n` must be greater than or equal to zero.
|
||||
@@ -414,9 +527,11 @@ extension Cursor {
|
||||
///
|
||||
/// The following example drops the last element from a cursor of integers.
|
||||
///
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.dropLast())
|
||||
/// // Prints "[1, 2, 3, 4]"
|
||||
/// ```swift
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.dropLast())
|
||||
/// // Prints "[1, 2, 3, 4]"
|
||||
/// ```
|
||||
///
|
||||
/// If the cursor has no elements, the result is an empty cursor.
|
||||
///
|
||||
@@ -502,11 +617,13 @@ extension Cursor {
|
||||
/// If the maximum length exceeds the number of elements in the cursor,
|
||||
/// the result contains all the elements in the cursor.
|
||||
///
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.prefix(2))
|
||||
/// // Prints "[1, 2]"
|
||||
/// try print(numbers.prefix(10))
|
||||
/// // Prints "[1, 2, 3, 4, 5]"
|
||||
/// ```swift
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.prefix(2))
|
||||
/// // Prints "[1, 2]"
|
||||
/// try print(numbers.prefix(10))
|
||||
/// // Prints "[1, 2, 3, 4, 5]"
|
||||
/// ```
|
||||
///
|
||||
/// - Parameter maxLength: The maximum number of elements to return. The
|
||||
/// value of `maxLength` must be greater than or equal to zero.
|
||||
@@ -562,11 +679,13 @@ extension Cursor {
|
||||
/// elements in the cursor, the result contains all the elements in the
|
||||
/// cursor.
|
||||
///
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.suffix(2))
|
||||
/// // Prints "[4, 5]"
|
||||
/// try print(numbers.suffix(10))
|
||||
/// // Prints "[1, 2, 3, 4, 5]"
|
||||
/// ```swift
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.suffix(2))
|
||||
/// // Prints "[4, 5]"
|
||||
/// try print(numbers.suffix(10))
|
||||
/// // Prints "[1, 2, 3, 4, 5]"
|
||||
/// ```
|
||||
///
|
||||
/// - Parameter maxLength: The maximum number of elements to return. The
|
||||
/// value of `maxLength` must be greater than or equal to zero.
|
||||
@@ -620,24 +739,16 @@ extension Cursor where Element: Equatable {
|
||||
extension Cursor where Element: Comparable {
|
||||
/// Returns the maximum element in the cursor.
|
||||
///
|
||||
/// - Parameter areInIncreasingOrder: A predicate that returns `true`
|
||||
/// if its first argument should be ordered before its second
|
||||
/// argument; otherwise, `false`.
|
||||
/// - Returns: The cursor's maximum element, according to
|
||||
/// `areInIncreasingOrder`. If the cursor has no elements, returns
|
||||
/// `nil`.
|
||||
/// - Returns: The cursor's maximum element. If the cursor has no
|
||||
/// elements, returns `nil`.
|
||||
public func max() throws -> Element? {
|
||||
try max(by: <)
|
||||
}
|
||||
|
||||
/// Returns the minimum element in the cursor.
|
||||
///
|
||||
/// - Parameter areInIncreasingOrder: A predicate that returns `true`
|
||||
/// if its first argument should be ordered before its second
|
||||
/// argument; otherwise, `false`.
|
||||
/// - Returns: The cursor's minimum element, according to
|
||||
/// `areInIncreasingOrder`. If the cursor has no elements, returns
|
||||
/// `nil`.
|
||||
/// - Returns: The cursor's minimum element. If the cursor has no
|
||||
/// elements, returns `nil`.
|
||||
public func min() throws -> Element? {
|
||||
try min(by: <)
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
primaryKey = .rowID(pkColumn.name)
|
||||
} else {
|
||||
primaryKey = try .regular([pkColumn], tableHasRowID: tableHasRowID(table))
|
||||
primaryKey = try .regular([pkColumn.name], tableHasRowID: tableHasRowID(table))
|
||||
}
|
||||
default:
|
||||
// Multi-columns primary key
|
||||
primaryKey = try .regular(pkColumns, tableHasRowID: tableHasRowID(table))
|
||||
primaryKey = try .regular(pkColumns.map(\.name), tableHasRowID: tableHasRowID(table))
|
||||
}
|
||||
|
||||
schemaCache[table.schemaID].set(primaryKey: .value(primaryKey), forTable: table.name)
|
||||
@@ -858,22 +858,8 @@ 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
|
||||
|
||||
@@ -1164,22 +1150,22 @@ public struct PrimaryKeyInfo {
|
||||
|
||||
/// An INTEGER PRIMARY KEY column that aliases the Row ID.
|
||||
/// Associated string is the column name.
|
||||
case rowID(ColumnInfo)
|
||||
case rowID(String)
|
||||
|
||||
/// Any primary key, but INTEGER PRIMARY KEY.
|
||||
/// Associated strings are column names.
|
||||
case regular(columnInfos: [ColumnInfo], tableHasRowID: Bool)
|
||||
case regular(columns: [String], tableHasRowID: Bool)
|
||||
}
|
||||
|
||||
private let impl: Impl
|
||||
|
||||
static func rowID(_ columnInfo: ColumnInfo) -> PrimaryKeyInfo {
|
||||
PrimaryKeyInfo(impl: .rowID(columnInfo))
|
||||
static func rowID(_ column: String) -> PrimaryKeyInfo {
|
||||
PrimaryKeyInfo(impl: .rowID(column))
|
||||
}
|
||||
|
||||
static func regular(_ columnInfos: [ColumnInfo], tableHasRowID: Bool) -> PrimaryKeyInfo {
|
||||
assert(!columnInfos.isEmpty)
|
||||
return PrimaryKeyInfo(impl: .regular(columnInfos: columnInfos, tableHasRowID: tableHasRowID))
|
||||
static func regular(_ columns: [String], tableHasRowID: Bool) -> PrimaryKeyInfo {
|
||||
assert(!columns.isEmpty)
|
||||
return PrimaryKeyInfo(impl: .regular(columns: columns, tableHasRowID: tableHasRowID))
|
||||
}
|
||||
|
||||
static let hiddenRowID = PrimaryKeyInfo(impl: .hiddenRowID)
|
||||
@@ -1189,34 +1175,21 @@ public struct PrimaryKeyInfo {
|
||||
switch impl {
|
||||
case .hiddenRowID:
|
||||
return [Column.rowID.name]
|
||||
case let .rowID(columnInfo):
|
||||
return [columnInfo.name]
|
||||
case let .regular(columnInfos: columnInfos, tableHasRowID: _):
|
||||
return columnInfos.map(\.name)
|
||||
case let .rowID(column):
|
||||
return [column]
|
||||
case let .regular(columns: columns, tableHasRowID: _):
|
||||
return columns
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 columnInfo):
|
||||
return columnInfo.name
|
||||
case .rowID(let column):
|
||||
return column
|
||||
case .regular:
|
||||
return nil
|
||||
}
|
||||
@@ -1243,7 +1216,7 @@ public struct PrimaryKeyInfo {
|
||||
return true
|
||||
case .rowID:
|
||||
return true
|
||||
case let .regular(columnInfos: _, tableHasRowID: tableHasRowID):
|
||||
case let .regular(columns: _, tableHasRowID: tableHasRowID):
|
||||
return tableHasRowID
|
||||
}
|
||||
}
|
||||
@@ -1343,6 +1316,10 @@ struct TableInfo: FetchableRecord {
|
||||
/// A value in the `type` column of `sqlite_master`.
|
||||
struct SchemaObjectType: Hashable, RawRepresentable, DatabaseValueConvertible {
|
||||
var rawValue: String
|
||||
init(rawValue: String) {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
|
||||
static let index = SchemaObjectType(rawValue: "index")
|
||||
static let table = SchemaObjectType(rawValue: "table")
|
||||
static let trigger = SchemaObjectType(rawValue: "trigger")
|
||||
|
||||
@@ -373,7 +373,7 @@ extension SQLStatementCursor: Cursor {
|
||||
let baseAddress = buffer.baseAddress! // never nil because the buffer contains the trailing \0.
|
||||
|
||||
// Compile next statement
|
||||
var statementEnd: UnsafePointer<CChar>? = nil
|
||||
var statementEnd: UnsafePointer<Int8>? = nil
|
||||
let statement = try Statement(
|
||||
database: database,
|
||||
statementStart: baseAddress + offset,
|
||||
|
||||
+74
-61
@@ -421,41 +421,6 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
configuration.SQLiteConnectionDidOpen?()
|
||||
}
|
||||
|
||||
/// Performs ``Configuration/JournalModeConfiguration/wal``.
|
||||
func setUpWALMode() throws {
|
||||
let journalMode = try String.fetchOne(self, sql: "PRAGMA journal_mode = WAL")
|
||||
guard journalMode == "wal" else {
|
||||
throw DatabaseError(message: "could not activate WAL Mode at path: \(path)")
|
||||
}
|
||||
|
||||
// https://www.sqlite.org/pragma.html#pragma_synchronous
|
||||
// > Many applications choose NORMAL when in WAL mode
|
||||
try execute(sql: "PRAGMA synchronous = NORMAL")
|
||||
|
||||
// Make sure a non-empty wal file exists.
|
||||
//
|
||||
// The presence of the wal file avoids an SQLITE_CANTOPEN (14)
|
||||
// error when the user opens a pool and reads from it.
|
||||
// See <https://github.com/groue/GRDB.swift/issues/102>.
|
||||
//
|
||||
// The non-empty wal file avoids an SQLITE_ERROR (1) error
|
||||
// when the user opens a pool and creates a wal snapshot
|
||||
// (which happens when starting a ValueObservation).
|
||||
// See <https://github.com/groue/GRDB.swift/issues/1383>.
|
||||
let walPath = path + "-wal"
|
||||
if try FileManager.default.fileExists(atPath: walPath) == false
|
||||
|| (URL(fileURLWithPath: walPath).resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0) == 0
|
||||
{
|
||||
try inSavepoint {
|
||||
try execute(sql: """
|
||||
CREATE TABLE grdb_issue_102 (id INTEGER PRIMARY KEY);
|
||||
DROP TABLE grdb_issue_102;
|
||||
""")
|
||||
return .commit
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func setupDoubleQuotedStringLiterals() {
|
||||
if configuration.acceptsDoubleQuotedStringLiterals {
|
||||
_enableDoubleQuotedStringLiterals(sqliteConnection)
|
||||
@@ -895,16 +860,31 @@ 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
|
||||
@@ -912,7 +892,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
_ mask: CInt,
|
||||
_ p: UnsafeMutableRawPointer?,
|
||||
_ x: UnsafeMutableRawPointer?,
|
||||
_ sqlite3_expanded_sql: @escaping @convention(c) (OpaquePointer?) -> UnsafeMutablePointer<CChar>?)
|
||||
_ sqlite3_expanded_sql: @escaping @convention(c) (OpaquePointer?) -> UnsafeMutablePointer<Int8>?)
|
||||
{
|
||||
guard let trace else { return }
|
||||
|
||||
@@ -920,22 +900,26 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
case SQLITE_TRACE_STMT:
|
||||
if let sqliteStatement = p, let unexpandedSQL = x {
|
||||
let statement = TraceEvent.Statement(
|
||||
sqliteStatement: OpaquePointer(sqliteStatement),
|
||||
unexpandedSQL: UnsafePointer(unexpandedSQL.assumingMemoryBound(to: CChar.self)),
|
||||
sqlite3_expanded_sql: sqlite3_expanded_sql,
|
||||
publicStatementArguments: configuration.publicStatementArguments)
|
||||
impl: .trace_v2(
|
||||
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(
|
||||
sqliteStatement: OpaquePointer(sqliteStatement),
|
||||
unexpandedSQL: nil,
|
||||
sqlite3_expanded_sql: sqlite3_expanded_sql,
|
||||
publicStatementArguments: configuration.publicStatementArguments)
|
||||
impl: .trace_v2(
|
||||
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
|
||||
@@ -1817,7 +1801,6 @@ 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
|
||||
@@ -1914,11 +1897,13 @@ 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.
|
||||
@@ -1929,11 +1914,17 @@ extension Database {
|
||||
|
||||
/// Information about an executed statement.
|
||||
public struct Statement: CustomStringConvertible {
|
||||
var sqliteStatement: SQLiteStatement
|
||||
var unexpandedSQL: UnsafePointer<CChar>?
|
||||
var sqlite3_expanded_sql: @convention(c) (OpaquePointer?) -> UnsafeMutablePointer<CChar>?
|
||||
var publicStatementArguments: Bool // See Configuration.publicStatementArguments
|
||||
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
|
||||
|
||||
#if !os(Linux)
|
||||
/// The executed SQL, where bound parameters are not expanded.
|
||||
///
|
||||
/// For example:
|
||||
@@ -1941,11 +1932,21 @@ extension Database {
|
||||
/// ```sql
|
||||
/// SELECT * FROM player WHERE email = ?
|
||||
/// ```
|
||||
public var sql: String {
|
||||
if let unexpandedSQL {
|
||||
return String(cString: unexpandedSQL).trimmedSQLStatement
|
||||
} else {
|
||||
return String(cString: sqlite3_sql(sqliteStatement)).trimmedSQLStatement
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1961,18 +1962,30 @@ extension Database {
|
||||
/// information from leaking in unexpected locations, so use this
|
||||
/// property with care.
|
||||
public var expandedSQL: String {
|
||||
guard let cString = sqlite3_expanded_sql(sqliteStatement) else {
|
||||
return ""
|
||||
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
|
||||
}
|
||||
defer { sqlite3_free(cString) }
|
||||
return String(cString: cString).trimmedSQLStatement
|
||||
}
|
||||
|
||||
public var description: String {
|
||||
if publicStatementArguments {
|
||||
switch impl {
|
||||
case let .trace_v1(expandedSQL):
|
||||
return expandedSQL
|
||||
} else {
|
||||
return sql
|
||||
|
||||
case let .trace_v2(_, _, _, publicStatementArguments):
|
||||
if publicStatementArguments {
|
||||
return expandedSQL
|
||||
} else {
|
||||
return _sql
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,9 +13,6 @@ 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 {
|
||||
@@ -75,12 +72,39 @@ public final class DatabasePool {
|
||||
purpose: "reader.\(readerCount)")
|
||||
})
|
||||
|
||||
// Set up journal mode unless readonly
|
||||
// Activate WAL Mode unless readonly
|
||||
if !configuration.readonly {
|
||||
switch configuration.journalMode {
|
||||
case .default, .wal:
|
||||
try writer.sync {
|
||||
try $0.setUpWALMode()
|
||||
try writer.sync { db in
|
||||
let journalMode = try String.fetchOne(db, sql: "PRAGMA journal_mode = WAL")
|
||||
guard journalMode == "wal" else {
|
||||
throw DatabaseError(message: "could not activate WAL Mode at path: \(path)")
|
||||
}
|
||||
|
||||
// https://www.sqlite.org/pragma.html#pragma_synchronous
|
||||
// > Many applications choose NORMAL when in WAL mode
|
||||
try db.execute(sql: "PRAGMA synchronous = NORMAL")
|
||||
|
||||
// Make sure a non-empty wal file exists.
|
||||
//
|
||||
// The presence of the wal file avoids an SQLITE_CANTOPEN (14)
|
||||
// error when the user opens a pool and reads from it.
|
||||
// See <https://github.com/groue/GRDB.swift/issues/102>.
|
||||
//
|
||||
// The non-empty wal file avoids an SQLITE_ERROR (1) error
|
||||
// when the user opens a pool and creates a wal snapshot
|
||||
// (which happens when starting a ValueObservation).
|
||||
// See <https://github.com/groue/GRDB.swift/issues/1383>.
|
||||
let walPath = path + "-wal"
|
||||
if try FileManager.default.fileExists(atPath: walPath) == false
|
||||
|| (URL(fileURLWithPath: walPath).resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0) == 0
|
||||
{
|
||||
try db.inSavepoint {
|
||||
try db.execute(sql: """
|
||||
CREATE TABLE grdb_issue_102 (id INTEGER PRIMARY KEY);
|
||||
DROP TABLE grdb_issue_102;
|
||||
""")
|
||||
return .commit
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -97,9 +121,6 @@ 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
|
||||
@@ -148,7 +169,7 @@ public final class DatabasePool {
|
||||
}
|
||||
}
|
||||
|
||||
// @unchecked because of databaseSnapshotCount, readerPool and suspensionObservers
|
||||
// @unchecked because of databaseSnapshotCount and readerPool
|
||||
extension DatabasePool: @unchecked Sendable { }
|
||||
|
||||
extension DatabasePool {
|
||||
@@ -324,21 +345,29 @@ extension DatabasePool: DatabaseReader {
|
||||
private func setupSuspension() {
|
||||
if configuration.observesSuspensionNotifications {
|
||||
let center = NotificationCenter.default
|
||||
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() }
|
||||
))
|
||||
center.addObserver(
|
||||
self,
|
||||
selector: #selector(DatabasePool.suspend(_:)),
|
||||
name: Database.suspendNotification,
|
||||
object: nil)
|
||||
center.addObserver(
|
||||
self,
|
||||
selector: #selector(DatabasePool.resume(_:)),
|
||||
name: Database.resumeNotification,
|
||||
object: nil)
|
||||
}
|
||||
}
|
||||
|
||||
@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
|
||||
|
||||
@@ -7,15 +7,15 @@ 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 {
|
||||
writer.configuration
|
||||
}
|
||||
|
||||
/// The path to the database file.
|
||||
///
|
||||
/// The path is `:memory:` for in-memory databases.
|
||||
public var path: String {
|
||||
writer.path
|
||||
}
|
||||
@@ -47,18 +47,6 @@ public final class DatabaseQueue {
|
||||
configuration: configuration,
|
||||
defaultLabel: "GRDB.DatabaseQueue")
|
||||
|
||||
// Set up journal mode unless readonly
|
||||
if !configuration.readonly {
|
||||
switch configuration.journalMode {
|
||||
case .default:
|
||||
break
|
||||
case .wal:
|
||||
try writer.sync {
|
||||
try $0.setUpWALMode()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
setupSuspension()
|
||||
|
||||
// Be a nice iOS citizen, and don't consume too much memory
|
||||
@@ -112,9 +100,6 @@ 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
|
||||
@@ -123,9 +108,6 @@ public final class DatabaseQueue {
|
||||
}
|
||||
}
|
||||
|
||||
// @unchecked because of suspensionObservers
|
||||
extension DatabaseQueue: @unchecked Sendable { }
|
||||
|
||||
extension DatabaseQueue {
|
||||
|
||||
// MARK: - Memory management
|
||||
@@ -207,21 +189,29 @@ extension DatabaseQueue: DatabaseReader {
|
||||
private func setupSuspension() {
|
||||
if configuration.observesSuspensionNotifications {
|
||||
let center = NotificationCenter.default
|
||||
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() }
|
||||
))
|
||||
center.addObserver(
|
||||
self,
|
||||
selector: #selector(DatabaseQueue.suspend(_:)),
|
||||
name: Database.suspendNotification,
|
||||
object: nil)
|
||||
center.addObserver(
|
||||
self,
|
||||
selector: #selector(DatabaseQueue.resume(_:)),
|
||||
name: Database.resumeNotification,
|
||||
object: nil)
|
||||
}
|
||||
}
|
||||
|
||||
@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
|
||||
|
||||
@@ -17,7 +17,6 @@ import Dispatch
|
||||
/// ### Database Information
|
||||
///
|
||||
/// - ``configuration``
|
||||
/// - ``path``
|
||||
///
|
||||
/// ### Reading from the Database
|
||||
///
|
||||
@@ -47,12 +46,6 @@ public protocol DatabaseReader: AnyObject, Sendable {
|
||||
/// The database configuration.
|
||||
var configuration: Configuration { get }
|
||||
|
||||
/// The path to the database file.
|
||||
///
|
||||
/// In-memory databases also have a path:
|
||||
/// see [In-Memory Databases](https://www.sqlite.org/inmemorydb.html).
|
||||
var path: String { get }
|
||||
|
||||
/// Closes the database connection.
|
||||
///
|
||||
/// - note: You do not have to call this method, and you should not call
|
||||
@@ -651,10 +644,6 @@ extension AnyDatabaseReader: DatabaseReader {
|
||||
base.configuration
|
||||
}
|
||||
|
||||
public var path: String {
|
||||
base.path
|
||||
}
|
||||
|
||||
public func close() throws {
|
||||
try base.close()
|
||||
}
|
||||
|
||||
@@ -964,10 +964,6 @@ extension AnyDatabaseWriter: DatabaseReader {
|
||||
base.configuration
|
||||
}
|
||||
|
||||
public var path: String {
|
||||
base.path
|
||||
}
|
||||
|
||||
public func close() throws {
|
||||
try base.close()
|
||||
}
|
||||
|
||||
+5
-3
@@ -39,6 +39,8 @@
|
||||
///
|
||||
/// - ``append(literal:)``
|
||||
/// - ``append(sql:arguments:)``
|
||||
/// - ``Swift/Collection/joined(separator:)``
|
||||
/// - ``Swift/Sequence/joined(separator:)``
|
||||
public struct SQL {
|
||||
/// `SQL.Element` is a component of an `SQL` literal.
|
||||
///
|
||||
@@ -316,12 +318,12 @@ extension SQL: SQLOrderingTerm {
|
||||
}
|
||||
|
||||
extension Sequence where Element == SQL {
|
||||
/// Returns the concatenated `SQL` literal of this sequence of literals,
|
||||
/// Concatenates the sequence elements into a new `SQL` literal,
|
||||
/// inserting the given raw SQL separator between each element.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```
|
||||
/// ```swift
|
||||
/// let components: [SQL] = [
|
||||
/// "UPDATE player",
|
||||
/// "SET name = \(name)",
|
||||
@@ -341,7 +343,7 @@ extension Sequence where Element == SQL {
|
||||
}
|
||||
|
||||
extension Collection where Element == SQL {
|
||||
/// Returns the concatenated `SQL` literal of this collection of literals,
|
||||
/// Concatenates the collection elements into a new `SQL` literal,
|
||||
/// inserting the given raw SQL separator between each element.
|
||||
///
|
||||
/// For example:
|
||||
|
||||
@@ -42,15 +42,14 @@ public final class Statement {
|
||||
public var sql: String {
|
||||
SchedulingWatchdog.preconditionValidQueue(database)
|
||||
|
||||
// trim white space and semicolon for homogeneous output
|
||||
// trim white space and semicolumn for homogeneous output
|
||||
return String(cString: sqlite3_sql(sqliteStatement)).trimmedSQLStatement
|
||||
}
|
||||
|
||||
/// The column names, ordered from left to right.
|
||||
public lazy var columnNames: [String] = {
|
||||
// swiftlint:disable:next redundant_self_in_closure
|
||||
let sqliteStatement = self.sqliteStatement
|
||||
return (0..<CInt(columnCount)).map { String(cString: sqlite3_column_name(sqliteStatement, $0)) }
|
||||
return (0..<CInt(self.columnCount)).map { String(cString: sqlite3_column_name(sqliteStatement, $0)) }
|
||||
}()
|
||||
|
||||
// The database region is reported by `sqlite3_set_authorizer`, and maybe
|
||||
@@ -91,8 +90,8 @@ public final class Statement {
|
||||
sqlite3_stmt_readonly(sqliteStatement) != 0
|
||||
}
|
||||
|
||||
/// A boolean value indicating if the statement can delete some rows.
|
||||
var canDeleteRows: Bool {
|
||||
/// A boolean value indicating if the statement deletes some rows.
|
||||
var isDeleteStatement: Bool {
|
||||
authorizerEventKinds.contains(where: \.isDelete)
|
||||
}
|
||||
|
||||
@@ -102,7 +101,7 @@ public final class Statement {
|
||||
/// Cache for index(ofColumn:). Keys are lowercase.
|
||||
private lazy var columnIndexes: [String: Int] = {
|
||||
Dictionary(
|
||||
columnNames.enumerated().map { ($0.element.lowercased(), $0.offset) },
|
||||
self.columnNames.enumerated().map { ($0.element.lowercased(), $0.offset) },
|
||||
uniquingKeysWith: { (left, _) in left }) // keep leftmost indexes
|
||||
}()
|
||||
|
||||
@@ -119,8 +118,8 @@ public final class Statement {
|
||||
/// - throws: DatabaseError in case of compilation error.
|
||||
required init?(
|
||||
database: Database,
|
||||
statementStart: UnsafePointer<CChar>,
|
||||
statementEnd: UnsafeMutablePointer<UnsafePointer<CChar>?>,
|
||||
statementStart: UnsafePointer<Int8>,
|
||||
statementEnd: UnsafeMutablePointer<UnsafePointer<Int8>?>,
|
||||
prepFlags: CUnsignedInt) throws
|
||||
{
|
||||
SchedulingWatchdog.preconditionValidQueue(database)
|
||||
@@ -223,7 +222,7 @@ public final class Statement {
|
||||
private var _arguments = StatementArguments()
|
||||
|
||||
lazy var sqliteArgumentCount: Int = {
|
||||
Int(sqlite3_bind_parameter_count(sqliteStatement))
|
||||
Int(sqlite3_bind_parameter_count(self.sqliteStatement))
|
||||
}()
|
||||
|
||||
// Returns ["id", nil, "name"] for "INSERT INTO table VALUES (:id, ?, :name)"
|
||||
|
||||
@@ -57,10 +57,10 @@ final class StatementAuthorizer {
|
||||
|
||||
private func authorize(
|
||||
_ actionCode: CInt,
|
||||
_ cString1: UnsafePointer<CChar>?,
|
||||
_ cString2: UnsafePointer<CChar>?,
|
||||
_ cString3: UnsafePointer<CChar>?,
|
||||
_ cString4: UnsafePointer<CChar>?)
|
||||
_ cString1: UnsafePointer<Int8>?,
|
||||
_ cString2: UnsafePointer<Int8>?,
|
||||
_ cString3: UnsafePointer<Int8>?,
|
||||
_ cString4: UnsafePointer<Int8>?)
|
||||
-> CInt
|
||||
{
|
||||
// Uncomment when debugging
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#if canImport(CoreGraphics)
|
||||
import CoreGraphics
|
||||
|
||||
/// CGFloat adopts DatabaseValueConvertible
|
||||
/// `CGFloat` is a database value.
|
||||
extension CGFloat: DatabaseValueConvertible {
|
||||
/// Returns a REAL database value.
|
||||
public var databaseValue: DatabaseValue {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import Foundation
|
||||
|
||||
/// Data is convertible to and from DatabaseValue.
|
||||
/// `Data` is a database value.
|
||||
extension Data: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
public init(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
if let bytes = sqlite3_column_blob(sqliteStatement, index) {
|
||||
|
||||
@@ -75,7 +75,7 @@ extension DatabaseDateComponents: StatementColumnConvertible {
|
||||
}
|
||||
let length = Int(sqlite3_column_bytes(sqliteStatement, index)) // avoid an strlen
|
||||
let components = cString.withMemoryRebound(
|
||||
to: CChar.self,
|
||||
to: Int8.self,
|
||||
capacity: length + 1 /* trailing \0 */) { cString in
|
||||
SQLiteDateParser().components(cString: cString, length: length)
|
||||
}
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import Foundation
|
||||
|
||||
#if !os(Linux)
|
||||
/// NSDate is stored in the database using the format
|
||||
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
|
||||
/// `NSDate` is a database value.
|
||||
extension NSDate: DatabaseValueConvertible {
|
||||
/// Returns a TEXT database value that contains the date encoded as
|
||||
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
|
||||
@@ -31,8 +30,6 @@ extension NSDate: DatabaseValueConvertible {
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Date is stored in the database using the format
|
||||
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
|
||||
extension Date: DatabaseValueConvertible {
|
||||
/// Returns a TEXT database value that contains the date encoded as
|
||||
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
|
||||
@@ -115,6 +112,7 @@ extension Date: DatabaseValueConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// `Date` is a database value.
|
||||
extension Date: StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#if !os(Linux)
|
||||
import Foundation
|
||||
|
||||
/// Decimal adopts DatabaseValueConvertible
|
||||
/// `Decimal` is a database value.
|
||||
extension Decimal: DatabaseValueConvertible {
|
||||
/// Returns a TEXT decimal value.
|
||||
public var databaseValue: DatabaseValue {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#if !os(Linux)
|
||||
import Foundation
|
||||
|
||||
/// NSData is convertible to and from DatabaseValue.
|
||||
/// `NSData` is a database value.
|
||||
extension NSData: DatabaseValueConvertible {
|
||||
|
||||
/// Returns a BLOB database value.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import Foundation
|
||||
|
||||
/// NSNull adopts DatabaseValueConvertible
|
||||
/// `NSDate` is a database value.
|
||||
extension NSNull: DatabaseValueConvertible {
|
||||
|
||||
/// Returns the NULL database value.
|
||||
|
||||
@@ -9,7 +9,7 @@ private let integerRoundingBehavior = NSDecimalNumberHandler(
|
||||
raiseOnUnderflow: false,
|
||||
raiseOnDivideByZero: false)
|
||||
|
||||
/// NSNumber adopts DatabaseValueConvertible
|
||||
/// `NSNumber` is a database value.
|
||||
extension NSNumber: DatabaseValueConvertible {
|
||||
|
||||
/// A database value.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#if !os(Linux)
|
||||
import Foundation
|
||||
|
||||
/// NSString adopts DatabaseValueConvertible
|
||||
/// `NSString` is a database value.
|
||||
extension NSString: DatabaseValueConvertible {
|
||||
|
||||
/// Returns a TEXT database value.
|
||||
|
||||
@@ -4,7 +4,6 @@ import Foundation
|
||||
|
||||
@usableFromInline
|
||||
struct SQLiteDateParser {
|
||||
// swiftlint:disable:next unneeded_synthesized_initializer
|
||||
@usableFromInline
|
||||
init() { }
|
||||
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import Foundation
|
||||
|
||||
#if !os(Linux)
|
||||
/// NSURL stores its absoluteString in the database.
|
||||
/// `NSURL` is a database value.
|
||||
///
|
||||
/// `NSURL` stores its `absoluteString` in the database.
|
||||
extension NSURL: DatabaseValueConvertible {
|
||||
|
||||
/// Returns a TEXT database value containing the absolute URL.
|
||||
@@ -18,5 +20,7 @@ extension NSURL: DatabaseValueConvertible {
|
||||
}
|
||||
#endif
|
||||
|
||||
/// URL stores its absoluteString in the database.
|
||||
/// `URL` is a database value.
|
||||
///
|
||||
/// `URL` stores its `absoluteString` in the database.
|
||||
extension URL: DatabaseValueConvertible { }
|
||||
@@ -1,7 +1,7 @@
|
||||
import Foundation
|
||||
|
||||
#if !os(Linux)
|
||||
/// NSUUID adopts DatabaseValueConvertible
|
||||
/// `NSUUID` is a database value.
|
||||
extension NSUUID: DatabaseValueConvertible {
|
||||
/// Returns a BLOB database value containing the uuid bytes.
|
||||
public var databaseValue: DatabaseValue {
|
||||
@@ -35,7 +35,7 @@ extension NSUUID: DatabaseValueConvertible {
|
||||
}
|
||||
#endif
|
||||
|
||||
/// UUID adopts DatabaseValueConvertible
|
||||
/// `UUID` is a database value.
|
||||
extension UUID: DatabaseValueConvertible {
|
||||
/// Returns a BLOB database value containing the uuid bytes.
|
||||
public var databaseValue: DatabaseValue {
|
||||
|
||||
@@ -44,6 +44,7 @@ extension Optional: SQLSelectable where Wrapped: SQLSelectable {
|
||||
|
||||
extension Optional: SQLSpecificExpressible where Wrapped: SQLSpecificExpressible { }
|
||||
|
||||
/// `Optional` is a database value when it wrapped type is.
|
||||
extension Optional: DatabaseValueConvertible where Wrapped: DatabaseValueConvertible {
|
||||
public var databaseValue: DatabaseValue {
|
||||
switch self {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// MARK: - Value Types
|
||||
|
||||
/// Bool adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
/// `Bool` is a database value.
|
||||
extension Bool: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
@@ -95,7 +95,7 @@ extension Bool: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// Int adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
/// `Int` is a database value.
|
||||
extension Int: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
@@ -134,7 +134,7 @@ extension Int: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// Int8 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
/// `Int8` is a database value.
|
||||
extension Int8: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
@@ -173,7 +173,7 @@ extension Int8: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// Int16 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
/// `Int16` is a database value.
|
||||
extension Int16: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
@@ -212,7 +212,7 @@ extension Int16: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// Int32 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
/// `Int32` is a database value.
|
||||
extension Int32: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
@@ -251,7 +251,7 @@ extension Int32: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// Int64 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
/// `Int64` is a database value.
|
||||
extension Int64: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
@@ -294,7 +294,7 @@ extension Int64: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// UInt adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
/// `UInt` is a database value.
|
||||
extension UInt: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
@@ -333,7 +333,7 @@ extension UInt: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// UInt8 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
/// `UInt8` is a database value.
|
||||
extension UInt8: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
@@ -372,7 +372,7 @@ extension UInt8: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// UInt16 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
/// `UInt16` is a database value.
|
||||
extension UInt16: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
@@ -411,7 +411,7 @@ extension UInt16: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// UInt32 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
/// `UInt32` is a database value.
|
||||
extension UInt32: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
@@ -450,7 +450,7 @@ extension UInt32: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// UInt64 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
/// `UInt64` is a database value.
|
||||
extension UInt64: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
@@ -489,7 +489,7 @@ extension UInt64: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// Double adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
/// `Double` is a database value.
|
||||
extension Double: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
@@ -529,7 +529,7 @@ extension Double: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// Float adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
/// `Float` is a database value.
|
||||
extension Float: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
@@ -569,7 +569,7 @@ extension Float: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// String adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
/// `String` is a database value.
|
||||
extension String: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
|
||||
@@ -20,8 +20,8 @@ extension Database {
|
||||
|
||||
// Drop cached statements that delete, because the addition of an
|
||||
// observer may change the need for truncate optimization prevention.
|
||||
publicStatementCache.removeAll { $0.canDeleteRows }
|
||||
internalStatementCache.removeAll { $0.canDeleteRows }
|
||||
publicStatementCache.removeAll { $0.isDeleteStatement }
|
||||
internalStatementCache.removeAll { $0.isDeleteStatement }
|
||||
|
||||
observationBroker.add(transactionObserver: transactionObserver, extent: extent)
|
||||
}
|
||||
@@ -33,8 +33,8 @@ extension Database {
|
||||
|
||||
// Drop cached statements that delete, because the removal of an
|
||||
// observer may change the need for truncate optimization prevention.
|
||||
publicStatementCache.removeAll { $0.canDeleteRows }
|
||||
internalStatementCache.removeAll { $0.canDeleteRows }
|
||||
publicStatementCache.removeAll { $0.isDeleteStatement }
|
||||
internalStatementCache.removeAll { $0.isDeleteStatement }
|
||||
|
||||
observationBroker.remove(transactionObserver: transactionObserver)
|
||||
}
|
||||
@@ -778,8 +778,7 @@ 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 observed writer
|
||||
/// database connection.
|
||||
/// - precondition: This method must not access the database.
|
||||
func databaseDidChange(with event: DatabaseEvent)
|
||||
|
||||
/// Called when a transaction is about to be committed.
|
||||
@@ -787,8 +786,7 @@ 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 observed writer
|
||||
/// database connection.
|
||||
/// - precondition: This method must not access the database.
|
||||
/// - throws: The eventual error that rollbacks pending changes.
|
||||
func databaseWillCommit() throws
|
||||
|
||||
@@ -1095,12 +1093,7 @@ public struct DatabaseEvent {
|
||||
self.impl = impl
|
||||
}
|
||||
|
||||
init(
|
||||
kind: Kind,
|
||||
rowID: Int64,
|
||||
databaseNameCString: UnsafePointer<CChar>?,
|
||||
tableNameCString: UnsafePointer<CChar>?)
|
||||
{
|
||||
init(kind: Kind, rowID: Int64, databaseNameCString: UnsafePointer<Int8>?, tableNameCString: UnsafePointer<Int8>?) {
|
||||
self.init(
|
||||
kind: kind,
|
||||
rowID: rowID,
|
||||
@@ -1136,8 +1129,8 @@ private protocol DatabaseEventImpl {
|
||||
/// Optimization: MetalDatabaseEventImpl does not create Swift strings from raw
|
||||
/// SQLite char* until actually asked for databaseName or tableName.
|
||||
private struct MetalDatabaseEventImpl: DatabaseEventImpl {
|
||||
let databaseNameCString: UnsafePointer<CChar>?
|
||||
let tableNameCString: UnsafePointer<CChar>?
|
||||
let databaseNameCString: UnsafePointer<Int8>?
|
||||
let tableNameCString: UnsafePointer<Int8>?
|
||||
|
||||
var databaseName: String { String(cString: databaseNameCString!) }
|
||||
var tableName: String { String(cString: tableNameCString!) }
|
||||
@@ -1272,8 +1265,8 @@ public struct DatabasePreUpdateEvent {
|
||||
kind: Kind,
|
||||
initialRowID: Int64,
|
||||
finalRowID: Int64,
|
||||
databaseNameCString: UnsafePointer<CChar>?,
|
||||
tableNameCString: UnsafePointer<CChar>?)
|
||||
databaseNameCString: UnsafePointer<Int8>?,
|
||||
tableNameCString: UnsafePointer<Int8>?)
|
||||
{
|
||||
self.init(
|
||||
kind: kind,
|
||||
@@ -1329,8 +1322,8 @@ private struct MetalDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl {
|
||||
let connection: SQLiteConnection
|
||||
let kind: DatabasePreUpdateEvent.Kind
|
||||
|
||||
let databaseNameCString: UnsafePointer<CChar>?
|
||||
let tableNameCString: UnsafePointer<CChar>?
|
||||
let databaseNameCString: UnsafePointer<Int8>?
|
||||
let tableNameCString: UnsafePointer<Int8>?
|
||||
|
||||
var databaseName: String { String(cString: databaseNameCString!) }
|
||||
var tableName: String { String(cString: tableNameCString!) }
|
||||
|
||||
@@ -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 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 views or 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.belongsTo("player")
|
||||
t.belongsTo("team")
|
||||
t.column("playerId", .integer).references("player")
|
||||
t.column("teamId", .text).references("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.belongsTo("team").notNull()
|
||||
t.column("teamId", .integer).notNull().references("team")
|
||||
}
|
||||
|
||||
// REQUIRES EXTRA CONFIGURATION
|
||||
@@ -319,8 +319,6 @@ 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
|
||||
@@ -374,13 +372,6 @@ 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:)``
|
||||
|
||||
@@ -21,13 +21,11 @@ We'll address all of those challenges below.
|
||||
>
|
||||
> Always consider sharing plain files, or any other inter-process communication technique, before sharing an SQLite database.
|
||||
|
||||
## Use the WAL mode
|
||||
## Use a Database Pool
|
||||
|
||||
In order to access a shared database, use a ``DatabasePool``. It opens the database in the [WAL mode], which helps sharing a database because it allows multiple processes to access the database concurrently.
|
||||
In order to access a shared database, use a ``DatabasePool``. It opens the database in the [WAL mode], which helps sharing a database.
|
||||
|
||||
It is also possible to use a ``DatabaseQueue``, with the `.wal` ``Configuration/journalMode``.
|
||||
|
||||
Since several processes may open the database at the same time, protect the creation of the database connection with an [NSFileCoordinator].
|
||||
Since several processes may open the database at the same time, protect the creation of the database pool with an [NSFileCoordinator].
|
||||
|
||||
- In a process that can create and write in the database, use this sample code:
|
||||
|
||||
|
||||
@@ -83,9 +83,7 @@ do {
|
||||
- ``acceptsDoubleQuotedStringLiterals``
|
||||
- ``busyMode``
|
||||
- ``foreignKeysEnabled``
|
||||
- ``journalMode``
|
||||
- ``readonly``
|
||||
- ``JournalModeConfiguration``
|
||||
|
||||
### Configuring GRDB Connections
|
||||
|
||||
|
||||
@@ -165,6 +165,38 @@ This extra conformance is not required: only aim at the low-level C interface if
|
||||
- ``fetchSet(_:_:)-1foke``
|
||||
- ``fetchOne(_:_:)-o6yj``
|
||||
|
||||
### Supported Value Types
|
||||
|
||||
- ``Swift/Bool``
|
||||
- ``CoreFoundation/CGFloat``
|
||||
- ``Foundation/Data``
|
||||
- ``DatabaseDateComponents``
|
||||
- ``Foundation/Date``
|
||||
- ``Swift/Double``
|
||||
- ``Foundation/Decimal``
|
||||
- ``Swift/Float``
|
||||
- ``Swift/Int``
|
||||
- ``Swift/Int8``
|
||||
- ``Swift/Int16``
|
||||
- ``Swift/Int32``
|
||||
- ``Swift/Int64``
|
||||
- ``Foundation/NSData``
|
||||
- ``Foundation/NSDate``
|
||||
- ``Foundation/NSNull``
|
||||
- ``Foundation/NSNumber``
|
||||
- ``Foundation/NSString``
|
||||
- ``Foundation/NSURL``
|
||||
- ``Foundation/NSUUID``
|
||||
- ``Swift/Optional``
|
||||
- ``Swift/UInt``
|
||||
- ``Swift/UInt8``
|
||||
- ``Swift/UInt16``
|
||||
- ``Swift/UInt32``
|
||||
- ``Swift/UInt64``
|
||||
- ``Swift/String``
|
||||
- ``Foundation/URL``
|
||||
- ``Foundation/UUID``
|
||||
|
||||
### Supporting Types
|
||||
|
||||
- ``DatabaseValueCursor``
|
||||
|
||||
@@ -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 access the observed writer database connection in any way. This limitation does not apply to `databaseDidCommit` and `databaseDidRollback` which can use their database argument.
|
||||
- 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.
|
||||
|
||||
## Filtering Database Events
|
||||
|
||||
|
||||
@@ -26,7 +26,10 @@ 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.belongsTo("author").notNull()
|
||||
t.column("authorId", .integer)
|
||||
.notNull()
|
||||
.indexed()
|
||||
.references("author", onDelete: .cascade)
|
||||
t.column("title", .text).notNull()
|
||||
}
|
||||
|
||||
|
||||
@@ -31,8 +31,10 @@ migrator.registerMigration("createLibrary") { db in
|
||||
try db.create(table: "book") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("title", .text).notNull() // (5)
|
||||
t.belongsTo("author", onDelete: .cascade) // (6)
|
||||
t.column("authorId", .integer) // (6)
|
||||
.notNull() // (7)
|
||||
.indexed() // (8)
|
||||
.references("author", onDelete: .cascade) // (9)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,8 +46,10 @@ 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. 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.
|
||||
6. The `book.authorId` column is used to link a book to the author it belongs to.
|
||||
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.
|
||||
|
||||
|
||||
@@ -81,7 +81,6 @@ For a more detailed overview, see [SQLite API](https://github.com/groue/GRDB.swi
|
||||
|
||||
### Database Values
|
||||
|
||||
- ``DatabaseDateComponents``
|
||||
- ``DatabaseValueConvertible``
|
||||
- ``StatementColumnConvertible``
|
||||
|
||||
|
||||
+3
-3
@@ -143,9 +143,9 @@ public struct FTS5 {
|
||||
private static func api_v2(
|
||||
_ db: Database,
|
||||
// swiftlint:disable:next line_length
|
||||
_ sqlite3_prepare_v3: @convention(c) (OpaquePointer?, UnsafePointer<CChar>?, CInt, CUnsignedInt, UnsafeMutablePointer<OpaquePointer?>?, UnsafeMutablePointer<UnsafePointer<CChar>?>?) -> CInt,
|
||||
_ sqlite3_prepare_v3: @convention(c) (OpaquePointer?, UnsafePointer<Int8>?, CInt, CUnsignedInt, UnsafeMutablePointer<OpaquePointer?>?, UnsafeMutablePointer<UnsafePointer<Int8>?>?) -> CInt,
|
||||
// swiftlint:disable:next line_length
|
||||
_ sqlite3_bind_pointer: @convention(c) (OpaquePointer?, CInt, UnsafeMutableRawPointer?, UnsafePointer<CChar>?, (@convention(c) (UnsafeMutableRawPointer?) -> Void)?) -> CInt)
|
||||
_ sqlite3_bind_pointer: @convention(c) (OpaquePointer?, CInt, UnsafeMutableRawPointer?, UnsafePointer<Int8>?, (@convention(c) (UnsafeMutableRawPointer?) -> Void)?) -> CInt)
|
||||
-> UnsafePointer<fts5_api>
|
||||
{
|
||||
var statement: SQLiteStatement? = nil
|
||||
@@ -157,7 +157,7 @@ public struct FTS5 {
|
||||
fatalError("FTS5 is not available")
|
||||
}
|
||||
defer { sqlite3_finalize(statement) }
|
||||
type.utf8Start.withMemoryRebound(to: CChar.self, capacity: type.utf8CodeUnitCount) { typePointer in
|
||||
type.utf8Start.withMemoryRebound(to: Int8.self, capacity: type.utf8CodeUnitCount) { typePointer in
|
||||
_ = sqlite3_bind_pointer(statement, 1, &api, typePointer, nil)
|
||||
}
|
||||
sqlite3_step(statement)
|
||||
|
||||
@@ -131,10 +131,10 @@ extension Database {
|
||||
tokenizerPointer: OpaquePointer?,
|
||||
context: UnsafeMutableRawPointer?,
|
||||
flags: CInt,
|
||||
pText: UnsafePointer<CChar>?,
|
||||
pText: UnsafePointer<Int8>?,
|
||||
nText: CInt,
|
||||
// swiftlint:disable:next line_length
|
||||
tokenCallback: (@convention(c) (UnsafeMutableRawPointer?, CInt, UnsafePointer<CChar>?, CInt, CInt, CInt) -> CInt)?)
|
||||
tokenCallback: (@convention(c) (UnsafeMutableRawPointer?, CInt, UnsafePointer<Int8>?, CInt, CInt, CInt) -> CInt)?)
|
||||
-> CInt
|
||||
{
|
||||
guard let tokenizerPointer else {
|
||||
|
||||
@@ -7,7 +7,7 @@ import Foundation
|
||||
public typealias FTS5TokenCallback = @convention(c) (
|
||||
_ context: UnsafeMutableRawPointer?,
|
||||
_ flags: CInt,
|
||||
_ pToken: UnsafePointer<CChar>?,
|
||||
_ pToken: UnsafePointer<Int8>?,
|
||||
_ nToken: CInt,
|
||||
_ iStart: CInt,
|
||||
_ iEnd: CInt)
|
||||
@@ -77,7 +77,7 @@ public protocol FTS5Tokenizer: AnyObject {
|
||||
func tokenize(
|
||||
context: UnsafeMutableRawPointer?,
|
||||
tokenization: FTS5Tokenization,
|
||||
pText: UnsafePointer<CChar>?,
|
||||
pText: UnsafePointer<Int8>?,
|
||||
nText: CInt,
|
||||
tokenCallback: @escaping FTS5TokenCallback)
|
||||
-> CInt
|
||||
@@ -143,7 +143,7 @@ extension FTS5Tokenizer {
|
||||
guard let addr = buffer.baseAddress else {
|
||||
return []
|
||||
}
|
||||
let pText = UnsafeMutableRawPointer(mutating: addr).assumingMemoryBound(to: CChar.self)
|
||||
let pText = UnsafeMutableRawPointer(mutating: addr).assumingMemoryBound(to: Int8.self)
|
||||
let nText = CInt(buffer.count)
|
||||
|
||||
var context = TokenizeContext()
|
||||
@@ -206,8 +206,8 @@ extension Database {
|
||||
} else {
|
||||
func withArrayOfCStrings<Result>(
|
||||
_ input: [String],
|
||||
_ output: inout ContiguousArray<UnsafePointer<CChar>>,
|
||||
_ accessor: (ContiguousArray<UnsafePointer<CChar>>) -> Result)
|
||||
_ output: inout ContiguousArray<UnsafePointer<Int8>>,
|
||||
_ accessor: (ContiguousArray<UnsafePointer<Int8>>) -> Result)
|
||||
-> Result
|
||||
{
|
||||
if output.count == input.count {
|
||||
@@ -219,7 +219,7 @@ extension Database {
|
||||
}
|
||||
}
|
||||
}
|
||||
var cStrings = ContiguousArray<UnsafePointer<CChar>>()
|
||||
var cStrings = ContiguousArray<UnsafePointer<Int8>>()
|
||||
cStrings.reserveCapacity(arguments.count)
|
||||
code = withArrayOfCStrings(arguments, &cStrings) { (cStrings) in
|
||||
cStrings.withUnsafeBufferPointer { azArg in
|
||||
@@ -252,7 +252,7 @@ extension Database {
|
||||
func tokenize(
|
||||
context: UnsafeMutableRawPointer?,
|
||||
tokenization: FTS5Tokenization,
|
||||
pText: UnsafePointer<CChar>?,
|
||||
pText: UnsafePointer<Int8>?,
|
||||
nText: CInt,
|
||||
tokenCallback: @escaping FTS5TokenCallback)
|
||||
-> CInt
|
||||
|
||||
@@ -87,7 +87,7 @@ extension FTS5WrapperTokenizer {
|
||||
public func tokenize(
|
||||
context: UnsafeMutableRawPointer?,
|
||||
tokenization: FTS5Tokenization,
|
||||
pText: UnsafePointer<CChar>?,
|
||||
pText: UnsafePointer<Int8>?,
|
||||
nText: CInt,
|
||||
tokenCallback: @escaping FTS5TokenCallback)
|
||||
-> CInt
|
||||
@@ -138,7 +138,7 @@ extension FTS5WrapperTokenizer {
|
||||
return
|
||||
}
|
||||
let pToken = UnsafeMutableRawPointer(mutating: addr)
|
||||
.assumingMemoryBound(to: CChar.self)
|
||||
.assumingMemoryBound(to: Int8.self)
|
||||
let nToken = CInt(buffer.count)
|
||||
|
||||
// Inject token bytes into SQLite
|
||||
|
||||
@@ -269,8 +269,8 @@ public struct DatabaseMigrator {
|
||||
writer.asyncBarrierWriteWithoutTransaction { dbResult in
|
||||
do {
|
||||
let db = try dbResult.get()
|
||||
if let lastMigration = _migrations.last {
|
||||
try migrate(db, upTo: lastMigration.identifier)
|
||||
if let lastMigration = self._migrations.last {
|
||||
try self.migrate(db, upTo: lastMigration.identifier)
|
||||
}
|
||||
completion(.success(db))
|
||||
} catch {
|
||||
@@ -409,7 +409,7 @@ public struct DatabaseMigrator {
|
||||
if eraseDatabaseOnSchemaChange {
|
||||
var needsErase = false
|
||||
try db.inTransaction(.deferred) {
|
||||
let appliedIdentifiers = try appliedIdentifiers(db)
|
||||
let appliedIdentifiers = try self.appliedIdentifiers(db)
|
||||
let knownIdentifiers = Set(_migrations.map { $0.identifier })
|
||||
if !appliedIdentifiers.isSubset(of: knownIdentifiers) {
|
||||
// Database contains an unknown migration
|
||||
@@ -446,7 +446,7 @@ public struct DatabaseMigrator {
|
||||
//
|
||||
// So let's create a "regular" temporary database:
|
||||
let tmpURL = URL(fileURLWithPath: NSTemporaryDirectory())
|
||||
.appendingPathComponent(ProcessInfo.processInfo.globallyUniqueString)
|
||||
.appendingPathComponent(ProcessInfo().globallyUniqueString)
|
||||
defer {
|
||||
try? FileManager().removeItem(at: tmpURL)
|
||||
}
|
||||
|
||||
@@ -28,23 +28,26 @@
|
||||
/// }
|
||||
/// try db.create(table: "book") { t in
|
||||
/// t.autoIncrementedPrimaryKey("id")
|
||||
/// t.belongsTo("author", onDelete: .cascade) // (2)
|
||||
/// t.column("authorId", .integer) // (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. 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.
|
||||
/// belongs to.
|
||||
/// 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,22 +28,26 @@
|
||||
/// }
|
||||
/// try db.create(table: "book") { t in
|
||||
/// t.autoIncrementedPrimaryKey("id")
|
||||
/// t.belongsTo("author", onDelete: .cascade) // (2)
|
||||
/// t.column("authorId", .integer) // (2)
|
||||
/// .notNull() // (3)
|
||||
/// .indexed() // (4)
|
||||
/// .references("author", onDelete: .cascade) // (5)
|
||||
/// t.column("title", .text)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// 1. The author table has a primary key.
|
||||
/// 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.
|
||||
/// 2. The `book.authorId` column is used to link a book to the author it
|
||||
/// belongs to.
|
||||
/// 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,9 +29,10 @@
|
||||
/// }
|
||||
/// try db.create(table: "demographics") { t in
|
||||
/// t.autoIncrementedPrimaryKey("id")
|
||||
/// t.belongsTo("country", onDelete: .cascade) // (2)
|
||||
/// t.column("countryCode", .text) // (2)
|
||||
/// .notNull() // (3)
|
||||
/// .unique() // (4)
|
||||
/// .references("country", onDelete: .cascade) // (5)
|
||||
/// t.column("population", .integer)
|
||||
/// t.column("density", .double)
|
||||
/// }
|
||||
@@ -39,17 +40,16 @@
|
||||
///
|
||||
/// 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. 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.
|
||||
/// profile to the country it belongs to.
|
||||
/// 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.
|
||||
|
||||
@@ -38,7 +38,7 @@ struct DatabasePromise<T> {
|
||||
/// Returns a promise whose value is transformed by the given closure.
|
||||
func map<U>(_ transform: @escaping (T) throws -> U) -> DatabasePromise<U> {
|
||||
DatabasePromise<U> { db in
|
||||
try transform(resolve(db))
|
||||
try transform(self.resolve(db))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -196,7 +196,7 @@ public struct SQLExpression {
|
||||
|
||||
/// An associative binary SQL operator, such as `+`, `*`, `AND`, etc.
|
||||
///
|
||||
/// Use it with the `joined(operator:)` method. For example:
|
||||
/// Use an associative operator with the `joined(operator:)` method:
|
||||
///
|
||||
/// ```swift
|
||||
/// // SELECT score + bonus + 1000 FROM player
|
||||
@@ -206,6 +206,27 @@ public struct SQLExpression {
|
||||
/// 1000.databaseValue]
|
||||
/// let request = Player.select(values.joined(operator: .add))
|
||||
/// ```
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Arithmetic Operators
|
||||
///
|
||||
/// - ``add``
|
||||
/// - ``multiply``
|
||||
///
|
||||
/// ### Logical Operators
|
||||
///
|
||||
/// - ``and``
|
||||
/// - ``or``
|
||||
///
|
||||
/// ### String Operators
|
||||
///
|
||||
/// - ``concat``
|
||||
///
|
||||
/// ### Bitwise Operators
|
||||
///
|
||||
/// - ``bitwiseAnd``
|
||||
/// - ``bitwiseOr``
|
||||
public struct AssociativeBinaryOperator: Hashable {
|
||||
/// The SQL operator
|
||||
let sql: String
|
||||
@@ -237,7 +258,7 @@ public struct SQLExpression {
|
||||
self.isBijective = bijective
|
||||
}
|
||||
|
||||
/// The `+` binary SQL operator.
|
||||
/// The arithmetic `+` binary SQL operator.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -245,13 +266,19 @@ public struct SQLExpression {
|
||||
/// // score + bonus
|
||||
/// [Column("score"), Column("bonus")].joined(operator: .add)
|
||||
/// ```
|
||||
///
|
||||
/// The neutral value of the `add` operator, used when joining an
|
||||
/// empty sequence, is `0`.
|
||||
///
|
||||
/// The `add` operator performs a numeric addition. To concatenate
|
||||
/// strings, use the ``concat`` operator instead.
|
||||
public static let add = AssociativeBinaryOperator(
|
||||
sql: "+",
|
||||
neutralValue: 0.databaseValue,
|
||||
strictlyAssociative: false,
|
||||
bijective: false)
|
||||
|
||||
/// The `*` binary SQL operator.
|
||||
/// The arithmetic `*` binary SQL operator.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -259,13 +286,16 @@ public struct SQLExpression {
|
||||
/// // score * factor
|
||||
/// [Column("score"), Column("factor")].joined(operator: .multiply)
|
||||
/// ```
|
||||
///
|
||||
/// The neutral value of the `multiply` operator, used when joining an
|
||||
/// empty sequence, is `1`.
|
||||
public static let multiply = AssociativeBinaryOperator(
|
||||
sql: "*",
|
||||
neutralValue: 1.databaseValue,
|
||||
strictlyAssociative: false,
|
||||
bijective: false)
|
||||
|
||||
/// The `AND` binary SQL operator.
|
||||
/// The logical `AND` binary SQL operator.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -273,13 +303,16 @@ public struct SQLExpression {
|
||||
/// // isBlue AND isTall
|
||||
/// [Column("isBlue"), Column("isTall")].joined(operator: .and)
|
||||
/// ```
|
||||
///
|
||||
/// The neutral value of the `and` operator, used when joining an
|
||||
/// empty sequence, is `true`.
|
||||
public static let and = AssociativeBinaryOperator(
|
||||
sql: "AND",
|
||||
neutralValue: true.databaseValue,
|
||||
strictlyAssociative: true,
|
||||
bijective: false)
|
||||
|
||||
/// The `OR` binary SQL operator.
|
||||
/// The logical `OR` binary SQL operator.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -287,6 +320,9 @@ public struct SQLExpression {
|
||||
/// // isBlue OR isTall
|
||||
/// [Column("isBlue"), Column("isTall")].joined(operator: .or)
|
||||
/// ```
|
||||
///
|
||||
/// The neutral value of the `or` operator, used when joining an
|
||||
/// empty sequence, is `false`.
|
||||
public static let or = AssociativeBinaryOperator(
|
||||
sql: "OR",
|
||||
neutralValue: false.databaseValue,
|
||||
@@ -301,13 +337,16 @@ public struct SQLExpression {
|
||||
/// // firstName || ' ' || lastName
|
||||
/// [Column("firstName"), " ", Column("lastName")].joined(operator: .concat)
|
||||
/// ```
|
||||
///
|
||||
/// The neutral value of the `concat` operator, used when joining an
|
||||
/// empty sequence, is the empty string.
|
||||
public static let concat = AssociativeBinaryOperator(
|
||||
sql: "||",
|
||||
neutralValue: "".databaseValue,
|
||||
strictlyAssociative: true,
|
||||
bijective: true)
|
||||
|
||||
/// The `&` bitwise AND SQL operator.
|
||||
/// The bitwise `&` SQL operator.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -315,13 +354,17 @@ public struct SQLExpression {
|
||||
/// // mask & 2
|
||||
/// [Column("mask"), 2.databaseValue].joined(operator: .bitwiseAnd)
|
||||
/// ```
|
||||
///
|
||||
/// The neutral value of the `bitwiseAnd` operator, used when
|
||||
/// joining an empty sequence, is `-1` (the signed 64-bit integer
|
||||
/// with all bits set).
|
||||
public static let bitwiseAnd = AssociativeBinaryOperator(
|
||||
sql: "&",
|
||||
neutralValue: (-1).databaseValue,
|
||||
strictlyAssociative: true,
|
||||
bijective: false)
|
||||
|
||||
/// The `|` bitwise OR SQL operator.
|
||||
/// The bitwise `|` SQL operator.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -329,6 +372,9 @@ public struct SQLExpression {
|
||||
/// // mask | 2
|
||||
/// [Column("mask"), 2.databaseValue].joined(operator: .bitwiseOr)
|
||||
/// ```
|
||||
///
|
||||
/// The neutral value of the `bitwiseOr` operator, used when
|
||||
/// joining an empty sequence, is `0`.
|
||||
public static let bitwiseOr = AssociativeBinaryOperator(
|
||||
sql: "|",
|
||||
neutralValue: 0.databaseValue,
|
||||
@@ -848,7 +894,7 @@ extension SQLExpression {
|
||||
///
|
||||
/// try "foo'bar".databaseValue.quotedSQL(db) // "'foo''bar'""
|
||||
func quotedSQL(_ db: Database) throws -> String {
|
||||
let context = SQLGenerationContext(db, argumentsSink: .literalValues)
|
||||
let context = SQLGenerationContext(db, argumentsSink: .forRawSQL)
|
||||
return try sql(context)
|
||||
}
|
||||
|
||||
@@ -1786,6 +1832,20 @@ extension SQLExpressible where Self == Column {
|
||||
/// - ``uppercased``
|
||||
/// - ``SQLDateModifier``
|
||||
///
|
||||
/// ### Create SQL Expressions from Sequences
|
||||
///
|
||||
/// - ``Swift/Sequence/contains(_:)-9i0ld``
|
||||
/// - ``Swift/Sequence/contains(_:)-o8ic``
|
||||
/// - ``Swift/Sequence/joined(operator:)-33dy5``
|
||||
/// - ``Swift/Sequence/joined(operator:)-4k88t``
|
||||
///
|
||||
/// ### Create SQL Expressions from Ranges
|
||||
///
|
||||
/// - ``Swift/ClosedRange/contains(_:)-64zwp``
|
||||
/// - ``Swift/ClosedRange/contains(_:)-19a6d``
|
||||
/// - ``Swift/Range/contains(_:)-11nr0``
|
||||
/// - ``Swift/Range/contains(_:)-3v32b``
|
||||
///
|
||||
/// ### Creating Ordering Terms
|
||||
///
|
||||
/// - ``asc``
|
||||
@@ -1853,13 +1913,8 @@ extension Sequence where Element: SQLSpecificExpressible {
|
||||
/// ```
|
||||
///
|
||||
/// When the sequence is empty, `joined(operator:)` returns the neutral
|
||||
/// value of the operator. It is:
|
||||
///
|
||||
/// - `0` for ``SQLExpression/AssociativeBinaryOperator/add``
|
||||
/// - `1` for ``SQLExpression/AssociativeBinaryOperator/multiply``
|
||||
/// - `false` for ``SQLExpression/AssociativeBinaryOperator/or``
|
||||
/// - `true` for ``SQLExpression/AssociativeBinaryOperator/and``
|
||||
/// - `""` for ``SQLExpression/AssociativeBinaryOperator/concat``
|
||||
/// value of the operator. See
|
||||
/// ``SQLExpression/AssociativeBinaryOperator`` for more information.
|
||||
public func joined(operator: SQLExpression.AssociativeBinaryOperator) -> SQLExpression {
|
||||
.associativeBinary(`operator`, map(\.sqlExpression))
|
||||
}
|
||||
@@ -1871,7 +1926,7 @@ extension Sequence where Element == any SQLSpecificExpressible {
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```
|
||||
/// ```swift
|
||||
/// // SELECT * FROM player
|
||||
/// // WHERE (registered
|
||||
/// // AND (score >= 1000)
|
||||
@@ -1884,13 +1939,8 @@ extension Sequence where Element == any SQLSpecificExpressible {
|
||||
/// ```
|
||||
///
|
||||
/// When the sequence is empty, `joined(operator:)` returns the neutral
|
||||
/// value of the operator. It is:
|
||||
///
|
||||
/// - `0` for ``SQLExpression/AssociativeBinaryOperator/add``
|
||||
/// - `1` for ``SQLExpression/AssociativeBinaryOperator/multiply``
|
||||
/// - `false` for ``SQLExpression/AssociativeBinaryOperator/or``
|
||||
/// - `true` for ``SQLExpression/AssociativeBinaryOperator/and``
|
||||
/// - `""` for ``SQLExpression/AssociativeBinaryOperator/concat``
|
||||
/// value of the operator. See
|
||||
/// ``SQLExpression/AssociativeBinaryOperator`` for more information.
|
||||
public func joined(operator: SQLExpression.AssociativeBinaryOperator) -> SQLExpression {
|
||||
.associativeBinary(`operator`, map(\.sqlExpression))
|
||||
}
|
||||
|
||||
@@ -1,145 +0,0 @@
|
||||
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,21 +172,15 @@ class StatementArgumentsSink {
|
||||
private(set) var arguments: StatementArguments
|
||||
private let rawSQL: Bool
|
||||
|
||||
/// 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)
|
||||
/// A sink which does not accept any arguments.
|
||||
static let forRawSQL = StatementArgumentsSink(rawSQL: true)
|
||||
|
||||
private init(rawSQL: Bool) {
|
||||
self.arguments = []
|
||||
self.rawSQL = rawSQL
|
||||
}
|
||||
|
||||
/// A sink which turns all argument values into `?` SQL parameters.
|
||||
///
|
||||
/// The `"WHERE name = \("O'Brien")"` SQL literal is turned into the
|
||||
/// `WHERE name = ?` SQL.
|
||||
/// A sink which accepts arguments
|
||||
convenience init() {
|
||||
self.init(rawSQL: false)
|
||||
}
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -566,8 +566,8 @@ private struct SQLQualifiedRelation {
|
||||
/// The full selection, including selection of joined relations
|
||||
var selectionPromise: DatabasePromise<[SQLSelection]> {
|
||||
DatabasePromise { db in
|
||||
let selection = try sourceSelectionPromise.resolve(db)
|
||||
return try joins.values.reduce(into: selection) { selection, join in
|
||||
let selection = try self.sourceSelectionPromise.resolve(db)
|
||||
return try self.joins.values.reduce(into: selection) { selection, join in
|
||||
let joinedSelection = try join.relation.selectionPromise.resolve(db)
|
||||
selection.append(contentsOf: joinedSelection)
|
||||
}
|
||||
|
||||
@@ -1,84 +0,0 @@
|
||||
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))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,476 +0,0 @@
|
||||
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,15 +38,6 @@ 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 ...
|
||||
|
||||
@@ -1,567 +0,0 @@
|
||||
/// 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,651 +0,0 @@
|
||||
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)
|
||||
}
|
||||
@@ -1,106 +0,0 @@
|
||||
/// 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)
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
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: "_"))"
|
||||
}
|
||||
}
|
||||
@@ -1,163 +0,0 @@
|
||||
/// 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
@@ -190,7 +190,3 @@ extension NSLocking {
|
||||
sideEffect?()
|
||||
}
|
||||
}
|
||||
|
||||
#if !canImport(ObjectiveC)
|
||||
@inlinable func autoreleasepool<Result>(invoking body: () throws -> Result) rethrows -> Result { try body() }
|
||||
#endif
|
||||
@@ -69,7 +69,6 @@
|
||||
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 */; };
|
||||
@@ -201,7 +200,6 @@
|
||||
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 */; };
|
||||
@@ -296,14 +294,6 @@
|
||||
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 */; };
|
||||
@@ -513,7 +503,6 @@
|
||||
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>"; };
|
||||
@@ -656,7 +645,6 @@
|
||||
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>"; };
|
||||
@@ -802,14 +790,6 @@
|
||||
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>"; };
|
||||
@@ -1047,7 +1027,6 @@
|
||||
56012B682573FAE600B4925B /* CommonTableExpressionTests.swift */,
|
||||
56EA63C7209C7F1E009715B8 /* DerivableRequestTests.swift */,
|
||||
56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */,
|
||||
568C3F7B2A5AB2D500A2309D /* ForeignKeyDefinitionTests.swift */,
|
||||
56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */,
|
||||
5698AC021D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift */,
|
||||
563EF45521631E3E007DAACD /* QueryInterfacePromiseTests.swift */,
|
||||
@@ -1196,12 +1175,8 @@
|
||||
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>";
|
||||
@@ -1209,11 +1184,6 @@
|
||||
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 */,
|
||||
);
|
||||
@@ -1887,7 +1857,6 @@
|
||||
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 */,
|
||||
@@ -1902,7 +1871,6 @@
|
||||
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 */,
|
||||
@@ -1954,7 +1922,6 @@
|
||||
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 */,
|
||||
@@ -1982,8 +1949,6 @@
|
||||
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 */,
|
||||
@@ -1997,7 +1962,6 @@
|
||||
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 */,
|
||||
@@ -2016,13 +1980,10 @@
|
||||
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 */,
|
||||
@@ -2263,7 +2224,6 @@
|
||||
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 */,
|
||||
|
||||
@@ -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_universal_xcframework
|
||||
test_archive: test_archive_GRDBOSX_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,51 +219,22 @@ test_SPM:
|
||||
$(SWIFT) build -c release
|
||||
set -o pipefail && $(SWIFT) test --parallel
|
||||
|
||||
test_universal_xcframework:
|
||||
test_archive_GRDBOSX_xcframework:
|
||||
rm -rf Tests/products
|
||||
mkdir Tests/products
|
||||
$(XCODEBUILD) archive \
|
||||
-project GRDB.xcodeproj \
|
||||
-scheme GRDB \
|
||||
-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 \
|
||||
-configuration Release \
|
||||
-destination "generic/platform=macOS" \
|
||||
OTHER_SWIFT_FLAGS=$(OTHER_SWIFT_FLAGS) \
|
||||
GCC_PREPROCESSOR_DEFINITIONS=$(GCC_PREPROCESSOR_DEFINITIONS) \
|
||||
-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" \
|
||||
-archivePath "$(PWD)/Tests/products/GRDB.xcarchive" \
|
||||
SKIP_INSTALL=NO \
|
||||
BUILD_LIBRARY_FOR_DISTRIBUTION=YES
|
||||
$(XCODEBUILD) -create-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'
|
||||
-framework '$(PWD)/Tests/products/GRDB.xcarchive/Products/Library/Frameworks/GRDB.framework' \
|
||||
-output '$(PWD)/Tests/products/GRDB.xcframework'
|
||||
|
||||
test_install_manual:
|
||||
$(XCODEBUILD) \
|
||||
|
||||
@@ -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**: September 1, 2023 • [version 6.18.0](https://github.com/groue/GRDB.swift/tree/v6.18.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md)
|
||||
**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)
|
||||
|
||||
**Requirements**: iOS 11.0+ / macOS 10.13+ / tvOS 11.0+ / watchOS 4.0+ • SQLite 3.19.3+ • Swift 5.7+ / Xcode 14+
|
||||
|
||||
|
||||
+1
-1
Submodule SQLiteCustom/src updated: 59f4dc65f0...95bfe16bb8.
@@ -57,13 +57,11 @@ opt_in_rules:
|
||||
- pattern_matching_keywords
|
||||
- prohibited_super_call
|
||||
- reduce_into
|
||||
- redundant_self_in_closure
|
||||
- redundant_type_annotation
|
||||
- shorthand_optional_binding
|
||||
- sorted_first_last
|
||||
- sorted_imports
|
||||
- toggle_bool
|
||||
- unhandled_throwing_task
|
||||
- vertical_parameter_alignment_on_call
|
||||
- yoda_condition
|
||||
|
||||
|
||||
+1
-1
@@ -15,7 +15,7 @@
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>FMWK</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>6.18.0</string>
|
||||
<string>6.15.1</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
|
||||
@@ -445,8 +445,6 @@
|
||||
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 */; };
|
||||
@@ -681,7 +679,6 @@
|
||||
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>"; };
|
||||
@@ -880,7 +877,6 @@
|
||||
56419CB724A54055004967E1 /* FetchRequestTests.swift */,
|
||||
56419D5B24A54061004967E1 /* FilterCursorTests.swift */,
|
||||
56419D4B24A54060004967E1 /* FlattenCursorTests.swift */,
|
||||
568C3F7E2A5AB36900A2309D /* ForeignKeyDefinitionTests.swift */,
|
||||
56419CF124A54059004967E1 /* ForeignKeyInfoTests.swift */,
|
||||
56419D2E24A5405E004967E1 /* FoundationDataTests.swift */,
|
||||
56419D6624A54062004967E1 /* FoundationDateComponentsTests.swift */,
|
||||
@@ -1213,7 +1209,6 @@
|
||||
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 */,
|
||||
@@ -1439,7 +1434,6 @@
|
||||
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 */,
|
||||
|
||||
@@ -17,9 +17,6 @@ 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,22 +447,6 @@
|
||||
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 */; };
|
||||
@@ -698,14 +682,6 @@
|
||||
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>"; };
|
||||
@@ -835,17 +811,14 @@
|
||||
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 */,
|
||||
@@ -853,7 +826,6 @@
|
||||
56419F9D24A5409D004967E1 /* DatabaseAfterNextTransactionCommitTests.swift */,
|
||||
56419F8A24A5409C004967E1 /* DatabaseAggregateTests.swift */,
|
||||
56419FBB24A540A0004967E1 /* DatabaseCollationTests.swift */,
|
||||
568C3F852A5AB3A800A2309D /* DatabaseColumnEncodingStrategyTests.swift */,
|
||||
56419F7024A5409A004967E1 /* DatabaseConfigurationTests.swift */,
|
||||
56419F2324A54095004967E1 /* DatabaseCursorTests.swift */,
|
||||
56419FBE24A540A0004967E1 /* DatabaseDateDecodingStrategyTests.swift */,
|
||||
@@ -881,7 +853,6 @@
|
||||
56419F0524A54093004967E1 /* DatabaseRegionObservationTests.swift */,
|
||||
56419F0424A54093004967E1 /* DatabaseRegionTests.swift */,
|
||||
56419F0D24A54093004967E1 /* DatabaseSavepointTests.swift */,
|
||||
568C3F892A5AB3A800A2309D /* DatabaseSnapshotPoolTests.swift */,
|
||||
56419FB424A5409F004967E1 /* DatabaseSnapshotTests.swift */,
|
||||
56419F1D24A54094004967E1 /* DatabaseSuspensionTests.swift */,
|
||||
56419F7324A5409A004967E1 /* DatabaseTests.swift */,
|
||||
@@ -910,12 +881,10 @@
|
||||
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 */,
|
||||
@@ -962,7 +931,6 @@
|
||||
56419F0724A54093004967E1 /* Record+QueryInterfaceRequestTests.swift */,
|
||||
56419F2124A54094004967E1 /* RecordEditedTests.swift */,
|
||||
56419F4824A54097004967E1 /* RecordInitializersTests.swift */,
|
||||
568C3F8A2A5AB3A800A2309D /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift */,
|
||||
56419F0C24A54093004967E1 /* RecordMinimalPrimaryKeyRowIDTests.swift */,
|
||||
56419F6124A54099004967E1 /* RecordMinimalPrimaryKeySingleTests.swift */,
|
||||
56419F5124A54098004967E1 /* RecordPersistenceConflictPolicy.swift */,
|
||||
@@ -1235,7 +1203,6 @@
|
||||
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 */,
|
||||
@@ -1245,11 +1212,9 @@
|
||||
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 */,
|
||||
@@ -1299,17 +1264,14 @@
|
||||
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 */,
|
||||
@@ -1364,7 +1326,6 @@
|
||||
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 */,
|
||||
@@ -1391,7 +1352,6 @@
|
||||
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 */,
|
||||
@@ -1468,7 +1428,6 @@
|
||||
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 */,
|
||||
@@ -1478,11 +1437,9 @@
|
||||
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 */,
|
||||
@@ -1532,17 +1489,14 @@
|
||||
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 */,
|
||||
@@ -1597,7 +1551,6 @@
|
||||
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 */,
|
||||
@@ -1624,7 +1577,6 @@
|
||||
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 */,
|
||||
|
||||
@@ -17,9 +17,6 @@ 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.belongsTo("team")
|
||||
t.column("teamId", .integer).references("team")
|
||||
t.column("name", .text)
|
||||
t.column("score", .integer)
|
||||
}
|
||||
try db.create(table: "award") { t in
|
||||
t.primaryKey("customPrimaryKey", .integer)
|
||||
t.belongsTo("team")
|
||||
t.column("teamId", .integer).references("team")
|
||||
t.column("name", .text)
|
||||
}
|
||||
|
||||
|
||||
@@ -55,7 +55,7 @@ class AssociationBelongsToDecodableRecordTests: GRDBTestCase {
|
||||
}
|
||||
try db.create(table: "players") { t in
|
||||
t.primaryKey("id", .integer)
|
||||
t.belongsTo("team")
|
||||
t.column("teamId", .integer).references("teams")
|
||||
t.column("name", .text)
|
||||
}
|
||||
|
||||
|
||||
@@ -57,7 +57,7 @@ class AssociationBelongsToFetchableRecordTests: GRDBTestCase {
|
||||
}
|
||||
try db.create(table: "players") { t in
|
||||
t.primaryKey("id", .integer)
|
||||
t.belongsTo("team")
|
||||
t.column("teamId", .integer).references("teams")
|
||||
t.column("name", .text)
|
||||
}
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ class AssociationBelongsToRowScopeTests: GRDBTestCase {
|
||||
}
|
||||
try db.create(table: "players") { t in
|
||||
t.primaryKey("id", .integer)
|
||||
t.belongsTo("team")
|
||||
t.column("teamId", .integer).references("teams")
|
||||
t.column("name", .text)
|
||||
}
|
||||
|
||||
|
||||
@@ -330,7 +330,7 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
|
||||
t.column("name", .text)
|
||||
}
|
||||
try db.create(table: "children") { t in
|
||||
t.belongsTo("parent")
|
||||
t.column("parentId", .integer).references("parents")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -546,8 +546,8 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
|
||||
t.column("name", .text)
|
||||
}
|
||||
try db.create(table: "children") { t in
|
||||
t.belongsTo("parent1", inTable: "parents")
|
||||
t.belongsTo("parent2", inTable: "parents")
|
||||
t.column("parent1Id", .integer).references("parents")
|
||||
t.column("parent2Id", .integer).references("parents")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1742,7 +1742,7 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
|
||||
}
|
||||
try db.create(table: "b") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("a")
|
||||
t.column("aId", .integer).references("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.belongsTo("parent")
|
||||
t.column("parentId", .integer).references("parents")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -36,7 +36,7 @@ class AssociationHasManyOrderingTests: GRDBTestCase {
|
||||
}
|
||||
try db.create(table: "player") { t in
|
||||
t.primaryKey("id", .integer)
|
||||
t.belongsTo("team").notNull()
|
||||
t.column("teamId", .integer).notNull().references("team")
|
||||
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.belongsTo("parent")
|
||||
t.column("parentId", .integer).references("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.belongsTo("parent")
|
||||
t.column("parentId", .integer).references("parents")
|
||||
}
|
||||
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.belongsTo("parent")
|
||||
t.column("parentId", .integer).references("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.belongsTo("parent")
|
||||
t.column("parentId", .integer).references("parents")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -346,8 +346,8 @@ class AssociationHasManySQLTests: GRDBTestCase {
|
||||
t.primaryKey("id", .integer)
|
||||
}
|
||||
try db.create(table: "children") { t in
|
||||
t.belongsTo("parent1", inTable: "parents")
|
||||
t.belongsTo("parent2", inTable: "parents")
|
||||
t.column("parent1Id", .integer).references("parents")
|
||||
t.column("parent2Id", .integer).references("parents")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1074,10 +1074,10 @@ class AssociationHasManySQLTests: GRDBTestCase {
|
||||
}
|
||||
try db.create(table: "child") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("parent")
|
||||
t.column("parentId", .integer).references("parent")
|
||||
}
|
||||
try db.create(table: "toy") { t in
|
||||
t.belongsTo("child")
|
||||
t.column("childId", .integer).references("child")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -40,8 +40,8 @@ class AssociationHasManyThroughOrderingTests: GRDBTestCase {
|
||||
t.column("name", .text).notNull()
|
||||
}
|
||||
try db.create(table: "playerRole") { t in
|
||||
t.belongsTo("team").notNull()
|
||||
t.belongsTo("player").notNull()
|
||||
t.column("teamId", .integer).notNull().references("team")
|
||||
t.column("playerId", .integer).notNull().references("player")
|
||||
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.belongsTo("child")
|
||||
t.column("childId").references("child")
|
||||
}
|
||||
try db.create(table: "grandChild") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("child")
|
||||
t.column("childId").references("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.belongsTo("child")
|
||||
t.column("childId").references("children")
|
||||
}
|
||||
try db.create(table: "grandChildren") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("child")
|
||||
t.column("childId").references("children")
|
||||
}
|
||||
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.belongsTo("child")
|
||||
t.column("childId").references("children")
|
||||
}
|
||||
try db.create(table: "grandChildren") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("child")
|
||||
t.column("childId").references("children")
|
||||
}
|
||||
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.belongsTo("parent")
|
||||
t.belongsTo("grandChild")
|
||||
t.column("parentId").references("parent")
|
||||
t.column("grandChildId").references("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.belongsTo("parent")
|
||||
t.belongsTo("grandChild")
|
||||
t.column("parentId").references("parents")
|
||||
t.column("grandChildId").references("grandChildren")
|
||||
}
|
||||
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.belongsTo("parent")
|
||||
t.belongsTo("grandChild")
|
||||
t.column("parentId").references("parent")
|
||||
t.column("grandChildId").references("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.belongsTo("b")
|
||||
t.column("bId").references("b")
|
||||
}
|
||||
try db.create(table: "c") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("b")
|
||||
t.column("bId").references("b")
|
||||
}
|
||||
|
||||
try testHasManyWithTwoSteps(
|
||||
@@ -66,11 +66,11 @@ class AssociationHasManyThroughSQLTests: GRDBTestCase {
|
||||
}
|
||||
try db.create(table: "b") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("a")
|
||||
t.column("aId").references("a")
|
||||
}
|
||||
try db.create(table: "c") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("b")
|
||||
t.column("bId").references("b")
|
||||
}
|
||||
|
||||
try testHasManyWithTwoSteps(
|
||||
@@ -109,8 +109,8 @@ class AssociationHasManyThroughSQLTests: GRDBTestCase {
|
||||
}
|
||||
try db.create(table: "b") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("c")
|
||||
t.belongsTo("a")
|
||||
t.column("cId").references("c")
|
||||
t.column("aId").references("a")
|
||||
}
|
||||
|
||||
try testHasManyWithTwoSteps(
|
||||
@@ -146,11 +146,11 @@ class AssociationHasManyThroughSQLTests: GRDBTestCase {
|
||||
}
|
||||
try db.create(table: "b") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("a")
|
||||
t.column("aId").references("a")
|
||||
}
|
||||
try db.create(table: "c") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("b")
|
||||
t.column("bId").references("b")
|
||||
}
|
||||
|
||||
try testHasManyWithTwoSteps(
|
||||
@@ -334,13 +334,13 @@ class AssociationHasManyThroughSQLTests: GRDBTestCase {
|
||||
}
|
||||
try db.create(table: "child") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("parent")
|
||||
t.column("parentId", .integer).references("parent")
|
||||
}
|
||||
try db.create(table: "toy") { t in
|
||||
t.belongsTo("child")
|
||||
t.column("childId", .integer).references("child")
|
||||
}
|
||||
try db.create(table: "pet") { t in
|
||||
t.belongsTo("child")
|
||||
t.column("childId", .integer).references("child")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -462,15 +462,15 @@ class AssociationHasManyThroughSQLTests: GRDBTestCase {
|
||||
}
|
||||
try db.create(table: "b") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("a")
|
||||
t.column("aId").references("a")
|
||||
}
|
||||
try db.create(table: "c") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("b")
|
||||
t.column("bId").references("b")
|
||||
}
|
||||
try db.create(table: "d") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("c")
|
||||
t.column("cId").references("c")
|
||||
}
|
||||
|
||||
try testHasManyWithThreeSteps(
|
||||
@@ -521,15 +521,15 @@ class AssociationHasManyThroughSQLTests: GRDBTestCase {
|
||||
}
|
||||
try db.create(table: "c") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("b")
|
||||
t.column("bId").references("b")
|
||||
}
|
||||
try db.create(table: "d") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("c")
|
||||
t.column("cId").references("c")
|
||||
}
|
||||
try db.create(table: "a") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("b")
|
||||
t.column("bId").references("b")
|
||||
}
|
||||
|
||||
try testHasManyWithThreeSteps(
|
||||
@@ -581,12 +581,12 @@ class AssociationHasManyThroughSQLTests: GRDBTestCase {
|
||||
}
|
||||
try db.create(table: "b") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("a")
|
||||
t.column("aId").references("a")
|
||||
}
|
||||
try db.create(table: "c") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("b")
|
||||
t.belongsTo("d")
|
||||
t.column("bId").references("b")
|
||||
t.column("dId").references("d")
|
||||
}
|
||||
|
||||
try testHasManyWithThreeSteps(
|
||||
|
||||
@@ -189,7 +189,7 @@ class AssociationHasOneSQLTests: GRDBTestCase {
|
||||
t.primaryKey("id", .integer)
|
||||
}
|
||||
try db.create(table: "children") { t in
|
||||
t.belongsTo("parent")
|
||||
t.column("parentId", .integer).references("parents")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -299,8 +299,8 @@ class AssociationHasOneSQLTests: GRDBTestCase {
|
||||
t.primaryKey("id", .integer)
|
||||
}
|
||||
try db.create(table: "children") { t in
|
||||
t.belongsTo("parent1", inTable: "parents")
|
||||
t.belongsTo("parent2", inTable: "parents")
|
||||
t.column("parent1Id", .integer).references("parents")
|
||||
t.column("parent2Id", .integer).references("parents")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -49,12 +49,12 @@ class AssociationHasOneThroughDecodableRecordTests: GRDBTestCase {
|
||||
}
|
||||
try db.create(table: "b") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("c")
|
||||
t.column("cId").references("c")
|
||||
t.column("name", .text)
|
||||
}
|
||||
try db.create(table: "a") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("b")
|
||||
t.column("bId").references("b")
|
||||
t.column("name", .text)
|
||||
}
|
||||
|
||||
|
||||
@@ -86,12 +86,12 @@ class AssociationHasOneThroughFetchableRecordTests: GRDBTestCase {
|
||||
}
|
||||
try db.create(table: "b") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("c")
|
||||
t.column("cId").references("c")
|
||||
t.column("name", .text)
|
||||
}
|
||||
try db.create(table: "a") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("b")
|
||||
t.column("bId").references("b")
|
||||
t.column("name", .text)
|
||||
}
|
||||
|
||||
|
||||
@@ -35,12 +35,12 @@ class AssociationHasOneThroughRowscopeTests: GRDBTestCase {
|
||||
}
|
||||
try db.create(table: "b") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("c")
|
||||
t.column("cId").references("c")
|
||||
t.column("name", .text)
|
||||
}
|
||||
try db.create(table: "a") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("b")
|
||||
t.column("bId").references("b")
|
||||
t.column("name", .text)
|
||||
}
|
||||
|
||||
|
||||
@@ -38,11 +38,11 @@ class AssociationHasOneThroughSQLDerivationTests: GRDBTestCase {
|
||||
}
|
||||
try db.create(table: "b") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("c")
|
||||
t.column("cId").references("c")
|
||||
}
|
||||
try db.create(table: "a") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("b")
|
||||
t.column("bId").references("b")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,11 +28,11 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase {
|
||||
}
|
||||
try db.create(table: "b") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("c")
|
||||
t.column("cId").references("c")
|
||||
}
|
||||
try db.create(table: "a") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("b")
|
||||
t.column("bId").references("b")
|
||||
}
|
||||
|
||||
try testHasOneWithTwoSteps(
|
||||
@@ -68,11 +68,11 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase {
|
||||
}
|
||||
try db.create(table: "a") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("b")
|
||||
t.column("bId").references("b")
|
||||
}
|
||||
try db.create(table: "c") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("b")
|
||||
t.column("bId").references("b")
|
||||
}
|
||||
|
||||
try testHasOneWithTwoSteps(
|
||||
@@ -111,8 +111,8 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase {
|
||||
}
|
||||
try db.create(table: "b") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("c")
|
||||
t.belongsTo("a")
|
||||
t.column("cId").references("c")
|
||||
t.column("aId").references("a")
|
||||
}
|
||||
|
||||
try testHasOneWithTwoSteps(
|
||||
@@ -148,11 +148,11 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase {
|
||||
}
|
||||
try db.create(table: "b") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("a")
|
||||
t.column("aId").references("a")
|
||||
}
|
||||
try db.create(table: "c") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("b")
|
||||
t.column("bId").references("b")
|
||||
}
|
||||
|
||||
try testHasOneWithTwoSteps(
|
||||
@@ -437,15 +437,15 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase {
|
||||
}
|
||||
try db.create(table: "c") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("d")
|
||||
t.column("dId").references("d")
|
||||
}
|
||||
try db.create(table: "b") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("c")
|
||||
t.column("cId").references("c")
|
||||
}
|
||||
try db.create(table: "a") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("b")
|
||||
t.column("bId").references("b")
|
||||
}
|
||||
|
||||
try testHasOneWithThreeSteps(
|
||||
@@ -494,15 +494,15 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase {
|
||||
}
|
||||
try db.create(table: "d") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("c")
|
||||
t.column("cId").references("c")
|
||||
}
|
||||
try db.create(table: "b") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("c")
|
||||
t.column("cId").references("c")
|
||||
}
|
||||
try db.create(table: "a") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("b")
|
||||
t.column("bId").references("b")
|
||||
}
|
||||
|
||||
try testHasOneWithThreeSteps(
|
||||
@@ -554,12 +554,12 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase {
|
||||
}
|
||||
try db.create(table: "c") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("b")
|
||||
t.belongsTo("d")
|
||||
t.column("bId").references("b")
|
||||
t.column("dId").references("d")
|
||||
}
|
||||
try db.create(table: "a") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("b")
|
||||
t.column("bId").references("b")
|
||||
}
|
||||
|
||||
try testHasOneWithThreeSteps(
|
||||
@@ -608,15 +608,15 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase {
|
||||
}
|
||||
try db.create(table: "c") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("b")
|
||||
t.column("bId").references("b")
|
||||
}
|
||||
try db.create(table: "d") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("c")
|
||||
t.column("cId").references("c")
|
||||
}
|
||||
try db.create(table: "a") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("b")
|
||||
t.column("bId").references("b")
|
||||
}
|
||||
|
||||
try testHasOneWithThreeSteps(
|
||||
@@ -668,12 +668,12 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase {
|
||||
}
|
||||
try db.create(table: "c") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("d")
|
||||
t.column("dId").references("d")
|
||||
}
|
||||
try db.create(table: "b") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("a")
|
||||
t.belongsTo("c")
|
||||
t.column("aId").references("a")
|
||||
t.column("cId").references("c")
|
||||
}
|
||||
|
||||
try testHasOneWithThreeSteps(
|
||||
@@ -725,12 +725,12 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase {
|
||||
}
|
||||
try db.create(table: "d") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("c")
|
||||
t.column("cId").references("c")
|
||||
}
|
||||
try db.create(table: "b") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("a")
|
||||
t.belongsTo("c")
|
||||
t.column("aId").references("a")
|
||||
t.column("cId").references("c")
|
||||
}
|
||||
|
||||
try testHasOneWithThreeSteps(
|
||||
@@ -782,12 +782,12 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase {
|
||||
}
|
||||
try db.create(table: "b") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("a")
|
||||
t.column("aId").references("a")
|
||||
}
|
||||
try db.create(table: "c") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("b")
|
||||
t.belongsTo("d")
|
||||
t.column("bId").references("b")
|
||||
t.column("dId").references("d")
|
||||
}
|
||||
|
||||
try testHasOneWithThreeSteps(
|
||||
@@ -836,15 +836,15 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase {
|
||||
}
|
||||
try db.create(table: "b") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("a")
|
||||
t.column("aId").references("a")
|
||||
}
|
||||
try db.create(table: "c") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("b")
|
||||
t.column("bId").references("b")
|
||||
}
|
||||
try db.create(table: "d") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("c")
|
||||
t.column("cId").references("c")
|
||||
}
|
||||
|
||||
try testHasOneWithThreeSteps(
|
||||
@@ -1724,19 +1724,19 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase {
|
||||
}
|
||||
try db.create(table: "d") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("e")
|
||||
t.column("eId").references("e")
|
||||
}
|
||||
try db.create(table: "c") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("d")
|
||||
t.column("dId").references("d")
|
||||
}
|
||||
try db.create(table: "b") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("c")
|
||||
t.column("cId").references("c")
|
||||
}
|
||||
try db.create(table: "a") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("b")
|
||||
t.column("bId").references("b")
|
||||
}
|
||||
|
||||
let associations = [
|
||||
|
||||
@@ -1350,7 +1350,9 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
|
||||
try dbQueue.write { db in
|
||||
try db.create(table: "employee") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("manager", inTable: "employee", onDelete: .restrict)
|
||||
t.column("managerId", .integer)
|
||||
.indexed()
|
||||
.references("employee", onDelete: .restrict)
|
||||
t.column("name", .text)
|
||||
}
|
||||
try db.execute(sql: """
|
||||
|
||||
@@ -19,96 +19,77 @@ 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, 12)
|
||||
XCTAssertEqual(columns.count, 11)
|
||||
|
||||
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.belongsTo("team")
|
||||
t.column("teamId", .integer).references("team")
|
||||
}
|
||||
try db.create(table: "award") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("player")
|
||||
t.column("playerId", .integer).references("player")
|
||||
}
|
||||
struct Team: TableRecord { }
|
||||
struct Player: TableRecord {
|
||||
|
||||
@@ -52,7 +52,7 @@ private class UserDatabaseValueConvertible2 : DatabaseValueConvertible {
|
||||
|
||||
#if SQLITE_ENABLE_FTS5
|
||||
private class UserFTS5Tokenizer : FTS5Tokenizer {
|
||||
func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer<CChar>?, nText: CInt, tokenCallback: @escaping FTS5TokenCallback) -> CInt { preconditionFailure() }
|
||||
func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer<Int8>?, nText: CInt, tokenCallback: @escaping FTS5TokenCallback) -> CInt { preconditionFailure() }
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -62,7 +62,7 @@ private class UserFTS5Tokenizer : FTS5Tokenizer {
|
||||
private class UserFTS5CustomTokenizer : FTS5CustomTokenizer {
|
||||
static let name: String = "UserFTS5CustomTokenizer"
|
||||
required init(db: Database, arguments: [String]) throws { preconditionFailure() }
|
||||
func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer<CChar>?, nText: CInt, tokenCallback: @escaping FTS5TokenCallback) -> CInt { preconditionFailure() }
|
||||
func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer<Int8>?, nText: CInt, tokenCallback: @escaping FTS5TokenCallback) -> CInt { preconditionFailure() }
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
@@ -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 = .none
|
||||
formatter.timeStyle = .medium
|
||||
return formatter
|
||||
}())
|
||||
}
|
||||
@@ -199,10 +199,10 @@ extension DatabaseDateEncodingStrategyTests {
|
||||
try testNullEncoding(strategy: StrategyFormatted.self)
|
||||
|
||||
for (date, value) in zip(testedDates, [
|
||||
"Saturday, December 20, 1969",
|
||||
"Friday, January 2, 1970",
|
||||
"Monday, January 1, 2001",
|
||||
"Tuesday, January 2, 2001",
|
||||
"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",
|
||||
]) { try test(strategy: StrategyFormatted.self, encodesDate: date, as: value) }
|
||||
}
|
||||
}
|
||||
|
||||
Loaded 100 of 116 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user