mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-27 04:14:21 +00:00
Table creation API enhancements
This commit is contained in:
1 parent
a72c207ec5
commit
5f2d6f8e2f
5 files changed
+357
-151
No files matched your search
@@ -1,6 +1,67 @@
|
||||
Release Notes
|
||||
=============
|
||||
|
||||
## Next Version
|
||||
|
||||
**New**
|
||||
|
||||
The table creation API has been enhanced:
|
||||
|
||||
- SQLite supports untyped columns:
|
||||
|
||||
```swift
|
||||
try dbQueue.inDatabase { db in
|
||||
// CREATE TABLE t(a, b)
|
||||
try db.create(table: "t") { t in
|
||||
t.column("a")
|
||||
t.column("b")
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This feature addresses [#169](https://github.com/groue/GRDB.swift/issues/169).
|
||||
|
||||
- The `indexed()` methods lets you create a non-unique index on a table column:
|
||||
|
||||
```swift
|
||||
try dbQueue.inDatabase { db in
|
||||
// CREATE TABLE rounds(score INTEGER)
|
||||
// CREATE INDEX rounds_on_score ON rounds(score)
|
||||
try db.create(table: "rounds") { t in
|
||||
t.column("score", .integer).indexed()
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- It is now possible to define external and auto references to tables without any explicit primary key. The generated SQL then uses the `rowid` hidden primary key column:
|
||||
|
||||
```swift
|
||||
try dbQueue.inDatabase { db in
|
||||
// CREATE TABLE nodes(
|
||||
// name TEXT,
|
||||
// parentId INTEGER REFERENCES nodes(rowid)
|
||||
// )
|
||||
try db.create(table: "nodes") { t in
|
||||
t.column("name", .text)
|
||||
t.column("parentId", .integer).references("nodes")
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**API diff**
|
||||
|
||||
```diff
|
||||
final class TableDefinition {
|
||||
- func column(_ name: String, _ type: Database.ColumnType) -> ColumnDefinition
|
||||
+ func column(_ name: String, _ type: Database.ColumnType? = nil) -> ColumnDefinition
|
||||
}
|
||||
|
||||
final class ColumnDefinition {
|
||||
+ @discardableResult func indexed() -> Self
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## 1.1
|
||||
|
||||
Released July 1, 2017
|
||||
|
||||
@@ -251,11 +251,11 @@ public final class TableDefinition {
|
||||
/// See https://www.sqlite.org/lang_createtable.html#tablecoldef
|
||||
///
|
||||
/// - parameter name: the column name.
|
||||
/// - parameter type: the column type.
|
||||
/// - parameter type: the eventual column type.
|
||||
/// - returns: An ColumnDefinition that allows you to refine the
|
||||
/// column definition.
|
||||
@discardableResult
|
||||
public func column(_ name: String, _ type: Database.ColumnType) -> ColumnDefinition {
|
||||
public func column(_ name: String, _ type: Database.ColumnType? = nil) -> ColumnDefinition {
|
||||
let column = ColumnDefinition(name: name, type: type)
|
||||
columns.append(column)
|
||||
return column
|
||||
@@ -358,95 +358,111 @@ public final class TableDefinition {
|
||||
}
|
||||
|
||||
fileprivate func sql(_ db: Database) throws -> String {
|
||||
var chunks: [String] = []
|
||||
chunks.append("CREATE")
|
||||
if temporary {
|
||||
chunks.append("TEMPORARY")
|
||||
}
|
||||
chunks.append("TABLE")
|
||||
if ifNotExists {
|
||||
chunks.append("IF NOT EXISTS")
|
||||
}
|
||||
chunks.append(name.quotedDatabaseIdentifier)
|
||||
|
||||
let primaryKeyColumns: [String]
|
||||
if let (columns, _) = primaryKeyConstraint {
|
||||
primaryKeyColumns = columns
|
||||
} else if let index = columns.index(where: { $0.primaryKey != nil }) {
|
||||
primaryKeyColumns = [columns[index].name]
|
||||
} else {
|
||||
primaryKeyColumns = []
|
||||
}
|
||||
var statements: [String] = []
|
||||
|
||||
do {
|
||||
var items: [String] = []
|
||||
try items.append(contentsOf: columns.map { try $0.sql(db, tableName: name, primaryKeyColumns: primaryKeyColumns) })
|
||||
var chunks: [String] = []
|
||||
chunks.append("CREATE")
|
||||
if temporary {
|
||||
chunks.append("TEMPORARY")
|
||||
}
|
||||
chunks.append("TABLE")
|
||||
if ifNotExists {
|
||||
chunks.append("IF NOT EXISTS")
|
||||
}
|
||||
chunks.append(name.quotedDatabaseIdentifier)
|
||||
|
||||
if let (columns, conflictResolution) = primaryKeyConstraint {
|
||||
var chunks: [String] = []
|
||||
chunks.append("PRIMARY KEY")
|
||||
chunks.append("(\((columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
|
||||
if let conflictResolution = conflictResolution {
|
||||
chunks.append("ON CONFLICT")
|
||||
chunks.append(conflictResolution.rawValue)
|
||||
}
|
||||
items.append(chunks.joined(separator: " "))
|
||||
let primaryKeyColumns: [String]
|
||||
if let (columns, _) = primaryKeyConstraint {
|
||||
primaryKeyColumns = columns
|
||||
} else if let index = columns.index(where: { $0.primaryKey != nil }) {
|
||||
primaryKeyColumns = [columns[index].name]
|
||||
} else {
|
||||
// WITHOUT ROWID optimization requires a primary key. If the
|
||||
// user sets withoutRowID, but does not define a primary key,
|
||||
// this is undefined behavior.
|
||||
//
|
||||
// We thus can use the rowId column even when the withoutRowID
|
||||
// flag is set ;-)
|
||||
primaryKeyColumns = [Column.rowID.name]
|
||||
}
|
||||
|
||||
for (columns, conflictResolution) in uniqueKeyConstraints {
|
||||
var chunks: [String] = []
|
||||
chunks.append("UNIQUE")
|
||||
chunks.append("(\((columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
|
||||
if let conflictResolution = conflictResolution {
|
||||
chunks.append("ON CONFLICT")
|
||||
chunks.append(conflictResolution.rawValue)
|
||||
do {
|
||||
var items: [String] = []
|
||||
try items.append(contentsOf: columns.map { try $0.sql(db, tableName: name, primaryKeyColumns: primaryKeyColumns) })
|
||||
|
||||
if let (columns, conflictResolution) = primaryKeyConstraint {
|
||||
var chunks: [String] = []
|
||||
chunks.append("PRIMARY KEY")
|
||||
chunks.append("(\((columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
|
||||
if let conflictResolution = conflictResolution {
|
||||
chunks.append("ON CONFLICT")
|
||||
chunks.append(conflictResolution.rawValue)
|
||||
}
|
||||
items.append(chunks.joined(separator: " "))
|
||||
}
|
||||
items.append(chunks.joined(separator: " "))
|
||||
|
||||
for (columns, conflictResolution) in uniqueKeyConstraints {
|
||||
var chunks: [String] = []
|
||||
chunks.append("UNIQUE")
|
||||
chunks.append("(\((columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
|
||||
if let conflictResolution = conflictResolution {
|
||||
chunks.append("ON CONFLICT")
|
||||
chunks.append(conflictResolution.rawValue)
|
||||
}
|
||||
items.append(chunks.joined(separator: " "))
|
||||
}
|
||||
|
||||
for (columns, table, destinationColumns, deleteAction, updateAction, deferred) in foreignKeyConstraints {
|
||||
var chunks: [String] = []
|
||||
chunks.append("FOREIGN KEY")
|
||||
chunks.append("(\((columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
|
||||
chunks.append("REFERENCES")
|
||||
if let destinationColumns = destinationColumns {
|
||||
chunks.append("\(table.quotedDatabaseIdentifier)(\((destinationColumns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
|
||||
} else if table == name {
|
||||
chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKeyColumns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
|
||||
} else if let primaryKey = try db.primaryKey(table) {
|
||||
chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKey.columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
|
||||
} else {
|
||||
// Programmer error
|
||||
fatalError("explicit referenced column(s) required, since table \(table) has no primary key")
|
||||
}
|
||||
if let deleteAction = deleteAction {
|
||||
chunks.append("ON DELETE")
|
||||
chunks.append(deleteAction.rawValue)
|
||||
}
|
||||
if let updateAction = updateAction {
|
||||
chunks.append("ON UPDATE")
|
||||
chunks.append(updateAction.rawValue)
|
||||
}
|
||||
if deferred {
|
||||
chunks.append("DEFERRABLE INITIALLY DEFERRED")
|
||||
}
|
||||
items.append(chunks.joined(separator: " "))
|
||||
}
|
||||
|
||||
for checkExpression in checkConstraints {
|
||||
var chunks: [String] = []
|
||||
chunks.append("CHECK")
|
||||
chunks.append("(" + checkExpression.sql + ")")
|
||||
items.append(chunks.joined(separator: " "))
|
||||
}
|
||||
|
||||
chunks.append("(\(items.joined(separator: ", ")))")
|
||||
}
|
||||
|
||||
for (columns, table, destinationColumns, deleteAction, updateAction, deferred) in foreignKeyConstraints {
|
||||
var chunks: [String] = []
|
||||
chunks.append("FOREIGN KEY")
|
||||
chunks.append("(\((columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
|
||||
chunks.append("REFERENCES")
|
||||
if let destinationColumns = destinationColumns {
|
||||
chunks.append("\(table.quotedDatabaseIdentifier)(\((destinationColumns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
|
||||
} else if table == name {
|
||||
chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKeyColumns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
|
||||
} else if let primaryKey = try db.primaryKey(table) {
|
||||
chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKey.columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
|
||||
} else {
|
||||
// Programmer error
|
||||
fatalError("explicit referenced column(s) required, since table \(table) has no primary key")
|
||||
}
|
||||
if let deleteAction = deleteAction {
|
||||
chunks.append("ON DELETE")
|
||||
chunks.append(deleteAction.rawValue)
|
||||
}
|
||||
if let updateAction = updateAction {
|
||||
chunks.append("ON UPDATE")
|
||||
chunks.append(updateAction.rawValue)
|
||||
}
|
||||
if deferred {
|
||||
chunks.append("DEFERRABLE INITIALLY DEFERRED")
|
||||
}
|
||||
items.append(chunks.joined(separator: " "))
|
||||
if withoutRowID {
|
||||
chunks.append("WITHOUT ROWID")
|
||||
}
|
||||
|
||||
for checkExpression in checkConstraints {
|
||||
var chunks: [String] = []
|
||||
chunks.append("CHECK")
|
||||
chunks.append("(" + checkExpression.sql + ")")
|
||||
items.append(chunks.joined(separator: " "))
|
||||
}
|
||||
|
||||
chunks.append("(\(items.joined(separator: ", ")))")
|
||||
statements.append(chunks.joined(separator: " "))
|
||||
}
|
||||
|
||||
if withoutRowID {
|
||||
chunks.append("WITHOUT ROWID")
|
||||
}
|
||||
return chunks.joined(separator: " ")
|
||||
let indexStatements = columns
|
||||
.flatMap { $0.indexDefinition(in: name) }
|
||||
.map { $0.sql() }
|
||||
statements.append(contentsOf: indexStatements)
|
||||
return statements.joined(separator: "; ")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -495,9 +511,13 @@ public final class TableAlteration {
|
||||
chunks.append("ALTER TABLE")
|
||||
chunks.append(name.quotedDatabaseIdentifier)
|
||||
chunks.append("ADD COLUMN")
|
||||
try chunks.append(column.sql(db, tableName: nil, primaryKeyColumns: nil))
|
||||
try chunks.append(column.sql(db, tableName: name, primaryKeyColumns: nil))
|
||||
let statement = chunks.joined(separator: " ")
|
||||
statements.append(statement)
|
||||
|
||||
if let indexDefinition = column.indexDefinition(in: name) {
|
||||
statements.append(indexDefinition.sql())
|
||||
}
|
||||
}
|
||||
|
||||
return statements.joined(separator: "; ")
|
||||
@@ -519,17 +539,22 @@ public final class TableAlteration {
|
||||
/// See https://www.sqlite.org/lang_createtable.html and
|
||||
/// https://www.sqlite.org/lang_altertable.html
|
||||
public final class ColumnDefinition {
|
||||
enum Index {
|
||||
case none
|
||||
case index
|
||||
case unique(Database.ConflictResolution)
|
||||
}
|
||||
fileprivate let name: String
|
||||
private let type: Database.ColumnType
|
||||
private let type: Database.ColumnType?
|
||||
fileprivate var primaryKey: (conflictResolution: Database.ConflictResolution?, autoincrement: Bool)?
|
||||
private var index: Index = .none
|
||||
private var notNullConflictResolution: Database.ConflictResolution?
|
||||
private var uniqueConflictResolution: Database.ConflictResolution?
|
||||
private var checkConstraints: [SQLExpression] = []
|
||||
private var foreignKeyConstraints: [(table: String, column: String?, deleteAction: Database.ForeignKeyAction?, updateAction: Database.ForeignKeyAction?, deferred: Bool)] = []
|
||||
private var defaultExpression: SQLExpression?
|
||||
private var collationName: String?
|
||||
|
||||
init(name: String, type: Database.ColumnType) {
|
||||
init(name: String, type: Database.ColumnType?) {
|
||||
self.name = name
|
||||
self.type = type
|
||||
}
|
||||
@@ -584,7 +609,24 @@ public final class ColumnDefinition {
|
||||
/// - returns: Self so that you can further refine the column definition.
|
||||
@discardableResult
|
||||
public func unique(onConflict conflictResolution: Database.ConflictResolution? = nil) -> Self {
|
||||
uniqueConflictResolution = conflictResolution ?? .abort
|
||||
index = .unique(conflictResolution ?? .abort)
|
||||
return self
|
||||
}
|
||||
|
||||
/// Adds an index of the column.
|
||||
///
|
||||
/// try db.create(table: "persons") { t in
|
||||
/// t.column("email", .text).indexed()
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/lang_createtable.html#uniqueconst
|
||||
///
|
||||
/// - returns: Self so that you can further refine the column definition.
|
||||
@discardableResult
|
||||
public func indexed() -> Self {
|
||||
if case .none = index {
|
||||
self.index = .index
|
||||
}
|
||||
return self
|
||||
}
|
||||
|
||||
@@ -708,10 +750,12 @@ public final class ColumnDefinition {
|
||||
return self
|
||||
}
|
||||
|
||||
fileprivate func sql(_ db: Database, tableName: String?, primaryKeyColumns: [String]?) throws -> String {
|
||||
fileprivate func sql(_ db: Database, tableName: String, primaryKeyColumns: [String]?) throws -> String {
|
||||
var chunks: [String] = []
|
||||
chunks.append(name.quotedDatabaseIdentifier)
|
||||
chunks.append(type.rawValue)
|
||||
if let type = type {
|
||||
chunks.append(type.rawValue)
|
||||
}
|
||||
|
||||
if let (conflictResolution, autoincrement) = primaryKey {
|
||||
chunks.append("PRIMARY KEY")
|
||||
@@ -734,14 +778,19 @@ public final class ColumnDefinition {
|
||||
chunks.append(conflictResolution.rawValue)
|
||||
}
|
||||
|
||||
switch uniqueConflictResolution {
|
||||
switch index {
|
||||
case .none:
|
||||
break
|
||||
case .abort?:
|
||||
chunks.append("UNIQUE")
|
||||
case let conflictResolution?:
|
||||
chunks.append("UNIQUE ON CONFLICT")
|
||||
chunks.append(conflictResolution.rawValue)
|
||||
case .unique(let conflictResolution):
|
||||
switch conflictResolution {
|
||||
case .abort:
|
||||
chunks.append("UNIQUE")
|
||||
default:
|
||||
chunks.append("UNIQUE ON CONFLICT")
|
||||
chunks.append(conflictResolution.rawValue)
|
||||
}
|
||||
case .index:
|
||||
break
|
||||
}
|
||||
|
||||
for checkConstraint in checkConstraints {
|
||||
@@ -762,14 +811,16 @@ public final class ColumnDefinition {
|
||||
for (table, column, deleteAction, updateAction, deferred) in foreignKeyConstraints {
|
||||
chunks.append("REFERENCES")
|
||||
if let column = column {
|
||||
// explicit reference
|
||||
chunks.append("\(table.quotedDatabaseIdentifier)(\(column.quotedDatabaseIdentifier))")
|
||||
} else if let tableName = tableName, let primaryKeyColumns = primaryKeyColumns, table == tableName {
|
||||
} else if table.lowercased() == tableName.lowercased() {
|
||||
// implicit autoreference
|
||||
let primaryKeyColumns = try primaryKeyColumns ?? db.primaryKey(table)?.columns ?? [Column.rowID.name]
|
||||
chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKeyColumns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
|
||||
} else if let primaryKey = try db.primaryKey(table) {
|
||||
chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKey.columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
|
||||
} else {
|
||||
// Programmer error
|
||||
fatalError("explicit referenced column required, since table \(table) has no primary key")
|
||||
// implicit external reference
|
||||
let primaryKeyColumns = try db.primaryKey(table)?.columns ?? [Column.rowID.name]
|
||||
chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKeyColumns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
|
||||
}
|
||||
if let deleteAction = deleteAction {
|
||||
chunks.append("ON DELETE")
|
||||
@@ -786,6 +837,21 @@ public final class ColumnDefinition {
|
||||
|
||||
return chunks.joined(separator: " ")
|
||||
}
|
||||
|
||||
fileprivate func indexDefinition(in table: String) -> IndexDefinition? {
|
||||
switch index {
|
||||
case .none: return nil
|
||||
case .unique: return nil
|
||||
case .index:
|
||||
return IndexDefinition(
|
||||
name: "\(table)_on_\(name)",
|
||||
table: table,
|
||||
columns: [name],
|
||||
unique: false,
|
||||
ifNotExists: false,
|
||||
condition: nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct IndexDefinition {
|
||||
|
||||
@@ -2696,11 +2696,15 @@ try db.create(table: "example") { t in ... }
|
||||
try db.create(table: "example", temporary: true, ifNotExists: true) { t in
|
||||
```
|
||||
|
||||
**Add regular columns** with their name and type (text, integer, double, numeric, boolean, blob, date and datetime) - see [SQLite data types](https://www.sqlite.org/datatype3.html):
|
||||
**Add regular columns** with their name and eventual type (text, integer, double, numeric, boolean, blob, date and datetime) - see [SQLite data types](https://www.sqlite.org/datatype3.html):
|
||||
|
||||
```swift
|
||||
// name TEXT,
|
||||
// creationDate DATETIME,
|
||||
// CREATE TABLE example (
|
||||
// a,
|
||||
// name TEXT,
|
||||
// creationDate DATETIME,
|
||||
try db.create(table: "example") { t in ... }
|
||||
t.column("a")
|
||||
t.column("name", .text)
|
||||
t.column("creationDate", .datetime)
|
||||
```
|
||||
@@ -2728,6 +2732,14 @@ Use an individual column as **primary**, **unique**, or **foreign key**. When de
|
||||
t.column("countryCode", .text).references("countries", onDelete: .cascade)
|
||||
```
|
||||
|
||||
**Create an index** on the column:
|
||||
|
||||
```swift
|
||||
t.column("score", .integer).indexed()
|
||||
```
|
||||
|
||||
For extra index options, see [Create Indexes](#create-indexes) below.
|
||||
|
||||
**Perform integrity checks** on individual columns, and SQLite will only let conforming rows in. In the example below, the `$0` closure variable is a column which lets you build any SQL [expression](#expressions).
|
||||
|
||||
```swift
|
||||
|
||||
@@ -128,6 +128,26 @@ class GRDBTestCase: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
// Compare SQL strings (ignoring leading and trailing white space and semicolons.
|
||||
func assertEqualSQL(_ lhs: String, _ rhs: String, file: StaticString = #file, line: UInt = #line) {
|
||||
// Trim white space and ";"
|
||||
let cs = CharacterSet.whitespacesAndNewlines.union(CharacterSet(charactersIn: ";"))
|
||||
XCTAssertEqual(lhs.trimmingCharacters(in: cs), rhs.trimmingCharacters(in: cs), file: file, line: line)
|
||||
}
|
||||
|
||||
// Compare SQL strings (ignoring leading and trailing white space and semicolons.
|
||||
func assertEqualSQL(_ db: Database, _ request: Request, _ sql: String, file: StaticString = #file, line: UInt = #line) throws {
|
||||
_ = try Row.fetchOne(db, request)
|
||||
assertEqualSQL(lastSQLQuery, sql, file: file, line: line)
|
||||
}
|
||||
|
||||
// Compare SQL strings (ignoring leading and trailing white space and semicolons.
|
||||
func assertEqualSQL(_ databaseReader: DatabaseReader, _ request: Request, _ sql: String, file: StaticString = #file, line: UInt = #line) throws {
|
||||
try databaseReader.unsafeRead { db in
|
||||
try assertEqualSQL(db, request, sql, file: file, line: line)
|
||||
}
|
||||
}
|
||||
|
||||
func sql(_ databaseReader: DatabaseReader, _ request: Request) -> String {
|
||||
return try! databaseReader.unsafeRead { db in
|
||||
_ = try Row.fetchOne(db, request)
|
||||
|
||||
@@ -17,8 +17,9 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.column("name", .text)
|
||||
}
|
||||
XCTAssertEqual(
|
||||
self.lastSQLQuery,
|
||||
|
||||
assertEqualSQL(
|
||||
lastSQLQuery,
|
||||
("CREATE TABLE \"test\" (" +
|
||||
"\"id\" INTEGER PRIMARY KEY, " +
|
||||
"\"name\" TEXT" +
|
||||
@@ -33,8 +34,8 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
try db.create(table: "test", temporary: true, ifNotExists: true, withoutRowID: true) { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
}
|
||||
XCTAssertEqual(
|
||||
self.lastSQLQuery,
|
||||
assertEqualSQL(
|
||||
lastSQLQuery,
|
||||
("CREATE TEMPORARY TABLE IF NOT EXISTS \"test\" (" +
|
||||
"\"id\" INTEGER PRIMARY KEY" +
|
||||
") WITHOUT ROWID") as String)
|
||||
@@ -42,8 +43,8 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
try db.create(table: "test", temporary: true, ifNotExists: true) { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
}
|
||||
XCTAssertEqual(
|
||||
self.lastSQLQuery,
|
||||
assertEqualSQL(
|
||||
lastSQLQuery,
|
||||
("CREATE TEMPORARY TABLE IF NOT EXISTS \"test\" (" +
|
||||
"\"id\" INTEGER PRIMARY KEY" +
|
||||
")") as String)
|
||||
@@ -51,14 +52,27 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testUntypedColumn() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
// Simple table creation
|
||||
try db.create(table: "test") { t in
|
||||
t.column("a")
|
||||
t.column("b")
|
||||
}
|
||||
|
||||
assertEqualSQL(lastSQLQuery, "CREATE TABLE \"test\" (\"a\", \"b\")")
|
||||
}
|
||||
}
|
||||
|
||||
func testColumnPrimaryKeyOptions() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inTransaction { db in
|
||||
try db.create(table: "test") { t in
|
||||
t.column("id", .integer).primaryKey(onConflict: .fail)
|
||||
}
|
||||
XCTAssertEqual(
|
||||
self.lastSQLQuery,
|
||||
assertEqualSQL(
|
||||
lastSQLQuery,
|
||||
("CREATE TABLE \"test\" (" +
|
||||
"\"id\" INTEGER PRIMARY KEY ON CONFLICT FAIL" +
|
||||
")") as String)
|
||||
@@ -68,8 +82,8 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
try db.create(table: "test") { t in
|
||||
t.column("id", .integer).primaryKey(autoincrement: true)
|
||||
}
|
||||
XCTAssertEqual(
|
||||
self.lastSQLQuery,
|
||||
assertEqualSQL(
|
||||
lastSQLQuery,
|
||||
("CREATE TABLE \"test\" (" +
|
||||
"\"id\" INTEGER PRIMARY KEY AUTOINCREMENT" +
|
||||
")") as String)
|
||||
@@ -88,8 +102,8 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
t.column("e", .integer).notNull(onConflict: .ignore)
|
||||
t.column("f", .integer).notNull(onConflict: .replace)
|
||||
}
|
||||
XCTAssertEqual(
|
||||
self.lastSQLQuery,
|
||||
assertEqualSQL(
|
||||
lastSQLQuery,
|
||||
("CREATE TABLE \"test\" (" +
|
||||
"\"a\" INTEGER NOT NULL, " +
|
||||
"\"b\" INTEGER NOT NULL, " +
|
||||
@@ -101,6 +115,20 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testColumnIndexed() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
sqlQueries.removeAll()
|
||||
try db.create(table: "test") { t in
|
||||
t.column("a", .integer).indexed()
|
||||
t.column("b", .integer).indexed()
|
||||
}
|
||||
assertEqualSQL(sqlQueries[0], "CREATE TABLE \"test\" (\"a\" INTEGER, \"b\" INTEGER)")
|
||||
assertEqualSQL(sqlQueries[1], "CREATE INDEX \"test_on_a\" ON \"test\"(\"a\")")
|
||||
assertEqualSQL(sqlQueries[2], "CREATE INDEX \"test_on_b\" ON \"test\"(\"b\")")
|
||||
}
|
||||
}
|
||||
|
||||
func testColumnUnique() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
@@ -112,8 +140,8 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
t.column("e", .integer).unique(onConflict: .ignore)
|
||||
t.column("f", .integer).unique(onConflict: .replace)
|
||||
}
|
||||
XCTAssertEqual(
|
||||
self.lastSQLQuery,
|
||||
assertEqualSQL(
|
||||
lastSQLQuery,
|
||||
("CREATE TABLE \"test\" (" +
|
||||
"\"a\" INTEGER UNIQUE, " +
|
||||
"\"b\" INTEGER UNIQUE, " +
|
||||
@@ -133,8 +161,8 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
t.column("b", .integer).check(sql: "b <> 2")
|
||||
t.column("c", .integer).check { $0 > 0 }.check { $0 < 10 }
|
||||
}
|
||||
XCTAssertEqual(
|
||||
self.lastSQLQuery,
|
||||
assertEqualSQL(
|
||||
lastSQLQuery,
|
||||
("CREATE TABLE \"test\" (" +
|
||||
"\"a\" INTEGER CHECK ((\"a\" > 0)), " +
|
||||
"\"b\" INTEGER CHECK (b <> 2), " +
|
||||
@@ -161,8 +189,8 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
t.column("d", .integer).defaults(to: "foo".data(using: .utf8)!)
|
||||
t.column("e", .integer).defaults(sql: "NULL")
|
||||
}
|
||||
XCTAssertEqual(
|
||||
self.lastSQLQuery,
|
||||
assertEqualSQL(
|
||||
lastSQLQuery,
|
||||
("CREATE TABLE \"test\" (" +
|
||||
"\"a\" INTEGER DEFAULT 1, " +
|
||||
"\"b\" INTEGER DEFAULT 1.0, " +
|
||||
@@ -184,8 +212,8 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
try db.create(table: "test") { t in
|
||||
t.column("name", .text).collate(.nocase)
|
||||
}
|
||||
XCTAssertEqual(
|
||||
self.lastSQLQuery,
|
||||
assertEqualSQL(
|
||||
lastSQLQuery,
|
||||
("CREATE TABLE \"test\" (" +
|
||||
"\"name\" TEXT COLLATE NOCASE" +
|
||||
")") as String)
|
||||
@@ -198,8 +226,8 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
try db.create(table: "test") { t in
|
||||
t.column("name", .text).collate(collation)
|
||||
}
|
||||
XCTAssertEqual(
|
||||
self.lastSQLQuery,
|
||||
assertEqualSQL(
|
||||
lastSQLQuery,
|
||||
("CREATE TABLE \"test\" (" +
|
||||
"\"name\" TEXT COLLATE foo" +
|
||||
")") as String)
|
||||
@@ -214,17 +242,22 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
t.column("name", .text).primaryKey()
|
||||
t.column("email", .text).unique()
|
||||
}
|
||||
try db.create(table: "pkless") { t in
|
||||
t.column("email", .text)
|
||||
}
|
||||
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")
|
||||
t.column("pklessRowId", .text).references("pkless")
|
||||
}
|
||||
XCTAssertEqual(
|
||||
self.lastSQLQuery,
|
||||
assertEqualSQL(
|
||||
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, " +
|
||||
"\"weird\" TEXT REFERENCES \"parent\"(\"name\") REFERENCES \"parent\"(\"email\")" +
|
||||
"\"weird\" TEXT REFERENCES \"parent\"(\"name\") REFERENCES \"parent\"(\"email\"), " +
|
||||
"\"pklessRowId\" TEXT REFERENCES \"pkless\"(\"rowid\")" +
|
||||
")") as String)
|
||||
}
|
||||
}
|
||||
@@ -237,8 +270,8 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
t.column("a", .text)
|
||||
t.column("b", .text)
|
||||
}
|
||||
XCTAssertEqual(
|
||||
self.lastSQLQuery,
|
||||
assertEqualSQL(
|
||||
lastSQLQuery,
|
||||
("CREATE TABLE \"test\" (" +
|
||||
"\"a\" TEXT, " +
|
||||
"\"b\" TEXT, " +
|
||||
@@ -252,8 +285,8 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
t.column("a", .text)
|
||||
t.column("b", .text)
|
||||
}
|
||||
XCTAssertEqual(
|
||||
self.lastSQLQuery,
|
||||
assertEqualSQL(
|
||||
lastSQLQuery,
|
||||
("CREATE TABLE \"test\" (" +
|
||||
"\"a\" TEXT, " +
|
||||
"\"b\" TEXT, " +
|
||||
@@ -273,8 +306,8 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
t.column("b", .text)
|
||||
t.column("c", .text)
|
||||
}
|
||||
XCTAssertEqual(
|
||||
self.lastSQLQuery,
|
||||
assertEqualSQL(
|
||||
lastSQLQuery,
|
||||
("CREATE TABLE \"test\" (" +
|
||||
"\"a\" TEXT, " +
|
||||
"\"b\" TEXT, " +
|
||||
@@ -300,8 +333,8 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
t.column("d", .text)
|
||||
t.column("e", .text)
|
||||
}
|
||||
XCTAssertEqual(
|
||||
self.lastSQLQuery,
|
||||
assertEqualSQL(
|
||||
lastSQLQuery,
|
||||
("CREATE TABLE \"child\" (" +
|
||||
"\"c\" TEXT, " +
|
||||
"\"d\" TEXT, " +
|
||||
@@ -321,8 +354,8 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
t.column("a", .integer)
|
||||
t.column("b", .integer)
|
||||
}
|
||||
XCTAssertEqual(
|
||||
self.lastSQLQuery,
|
||||
assertEqualSQL(
|
||||
lastSQLQuery,
|
||||
("CREATE TABLE \"test\" (" +
|
||||
"\"a\" INTEGER, " +
|
||||
"\"b\" INTEGER, " +
|
||||
@@ -347,8 +380,8 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.column("id2", .integer).references("test1")
|
||||
}
|
||||
XCTAssertEqual(
|
||||
self.lastSQLQuery,
|
||||
assertEqualSQL(
|
||||
lastSQLQuery,
|
||||
("CREATE TABLE \"test1\" (" +
|
||||
"\"id\" INTEGER PRIMARY KEY, " +
|
||||
"\"id2\" INTEGER REFERENCES \"test1\"(\"id\")" +
|
||||
@@ -359,8 +392,8 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
t.column("id2", .integer).references("test2")
|
||||
t.primaryKey(["id"])
|
||||
}
|
||||
XCTAssertEqual(
|
||||
self.lastSQLQuery,
|
||||
assertEqualSQL(
|
||||
lastSQLQuery,
|
||||
("CREATE TABLE \"test2\" (" +
|
||||
"\"id\" INTEGER, " +
|
||||
"\"id2\" INTEGER REFERENCES \"test2\"(\"id\"), " +
|
||||
@@ -375,8 +408,8 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
t.foreignKey(["c", "d"], references: "test3")
|
||||
t.primaryKey(["a", "b"])
|
||||
}
|
||||
XCTAssertEqual(
|
||||
self.lastSQLQuery,
|
||||
assertEqualSQL(
|
||||
lastSQLQuery,
|
||||
("CREATE TABLE \"test3\" (" +
|
||||
"\"a\" INTEGER, " +
|
||||
"\"b\" INTEGER, " +
|
||||
@@ -385,6 +418,15 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
"PRIMARY KEY (\"a\", \"b\"), " +
|
||||
"FOREIGN KEY (\"c\", \"d\") REFERENCES \"test3\"(\"a\", \"b\")" +
|
||||
")") as String)
|
||||
|
||||
try db.create(table: "test4") { t in
|
||||
t.column("parent", .integer).references("test4")
|
||||
}
|
||||
assertEqualSQL(
|
||||
lastSQLQuery,
|
||||
("CREATE TABLE \"test4\" (" +
|
||||
"\"parent\" INTEGER REFERENCES \"test4\"(\"rowid\")" +
|
||||
")") as String)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -398,7 +440,7 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
XCTAssertEqual(try db.columnCount(in: "test"), 1)
|
||||
|
||||
try db.rename(table: "test", to: "foo")
|
||||
XCTAssertEqual(self.lastSQLQuery, "ALTER TABLE \"test\" RENAME TO \"foo\"")
|
||||
assertEqualSQL(lastSQLQuery, "ALTER TABLE \"test\" RENAME TO \"foo\"")
|
||||
XCTAssertFalse(try db.tableExists("test"))
|
||||
XCTAssertTrue(try db.tableExists("foo"))
|
||||
XCTAssertEqual(try db.columnCount(in: "foo"), 1)
|
||||
@@ -411,15 +453,20 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
try db.create(table: "test") { t in
|
||||
t.column("a", .text)
|
||||
}
|
||||
try db.create(table: "alt") { t in
|
||||
t.column("a", .text)
|
||||
}
|
||||
|
||||
self.sqlQueries.removeAll()
|
||||
sqlQueries.removeAll()
|
||||
try db.alter(table: "test") { t in
|
||||
t.add(column: "b", .text)
|
||||
t.add(column: "c", .integer).notNull().defaults(to: 1)
|
||||
t.add(column: "d", .text).references("alt")
|
||||
}
|
||||
|
||||
XCTAssertEqual(self.sqlQueries[0], "ALTER TABLE \"test\" ADD COLUMN \"b\" TEXT;")
|
||||
XCTAssertEqual(self.sqlQueries[1], " ALTER TABLE \"test\" ADD COLUMN \"c\" INTEGER NOT NULL DEFAULT 1")
|
||||
assertEqualSQL(sqlQueries[sqlQueries.count - 3], "ALTER TABLE \"test\" ADD COLUMN \"b\" TEXT")
|
||||
assertEqualSQL(sqlQueries[sqlQueries.count - 2], "ALTER TABLE \"test\" ADD COLUMN \"c\" INTEGER NOT NULL DEFAULT 1")
|
||||
assertEqualSQL(sqlQueries[sqlQueries.count - 1], "ALTER TABLE \"test\" ADD COLUMN \"d\" TEXT REFERENCES \"alt\"(\"rowid\")")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -434,7 +481,7 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
XCTAssertEqual(try db.columnCount(in: "test"), 2)
|
||||
|
||||
try db.drop(table: "test")
|
||||
XCTAssertEqual(self.lastSQLQuery, "DROP TABLE \"test\"")
|
||||
assertEqualSQL(lastSQLQuery, "DROP TABLE \"test\"")
|
||||
XCTAssertFalse(try db.tableExists("test"))
|
||||
}
|
||||
}
|
||||
@@ -449,10 +496,10 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
}
|
||||
|
||||
try db.create(index: "test_on_a", on: "test", columns: ["a"])
|
||||
XCTAssertEqual(self.lastSQLQuery, "CREATE INDEX \"test_on_a\" ON \"test\"(\"a\")")
|
||||
assertEqualSQL(lastSQLQuery, "CREATE INDEX \"test_on_a\" ON \"test\"(\"a\")")
|
||||
|
||||
try db.create(index: "test_on_a_b", on: "test", columns: ["a", "b"], unique: true, ifNotExists: true)
|
||||
XCTAssertEqual(self.lastSQLQuery, "CREATE UNIQUE INDEX IF NOT EXISTS \"test_on_a_b\" ON \"test\"(\"a\", \"b\")")
|
||||
assertEqualSQL(lastSQLQuery, "CREATE UNIQUE INDEX IF NOT EXISTS \"test_on_a_b\" ON \"test\"(\"a\", \"b\")")
|
||||
|
||||
// Sanity check
|
||||
XCTAssertEqual(try Set(db.indexes(on: "test").map { $0.name }), ["test_on_a", "test_on_a_b"])
|
||||
@@ -475,7 +522,7 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
}
|
||||
|
||||
try db.create(index: "test_on_a_b", on: "test", columns: ["a", "b"], unique: true, ifNotExists: true, condition: Column("a") == 1)
|
||||
XCTAssertEqual(self.lastSQLQuery, "CREATE UNIQUE INDEX IF NOT EXISTS \"test_on_a_b\" ON \"test\"(\"a\", \"b\") WHERE (\"a\" = 1)")
|
||||
assertEqualSQL(lastSQLQuery, "CREATE UNIQUE INDEX IF NOT EXISTS \"test_on_a_b\" ON \"test\"(\"a\", \"b\") WHERE (\"a\" = 1)")
|
||||
|
||||
// Sanity check
|
||||
XCTAssertEqual(try Set(db.indexes(on: "test").map { $0.name }), ["test_on_a_b"])
|
||||
@@ -492,7 +539,7 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
try db.create(index: "test_on_name", on: "test", columns: ["name"])
|
||||
|
||||
try db.drop(index: "test_on_name")
|
||||
XCTAssertEqual(self.lastSQLQuery, "DROP INDEX \"test_on_name\"")
|
||||
assertEqualSQL(lastSQLQuery, "DROP INDEX \"test_on_name\"")
|
||||
|
||||
// Sanity check
|
||||
XCTAssertTrue(try db.indexes(on: "test").isEmpty)
|
||||
|
||||
Reference in new issue
Block a user