Compare commits

...
28 Commits
Author SHA1 Message Date
Gwendal Roué b9d0dae5ac v2.0.2 2017-10-05 19:55:13 +02:00
Gwendal Roué ab2a74285d Issue156.playground 2017-10-05 19:09:22 +02:00
Gwendal Roué e37ab72182 Fix compiler error 2017-10-05 15:55:20 +02:00
Gwendal Roué 891dec64a0 Cleanup fix for failing test for "DROP TABLE t" executed from a prepared statement. 2017-10-05 15:34:36 +02:00
Gwendal Roué 90086789c6 Fix failing test for "DROP TABLE t" executed from a prepared statement.
Refactor authorization and truncate optimization prevention around the StatementAuthorizer protocol.
2017-10-05 15:15:13 +02:00
Gwendal Roué 2cdcdb9cd6 Refactor Statement initializers 2017-10-05 14:01:12 +02:00
Gwendal Roué 9c6879bd97 Xcode 9 sometimes performs gratuitous changes to shared schemes 2017-10-05 13:56:38 +02:00
Gwendal Roué fc88acc782 Add failing test for "DROP TABLE t" executed from a prepared statement. 2017-10-05 13:55:51 +02:00
Gwendal Roué 1578dfe26b Cleanup 2017-10-05 13:50:31 +02:00
Gwendal Roué eb5e5a7069 WhyAdoptGRDB.md 2017-10-04 08:02:19 +02:00
Gwendal Roué b58cfefa13 Refactor database setup sample code so that database migrator can be tested 2017-10-03 08:40:44 +02:00
Gwendal Roué de4d395aea WhyAdoptGRDB.md 2017-10-01 06:10:19 +02:00
Gwendal Roué 7072bd9f36 WhyAdoptGRDB.md 2017-10-01 06:08:54 +02:00
Gwendal Roué 8e36bc64fd WhyAdoptGRDB.md 2017-10-01 05:55:35 +02:00
Gwendal Roué 4326a705f3 Typo 2017-09-30 22:05:17 +02:00
Gwendal Roué eb99e294ed Typo 2017-09-30 20:53:44 +02:00
Gwendal Roué 27acb2b967 WhyAdoptGRDB.md 2017-09-30 20:24:33 +02:00
Gwendal Roué 9cf5124a52 Documentation 2017-09-30 00:22:00 +02:00
Gwendal Roué d00282f077 Documentation 2017-09-28 06:47:19 +02:00
Gwendal Roué 2556bedcda Enhance versions table 2017-09-28 06:01:29 +02:00
Gwendal Roué a569acd12a Documentation 2017-09-26 19:25:47 +02:00
Gwendal Roué 5e6c462708 Documentation 2017-09-26 19:23:55 +02:00
Gwendal Roué 4e0900dffa Documentation 2017-09-26 19:21:52 +02:00
Gwendal Roué 5c61211522 Swift flags for enhancing compilation time (from @jessesquires' https://www.jessesquires.com/blog/measuring-compile-times-xcode9/) 2017-09-21 17:24:00 +02:00
Gwendal Roué 0747dc5cf6 Diff links 2017-09-17 12:04:32 +02:00
Gwendal Roué 85099c8ad6 v2.0.1 2017-09-17 11:44:31 +02:00
Gwendal Roué 72da91a8c7 Remove obsolete FAQ 2017-09-17 08:10:16 +02:00
Gwendal Roué 4aced858a8 Fix documentation typo 2017-09-17 08:04:13 +02:00
21 changed files with 829 additions and 335 deletions

No files matched your search

+20 -6
View File
@@ -1,9 +1,23 @@
Release Notes
=============
## 2.0.2
Released October 5, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v2.0.1...v2.0.2)
**Fixed**: `DROP TABLE` statements would not drop tables when run through a prepared statement.
## 2.0.1
Released September 17, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v2.0...v2.0.1)
**Fixed**: restored support for Swift Package Manager
## 2.0
Released September 16, 2017
Released September 16, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v1.3.0...v2.0)
**GRDB 2.0 brings support for Swift 4.** Notable changes are:
@@ -345,7 +359,7 @@ New features have been added in order to plug a few holes and support the [RxGRD
## 1.3.0
Released August 18, 2017
Released August 18, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v1.2.2...v1.3.0)
**New**
@@ -367,7 +381,7 @@ Released August 18, 2017
## 1.2.2
Released July 20, 2017
Released July 20, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v1.2.1...v1.2.2)
**Fixed**
@@ -376,7 +390,7 @@ Released July 20, 2017
## 1.2.1
Released July 19, 2017
Released July 19, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v1.2...v1.2.1)
**Fixed**
@@ -393,7 +407,7 @@ Released July 19, 2017
## 1.2
Released July 13, 2017
Released July 13, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v1.1...v1.2)
**New**
@@ -492,7 +506,7 @@ Released July 13, 2017
## 1.1
Released July 1, 2017
Released July 1, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v1.0...v1.1)
**New**
@@ -20,7 +20,7 @@
56B0360C1E8D9EBE003B6DA4 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 56B0360A1E8D9EBE003B6DA4 /* Main.storyboard */; };
56B0360E1E8D9EBE003B6DA4 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 56B0360D1E8D9EBE003B6DA4 /* Assets.xcassets */; };
56B036111E8D9EBE003B6DA4 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 56B0360F1E8D9EBE003B6DA4 /* LaunchScreen.storyboard */; };
56B0361B1E8D9F38003B6DA4 /* Database.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036191E8D9F38003B6DA4 /* Database.swift */; };
56B0361B1E8D9F38003B6DA4 /* AppDatabase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036191E8D9F38003B6DA4 /* AppDatabase.swift */; };
56B0361C1E8D9F38003B6DA4 /* Person.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361A1E8D9F38003B6DA4 /* Person.swift */; };
56B036221E8D9F4C003B6DA4 /* DemoViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361E1E8D9F4C003B6DA4 /* DemoViewController.swift */; };
56B036231E8D9F4C003B6DA4 /* PersonEditionViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361F1E8D9F4C003B6DA4 /* PersonEditionViewController.swift */; };
@@ -31,6 +31,13 @@
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
563BD2F01F8364C1006A5390 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 56439B501F4CA1DC0066043F;
remoteInfo = GRDBOSXPerformanceComparisonTests;
};
568E5FCD1E926430002582E0 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56B035FB1E8D9EBE003B6DA4 /* Project object */;
@@ -257,7 +264,7 @@
56B0360D1E8D9EBE003B6DA4 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
56B036101E8D9EBE003B6DA4 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
56B036121E8D9EBE003B6DA4 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
56B036191E8D9F38003B6DA4 /* Database.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Database.swift; sourceTree = "<group>"; };
56B036191E8D9F38003B6DA4 /* AppDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDatabase.swift; sourceTree = "<group>"; };
56B0361A1E8D9F38003B6DA4 /* Person.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Person.swift; sourceTree = "<group>"; };
56B0361E1E8D9F4C003B6DA4 /* DemoViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DemoViewController.swift; sourceTree = "<group>"; };
56B0361F1E8D9F4C003B6DA4 /* PersonEditionViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersonEditionViewController.swift; sourceTree = "<group>"; };
@@ -332,7 +339,7 @@
isa = PBXGroup;
children = (
56B036061E8D9EBE003B6DA4 /* AppDelegate.swift */,
56B036191E8D9F38003B6DA4 /* Database.swift */,
56B036191E8D9F38003B6DA4 /* AppDatabase.swift */,
56B0361A1E8D9F38003B6DA4 /* Person.swift */,
56B0361D1E8D9F3D003B6DA4 /* Controllers */,
56B0360A1E8D9EBE003B6DA4 /* Main.storyboard */,
@@ -360,6 +367,7 @@
56B0363B1E8D9F79003B6DA4 /* GRDB.framework */,
56B0363D1E8D9F79003B6DA4 /* GRDBOSXTests.xctest */,
56B0363F1E8D9F79003B6DA4 /* GRDBOSXPerformanceTests.xctest */,
563BD2F11F8364C1006A5390 /* GRDBOSXPerformanceComparisonTests.xctest */,
56B036411E8D9F79003B6DA4 /* GRDBOSXCrashTests.xctest */,
56B036431E8D9F79003B6DA4 /* GRDBCipher.framework */,
56B036451E8D9F79003B6DA4 /* GRDBCipherOSXTests.xctest */,
@@ -494,6 +502,13 @@
/* End PBXProject section */
/* Begin PBXReferenceProxy section */
563BD2F11F8364C1006A5390 /* GRDBOSXPerformanceComparisonTests.xctest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = GRDBOSXPerformanceComparisonTests.xctest;
remoteRef = 563BD2F01F8364C1006A5390 /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
56B0363B1E8D9F79003B6DA4 /* GRDB.framework */ = {
isa = PBXReferenceProxy;
fileType = wrapper.framework;
@@ -660,7 +675,7 @@
buildActionMask = 2147483647;
files = (
56B0361C1E8D9F38003B6DA4 /* Person.swift in Sources */,
56B0361B1E8D9F38003B6DA4 /* Database.swift in Sources */,
56B0361B1E8D9F38003B6DA4 /* AppDatabase.swift in Sources */,
56B036071E8D9EBE003B6DA4 /* AppDelegate.swift in Sources */,
56B036241E8D9F4C003B6DA4 /* PersonsViewController.swift in Sources */,
56B036231E8D9F4C003B6DA4 /* PersonEditionViewController.swift in Sources */,
@@ -0,0 +1,57 @@
import GRDB
/// A type responsible for initializing the application database.
///
/// See AppDelegate.setupDatabase()
struct AppDatabase {
/// Creates a fully initialized database at path
static func openDatabase(atPath path: String) throws -> DatabaseQueue {
// Connect to the database
// See https://github.com/groue/GRDB.swift/#database-connections
dbQueue = try DatabaseQueue(path: path)
// Use DatabaseMigrator to define the database schema
// See https://github.com/groue/GRDB.swift/#migrations
try migrator.migrate(dbQueue)
return dbQueue
}
/// The DatabaseMigrator that defines the database schema.
///
/// This migrator is exposed so that migrations can be tested.
// See https://github.com/groue/GRDB.swift/#migrations
static var migrator: DatabaseMigrator {
var migrator = DatabaseMigrator()
migrator.registerMigration("createPersons") { db in
// Create a table
// See https://github.com/groue/GRDB.swift#create-tables
try db.create(table: "persons") { t in
// An integer primary key auto-generates unique IDs
t.column("id", .integer).primaryKey()
// Sort person names in a localized case insensitive fashion by default
// See https://github.com/groue/GRDB.swift/#unicode
t.column("name", .text).notNull().collate(.localizedCaseInsensitiveCompare)
t.column("score", .integer).notNull()
}
}
migrator.registerMigration("fixtures") { db in
// Populate the persons table with random data
for _ in 0..<8 {
try Person(name: Person.randomName(), score: Person.randomScore()).insert(db)
}
}
// // Migrations for future application versions will be inserted here:
// migrator.registerMigration(...) { db in
// ...
// }
return migrator
}
}
@@ -1,4 +1,8 @@
import UIKit
import GRDB
// The shared database queue
var dbQueue: DatabaseQueue!
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
@@ -8,4 +12,14 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
try! setupDatabase(application)
return true
}
private func setupDatabase(_ application: UIApplication) throws {
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! as NSString
let databasePath = documentsPath.appendingPathComponent("db.sqlite")
dbQueue = try AppDatabase.openDatabase(atPath: databasePath)
// Be a nice iOS citizen, and don't consume too much memory
// See https://github.com/groue/GRDB.swift/#memory-management
dbQueue.setupMemoryManagement(in: application)
}
}
@@ -1,56 +0,0 @@
import GRDB
import UIKit
// The shared database queue
var dbQueue: DatabaseQueue!
func setupDatabase(_ application: UIApplication) throws {
// Connect to the database
// See https://github.com/groue/GRDB.swift/#database-connections
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! as NSString
let databasePath = documentsPath.appendingPathComponent("db.sqlite")
dbQueue = try DatabaseQueue(path: databasePath)
// Be a nice iOS citizen, and don't consume too much memory
// See https://github.com/groue/GRDB.swift/#memory-management
dbQueue.setupMemoryManagement(in: application)
// Use DatabaseMigrator to setup the database
// See https://github.com/groue/GRDB.swift/#migrations
var migrator = DatabaseMigrator()
migrator.registerMigration("createPersons") { db in
// Create a table
// See https://github.com/groue/GRDB.swift#create-tables
try db.create(table: "persons") { t in
// An integer primary key auto-generates unique IDs
t.column("id", .integer).primaryKey()
// Sort person names in a localized case insensitive fashion by default
// See https://github.com/groue/GRDB.swift/#unicode
t.column("name", .text).notNull().collate(.localizedCaseInsensitiveCompare)
t.column("score", .integer).notNull()
}
// Populate the persons table with random data
for _ in 0..<8 {
try Person(name: Person.randomName(), score: Person.randomScore()).insert(db)
}
}
// // Migrations for future application versions will be inserted here:
// migrator.registerMigration(...) { db in
// ...
// }
try migrator.migrate(dbQueue)
}
+1 -1
View File
@@ -15,7 +15,7 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
```sh
cd [GRDB directory]
git checkout v2.0
git checkout v2.0.2
git submodule update --init SQLiteCustom/src
````
+280
View File
@@ -0,0 +1,280 @@
Why Adopt GRDB?
===============
This document aims at exposing why GRDB could become your favorite database library.
We'll start with a few [core principles](#core-principles), so that you see where this library aims at. Then we'll see how GRDB [solves problems](#solving-problems) that developers often face when they use database libraries such as FMDB, FCModel, SQLite.swift, Core Data, or Realm.
## Core Principles
### It is generally easier to access a database through "record types".
This is because a database row is not an easy type to deal with, and will never be, compared to a regular model. `player.name` looks and feels more natural than `playerRow[nameColumn]`, doesn't it?
The reputation of "active records" and ORMs has been tarnished by the recent focus on immutability, memory safety, and functional idioms that comes with languages like Swift and Rust. Features of 1st-generation records such as auto-updating, uniquing, lazy loading of relations, etc. are now considered ill-advised, if not plain harmful because of the multi-threading headaches they cause.
Yet recent ORMs such as Rust's [Diesel] have shown that it is possible to build record types that behave as plain and simple values. GRDB belongs to this family.
### Raw SQL is sometimes the correct tool for the job.
Complex database queries sometimes need to be prototyped and debugged in an SQL shell. Once perfected, the process of translating this raw SQL query into calls to a query builder can be long and painful, with no guarantee of success. And the resulting code often lacks the legibility of the initial SQL. When this happens, the query builder is no longer useful: whoever wants to write raw SQL should always be welcome.
### The database file is the single source of truth.
Each Core Data's managed object context has its own version of the database. This can be useful when developing a macOS application full of inspector panels and nested undo stacks. But that's about it.
In the same vein, each application thread has its own version of a Realm database, with non trivial synchronization points.
Conversely, GRDB assumes that many apps want to use the database as a reliable and unambiguous storage.
### Applications developers have specific needs.
GRDB puts all bets on SQLite, and focuses on front-end GUI applications.
This means that dealing with servers, MySQL, or PostgreSQL is out of scope. GRDB is not an alternative to IBM's [Swift-Kuery], Vapor's [Fluent], or Perfect's [StORM].
Focusing on SQLite and applications has allowed GRDB to build features usually only found in company-sponsored libraries: migrations, changes tracking, database observation, multi-threading safety, table view animations, support for reactive streams...
Some will call GRDB "opinionated", or "bloated". Well, the bet of GRDB is that developers can take great profit from a library that provides efficient and community-tested solutions to existing problems. For example, one can not address the multithreading difficulties of Core Data or Realm without looking at database concurrency and records straight in the face.
Since you don't have to take my words for granted, we'll now see how GRDB actually solves common problems that developers face with other database libraries.
## Solving Problems
What is the purpose of the above principles, if not providing solutions to difficulties and limitations of other persistence libraries?
### Allow any Swift struct or class to become a database record
Most libraries that provide record types want you to subclass a root class: NSManagedObject, Realm.Object, FCModel.
The main problem with those root classes is that they are classes. You can't define records from plain Swift structs, and leverage all advantages of Swift value types: immutability, multi-threading safety, etc.
With GRDB, any type can become a database record. For example, let's start from this `Place` struct:
```swift
struct Place {
var id: Int64?
let title: String
let coordinate: CLLocationCoordinate2D
}
```
By adopting the [RowConvertible] protocol, places can be loaded from SQL requests:
```swift
extension Place: RowConvertible { ... }
let places = try Place.fetchAll(db, "SELECT * FROM places") // [Place]
```
Add the [TableMapping] protocol, and SQL requests are generated for you:
```swift
extension Place: TableMapping { ... }
let place = try Place.fetchOne(db, key: 1) // Place?
```
Add the [Persistable] protocol, and places know how to insert, update and delete themselves:
```swift
extension Place: Persistable { ... }
try place.delete(db)
```
Being a protocol-oriented library that welcomes immutable types, GRDB records are unlike records in other ORM libraries. Particularly, records do not auto-update, and records are not uniqued. We'll see below that the lack of those features can be replaced with database change notifications, with many advantages.
### Allow database records to cross threads
As soon as records are immutable values, they can safely be used from different threads. You no longer have to pass object ids or references between threads, as in Core Data or Realm:
```swift
if let player = try Player.fetchOne(db, key: 1) {
DispatchQueue.main.async {
nameField.text = player.name
}
}
```
### Replace auto-updating records with notifications of database changes
GRDB records are plain values, like other values in your application. They are not tied to the database. Sometimes you build them from scratch, and sometimes you fetch them:
```swift
let player = Player(name: "arthur", score: 1000)
let players = try Player.fetchAll(db)
```
**Fetched records behave just like an in-memory cache of the database content.** Your application is free to decide, on its own, how it should handle the lifetime of those cached values: by ignoring future database changes, by observing database changes and react accordingly, or in any way deemed relevant.
There are several ways to be notified of database changes. You can build on top of the low-level [TransactionObserver] protocol. Or you can use [FetchedRecordsController], which looks a lot like Core Data's NSFetchedResultsController, and is able to animate table and collection views. And don't forget [RxGRDB], a set of reactive extensions based on [RxSwift]:
```swift
Player.all().rx
.fetchAll(in: dbQueue)
.subscribe(onNext: { players: [Player] in
print("Players have changed")
})
```
No matter which observation technique you use, you have common guarantees:
First, notifications only come from database changes safely saved on disk. This is part of the "database as the single source of truth" core principle. You won't get notifications from unsaved changes or changes that have an opportunity to be rollbacked.
Next, you choose the dispatch queue on which notifications happen. It can be on the special "writer queue", which allows you to process changes before any other thread has any opportunity to perform further database modifications. But notifications can also happen on the queue of your choice (generally the main queue, by default, as in the example above). Of course, GRDB makes sure notifications happen in the same order as database transactions.
Finally, all changes are notified, no matter how they are performed: record methods, raw SQL statements, foreign key cascades, and even SQL triggers.
### Non-blocking database reads
GRDB ships with two ways to access databases, [database queues](https://github.com/groue/GRDB.swift/blob/master/README.md#database-queues) and [pools](https://github.com/groue/GRDB.swift/blob/master/README.md#database-pools).
Database queues look a lot like FMDB's [FMDatabaseQueue](https://github.com/ccgus/fmdb#using-fmdatabasequeue-and-thread-safety): they serialize database accesses in a serial dispatch queue. There is never more than one thread that is accessing the database. This means that a long running database transaction that happens in a background thread, such as the synchronization of your local database from a remote server, can block your UI. As long as the queue is busy, the main thread can't fetch the values it wants to display on screen.
[Database pools](https://github.com/groue/GRDB.swift/blob/master/README.md#database-pools) can lift these unwanted locks. With database pools, reads are generally non-blocking, unless the maximum number of concurrent reads has been reached (and this maximum number can be configured).
### Strong and clear multi-threading guarantees
I'd like to compare GRDB's handling of concurrency with other libraries. To be as clear as possible, we'll identity a few threats, or potential sources of bugs, and wonder if those are handled by the library, or left to the host application.
The more threats are handled by the application, the more skilled and careful a developer has to be in order to avoid them.
- **Concurrent writes**: Two threads want to write in the database as the same time. SQLite does not allow that.
- **Isolation troubles**: As two database queries run one after the other, a concurrent thread sneaks in and modifies the database in between. The two queries can thus perform inconsistent fetches or updates, unless they are properly isolated. Lack of isolation may display funny values on the screen, trigger a relational constraint error, or silently corrupt the database content.
- **Conflicts**: The same piece of data is both edited by the application user, and refreshed from a network operation. What will eventually be stored in the database? Can any conflict be noticed?
- **Blocked UI**: Can it happen that the UI is blocked because the main thread has to wait for a background thread to release a lock on the database?
| Library | Concurrent Writes | Isolation Trouble | Conflicts | Blocked UI |
| ------- | ----------------- | ----------------- | --------- | ---------- |
| FMDB's FMDatabase | Handled by the application | Handled by the application | Handled by the application | Handled by the application |
| FMDB's FMDatabaseQueue | :white_check_mark: | :white_check_mark: | Handled by the application | UI is blocked |
| SQLite.swift | :white_check_mark: | Handled by the application | Handled by the application | Handled by the application |
| Core Data | Handled by the application, because of the constant threat of conflict errors | :white_check_mark: | Handled by the application, and it is very difficult because of the subtleties of Core Data's conflict policies | Handled by the application |
| GRDB's DatabaseQueue | :white_check_mark: | :white_check_mark: | Handled by the application | UI is blocked |
| GRDB's DatabasePool | :white_check_mark: | :white_check_mark: | Handled by the application | :white_check_mark: (as long as the maximum number of readers has not been reached) |
I had to omit Realm and FCModel from the list, because I don't know them well enough. Yet I'd bet that Realm shares some behaviors with Core Data, and FCModel shares some behaviors with FMDatabaseQueue.
We can see that the threat of conflicts is *always* left to the application. Core Data provides conflict policies, but no one can pretend that they are easy to use or test. This is an argument for leaving the application 100% responsible for conflict handling, in hope that simple ones can be handled in a simple way. A weaker way to say this is that conflict handling at the library level can wait :sweat_smile:.
Finally, raw FMDatabase, SQLite.swift, and Core Data are the hardest tools, and you'd better be a very skilled developer in order to use them properly.
For further information about GRDB concurrency, check its detailed [Concurrency Guide].
### Never pay for using raw SQL
SQL is a weird language. Born in the 70s, easy to [misuse](https://xkcd.com/327/), feared by some developers, despised by others, and yet wonderfully concise and powerful.
GRDB provides high-level record methods that generate SQL for you:
```swift
// SELECT * FROM players ORDER BY score DESC LIMIT 10
let bestPlayers: [Player] = try Player
.order(scoreColumn.desc)
.limit(10)
.fetchAll(db)
// SELECT MAX(score) FROM players
let maximumScore: Int? = try Player
.select(max(scoreColumn))
.asRequestOf(Int.self)
.fetchOne(db)
// SELECT COUNT(*) FROM players WHERE score = ?
let exAequoCount: Int = try Player
.filter(scoreColumn == maximumScore)
.fetchCount(db)
```
But you can *always* switch to SQL when you want to:
```swift
let bestPlayers: [Player] = try Player.fetchAll(db, """
SELECT * FROM players ORDER BY score DESC LIMIT 10
""")
let maximumScore: Int? = try Int.fetchOne(db, """
SELECT MAX(score) FROM players
""")
let exAequoCount: Int? = try Int.fetchOne(db, """
SELECT COUNT(*) FROM players WHERE score = ?
""", arguments: [maximumScore])
```
SQL is also welcome in high-level database observation tools like [FetchedRecordsController] and [RxGRDB]:
```swift
SQLRequest("SELECT * FROM players ORDER BY score DESC LIMIT 10")
.asRequest(of: Player.self)
.rx
.fetchAll(in: dbQueue)
.subscribe(onNext: { players: [Player] in
print("Best 10 players have changed")
})
```
You can of course deal with raw database rows, and fetch [lazy cursors](https://github.com/groue/GRDB.swift/blob/master/README.md#cursors) instead of arrays:
```swift
let rows = try Row.fetchCursor(db, "SELECT * FROM players")
while let row = try rows.next() {
let id: Int64 = row["id"]
let name: String = row["name"]
let score: Int = row["score"]
}
```
When you feel like your code clarity would be enhanced by hiding your custom SQL in a dedicated method, you can build [custom requests](https://github.com/groue/GRDB.swift/blob/master/README.md#custom-requests):
```swift
extension Player {
static func customRequest(...) -> AnyTypedRequest<Player> {
return SQLRequest("""
SELECT ...
""", arguments: ...)
.asRequestOf(Player.self)
}
}
let players = Player.customRequest(...).fetchAll(db)
```
---
If this little tour of GRDB has convinced you, the real trip starts here: [GRDB].
And if you happen to maintain an Objective-C application that uses FMDB, checkout [GRDBObjc]. It provides FMDB-compatible bindings to GRDB, so that you can inject sweet drops of Swift into your app, at your own pace, and at minimal cost.
Happy GRDB! :gift:
[Concurrency Guide]: https://github.com/groue/GRDB.swift/blob/master/README.md#concurrency
[Core Data]: https://developer.apple.com/documentation/coredata
[DatabasePool]: https://github.com/groue/GRDB.swift/blob/master/README.md#database-pools
[Diesel]: http://diesel.rs
[FCModel]: https://github.com/marcoarment/FCModel
[FetchedRecordsController]: https://github.com/groue/GRDB.swift/blob/master/README.md#fetchedrecordscontroller
[Fluent]: https://github.com/vapor/fluent
[FMDB]: http://github.com/ccgus/fmdb
[GRDB]: http://github.com/groue/GRDB.swift
[GRDBObjc]: http://github.com/groue/GRDBObjc
[Persistable]: https://github.com/groue/GRDB.swift/blob/master/README.md#records
[Realm]: http://realm.io
[RowConvertible]: https://github.com/groue/GRDB.swift/blob/master/README.md#records
[RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB
[RxSwift]: https://github.com/ReactiveX/RxSwift
[SQLite.swift]: http://github.com/stephencelis/SQLite.swift
[StORM]: https://www.perfect.org/docs/StORM.html
[Swift-Kuery]: http://github.com/IBM-Swift/Swift-Kuery
[TableMapping]: https://github.com/groue/GRDB.swift/blob/master/README.md#records
[TransactionObserver]: https://github.com/groue/GRDB.swift/blob/master/README.md#transactionobserver-protocol
+1 -1
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '2.0'
s.version = '2.0.2'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A Swift application toolkit for SQLite databases.'
@@ -26,6 +26,7 @@
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
language = ""
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
@@ -55,6 +56,7 @@
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
language = ""
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
+3
View File
@@ -16,6 +16,9 @@
<FileRef
location = "group:TransactionObserver.playground">
</FileRef>
<FileRef
location = "group:Issue156.playground">
</FileRef>
<FileRef
location = "group:MyPlayground.playground">
</FileRef>
+195 -172
View File
@@ -330,6 +330,25 @@ public final class Database {
/// Available collations
private var collations = Set<DatabaseCollation>()
/// Current authorizer
var authorizer: StatementAuthorizer? {
didSet {
switch (oldValue, authorizer) {
case (.some, nil):
sqlite3_set_authorizer(sqliteConnection, nil, nil)
case (nil, .some):
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_set_authorizer(sqliteConnection, { (dbPointer, actionCode, cString1, cString2, cString3, cString4) -> Int32 in
guard let dbPointer = dbPointer else { return SQLITE_OK }
let db = Unmanaged<Database>.fromOpaque(dbPointer).takeUnretainedValue()
return db.authorizer!.authorize(actionCode, cString1, cString2, cString3, cString4)
}, dbPointer)
default:
break
}
}
}
/// Schema Cache
var schemaCache: DatabaseSchemaCache // internal so that it can be tested
@@ -436,7 +455,6 @@ public final class Database {
setupDefaultFunctions()
setupDefaultCollations()
setupTransactionHooks()
installDefaultAuthorizer()
}
/// This method must be called before database deallocation
@@ -589,28 +607,6 @@ public final class Database {
}, dbPointer)
}
fileprivate func installDefaultAuthorizer() {
// https://www.sqlite.org/capi3ref.html#sqlite3_set_authorizer
// > When sqlite3_prepare_v2() is used to prepare a statement, the
// > statement might be re-prepared during sqlite3_step() due to a
// > schema change. Hence, the application should ensure that the
// > correct authorizer callback remains in place during the
// > sqlite3_step().
//
// As a matter of fact, without this default authorizer, the truncate
// optimization prevents transaction observers from observing
// individual deletions.
sqlite3_set_authorizer(sqliteConnection, { (_, actionCode, cString1, cString2, cString3, cString4) -> Int32 in
if actionCode == SQLITE_DELETE && String(cString: cString1!) != "sqlite_master" {
// Prevent [truncate optimization](https://www.sqlite.org/lang_delete.html#truncateopt)
// so that transaction observers can observe individual deletions.
return SQLITE_IGNORE
} else {
return SQLITE_OK
}
}, nil)
}
private static func close(connection sqliteConnection: SQLiteConnection) {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
close_v2(connection: sqliteConnection)
@@ -712,7 +708,38 @@ extension Database {
/// - returns: A SelectStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
func makeSelectStatement(_ sql: String, prepFlags: Int32) throws -> SelectStatement {
return try SelectStatement(database: self, sql: sql, prepFlags: prepFlags)
let statementCompilationAuthorizer = StatementCompilationAuthorizer()
authorizer = statementCompilationAuthorizer
defer { authorizer = nil }
var statement: SelectStatement? = nil
let sqlCodeUnits = sql.utf8CString
var remainingSQL = ""
try sqlCodeUnits.withUnsafeBufferPointer { codeUnits in
let statementStart = UnsafePointer<Int8>(codeUnits.baseAddress)!
var statementEnd: UnsafePointer<Int8>? = nil
do {
statement = try SelectStatement(
database: self,
statementStart: statementStart,
statementEnd: &statementEnd,
prepFlags: prepFlags,
authorizer: statementCompilationAuthorizer)
} catch is EmptyStatementError {
throw DatabaseError(resultCode: .SQLITE_ERROR, message: "empty statement", sql: sql, arguments: nil)
}
let remainingData = Data(
bytesNoCopy: UnsafeMutableRawPointer(mutating: statementEnd!),
count: statementStart + sqlCodeUnits.count - statementEnd! - 1,
deallocator: .none)
remainingSQL = String(data: remainingData, encoding: .utf8)!.trimmingCharacters(in: .whitespacesAndNewlines)
}
guard remainingSQL.isEmpty else {
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "Multiple statements found. To execute multiple statements, use Database.execute() instead.", sql: sql, arguments: nil)
}
return statement!
}
/// Returns a prepared statement that can be reused.
@@ -764,7 +791,38 @@ extension Database {
/// - returns: An UpdateStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
func makeUpdateStatement(_ sql: String, prepFlags: Int32) throws -> UpdateStatement {
return try UpdateStatement(database: self, sql: sql, prepFlags: prepFlags)
let statementCompilationAuthorizer = StatementCompilationAuthorizer()
authorizer = statementCompilationAuthorizer
defer { authorizer = nil }
var statement: UpdateStatement? = nil
let sqlCodeUnits = sql.utf8CString
var remainingSQL = ""
try sqlCodeUnits.withUnsafeBufferPointer { codeUnits in
let statementStart = UnsafePointer<Int8>(codeUnits.baseAddress)!
var statementEnd: UnsafePointer<Int8>? = nil
do {
statement = try UpdateStatement(
database: self,
statementStart: statementStart,
statementEnd: &statementEnd,
prepFlags: prepFlags,
authorizer: statementCompilationAuthorizer)
} catch is EmptyStatementError {
throw DatabaseError(resultCode: .SQLITE_ERROR, message: "empty statement", sql: sql, arguments: nil)
}
let remainingData = Data(
bytesNoCopy: UnsafeMutableRawPointer(mutating: statementEnd!),
count: statementStart + sqlCodeUnits.count - statementEnd! - 1,
deallocator: .none)
remainingSQL = String(data: remainingData, encoding: .utf8)!.trimmingCharacters(in: .whitespacesAndNewlines)
}
guard remainingSQL.isEmpty else {
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "Multiple statements found. To execute multiple statements, use Database.execute() instead.", sql: sql, arguments: nil)
}
return statement!
}
/// Returns a prepared statement that can be reused.
@@ -811,11 +869,8 @@ extension Database {
/// - throws: A DatabaseError whenever an SQLite error occurs.
public func execute(_ sql: String, arguments: StatementArguments? = nil) throws {
// This method is like sqlite3_exec (https://www.sqlite.org/c3ref/exec.html)
// It adds support for arguments.
SchedulingWatchdog.preconditionValidQueue(self)
// The tricky part is to consume arguments as statements are executed.
// It adds support for arguments, and the tricky part is to consume
// arguments as statements are executed.
//
// Here we build two functions:
// - consumeArguments returns arguments for a statement
@@ -835,63 +890,39 @@ extension Database {
}
}
// Execute statements
let sqlCodeUnits = sql.utf8CString
var error: Error?
// During the execution of sqlite3_prepare_v2, the observer listens to
// authorization callbacks in order to recognize "interesting"
// statements. See updateStatementDidExecute().
let observer = StatementCompilationObserver(self)
observer.start()
sqlCodeUnits.withUnsafeBufferPointer { codeUnits in
try sqlCodeUnits.withUnsafeBufferPointer { codeUnits in
let sqlStart = UnsafePointer<Int8>(codeUnits.baseAddress)!
let sqlEnd = sqlStart + sqlCodeUnits.count
var statementStart = sqlStart
while statementStart < sqlEnd - 1 {
observer.reset()
var statementEnd: UnsafePointer<Int8>? = nil
var sqliteStatement: SQLiteStatement? = nil
let code = sqlite3_prepare_v2(sqliteConnection, statementStart, -1, &sqliteStatement, &statementEnd)
guard code == SQLITE_OK else {
error = DatabaseError(resultCode: code, message: lastErrorMessage, sql: sql)
break
}
guard sqliteStatement != nil else {
// The remaining string contains only whitespace
assert(String(data: Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: statementStart), count: statementEnd! - statementStart, deallocator: .none), encoding: .utf8)!.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
break
}
do {
let statement = UpdateStatement(
let statementCompilationAuthorizer = StatementCompilationAuthorizer()
authorizer = statementCompilationAuthorizer
defer { authorizer = nil }
let statement = try UpdateStatement(
database: self,
sqliteStatement: sqliteStatement!,
invalidatesDatabaseSchemaCache: observer.invalidatesDatabaseSchemaCache,
transactionStatementInfo: observer.transactionStatementInfo,
databaseEventKinds: observer.databaseEventKinds)
statementStart: statementStart,
statementEnd: &statementEnd,
prepFlags: 0,
authorizer: statementCompilationAuthorizer)
let arguments = try consumeArguments(statement)
statement.unsafeSetArguments(arguments)
try statement.execute()
} catch let statementError {
error = statementError
statementStart = statementEnd!
} catch is EmptyStatementError {
break
}
statementStart = statementEnd!
}
}
observer.stop()
if let error = error {
throw error
}
// Force arguments validity: it is a programmer error to provide
// arguments that do not match the statement.
try! validateRemainingArguments() // throws if there are remaining arguments.
@@ -1487,12 +1518,15 @@ public struct ForeignKeyInfo {
// =========================================================================
// MARK: - StatementCompilationObserver
// MARK: - StatementAuthorizer
/// A protocol around sqlite3_set_authorizer
protocol StatementAuthorizer : class {
func authorize(_ actionCode: Int32, _ cString1: UnsafePointer<Int8>?, _ cString2: UnsafePointer<Int8>?, _ cString3: UnsafePointer<Int8>?, _ cString4: UnsafePointer<Int8>?) -> Int32
}
/// A class that gathers information about a statement during its compilation.
final class StatementCompilationObserver {
let database: Database
final class StatementCompilationAuthorizer : StatementAuthorizer {
/// A dictionary [tablename: Set<columnName>] of accessed columns
var selectionInfo = SelectStatement.SelectionInfo()
@@ -1507,99 +1541,77 @@ final class StatementCompilationObserver {
/// Not nil if a statement is a BEGIN/COMMIT/ROLLBACK/RELEASE transaction/savepoint statement.
var transactionStatementInfo: UpdateStatement.TransactionStatementInfo?
var isDropTableStatement = false
var needsTruncateOptimizationPreventionDuringExecution = false
init(_ database: Database) {
self.database = database
}
private var isDropTableStatement = false
// Call this method before calling sqlite3_prepare_v2()
func start() {
let observerPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_set_authorizer(database.sqliteConnection, { (observerPointer, actionCode, cString1, cString2, cString3, cString4) -> Int32 in
// print("\(actionCode) \([cString1, cString2, cString3, cString4].flatMap { $0.map({ String(cString: $0) }) })")
// https://www.sqlite.org/c3ref/set_authorizer.html:
//
// > Applications must always be prepared to encounter a NULL
// > pointer in any of the third through the sixth parameters of
// > the authorization callback.
switch actionCode {
case SQLITE_DROP_TABLE, SQLITE_DROP_TEMP_TABLE, SQLITE_DROP_TEMP_VIEW, SQLITE_DROP_VIEW, SQLITE_DETACH, SQLITE_ALTER_TABLE, SQLITE_DROP_VTABLE, SQLITE_CREATE_INDEX, SQLITE_CREATE_TEMP_INDEX, SQLITE_DROP_INDEX, SQLITE_DROP_TEMP_INDEX:
let observer = Unmanaged<StatementCompilationObserver>.fromOpaque(observerPointer!).takeUnretainedValue()
if actionCode == SQLITE_DROP_TABLE || actionCode == SQLITE_DROP_VTABLE {
observer.isDropTableStatement = true
}
observer.invalidatesDatabaseSchemaCache = true
case SQLITE_READ:
guard let tableName = cString1.map({ String(cString: $0) }) else { return SQLITE_OK }
guard let columnName = cString2.map({ String(cString: $0) }) else { return SQLITE_OK }
let observer = Unmanaged<StatementCompilationObserver>.fromOpaque(observerPointer!).takeUnretainedValue()
if columnName.isEmpty {
// SELECT COUNT(*) FROM table
observer.selectionInfo.insert(allColumnsOfTable: tableName)
} else {
// SELECT column FROM table
observer.selectionInfo.insert(column: columnName, ofTable: tableName)
}
case SQLITE_INSERT:
guard let tableName = cString1.map({ String(cString: $0) }) else { return SQLITE_OK }
let observer = Unmanaged<StatementCompilationObserver>.fromOpaque(observerPointer!).takeUnretainedValue()
observer.databaseEventKinds.append(.insert(tableName: tableName))
case SQLITE_DELETE:
guard let tableName = cString1.map({ String(cString: $0) }) else { return SQLITE_OK }
let observer = Unmanaged<StatementCompilationObserver>.fromOpaque(observerPointer!).takeUnretainedValue()
if tableName != "sqlite_master" && !observer.isDropTableStatement {
observer.databaseEventKinds.append(.delete(tableName: tableName))
// Prevent [truncate optimization](https://www.sqlite.org/lang_delete.html#truncateopt)
// so that transaction observers can observe individual deletions.
return SQLITE_IGNORE
}
case SQLITE_UPDATE:
guard let tableName = cString1.map({ String(cString: $0) }) else { return SQLITE_OK }
guard let columnName = cString2.map({ String(cString: $0) }) else { return SQLITE_OK }
let observer = Unmanaged<StatementCompilationObserver>.fromOpaque(observerPointer!).takeUnretainedValue()
observer.insertUpdateEventKind(tableName: tableName, columnName: columnName)
case SQLITE_TRANSACTION:
guard let rawAction = cString1.map({ String(cString: $0) }) else { return SQLITE_OK }
let observer = Unmanaged<StatementCompilationObserver>.fromOpaque(observerPointer!).takeUnretainedValue()
let action = UpdateStatement.TransactionStatementInfo.TransactionAction(rawValue: rawAction)!
observer.transactionStatementInfo = .transaction(action: action)
case SQLITE_SAVEPOINT:
guard let rawAction = cString1.map({ String(cString: $0) }) else { return SQLITE_OK }
guard let savepointName = cString2.map({ String(cString: $0) }) else { return SQLITE_OK }
let observer = Unmanaged<StatementCompilationObserver>.fromOpaque(observerPointer!).takeUnretainedValue()
let action = UpdateStatement.TransactionStatementInfo.SavepointAction(rawValue: rawAction)!
observer.transactionStatementInfo = .savepoint(name: savepointName, action: action)
case SQLITE_FUNCTION:
// Starting SQLite 3.19.0, `SELECT COUNT(*) FROM table` triggers
// an authorization callback for SQLITE_READ with an empty
// column: http://www.sqlite.org/changes.html#version_3_19_0
//
// Before SQLite 3.19.0, `SELECT COUNT(*) FROM table` does not
// trigger any authorization callback that tells about the
// counted table: any use of the COUNT function makes the
// selection undetermined.
guard sqlite3_libversion_number() < 3019000 else { return SQLITE_OK }
guard let functionName = cString2.map({ String(cString: $0) }) else { return SQLITE_OK }
if functionName.uppercased() == "COUNT" {
let observer = Unmanaged<StatementCompilationObserver>.fromOpaque(observerPointer!).takeUnretainedValue()
observer.selectionInfo = SelectStatement.SelectionInfo.unknown()
}
default:
break
func authorize(_ actionCode: Int32, _ cString1: UnsafePointer<Int8>?, _ cString2: UnsafePointer<Int8>?, _ cString3: UnsafePointer<Int8>?, _ cString4: UnsafePointer<Int8>?) -> Int32 {
// print("StatementCompilationAuthorizer: \(actionCode) \([cString1, cString2, cString3, cString4].flatMap { $0.map({ String(cString: $0) }) })")
switch actionCode {
case SQLITE_DROP_TABLE, SQLITE_DROP_TEMP_TABLE, SQLITE_DROP_TEMP_VIEW, SQLITE_DROP_VIEW, SQLITE_DETACH, SQLITE_ALTER_TABLE, SQLITE_DROP_VTABLE, SQLITE_CREATE_INDEX, SQLITE_CREATE_TEMP_INDEX, SQLITE_DROP_INDEX, SQLITE_DROP_TEMP_INDEX:
if actionCode == SQLITE_DROP_TABLE || actionCode == SQLITE_DROP_VTABLE {
isDropTableStatement = true
}
invalidatesDatabaseSchemaCache = true
return SQLITE_OK
case SQLITE_READ:
guard let tableName = cString1.map({ String(cString: $0) }) else { return SQLITE_OK }
guard let columnName = cString2.map({ String(cString: $0) }) else { return SQLITE_OK }
if columnName.isEmpty {
// SELECT COUNT(*) FROM table
selectionInfo.insert(allColumnsOfTable: tableName)
} else {
// SELECT column FROM table
selectionInfo.insert(column: columnName, ofTable: tableName)
}
return SQLITE_OK
}, observerPointer)
}
// Call this method between two calls to calling sqlite3_prepare_v2()
func reset() {
selectionInfo = SelectStatement.SelectionInfo()
databaseEventKinds = []
invalidatesDatabaseSchemaCache = false
transactionStatementInfo = nil
isDropTableStatement = false
case SQLITE_INSERT:
guard let tableName = cString1.map({ String(cString: $0) }) else { return SQLITE_OK }
databaseEventKinds.append(.insert(tableName: tableName))
return SQLITE_OK
case SQLITE_DELETE:
guard !isDropTableStatement else { return SQLITE_OK }
guard let tableName = cString1.map({ String(cString: $0) }), tableName != "sqlite_master" else { return SQLITE_OK }
databaseEventKinds.append(.delete(tableName: tableName))
// Prevent the [truncate optimization](https://www.sqlite.org/lang_delete.html#truncateopt)
// See TruncateOptimizationBlocker
needsTruncateOptimizationPreventionDuringExecution = true
return SQLITE_IGNORE
case SQLITE_UPDATE:
guard let tableName = cString1.map({ String(cString: $0) }) else { return SQLITE_OK }
guard let columnName = cString2.map({ String(cString: $0) }) else { return SQLITE_OK }
insertUpdateEventKind(tableName: tableName, columnName: columnName)
return SQLITE_OK
case SQLITE_TRANSACTION:
guard let rawAction = cString1.map({ String(cString: $0) }) else { return SQLITE_OK }
let action = UpdateStatement.TransactionStatementInfo.TransactionAction(rawValue: rawAction)!
transactionStatementInfo = .transaction(action: action)
return SQLITE_OK
case SQLITE_SAVEPOINT:
guard let rawAction = cString1.map({ String(cString: $0) }) else { return SQLITE_OK }
guard let savepointName = cString2.map({ String(cString: $0) }) else { return SQLITE_OK }
let action = UpdateStatement.TransactionStatementInfo.SavepointAction(rawValue: rawAction)!
transactionStatementInfo = .savepoint(name: savepointName, action: action)
return SQLITE_OK
case SQLITE_FUNCTION:
// Starting SQLite 3.19.0, `SELECT COUNT(*) FROM table` triggers
// an authorization callback for SQLITE_READ with an empty
// column: http://www.sqlite.org/changes.html#version_3_19_0
//
// Before SQLite 3.19.0, `SELECT COUNT(*) FROM table` does not
// trigger any authorization callback that tells about the
// counted table: any use of the COUNT function makes the
// selection undetermined.
guard sqlite3_libversion_number() < 3019000 else { return SQLITE_OK }
guard let functionName = cString2.map({ String(cString: $0) }) else { return SQLITE_OK }
if functionName.uppercased() == "COUNT" {
selectionInfo = SelectStatement.SelectionInfo.unknown()
}
return SQLITE_OK
default:
return SQLITE_OK
}
}
func insertUpdateEventKind(tableName: String, columnName: String) {
@@ -1613,10 +1625,21 @@ final class StatementCompilationObserver {
}
databaseEventKinds.append(.update(tableName: tableName, columnNames: [columnName]))
}
func stop() {
// Restore default authorizer
database.installDefaultAuthorizer()
}
/// This authorizer prevents the [truncate optimization](https://www.sqlite.org/lang_delete.html#truncateopt)
/// which makes transaction observers unable to observe individual deletions
/// when user runs `DELETE FROM t` statements.
//
/// Warning: to perform well, this authorizer requires that:
//
/// - It is used during statement execution, not during statement compilation.
/// - Statement compilation was authorized with a StatementCompilationAuthorizer
/// that has set its needsTruncateOptimizationPreventionDuringExecution flag.
final class TruncateOptimizationBlocker : StatementAuthorizer {
func authorize(_ actionCode: Int32, _ cString1: UnsafePointer<Int8>?, _ cString2: UnsafePointer<Int8>?, _ cString3: UnsafePointer<Int8>?, _ cString4: UnsafePointer<Int8>?) -> Int32 {
// print("TruncateOptimizationBlocker: \(actionCode) \([cString1, cString2, cString3, cString4].flatMap { $0.map({ String(cString: $0) }) })")
return (actionCode == SQLITE_DELETE) ? SQLITE_IGNORE : SQLITE_OK
}
}
@@ -1924,17 +1947,17 @@ extension Database {
///
/// An INSERT statement will pass, but not DROP TABLE (which invalidates the
/// database cache), or RELEASE SAVEPOINT (which alters the savepoint stack)
static func preconditionValidSelectStatement(sql: String, observer: StatementCompilationObserver) {
GRDBPrecondition(observer.invalidatesDatabaseSchemaCache == false, "Invalid statement type for query \(String(reflecting: sql)): use UpdateStatement instead.")
GRDBPrecondition(observer.transactionStatementInfo == nil, "Invalid statement type for query \(String(reflecting: sql)): use UpdateStatement instead.")
static func preconditionValidSelectStatement(sql: String, authorizer: StatementCompilationAuthorizer) {
GRDBPrecondition(authorizer.invalidatesDatabaseSchemaCache == false, "Invalid statement type for query \(String(reflecting: sql)): use UpdateStatement instead.")
GRDBPrecondition(authorizer.transactionStatementInfo == nil, "Invalid statement type for query \(String(reflecting: sql)): use UpdateStatement instead.")
// Don't check for observer.databaseEventKinds.isEmpty
// Don't check for authorizer.databaseEventKinds.isEmpty
//
// When observer.databaseEventKinds.isEmpty is NOT empty, this means
// When authorizer.databaseEventKinds.isEmpty is NOT empty, this means
// that the database is changed by the statement.
//
// It thus looks like the statement should be performed by an
// UpdateStatement, not a SelectStatement: transaction observers are not
// UpdateStatement, not a SelectStatement: transaction authorizers are not
// notified of database changes when they are executed by
// a SelectStatement.
//
@@ -1948,7 +1971,7 @@ extension Database {
// himself: just give up, and allow SelectStatement to execute database
// changes. We'll cope with eventual troubles later, when they occur.
//
// GRDBPrecondition(observer.databaseEventKinds.isEmpty, "Invalid statement type for query \(String(reflecting: sql)): use UpdateStatement instead.")
// GRDBPrecondition(authorizer.databaseEventKinds.isEmpty, "Invalid statement type for query \(String(reflecting: sql)): use UpdateStatement instead.")
}
func updateStatementWillExecute(_ statement: UpdateStatement) {
+74 -57
View File
@@ -8,6 +8,10 @@ import Foundation
/// A raw SQLite statement, suitable for the SQLite C API.
public typealias SQLiteStatement = OpaquePointer
/// An error emitted when one tries to compile an empty statement.
struct EmptyStatementError : Error {
}
/// A statement represents an SQL query.
///
/// It is the base class of UpdateStatement that executes *update statements*,
@@ -27,53 +31,47 @@ public class Statement {
/// The database
unowned let database: Database
init(database: Database, sqliteStatement: SQLiteStatement) {
self.database = database
self.sqliteStatement = sqliteStatement
}
/// Creates a prepared statement.
///
/// - parameter database: A database connection.
/// - parameter sql: An SQL query.
/// - parameter statementStart: A pointer to a UTF-8 encoded C string
/// containing SQL.
/// - parameter statementEnd: Upon success, the pointer to the next
/// statement in the C string.
/// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
/// - parameter observer: A StatementCompilationObserver
fileprivate init(database: Database, sql: String, prepFlags: Int32, observer: StatementCompilationObserver) throws {
/// - throws: DatabaseError in case of compilation error, and
/// EmptyStatementError if the compiled string is blank or empty.
init(database: Database, statementStart: UnsafePointer<Int8>, statementEnd: UnsafeMutablePointer<UnsafePointer<Int8>?>, prepFlags: Int32) throws {
SchedulingWatchdog.preconditionValidQueue(database)
observer.start()
defer { observer.stop() }
let sqlCodeUnits = sql.utf8CString
var sqliteStatement: SQLiteStatement? = nil
var code: Int32 = 0
var remainingSQL = ""
sqlCodeUnits.withUnsafeBufferPointer { codeUnits in
let sqlStart = UnsafePointer<Int8>(codeUnits.baseAddress)!
var sqlEnd: UnsafePointer<Int8>? = nil
// sqlite3_prepare_v3 was introduced in SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20
#if GRDBCUSTOMSQLITE
code = sqlite3_prepare_v3(database.sqliteConnection, sqlStart, -1, UInt32(bitPattern: prepFlags), &sqliteStatement, &sqlEnd)
#else
code = sqlite3_prepare_v2(database.sqliteConnection, sqlStart, -1, &sqliteStatement, &sqlEnd)
#endif
let remainingData = Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: sqlEnd!), count: sqlStart + sqlCodeUnits.count - sqlEnd! - 1, deallocator: .none)
remainingSQL = String(data: remainingData, encoding: .utf8)!.trimmingCharacters(in: .whitespacesAndNewlines)
}
// sqlite3_prepare_v3 was introduced in SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20
#if GRDBCUSTOMSQLITE
let code = sqlite3_prepare_v3(database.sqliteConnection, statementStart, -1, UInt32(bitPattern: prepFlags), &sqliteStatement, statementEnd)
#else
let code = sqlite3_prepare_v2(database.sqliteConnection, statementStart, -1, &sqliteStatement, statementEnd)
#endif
guard code == SQLITE_OK else {
throw DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql)
throw DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: String(cString: statementStart))
}
guard remainingSQL.isEmpty else {
sqlite3_finalize(sqliteStatement)
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "Multiple statements found. To execute multiple statements, use Database.execute() instead.", sql: sql, arguments: nil)
guard let statement = sqliteStatement else {
// Sanity check: verify that the string contains only whitespace
assert(String(data: Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: statementStart), count: statementEnd.pointee! - statementStart, deallocator: .none), encoding: .utf8)!.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
// I wish we could simply return nil, and make this initializer failable.
//
// Unfortunately, there is a Swift bug with failable+throwing initializers:
// https://bugs.swift.org/browse/SR-6067
//
// We thus use sentinel error for empty statements.
throw EmptyStatementError()
}
self.database = database
self.sqliteStatement = sqliteStatement!
self.sqliteStatement = statement
}
deinit {
@@ -236,15 +234,24 @@ public final class SelectStatement : Statement {
/// Creates a prepared statement.
///
/// - parameter database: A database connection.
/// - parameter sql: An SQL query.
/// - parameter statementStart: A pointer to a UTF-8 encoded C string
/// containing SQL.
/// - parameter statementEnd: Upon success, the pointer to the next
/// statement in the C string.
/// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
init(database: Database, sql: String, prepFlags: Int32) throws {
/// - authorizer: A StatementCompilationAuthorizer
/// - throws: DatabaseError in case of compilation error, and
/// EmptyStatementError if the compiled string is blank or empty.
init(database: Database, statementStart: UnsafePointer<Int8>, statementEnd: UnsafeMutablePointer<UnsafePointer<Int8>?>, prepFlags: Int32, authorizer: StatementCompilationAuthorizer) throws {
self.selectionInfo = SelectionInfo()
let observer = StatementCompilationObserver(database)
try super.init(database: database, sql: sql, prepFlags: prepFlags, observer: observer)
Database.preconditionValidSelectStatement(sql: sql, observer: observer)
self.selectionInfo = observer.selectionInfo
try super.init(
database: database,
statementStart: statementStart,
statementEnd: statementEnd,
prepFlags: prepFlags)
Database.preconditionValidSelectStatement(sql: sql, authorizer: authorizer)
self.selectionInfo = authorizer.selectionInfo
}
/// The number of columns in the resulting rows.
@@ -408,31 +415,39 @@ public final class UpdateStatement : Statement {
/// If true, the database schema cache gets invalidated after this statement
/// is executed.
private(set) var invalidatesDatabaseSchemaCache: Bool
/// If true, the statement needs support from TruncateOptimizationBlocker
/// when executed
private(set) var needsTruncateOptimizationPreventionDuringExecution: Bool
private(set) var transactionStatementInfo: TransactionStatementInfo?
private(set) var databaseEventKinds: [DatabaseEventKind]
init(database: Database, sqliteStatement: SQLiteStatement, invalidatesDatabaseSchemaCache: Bool, transactionStatementInfo: TransactionStatementInfo?, databaseEventKinds: [DatabaseEventKind]) {
self.invalidatesDatabaseSchemaCache = invalidatesDatabaseSchemaCache
self.transactionStatementInfo = transactionStatementInfo
self.databaseEventKinds = databaseEventKinds
super.init(database: database, sqliteStatement: sqliteStatement)
}
/// Creates a prepared statement.
///
/// - parameter database: A database connection.
/// - parameter sql: An SQL query.
/// - parameter statementStart: A pointer to a UTF-8 encoded C string
/// containing SQL.
/// - parameter statementEnd: Upon success, the pointer to the next
/// statement in the C string.
/// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
init(database: Database, sql: String, prepFlags: Int32) throws {
/// - authorizer: A StatementCompilationAuthorizer
/// - throws: DatabaseError in case of compilation error, and
/// EmptyStatementError if the compiled string is blank or empty.
init(database: Database, statementStart: UnsafePointer<Int8>, statementEnd: UnsafeMutablePointer<UnsafePointer<Int8>?>, prepFlags: Int32, authorizer: StatementCompilationAuthorizer) throws {
self.invalidatesDatabaseSchemaCache = false
self.needsTruncateOptimizationPreventionDuringExecution = false
self.databaseEventKinds = []
let observer = StatementCompilationObserver(database)
try super.init(database: database, sql: sql, prepFlags: prepFlags, observer: observer)
self.invalidatesDatabaseSchemaCache = observer.invalidatesDatabaseSchemaCache
self.transactionStatementInfo = observer.transactionStatementInfo
self.databaseEventKinds = observer.databaseEventKinds
try super.init(
database: database,
statementStart: statementStart,
statementEnd: statementEnd,
prepFlags: prepFlags)
self.invalidatesDatabaseSchemaCache = authorizer.invalidatesDatabaseSchemaCache
self.needsTruncateOptimizationPreventionDuringExecution = authorizer.needsTruncateOptimizationPreventionDuringExecution
self.transactionStatementInfo = authorizer.transactionStatementInfo
self.databaseEventKinds = authorizer.databaseEventKinds
}
/// Executes the SQL query.
@@ -445,6 +460,10 @@ public final class UpdateStatement : Statement {
reset()
database.updateStatementWillExecute(self)
if needsTruncateOptimizationPreventionDuringExecution {
database.authorizer = TruncateOptimizationBlocker()
}
while true {
switch sqlite3_step(sqliteStatement) {
case SQLITE_ROW:
@@ -467,15 +486,13 @@ public final class UpdateStatement : Statement {
continue
case SQLITE_DONE:
database.authorizer = nil
database.updateStatementDidExecute(self)
return
case let code:
// Failure
//
// Let database rethrow eventual transaction observer error:
database.authorizer = nil
try database.updateStatementDidFail(self)
throw DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql, arguments: self.arguments) // Error uses self.arguments, not the optional arguments parameter.
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDBCipher'
s.version = '2.0'
s.version = '2.0.2'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A Swift application toolkit for SQLite databases.'
@@ -0,0 +1,101 @@
// Issue156
//
// This playground exists as a test of issue #156, for which I'm not sure we
// have a test today.
import Foundation
import GRDB
import PlaygroundSupport
class TestDeleteAll: NSObject {
let databasePool: DatabasePool
let fetchedRecordsController: FetchedRecordsController<MyRecord>
override init() {
// Init a databasePool & a fetchedRecordsController
let databasePath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] + "/myDatabase.sqlite"
databasePool = try! DatabasePool(path: databasePath)
var migrator = DatabaseMigrator()
migrator.registerMigration("1") { db in
try! db.create(table: MyRecord.databaseTableName) { t in
t.column(MyRecord.MyColumn.name, .text)
}
}
try! migrator.migrate(databasePool)
fetchedRecordsController = try! FetchedRecordsController<MyRecord>(databasePool, request: MyRecord.all())
try! fetchedRecordsController.performFetch()
fetchedRecordsController.trackChanges { controller in
print("RecordsDidChange triggered: number of records = \(controller.fetchedRecords.count)\n")
}
super.init()
run()
}
func run() {
insertThreeRecords()
perform(#selector(deleteAllWithFilter), with: nil, afterDelay: 1)
perform(#selector(insertThreeRecords), with: nil, afterDelay: 2)
perform(#selector(deleteAll), with: nil, afterDelay: 3)
perform(#selector(insertThreeRecords), with: nil, afterDelay: 4)
}
@objc
func insertThreeRecords() {
print("Insert 3 records")
let myRecord1 = MyRecord(myColumn: "1")
let myRecord2 = MyRecord(myColumn: "2")
let myRecord3 = MyRecord(myColumn: "3")
try! databasePool.writeInTransaction { db in
try myRecord1.save(db)
try myRecord2.save(db)
try myRecord3.save(db)
return .commit
}
}
@objc
func deleteAllWithFilter() {
print("Delete all records with filter(1 == 1).deleteAll(db)")
_ = try! databasePool.write { db in
try MyRecord.filter(1 == 1).deleteAll(db)
}
}
@objc
func deleteAll() {
print("Delete all records with deleteAll(db)")
_ = try! databasePool.write { db in
try MyRecord.deleteAll(db)
}
}
}
struct MyRecord: RowConvertible, TableMapping, Persistable {
static let MyColumn = Column("MyColumn")
static var databaseTableName: String { return String(describing: self) }
let myColumn: String
init(myColumn: String) {
self.myColumn = myColumn
}
init(row: Row) {
self.myColumn = row[MyRecord.MyColumn]
}
func encode(to container: inout PersistenceContainer) {
container[MyRecord.MyColumn] = myColumn
}
}
TestDeleteAll()
PlaygroundPage.current.needsIndefiniteExecution = true
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<playground version='5.0' target-platform='macos'>
<timeline fileName='timeline.xctimeline'/>
</playground>
+35 -34
View File
@@ -3,7 +3,7 @@ GRDB 2.0 [![Swift](https://img.shields.io/badge/swift-4-orange.svg?style=flat)](
### A toolkit for SQLite databases, with a focus on application development
**Latest release**: September 16, 2017 • version 2.0 • [CHANGELOG](CHANGELOG.md)
**Latest release**: October 5, 2017 • version 2.0.2 • [CHANGELOG](CHANGELOG.md)
**Requirements**: iOS 8.0+ / OSX 10.9+ / watchOS 2.0+ &bull; Swift 4.0 / Xcode 9+
@@ -14,7 +14,7 @@ GRDB 2.0 [![Swift](https://img.shields.io/badge/swift-4-orange.svg?style=flat)](
| Swift 3 | [v1.0](https://github.com/groue/GRDB.swift/tree/v1.0) |
| Swift 3.1 | [v1.3.0](https://github.com/groue/GRDB.swift/tree/v1.3.0) |
| Swift 3.2 | [v1.3.0](https://github.com/groue/GRDB.swift/tree/v1.3.0) |
| Swift 4 | [v2.0](https://github.com/groue/GRDB.swift/tree/v2.0) |
| **Swift 4** | **v2.0.2** |
Follow [@groue](http://twitter.com/groue) on Twitter for release announcements and usage tips.
@@ -27,6 +27,10 @@ Compared to [SQLite.swift](http://github.com/stephencelis/SQLite.swift) or [FMDB
It comes with [up-to-date documentation](#documentation), [general articles](https://medium.com/@gwendal.roue), [sample code](#sample-code), and a lot of interesting resolved issues that may answer your eventual [questions](https://github.com/groue/GRDB.swift/issues?utf8=✓&q=is%3Aissue%20label%3Aquestion) and foster [best practices](https://github.com/groue/GRDB.swift/issues?q=is%3Aissue+label%3A%22best+practices%22).
For more information, check out:
- [Why Adopt GRDB?](Documentation/WhyAdoptGRDB.md) The reasons why GRDB could become your favorite database library.
- [How to build an iOS application with SQLite and GRDB.swift](https://medium.com/@gwendal.roue/how-to-build-an-ios-application-with-sqlite-and-grdb-swift-d023a06c29b3) The architecture of a GRDB-powered application.
---
@@ -66,8 +70,6 @@ More than a set of tools that leverage SQLite abilities, GRDB is also:
- **Safer**: read the blog post [Four different ways to handle SQLite concurrency](https://medium.com/@gwendal.roue/four-different-ways-to-handle-sqlite-concurrency-db3bcc74d00e)
- **Faster**: see [Comparing the Performances of Swift SQLite libraries](https://github.com/groue/GRDB.swift/wiki/Performance) for a comparison between raw SQLite, FMDB, SQLite.swift, Core Data, Realm, and GRDB.
For a general overview of how a protocol-oriented library impacts database accesses, have a look at [How to build an iOS application with SQLite and GRDB.swift](https://medium.com/@gwendal.roue/how-to-build-an-ios-application-with-sqlite-and-grdb-swift-d023a06c29b3).
## Usage
@@ -262,9 +264,8 @@ The [Swift Package Manager](https://swift.org/package-manager/) automates the di
```swift
let package = Package(
...
dependencies: [
.Package(url: "https://github.com/groue/GRDB.swift.git", majorVersion: 0)
.package(url: "https://github.com/groue/GRDB.swift.git", from: "2.0.2")
]
)
```
@@ -281,7 +282,7 @@ Any pull request that has the `make test_CarthageBuild` command successfully com
## Manually
1. [Download](https://github.com/groue/GRDB.swift/releases/tag/v2.0) a copy of GRDB, or clone its repository and make sure you use the latest tagged version with the `git checkout v2.0` command.
1. [Download](https://github.com/groue/GRDB.swift/releases/tag/v2.0.2) a copy of GRDB, or clone its repository and make sure you use the latest tagged version with the `git checkout v2.0.2` command.
2. Embed the `GRDB.xcodeproj` project in your own project.
@@ -362,7 +363,7 @@ let placeCount = try dbQueue.inDatabase { db in
**A database queue needs your application to follow rules in order to deliver its safety guarantees.** Please refer to the [Concurrency](#concurrency) chapter.
See [DemoApps/GRDBDemoiOS/Database.swift](DemoApps/GRDBDemoiOS/GRDBDemoiOS/Database.swift) for a sample code that sets up a database queue on iOS.
See [DemoApps/GRDBDemoiOS/AppDatabase.swift](DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift) for a sample code that sets up a database queue on iOS.
### DatabaseQueue Configuration
@@ -442,7 +443,7 @@ Database pools allow several threads to access the database at the same time:
See [Advanced DatabasePool](#advanced-databasepool) for more DatabasePool hotness.
For a sample code that sets up a database pool on iOS, see [DemoApps/GRDBDemoiOS/Database.swift](DemoApps/GRDBDemoiOS/GRDBDemoiOS/Database.swift), and replace DatabaseQueue with DatabasePool.
For a sample code that sets up a database pool on iOS, see [DemoApps/GRDBDemoiOS/AppDatabase.swift](DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift), and replace DatabaseQueue with DatabasePool.
### DatabasePool Configuration
@@ -2649,45 +2650,46 @@ This is the list of record methods, along with their required protocols. The [Re
| Method | Protocols | Notes |
| ------ | --------- | :---: |
| **Inserting and Updating Records** | | |
| `try record.insert(db)` | [Persistable](#persistable-protocol) | |
| `try record.save(db)` | [Persistable](#persistable-protocol) | |
| `try record.update(db)` | [Persistable](#persistable-protocol) | |
| `try record.update(db, columns: ...)` | [Persistable](#persistable-protocol) | |
| `record.databaseDictionary` | [Persistable](#persistable-protocol) | |
| **Checking Record Existence** | | |
| **Insert and Update Records** | | |
| `record.insert(db)` | [Persistable](#persistable-protocol) | |
| `record.save(db)` | [Persistable](#persistable-protocol) | |
| `record.update(db)` | [Persistable](#persistable-protocol) | |
| `record.update(db, columns: ...)` | [Persistable](#persistable-protocol) | |
| `record.updateChanges(db)` | [Record](#record-class) | |
| **Delete Records** | | |
| `record.delete(db)` | [Persistable](#persistable-protocol) | |
| `Type.deleteOne(db, key: ...)` | [Persistable](#persistable-protocol) | <a href="#list-of-record-methods-1">¹</a> |
| `Type.deleteAll(db)` | [Persistable](#persistable-protocol) | |
| `Type.deleteAll(db, keys: ...)` | [Persistable](#persistable-protocol) | <a href="#list-of-record-methods-1">¹</a> |
| `Type.filter(...).deleteAll(db)` | [Persistable](#persistable-protocol) | <a href="#list-of-record-methods-2">²</a> |
| **Check Record Existence** | | |
| `record.exists(db)` | [Persistable](#persistable-protocol) | |
| **Deleting Records** | | |
| `try record.delete(db)` | [Persistable](#persistable-protocol) | |
| `try Type.deleteOne(db, key: ...)` | [Persistable](#persistable-protocol) | <a href="#list-of-record-methods-1">¹</a> |
| `try Type.deleteAll(db)` | [Persistable](#persistable-protocol) | |
| `try Type.deleteAll(db, keys: ...)` | [Persistable](#persistable-protocol) | <a href="#list-of-record-methods-1">¹</a> |
| `try Type.filter(...).deleteAll(db)` | [Persistable](#persistable-protocol) | <a href="#list-of-record-methods-2">²</a> |
| **Counting Records** | | |
| **Convert Record to Dictionary** | | |
| `record.databaseDictionary` | [Persistable](#persistable-protocol) | |
| **Count Records** | | |
| `Type.fetchCount(db)` | [TableMapping](#tablemapping-protocol) | |
| `Type.filter(...).fetchCount(db)` | [TableMapping](#tablemapping-protocol) | <a href="#list-of-record-methods-2">²</a> |
| **Fetching Record [Cursors](#cursors)** | | |
| **Fetch Record [Cursors](#cursors)** | | |
| `Type.fetchCursor(db)` | [RowConvertible](#rowconvertible-protocol) & [TableMapping](#tablemapping-protocol) | |
| `Type.fetchCursor(db, keys: ...)` | [RowConvertible](#rowconvertible-protocol) & [TableMapping](#tablemapping-protocol) | <a href="#list-of-record-methods-1">¹</a> |
| `Type.fetchCursor(db, sql)` | [RowConvertible](#rowconvertible-protocol) | <a href="#list-of-record-methods-3">³</a> |
| `Type.fetchCursor(statement)` | [RowConvertible](#rowconvertible-protocol) | <a href="#list-of-record-methods-4">⁴</a> |
| `Type.filter(...).fetchCursor(db)` | [RowConvertible](#rowconvertible-protocol) & [TableMapping](#tablemapping-protocol) | <a href="#list-of-record-methods-2">²</a> |
| **Fetching Record Arrays** | | |
| **Fetch Record Arrays** | | |
| `Type.fetchAll(db)` | [RowConvertible](#rowconvertible-protocol) & [TableMapping](#tablemapping-protocol) | |
| `Type.fetchAll(db, keys: ...)` | [RowConvertible](#rowconvertible-protocol) & [TableMapping](#tablemapping-protocol) | <a href="#list-of-record-methods-1">¹</a> |
| `Type.fetchAll(db, sql)` | [RowConvertible](#rowconvertible-protocol) | <a href="#list-of-record-methods-3">³</a> |
| `Type.fetchAll(statement)` | [RowConvertible](#rowconvertible-protocol) | <a href="#list-of-record-methods-4">⁴</a> |
| `Type.filter(...).fetchAll(db)` | [RowConvertible](#rowconvertible-protocol) & [TableMapping](#tablemapping-protocol) | <a href="#list-of-record-methods-2">²</a> |
| **Fetching Individual Records** | | |
| **Fetch Individual Records** | | |
| `Type.fetchOne(db)` | [RowConvertible](#rowconvertible-protocol) & [TableMapping](#tablemapping-protocol) | |
| `Type.fetchOne(db, key: ...)` | [RowConvertible](#rowconvertible-protocol) & [TableMapping](#tablemapping-protocol) | <a href="#list-of-record-methods-1">¹</a> |
| `Type.fetchOne(db, sql)` | [RowConvertible](#rowconvertible-protocol) | <a href="#list-of-record-methods-3">³</a> |
| `Type.fetchOne(statement)` | [RowConvertible](#rowconvertible-protocol) | <a href="#list-of-record-methods-4">⁴</a> |
| `Type.filter(...).fetchOne(db)` | [RowConvertible](#rowconvertible-protocol) & [TableMapping](#tablemapping-protocol) | <a href="#list-of-record-methods-2">²</a> |
| **Changes Tracking** | | |
| **[Track Changes](#changes-tracking)** | | |
| `record.hasPersistentChangedValues` | [Record](#record-class) | |
| `record.persistentChangedValues` | [Record](#record-class) | |
| `record.updateChanges(db)` | [Record](#record-class) | |
<a name="list-of-record-methods-1">¹</a> All unique keys are supported: primary keys (single-column, composite, [implicit RowID](#the-implicit-rowid-primary-key)) and unique indexes:
@@ -4297,7 +4299,7 @@ The eventual content already present in the regular table is indexed, and every
For more information, see the SQLite documentation about external content tables: [FTS4](https://www.sqlite.org/fts3.html#_external_content_fts4_tables_), [FTS5](https://sqlite.org/fts5.html#external_content_tables).
See also [WWDC Companion](https://github.com/groue/WWDCCompanion), a sample app that uses external content tables to store, display, and let the user search the WWDC 2016 sessions.
See also [WWDC Companion](https://github.com/groue/WWDCCompanion), a sample app that uses external content tables to store, display, and let the user search the WWDC sessions.
#### Querying External Content Full-Text Tables
@@ -5019,7 +5021,7 @@ Alternatively, perform a manual installation of GRDB and SQLCipher:
```sh
cd [GRDB directory]
git checkout v2.0
git checkout v2.0.2
git submodule update --init SQLCipher/src
```
@@ -5178,7 +5180,7 @@ do {
error.sql
// Full error description:
// "SQLite error 787 with statement `INSERT INTO pets (masterId, name)
// "SQLite error 19 with statement `INSERT INTO pets (masterId, name)
// VALUES (?, ?)` arguments [1, "Bobby"]: FOREIGN KEY constraint failed""
error.description
}
@@ -5268,7 +5270,7 @@ They uncover programmer errors, false assumptions, and prevent misuses. Here are
let dbValue: DatabaseValue = row["date"]
if dbValue.isNull {
// Handle NULL
if let date = Date.fromDatabaseValue(dbValue) {
} else if let date = Date.fromDatabaseValue(dbValue) {
// Handle valid date
} else {
// Handle invalid date
@@ -5550,7 +5552,7 @@ Those guarantees hold as long as you follow three rules:
This means that opening a new connection each time you access the database is probably a very bad idea. Do share a single connection instead.
See, for example, [DemoApps/GRDBDemoiOS/Database.swift](DemoApps/GRDBDemoiOS/GRDBDemoiOS/Database.swift) for a sample code that properly sets up a single database queue that is available throughout the application.
See, for example, [DemoApps/GRDBDemoiOS/AppDatabase.swift](DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift) for a sample code that properly sets up a single database queue that is available throughout the application.
If there are several instances of database queues or pools that access the same database, a multi-threaded application will eventually face "database is locked" errors. See [Dealing with External Connections](#dealing-with-external-connections).
@@ -6041,7 +6043,6 @@ FAQ
- [How do I close a database connection?](#how-do-i-close-a-database-connection)
- [How do I open a database stored as a resource of my application?](#how-do-i-open-a-database-stored-as-a-resource-of-my-application)
- [Generic parameter 'T' could not be inferred](#generic-parameter-t-could-not-be-inferred)
- [Compilation takes a long time](#compilation-takes-a-long-time)
- [SQLite error 10 "disk I/O error", SQLite error 23 "not authorized"](#sqlite-error-10-disk-io-error-sqlite-error-23-not-authorized)
- [What Are Experimental Features?](#what-are-experimental-features)
+3
View File
@@ -3,3 +3,6 @@ INFOPLIST_FILE = Support/Info.plist
PRODUCT_NAME = GRDB
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.$(PRODUCT_NAME:rfc1034identifier)
MODULEMAP_FILE = $(SRCROOT)/Support/module.modulemap
// Slow compilation hunt:
// OTHER_SWIFT_FLAGS = $(inherited) -Xfrontend -warn-long-expression-type-checking=100 -Xfrontend -warn-long-function-bodies=100
+1 -1
View File
@@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>2.0</string>
<string>2.0.2</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
+1 -1
View File
@@ -266,7 +266,7 @@ class DatabaseAggregateTests: GRDBTestCase {
struct Aggregate : DatabaseAggregate {
var result: DatabaseValueConvertible?
mutating func step(_ dbValues: [DatabaseValue]) {
result = String.fromDatabaseValue(dbValues[0]).map { $0.uppercased() }
result = String.fromDatabaseValue(dbValues[0])?.uppercased()
}
func finalize() -> DatabaseValueConvertible? {
return result
@@ -307,4 +307,20 @@ class UpdateStatementTests : GRDBTestCase {
}
}
}
func testDropTablePreparedStatement() throws {
// In v2.0.1...
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
XCTAssertFalse(try db.tableExists("t"))
try db.execute("CREATE TABLE t(a)")
XCTAssertTrue(try db.tableExists("t"))
try db.execute("DROP TABLE t") // ... this would drop the table
XCTAssertFalse(try db.tableExists("t"))
try db.execute("CREATE TABLE t(a)")
XCTAssertTrue(try db.tableExists("t"))
try db.makeUpdateStatement("DROP TABLE t").execute() // ... but this would not. WTF??? Hence this regression test.
XCTAssertFalse(try db.tableExists("t"))
}
}
}
+1 -1
View File
@@ -6,7 +6,7 @@ import PackageDescription
let package = Package(
name: "SPM",
dependencies: [
.package(url: "https://github.com/groue/GRDB.swift.git", from: "1.2.0"),
.package(url: "https://github.com/groue/GRDB.swift.git", from: "2.0.1"),
],
targets: [
.target(name: "SPM", dependencies: ["GRDB"]),