Toward improved DatabaseRegion for joined requests

This commit is contained in:
Gwendal Roué committed 2018-05-01 17:20:37 +02:00
1 parent 8e2cdeebc3
commit ffaabdfd62
7 files changed
+169 -98

No files matched your search

+8 -8
View File
@@ -232,24 +232,24 @@ extension Database {
}
/// Returns the actual name of the database table
func canonicalName(table: String) throws -> String {
if let canonicalName = schemaCache.canonicalName(table: table) {
return canonicalName
func canonicalTableName(_ tableName: String) throws -> String {
if let canonicalTableName = schemaCache.canonicalTableName(tableName) {
return canonicalTableName
}
guard let canonicalName = try String.fetchOne(self, """
guard let canonicalTableName = try String.fetchOne(self, """
SELECT name FROM (
SELECT name, type FROM sqlite_master
UNION
SELECT name, type FROM sqlite_temp_master)
WHERE type = 'table' AND LOWER(name) = ?
""", arguments: [table.lowercased()])
""", arguments: [tableName.lowercased()])
else {
throw DatabaseError(message: "no such table: \(table)")
throw DatabaseError(message: "no such table: \(tableName)")
}
schemaCache.set(canonicalName: canonicalName, forTable: table)
return canonicalName
schemaCache.set(canonicalTableName: canonicalTableName, forTable: tableName)
return canonicalTableName
}
}
+10 -10
View File
@@ -2,8 +2,8 @@
protocol DatabaseSchemaCache {
mutating func clear()
func canonicalName(table: String) -> String?
mutating func set(canonicalName: String, forTable table: String)
func canonicalTableName(_ table: String) -> String?
mutating func set(canonicalTableName: String, forTable table: String)
func primaryKey(_ table: String) -> PrimaryKeyInfo?
mutating func set(primaryKey: PrimaryKeyInfo, forTable table: String)
@@ -20,26 +20,26 @@ protocol DatabaseSchemaCache {
/// A thread-unsafe database schema cache
struct SimpleDatabaseSchemaCache: DatabaseSchemaCache {
private var canonicalNames: [String: String] = [:]
private var canonicalTableNames: [String: String] = [:]
private var primaryKeys: [String: PrimaryKeyInfo] = [:]
private var columns: [String: [ColumnInfo]] = [:]
private var indexes: [String: [IndexInfo]] = [:]
private var foreignKeys: [String: [ForeignKeyInfo]] = [:]
mutating func clear() {
canonicalNames = [:]
canonicalTableNames = [:]
primaryKeys = [:]
columns = [:]
indexes = [:]
foreignKeys = [:]
}
func canonicalName(table: String) -> String? {
return canonicalNames[table]
func canonicalTableName(_ table: String) -> String? {
return canonicalTableNames[table]
}
mutating func set(canonicalName: String, forTable table: String) {
canonicalNames[table] = table
mutating func set(canonicalTableName: String, forTable table: String) {
canonicalTableNames[table] = table
}
func primaryKey(_ table: String) -> PrimaryKeyInfo? {
@@ -79,8 +79,8 @@ struct SimpleDatabaseSchemaCache: DatabaseSchemaCache {
struct EmptyDatabaseSchemaCache: DatabaseSchemaCache {
func clear() { }
func canonicalName(table: String) -> String? { return nil }
func set(canonicalName: String, forTable table: String) { }
func canonicalTableName(_ table: String) -> String? { return nil }
func set(canonicalTableName: String, forTable table: String) { }
func primaryKey(_ table: String) -> PrimaryKeyInfo? { return nil }
func set(primaryKey: PrimaryKeyInfo, forTable table: String) { }
@@ -186,7 +186,7 @@ struct QueryInterfaceQuery {
}
extension QueryInterfaceQuery {
private var qualifiedQuery: QueryInterfaceQuery {
var qualifiedQuery: QueryInterfaceQuery {
var query = self
let alias = TableAlias()
@@ -239,9 +239,9 @@ extension QueryInterfaceQuery {
return adapter.addingScopes(scopes)
}
/// precondition: self is the result of qualifiedQuery
func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
let query = qualifiedQuery
return try (query.makeSelectStatement(db), query.rowAdapter(db))
return try (makeSelectStatement(db), rowAdapter(db))
}
func fetchCount(_ db: Database) throws -> Int {
@@ -250,6 +250,7 @@ extension QueryInterfaceQuery {
}
/// The database region that the request looks into.
/// precondition: self is the result of qualifiedQuery
func fetchedRegion(_ db: Database) throws -> DatabaseRegion {
let statement = try qualifiedQuery.makeSelectStatement(db)
let region = statement.fetchedRegion
@@ -257,7 +258,7 @@ extension QueryInterfaceQuery {
// Can we intersect the region with rowIds?
//
// Give up unless request feeds from a single database table
guard joins.isEmpty, case .table(tableName: let tableName, alias: _) = source else {
guard case .table(tableName: let tableName, alias: _) = source else {
// TODO: try harder
return region
}
@@ -279,7 +280,7 @@ extension QueryInterfaceQuery {
}
// Database regions are case-insensitive: use the canonical table name
let canonicalTableName = try db.canonicalName(table: tableName)
let canonicalTableName = try db.canonicalTableName(tableName)
return region.tableIntersection(canonicalTableName, rowIds: rowIds)
}
@@ -23,7 +23,7 @@ extension QueryInterfaceRequest : FetchRequest {
/// - returns: A prepared statement and an eventual row adapter.
/// :nodoc:
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
return try query.prepare(db)
return try query.qualifiedQuery.prepare(db)
}
/// Returns the number of rows fetched by the request.
@@ -39,7 +39,7 @@ extension QueryInterfaceRequest : FetchRequest {
/// - parameter db: A database connection.
/// :nodoc:
public func fetchedRegion(_ db: Database) throws -> DatabaseRegion {
return try query.fetchedRegion(db)
return try query.qualifiedQuery.fetchedRegion(db)
}
}
@@ -292,42 +292,7 @@ public struct SQLExpressionBinary : SQLExpression {
return SQLExpressionNot(self)
}
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func matchedRowIds(rowIdName: String?) -> Set<Int64>? {
// FIXME: this implementation ignores column aliases
switch op {
case .equal, .is:
// Look for `id ==/IS 1`, `rowid ==/IS 1`, `1 ==/IS id`, `1 ==/IS rowid`
func matchedRowIds(column: ColumnExpression, dbValue: DatabaseValue) -> Set<Int64>? {
var rowIdNames = [Column.rowID.name.lowercased()]
if let rowIdName = rowIdName {
rowIdNames.append(rowIdName.lowercased())
}
guard rowIdNames.contains(column.name.lowercased()) else {
return nil
}
if let rowId = Int64.fromDatabaseValue(dbValue) {
return [rowId]
} else {
return []
}
}
switch (lhs, rhs) {
case (let column as ColumnExpression, let dbValue as DatabaseValue):
return matchedRowIds(column: column, dbValue: dbValue)
case (let dbValue as DatabaseValue, let column as ColumnExpression):
return matchedRowIds(column: column, dbValue: dbValue)
default:
return nil
}
default:
return nil
}
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
@@ -425,6 +390,91 @@ struct SQLExpressionOr : SQLExpression {
}
}
// MARK: - SQLExpressionEqual
struct SQLExpressionEqual: SQLExpression {
var lhs: SQLExpression
var rhs: SQLExpression
var op: Operator
init(_ op: Operator, _ lhs: SQLExpression, _ rhs: SQLExpression) {
self.lhs = lhs
self.rhs = rhs
self.op = op
}
enum Operator: String {
case equal = "="
case notEqual = "<>"
case `is` = "IS"
case isNot = "IS NOT"
var negated: Operator {
switch self {
case .equal: return .notEqual
case .notEqual: return .equal
case .is: return .isNot
case .isNot: return .is
}
}
}
func expressionSQL(_ context: inout SQLGenerationContext) -> String {
return "(" +
lhs.expressionSQL(&context) +
" " +
op.rawValue +
" " +
rhs.expressionSQL(&context) +
")"
}
var negated: SQLExpression {
return SQLExpressionEqual(op.negated, lhs, rhs)
}
func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
return SQLExpressionEqual(op, lhs.qualifiedExpression(with: alias), rhs.qualifiedExpression(with: alias))
}
func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression {
return SQLExpressionEqual(op, lhs.resolvedExpression(inContext: context), rhs.resolvedExpression(inContext: context))
}
func matchedRowIds(rowIdName: String?) -> Set<Int64>? {
// FIXME: this implementation ignores column aliases
switch op {
case .equal, .is:
// Look for `id ==/IS 1`, `rowid ==/IS 1`, `1 ==/IS id`, `1 ==/IS rowid`
func matchedRowIds(column: ColumnExpression, dbValue: DatabaseValue) -> Set<Int64>? {
var rowIdNames = [Column.rowID.name.lowercased()]
if let rowIdName = rowIdName {
rowIdNames.append(rowIdName.lowercased())
}
guard rowIdNames.contains(column.name.lowercased()) else {
return nil
}
if let rowId = Int64.fromDatabaseValue(dbValue) {
return [rowId]
} else {
return []
}
}
switch (lhs, rhs) {
case (let column as ColumnExpression, let dbValue as DatabaseValue):
return matchedRowIds(column: column, dbValue: dbValue)
case (let dbValue as DatabaseValue, let column as ColumnExpression):
return matchedRowIds(column: column, dbValue: dbValue)
default:
return nil
}
case .notEqual, .isNot:
return nil
}
}
}
// MARK: - SQLExpressionContains
/// SQLExpressionContains is an expression that checks the inclusion of a
@@ -455,7 +505,14 @@ struct SQLExpressionContains : SQLExpression {
return SQLExpressionContains(expression, collection, negated: !isNegated)
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
return SQLExpressionContains(expression.qualifiedExpression(with: alias), collection, negated: isNegated)
}
func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression {
return SQLExpressionContains(expression.resolvedExpression(inContext: context), collection, negated: isNegated)
}
func matchedRowIds(rowIdName: String?) -> Set<Int64>? {
// FIXME: this implementation ignores column aliases
// Look for `id IN (1, 2, 3)`
@@ -469,7 +526,7 @@ struct SQLExpressionContains : SQLExpression {
if let rowIdName = rowIdName {
rowIdNames.append(rowIdName.lowercased())
}
guard rowIdNames.contains(column.name.lowercased()) else {
return nil
}
@@ -483,14 +540,6 @@ struct SQLExpressionContains : SQLExpression {
}
return rowIDs
}
func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
return SQLExpressionContains(expression.qualifiedExpression(with: alias), collection, negated: isNegated)
}
func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression {
return SQLExpressionContains(expression.resolvedExpression(inContext: context), collection, negated: isNegated)
}
}
// MARK: - SQLExpressionBetween
+13 -27
View File
@@ -1,38 +1,24 @@
// MARK: - Egality and Identity Operators (=, <>, IS, IS NOT)
extension SQLBinaryOperator {
/// The `=` binary operator
static let equal = SQLBinaryOperator("=", negated: "<>")
/// The `<>` binary operator
static let notEqual = SQLBinaryOperator("<>", negated: "=")
/// The `IS` binary operator
static let `is` = SQLBinaryOperator("IS", negated: "IS NOT")
/// The `IS NOT` binary operator
static let isNot = SQLBinaryOperator("IS NOT", negated: "IS")
}
// Outputs "x = y" or "x IS NULL"
private func isEqual(_ lhs: SQLExpression, _ rhs: SQLExpression) -> SQLExpression {
switch (lhs, rhs) {
case (let lhs, let rhs as DatabaseValue):
switch rhs.storage {
case .null:
return SQLExpressionBinary(.is, lhs, DatabaseValue.null)
return SQLExpressionEqual(.is, lhs, rhs)
default:
return SQLExpressionBinary(.equal, lhs, rhs)
return SQLExpressionEqual(.equal, lhs, rhs)
}
case (let lhs as DatabaseValue, let rhs):
switch lhs.storage {
case .null:
return SQLExpressionBinary(.is, rhs, DatabaseValue.null)
return SQLExpressionEqual(.is, rhs, lhs)
default:
return SQLExpressionBinary(.equal, lhs, rhs)
return SQLExpressionEqual(.equal, lhs, rhs)
}
default:
return SQLExpressionBinary(.equal, lhs, rhs)
return SQLExpressionEqual(.equal, lhs, rhs)
}
}
@@ -229,7 +215,7 @@ public func != (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL
/// // name IS 'Arthur'
/// Column("name") === "Arthur"
public func === (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpression {
return SQLExpressionBinary(.is, lhs.sqlExpression, rhs?.sqlExpression ?? DatabaseValue.null)
return SQLExpressionEqual(.is, lhs.sqlExpression, rhs?.sqlExpression ?? DatabaseValue.null)
}
/// An SQL expression that compares two expressions with the `IS` SQL operator.
@@ -246,9 +232,9 @@ public func === (lhs: SQLCollatedExpression, rhs: SQLExpressible?) -> SQLExpress
/// "Arthur" === Column("name")
public func === (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpression {
if let lhs = lhs {
return SQLExpressionBinary(.is, lhs.sqlExpression, rhs.sqlExpression)
return SQLExpressionEqual(.is, lhs.sqlExpression, rhs.sqlExpression)
} else {
return SQLExpressionBinary(.is, rhs.sqlExpression, DatabaseValue.null)
return SQLExpressionEqual(.is, rhs.sqlExpression, DatabaseValue.null)
}
}
@@ -265,7 +251,7 @@ public func === (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> SQLExpress
/// // email IS login
/// Column("email") === Column("login")
public func === (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression {
return SQLExpressionBinary(.is, lhs.sqlExpression, rhs.sqlExpression)
return SQLExpressionEqual(.is, lhs.sqlExpression, rhs.sqlExpression)
}
/// An SQL expression that compares two expressions with the `IS NOT` SQL operator.
@@ -273,7 +259,7 @@ public func === (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQ
/// // name IS NOT 'Arthur'
/// Column("name") !== "Arthur"
public func !== (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpression {
return SQLExpressionBinary(.isNot, lhs.sqlExpression, rhs?.sqlExpression ?? DatabaseValue.null)
return SQLExpressionEqual(.isNot, lhs.sqlExpression, rhs?.sqlExpression ?? DatabaseValue.null)
}
/// An SQL expression that compares two expressions with the `IS NOT` SQL operator.
@@ -290,9 +276,9 @@ public func !== (lhs: SQLCollatedExpression, rhs: SQLExpressible?) -> SQLExpress
/// "Arthur" !== Column("name")
public func !== (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpression {
if let lhs = lhs {
return SQLExpressionBinary(.isNot, lhs.sqlExpression, rhs.sqlExpression)
return SQLExpressionEqual(.isNot, lhs.sqlExpression, rhs.sqlExpression)
} else {
return SQLExpressionBinary(.isNot, rhs.sqlExpression, DatabaseValue.null)
return SQLExpressionEqual(.isNot, rhs.sqlExpression, DatabaseValue.null)
}
}
@@ -309,7 +295,7 @@ public func !== (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> SQLExpress
/// // email IS NOT login
/// Column("email") !== Column("login")
public func !== (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression {
return SQLExpressionBinary(.isNot, lhs.sqlExpression, rhs.sqlExpression)
return SQLExpressionEqual(.isNot, lhs.sqlExpression, rhs.sqlExpression)
}
+35
View File
@@ -410,6 +410,41 @@ class DatabaseRegionTests : GRDBTestCase {
}
}
func testDatabaseRegionOfJoinedRequests() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE a (id INTEGER PRIMARY KEY, name TEXT)")
try db.execute("CREATE TABLE b (id INTEGER PRIMARY KEY, name TEXT, aid INTEGER REFERENCES a(id))")
try db.execute("CREATE TABLE c (id INTEGER PRIMARY KEY, name TEXT, aid INTEGER REFERENCES a(id))")
struct A: TableRecord {
static let databaseTableName = "a"
static let b = hasOne(B.self)
static let c = hasMany(C.self)
}
struct B: TableRecord {
static let databaseTableName = "b"
static let a = belongsTo(A.self)
}
struct C: TableRecord {
static let databaseTableName = "c"
}
do {
let request = A.filter(key: 1)
.including(optional: A.b.filter(key: 2))
.including(optional: A.c.filter(keys: [1, 2, 3]))
// This test will fail when we are able to improve regions of joined requestt
try XCTAssertEqual(request.fetchedRegion(db).description, "a(id,name)[1],b(aid,id,name),c(aid,id,name)")
}
do {
let request = B.filter(key: 1)
.including(optional: B.a.filter(key: 2)
.including(optional: A.c.filter(keys: [1, 2, 3])))
// This test will fail when we are able to improve regions of joined requestt
try XCTAssertEqual(request.fetchedRegion(db).description, "a(id,name),b(aid,id,name)[1],c(aid,id,name)")
}
}
}
func testDatabaseRegionOfDerivedRequests() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in