diff --git a/SQLite/Typed/Query.swift b/SQLite/Typed/Query.swift index f5803770..e45034ca 100644 --- a/SQLite/Typed/Query.swift +++ b/SQLite/Typed/Query.swift @@ -744,6 +744,13 @@ extension QueryType { ]) } + func tableName(qualified qualified: Bool) -> Expressible { + if qualified { + return tableName() + } + return Expression(clauses.from.alias ?? clauses.from.name) + } + func database(namespace name: String) -> Expressible { let name = Expression(name) diff --git a/SQLite/Typed/Schema.swift b/SQLite/Typed/Schema.swift index f1f0287d..16e11c16 100644 --- a/SQLite/Typed/Schema.swift +++ b/SQLite/Typed/Schema.swift @@ -134,7 +134,7 @@ extension Table { let clauses: [Expressible?] = [ create("INDEX", indexName(columns), unique ? .Unique : nil, ifNotExists), Expression(literal: "ON"), - tableName(), + tableName(qualified: false), "".wrap(columns) as Expression ] @@ -505,7 +505,7 @@ private func definition(column: Expressible, _ datatype: String, _ primaryKey: P private func reference(primary: (QueryType, Expressible)) -> Expressible { return " ".join([ Expression(literal: "REFERENCES"), - primary.0.tableName(), + primary.0.tableName(qualified: false), "".wrap(primary.1) as Expression ]) } diff --git a/SQLiteTests/SchemaTests.swift b/SQLiteTests/SchemaTests.swift index b3cb9a63..416b3646 100644 --- a/SQLiteTests/SchemaTests.swift +++ b/SQLiteTests/SchemaTests.swift @@ -300,6 +300,10 @@ class SchemaTests : XCTestCase { "CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL REFERENCES \"table\" (\"int64\"))", table.create { t in t.column(int64, references: table, int64) } ) + XCTAssertEqual( + "CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL REFERENCES \"table\" (\"int64\"))", + table.create { t in t.column(int64, references: qualifiedTable, int64) } + ) XCTAssertEqual( "CREATE TABLE \"table\" (\"int64\" INTEGER NOT NULL UNIQUE REFERENCES \"table\" (\"int64\"))", table.create { t in t.column(int64, unique: true, references: table, int64) } @@ -724,6 +728,10 @@ class SchemaTests : XCTestCase { "CREATE UNIQUE INDEX IF NOT EXISTS \"index_table_on_int64\" ON \"table\" (\"int64\")", table.createIndex([int64], unique: true, ifNotExists: true) ) + XCTAssertEqual( + "CREATE UNIQUE INDEX IF NOT EXISTS \"main\".\"index_table_on_int64\" ON \"table\" (\"int64\")", + qualifiedTable.createIndex([int64], unique: true, ifNotExists: true) + ) } func test_dropIndex_compilesCreateIndexExpression() { diff --git a/SQLiteTests/TestHelpers.swift b/SQLiteTests/TestHelpers.swift index c0ff9bb9..464b9c27 100644 --- a/SQLiteTests/TestHelpers.swift +++ b/SQLiteTests/TestHelpers.swift @@ -110,5 +110,6 @@ func AssertThrows(@autoclosure expression: () throws -> T, file: StaticString } let table = Table("table") +let qualifiedTable = Table("table", database: "main") let virtualTable = VirtualTable("virtual_table") let _view = View("view") // avoid Mac XCTestCase collision