mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-27 04:14:21 +00:00
Cleanup
This commit is contained in:
1 parent
a1d21a07a1
commit
d70f112014
5 files changed
+80
-101
No files matched your search
@@ -574,11 +574,11 @@ extension Database {
|
||||
arguments: [tableName.lowercaseString]) != nil
|
||||
}
|
||||
|
||||
/// Return the primary key for table named `tableName`, or nil if table does
|
||||
/// not exist.
|
||||
/// Return the primary key for table named `tableName`.
|
||||
/// Crashes if table does not exist.
|
||||
///
|
||||
/// This method is not thread-safe.
|
||||
func primaryKey(tableName: String) -> PrimaryKey? {
|
||||
func primaryKey(tableName: String) -> PrimaryKey {
|
||||
if let primaryKey = primaryKeyCache[tableName] {
|
||||
return primaryKey
|
||||
}
|
||||
@@ -609,8 +609,7 @@ extension Database {
|
||||
|
||||
let columnInfos = self.columnInfos(tableName)
|
||||
guard columnInfos.count > 0 else {
|
||||
// Table does not exist
|
||||
return nil
|
||||
fatalError("no such table: \(tableName)")
|
||||
}
|
||||
|
||||
let primaryKey: PrimaryKey
|
||||
|
||||
@@ -18,6 +18,21 @@ extension PersistenceError : CustomStringConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
private func databaseValue(forColumn column: String, inDictionary dictionary: [String: DatabaseValueConvertible?]) -> DatabaseValue {
|
||||
if let value = dictionary[column] {
|
||||
return value?.databaseValue ?? .Null
|
||||
}
|
||||
let column = column.lowercaseString
|
||||
for (key, value) in dictionary where key.lowercaseString == column {
|
||||
return value?.databaseValue ?? .Null
|
||||
}
|
||||
return .Null
|
||||
}
|
||||
|
||||
private func databaseValues(forColumns columns: [String], inDictionary dictionary: [String: DatabaseValueConvertible?]) -> [DatabaseValue] {
|
||||
return columns.map { databaseValue(forColumn: $0, inDictionary: dictionary) }
|
||||
}
|
||||
|
||||
|
||||
// MARK: - MutableDatabasePersistable
|
||||
|
||||
@@ -194,6 +209,18 @@ public extension MutableDatabasePersistable {
|
||||
|
||||
// MARK: - CRUD Internals
|
||||
|
||||
private func canUpdateInDatabase(db: Database) -> Bool {
|
||||
// Fail early if database table does not exist.
|
||||
let databaseTableName = self.dynamicType.databaseTableName()
|
||||
let primaryKey = db.primaryKey(databaseTableName)
|
||||
|
||||
let persistentDictionary = self.persistentDictionary
|
||||
for column in primaryKey.columns where !databaseValue(forColumn: column, inDictionary: persistentDictionary).isNull {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/// Don't invoke this method directly: it is an internal method for types
|
||||
/// that adopt MutableDatabasePersistable.
|
||||
///
|
||||
@@ -236,7 +263,7 @@ public extension MutableDatabasePersistable {
|
||||
// Make sure we call self.insert and self.update so that classes that
|
||||
// override insert or save have opportunity to perform their custom job.
|
||||
|
||||
if DataMapper(db, self).resolvingPrimaryKeyDictionary == nil {
|
||||
if !canUpdateInDatabase(db) {
|
||||
try insert(db)
|
||||
return
|
||||
}
|
||||
@@ -392,7 +419,7 @@ public extension DatabasePersistable {
|
||||
// Make sure we call self.insert and self.update so that classes that
|
||||
// override insert or save have opportunity to perform their custom job.
|
||||
|
||||
if DataMapper(db, self).resolvingPrimaryKeyDictionary == nil {
|
||||
if !canUpdateInDatabase(db) {
|
||||
try insert(db)
|
||||
return
|
||||
}
|
||||
@@ -433,72 +460,10 @@ final class DataMapper {
|
||||
/// The table primary key
|
||||
let primaryKey: PrimaryKey
|
||||
|
||||
/// An excerpt from persistentDictionary whose keys are primary key columns.
|
||||
///
|
||||
/// It is nil when persistable has no primary key.
|
||||
lazy var primaryKeyDictionary: [String: DatabaseValueConvertible?]? = {
|
||||
let pkColumns = self.primaryKey.columns
|
||||
guard pkColumns.count > 0 else {
|
||||
return nil
|
||||
}
|
||||
let persistentDictionary = self.persistentDictionary
|
||||
return Dictionary(keys: pkColumns) { pkColumn in
|
||||
if let value = persistentDictionary[pkColumn] {
|
||||
return value
|
||||
}
|
||||
let pkColumn = pkColumn.lowercaseString
|
||||
for (column, value) in persistentDictionary where column.lowercaseString == pkColumn {
|
||||
return value
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}()
|
||||
|
||||
/// An excerpt from persistentDictionary whose keys are primary key
|
||||
/// columns. It is able to resolve a row in the database.
|
||||
///
|
||||
/// It is nil when the primaryKeyDictionary is nil or unable to identify a
|
||||
/// row in the database.
|
||||
lazy var resolvingPrimaryKeyDictionary: [String: DatabaseValueConvertible?]? = {
|
||||
// IMPLEMENTATION NOTE
|
||||
//
|
||||
// https://www.sqlite.org/lang_createtable.html
|
||||
//
|
||||
// > According to the SQL standard, PRIMARY KEY should always
|
||||
// > imply NOT NULL. Unfortunately, due to a bug in some early
|
||||
// > versions, this is not the case in SQLite. Unless the column
|
||||
// > is an INTEGER PRIMARY KEY or the table is a WITHOUT ROWID
|
||||
// > table or the column is declared NOT NULL, SQLite allows
|
||||
// > NULL values in a PRIMARY KEY column. SQLite could be fixed
|
||||
// > to conform to the standard, but doing so might break legacy
|
||||
// > applications. Hence, it has been decided to merely document
|
||||
// > the fact that SQLite allowing NULLs in most PRIMARY KEY
|
||||
// > columns.
|
||||
//
|
||||
// What we implement: we consider that the primary key is missing if
|
||||
// and only if *all* columns of the primary key are NULL.
|
||||
//
|
||||
// For tables with a single column primary key, we comply to the
|
||||
// SQL standard.
|
||||
//
|
||||
// For tables with multi-column primary keys, we let the user
|
||||
// store NULL in all but one columns of the primary key.
|
||||
|
||||
guard let dictionary = self.primaryKeyDictionary else {
|
||||
return nil
|
||||
}
|
||||
for case let value? in dictionary.values {
|
||||
return dictionary
|
||||
}
|
||||
return nil
|
||||
}()
|
||||
|
||||
init(_ db: Database, _ persistable: MutableDatabasePersistable) {
|
||||
// Fail early if database table does not exist.
|
||||
let databaseTableName = persistable.dynamicType.databaseTableName()
|
||||
guard let primaryKey = db.primaryKey(databaseTableName) else {
|
||||
fatalError("no such table: \(databaseTableName)")
|
||||
}
|
||||
let primaryKey = db.primaryKey(databaseTableName)
|
||||
|
||||
// Fail early if persistentDictionary is empty
|
||||
let persistentDictionary = persistable.persistentDictionary
|
||||
@@ -523,19 +488,12 @@ final class DataMapper {
|
||||
|
||||
func updateStatement() -> UpdateStatement {
|
||||
// Fail early if primary key does not resolve to a database row.
|
||||
guard let primaryKeyDictionary = resolvingPrimaryKeyDictionary else {
|
||||
fatalError("invalid primary key in \(persistable)")
|
||||
}
|
||||
let primaryKeyColumns = primaryKey.columns
|
||||
let primaryKeyValues = databaseValues(forColumns: primaryKeyColumns, inDictionary: persistentDictionary)
|
||||
precondition(primaryKeyValues.indexOf({ !$0.isNull }) != nil, "invalid primary key in \(persistable)")
|
||||
|
||||
var updatedDictionary = persistentDictionary
|
||||
|
||||
// Don't update primary key columns
|
||||
for column in primaryKeyDictionary.keys {
|
||||
updatedDictionary.removeValueForKey(column)
|
||||
}
|
||||
|
||||
// We need something to update.
|
||||
if updatedDictionary.count == 0 {
|
||||
var updatedColumns = Array(persistentDictionary.keys.filter { !primaryKeyColumns.contains($0) })
|
||||
if updatedColumns.isEmpty {
|
||||
// IMPLEMENTATION NOTE
|
||||
//
|
||||
// It is important to update something, so that
|
||||
@@ -544,46 +502,47 @@ final class DataMapper {
|
||||
//
|
||||
// The goal is to be able to write tests with minimal tables,
|
||||
// including tables made of a single primary key column.
|
||||
updatedDictionary = primaryKeyDictionary
|
||||
updatedColumns = primaryKeyColumns
|
||||
}
|
||||
let updatedValues = databaseValues(forColumns: updatedColumns, inDictionary: persistentDictionary)
|
||||
|
||||
let sql = UpdateQuery(
|
||||
tableName: databaseTableName,
|
||||
updatedColumns: Array(updatedDictionary.keys),
|
||||
conditionColumns: Array(primaryKeyDictionary.keys))
|
||||
updatedColumns: updatedColumns,
|
||||
conditionColumns: primaryKeyColumns)
|
||||
.sql
|
||||
let statement = try! db.cachedUpdateStatement(sql)
|
||||
statement.unsafeSetArguments(StatementArguments(Array(updatedDictionary.values) + Array(primaryKeyDictionary.values)))
|
||||
statement.unsafeSetArguments(StatementArguments(updatedValues + primaryKeyValues))
|
||||
return statement
|
||||
}
|
||||
|
||||
func deleteStatement() -> UpdateStatement {
|
||||
// Fail early if primary key does not resolve to a database row.
|
||||
guard let primaryKeyDictionary = resolvingPrimaryKeyDictionary else {
|
||||
fatalError("invalid primary key in \(persistable)")
|
||||
}
|
||||
let primaryKeyColumns = primaryKey.columns
|
||||
let primaryKeyValues = databaseValues(forColumns: primaryKeyColumns, inDictionary: persistentDictionary)
|
||||
precondition(primaryKeyValues.indexOf({ !$0.isNull }) != nil, "invalid primary key in \(persistable)")
|
||||
|
||||
let sql = DeleteQuery(
|
||||
tableName: databaseTableName,
|
||||
conditionColumns: Array(primaryKeyDictionary.keys))
|
||||
conditionColumns: primaryKeyColumns)
|
||||
.sql
|
||||
let statement = try! db.cachedUpdateStatement(sql)
|
||||
statement.unsafeSetArguments(StatementArguments(primaryKeyDictionary.values))
|
||||
statement.unsafeSetArguments(StatementArguments(primaryKeyValues))
|
||||
return statement
|
||||
}
|
||||
|
||||
func existsStatement() -> SelectStatement {
|
||||
// Fail early if primary key does not resolve to a database row.
|
||||
guard let primaryKeyDictionary = resolvingPrimaryKeyDictionary else {
|
||||
fatalError("invalid primary key in \(persistable)")
|
||||
}
|
||||
let primaryKeyColumns = primaryKey.columns
|
||||
let primaryKeyValues = databaseValues(forColumns: primaryKeyColumns, inDictionary: persistentDictionary)
|
||||
precondition(primaryKeyValues.indexOf({ !$0.isNull }) != nil, "invalid primary key in \(persistable)")
|
||||
|
||||
let sql = ExistsQuery(
|
||||
tableName: databaseTableName,
|
||||
conditionColumns: Array(primaryKeyDictionary.keys))
|
||||
conditionColumns: primaryKeyColumns)
|
||||
.sql
|
||||
let statement = try! db.cachedSelectStatement(sql)
|
||||
statement.unsafeSetArguments(StatementArguments(primaryKeyDictionary.values))
|
||||
statement.unsafeSetArguments(StatementArguments(primaryKeyValues))
|
||||
return statement
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,12 +67,9 @@ extension RowConvertible where Self: DatabaseTableMapping {
|
||||
//
|
||||
// Returns nil if keys is empty.
|
||||
private static func fetchByPrimaryKeyStatement<Sequence: SequenceType where Sequence.Generator.Element: DatabaseValueConvertible>(db: Database, keys: Sequence) -> SelectStatement? {
|
||||
let databaseTableName = self.databaseTableName()
|
||||
|
||||
// Fail early if database table does not exist.
|
||||
guard let primaryKey = db.primaryKey(databaseTableName) else {
|
||||
fatalError("no such table: \(databaseTableName)")
|
||||
}
|
||||
let databaseTableName = self.databaseTableName()
|
||||
let primaryKey = db.primaryKey(databaseTableName)
|
||||
|
||||
// Fail early if database table has not one column in its primary key
|
||||
let columns = primaryKey.columns
|
||||
|
||||
@@ -493,6 +493,17 @@ public struct StatementArguments {
|
||||
kind = .Values(Array(sequence))
|
||||
}
|
||||
|
||||
/// Initializes arguments from a sequence of optional values.
|
||||
///
|
||||
/// let values: [String] = ["foo", "bar"]
|
||||
/// db.execute("INSERT ... (?,?)", arguments: StatementArguments(values))
|
||||
///
|
||||
/// - parameter sequence: A sequence of DatabaseValueConvertible values.
|
||||
/// - returns: A StatementArguments.
|
||||
public init<Sequence: SequenceType where Sequence.Generator.Element: DatabaseValueConvertible>(_ sequence: Sequence) {
|
||||
kind = .Values(sequence.map { $0 })
|
||||
}
|
||||
|
||||
|
||||
// MARK: Named Arguments
|
||||
|
||||
@@ -508,6 +519,18 @@ public struct StatementArguments {
|
||||
kind = .NamedValues(Dictionary(sequence))
|
||||
}
|
||||
|
||||
/// Initializes arguments from a sequence of (key, value) pairs, such as
|
||||
/// a dictionary.
|
||||
///
|
||||
/// let values: [String: String] = ["firstName": "Arthur", "lastName": "Miller"]
|
||||
/// db.execute("INSERT ... (:firstName, :lastName)", arguments: StatementArguments(values))
|
||||
///
|
||||
/// - parameter sequence: A sequence of (key, value) pairs
|
||||
/// - returns: A StatementArguments.
|
||||
public init<Sequence: SequenceType, Value: DatabaseValueConvertible where Sequence.Generator.Element == (String, Value)>(_ sequence: Sequence) {
|
||||
kind = .NamedValues(Dictionary(sequence.map { (key, value) in return (key, value as DatabaseValueConvertible?) }))
|
||||
}
|
||||
|
||||
public var isEmpty: Bool {
|
||||
switch kind {
|
||||
case .Values(let values):
|
||||
|
||||
Reference in new issue
Block a user