mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-29 04:24:21 +00:00
Merge branch 'master' of github.com:groue/GRDB.swift into Swift3
Conflicts: GRDB/QueryInterface/SQLTableBuilder.swift GRDB/Record/Persistable.swift GRDB/Record/Record.swift README.md TODO.md Tests/Public/Core/Persistable/MutablePersistableTests.swift Tests/Public/SQLTableBuilder/SQLTableBuilderTests.swift
This commit is contained in:
commit
c92f0f3edf
15 files changed
+280
-107
No files matched your search
@@ -1,6 +1,27 @@
|
||||
Release Notes
|
||||
=============
|
||||
|
||||
## 0.79.1
|
||||
|
||||
Released August 10, 2016
|
||||
|
||||
**Fixed**
|
||||
|
||||
- [ColumnDefinition](https://github.com/groue/GRDB.swift#database-schema) `check` and `references` methods can now define several constraints:
|
||||
|
||||
```swift
|
||||
try db.create(table: "users") { t in
|
||||
t.column("name", .Text).notNull()
|
||||
.check { length($0) > 0 }
|
||||
.check { !["root", "admin"].contains($0) }
|
||||
}
|
||||
```
|
||||
|
||||
- [Persistable](https://github.com/groue/GRDB.swift#persistable-protocol) `update`, `exists` and `delete` methods now work with objects that have a nil primary key. They used to crash.
|
||||
|
||||
- The `update(_:columns:)` method, which performs partial updates, no longer ignores unknown columns.
|
||||
|
||||
|
||||
## 0.79.0
|
||||
|
||||
Released August 8, 2016
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '0.79.0'
|
||||
s.version = '0.79.1'
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A Swift application toolkit for SQLite databases.'
|
||||
s.homepage = 'https://github.com/groue/GRDB.swift'
|
||||
|
||||
@@ -4621,7 +4621,7 @@
|
||||
baseConfigurationReference = 568BE51F1CB0360500270F93 /* GRDB.xcconfig */;
|
||||
buildSettings = {
|
||||
APPLICATION_EXTENSION_API_ONLY = YES;
|
||||
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
|
||||
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "";
|
||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||
DEFINES_MODULE = YES;
|
||||
DYLIB_COMPATIBILITY_VERSION = 1;
|
||||
@@ -4642,7 +4642,7 @@
|
||||
baseConfigurationReference = 568BE51F1CB0360500270F93 /* GRDB.xcconfig */;
|
||||
buildSettings = {
|
||||
APPLICATION_EXTENSION_API_ONLY = YES;
|
||||
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
|
||||
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "";
|
||||
COPY_PHASE_STRIP = NO;
|
||||
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
|
||||
DEFINES_MODULE = YES;
|
||||
@@ -4729,7 +4729,7 @@
|
||||
baseConfigurationReference = 56B8F49A1B4E2F3600C24296 /* GRDB.xcconfig */;
|
||||
buildSettings = {
|
||||
APPLICATION_EXTENSION_API_ONLY = YES;
|
||||
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
|
||||
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "";
|
||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||
DEFINES_MODULE = YES;
|
||||
DYLIB_COMPATIBILITY_VERSION = 1;
|
||||
@@ -4751,7 +4751,7 @@
|
||||
baseConfigurationReference = 56B8F49A1B4E2F3600C24296 /* GRDB.xcconfig */;
|
||||
buildSettings = {
|
||||
APPLICATION_EXTENSION_API_ONLY = YES;
|
||||
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
|
||||
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "";
|
||||
COPY_PHASE_STRIP = NO;
|
||||
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
|
||||
DEFINES_MODULE = YES;
|
||||
@@ -4969,7 +4969,7 @@
|
||||
buildSettings = {
|
||||
APPLICATION_EXTENSION_API_ONLY = YES;
|
||||
CLANG_ANALYZER_NONNULL = YES;
|
||||
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
|
||||
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "";
|
||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||
DEFINES_MODULE = YES;
|
||||
DYLIB_COMPATIBILITY_VERSION = 1;
|
||||
@@ -4992,7 +4992,7 @@
|
||||
buildSettings = {
|
||||
APPLICATION_EXTENSION_API_ONLY = YES;
|
||||
CLANG_ANALYZER_NONNULL = YES;
|
||||
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
|
||||
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "";
|
||||
COPY_PHASE_STRIP = NO;
|
||||
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
|
||||
DEFINES_MODULE = YES;
|
||||
|
||||
@@ -428,10 +428,10 @@ public final class ColumnDefinition {
|
||||
private var primaryKey: (conflictResolution: SQLConflictResolution?, autoincrement: Bool)?
|
||||
private var notNullConflictResolution: SQLConflictResolution?
|
||||
private var uniqueConflictResolution: SQLConflictResolution?
|
||||
private var checkExpression: _SQLExpression?
|
||||
private var checkConstraints: [_SQLExpression] = []
|
||||
private var foreignKeyConstraints: [(table: String, column: String?, deleteAction: SQLForeignKeyAction?, updateAction: SQLForeignKeyAction?, deferred: Bool)] = []
|
||||
private var defaultExpression: _SQLExpression?
|
||||
private var collationName: String?
|
||||
private var reference: (table: String, column: String?, deleteAction: SQLForeignKeyAction?, updateAction: SQLForeignKeyAction?, deferred: Bool)?
|
||||
|
||||
init(name: String, type: SQLColumnType) {
|
||||
self.name = name
|
||||
@@ -501,7 +501,7 @@ public final class ColumnDefinition {
|
||||
/// represents the defined column, and returns the expression to check.
|
||||
/// - returns: Self so that you can further refine the column definition.
|
||||
@discardableResult public func check(_ condition: @noescape (Column) -> SQLExpressible) -> Self {
|
||||
checkExpression = condition(Column(name)).sqlExpression
|
||||
checkConstraints.append(condition(Column(name)).sqlExpression)
|
||||
return self
|
||||
}
|
||||
|
||||
@@ -516,7 +516,7 @@ public final class ColumnDefinition {
|
||||
/// - parameter sql: An SQL snippet.
|
||||
/// - returns: Self so that you can further refine the column definition.
|
||||
@discardableResult public func check(sql: String) -> Self {
|
||||
checkExpression = _SQLExpression.sqlLiteral(sql, nil)
|
||||
checkConstraints.append(_SQLExpression.sqlLiteral(sql, nil))
|
||||
return self
|
||||
}
|
||||
|
||||
@@ -598,7 +598,7 @@ public final class ColumnDefinition {
|
||||
/// See https://www.sqlite.org/foreignkeys.html#fk_deferred.
|
||||
/// - returns: Self so that you can further refine the column definition.
|
||||
@discardableResult public func references(_ table: String, column: String? = nil, onDelete deleteAction: SQLForeignKeyAction? = nil, onUpdate updateAction: SQLForeignKeyAction? = nil, deferred: Bool = false) -> Self {
|
||||
reference = (table: table, column: column, deleteAction: deleteAction, updateAction: updateAction, deferred: deferred)
|
||||
foreignKeyConstraints.append((table: table, column: column, deleteAction: deleteAction, updateAction: updateAction, deferred: deferred))
|
||||
return self
|
||||
}
|
||||
|
||||
@@ -638,10 +638,10 @@ public final class ColumnDefinition {
|
||||
chunks.append(conflictResolution.rawValue)
|
||||
}
|
||||
|
||||
if let checkExpression = checkExpression {
|
||||
for checkConstraint in checkConstraints {
|
||||
chunks.append("CHECK")
|
||||
var arguments: StatementArguments? = nil // nil so that checkExpression.sql(&arguments) embeds literals
|
||||
chunks.append("(" + checkExpression.sql(&arguments) + ")")
|
||||
var arguments: StatementArguments? = nil // nil so that checkConstraint.sql(&arguments) embeds literals
|
||||
chunks.append("(" + checkConstraint.sql(&arguments) + ")")
|
||||
}
|
||||
|
||||
if let defaultExpression = defaultExpression {
|
||||
@@ -655,7 +655,7 @@ public final class ColumnDefinition {
|
||||
chunks.append(collationName)
|
||||
}
|
||||
|
||||
if let (table, column, deleteAction, updateAction, deferred) = reference {
|
||||
for (table, column, deleteAction, updateAction, deferred) in foreignKeyConstraints {
|
||||
chunks.append("REFERENCES")
|
||||
if let column = column {
|
||||
chunks.append("\(table.quotedDatabaseIdentifier)(\(column.quotedDatabaseIdentifier))")
|
||||
@@ -704,7 +704,7 @@ private struct IndexDefinition {
|
||||
chunks.append("\(table.quotedDatabaseIdentifier)(\((columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
|
||||
if let condition = condition {
|
||||
chunks.append("WHERE")
|
||||
var arguments: StatementArguments? = nil // nil so that checkExpression.sql(&arguments) embeds literals
|
||||
var arguments: StatementArguments? = nil // nil so that condition.sql(&arguments) embeds literals
|
||||
chunks.append(condition.sql(&arguments))
|
||||
}
|
||||
return chunks.joined(separator: " ")
|
||||
|
||||
@@ -10,7 +10,7 @@ public final class FetchedRecordsController<Record: RowConvertible> {
|
||||
|
||||
// MARK: - Initialization
|
||||
|
||||
/// Returns a fetched records controller initialized from a SQL query and
|
||||
/// Creates a fetched records controller initialized from a SQL query and
|
||||
/// its eventual arguments.
|
||||
///
|
||||
/// let controller = FetchedRecordsController<Wine>(
|
||||
@@ -40,7 +40,7 @@ public final class FetchedRecordsController<Record: RowConvertible> {
|
||||
self.init(databaseWriter, request: SQLFetchRequest(sql: sql, arguments: arguments, adapter: adapter), queue: queue, isSameRecord: isSameRecord)
|
||||
}
|
||||
|
||||
/// Returns a fetched records controller initialized from a fetch request
|
||||
/// Creates a fetched records controller initialized from a fetch request
|
||||
/// from the [Query Interface](https://github.com/groue/GRDB.swift#the-query-interface).
|
||||
///
|
||||
/// let request = Wine.order(Column("name"))
|
||||
@@ -363,13 +363,9 @@ extension FetchedRecordsController where Record: TableMapping {
|
||||
|
||||
// MARK: - Initialization
|
||||
|
||||
/// Returns a fetched records controller initialized from a SQL query and
|
||||
/// Creates a fetched records controller initialized from a SQL query and
|
||||
/// its eventual arguments.
|
||||
///
|
||||
/// The type of the fetched records must be a subclass of the Record class,
|
||||
/// or adopt both RowConvertible, and Persistable or MutablePersistable
|
||||
/// protocols.
|
||||
///
|
||||
/// let controller = FetchedRecordsController<Wine>(
|
||||
/// dbQueue,
|
||||
/// sql: "SELECT * FROM wines WHERE color = ? ORDER BY name",
|
||||
@@ -395,7 +391,8 @@ extension FetchedRecordsController where Record: TableMapping {
|
||||
self.init(databaseWriter, request: SQLFetchRequest(sql: sql, arguments: arguments, adapter: adapter), queue: queue, compareRecordsByPrimaryKey: compareRecordsByPrimaryKey)
|
||||
}
|
||||
|
||||
/// Returns a fetched records controller initialized from a fetch request.
|
||||
/// Creates a fetched records controller initialized from a fetch request.
|
||||
/// from the [Query Interface](https://github.com/groue/GRDB.swift#the-query-interface).
|
||||
///
|
||||
/// let request = Wine.order(Column("name"))
|
||||
/// let controller = FetchedRecordsController<Wine>(
|
||||
|
||||
@@ -191,7 +191,7 @@ public extension MutablePersistable {
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter columns: The columns to update.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
/// PersistenceError.NotFound is thrown if the primary key does not
|
||||
/// PersistenceError.recordNotFound is thrown if the primary key does not
|
||||
/// match any row in the database.
|
||||
func update(_ db: Database, columns: Set<String>) throws {
|
||||
try performUpdate(db, columns: columns)
|
||||
@@ -202,7 +202,7 @@ public extension MutablePersistable {
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter columns: The columns to update.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
/// PersistenceError.NotFound is thrown if the primary key does not
|
||||
/// PersistenceError.recordNotFound is thrown if the primary key does not
|
||||
/// match any row in the database.
|
||||
func update<Sequence: Swift.Sequence>(_ db: Database, columns: Sequence) throws where Sequence.Iterator.Element == Column {
|
||||
try update(db, columns: Set(columns.map { $0.name }))
|
||||
@@ -213,7 +213,7 @@ public extension MutablePersistable {
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter columns: The columns to update.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
/// PersistenceError.NotFound is thrown if the primary key does not
|
||||
/// PersistenceError.recordNotFound is thrown if the primary key does not
|
||||
/// match any row in the database.
|
||||
func update<Sequence: Swift.Sequence>(_ db: Database, columns: Sequence) throws where Sequence.Iterator.Element == String {
|
||||
try update(db, columns: Set(columns))
|
||||
@@ -223,7 +223,7 @@ public extension MutablePersistable {
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
/// PersistenceError.NotFound is thrown if the primary key does not
|
||||
/// PersistenceError.recordNotFound is thrown if the primary key does not
|
||||
/// match any row in the database.
|
||||
func update(_ db: Database) throws {
|
||||
let databaseTableName = self.dynamicType.databaseTableName
|
||||
@@ -279,9 +279,9 @@ public extension MutablePersistable {
|
||||
/// implementation of insert(). They should not provide their own
|
||||
/// implementation of performInsert().
|
||||
mutating func performInsert(_ db: Database) throws {
|
||||
let dataMapper = DataMapper(db, self)
|
||||
try dataMapper.insertStatement().execute()
|
||||
didInsert(with: db.lastInsertedRowID, for: dataMapper.primaryKey?.rowIDColumn)
|
||||
let dao = DAO(db, self)
|
||||
try dao.insertStatement().execute()
|
||||
didInsert(with: db.lastInsertedRowID, for: dao.primaryKey?.rowIDColumn)
|
||||
}
|
||||
|
||||
/// Don't invoke this method directly: it is an internal method for types
|
||||
@@ -295,10 +295,14 @@ public extension MutablePersistable {
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter columns: The columns to update.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
/// PersistenceError.NotFound is thrown if the primary key does not
|
||||
/// PersistenceError.recordNotFound is thrown if the primary key does not
|
||||
/// match any row in the database.
|
||||
func performUpdate(_ db: Database, columns: Set<String>) throws {
|
||||
try DataMapper(db, self).updateStatement(columns: columns).execute()
|
||||
guard let statement = DAO(db, self).updateStatement(columns: columns) else {
|
||||
// Nil primary key
|
||||
throw PersistenceError.recordNotFound(self)
|
||||
}
|
||||
try statement.execute()
|
||||
if db.changesCount == 0 {
|
||||
throw PersistenceError.recordNotFound(self)
|
||||
}
|
||||
@@ -341,7 +345,11 @@ public extension MutablePersistable {
|
||||
/// their implementation of delete(). They should not provide their own
|
||||
/// implementation of performDelete().
|
||||
func performDelete(_ db: Database) throws -> Bool {
|
||||
try DataMapper(db, self).deleteStatement().execute()
|
||||
guard let statement = DAO(db, self).deleteStatement() else {
|
||||
// Nil primary key
|
||||
return false
|
||||
}
|
||||
try statement.execute()
|
||||
return db.changesCount > 0
|
||||
}
|
||||
|
||||
@@ -353,7 +361,11 @@ public extension MutablePersistable {
|
||||
/// their implementation of exists(). They should not provide their own
|
||||
/// implementation of performExists().
|
||||
func performExists(_ db: Database) -> Bool {
|
||||
return (Row.fetchOne(DataMapper(db, self).existsStatement()) != nil)
|
||||
guard let statement = DAO(db, self).existsStatement() else {
|
||||
// Nil primary key
|
||||
return false
|
||||
}
|
||||
return Row.fetchOne(statement) != nil
|
||||
}
|
||||
|
||||
}
|
||||
@@ -461,9 +473,9 @@ public extension Persistable {
|
||||
/// implementation of insert(). They should not provide their own
|
||||
/// implementation of performInsert().
|
||||
func performInsert(_ db: Database) throws {
|
||||
let dataMapper = DataMapper(db, self)
|
||||
try dataMapper.insertStatement().execute()
|
||||
didInsert(with: db.lastInsertedRowID, for: dataMapper.primaryKey?.rowIDColumn)
|
||||
let dao = DAO(db, self)
|
||||
try dao.insertStatement().execute()
|
||||
didInsert(with: db.lastInsertedRowID, for: dao.primaryKey?.rowIDColumn)
|
||||
}
|
||||
|
||||
/// Don't invoke this method directly: it is an internal method for types
|
||||
@@ -497,20 +509,20 @@ public extension Persistable {
|
||||
}
|
||||
|
||||
|
||||
// MARK: - DataMapper
|
||||
// MARK: - DAO
|
||||
|
||||
/// DataMapper takes care of Persistable CRUD
|
||||
final class DataMapper {
|
||||
/// DAO takes care of Persistable CRUD
|
||||
final class DAO {
|
||||
|
||||
/// The database
|
||||
let db: Database
|
||||
|
||||
/// The persistable
|
||||
let persistable: MutablePersistable
|
||||
/// The record
|
||||
let record: MutablePersistable
|
||||
|
||||
/// DataMapper keeps a copy the persistable's persistentDictionary, so
|
||||
/// that this dictionary is built once whatever the database operation.
|
||||
/// It is guaranteed to have at least one (key, value) pair.
|
||||
/// DAO keeps a copy the record's persistentDictionary, so that this
|
||||
/// dictionary is built once whatever the database operation. It is
|
||||
/// guaranteed to have at least one (key, value) pair.
|
||||
let persistentDictionary: [String: DatabaseValueConvertible?]
|
||||
|
||||
/// The table name
|
||||
@@ -519,17 +531,17 @@ final class DataMapper {
|
||||
/// The table primary key
|
||||
let primaryKey: PrimaryKeyInfo?
|
||||
|
||||
init(_ db: Database, _ persistable: MutablePersistable) {
|
||||
init(_ db: Database, _ record: MutablePersistable) {
|
||||
// Fail early if database table does not exist.
|
||||
let databaseTableName = persistable.dynamicType.databaseTableName
|
||||
let databaseTableName = record.dynamicType.databaseTableName
|
||||
let primaryKey = try! db.primaryKey(databaseTableName)
|
||||
|
||||
// Fail early if persistentDictionary is empty
|
||||
let persistentDictionary = persistable.persistentDictionary
|
||||
GRDBPrecondition(persistentDictionary.count > 0, "\(persistable.dynamicType).persistentDictionary: invalid empty dictionary")
|
||||
let persistentDictionary = record.persistentDictionary
|
||||
GRDBPrecondition(persistentDictionary.count > 0, "\(record.dynamicType).persistentDictionary: invalid empty dictionary")
|
||||
|
||||
self.db = db
|
||||
self.persistable = persistable
|
||||
self.record = record
|
||||
self.persistentDictionary = persistentDictionary
|
||||
self.databaseTableName = databaseTableName
|
||||
self.primaryKey = primaryKey
|
||||
@@ -544,17 +556,25 @@ final class DataMapper {
|
||||
return statement
|
||||
}
|
||||
|
||||
func updateStatement(columns: Set<String>) -> UpdateStatement {
|
||||
/// Returns nil if and only if primary key is nil
|
||||
func updateStatement(columns: Set<String>) -> UpdateStatement? {
|
||||
// Fail early if primary key does not resolve to a database row.
|
||||
let primaryKeyColumns = primaryKey?.columns ?? []
|
||||
let primaryKeyValues = databaseValues(for: primaryKeyColumns, inDictionary: persistentDictionary)
|
||||
GRDBPrecondition(primaryKeyValues.contains { !$0.isNull }, "record can not be identified. persistentDictionary must contain non-nil value(s) for the key(s) \(primaryKeyColumns.joined(separator: ","))")
|
||||
guard primaryKeyValues.contains(where: { !$0.isNull }) else { return nil }
|
||||
|
||||
let lowercasePersistentColumns = Set(persistentDictionary.keys.map { $0.lowercased() })
|
||||
let lowercasePrimaryKeyColumns = Set(primaryKeyColumns.map { $0.lowercased() })
|
||||
var updatedColumns: [String] = []
|
||||
for column in columns {
|
||||
let lowercaseColumn = column.lowercased()
|
||||
// Make sure the requested column is present in persistentDictionary
|
||||
GRDBPrecondition(lowercasePersistentColumns.contains(lowercaseColumn), "column \(column) can't be updated because it is missing from persistentDictionary")
|
||||
// Don't update primary key columns
|
||||
guard !lowercasePrimaryKeyColumns.contains(column) else { continue }
|
||||
updatedColumns.append(column)
|
||||
}
|
||||
|
||||
// Don't update primary key columns
|
||||
var updatedColumns = Array(persistentDictionary.keys)
|
||||
.map { $0.lowercased() }
|
||||
.filter { (lowercaseKey: String) in columns.contains { $0.lowercased() == lowercaseKey } }
|
||||
.filter { (lowercaseKey: String) in !primaryKeyColumns.contains { $0.lowercased() == lowercaseKey } }
|
||||
if updatedColumns.isEmpty {
|
||||
// IMPLEMENTATION NOTE
|
||||
//
|
||||
@@ -577,11 +597,12 @@ final class DataMapper {
|
||||
return statement
|
||||
}
|
||||
|
||||
func deleteStatement() -> UpdateStatement {
|
||||
/// Returns nil if and only if primary key is nil
|
||||
func deleteStatement() -> UpdateStatement? {
|
||||
// Fail early if primary key does not resolve to a database row.
|
||||
let primaryKeyColumns = primaryKey?.columns ?? []
|
||||
let primaryKeyValues = databaseValues(for: primaryKeyColumns, inDictionary: persistentDictionary)
|
||||
GRDBPrecondition(primaryKeyValues.contains { !$0.isNull }, "record can not be identified. persistentDictionary must contain non-nil value(s) for the key(s) \(primaryKeyColumns.joined(separator: ","))")
|
||||
guard primaryKeyValues.contains(where: { !$0.isNull }) else { return nil }
|
||||
|
||||
let query = DeleteQuery(
|
||||
tableName: databaseTableName,
|
||||
@@ -591,11 +612,12 @@ final class DataMapper {
|
||||
return statement
|
||||
}
|
||||
|
||||
func existsStatement() -> SelectStatement {
|
||||
/// Returns nil if and only if primary key is nil
|
||||
func existsStatement() -> SelectStatement? {
|
||||
// Fail early if primary key does not resolve to a database row.
|
||||
let primaryKeyColumns = primaryKey?.columns ?? []
|
||||
let primaryKeyValues = databaseValues(for: primaryKeyColumns, inDictionary: persistentDictionary)
|
||||
GRDBPrecondition(primaryKeyValues.contains { !$0.isNull }, "record can not be identified. persistentDictionary must contain non-nil value(s) for the key(s) \(primaryKeyColumns.joined(separator: ","))")
|
||||
guard primaryKeyValues.contains(where: { !$0.isNull }) else { return nil }
|
||||
|
||||
let query = ExistsQuery(
|
||||
tableName: databaseTableName,
|
||||
|
||||
@@ -215,11 +215,11 @@ public class Record : RowConvertible, TableMapping, Persistable {
|
||||
// So let's provide our custom implementation of insert, which uses the
|
||||
// same persistentDictionary for both insertion, and change tracking.
|
||||
|
||||
let dataMapper = DataMapper(db, self)
|
||||
var persistentDictionary = dataMapper.persistentDictionary
|
||||
try dataMapper.insertStatement().execute()
|
||||
let dao = DAO(db, self)
|
||||
var persistentDictionary = dao.persistentDictionary
|
||||
try dao.insertStatement().execute()
|
||||
let rowID = db.lastInsertedRowID
|
||||
let rowIDColumn = dataMapper.primaryKey?.rowIDColumn
|
||||
let rowIDColumn = dao.primaryKey?.rowIDColumn
|
||||
didInsert(with: rowID, for: rowIDColumn)
|
||||
|
||||
// Update persistentDictionary with inserted id, so that we can
|
||||
@@ -265,14 +265,18 @@ public class Record : RowConvertible, TableMapping, Persistable {
|
||||
//
|
||||
// So let's provide our custom implementation of insert, which uses the
|
||||
// same persistentDictionary for both update, and change tracking.
|
||||
let dataMapper = DataMapper(db, self)
|
||||
try dataMapper.updateStatement(columns: columns).execute()
|
||||
let dao = DAO(db, self)
|
||||
guard let statement = dao.updateStatement(columns: columns) else {
|
||||
// Nil primary key
|
||||
throw PersistenceError.recordNotFound(self)
|
||||
}
|
||||
try statement.execute()
|
||||
if db.changesCount == 0 {
|
||||
throw PersistenceError.recordNotFound(self)
|
||||
}
|
||||
|
||||
// Set hasPersistentChangedValues to false
|
||||
referenceRow = Row(dataMapper.persistentDictionary)
|
||||
referenceRow = Row(dao.persistentDictionary)
|
||||
}
|
||||
|
||||
/// Executes an INSERT or an UPDATE statement so that `self` is saved in
|
||||
|
||||
@@ -3,9 +3,9 @@ GRDB.swift [
|
||||
|
||||
### A Swift application toolkit for SQLite databases.
|
||||
|
||||
**Requirements**: iOS 8.0+ / OSX 10.9+ • Xcode Version 8.0 beta 4 (8S188o) • Swift 3.
|
||||
**Requirements**: iOS 8.0+ / OSX 10.9+ • Xcode Version 8.0 beta 5 (8S193k) • Swift 3.
|
||||
|
||||
The Swift3 branch has no version. It is currently synced with v0.79.0 of the Swift 2.2 [main branch](https://github.com/groue/GRDB.swift).
|
||||
The Swift3 branch has no version. It is currently synced with v0.79.1 of the Swift 2.2 [main branch](https://github.com/groue/GRDB.swift).
|
||||
|
||||
Follow [@groue](http://twitter.com/groue) on Twitter for release announcements and usage tips.
|
||||
|
||||
@@ -302,7 +302,7 @@ let dbQueue = try DatabaseQueue(
|
||||
configuration: config)
|
||||
```
|
||||
|
||||
See [Configuration](http://cocoadocs.org/docsets/GRDB.swift/0.79.0/Structs/Configuration.html) for more details.
|
||||
See [Configuration](http://cocoadocs.org/docsets/GRDB.swift/0.79.1/Structs/Configuration.html) for more details.
|
||||
|
||||
|
||||
## Database Pools
|
||||
@@ -382,7 +382,7 @@ let dbPool = try DatabasePool(
|
||||
configuration: config)
|
||||
```
|
||||
|
||||
See [Configuration](http://cocoadocs.org/docsets/GRDB.swift/0.79.0/Structs/Configuration.html) for more details.
|
||||
See [Configuration](http://cocoadocs.org/docsets/GRDB.swift/0.79.1/Structs/Configuration.html) for more details.
|
||||
|
||||
|
||||
Database pools are more memory-hungry than database queues. See [Memory Management](#memory-management) for more information.
|
||||
@@ -909,18 +909,27 @@ Here is the support provided by GRDB for the various [date formats](https://www.
|
||||
|
||||
#### Date
|
||||
|
||||
**GRDB stores Date using the format "yyyy-MM-dd HH:mm:ss.SSS" in the UTC time zone.** It is precise to the millisecond.
|
||||
|
||||
This format may not fit your needs. We provide below some sample code for [storing dates as timestamps](#custom-value-types) that you can adapt for your application.
|
||||
|
||||
Date can be stored and fetched from the database just like other [value types](#values):
|
||||
**Date** can be stored and fetched from the database just like other [value types](#values):
|
||||
|
||||
```swift
|
||||
try db.execute(
|
||||
"INSERT INTO persons (creationDate, ...) VALUES (?, ...)",
|
||||
arguments: [Date(), ...])
|
||||
|
||||
let creationDate: Date = row.value(named: "creationDate")
|
||||
```
|
||||
|
||||
Dates are stored using the format "YYYY-MM-DD HH:MM:SS.SSS" in the UTC time zone. It is precise to the millisecond.
|
||||
|
||||
> :point_up: **Note**: this format was chosen because it is the only format that is:
|
||||
>
|
||||
> - Comparable (`ORDER BY date` works)
|
||||
> - Comparable with the SQLite keyword NOW (`WHERE date > NOW` works)
|
||||
> - Able to feed [SQLite date & time functions](https://www.sqlite.org/lang_datefunc.html)
|
||||
> - Precise enough
|
||||
>
|
||||
> Yet this format may not fit your needs. For example, you may want to store dates as timestamps. In this case, store and load Doubles instead of Date, and perform the required conversions.
|
||||
|
||||
|
||||
#### DateComponents
|
||||
|
||||
@@ -1167,8 +1176,6 @@ The `databaseValue` property returns [DatabaseValue](#databasevalue), a type tha
|
||||
|
||||
The `fromDatabaseValue()` factory method returns an instance of your custom type if the databaseValue contains a suitable value. If the databaseValue does not contain a suitable value, such as "foo" for Date, the method returns nil.
|
||||
|
||||
As an example, see [DatabaseTimestamp.playground](Playgrounds/DatabaseTimestamp.playground/Contents.swift): it shows how to store dates as timestamps, unlike the built-in [Date](#date-and-datecomponents).
|
||||
|
||||
|
||||
## Prepared Statements
|
||||
|
||||
@@ -1470,10 +1477,10 @@ for person in Person.fetch(db, sql, adapter: adapter) {
|
||||
|
||||
For more information about row adapters, see the documentation of:
|
||||
|
||||
- [RowAdapter](http://cocoadocs.org/docsets/GRDB.swift/0.79.0/Protocols/RowAdapter.html): the protocol that lets you define your custom row adapters
|
||||
- [ColumnMapping](http://cocoadocs.org/docsets/GRDB.swift/0.79.0/Structs/ColumnMapping.html): a row adapter that renames row columns
|
||||
- [SuffixRowAdapter](http://cocoadocs.org/docsets/GRDB.swift/0.79.0/Structs/SuffixRowAdapter.html): a row adapter that hides the first columns of a row
|
||||
- [ScopeAdapter](http://cocoadocs.org/docsets/GRDB.swift/0.79.0/Structs/ScopeAdapter.html): the row adapter that groups several adapters together to define scopes
|
||||
- [RowAdapter](http://cocoadocs.org/docsets/GRDB.swift/0.79.1/Protocols/RowAdapter.html): the protocol that lets you define your custom row adapters
|
||||
- [ColumnMapping](http://cocoadocs.org/docsets/GRDB.swift/0.79.1/Structs/ColumnMapping.html): a row adapter that renames row columns
|
||||
- [SuffixRowAdapter](http://cocoadocs.org/docsets/GRDB.swift/0.79.1/Structs/SuffixRowAdapter.html): a row adapter that hides the first columns of a row
|
||||
- [ScopeAdapter](http://cocoadocs.org/docsets/GRDB.swift/0.79.1/Structs/ScopeAdapter.html): the row adapter that groups several adapters together to define scopes
|
||||
|
||||
|
||||
## Raw SQLite Pointers
|
||||
@@ -3335,7 +3342,7 @@ do {
|
||||
```swift
|
||||
do {
|
||||
try person.update(db)
|
||||
} catch PersistenceError.NotFound {
|
||||
} catch PersistenceError.recordNotFound {
|
||||
// There was nothing to update
|
||||
}
|
||||
```
|
||||
@@ -3623,7 +3630,7 @@ let count2 = dbQueue.inDatabase { db in
|
||||
|
||||
SQLite concurrency is a wiiide topic.
|
||||
|
||||
First have a detailed look at the full API of [DatabaseQueue](http://cocoadocs.org/docsets/GRDB.swift/0.79.0/Classes/DatabaseQueue.html) and [DatabasePool](http://cocoadocs.org/docsets/GRDB.swift/0.79.0/Classes/DatabasePool.html). Both adopt the [DatabaseReader](http://cocoadocs.org/docsets/GRDB.swift/0.79.0/Protocols/DatabaseReader.html) and [DatabaseWriter](http://cocoadocs.org/docsets/GRDB.swift/0.79.0/Protocols/DatabaseWriter.html) protocols, so that you can write code that targets both classes.
|
||||
First have a detailed look at the full API of [DatabaseQueue](http://cocoadocs.org/docsets/GRDB.swift/0.79.1/Classes/DatabaseQueue.html) and [DatabasePool](http://cocoadocs.org/docsets/GRDB.swift/0.79.1/Classes/DatabasePool.html). Both adopt the [DatabaseReader](http://cocoadocs.org/docsets/GRDB.swift/0.79.1/Protocols/DatabaseReader.html) and [DatabaseWriter](http://cocoadocs.org/docsets/GRDB.swift/0.79.1/Protocols/DatabaseWriter.html) protocols, so that you can write code that targets both classes.
|
||||
|
||||
If the built-in queues and pools do not fit your needs, or if you can not guarantee that a single queue or pool is accessing your database file, you may have a look at:
|
||||
|
||||
@@ -3948,7 +3955,6 @@ Sample Code
|
||||
- The [Documentation](#documentation) is full of GRDB snippets.
|
||||
- [GRDBDemoiOS](DemoApps/GRDBDemoiOS): A sample iOS application.
|
||||
- Check `GRDB.xcworkspace`: it contains GRDB-enabled playgrounds to play with.
|
||||
- How to read and write Date as timestamp: [DatabaseTimestamp.playground](Playgrounds/DatabaseTimestamp.playground/Contents.swift)
|
||||
- How to synchronize a database table with a JSON payload: [JSONSynchronization.playground](Playgrounds/JSONSynchronization.playground/Contents.swift)
|
||||
- A class that behaves like NSUserDefaults, but backed by SQLite: [UserDefaults.playground](Playgrounds/UserDefaults.playground/Contents.swift)
|
||||
- How to notify view controllers of database changes: [TableChangeObserver.swift](https://gist.github.com/groue/2e21172719e634657dfd)
|
||||
|
||||
+1
-1
@@ -15,7 +15,7 @@
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>FMWK</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>0.79.0</string>
|
||||
<string>0.79.1</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
|
||||
@@ -4,6 +4,9 @@
|
||||
- [ ] Swift3: check .autoreleaseWorkItem option in GCD Queue creation
|
||||
- [ ] Swift3: move database event filtering into the TransactionObserver protocol
|
||||
- [ ] Fatal Error when MutablePersistable.update(_:columns:) is given columns that do not exist in the database.
|
||||
- [ ] @hdlj: Extensibility of the Query Interface
|
||||
- [ ] @hdlj: FetchedRecordsController throttling
|
||||
- [ ] @hdlj: Check RAM pressure
|
||||
- [ ] What is the behavior inTransaction and inSavepoint behaviors in case of commit error? Code looks like we do not rollback, leaving the app in a weird state (out of Swift transaction block with a SQLite transaction that may still be opened).
|
||||
- [ ] GRDBCipher: remove limitations on iOS or OS X versions
|
||||
- [ ] FetchedRecordsController: take inspiration from https://github.com/jflinter/Dwifft
|
||||
@@ -25,7 +28,6 @@
|
||||
|
||||
Not sure
|
||||
|
||||
- [ ] Record.exists(db) should return false when primary key is nil
|
||||
- [X] Have Row adopt LiteralDictionaryConvertible
|
||||
- [ ] ... allowing non unique column names
|
||||
- [ ] Remove DatabaseValue.value()
|
||||
|
||||
@@ -10,11 +10,12 @@ import XCTest
|
||||
private struct MutablePersistablePerson : MutablePersistable {
|
||||
var id: Int64?
|
||||
var name: String?
|
||||
var age: Int?
|
||||
|
||||
static let databaseTableName = "persons"
|
||||
|
||||
var persistentDictionary: [String: DatabaseValueConvertible?] {
|
||||
return ["id": id, "name": name]
|
||||
return ["id": id, "name": name, "age": age]
|
||||
}
|
||||
|
||||
mutating func didInsert(with rowID: Int64, for column: String?) {
|
||||
@@ -92,7 +93,8 @@ class MutablePersistableTests: GRDBTestCase {
|
||||
try db.execute(
|
||||
"CREATE TABLE persons (" +
|
||||
"id INTEGER PRIMARY KEY, " +
|
||||
"name NOT NULL " +
|
||||
"name NOT NULL, " +
|
||||
"age INTEGER" +
|
||||
")")
|
||||
try db.execute(
|
||||
"CREATE TABLE countries (" +
|
||||
@@ -110,7 +112,7 @@ class MutablePersistableTests: GRDBTestCase {
|
||||
assertNoError {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
var person = MutablePersistablePerson(id: nil, name: "Arthur")
|
||||
var person = MutablePersistablePerson(id: nil, name: "Arthur", age: 24)
|
||||
try person.insert(db)
|
||||
|
||||
let rows = Row.fetchAll(db, "SELECT * FROM persons")
|
||||
@@ -125,9 +127,9 @@ class MutablePersistableTests: GRDBTestCase {
|
||||
assertNoError {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
var person1 = MutablePersistablePerson(id: nil, name: "Arthur")
|
||||
var person1 = MutablePersistablePerson(id: nil, name: "Arthur", age: 24)
|
||||
try person1.insert(db)
|
||||
var person2 = MutablePersistablePerson(id: nil, name: "Barbara")
|
||||
var person2 = MutablePersistablePerson(id: nil, name: "Barbara", age: 24)
|
||||
try person2.insert(db)
|
||||
|
||||
person1.name = "Craig"
|
||||
@@ -147,9 +149,9 @@ class MutablePersistableTests: GRDBTestCase {
|
||||
assertNoError {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
var person1 = MutablePersistablePerson(id: nil, name: "Arthur")
|
||||
var person1 = MutablePersistablePerson(id: nil, name: "Arthur", age: 24)
|
||||
try person1.insert(db)
|
||||
var person2 = MutablePersistablePerson(id: nil, name: "Barbara")
|
||||
var person2 = MutablePersistablePerson(id: nil, name: "Barbara", age: 36)
|
||||
try person2.insert(db)
|
||||
|
||||
do {
|
||||
@@ -160,32 +162,39 @@ class MutablePersistableTests: GRDBTestCase {
|
||||
XCTAssertEqual(rows.count, 2)
|
||||
XCTAssertEqual(rows[0].value(named: "id") as Int64, person1.id!)
|
||||
XCTAssertEqual(rows[0].value(named: "name") as String, "Arthur")
|
||||
XCTAssertEqual(rows[0].value(named: "age") as Int, 24)
|
||||
XCTAssertEqual(rows[1].value(named: "id") as Int64, person2.id!)
|
||||
XCTAssertEqual(rows[1].value(named: "name") as String, "Barbara")
|
||||
XCTAssertEqual(rows[1].value(named: "age") as Int, 36)
|
||||
}
|
||||
|
||||
do {
|
||||
person1.name = "Craig"
|
||||
person1.age = 25
|
||||
try person1.update(db, columns: [Column("name")])
|
||||
|
||||
let rows = Row.fetchAll(db, "SELECT * FROM persons ORDER BY id")
|
||||
XCTAssertEqual(rows.count, 2)
|
||||
XCTAssertEqual(rows[0].value(named: "id") as Int64, person1.id!)
|
||||
XCTAssertEqual(rows[0].value(named: "name") as String, "Craig")
|
||||
XCTAssertEqual(rows[0].value(named: "age") as Int, 24)
|
||||
XCTAssertEqual(rows[1].value(named: "id") as Int64, person2.id!)
|
||||
XCTAssertEqual(rows[1].value(named: "name") as String, "Barbara")
|
||||
XCTAssertEqual(rows[1].value(named: "age") as Int, 36)
|
||||
}
|
||||
|
||||
do {
|
||||
person1.name = "David"
|
||||
try person1.update(db, columns: ["age"])
|
||||
try person1.update(db, columns: ["AgE"]) // case insensitivity
|
||||
|
||||
let rows = Row.fetchAll(db, "SELECT * FROM persons ORDER BY id")
|
||||
XCTAssertEqual(rows.count, 2)
|
||||
XCTAssertEqual(rows[0].value(named: "id") as Int64, person1.id!)
|
||||
XCTAssertEqual(rows[0].value(named: "name") as String, "Craig")
|
||||
XCTAssertEqual(rows[0].value(named: "age") as Int, 25)
|
||||
XCTAssertEqual(rows[1].value(named: "id") as Int64, person2.id!)
|
||||
XCTAssertEqual(rows[1].value(named: "name") as String, "Barbara")
|
||||
XCTAssertEqual(rows[1].value(named: "age") as Int, 36)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -195,7 +204,7 @@ class MutablePersistableTests: GRDBTestCase {
|
||||
assertNoError {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
var person1 = MutablePersistablePerson(id: nil, name: "Arthur")
|
||||
var person1 = MutablePersistablePerson(id: nil, name: "Arthur", age: 24)
|
||||
try person1.save(db)
|
||||
|
||||
var rows = Row.fetchAll(db, "SELECT * FROM persons")
|
||||
@@ -203,7 +212,7 @@ class MutablePersistableTests: GRDBTestCase {
|
||||
XCTAssertEqual(rows[0].value(named: "id") as Int64, person1.id!)
|
||||
XCTAssertEqual(rows[0].value(named: "name") as String, "Arthur")
|
||||
|
||||
var person2 = MutablePersistablePerson(id: nil, name: "Barbara")
|
||||
var person2 = MutablePersistablePerson(id: nil, name: "Barbara", age: 24)
|
||||
try person2.save(db)
|
||||
|
||||
person1.name = "Craig"
|
||||
@@ -233,9 +242,9 @@ class MutablePersistableTests: GRDBTestCase {
|
||||
assertNoError {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
var person1 = MutablePersistablePerson(id: nil, name: "Arthur")
|
||||
var person1 = MutablePersistablePerson(id: nil, name: "Arthur", age: 24)
|
||||
try person1.insert(db)
|
||||
var person2 = MutablePersistablePerson(id: nil, name: "Barbara")
|
||||
var person2 = MutablePersistablePerson(id: nil, name: "Barbara", age: 24)
|
||||
try person2.insert(db)
|
||||
|
||||
// TODO: test delete return value
|
||||
@@ -253,7 +262,7 @@ class MutablePersistableTests: GRDBTestCase {
|
||||
assertNoError {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
var person = MutablePersistablePerson(id: nil, name: "Arthur")
|
||||
var person = MutablePersistablePerson(id: nil, name: "Arthur", age: 24)
|
||||
try person.insert(db)
|
||||
XCTAssertTrue(person.exists(db))
|
||||
|
||||
|
||||
@@ -138,6 +138,21 @@ class PrimaryKeyMultipleTests: GRDBTestCase {
|
||||
|
||||
// MARK: - Update
|
||||
|
||||
func testUpdateWithNilPrimaryKeyThrowsRecordNotFound() {
|
||||
assertNoError {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record = Citizenship(personName: nil, countryName: nil, native: true)
|
||||
do {
|
||||
try record.update(db)
|
||||
XCTFail("Expected PersistenceError.recordNotFound")
|
||||
} catch PersistenceError.recordNotFound {
|
||||
// Expected PersistenceError.recordNotFound
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testUpdateWithNotNilPrimaryKeyThatDoesNotMatchAnyRowThrowsRecordNotFound() {
|
||||
assertNoError {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
@@ -275,6 +290,17 @@ class PrimaryKeyMultipleTests: GRDBTestCase {
|
||||
|
||||
// MARK: - Delete
|
||||
|
||||
func testDeleteWithNilPrimaryKey() {
|
||||
assertNoError {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record = Citizenship(personName: nil, countryName: nil, native: true)
|
||||
let deleted = try record.delete(db)
|
||||
XCTAssertFalse(deleted)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testDeleteWithNotNilPrimaryKeyThatDoesNotMatchAnyRowDoesNothing() {
|
||||
assertNoError {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
@@ -394,6 +420,16 @@ class PrimaryKeyMultipleTests: GRDBTestCase {
|
||||
|
||||
// MARK: - Exists
|
||||
|
||||
func testExistsWithNilPrimaryKeyReturnsFalse() {
|
||||
assertNoError {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
dbQueue.inDatabase { db in
|
||||
let record = Citizenship(personName: nil, countryName: nil, native: true)
|
||||
XCTAssertFalse(record.exists(db))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testExistsWithNotNilPrimaryKeyThatDoesNotMatchAnyRowReturnsFalse() {
|
||||
assertNoError {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
@@ -197,6 +197,21 @@ class PrimaryKeyRowIDTests: GRDBTestCase {
|
||||
|
||||
// MARK: - Update
|
||||
|
||||
func testUpdateWithNilPrimaryKeyThrowsRecordNotFound() {
|
||||
assertNoError {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record = Person(id: nil, name: "Arthur")
|
||||
do {
|
||||
try record.update(db)
|
||||
XCTFail("Expected PersistenceError.recordNotFound")
|
||||
} catch PersistenceError.recordNotFound {
|
||||
// Expected PersistenceError.recordNotFound
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testUpdateWithNotNilPrimaryKeyThatDoesNotMatchAnyRowThrowsRecordNotFound() {
|
||||
assertNoError {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
@@ -340,6 +355,17 @@ class PrimaryKeyRowIDTests: GRDBTestCase {
|
||||
|
||||
// MARK: - Delete
|
||||
|
||||
func testDeleteWithNilPrimaryKey() {
|
||||
assertNoError {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record = Person(id: nil, name: "Arthur")
|
||||
let deleted = try record.delete(db)
|
||||
XCTAssertFalse(deleted)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testDeleteWithNotNilPrimaryKeyThatDoesNotMatchAnyRowDoesNothing() {
|
||||
assertNoError {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
@@ -537,6 +563,16 @@ class PrimaryKeyRowIDTests: GRDBTestCase {
|
||||
|
||||
// MARK: - Exists
|
||||
|
||||
func testExistsWithNilPrimaryKeyReturnsFalse() {
|
||||
assertNoError {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
dbQueue.inDatabase { db in
|
||||
let record = Person(id: nil, name: "Arthur")
|
||||
XCTAssertFalse(record.exists(db))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testExistsWithNotNilPrimaryKeyThatDoesNotMatchAnyRowReturnsFalse() {
|
||||
assertNoError {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
@@ -129,6 +129,21 @@ class PrimaryKeySingleTests: GRDBTestCase {
|
||||
|
||||
// MARK: - Update
|
||||
|
||||
func testUpdateWithNilPrimaryKeyThrowsRecordNotFound() {
|
||||
assertNoError {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record = Pet(UUID: nil, name: "Bobby")
|
||||
do {
|
||||
try record.update(db)
|
||||
XCTFail("Expected PersistenceError.recordNotFound")
|
||||
} catch PersistenceError.recordNotFound {
|
||||
// Expected PersistenceError.recordNotFound
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testUpdateWithNotNilPrimaryKeyThatDoesNotMatchAnyRowThrowsRecordNotFound() {
|
||||
assertNoError {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
@@ -266,6 +281,17 @@ class PrimaryKeySingleTests: GRDBTestCase {
|
||||
|
||||
// MARK: - Delete
|
||||
|
||||
func testDeleteWithNilPrimaryKey() {
|
||||
assertNoError {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let record = Pet(UUID: nil, name: "Bobby")
|
||||
let deleted = try record.delete(db)
|
||||
XCTAssertFalse(deleted)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testDeleteWithNotNilPrimaryKeyThatDoesNotMatchAnyRowDoesNothing() {
|
||||
assertNoError {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
@@ -459,6 +485,16 @@ class PrimaryKeySingleTests: GRDBTestCase {
|
||||
|
||||
// MARK: - Exists
|
||||
|
||||
func testExistsWithNilPrimaryKeyReturnsFalse() {
|
||||
assertNoError {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
dbQueue.inDatabase { db in
|
||||
let record = Pet(UUID: nil, name: "Bobby")
|
||||
XCTAssertFalse(record.exists(db))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testExistsWithNotNilPrimaryKeyThatDoesNotMatchAnyRowReturnsFalse() {
|
||||
assertNoError {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
@@ -135,17 +135,19 @@ class SQLTableBuilderTests: GRDBTestCase {
|
||||
try db.create(table: "test") { t in
|
||||
t.column("a", .integer).check { $0 > 0 }
|
||||
t.column("b", .integer).check(sql: "b <> 2")
|
||||
t.column("c", .integer).check { $0 > 0 }.check { $0 < 10 }
|
||||
}
|
||||
XCTAssertEqual(self.lastSQLQuery,
|
||||
"CREATE TABLE \"test\" (" +
|
||||
"\"a\" INTEGER CHECK ((\"a\" > 0)), " +
|
||||
"\"b\" INTEGER CHECK (b <> 2)" +
|
||||
"\"b\" INTEGER CHECK (b <> 2), " +
|
||||
"\"c\" INTEGER CHECK ((\"c\" > 0)) CHECK ((\"c\" < 10))" +
|
||||
")")
|
||||
|
||||
// Sanity check
|
||||
try db.execute("INSERT INTO test (a, b) VALUES (1, 0)")
|
||||
try db.execute("INSERT INTO test (a, b, c) VALUES (1, 0, 1)")
|
||||
do {
|
||||
try db.execute("INSERT INTO test (a, b) VALUES (0, 0)")
|
||||
try db.execute("INSERT INTO test (a, b, c) VALUES (0, 0, 1)")
|
||||
XCTFail()
|
||||
} catch {
|
||||
}
|
||||
@@ -221,11 +223,13 @@ class SQLTableBuilderTests: GRDBTestCase {
|
||||
try db.create(table: "child") { t in
|
||||
t.column("parentName", .text).references("parent", onDelete: .cascade, onUpdate: .cascade)
|
||||
t.column("parentEmail", .text).references("parent", column: "email", onDelete: .restrict, deferred: true)
|
||||
t.column("weird", .text).references("parent", column: "name").references("parent", column: "email")
|
||||
}
|
||||
XCTAssertEqual(self.lastSQLQuery,
|
||||
"CREATE TABLE \"child\" (" +
|
||||
"\"parentName\" TEXT REFERENCES \"parent\"(\"name\") ON DELETE CASCADE ON UPDATE CASCADE, " +
|
||||
"\"parentEmail\" TEXT REFERENCES \"parent\"(\"email\") ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED" +
|
||||
"\"parentEmail\" TEXT REFERENCES \"parent\"(\"email\") ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED, " +
|
||||
"\"weird\" TEXT REFERENCES \"parent\"(\"name\") REFERENCES \"parent\"(\"email\")" +
|
||||
")")
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user