mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-30 04:28:44 +00:00
SQLTableBuilder: column.check()
This commit is contained in:
1 parent
b1109780ed
commit
5edb5276f8
2 files changed
+33
No files matched your search
@@ -43,6 +43,7 @@ public class SQLColumnBuilder {
|
||||
var primaryKey: (ordering: SQLOrdering?, conflictResolution: SQLConflictResolution?, autoincrement: Bool)?
|
||||
var notNullConflictResolution: SQLConflictResolution?
|
||||
var uniqueConflictResolution: SQLConflictResolution?
|
||||
var checkExpression: _SQLExpression?
|
||||
|
||||
init(name: String, type: SQLColumnType) {
|
||||
self.name = name
|
||||
@@ -61,6 +62,10 @@ public class SQLColumnBuilder {
|
||||
uniqueConflictResolution = conflictResolution ?? .Abort
|
||||
}
|
||||
|
||||
public func check(@noescape condition: (SQLColumn) -> _SQLExpressible) {
|
||||
checkExpression = condition(SQLColumn(name)).sqlExpression
|
||||
}
|
||||
|
||||
var sql: String {
|
||||
var chunks: [String] = []
|
||||
chunks.append(name.quotedDatabaseIdentifier)
|
||||
@@ -100,6 +105,11 @@ public class SQLColumnBuilder {
|
||||
chunks.append(conflictResolution.rawValue)
|
||||
}
|
||||
|
||||
if let checkExpression = checkExpression {
|
||||
var arguments: StatementArguments? = nil // nil so that checkExpression.sql(&arguments) embeds literals
|
||||
chunks.append("CHECK(" + checkExpression.sql(&arguments) + ")")
|
||||
}
|
||||
|
||||
return chunks.joinWithSeparator(" ")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -118,6 +118,29 @@ class SQLTableBuilderTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testColumnCheck() {
|
||||
assertNoError {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.create(table: "test") { t in
|
||||
t.column("a", .Integer).check { $0 > 0 }
|
||||
}
|
||||
XCTAssertEqual(self.lastSQLQuery,
|
||||
"CREATE TABLE \"test\" (" +
|
||||
"\"a\" INTEGER CHECK((\"a\" > 0))" +
|
||||
")")
|
||||
|
||||
// Sanity check
|
||||
try db.execute("INSERT INTO test (a) VALUES (1)")
|
||||
do {
|
||||
try db.execute("INSERT INTO test (a) VALUES (0)")
|
||||
XCTFail()
|
||||
} catch {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testDropTable() {
|
||||
assertNoError {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
Reference in new issue
Block a user