Introduce FastPrimaryKeyExpression, drop SQLPrimaryKeyExpression

Also, don't let the user access this expression, so that he does not attempt at decoding it. Its only purpose is to generate efficient SQL.
This commit is contained in:
Gwendal Roué committed 2020-07-01 20:40:11 +02:00
1 parent bd4a76d5de
commit 2201026ce8
22 files changed
+151 -284

No files matched your search

+2 -1
View File
@@ -71,7 +71,8 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
## Next Release
- **Breaking Change**: [#803](https://github.com/groue/GRDB.swift/pull/803): Remove FetchedRecordsController
- **Breaking Change**: Removed `TableRecord.primaryKey` and `selectPrimaryKey(as:)` introduced in 5.0.0-beta.5
- The [How do I filter records and only keep those that are NOT associated to another record?](README.md#how-do-i-filter-records-and-only-keep-those-that-are-not-associated-to-another-record) FAQ has been updated.
## 5.0.0-beta.6
+30 -7
View File
@@ -140,17 +140,28 @@ extension Database {
if pkColumn.type.uppercased() == "INTEGER" {
primaryKey = .rowID(pkColumn.name)
} else {
primaryKey = .regular([pkColumn.name])
primaryKey = try .regular([pkColumn.name], tableHasRowID: tableHasRowID(tableName))
}
default:
// Multi-columns primary key
primaryKey = .regular(pkColumns.map(\.name))
primaryKey = try .regular(pkColumns.map(\.name), tableHasRowID: tableHasRowID(tableName))
}
schemaCache.set(primaryKey: primaryKey, forTable: tableName)
return primaryKey
}
/// Returns whether the table has a rowid column.
private func tableHasRowID(_ tableName: String) throws -> Bool {
// Not need to cache the result, because this information feeds
// `PrimaryKeyInfo`, which is cached.
do {
_ = try makeSelectStatement(sql: "SELECT rowID FROM \(tableName.quotedDatabaseIdentifier)")
return true
} catch DatabaseError.SQLITE_ERROR {
return false
}
}
/// The indexes on table named `tableName`; returns the empty array if the
/// table does not exist.
///
@@ -521,7 +532,7 @@ public struct PrimaryKeyInfo {
/// Any primary key, but INTEGER PRIMARY KEY.
/// Associated strings are column names.
case regular([String])
case regular(columns: [String], tableHasRowID: Bool)
}
private let impl: Impl
@@ -530,9 +541,9 @@ public struct PrimaryKeyInfo {
PrimaryKeyInfo(impl: .rowID(column))
}
static func regular(_ columns: [String]) -> PrimaryKeyInfo {
static func regular(_ columns: [String], tableHasRowID: Bool) -> PrimaryKeyInfo {
assert(!columns.isEmpty)
return PrimaryKeyInfo(impl: .regular(columns))
return PrimaryKeyInfo(impl: .regular(columns: columns, tableHasRowID: tableHasRowID))
}
static let hiddenRowID = PrimaryKeyInfo(impl: .hiddenRowID)
@@ -542,9 +553,9 @@ public struct PrimaryKeyInfo {
switch impl {
case .hiddenRowID:
return [Column.rowID.name]
case .rowID(let column):
case let .rowID(column):
return [column]
case .regular(let columns):
case let .regular(columns: columns, tableHasRowID: _):
return columns
}
}
@@ -572,6 +583,18 @@ public struct PrimaryKeyInfo {
return false
}
}
/// When false, the table is a WITHOUT ROWID table
var tableHasRowID: Bool {
switch impl {
case .hiddenRowID:
return true
case .rowID:
return true
case let .regular(columns: _, tableHasRowID: tableHasRowID):
return tableHasRowID
}
}
}
/// You get foreign keys from table names, with the
@@ -38,9 +38,7 @@ extension AssociationToMany {
///
/// let teams: [Team] = try Team.having(Team.players.count() > 10).fetchAll(db)
public var count: AssociationAggregate<OriginRowDecoder> {
let expression = SQLExpressionCountDistinct(
SQLPrimaryKeyExpression(
tableName: self.databaseTableName))
let expression = SQLExpressionCountDistinct(FastPrimaryKeyExpression())
return makeAggregate(expression).forKey("\(key.singularizedName)Count")
}
@@ -60,10 +58,7 @@ extension AssociationToMany {
/// let teams: [Team] = try Team.having(!Team.players.isEmpty())
/// let teams: [Team] = try Team.having(Team.players.isEmpty() == false)
public var isEmpty: AssociationAggregate<OriginRowDecoder> {
let expression = SQLExpressionIsEmpty(
SQLExpressionCountDistinct(
SQLPrimaryKeyExpression(
tableName: self.databaseTableName)))
let expression = SQLExpressionIsEmpty(SQLExpressionCountDistinct(FastPrimaryKeyExpression()))
return makeAggregate(expression).forKey("hasNo\(key.singularizedName.uppercasingFirstCharacter)")
}
@@ -192,30 +192,6 @@ extension QueryInterfaceRequest: SelectionRequest {
public func annotated(with selection: @escaping (Database) throws -> [SQLSelectable]) -> QueryInterfaceRequest {
map(\.query) { $0.annotated(with: selection) }
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// Creates a request which selects the primary key of the table.
///
/// For example:
///
/// struct Player: TableRecord { ... }
///
/// let playerIds = dbQueue.read { db in
/// try Player.all().selectPrimaryKey(as: Int64.self).fetchAll(db)
/// }
///
/// For tables that have no explicit primary key, the request selects the
/// `rowid` column.
///
/// For tables whose primary key spans several columns, the current
/// implementation also returns a request that selects the `rowid` column.
/// Future GRDB versions may return a [row value](https://www.sqlite.org/rowvalue.html).
public func selectPrimaryKey<RowDecoder>(as type: RowDecoder.Type = RowDecoder.self)
-> QueryInterfaceRequest<RowDecoder>
{
select(SQLPrimaryKeyExpression(tableName: databaseTableName), as: RowDecoder.self)
}
}
extension QueryInterfaceRequest: FilteredRequest {
@@ -780,61 +780,46 @@ struct SQLExpressionCollate: SQLExpression {
}
}
// MARK: - SQLPrimaryKeyExpression
// MARK: - FastPrimaryKeyExpression
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// SQLPrimaryKeyExpression is the primary key of a table.
/// FastPrimaryKeyExpression is an expression that picks the fastest available
/// primary key.
///
/// For tables that have no explicit primary key, SQLPrimaryKeyExpression is the
/// `rowid` column.
///
/// For tables whose primary key spans several columns, the current
/// implementation of SQLPrimaryKeyExpression also is the `rowid` column. Future
/// GRDB versions may return a [row value](https://www.sqlite.org/rowvalue.html).
///
/// For example:
///
/// struct Player: TableRecord { ... }
///
/// let player = dbQueue.read { db in
/// try Player.filter(Player.primaryKey == 12).fetchOne(db)
/// }
public struct SQLPrimaryKeyExpression: SQLExpression {
let tableName: String
/// Support for SQLPrimaryKeyExpression and SQLQualifiedPrimaryKeyExpression
fileprivate static func primaryKeyColumn(_ db: Database, tableName: String) throws -> Column {
let columns = try db.primaryKey(tableName).columns
if columns.count == 1 {
return Column(columns[0])
} else {
return Column.rowID
}
/// It crashes for WITHOUT ROWID table with a multi-columns primary key.
/// Future versions of GRDB may use [row values](https://www.sqlite.org/rowvalue.html).
struct FastPrimaryKeyExpression: SQLExpression {
func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
// Likely a GRDB bug: how comes this expression is used before it
// has been qualified?
fatalError("FastPrimaryKeyExpression was not qualified.")
}
public func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
try SQLPrimaryKeyExpression
.primaryKeyColumn(context.db, tableName: tableName)
.expressionSQL(context, wrappedInParenthesis: wrappedInParenthesis)
}
public func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
SQLQualifiedPrimaryKeyExpression(tableName: tableName, alias: alias)
func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
QualifiedFastPrimaryKeyExpression(alias: alias)
}
}
struct SQLQualifiedPrimaryKeyExpression: SQLExpression {
let tableName: String
struct QualifiedFastPrimaryKeyExpression: SQLExpression {
let alias: TableAlias
func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
GRDBPrecondition(
tableName.lowercased() == alias.tableName.lowercased(),
"Table names don't match: \(tableName) and \(alias.tableName)")
return try SQLPrimaryKeyExpression
.primaryKeyColumn(context.db, tableName: tableName)
let column: Column
let primaryKey = try context.db.primaryKey(alias.tableName)
if let rowIDColumn = primaryKey.rowIDColumn {
// Prefer the user-provided name of the row id
column = Column(rowIDColumn)
} else if primaryKey.tableHasRowID {
// Prefer the row id
column = .rowID
} else if primaryKey.columns.count == 1 {
// WITHOUT ROWID table: use primary key column
column = Column(primaryKey.columns[0])
} else {
fatalError("Not implemented: WITHOUT ROWID table with a multi-columns primary key")
}
return try column
.qualifiedExpression(with: alias)
.expressionSQL(context, wrappedInParenthesis: wrappedInParenthesis)
}
@@ -357,6 +357,14 @@ public class TableAlias: Hashable {
ordering.qualifiedOrdering(with: self)
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// An expression that evaluates to true if the record refered by this
/// `TableAlias` exists.
public var exists: SQLExpression {
QualifiedFastPrimaryKeyExpression(alias: self) != nil
}
/// :nodoc:
public func hash(into hasher: inout Hasher) {
hasher.combine(ObjectIdentifier(root))
@@ -346,13 +346,15 @@ struct SQLQueryGenerator: Refinable {
fatalError("Can't delete without any database table")
}
let context = SQLGenerationContext(db)
let primaryKey = SQLPrimaryKeyExpression(tableName: tableName)
let alias = TableAlias(tableName: tableName)
let context = SQLGenerationContext(db, aliases: [alias])
let subqueryContext = SQLGenerationContext(parent: context, aliases: relation.allAliases)
let primaryKey = FastPrimaryKeyExpression()
var sql = "DELETE FROM \(tableName.quotedDatabaseIdentifier) WHERE "
sql += try primaryKey.expressionSQL(context, wrappedInParenthesis: false)
sql += try alias[primaryKey].expressionSQL(context, wrappedInParenthesis: false)
sql += " IN ("
sql += try map(\.relation, { $0.selectOnly([primaryKey]) }).requestSQL(context)
sql += try map(\.relation, { $0.selectOnly([primaryKey]) }).requestSQL(subqueryContext)
sql += ")"
let statement = try db.makeUpdateStatement(sql: sql)
@@ -450,8 +452,10 @@ struct SQLQueryGenerator: Refinable {
return nil
}
let context = SQLGenerationContext(db)
let primaryKey = SQLPrimaryKeyExpression(tableName: tableName)
let alias = TableAlias(tableName: tableName)
let context = SQLGenerationContext(db, aliases: [alias])
let subqueryContext = SQLGenerationContext(parent: context, aliases: relation.allAliases)
let primaryKey = FastPrimaryKeyExpression()
// UPDATE table...
var sql = "UPDATE "
@@ -468,9 +472,9 @@ struct SQLQueryGenerator: Refinable {
// WHERE id IN (SELECT id FROM ...)
sql += " WHERE "
sql += try primaryKey.expressionSQL(context, wrappedInParenthesis: false)
sql += try alias[primaryKey].expressionSQL(context, wrappedInParenthesis: false)
sql += " IN ("
sql += try map(\.relation, { $0.selectOnly([primaryKey]) }).requestSQL(context)
sql += try map(\.relation, { $0.selectOnly([primaryKey]) }).requestSQL(subqueryContext)
sql += ")"
let statement = try db.makeUpdateStatement(sql: sql)
@@ -126,31 +126,6 @@ extension TableRecord {
all().select(literal: sqlLiteral, as: type)
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// Creates a request which selects the primary key of the table.
///
/// For example:
///
/// struct Player: TableRecord { ... }
///
/// let playerIds = dbQueue.read { db in
/// try Player.selectPrimaryKey(as: Int64.self).fetchAll(db)
/// }
///
/// For tables that have no explicit primary key, the request selects the
/// `rowid` column.
///
/// For tables whose primary key spans several columns, the current
/// implementation also returns a request that selects the `rowid` column.
/// Future GRDB versions may return a [row value](https://www.sqlite.org/rowvalue.html).
public static func selectPrimaryKey<RowDecoder>(
as type: RowDecoder.Type = RowDecoder.self)
-> QueryInterfaceRequest<RowDecoder>
{
all().selectPrimaryKey(as: type)
}
/// Creates a request which appends *selection*.
///
/// // SELECT id, email, name FROM player
-26
View File
@@ -140,32 +140,6 @@ extension TableRecord {
}
}
extension TableRecord {
// MARK: - Primary Key
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// The primary key of the table.
///
/// For example:
///
/// struct Player: TableRecord { ... }
///
/// let player = dbQueue.read { db in
/// try Player.filter(Player.primaryKey == 12).fetchOne(db)
/// }
///
/// For tables that have no explicit primary key, this property returns the
/// `rowid` column.
///
/// For tables whose primary key spans several columns, the current
/// implementation also returns the `rowid` column. Future GRDB versions
/// may return a [row value](https://www.sqlite.org/rowvalue.html).
public static var primaryKey: SQLPrimaryKeyExpression {
SQLPrimaryKeyExpression(tableName: databaseTableName)
}
}
/// Calculating `defaultDatabaseTableName` is somewhat expensive due to the regular expression evaluation
///
/// This cache mitigates the cost of the calculation by storing the name for later retrieval
+1 -21
View File
@@ -3622,7 +3622,6 @@ This is the list of record methods, along with their required protocols. The [Re
| `Type.none()` | [TableRecord] | <a href="#list-of-record-methods-2">²</a> |
| `Type.select(...)` | [TableRecord] | <a href="#list-of-record-methods-2">²</a> |
| `Type.select(..., as:...)` | [TableRecord] | <a href="#list-of-record-methods-2">²</a> |
| `Type.selectPrimaryKey(as:...)` | [TableRecord] | <a href="#list-of-record-methods-2">²</a> |
| `Type.annotated(with:...)` | [TableRecord] | <a href="#list-of-record-methods-2">²</a> |
| `Type.filter(...)` | [TableRecord] | <a href="#list-of-record-methods-2">²</a> |
| `Type.matching(...)` | [TableRecord] | <a href="#list-of-record-methods-2">²</a> |
@@ -4144,25 +4143,6 @@ You can now build requests with the following methods: `all`, `none`, `select`,
- Other requests that involve the primary key:
- `selectPrimaryKey(as:)` selects the primary key.
```swift
// SELECT id FROM player
Player.selectPrimaryKey(as: Int64.self)
// SELECT code FROM country
Country.selectPrimaryKey(as: String.self)
```
It is equivalent to:
```swift
Player.select(Player.primaryKey, as: Int64.self)
Country.select(Country.primaryKey, as: Int64.self)
```
> :point_up: **Note**: `selectPrimaryKey` and `primaryKey` are [experimental](#what-are-experimental-features) and currently pick the `rowid` column for tables that have a composite primary key that spans several columns. Future GRDB version may change this behavior.
- `orderByPrimaryKey()` sorts by primary key.
```swift
@@ -7584,7 +7564,7 @@ let books: [Book] = try dbQueue.read { db in
let authorAlias = TableAlias()
let request = Book
.joining(optional: Book.author.aliased(authorAlias))
.filter(authorAlias[Author.primaryKey] == nil)
.filter(!authorAlias.exists)
return try request.fetchAll(db)
}
```
@@ -1179,7 +1179,7 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
let authorAlias = TableAlias()
let request = Book
.joining(optional: Book.author.aliased(authorAlias))
.filter(authorAlias[Author.primaryKey] == nil)
.filter(!authorAlias.exists)
try assertEqualSQL(db, request, """
SELECT "book".* FROM "book" \
LEFT JOIN "author" ON "author"."id" = "book"."authorID" \
+29 -1
View File
@@ -1,5 +1,5 @@
import XCTest
import GRDB
@testable import GRDB
class PrimaryKeyInfoTests: GRDBTestCase {
@@ -11,6 +11,7 @@ class PrimaryKeyInfoTests: GRDBTestCase {
XCTAssertEqual(primaryKey.columns, [Column.rowID.name])
XCTAssertNil(primaryKey.rowIDColumn)
XCTAssertTrue(primaryKey.isRowID)
XCTAssertTrue(primaryKey.tableHasRowID)
}
}
@@ -22,6 +23,7 @@ class PrimaryKeyInfoTests: GRDBTestCase {
XCTAssertEqual(primaryKey.columns, ["id"])
XCTAssertEqual(primaryKey.rowIDColumn, "id")
XCTAssertTrue(primaryKey.isRowID)
XCTAssertTrue(primaryKey.tableHasRowID)
}
}
@@ -33,6 +35,7 @@ class PrimaryKeyInfoTests: GRDBTestCase {
XCTAssertEqual(primaryKey.columns, ["name"])
XCTAssertNil(primaryKey.rowIDColumn)
XCTAssertFalse(primaryKey.isRowID)
XCTAssertTrue(primaryKey.tableHasRowID)
}
}
@@ -44,6 +47,31 @@ class PrimaryKeyInfoTests: GRDBTestCase {
XCTAssertEqual(primaryKey.columns, ["a", "b"])
XCTAssertNil(primaryKey.rowIDColumn)
XCTAssertFalse(primaryKey.isRowID)
XCTAssertTrue(primaryKey.tableHasRowID)
}
}
func testNonRowIDPrimaryKeyWithoutRowID() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute(sql: "CREATE TABLE items (name TEXT PRIMARY KEY) WITHOUT ROWID")
let primaryKey = try db.primaryKey("items")
XCTAssertEqual(primaryKey.columns, ["name"])
XCTAssertNil(primaryKey.rowIDColumn)
XCTAssertFalse(primaryKey.isRowID)
XCTAssertFalse(primaryKey.tableHasRowID)
}
}
func testCompoundPrimaryKeyWithoutRowID() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute(sql: "CREATE TABLE items (a TEXT, b INTEGER, PRIMARY KEY (a,b)) WITHOUT ROWID")
let primaryKey = try db.primaryKey("items")
XCTAssertEqual(primaryKey.columns, ["a", "b"])
XCTAssertNil(primaryKey.rowIDColumn)
XCTAssertFalse(primaryKey.isRowID)
XCTAssertFalse(primaryKey.tableHasRowID)
}
}
}
@@ -1,5 +1,5 @@
import XCTest
import GRDB
@testable import GRDB
private struct Col {
static let id = Column("id")
@@ -1260,4 +1260,41 @@ class QueryInterfaceExpressionsTests: GRDBTestCase {
sql(dbQueue, tableRequest.select(customFunction(Col.age, 1, 2))),
"SELECT avgOf(\"age\", 1, 2) FROM \"readers\"")
}
// MARK: - FastPrimaryKeyExpression
func testFastPrimaryKeyExpression() throws {
struct IntegerPrimaryKeyRecord: TableRecord { }
struct UUIDRecord: TableRecord { }
struct UUIDRecordWithoutRowID: TableRecord { }
struct RowIDRecord: TableRecord { }
struct CompoundPrimaryKeyRecord: TableRecord { }
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.execute(sql: """
CREATE TABLE integerPrimaryKeyRecord (id INTEGER PRIMARY KEY);
CREATE TABLE uuidRecord (uuid TEXT PRIMARY KEY);
CREATE TABLE uuidRecordWithoutRowID (uuid TEXT PRIMARY KEY) WITHOUT ROWID;
CREATE TABLE rowIDRecord (name TEXT);
CREATE TABLE compoundPrimaryKeyRecord (a INTEGER, b INTEGER, PRIMARY KEY (a, b));
""")
try assertEqualSQL(db, IntegerPrimaryKeyRecord.select(FastPrimaryKeyExpression()), """
SELECT "id" FROM "integerPrimaryKeyRecord"
""")
try assertEqualSQL(db, UUIDRecord.select(FastPrimaryKeyExpression()), """
SELECT "rowid" FROM "uuidRecord"
""")
try assertEqualSQL(db, UUIDRecordWithoutRowID.select(FastPrimaryKeyExpression()), """
SELECT "uuid" FROM "uuidRecordWithoutRowID"
""")
try assertEqualSQL(db, RowIDRecord.select(FastPrimaryKeyExpression()), """
SELECT "rowid" FROM "rowIDRecord"
""")
try assertEqualSQL(db, CompoundPrimaryKeyRecord.select(FastPrimaryKeyExpression()), """
SELECT "rowid" FROM "compoundPrimaryKeyRecord"
""")
}
}
}
@@ -391,17 +391,6 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase {
}
// MARK: - Select Primary Key
func testSelectPrimaryKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let request: QueryInterfaceRequest<Int64> = MinimalRowID.selectPrimaryKey()
try assertEqualSQL(db, request, "SELECT \"id\" FROM \"minimalRowIDs\"")
}
}
// MARK: - Fetch With Primary Key
func testFetchCursorWithPrimaryKeys() throws {
@@ -407,17 +407,6 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
}
// MARK: - Select Primary Key
func testSelectPrimaryKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let request: QueryInterfaceRequest<UUID> = MinimalSingle.selectPrimaryKey()
try assertEqualSQL(db, request, "SELECT \"UUID\" FROM \"minimalSingles\"")
}
}
// MARK: - Fetch With Primary Key
func testFetchCursorWithPrimaryKeys() throws {
@@ -477,17 +477,6 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase {
}
// MARK: - Select Primary Key
func testSelectPrimaryKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let request: QueryInterfaceRequest<Int64> = Person.selectPrimaryKey()
try assertEqualSQL(db, request, "SELECT \"rowid\" FROM \"persons\"")
}
}
// MARK: - Fetch With Primary Key
func testFetchCursorWithPrimaryKeys() throws {
@@ -430,18 +430,6 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase {
}
// MARK: - Select Primary Key
func testSelectPrimaryKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let request: QueryInterfaceRequest<Int64> = Citizenship.selectPrimaryKey()
// May change in a future release, when we support SQLite row values.
try assertEqualSQL(db, request, "SELECT \"rowid\" FROM \"citizenships\"")
}
}
// MARK: - Exists
func testExistsWithNilPrimaryKeyReturnsFalse() throws {
@@ -125,17 +125,6 @@ class RecordPrimaryKeyNoneTests: GRDBTestCase {
}
// MARK: - Select Primary Key
func testSelectPrimaryKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let request: QueryInterfaceRequest<Int64> = Item.selectPrimaryKey()
try assertEqualSQL(db, request, "SELECT \"rowid\" FROM \"items\"")
}
}
// MARK: - Fetch With Primary Key
func testFetchCursorWithPrimaryKeys() throws {
@@ -473,17 +473,6 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase {
}
// MARK: - Select Primary Key
func testSelectPrimaryKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let request: QueryInterfaceRequest<Int64> = Person.selectPrimaryKey()
try assertEqualSQL(db, request, "SELECT \"id\" FROM \"persons\"")
}
}
// MARK: - Fetch With Primary Key
func testFetchCursorWithPrimaryKeys() throws {
@@ -421,17 +421,6 @@ class RecordPrimaryKeySingleTests: GRDBTestCase {
}
// MARK: - Select Primary Key
func testSelectPrimaryKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let request: QueryInterfaceRequest<UUID> = Pet.selectPrimaryKey()
try assertEqualSQL(db, request, "SELECT \"UUID\" FROM \"pets\"")
}
}
// MARK: - Fetch With Primary Key
func testFetchCursorWithPrimaryKeys() throws {
@@ -414,17 +414,6 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase {
}
// MARK: - Select Primary Key
func testSelectPrimaryKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let request: QueryInterfaceRequest<String> = Email.selectPrimaryKey()
try assertEqualSQL(db, request, "SELECT \"email\" FROM \"emails\"")
}
}
// MARK: - Fetch With Primary Key
func testFetchCursorWithPrimaryKeys() throws {
-30
View File
@@ -125,34 +125,4 @@ class TableRecordTests: GRDBTestCase {
XCTAssertEqual(lastSQLQuery, "SELECT \"a\", \"b\" FROM \"t1\"")
}
}
func testPrimaryKey() throws {
struct IntegerPrimaryKeyRecord: TableRecord { }
struct UUIDRecord: TableRecord { }
struct RowIDRecord: TableRecord { }
struct CompoundPrimaryKeyRecord: TableRecord { }
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.execute(sql: """
CREATE TABLE integerPrimaryKeyRecord (id INTEGER PRIMARY KEY);
CREATE TABLE uuidRecord (uuid TEXT PRIMARY KEY);
CREATE TABLE rowIDRecord (name TEXT);
CREATE TABLE compoundPrimaryKeyRecord (a INTEGER, b INTEGER, PRIMARY KEY (a, b));
""")
try assertEqualSQL(db, IntegerPrimaryKeyRecord.order(IntegerPrimaryKeyRecord.primaryKey), """
SELECT * FROM "integerPrimaryKeyRecord" ORDER BY "id"
""")
try assertEqualSQL(db, UUIDRecord.order(UUIDRecord.primaryKey), """
SELECT * FROM "uuidRecord" ORDER BY "uuid"
""")
try assertEqualSQL(db, RowIDRecord.order(RowIDRecord.primaryKey), """
SELECT * FROM "rowIDRecord" ORDER BY "rowid"
""")
try assertEqualSQL(db, CompoundPrimaryKeyRecord.order(CompoundPrimaryKeyRecord.primaryKey), """
SELECT * FROM "compoundPrimaryKeyRecord" ORDER BY "rowid"
""")
}
}
}