From 59d41af3b4f750b477b2c1a5b089ee9847f2ac52 Mon Sep 17 00:00:00 2001 From: Marc Prud'hommeaux Date: Tue, 29 Jul 2025 18:57:23 +0200 Subject: [PATCH 1/9] Support delete, update, order by, and join clauses --- README.md | 73 +- Sources/SkipSQL/SQLCodable.swift | 792 ++++++++++++++++++---- Sources/SkipSQL/SQLContext.swift | 108 ++- Tests/SkipSQLPlusTests/SQLPlusTests.swift | 66 +- Tests/SkipSQLTests/SQLContextTests.swift | 541 ++++++++++++--- 5 files changed, 1257 insertions(+), 323 deletions(-) diff --git a/README.md b/README.md index 65d6993..8f69c21 100644 --- a/README.md +++ b/README.md @@ -123,18 +123,11 @@ SkipSQL includes a basic mechanism for mapping Swift types to tables through the ```swift /// A struct that can read and write its values to the `DEMO_TABLE` table. public struct DemoTable : SQLCodable, Equatable { - public static var tableName = "DEMO_TABLE" - - /// All the columns defined for this table - public static var columns: [SQLColumn] { - [id, txt, num, int, dbl, blb] - } - public var id: Int64? static let id = SQLColumn(name: "ID", type: .long, primaryKey: true, autoincrement: true) public var txt: String? - static let txt = SQLColumn(name: "TXT", type: .text, unique: true, nullable: false) + static let txt = SQLColumn(name: "TXT", type: .text, unique: true, nullable: false, index: SQLIndex(name: "IDX_TXT")) public var num: Double? static let num = SQLColumn(name: "NUM", type: .real) @@ -143,52 +136,12 @@ public struct DemoTable : SQLCodable, Equatable { static let int = SQLColumn(name: "INT", type: .long, nullable: false) public var dbl: Double? - static let dbl = SQLColumn(name: "DBL", type: .real, defaultValue: SQLValue(Double.pi)) + static let dbl = SQLColumn(name: "DBL", type: .real, defaultValue: SQLValue(Double.pi), index: SQLIndex(name: "IDX_DBL", unique: false)) public var blb: Data? static let blb = SQLColumn(name: "BLB", type: .blob) - /// Returns a `SQLValue` for the specified `SQLColumn` - public func binding(forColumn column: SQLColumn) throws -> SQLValue { - switch column { - case Self.id: return SQLValue(self.id) - case Self.txt: return SQLValue(self.txt) - case Self.num: return SQLValue(self.num) - case Self.int: return SQLValue(self.int) - case Self.dbl: return SQLValue(self.dbl) - case Self.blb: return SQLValue(self.blb) - default: throw SQLBindingError.unknownColumn(column) - } - } - - /// Updates the value of the given column with the given value - public mutating func update(column: SQLColumn, value: SQLValue) throws { - switch column { - case Self.id: self.id = value.longValue - case Self.txt: self.txt = value.textValue - case Self.num: self.num = value.realValue - case Self.int: self.int = .init(try SQLBindingError.checkNonNull(value.longValue, column)) - case Self.dbl: self.dbl = value.realValue - case Self.blb: self.blb = value.blobValue - default: throw SQLBindingError.unknownColumn(column) - } - } - - /// Create an instance of this type from the given row values - public static func create(withRow row: [SQLValue], fromColumns: [SQLColumn]? = nil) throws -> Self { - try DemoTable(withRow: row, fromColumns: fromColumns) - } - - init(withRow row: [SQLValue], fromColumns: [SQLColumn]? = nil) throws { - self.int = 0 // need to initialize any non-nil instances with placeholder values - let columns = fromColumns ?? Self.columns - if row.count != columns.count { - throw SQLBindingError.columnValuesMismatch(row.count, columns.count) - } - for (value, column) in zip(row, columns) { - try update(column: column, value: value) - } - } + public static let table = SQLTable(name: "DEMO_TABLE", columns: [id, txt, num, int, dbl, blb]) public init(id: Int64? = nil, txt: String? = nil, num: Double? = nil, int: Int, dbl: Double? = nil, blb: Data? = nil) { self.id = id @@ -198,6 +151,24 @@ public struct DemoTable : SQLCodable, Equatable { self.dbl = dbl self.blb = blb } + + public init(row: SQLRow) throws { + self.id = try Self.id.longValueRequired(in: row) + self.txt = try Self.txt.textValueRequired(in: row) + self.num = Self.num.realValue(in: row) + self.int = try Int(Self.int.longValueRequired(in: row)) + self.dbl = Self.dbl.realValue(in: row) + self.blb = Self.blb.blobValue(in: row) + } + + public func encode(row: inout SQLRow) throws { + row[Self.id] = SQLValue(self.id) + row[Self.txt] = SQLValue(self.txt) + row[Self.num] = SQLValue(self.num) + row[Self.int] = SQLValue(self.int) + row[Self.dbl] = SQLValue(self.dbl) + row[Self.blb] = SQLValue(self.blb) + } } ``` @@ -209,7 +180,7 @@ The `SQLPredicate` type enables querying the database for instances of a `SQLCod // issues: SELECT "ID", "TXT", "NUM", "INT", "DBL", "BLB" FROM "DEMO_TABLE" WHERE ("NUM" IS NULL OR "TXT" = 'ABC') let predicate = DemoTable.num.isNull().or(DemoTable.txt.equals(SQLValue("ABC"))) -let resultSet = try sqlite.query(DemoTable.self, with: [predicate]) +let resultSet = try sqlite.query(DemoTable.self, where: predicate) defer { resultSet.close() } let cursor = resultSet.makeIterator() diff --git a/Sources/SkipSQL/SQLCodable.swift b/Sources/SkipSQL/SQLCodable.swift index 2d13eaf..a81eae2 100644 --- a/Sources/SkipSQL/SQLCodable.swift +++ b/Sources/SkipSQL/SQLCodable.swift @@ -2,23 +2,103 @@ // SPDX-License-Identifier: LGPL-3.0-only WITH LGPL-3.0-linking-exception import Foundation #if SKIP -import kotlin.reflect.full.__ +import kotlin.reflect.full.companionObjectInstance #endif /// A type that can be stored and retrieved from a SQL context -public protocol SQLCodable : Sendable { - /// The name of the table that stores this type - static var tableName: String { get } - /// The table's column definitions - static var columns: [SQLColumn] { get } - /// Instantiate this item with the given rows with the (optional) corresponding columns. - static func create(withRow row: [SQLValue], fromColumns: [SQLColumn]?) throws -> Self - /// Updates the property in this instance with the value of the given column, which must exactly match one of the `columns` values - mutating func update(column: SQLColumn, value: SQLValue) throws - /// Returns the binding for the given `SQLColumn` - func binding(forColumn: SQLColumn) throws -> SQLValue +public protocol SQLCodable { + /// The table and columns for this type + static var table: SQLTable { get } + + /// Create this instance from a map of columns and their values + init(row: SQLRow, context: SQLContext) throws + + func encode(row: inout SQLRow) throws } +public typealias SQLRow = [SQLColumn: SQLValue] + +/// A representable of a SQL table +public struct SQLTable : Hashable, Sendable { + public var name: String + public var columns: [SQLColumn] + + public init(name: String, columns: [SQLColumn]) { + self.name = name + self.columns = columns + } + + public var quotedName: String { + name.quote(#"""#) + } + + public func dropTableSQL(ifExists: Bool = false) -> SQLExpression { + var sql = "DROP TABLE " + if ifExists { + sql += "IF EXISTS " + } + sql += self.quotedName + return SQLExpression(sql) + } + + /// Returns the SQL to create this table. + public func createTableSQL(ifNotExists: Bool = false, clauses additionalClauses: [String] = []) -> SQLExpression { + var sql = "CREATE TABLE " + if ifNotExists { + sql += "IF NOT EXISTS " + } + var clauses: [String] = [] + let pkColumns = self.columns.filter(\.primaryKey) + if pkColumns.count >= 2 { + // primary key clause added to the end only when there are multiple PKs for the table + clauses.append("PRIMARY KEY (\(pkColumns.map(\.quotedName).joined(separator: ", ")))") + } + + let fkColumns = self.columns.filter({ $0.references != nil }) + for fkColumn in fkColumns { + // add in any foreign key clauses + if let reference = fkColumn.references { + clauses.append("FOREIGN KEY (\(fkColumn.quotedName)) REFERENCES \(reference.referencesClause)") + } + } + + // finally add any manual clauses that are needed + clauses += additionalClauses + + sql += self.quotedName + sql += " (" + sql += (self.columns.map({ col in + col.definition(withPrimaryKey: pkColumns.count == 1) + }) + clauses).joined(separator: ", ") + sql += ")" + + return SQLExpression(sql) + } + + /// Returns the SQL to create any indices on this table. + public func createIndexSQL(ifNotExists: Bool = false) -> [SQLExpression] { + var stmnts: [SQLExpression] = [] + for column in self.columns { + if let index = column.index { + var sql = "CREATE INDEX " + if ifNotExists { + sql += "IF NOT EXISTS " + } + sql += index.name.quote() + sql += " ON " + sql += self.name.quote() + sql += "(" + // TODO: compound indices + sql += column.quotedName + sql += ")" + stmnts.append(SQLExpression(sql)) + } + } + return stmnts + } +} + +/// A representable of a SQL column public struct SQLColumn : Hashable, Sendable { public var name: String public var type: SQLType @@ -27,10 +107,12 @@ public struct SQLColumn : Hashable, Sendable { public var unique: Bool public var nullable: Bool public var defaultValue: SQLValue? + public var index: SQLIndex? + public var references: SQLForeignKey? /// An optional override of the columns definition for use in a `CREATE TABLE` statement public var columnDefinition: String? - public init(name: String, type: SQLType, primaryKey: Bool = false, autoincrement: Bool = false, unique: Bool = false, nullable: Bool = true, defaultValue: SQLValue? = nil, columnDefinition: String? = nil) { + public init(name: String, type: SQLType, primaryKey: Bool = false, autoincrement: Bool = false, unique: Bool = false, nullable: Bool = true, defaultValue: SQLValue? = nil, index: SQLIndex? = nil, references: SQLForeignKey? = nil, columnDefinition: String? = nil) { self.name = name self.type = type self.primaryKey = primaryKey @@ -38,6 +120,8 @@ public struct SQLColumn : Hashable, Sendable { self.unique = unique self.nullable = nullable self.defaultValue = defaultValue + self.references = references + self.index = index self.columnDefinition = columnDefinition } @@ -45,17 +129,19 @@ public struct SQLColumn : Hashable, Sendable { name.quote(#"""#) } - public var definition: String { + func definition(withPrimaryKey: Bool) -> String { if let columnDefinition { // definition override return columnDefinition } var def = quotedName + " " + type.typeName - if primaryKey { - def += " PRIMARY KEY" - } - if autoincrement { - def += " AUTOINCREMENT" + if withPrimaryKey { + if primaryKey { + def += " PRIMARY KEY" + } + if autoincrement { + def += " AUTOINCREMENT" + } } if unique { def += " UNIQUE" @@ -70,51 +156,158 @@ public struct SQLColumn : Hashable, Sendable { } } +public struct SQLIndex : Hashable, Sendable { + public var name: String + public var unique: Bool + + public init(name: String, unique: Bool = false) { + self.name = name + self.unique = unique + } +} + +public struct SQLForeignKey : Hashable, Sendable { + public var table: SQLTable + public var columns: [SQLColumn] + public var deleteAction: SQLForeignKeyAction? + public var updateAction: SQLForeignKeyAction? + + public init(table: SQLTable, column: SQLColumn, onDelete deleteAction: SQLForeignKeyAction? = nil, onUpdate updateAction: SQLForeignKeyAction? = nil) { + self.table = table + self.columns = [column] + self.deleteAction = deleteAction + self.updateAction = updateAction + } + + public var referencesClause: String { + var fkClause = self.table.quotedName + fkClause += "(" + fkClause += self.columns.map(\.quotedName).joined(separator: ", ") + fkClause += ")" + if let onDelete = self.deleteAction { + fkClause += " ON DELETE \(onDelete.actionClause)" + } + if let onUpdate = self.updateAction { + fkClause += " ON UPDATE \(onUpdate.actionClause)" + } + return fkClause + } +} + +public enum SQLForeignKeyAction : Hashable, Sendable { + case cascade + case restrict + case setNull + case setDefault + + public var actionClause: String { + switch self { + case .cascade: return "CASCADE" + case .restrict: return "RESTRICT" + case .setNull: return "SET NULL" + case .setDefault: return "SET DEFAULT" + } + } +} + public extension SQLCodable { + /// Returns the encoded row of this instance + func encodedRow() throws -> SQLRow { + var row = SQLRow() + try encode(row: &row) + return row + } + + /// Returns the values for the primary key columns, if any + static var primaryKeyColumns: [SQLColumn] { + self.table.columns.filter(\.primaryKey) + } + /// Returns the values for the primary key columns, if any var primaryKeyValues: [SQLValue] { - // force unwrap because binding failing for a primary key value should be considered a programming error - type(of: self).columns.filter(\.primaryKey).map({ try! self.binding(forColumn: $0) }) + get throws { + let row = try self.encodedRow() + return type(of: self).primaryKeyColumns.map({ row[$0] ?? .null }) + } } static func selectSQL(alias: String? = nil) -> SQLExpression { let aliasName = alias == nil ? "" : alias! - let aliasSuffix = alias == nil ? "" : (" " + aliasName) + let aliasSuffix = alias == nil ? "" : (" AS " + aliasName) let aliasPrefix = alias == nil ? "" : (aliasName + ".") var sql = "SELECT " - sql += columns.map({ aliasPrefix + $0.quotedName }).joined(separator: ", ") + sql += self.table.columns.map({ aliasPrefix + $0.quotedName }).joined(separator: ", ") sql += " FROM " - sql += tableName.quote() + sql += self.table.name.quote() sql += aliasSuffix return SQLExpression(sql) } +} - static func dropSQL(ifExists: Bool = false) -> SQLExpression { - var sql = "DROP TABLE " - if ifExists { - sql += "IF EXISTS " +public extension SQLContext { + /// Prepares the given SQL as a statement, which can be executed with parameter bindings. + func prepare(expr: SQLExpression) throws -> SQLStatement { + let stmnt = try prepare(sql: expr.sql) + if !expr.bindings.isEmpty { + try stmnt.bind(parameters: expr.bindings) } - sql += tableName.quote() - return SQLExpression(sql) + return stmnt } - static func createSQL(ifNotExists: Bool = false) -> SQLExpression { - var sql = "CREATE TABLE " - if ifNotExists { - sql += "IF NOT EXISTS " + /// Delete the given instances from the database. Instances must have at least one primary key defined. + @inline(__always) func delete(instances: [T]) throws { + try delete(T.self, where: primaryKeyQuery(instances)) + } + + /// Delete the given instances from the database. Instances must have at least one primary key defined. + @inline(__always) func delete(_ type: T.Type, where: SQLPredicate? = nil) throws { + // SKIP INSERT: val T = T::class.companionObjectInstance as SQLCodableCompanion // needed to access statics in generic constrained type + var deleteSQL = SQLExpression("DELETE FROM " + T.table.quotedName) + if let `where` { + deleteSQL.append(" WHERE ") + `where`.apply(to: &deleteSQL) + } + try exec(deleteSQL) + } + + /// Returns a predicate that can be used to locate instances based on the primary key(s) of the given instances + @inline(__always) func primaryKeyQuery(_ instances: [T]) throws -> SQLPredicate { + // SKIP INSERT: val T = T::class.companionObjectInstance as SQLCodableCompanion // needed to access statics in generic constrained type + let tableName = T.table.name + let pkColumns = T.primaryKeyColumns + + let pkValues = try instances.map({ try $0.primaryKeyValues }) + + if pkColumns.isEmpty { + // we need at least a single primary keys defined + throw SQLBindingError.noPrimaryKeys(tableName) + } else if pkColumns.count == 1 { + let pkColumn = pkColumns[0] + let pks = pkValues.map({ $0[0] }) + if pks.count == 1 { + return SQLPredicate.equals(pkColumn, pks[0]) + } else { + return SQLPredicate.in(pkColumn, pks.map({ $0 })) + } + } else { + let columnsTuple: SQLRepresentable = SQLTuple(columns: pkColumns) + let valuesTuples: [SQLRepresentable] = pkValues.map({ SQLTuple(values: $0) }) + // multiple primary keys: query based on the tuple + return SQLPredicate.in(columnsTuple, valuesTuples) } - sql += tableName.quote() - sql += " (" - sql += columns.map({ $0.definition }).joined(separator: ", ") - sql += ")" - return SQLExpression(sql) } - func insertSQL(upsert: Bool, explicitNulls: Bool = false) throws -> SQLExpression { - let allColumns = type(of: self).columns - let allBindings = try allColumns.map({ try self.binding(forColumn: $0) }) + /// Returns the SQL for an INSERT or UPDATE for the given instance. + /// - Parameters: + /// - upsert: INSERT if false, INSERT … ON CONFLICT if true, UPDATE if nil + @inline(__always) func insertUpdateSQL(for instance: T, upsert: Bool? = nil, explicitNulls: Bool = false) throws -> SQLExpression { + // SKIP INSERT: val T = T::class.companionObjectInstance as SQLCodableCompanion // needed to access statics in generic constrained type + let tableName = T.table.quotedName + let allColumns = T.table.columns + let row = try instance.encodedRow() + let allBindings = allColumns.map({ row[$0] ?? .null }) var columns: [SQLColumn] = [] var bindings: [SQLValue] = [] if explicitNulls { @@ -123,7 +316,7 @@ public extension SQLCodable { } else { // filter out any NULL values so that defaults defined in the column are used for (col, value) in zip(allColumns, allBindings) { - if value == .null { + if value == SQLValue.null { continue } columns.append(col) @@ -131,56 +324,103 @@ public extension SQLCodable { } } - var sql = "INSERT INTO \(type(of: self).tableName) (" - sql += columns.map({ $0.quotedName }).joined(separator: ", ") - sql += ") VALUES (" - sql += columns.map({ _ in "?" }).joined(separator: ", ") - sql += ")" - if upsert, let pkColumn = columns.first(where: { $0.primaryKey == true }) { - sql += " ON CONFLICT(" - sql += pkColumn.quotedName - sql += ") DO UPDATE SET" + let update = upsert == nil + + var expression = SQLExpression("") + if update { + expression.append("UPDATE \(tableName) SET ") + } else { + expression.append("INSERT INTO \(tableName) ") + expression.append("(") + expression.append(columns.map(\.quotedName).joined(separator: ", ")) + expression.append(")") + expression.append(" VALUES ") + expression.append("(") + } + var updateValueCount = 0 + for (col, value) in zip(columns, bindings) { + if updateValueCount > 0 { + expression.append(", ") + } + if update { + if !col.primaryKey { // don't bother updating the primary key values, because these don't change + expression.append(col.quotedName + " = ") + value.apply(to: &expression) // add the "?" and binding + updateValueCount += 1 + } + } else { + value.apply(to: &expression) // add the "?" and binding + updateValueCount += 1 + } + } + if !update { + expression.append(")") + } + + if update == false, + upsert == true, + let pkColumn = columns.first(where: { $0.primaryKey == true }) { + expression.append(" ON CONFLICT(") + expression.append(pkColumn.quotedName) + expression.append(") DO UPDATE SET ") for (index, col) in columns.enumerated() { if index != 0 { - sql += "," + expression.append(", ") } - sql += " " + col.quotedName + " = EXCLUDED." + col.quotedName + expression.append(col.quotedName + " = EXCLUDED." + col.quotedName) } + } else if update == true { + expression.append(" WHERE ") + try primaryKeyQuery([instance]).apply(to: &expression) } - return SQLExpression(sql, bindings) + return expression } -} -public extension SQLContext { - /// Prepares the given SQL as a statement, which can be executed with parameter bindings. - func prepare(expr: SQLExpression) throws -> SQLStatement { - let stmnt = try prepare(sql: expr.template) - if !expr.bindings.isEmpty { - try stmnt.bind(parameters: expr.bindings) - } - return stmnt + /// Performs an update of the given `SQLCodable` instance + @inline(__always) func update(_ ob: T) throws { + try exec(insertUpdateSQL(for: ob, upsert: nil)) } /// Performs an insert of the given `SQLCodable` instance - func insert(_ ob: T, upsert: Bool = false) throws { - try exec(ob.insertSQL(upsert: upsert)) - } - - /// Performs an insert of the given `SQLCodable` instance and updates it with the expected ROWID for any primary key columns in the instance - @inline(__always) func inserted(_ ob: inout T, refresh: Bool = false) throws { - try insert(ob, upsert: false) - + @inline(__always) @discardableResult func insert(_ ob: T, upsert: Bool = false) throws -> T { + // SKIP INSERT: val T = T::class.companionObjectInstance as SQLCodableCompanion // needed to access statics in generic constrained type + try exec(insertUpdateSQL(for: ob, upsert: upsert)) // check for primary key column and update it with the last insert Row ID - //let columns = T.columns - let columns = type(of: ob).columns // needed for Kotlin + let columns = T.table.columns + let row = try ob.encodedRow() + var rowMap = try _createSQLRow(columns, columns.map({ row[$0] ?? .null })) + var changedFields = 0 for col in columns { - if col.primaryKey && col.type == .long { - // get the last inserted row id and update it in the object - try ob.update(column: col, value: .long(lastInsertRowID)) - break // only a single primary key is supported for auto-update + if row[col] == .null { + if col.primaryKey && col.autoincrement { + // get the last inserted row id and update it in the object + if rowMap[col] != .long(lastInsertRowID) { + rowMap[col] = .long(lastInsertRowID) + changedFields += 1 + } + } else if let defaultValue = col.defaultValue { + if rowMap[col] != defaultValue { + rowMap[col] = defaultValue + changedFields += 1 + } + } } } + if changedFields == 0 { + // if we didn't auto-assign any fields, don't bother re-initializing a new instance just to set the fields again + return ob + } else { + // SKIP NOWARN + let created = try type(of: ob).init(row: rowMap, context: self) as T + return created + } + } + + /// Performs an insert of the given `SQLCodable` instance and updates it with the expected ROWID for any primary key columns in the instance + @inline(__always) func inserted(_ ob: inout T, refresh: Bool = false) throws { + ob = try insert(ob, upsert: false) if refresh { + // TODO: this could be changed to use a "RETURNING *" clause to get the inserted rows back in a single statement, but "RETURNING" is only available in SQLite 3.35.0 (iOS 15/Android 14 API 34), so we would need to gracefully fallback to this implementation for older OSs. try self.refresh(&ob) } } @@ -190,45 +430,239 @@ public extension SQLContext { ob = try fetch(T.self, primaryKeys: ob.primaryKeyValues) ?? ob } - @inline(__always) func select(_ type: T.Type, _ expr: SQLExpression? = nil) throws -> RowCursor { - // Type parameter 'T' cannot have or inherit a companion object, so it cannot be on the left-hand side of a dot. - // SKIP REPLACE: val TType = T::class.companionObjectInstance as SQLCodableCompanion - let TType = T.self - return RowCursor(statement: try prepare(expr: expr ?? TType.selectSQL()), creator: { row in - let values = row.rowValues() - let columns = TType.columns - let created = try TType.create(withRow: values, fromColumns: columns) - return created as T + private func selectQuery(_ type: T.Type, _ expr: SQLExpression? = nil) throws -> RowCursor { + let columns = type.table.columns + return RowCursor(statement: try prepare(expr: expr ?? type.selectSQL()), creator: { row in + // SKIP NOWARN + let created: T = try type.init(row: _createSQLRow(columns, row.rowValues()), context: self) as T + return created }) } /// Return the data item with the given primary keys. - @inline(__always) func fetch(_ type: T.Type, id primaryKeys: SQLValue...) throws -> T? { + func fetch(_ type: T.Type, id primaryKeys: SQLValue...) throws -> T? { try self.fetch(type, primaryKeys: primaryKeys) } /// Return the data item with the given primary keys. - @inline(__always) func fetch(_ type: T.Type, primaryKeys: [SQLValue]) throws -> T? { - // SKIP REPLACE: val TType = T::class.companionObjectInstance as SQLCodableCompanion - let TType = T.self - let columns = TType.columns + func fetch(_ type: T.Type, primaryKeys: [SQLValue]) throws -> T? { + let columns = type.table.columns let primaryKeyColumns = columns.filter(\.primaryKey) - let cursor = try self.query(type, with: zip(primaryKeyColumns, primaryKeys).map({ SQLPredicate.equals($0, $1) })) + let cursor = try self.query(type, where: .and(zip(primaryKeyColumns, primaryKeys).map({ SQLPredicate.equals($0, $1) }))) defer { cursor.close() } return try cursor.makeIterator().next()?.get() } /// Issue a query for matching values for the given column/value comparison. - @inline(__always) func query(_ type: T.Type, alias: String? = nil, with predicates: [SQLPredicate]) throws -> RowCursor { - // SKIP REPLACE: val TType = T::class.companionObjectInstance as SQLCodableCompanion - let TType = T.self - var select = TType.selectSQL(alias: alias) - select.template += " WHERE " - SQLPredicate.and(predicates).apply(to: &select) - return try self.select(type, select) + func query(_ type: T.Type, _ alias: String? = nil, where predicate: SQLPredicate? = nil, orderBy: [(SQLRepresentable, SQLOrder)] = [], limit: Int? = nil, offset: Int? = nil) throws -> RowCursor { + var select = type.selectSQL(alias: alias) + applyClauses(to: &select, where: predicate, orderBy: orderBy, limit: limit, offset: offset) + return try self.selectQuery(type, select) + } + + internal func joinQuery(tableAliases: [(SQLTable, String?)], joins: [SQLJoinType], onColumns: [SQLColumn?], where: SQLPredicate?, orderBy: [(SQLRepresentable, SQLOrder)] = [], limit: Int? = nil, offset: Int? = nil) throws -> SQLExpression { + var sql = "SELECT " + + var selectColumns: [String] = [] + for tableAliase in tableAliases { + selectColumns += tableAliase.0.columns.map({ (tableAliase.1?.appendingString(".") ?? "") + $0.quotedName }) + } + + sql += selectColumns.joined(separator: ", ") + sql += " FROM " + + var select = SQLExpression(sql) + + for (index, tableAlias) in tableAliases.enumerated() { + let table = tableAlias.0 + let alias = tableAlias.1 + if index > 0 { + select.append(" " + joins[index - 1].joinClause + " ") + } + select.append(table.quotedName) + if let alias { + select.append(" AS " + alias) + } + if index > 0 { + let onColumn = onColumns[index - 1] + if let onColumn { + let previousTable = tableAliases[index - 1].0 + let previousAlias = tableAliases[index - 1].1 + var joinPredicates: [SQLPredicate] = [] + + // scan the columns on each side of the table for foreign keys that match the other table + if let reference = onColumn.references { + for refColumn in reference.columns { + // if aliases are null, we will disambiguate the columns by referencing them with the table name + let palias = previousAlias ?? previousTable.quotedName + let talias = alias ?? table.quotedName + let isPreviousRef = previousTable == reference.table && previousTable.columns.contains(refColumn) + let col1 = refColumn.alias(isPreviousRef ? palias : talias) + let col2 = onColumn.alias(isPreviousRef ? talias : palias) + // only equijoins are currently supported + joinPredicates.append(SQLPredicate.equals(col1, col2)) + } + } + if !joinPredicates.isEmpty { + select.append(" ON ") + SQLPredicate.and(joinPredicates).apply(to: &select) + } + } + } + } + + applyClauses(to: &select, where: `where`, orderBy: orderBy, limit: limit, offset: offset) + return select + } + + func applyClauses(to select: inout SQLExpression, where predicate: SQLPredicate?, orderBy: [(SQLRepresentable, SQLOrder)], limit: Int?, offset: Int?) { + if let predicate { + select.append(" WHERE ") + predicate.apply(to: &select) + } + if !orderBy.isEmpty { + select.append(" ORDER BY ") + for (index, columnDirection) in orderBy.enumerated() { + if index > 0 { + select.append(", ") + } + columnDirection.0.apply(to: &select) + select.append(" " + (columnDirection.1.orderClause)) + } + } + + if let limit { + select.append(" LIMIT \(limit)") + } + + if let offset { + select.append(" OFFSET \(offset)") + } + } + + /// Performs a query with a 2-way join. + /// - Parameters: + /// - type1: the first SQLCodable type + /// - join: the join between the first and second table + /// - type2: the second SQLCodable type + /// - where: a WHERE clause + /// - Returns: a RowCursor that deserializes into the instance types + func query(_ type1: T1.Type, _ alias1: String?, join: SQLJoinType, on: SQLColumn?, _ type2: T2.Type, _ alias2: String?, where: SQLPredicate? = nil, orderBy: [(SQLRepresentable, SQLOrder)] = []) throws -> RowCursor<(T1?, T2?)> { + let columns1 = type1.table.columns + let c1c = columns1.count + let columns2 = type2.table.columns + let c2c = columns2.count + + let select = try joinQuery(tableAliases: [(type1.table, alias1), (type2.table, alias2)], joins: [join], onColumns: [on], where: `where`, orderBy: orderBy) + return RowCursor(statement: try prepare(expr: select), creator: { row in + let values = row.rowValues() + + let values1 = Array(values[0..(_ type1: T1.Type, _ alias1: String, join1: SQLJoinType, on1: SQLColumn?, _ type2: T2.Type, _ alias2: String, join2: SQLJoinType, on2: SQLColumn?, _ type3: T3.Type, _ alias3: String, where: SQLPredicate? = nil, orderBy: [(SQLRepresentable, SQLOrder)] = []) throws -> RowCursor<(T1?, T2?, T3?)> { + let columns1 = type1.table.columns + let c1c = columns1.count + let columns2 = type2.table.columns + let c2c = columns2.count + let columns3 = type3.table.columns + let c3c = columns3.count + + let select = try joinQuery(tableAliases: [(type1.table, alias1), (type2.table, alias2), (type3.table, alias3)], joins: [join1, join2], onColumns: [on1, on2], where: `where`, orderBy: orderBy) + return RowCursor(statement: try prepare(expr: select), creator: { row in + let values = row.rowValues() + + let values1 = Array(values[0..(_ type1: T1.Type, _ alias1: String, join1: SQLJoinType, on1: SQLColumn?, _ type2: T2.Type, _ alias2: String, join2: SQLJoinType, on2: SQLColumn?, _ type3: T3.Type, _ alias3: String, join3: SQLJoinType, on3: SQLColumn?, _ type4: T4.Type, _ alias4: String, where: SQLPredicate? = nil, orderBy: [(SQLRepresentable, SQLOrder)] = []) throws -> RowCursor<(T1?, T2?, T3?, T4?)> { + let columns1 = type1.table.columns + let c1c = columns1.count + let columns2 = type2.table.columns + let c2c = columns2.count + let columns3 = type3.table.columns + let c3c = columns3.count + let columns4 = type4.table.columns + let c4c = columns4.count + + let select = try joinQuery(tableAliases: [(type1.table, alias1), (type2.table, alias2), (type3.table, alias3), (type4.table, alias4)], joins: [join1, join2, join3], onColumns: [on1, on2, on3], where: `where`, orderBy: orderBy) + return RowCursor(statement: try prepare(expr: select), creator: { row in + let values = row.rowValues() + + let values1 = Array(values[0.. SQLRow { + SQLRow(uniqueKeysWithValues: zip(columns, values)) +} + +/// Returns true is all the values in the list are null +public func _areAllNull(_ values: [SQLValue]) -> Bool { + // needs to be public for the reified Kotlin side + values.first(where: { $0 != .null }) == nil +} + /// A type that can be represented in a SQL Statement public protocol SQLRepresentable { /// Applies the given representation to the SQL statement @@ -237,7 +671,7 @@ public protocol SQLRepresentable { extension SQLColumn : SQLRepresentable { public func apply(to expression: inout SQLExpression) { - expression.template += self.quotedName + expression.append(self.quotedName) } public func alias(_ aliasName: String) -> SQLAliasedColumn { @@ -247,11 +681,39 @@ extension SQLColumn : SQLRepresentable { extension SQLValue : SQLRepresentable { public func apply(to expression: inout SQLExpression) { - expression.template += "?" - expression.bindings += [self] + expression.append("?", self) + } +} + +/// A list of multiple `SQLRepresentable`s expressed as a tuple. +public struct SQLTuple : SQLRepresentable { + public var representations: [SQLRepresentable] + + public init(_ representations: [SQLRepresentable]) { + self.representations = representations + } + + public init(columns: [SQLColumn]) { + self.representations = columns.map({ $0 as SQLRepresentable }) // needed to help Kotlin contravariant array + } + + public init(values: [SQLValue]) { + self.representations = values.map({ $0 as SQLRepresentable }) // needed to help Kotlin contravariant array + } + + public func apply(to expression: inout SQLExpression) { + expression.append("(") + for (index, rep) in representations.enumerated() { + if index > 0 { + expression.append(", ") + } + rep.apply(to: &expression) + } + expression.append(")") } } +/// A column with an alias. public struct SQLAliasedColumn : SQLRepresentable { public var column: SQLColumn public var alias: String @@ -262,11 +724,54 @@ public struct SQLAliasedColumn : SQLRepresentable { } public func apply(to expression: inout SQLExpression) { - expression.template += alias + "." + expression.append(alias + ".") column.apply(to: &expression) } } +public enum SQLOrder { + case ascending + case descending + + public var orderClause: String { + switch self { + case .ascending: return "ASC" + case .descending: return "DESC" + } + } +} + +/// A type of join +public enum SQLJoinType { + case left + case right + case full + case inner + case cross + + public var joinClause: String { + switch self { + case .left: return "LEFT OUTER JOIN" + case .right: return "RIGHT OUTER JOIN" + case .full: return "FULL OUTER JOIN" + case .inner: return "INNER JOIN" + case .cross: return "CROSS JOIN" + } + } +} + +internal struct SQLJoinClause { + let aliases: [String] + let columns: [SQLColumn?] + let joinType: SQLJoinType + + init(aliases: [String], columns: [SQLColumn?], joinType: SQLJoinType) { + self.aliases = aliases + self.columns = columns + self.joinType = joinType + } +} + public struct SQLPredicate : SQLRepresentable { /// Applies the given predicate to the SQL statement public let applicator: (inout SQLExpression) -> () @@ -280,16 +785,16 @@ public extension SQLPredicate { private static func compound(conjunction: String, _ predicates: [SQLPredicate]) -> SQLPredicate { SQLPredicate { exp in if predicates.count > 1 { - exp.template += "(" + exp.append("(") } for (index, predicate) in predicates.enumerated() { if index > 0 { - exp.template += " " + conjunction + " " + exp.append(" " + conjunction + " ") } predicate.apply(to: &exp) } if predicates.count > 1 { - exp.template += ")" + exp.append(")") } } } @@ -312,17 +817,17 @@ public extension SQLPredicate { static func not(_ predicate: SQLPredicate) -> SQLPredicate { SQLPredicate { exp in - exp.template += "NOT " - exp.template += "(" + exp.append("NOT ") + exp.append("(") predicate.apply(to: &exp) - exp.template += ")" + exp.append(")") } } static func compare(lhs: SQLRepresentable, op: String, rhs: SQLRepresentable) -> SQLPredicate { SQLPredicate { exp in lhs.apply(to: &exp) - exp.template += " " + op + " " + exp.append(" " + op + " ") rhs.apply(to: &exp) } } @@ -370,23 +875,23 @@ public extension SQLPredicate { static func isNull(_ rep: SQLRepresentable) -> SQLPredicate { SQLPredicate { exp in rep.apply(to: &exp) - exp.template += " IS NULL" + exp.append(" IS NULL") } } static func isNotNull(_ rep: SQLRepresentable) -> SQLPredicate { SQLPredicate { exp in rep.apply(to: &exp) - exp.template += " IS NOT NULL" + exp.append(" IS NOT NULL") } } static func between(_ rep: SQLRepresentable, min: SQLRepresentable, max: SQLRepresentable) -> SQLPredicate { SQLPredicate { exp in rep.apply(to: &exp) - exp.template += " BETWEEN " + exp.append(" BETWEEN ") min.apply(to: &exp) - exp.template += " AND " + exp.append(" AND ") min.apply(to: &exp) } } @@ -394,32 +899,34 @@ public extension SQLPredicate { static func notBetween(_ rep: SQLRepresentable, min: SQLRepresentable, max: SQLRepresentable) -> SQLPredicate { SQLPredicate { exp in rep.apply(to: &exp) - exp.template += " NOT BETWEEN " + exp.append(" NOT BETWEEN ") min.apply(to: &exp) - exp.template += " AND " + exp.append(" AND ") min.apply(to: &exp) } } - static func `in`(_ rep: SQLRepresentable, _ values: [SQLValue]) -> SQLPredicate { + static func `in`(_ rep: SQLRepresentable, _ values: [SQLRepresentable]) -> SQLPredicate { SQLPredicate { exp in rep.apply(to: &exp) - exp.template += " IN " - exp.template += "(" + exp.append(" IN ") + exp.append("(") for (index, value) in values.enumerated() { if index > 0 { - exp.template += ", " + exp.append(", ") } value.apply(to: &exp) } - exp.template += ")" + exp.append(")") } } static func custom(sql: String, bindings: [SQLValue] = []) -> SQLPredicate { SQLPredicate { exp in - exp.template += " " + sql - exp.bindings += bindings + exp.append(" " + sql) + for binding in bindings { + exp.append("", binding) + } } } } @@ -473,7 +980,7 @@ public extension SQLRepresentable { .notBetween(self, min: min, max: max) } - func `in`(_ values: [SQLValue]) -> SQLPredicate { + func `in`(_ values: [SQLRepresentable]) -> SQLPredicate { .in(self, values) } } @@ -482,6 +989,7 @@ public enum SQLBindingError : Error { case unknownColumn(SQLColumn) case nullColumn(SQLColumn) case columnValuesMismatch(Int, Int) + case noPrimaryKeys(String) /// Verifies that the value is not null, throwing a `nullColumn` error if it is null. public static func checkNonNull(_ value: T?, _ column: SQLColumn) throws -> T { @@ -489,3 +997,37 @@ public enum SQLBindingError : Error { return value } } + +public extension SQLColumn { + func longValue(in row: SQLRow) -> Int64? { + row[self]?.longValue + } + + func longValueRequired(in row: SQLRow) throws -> Int64 { + try SQLBindingError.checkNonNull(longValue(in: row), self) + } + + func realValue(in row: SQLRow) -> Double? { + row[self]?.realValue + } + + func realValueRequired(in row: SQLRow) throws -> Double { + try SQLBindingError.checkNonNull(realValue(in: row), self) + } + + func textValue(in row: SQLRow) -> String? { + row[self]?.textValue + } + + func textValueRequired(in row: SQLRow) throws -> String { + try SQLBindingError.checkNonNull(textValue(in: row), self) + } + + func blobValue(in row: SQLRow) -> Data? { + row[self]?.blobValue + } + + func blobValueRequired(in row: SQLRow) throws -> Data { + try SQLBindingError.checkNonNull(blobValue(in: row), self) + } +} diff --git a/Sources/SkipSQL/SQLContext.swift b/Sources/SkipSQL/SQLContext.swift index fb5f8b0..40febb9 100644 --- a/Sources/SkipSQL/SQLContext.swift +++ b/Sources/SkipSQL/SQLContext.swift @@ -1,21 +1,15 @@ // Copyright 2023–2025 Skip // SPDX-License-Identifier: LGPL-3.0-only WITH LGPL-3.0-linking-exception import Foundation -import OSLog #if SKIP import SkipFFI #endif -let logger: Logger = Logger(subsystem: "skip.sql", category: "SQL") - /// A context for performing operations on a SQLite database. public class SQLContext { /// The SQLite3 library to use. fileprivate let SQLite3: SQLiteLibrary - /// The logging level for this context; SQL statements and warnings will be sent to this log. - public var logLevel: OSLogType? = nil - /// The pointer to the SQLite database. private let db: OpaquePointer private var closed = false @@ -54,14 +48,9 @@ public class SQLContext { /// - Parameters: /// - path: The path to the local file, or ":memory:" for an in-memory database. /// - flags: The flags to use to open the database. - public init(path: String, flags: OpenFlags? = nil, logLevel: OSLogType? = nil, configuration: SQLiteConfiguration = .platform) throws { - self.logLevel = logLevel + public init(path: String, flags: OpenFlags? = nil, configuration: SQLiteConfiguration = .platform) throws { self.SQLite3 = configuration.library self.db = try Self.connect(path: path, flags: flags, configuration: configuration)! - - if let logLevel = logLevel { - logger.log(level: logLevel, "opened database: \(path)") - } } private static func connect(path: String, flags: OpenFlags? = nil, configuration: SQLiteConfiguration = .platform) throws -> OpaquePointer? { @@ -79,7 +68,7 @@ public class SQLContext { } public struct OpenFlags: OptionSet { - public let rawValue: Int32 + public let rawValue: Int32 public init(rawValue: Int32) { self.rawValue = rawValue @@ -98,7 +87,7 @@ public class SQLContext { public func exec(_ expr: SQLExpression) throws { try checkClosed() - let stmnt = try prepare(sql: expr.template) + let stmnt = try prepare(sql: expr.sql) var err: Error? = nil do { try stmnt.update(parameters: expr.bindings) @@ -138,9 +127,6 @@ public class SQLContext { /// Prepares the given SQL as a statement, which can be executed with parameter bindings. public func prepare(sql: String) throws -> SQLStatement { try checkClosed() - if let logLevel = self.logLevel { - logger.log(level: logLevel, "prepare: \(sql)") - } var stmntPtr: OpaquePointer? = nil try check(SQLite3, db: db, code: withUnsafeMutablePointer(to: &stmntPtr) { ptr in @@ -206,13 +192,13 @@ public class SQLContext { } /// Issue a query and return all the rows in a single batch - public func query(sql: String, parameters: [SQLValue] = []) throws -> [[SQLValue]] { + public func selectAll(sql: String, parameters: [SQLValue] = []) throws -> [[SQLValue]] { try cursor(SQLExpression(sql, parameters)).map({ try $0.get() }) } /// Issues a SQL query with the optional parameters and returns all the values. public func cursor(_ expr: SQLExpression) throws -> RowCursor<[SQLValue]> { - let stmnt = try prepare(sql: expr.template) + let stmnt = try prepare(sql: expr.sql) if !expr.bindings.isEmpty { try stmnt.bind(parameters: expr.bindings) } @@ -267,13 +253,13 @@ public class SQLContext { } _ = SQLite3.sqlite3_trace_v2(db, UInt32(SQLITE_TRACE_STMT), { - (_: UInt32, context: UnsafeMutableRawPointer?, pointer: UnsafeMutableRawPointer?, _: UnsafeMutableRawPointer?) in - if let pointer { - unsafeBitCast(context, to: TraceBox.self)(pointer) - } - return Int32(0) - }, - unsafeBitCast(box, to: UnsafeMutableRawPointer.self) + (_: UInt32, context: UnsafeMutableRawPointer?, pointer: UnsafeMutableRawPointer?, _: UnsafeMutableRawPointer?) in + if let pointer { + unsafeBitCast(context, to: TraceBox.self)(pointer) + } + return Int32(0) + }, + unsafeBitCast(box, to: UnsafeMutableRawPointer.self) ) traceHook = box #else @@ -337,15 +323,56 @@ public class SQLContext { SQLite3.sqlite3_update_hook(db, self.updateHook, nil) #endif } + + // MARK: PRAGMAs + + /// Query, set, or clear the enforcement of foreign key constraints. + /// + /// - SeeAlso: [https://sqlite.org/pragma.html#pragma_foreign_keys](https://sqlite.org/pragma.html#pragma_foreign_keys) + public var foreignKeysEnabled: Bool { + get { (try? selectAll(sql: "PRAGMA foreign_keys").first?.first) == SQLValue(1) } + set { try? exec(sql: "PRAGMA foreign_keys = " + (newValue ? "ON" : "OFF")) } + } + + /// Query, set, or clear the enforcement of foreign key constraints. + /// + /// - SeeAlso: [https://sqlite.org/pragma.html#encoding](https://sqlite.org/pragma.html#encoding) + public var encoding: String? { + get { (try? selectAll(sql: "PRAGMA encoding").first?.first)?.textValue } + set { try? exec(sql: "PRAGMA encoding = ?", parameters: [SQLValue(newValue)]) } + } + + /// Query, set, or clear READ UNCOMMITTED isolation. + /// + /// The default isolation level for SQLite is SERIALIZABLE. Any process or thread can select READ UNCOMMITTED isolation, but SERIALIZABLE will still be used except between connections that share a common page and schema cache. Cache sharing is enabled using the sqlite3_enable_shared_cache() API. Cache sharing is disabled by default. + /// + /// - SeeAlso: [https://sqlite.org/pragma.html#read_uncommitted](https://sqlite.org/pragma.html#read_uncommitted) + public var readUncommitted: Bool { + get { (try? selectAll(sql: "PRAGMA read_uncommitted").first?.first) == SQLValue(1) } + set { try? exec(sql: "PRAGMA read_uncommitted = " + (newValue ? "ON" : "OFF")) } + } } public struct SQLExpression { - public var template: String - public var bindings: [SQLValue] + public var parts: [(String, SQLValue?)] = [] + + public init(_ sql: String, _ bindings: [SQLValue] = []) { + self.parts += [(sql, nil)] + for binding in bindings { + self.parts += [("", binding)] + } + } + + public var sql: String { + parts.map(\.0).joined() + } - public init(_ template: String, _ bindings: [SQLValue] = []) { - self.template = template - self.bindings = bindings + public var bindings: [SQLValue] { + parts.compactMap(\.1) + } + + public mutating func append(_ sql: String, _ binding: SQLValue? = nil) { + parts += [(sql, binding)] } } @@ -363,6 +390,10 @@ extension String { quoted += mark.description return quoted } + + func appendingString(_ other: String) -> String { + self + other + } } /// A lazy sequence of rows from the database @@ -382,7 +413,20 @@ public class RowCursor : Sequence { } catch { } } - + + /// Loads the specified number of elements. + public func load(count: Int = Int.max) throws -> [Row] { + let cursor = makeIterator() + var instances: [Row] = [] + while let row = cursor.next() { + let instance = try row.get() // instantiate the type from the row + instances.append(instance) + if instances.count >= count { + break + } + } + return instances + } #if !SKIP public func makeIterator() -> RowIterator { diff --git a/Tests/SkipSQLPlusTests/SQLPlusTests.swift b/Tests/SkipSQLPlusTests/SQLPlusTests.swift index 6648766..1f4bf18 100644 --- a/Tests/SkipSQLPlusTests/SQLPlusTests.swift +++ b/Tests/SkipSQLPlusTests/SQLPlusTests.swift @@ -11,12 +11,12 @@ final class SQLPlusTests: XCTestCase { func testSQLPlus() throws { let sqlplus = SQLContext(configuration: .plus) - _ = try sqlplus.query(sql: "SELECT 1") - _ = try sqlplus.query(sql: "SELECT CURRENT_TIMESTAMP") - _ = try sqlplus.query(sql: "PRAGMA compile_options") + _ = try sqlplus.selectAll(sql: "SELECT 1") + _ = try sqlplus.selectAll(sql: "SELECT CURRENT_TIMESTAMP") + _ = try sqlplus.selectAll(sql: "PRAGMA compile_options") // ensure that FTS works - _ = try sqlplus.query(sql: "CREATE VIRTUAL TABLE \"documents\" USING fts5(content)") + _ = try sqlplus.selectAll(sql: "CREATE VIRTUAL TABLE \"documents\" USING fts5(content)") let stmnt = try sqlplus.prepare(sql: "SELECT 1") XCTAssertEqual("SELECT 1", stmnt.sql) @@ -25,45 +25,45 @@ final class SQLPlusTests: XCTestCase { try stmnt.close() // the locally built SQLite version (contrast with the macOS version 3.43.2) - XCTAssertEqual([SQLValue.text("3.49.2")], try sqlplus.query(sql: "SELECT sqlite_version()").first) - XCTAssertEqual([SQLValue.text("ATOMIC_INTRINSICS=1")], try sqlplus.query(sql: "PRAGMA compile_options").first) - XCTAssertEqual([SQLValue.text("4.9.0 community")], try sqlplus.query(sql: "PRAGMA cipher_version").first) - //XCTAssertEqual([SQLValue.text("PRAGMA cipher_default_kdf_iter = 256000")], try sqlplus.query(sql: "PRAGMA cipher_default_settings").first) - //XCTAssertEqual([SQLValue.text("XXX")], try sqlplus.query(sql: "PRAGMA cipher_provider").first) - //XCTAssertEqual([SQLValue.text("XXX")], try sqlplus.query(sql: "PRAGMA cipher_provider_version").first) + XCTAssertEqual([SQLValue.text("3.49.2")], try sqlplus.selectAll(sql: "SELECT sqlite_version()").first) + XCTAssertEqual([SQLValue.text("ATOMIC_INTRINSICS=1")], try sqlplus.selectAll(sql: "PRAGMA compile_options").first) + XCTAssertEqual([SQLValue.text("4.9.0 community")], try sqlplus.selectAll(sql: "PRAGMA cipher_version").first) + //XCTAssertEqual([SQLValue.text("PRAGMA cipher_default_kdf_iter = 256000")], try sqlplus.selectAll(sql: "PRAGMA cipher_default_settings").first) + //XCTAssertEqual([SQLValue.text("XXX")], try sqlplus.selectAll(sql: "PRAGMA cipher_provider").first) + //XCTAssertEqual([SQLValue.text("XXX")], try sqlplus.selectAll(sql: "PRAGMA cipher_provider_version").first) } func testSQLiteJSON() throws { let sqlplus = SQLContext(configuration: .plus) // The $[#] path feature in the JSON functions was added in version 3.31.0 - XCTAssertEqual([SQLValue.text("3.49.2")], try sqlplus.query(sql: "SELECT sqlite_version()").first) + XCTAssertEqual([SQLValue.text("3.49.2")], try sqlplus.selectAll(sql: "SELECT sqlite_version()").first) try sqlplus.exec(sql: #"CREATE TABLE users (id INTEGER PRIMARY KEY, profile JSON)"#) try sqlplus.exec(sql: #"INSERT INTO users (id, profile) VALUES (1, ?)"#, parameters: [.text(#"{"name": "Alice", "age": 30}"#)]) try sqlplus.exec(sql: #"INSERT INTO users (id, profile) VALUES (2, ?)"#, parameters: [.text(#"{"name": "Bob", "age": 25}"#)]) - let j1 = try sqlplus.query(sql: "SELECT json_extract(profile, '$.name') as name FROM users WHERE id = ?", parameters: [.long(1)]).first + let j1 = try sqlplus.selectAll(sql: "SELECT json_extract(profile, '$.name') as name FROM users WHERE id = ?", parameters: [.long(1)]).first XCTAssertEqual([.text("Alice")], j1) - let j2 = try sqlplus.query(sql: "SELECT json_extract(profile, '$.name') as name, json_extract(profile, '$.age') as age FROM users WHERE id = ?", parameters: [.long(2)]).first + let j2 = try sqlplus.selectAll(sql: "SELECT json_extract(profile, '$.name') as name, json_extract(profile, '$.age') as age FROM users WHERE id = ?", parameters: [.long(2)]).first XCTAssertEqual([.text("Bob"), .long(25)], j2) - XCTAssertEqual([.text("[1]")], try sqlplus.query(sql: "SELECT JSON_QUOTE(JSON('[1]'))").first) - XCTAssertEqual([.long(0)], try sqlplus.query(sql: "SELECT JSON_VALID('{\"x\":35')").first) - XCTAssertEqual([.text("array")], try sqlplus.query(sql: "SELECT JSON_TYPE('{\"a\":[2,3.5,true,false,null,\"x\"]}', '$.a')").first) - XCTAssertEqual([.text("[1,3,4]")], try sqlplus.query(sql: "SELECT JSON_REMOVE('[0,1,2,3,4]', '$[2]','$[0]')").first) - XCTAssertEqual([.text("[1,3,4]")], try sqlplus.query(sql: "SELECT JSON_REMOVE('[0,1,2,3,4]', '$[2]','$[0]')").first) - XCTAssertEqual([.text("{\"a\":1,\"b\":2,\"c\":3,\"d\":4}")], try sqlplus.query(sql: "SELECT JSON_PATCH('{\"a\":1,\"b\":2}','{\"c\":3,\"d\":4}')").first) - XCTAssertEqual([.text("{\"c\":{\"e\":5}}")], try sqlplus.query(sql: "SELECT JSON_OBJECT('c', JSON('{\"e\":5}'))").first) - XCTAssertEqual([.text("{\"a\":99,\"c\":4}")], try sqlplus.query(sql: "SELECT JSON_SET('{\"a\":2,\"c\":4}', '$.a', 99)").first) - XCTAssertEqual([.text("{\"a\":99,\"c\":4}")], try sqlplus.query(sql: "SELECT JSON_REPLACE('{\"a\":2,\"c\":4}', '$.a', 99)").first) - XCTAssertEqual([.text("[1,2,3,4,99]")], try sqlplus.query(sql: "SELECT JSON_INSERT('[1,2,3,4]','$[#]',99)").first) - XCTAssertEqual([.text("[[4,5],2]")], try sqlplus.query(sql: "SELECT JSON_EXTRACT('{\"a\":2,\"c\":[4,5]}','$.c','$.a')").first) - XCTAssertEqual([.long(3)], try sqlplus.query(sql: "SELECT JSON_ARRAY_LENGTH('{\"one\":[1,2,3]}', '$.one')").first) - XCTAssertEqual([.long(4)], try sqlplus.query(sql: "SELECT JSON_ARRAY_LENGTH('[1,2,3,4]')").first) - XCTAssertEqual([.text("[1,2,\"3\",4]")], try sqlplus.query(sql: "SELECT JSON_ARRAY(1, 2, '3', 4)").first) - XCTAssertEqual([.text("{\"a\":1,\"b\":2,\"c\":3,\"d\":4}")], try sqlplus.query(sql: "SELECT JSON_PATCH('{\"a\":1,\"b\":2}', '{\"c\":3,\"d\":4}')").first) + XCTAssertEqual([.text("[1]")], try sqlplus.selectAll(sql: "SELECT JSON_QUOTE(JSON('[1]'))").first) + XCTAssertEqual([.long(0)], try sqlplus.selectAll(sql: "SELECT JSON_VALID('{\"x\":35')").first) + XCTAssertEqual([.text("array")], try sqlplus.selectAll(sql: "SELECT JSON_TYPE('{\"a\":[2,3.5,true,false,null,\"x\"]}', '$.a')").first) + XCTAssertEqual([.text("[1,3,4]")], try sqlplus.selectAll(sql: "SELECT JSON_REMOVE('[0,1,2,3,4]', '$[2]','$[0]')").first) + XCTAssertEqual([.text("[1,3,4]")], try sqlplus.selectAll(sql: "SELECT JSON_REMOVE('[0,1,2,3,4]', '$[2]','$[0]')").first) + XCTAssertEqual([.text("{\"a\":1,\"b\":2,\"c\":3,\"d\":4}")], try sqlplus.selectAll(sql: "SELECT JSON_PATCH('{\"a\":1,\"b\":2}','{\"c\":3,\"d\":4}')").first) + XCTAssertEqual([.text("{\"c\":{\"e\":5}}")], try sqlplus.selectAll(sql: "SELECT JSON_OBJECT('c', JSON('{\"e\":5}'))").first) + XCTAssertEqual([.text("{\"a\":99,\"c\":4}")], try sqlplus.selectAll(sql: "SELECT JSON_SET('{\"a\":2,\"c\":4}', '$.a', 99)").first) + XCTAssertEqual([.text("{\"a\":99,\"c\":4}")], try sqlplus.selectAll(sql: "SELECT JSON_REPLACE('{\"a\":2,\"c\":4}', '$.a', 99)").first) + XCTAssertEqual([.text("[1,2,3,4,99]")], try sqlplus.selectAll(sql: "SELECT JSON_INSERT('[1,2,3,4]','$[#]',99)").first) + XCTAssertEqual([.text("[[4,5],2]")], try sqlplus.selectAll(sql: "SELECT JSON_EXTRACT('{\"a\":2,\"c\":[4,5]}','$.c','$.a')").first) + XCTAssertEqual([.long(3)], try sqlplus.selectAll(sql: "SELECT JSON_ARRAY_LENGTH('{\"one\":[1,2,3]}', '$.one')").first) + XCTAssertEqual([.long(4)], try sqlplus.selectAll(sql: "SELECT JSON_ARRAY_LENGTH('[1,2,3,4]')").first) + XCTAssertEqual([.text("[1,2,\"3\",4]")], try sqlplus.selectAll(sql: "SELECT JSON_ARRAY(1, 2, '3', 4)").first) + XCTAssertEqual([.text("{\"a\":1,\"b\":2,\"c\":3,\"d\":4}")], try sqlplus.selectAll(sql: "SELECT JSON_PATCH('{\"a\":1,\"b\":2}', '{\"c\":3,\"d\":4}')").first) } func testSQLCipher() throws { @@ -73,15 +73,15 @@ final class SQLPlusTests: XCTestCase { logger.log("testEncryption: checking db: \(dbPath.path)") let db = try SQLContext(path: dbPath.path, flags: [.create, .readWrite], configuration: .plus) if let key = key { - _ = try db.query(sql: "PRAGMA key = '\(key)'") + _ = try db.selectAll(sql: "PRAGMA key = '\(key)'") } if let plaintextHeader = plaintextHeader { - _ = try db.query(sql: "PRAGMA cipher_plaintext_header_size = \(plaintextHeader)") + _ = try db.selectAll(sql: "PRAGMA cipher_plaintext_header_size = \(plaintextHeader)") } - //_ = try db.query(sql: #"PRAGMA cipher_plaintext_header_size = 32"#) - //_ = try db.query(sql: #"PRAGMA cipher_salt = "x'01010101010101010101010101010101'""#) - //_ = try db.query(sql: #"PRAGMA user_version = 1; -- force header write"#) + //_ = try db.selectAll(sql: #"PRAGMA cipher_plaintext_header_size = 32"#) + //_ = try db.selectAll(sql: #"PRAGMA cipher_salt = "x'01010101010101010101010101010101'""#) + //_ = try db.selectAll(sql: #"PRAGMA user_version = 1; -- force header write"#) try db.exec(sql: #"CREATE TABLE SOME_TABLE(col)"#) try db.exec(sql: #"INSERT INTO SOME_TABLE(col) VALUES(?)"#, parameters: [.text(string)]) diff --git a/Tests/SkipSQLTests/SQLContextTests.swift b/Tests/SkipSQLTests/SQLContextTests.swift index 5c96426..d41290e 100644 --- a/Tests/SkipSQLTests/SQLContextTests.swift +++ b/Tests/SkipSQLTests/SQLContextTests.swift @@ -23,7 +23,7 @@ final class SQLContextTests: XCTestCase { ctx.trace { sql.append($0) } do { - _ = try ctx.query(sql: "SELECT ?", parameters: [.text("ABC")]) + _ = try ctx.selectAll(sql: "SELECT ?", parameters: [.text("ABC")]) XCTAssertEqual("SELECT 'ABC'", sql.last) } @@ -34,13 +34,13 @@ final class SQLContextTests: XCTestCase { func testSQLite() throws { let sqlite = SQLContext(configuration: .test) - _ = try sqlite.query(sql: "SELECT 1") - _ = try sqlite.query(sql: "SELECT CURRENT_TIMESTAMP") - _ = try sqlite.query(sql: "PRAGMA compile_options") + _ = try sqlite.selectAll(sql: "SELECT 1") + _ = try sqlite.selectAll(sql: "SELECT CURRENT_TIMESTAMP") + _ = try sqlite.selectAll(sql: "PRAGMA compile_options") #if os(macOS) - //XCTAssertEqual([SQLValue.text("3.43.2")], try sqlite.query(sql: "SELECT sqlite_version()").first) - XCTAssertEqual([SQLValue.text("ATOMIC_INTRINSICS=1")], try sqlite.query(sql: "PRAGMA compile_options").first) + //XCTAssertEqual([SQLValue.text("3.43.2")], try sqlite.selectAll(sql: "SELECT sqlite_version()").first) + XCTAssertEqual([SQLValue.text("ATOMIC_INTRINSICS=1")], try sqlite.selectAll(sql: "PRAGMA compile_options").first) #endif var updates = 0 @@ -172,7 +172,7 @@ final class SQLContextTests: XCTestCase { //SQLValue.blob(Data()), SQLValue.blob(Data([UInt8(0x01), UInt8(0x02)])), ] { - XCTAssertEqual(value, try sqlite.query(sql: "SELECT ?", parameters: [value]).first?.first) + XCTAssertEqual(value, try sqlite.selectAll(sql: "SELECT ?", parameters: [value]).first?.first) } } @@ -275,7 +275,7 @@ final class SQLContextTests: XCTestCase { do { // out of order positional parameters - XCTAssertEqual([SQLValue.text("ONE"), .text("TWO")], try ctx.query(sql: "SELECT ?2, ?1", parameters: [.text("TWO"), .text("ONE")]).first) + XCTAssertEqual([SQLValue.text("ONE"), .text("TWO")], try ctx.selectAll(sql: "SELECT ?2, ?1", parameters: [.text("TWO"), .text("ONE")]).first) } try ctx.close() @@ -352,19 +352,63 @@ final class SQLContextTests: XCTestCase { statements.append(sql) } - let blob = "XYZ".data(using: .utf8) + XCTAssertEqual("UTF-8", sqlite.encoding) + + XCTAssertFalse(sqlite.foreignKeysEnabled) + sqlite.foreignKeysEnabled = true + XCTAssertTrue(sqlite.foreignKeysEnabled) + + var blob = "XYZ".data(using: .utf8) XCTAssertEqual("x'58595a'", SQLValue(blob).literalValue) + func check(count expectedCount: Int, _ predicate: SQLPredicate? = nil, alias: String? = nil, sql: String? = nil) throws { + let resultSet = try sqlite.query(DemoTable.self, alias, where: predicate) + defer { resultSet.close() } + let instances = try resultSet.load() + XCTAssertEqual(expectedCount, instances.count) + if let sql { + XCTAssertEqual(sql, statements.last) + } + } + + func checkJoin(count expectedCount: Int, _ predicate: SQLPredicate? = nil, alias: String? = nil, sql: String? = nil) throws { + let resultSet = try sqlite.query(DemoJoinTable.self, alias, where: predicate) + defer { resultSet.close() } + let instances = try resultSet.load() + XCTAssertEqual(expectedCount, instances.count) + if let sql { + XCTAssertEqual(sql, statements.last) + } + } + func count(distinct: Bool = false, columns: String = "*", table: String) throws -> SQLValue? { try sqlite.prepare(sql: "SELECT COUNT(\(distinct ? "DISTINCT" : "") \(columns)) FROM \"\(table)\"").nextValues(close: true)?.first } - try sqlite.exec(DemoTable.createSQL()) + try sqlite.exec(DemoTable.table.createTableSQL()) + XCTAssertEqual(#"CREATE TABLE "DEMO_TABLE" ("ID" INTEGER PRIMARY KEY AUTOINCREMENT, "TXT" TEXT UNIQUE NOT NULL, "NUM" REAL, "INT" INTEGER NOT NULL, "DBL" REAL DEFAULT 3.141592653589793, "BLB" BLOB)"#, statements.last) + + try check(count: 0) + var ob = DemoTable(txt: "ABC", num: 12.3, int: 456, dbl: 7.89, blb: blob) try sqlite.inserted(&ob) + XCTAssertEqual(#"INSERT INTO "DEMO_TABLE" ("TXT", "NUM", "INT", "DBL", "BLB") VALUES ('ABC', 12.3, 456, 7.89, x'58595a')"#, statements.last) + XCTAssertEqual(1, sqlite.changes, "insert should report a change") + + ob.int *= 2 + ob.num = ob.num! * 2.0 + blob = "1234567890".data(using: .utf8) + ob.blb = blob + try sqlite.update(ob) + XCTAssertEqual(#"UPDATE "DEMO_TABLE" SET "TXT" = 'ABC', "NUM" = 24.6, "INT" = 912, "DBL" = 7.89, "BLB" = x'31323334353637383930' WHERE "ID" = 1"#, statements.last) + XCTAssertEqual(1, sqlite.changes, "update with changed fields should report a change") + + let ob1 = ob XCTAssertEqual(1, ob.id, "primary key should have been assigned") let initialInstance = ob + try check(count: 1) + XCTAssertEqual(SQLValue.long(1), try count(table: "DEMO_TABLE")) try XCTAssertNotNil(sqlite.fetch(DemoTable.self, id: SQLValue(1))) try XCTAssertNil(sqlite.fetch(DemoTable.self, id: SQLValue(9999))) @@ -381,6 +425,7 @@ final class SQLContextTests: XCTestCase { ob.txt = "DEF" ob.dbl = nil try sqlite.inserted(&ob, refresh: true) + let ob2 = ob XCTAssertEqual(2, ob.id, "primary key should have been assigned") XCTAssertEqual(Double.pi, ob.dbl, "default value should have been assigned") @@ -391,11 +436,13 @@ final class SQLContextTests: XCTestCase { ob.txt = "HIJ" ob.id = 6 try sqlite.inserted(&ob) + let ob6 = ob XCTAssertEqual(6, ob.id, "manual primary key specification should have been used") ob.txt = "KLM" ob.id = nil // auto-assign the next row try sqlite.inserted(&ob) + let ob7 = ob XCTAssertEqual(7, ob.id) ob.txt = "NMO" @@ -414,6 +461,7 @@ final class SQLContextTests: XCTestCase { // try again as an upsert try sqlite.insert(ob, upsert: true) + let ob4 = ob XCTAssertEqual(SQLValue.long(5), try count(table: "DEMO_TABLE")) @@ -424,7 +472,8 @@ final class SQLContextTests: XCTestCase { // SQLite error code 6: database table is locked defer { cursor.close() } - let bindings = try DemoTable.columns.map({ try initialInstance.binding(forColumn: $0) }) + let initialRow = try initialInstance.encodedRow() + let bindings = DemoTable.table.columns.map({ initialRow[$0] ?? .null }) let rowValues = try cursor.makeIterator().next()?.get() XCTAssertEqual(bindings, rowValues) } @@ -432,7 +481,7 @@ final class SQLContextTests: XCTestCase { // now try a cursored read of database instances do { //let cursor = try DemoTable.select(context: sqlite) - let cursor = try sqlite.select(DemoTable.self) + let cursor = try sqlite.query(DemoTable.self) // if we don't close the cursor before dropping the table, results in the error in Kotlin (GC'd): // SQLite error code 6: database table is locked @@ -442,34 +491,24 @@ final class SQLContextTests: XCTestCase { } // inserting autoincrement primary key - try sqlite.insert(DemoTable(txt: "", int: 999)) + var ob8 = DemoTable(txt: "", int: 999) + try sqlite.inserted(&ob8, refresh: true) do { - let idRanges = try sqlite.query(sql: "SELECT GROUP_CONCAT(ROWID, ',') AS ids FROM DEMO_TABLE") + let idRanges = try sqlite.selectAll(sql: "SELECT GROUP_CONCAT(ROWID, ',') AS ids FROM DEMO_TABLE") XCTAssertEqual("8,1,2,6,7,4", idRanges.first?.first?.textValue) } - func check(count expectedCount: Int, _ predicate: SQLPredicate, alias: String? = nil, sql: String? = nil) throws { - let resultSet = try sqlite.query(DemoTable.self, alias: alias, with: [predicate]) - defer { resultSet.close() } - var count = 0 - let cursor = resultSet.makeIterator() - while let row = cursor.next() { - let instance = try row.get() // instantiate the type from the row - count += 1 - let _ = instance - //logger.log("got instance: \(instance.id ?? 0)") - } - XCTAssertEqual(expectedCount, count) - if let sql { - XCTAssertEqual(sql, statements.last) - } + do { + // check limit/offset queries + XCTAssertEqual(1, try sqlite.query(DemoTable.self, limit: 1).load().count) + XCTAssertEqual(2, try sqlite.query(DemoTable.self, limit: 100, offset: 4).load().count) } try check(count: 1, .equals(DemoTable.txt, SQLValue("ABC")), sql: #"SELECT "ID", "TXT", "NUM", "INT", "DBL", "BLB" FROM "DEMO_TABLE" WHERE "TXT" = 'ABC'"#) try check(count: 1, .equals(DemoTable.txt.alias("t0"), SQLValue("ABC")), alias: "t0", - sql: #"SELECT t0."ID", t0."TXT", t0."NUM", t0."INT", t0."DBL", t0."BLB" FROM "DEMO_TABLE" t0 WHERE t0."TXT" = 'ABC'"#) + sql: #"SELECT t0."ID", t0."TXT", t0."NUM", t0."INT", t0."DBL", t0."BLB" FROM "DEMO_TABLE" AS t0 WHERE t0."TXT" = 'ABC'"#) try check(count: 5, .notEquals(DemoTable.txt, SQLValue("ABC")), sql: #"SELECT "ID", "TXT", "NUM", "INT", "DBL", "BLB" FROM "DEMO_TABLE" WHERE "TXT" <> 'ABC'"#) @@ -514,33 +553,252 @@ final class SQLContextTests: XCTestCase { try check(count: 3, DemoTable.num.isNull().or(DemoTable.txt.equals(SQLValue("ABC"))), sql: #"SELECT "ID", "TXT", "NUM", "INT", "DBL", "BLB" FROM "DEMO_TABLE" WHERE ("NUM" IS NULL OR "TXT" = 'ABC')"#) - try check(count: 1, DemoTable.num.isNull().and(DemoTable.txt.greaterThanOrEqual(SQLValue("G"))), sql: #"SELECT "ID", "TXT", "NUM", "INT", "DBL", "BLB" FROM "DEMO_TABLE" WHERE ("NUM" IS NULL AND "TXT" >= 'G')"#) try check(count: 5, .equals(DemoTable.blb, SQLValue(blob)), - sql: #"SELECT "ID", "TXT", "NUM", "INT", "DBL", "BLB" FROM "DEMO_TABLE" WHERE "BLB" = x'58595a'"#) + sql: #"SELECT "ID", "TXT", "NUM", "INT", "DBL", "BLB" FROM "DEMO_TABLE" WHERE "BLB" = x'31323334353637383930'"#) try check(count: 5, .equals(DemoTable.dbl, SQLValue(Double.pi)), sql: #"SELECT "ID", "TXT", "NUM", "INT", "DBL", "BLB" FROM "DEMO_TABLE" WHERE "DBL" = 3.14159265358979"#) - try sqlite.exec(DemoTable.dropSQL()) + try sqlite.exec(DemoRelation.table.createTableSQL()) + XCTAssertEqual(#"CREATE TABLE "DEMO_RELATION" ("PK" INTEGER PRIMARY KEY AUTOINCREMENT, "FK" INTEGER, "INFO" TEXT UNIQUE NOT NULL, FOREIGN KEY ("FK") REFERENCES "DEMO_TABLE"("ID") ON DELETE SET NULL)"#, statements.last) + + try sqlite.exec(DemoJoinTable.table.createTableSQL()) + XCTAssertEqual(#"CREATE TABLE "DEMO_JOIN_TABLE" ("ID1" INTEGER NOT NULL, "ID2" INTEGER NOT NULL, PRIMARY KEY ("ID1", "ID2"), FOREIGN KEY ("ID1") REFERENCES "DEMO_TABLE"("ID") ON DELETE CASCADE, FOREIGN KEY ("ID2") REFERENCES "DEMO_TABLE"("ID") ON DELETE CASCADE)"#, statements.last) + + try DemoTable.table.createIndexSQL().forEach { try sqlite.exec($0) } + XCTAssertEqual(#"CREATE INDEX "IDX_DBL" ON "DEMO_TABLE"("DBL")"#, statements.last) + + let joinOb1 = try sqlite.insert(DemoJoinTable(id1: 1, id2: 1)) + let joinOb2 = try sqlite.insert(DemoJoinTable(id1: 2, id2: 4)) + let joinOb3 = try XCTUnwrap(ob4.addManyToManyRelation(instance: ob6, to: sqlite)) // same as: try sqlite.insert(DemoJoinTable(id1: 4, id2: 6)) + + do { + XCTAssertEqual(try ob1.manyToManyRelation(in: sqlite), [ob1]) + XCTAssertEqual(#"SELECT t0."ID", t0."TXT", t0."NUM", t0."INT", t0."DBL", t0."BLB", t1."ID1", t1."ID2", t2."ID", t2."TXT", t2."NUM", t2."INT", t2."DBL", t2."BLB" FROM "DEMO_TABLE" AS t0 INNER JOIN "DEMO_JOIN_TABLE" AS t1 ON t0."ID" = t1."ID1" INNER JOIN "DEMO_TABLE" AS t2 ON t2."ID" = t1."ID2" WHERE t0."ID" = 1"#, statements.last) + XCTAssertEqual(try ob2.manyToManyRelation(in: sqlite), [ob4]) + XCTAssertEqual(try ob4.manyToManyRelation(in: sqlite), [ob6]) + } + + do { // a single aliased query + let singleQuery = try sqlite.query(DemoTable.self, "t0") + defer { singleQuery.close() } + let singleQueryResults = try singleQuery.load() + XCTAssertEqual(6, singleQueryResults.count) + XCTAssertEqual(ob1, singleQueryResults.first) + XCTAssertEqual(#"SELECT t0."ID", t0."TXT", t0."NUM", t0."INT", t0."DBL", t0."BLB" FROM "DEMO_TABLE" AS t0"#, statements.last) + } + + do { // a cross join + let crossJoin = try sqlite.query(DemoTable.self, "t0", + join: .cross, on: nil, + DemoJoinTable.self, "t1") + defer { crossJoin.close() } + let crossJoinResults = try crossJoin.load() + XCTAssertEqual(6 * 3, crossJoinResults.count) + XCTAssertEqual(ob1, crossJoinResults.first?.0) + XCTAssertEqual(joinOb1, crossJoinResults.first?.1) + XCTAssertEqual(#"SELECT t0."ID", t0."TXT", t0."NUM", t0."INT", t0."DBL", t0."BLB", t1."ID1", t1."ID2" FROM "DEMO_TABLE" AS t0 CROSS JOIN "DEMO_JOIN_TABLE" AS t1"#, statements.last) + } + + do { // a two-way inner join + let joined2 = try sqlite.query(DemoTable.self, "t0", + join: .inner, on: DemoJoinTable.id1, + DemoJoinTable.self, "t1", + orderBy: [(DemoTable.id.alias("t0"), .descending), (DemoTable.txt.alias("t0"), .ascending)]) + defer { joined2.close() } + let joined2Results = try joined2.load() + XCTAssertEqual(3, joined2Results.count) + XCTAssertEqual(ob1, joined2Results.last?.0) + XCTAssertEqual(joinOb1, joined2Results.last?.1) + XCTAssertEqual(#"SELECT t0."ID", t0."TXT", t0."NUM", t0."INT", t0."DBL", t0."BLB", t1."ID1", t1."ID2" FROM "DEMO_TABLE" AS t0 INNER JOIN "DEMO_JOIN_TABLE" AS t1 ON t0."ID" = t1."ID1" ORDER BY t0."ID" DESC, t0."TXT" ASC"#, statements.last) + } + + do { // a two-way inner join with a condition + let joined2 = try sqlite.query(DemoTable.self, "t0", + join: .inner, on: DemoJoinTable.id1, + DemoJoinTable.self, "t1", + where: DemoTable.txt.alias("t0").equals(SQLValue("ABC"))) + defer { joined2.close() } + let joined2Results = try joined2.load() + XCTAssertEqual(1, joined2Results.count) + XCTAssertEqual(ob1, joined2Results.first?.0) + XCTAssertEqual(joinOb1, joined2Results.first?.1) + XCTAssertEqual(#"SELECT t0."ID", t0."TXT", t0."NUM", t0."INT", t0."DBL", t0."BLB", t1."ID1", t1."ID2" FROM "DEMO_TABLE" AS t0 INNER JOIN "DEMO_JOIN_TABLE" AS t1 ON t0."ID" = t1."ID1" WHERE t0."TXT" = 'ABC'"#, statements.last) + } + + do { // a two-way inner join without aliases + let joined2 = try sqlite.query(DemoTable.self, nil, + join: .inner, on: DemoJoinTable.id1, + DemoJoinTable.self, nil, + where: DemoTable.txt.equals(SQLValue("ABC"))) + defer { joined2.close() } + let joined2Results = try joined2.load() + XCTAssertEqual(1, joined2Results.count) + XCTAssertEqual(ob1, joined2Results.first?.0) + XCTAssertEqual(joinOb1, joined2Results.first?.1) + XCTAssertEqual(#"SELECT "ID", "TXT", "NUM", "INT", "DBL", "BLB", "ID1", "ID2" FROM "DEMO_TABLE" INNER JOIN "DEMO_JOIN_TABLE" ON "DEMO_TABLE"."ID" = "DEMO_JOIN_TABLE"."ID1" WHERE "TXT" = 'ABC'"#, statements.last) + } + + do { // a two-way inner join without aliases (to the other foreign key) + let joined2 = try sqlite.query(DemoTable.self, nil, + join: .inner, on: DemoJoinTable.id2, + DemoJoinTable.self, nil) + defer { joined2.close() } + let joined2Results = try joined2.load() + XCTAssertEqual(3, joined2Results.count) + XCTAssertEqual(ob1, joined2Results.first?.0) + XCTAssertEqual(joinOb1, joined2Results.first?.1) + XCTAssertEqual(#"SELECT "ID", "TXT", "NUM", "INT", "DBL", "BLB", "ID1", "ID2" FROM "DEMO_TABLE" INNER JOIN "DEMO_JOIN_TABLE" ON "DEMO_TABLE"."ID" = "DEMO_JOIN_TABLE"."ID2""#, statements.last) + } + + do { // a three-way RIGHT/LEFT join + let rightLeftJoined = try sqlite.query(DemoTable.self, "t0", + join1: .right, on1: DemoJoinTable.id1, + DemoJoinTable.self, "t1", + join2: .left, on2: DemoJoinTable.id2, + DemoTable.self, "t2") + defer { rightLeftJoined.close() } + let rightLeftJoinedResults = try rightLeftJoined.load() + XCTAssertEqual(3, rightLeftJoinedResults.count) + XCTAssertEqual(ob1, rightLeftJoinedResults.first?.0) + XCTAssertEqual(joinOb1, rightLeftJoinedResults.first?.1) + XCTAssertEqual(joinOb2, rightLeftJoinedResults.dropLast().last?.1) + XCTAssertEqual(joinOb3, rightLeftJoinedResults.last?.1) + XCTAssertEqual(ob1, rightLeftJoinedResults.first?.2) + + XCTAssertEqual(#"SELECT t0."ID", t0."TXT", t0."NUM", t0."INT", t0."DBL", t0."BLB", t1."ID1", t1."ID2", t2."ID", t2."TXT", t2."NUM", t2."INT", t2."DBL", t2."BLB" FROM "DEMO_TABLE" AS t0 RIGHT OUTER JOIN "DEMO_JOIN_TABLE" AS t1 ON t0."ID" = t1."ID1" LEFT OUTER JOIN "DEMO_TABLE" AS t2 ON t2."ID" = t1."ID2""#, statements.last) + } + + do { // a three-way LEFT/RIGHT join (where some items will be expected to be nil) + let leftRightJoined = try sqlite.query(DemoTable.self, "t0", + join1: .left, on1: DemoJoinTable.id1, + DemoJoinTable.self, "t1", + join2: .right, on2: DemoJoinTable.id2, + DemoTable.self, "t2", + where: DemoTable.int.alias("t2").isNotNull()) + defer { leftRightJoined.close() } + let leftRightJoinedResults = try leftRightJoined.load() + XCTAssertEqual(6, leftRightJoinedResults.count) + XCTAssertEqual(ob1, leftRightJoinedResults.first?.0) + XCTAssertEqual(joinOb1, leftRightJoinedResults.first?.1) + XCTAssertEqual(ob1, leftRightJoinedResults.first?.2) + + XCTAssertEqual(nil, leftRightJoinedResults.last?.0) + XCTAssertEqual(nil, leftRightJoinedResults.last?.1) + XCTAssertEqual(ob8, leftRightJoinedResults.last?.2) + XCTAssertEqual(#"SELECT t0."ID", t0."TXT", t0."NUM", t0."INT", t0."DBL", t0."BLB", t1."ID1", t1."ID2", t2."ID", t2."TXT", t2."NUM", t2."INT", t2."DBL", t2."BLB" FROM "DEMO_TABLE" AS t0 LEFT OUTER JOIN "DEMO_JOIN_TABLE" AS t1 ON t0."ID" = t1."ID1" RIGHT OUTER JOIN "DEMO_TABLE" AS t2 ON t2."ID" = t1."ID2" WHERE t2."INT" IS NOT NULL"#, statements.last) + } + + do { // a three-way full outer join + let leftRightJoined = try sqlite.query(DemoTable.self, "t0", + join1: .full, on1: DemoJoinTable.id1, + DemoJoinTable.self, "t1", + join2: .full, on2: DemoJoinTable.id2, + DemoTable.self, "t2") + defer { leftRightJoined.close() } + let leftRightJoinedResults = try leftRightJoined.load() + XCTAssertEqual(9, leftRightJoinedResults.count) + XCTAssertEqual(ob1, leftRightJoinedResults.first?.0) + XCTAssertEqual(joinOb1, leftRightJoinedResults.first?.1) + XCTAssertEqual(ob1, leftRightJoinedResults.first?.2) + + XCTAssertEqual(nil, leftRightJoinedResults.last?.0) + XCTAssertEqual(nil, leftRightJoinedResults.last?.1) + XCTAssertEqual(ob8, leftRightJoinedResults.last?.2) + XCTAssertEqual(#"SELECT t0."ID", t0."TXT", t0."NUM", t0."INT", t0."DBL", t0."BLB", t1."ID1", t1."ID2", t2."ID", t2."TXT", t2."NUM", t2."INT", t2."DBL", t2."BLB" FROM "DEMO_TABLE" AS t0 FULL OUTER JOIN "DEMO_JOIN_TABLE" AS t1 ON t0."ID" = t1."ID1" FULL OUTER JOIN "DEMO_TABLE" AS t2 ON t2."ID" = t1."ID2""#, statements.last) + } + + // 1-to-many relation + var relOb = try sqlite.insert(DemoRelation(fk: ob1.id, info: "XYZ")) + XCTAssertEqual(Int64(1), relOb.pk) + XCTAssertEqual([relOb], try ob1.oneToManyRelation(in: sqlite), "relation fetch should have returned relations") + + try check(count: 6) + try checkJoin(count: 3) + + try sqlite.delete(instances: [ob1]) + + XCTAssertEqual(ob1.id, relOb.fk) + try sqlite.refresh(&relOb) + XCTAssertEqual(nil, relOb.fk) // delete should have nulled the foreign key relation + + try check(count: 5) + try checkJoin(count: 2) // delete should have cascaded to join table + + try sqlite.delete(instances: [XCTUnwrap(sqlite.fetch(DemoTable.self, id: SQLValue(4)))]) + try checkJoin(count: 0) // ID 4 has 2 join rows which should have both cascaded + + try sqlite.delete(instances: [joinOb1, joinOb2, joinOb3]) // delete with compound primary key (already deleted, but we are just checking the SQL) + XCTAssertEqual(#"DELETE FROM "DEMO_JOIN_TABLE" WHERE ("ID1", "ID2") IN ((1, 1), (2, 4), (4, 6))"#, statements.last) + XCTAssertEqual(0, sqlite.changes, "delete with no matching instances should not have reported changes") + + do { + try sqlite.insert(joinOb1) // referenced tables do not exist + XCTFail("insert join table with non-existant references should have failed") + } catch let error as SQLError { + // expected + XCTAssertEqual("FOREIGN KEY constraint failed", error.msg) + } + + try check(count: 4) + + let remaining = try sqlite.query(DemoTable.self, orderBy: [(DemoTable.id, .descending), (DemoTable.txt, .ascending)]).load() + XCTAssertEqual(#"SELECT "ID", "TXT", "NUM", "INT", "DBL", "BLB" FROM "DEMO_TABLE" ORDER BY "ID" DESC, "TXT" ASC"#, statements.last) + + try sqlite.delete(instances: remaining) + XCTAssertEqual(#"DELETE FROM "DEMO_TABLE" WHERE "ID" IN (8, 7, 6, 2)"#, statements.last) + XCTAssertEqual(4, sqlite.changes, "delete should have reported changes") + + try check(count: 0) + + try sqlite.exec(DemoJoinTable.table.dropTableSQL()) + try sqlite.exec(DemoTable.table.dropTableSQL()) } -} -/// A struct that can read and write its values to the `DEMO_TABLE` table. -public struct DemoTable : SQLCodable, Equatable { - public static var tableName = "DEMO_TABLE" + func testSQLRefType() throws { + let sqlite = SQLContext(configuration: .test) + var statements: [String] = [] + sqlite.trace { sql in + self.logger.info("SQL: \(sql)") + statements.append(sql) + } - /// All the columns defined for this table - public static var columns: [SQLColumn] { - [id, txt, num, int, dbl, blb] + try ([SQLRefType.table.createTableSQL()] + SQLRefType.table.createIndexSQL()).forEach { + try sqlite.exec($0) + } + + let ref = try SQLRefType(context: sqlite, str: "ABC") + XCTAssertEqual(1, ref.rowid) + XCTAssertEqual(#"INSERT INTO "SQL_REF" ("STR") VALUES ('ABC')"#, statements.last) + + ref.str += ref.str + XCTAssertEqual(#"UPDATE "SQL_REF" SET "STR" = 'ABCABC' WHERE "ROWID" = 1"#, statements.last) + + ref.str += ref.str + XCTAssertEqual(#"UPDATE "SQL_REF" SET "STR" = 'ABCABCABCABC' WHERE "ROWID" = 1"#, statements.last) + + try ref.delete() + XCTAssertEqual(#"DELETE FROM "SQL_REF" WHERE "ROWID" = 1"#, statements.last) + + let ref2 = try SQLRefType(context: sqlite, str: "ABC") + XCTAssertEqual(1, ref2.rowid, "non-autoicrement rowid should have been reused after delete") + + let ref3 = try SQLRefType(context: sqlite, str: "ABC") + XCTAssertEqual(2, ref3.rowid) + + try sqlite.exec(SQLRefType.table.dropTableSQL()) } +} +/// A struct that can read and write its values to the `DEMO_TABLE` table. +public struct DemoTable : SQLCodable, Equatable { public var id: Int64? static let id = SQLColumn(name: "ID", type: .long, primaryKey: true, autoincrement: true) public var txt: String? - static let txt = SQLColumn(name: "TXT", type: .text, unique: true, nullable: false) + static let txt = SQLColumn(name: "TXT", type: .text, unique: true, nullable: false, index: SQLIndex(name: "IDX_TXT")) public var num: Double? static let num = SQLColumn(name: "NUM", type: .real) @@ -549,59 +807,178 @@ public struct DemoTable : SQLCodable, Equatable { static let int = SQLColumn(name: "INT", type: .long, nullable: false) public var dbl: Double? - static let dbl = SQLColumn(name: "DBL", type: .real, defaultValue: SQLValue(Double.pi)) + static let dbl = SQLColumn(name: "DBL", type: .real, defaultValue: SQLValue(Double.pi), index: SQLIndex(name: "IDX_DBL", unique: false)) public var blb: Data? static let blb = SQLColumn(name: "BLB", type: .blob) - /// Returns a `SQLValue` for the specified `SQLColumn` - public func binding(forColumn column: SQLColumn) throws -> SQLValue { - switch column { - case Self.id: return SQLValue(self.id) - case Self.txt: return SQLValue(self.txt) - case Self.num: return SQLValue(self.num) - case Self.int: return SQLValue(self.int) - case Self.dbl: return SQLValue(self.dbl) - case Self.blb: return SQLValue(self.blb) - default: throw SQLBindingError.unknownColumn(column) - } + public static let table = SQLTable(name: "DEMO_TABLE", columns: [id, txt, num, int, dbl, blb]) + + public init(id: Int64? = nil, txt: String? = nil, num: Double? = nil, int: Int, dbl: Double? = nil, blb: Data? = nil) { + self.id = id + self.txt = txt + self.num = num + self.int = int + self.dbl = dbl + self.blb = blb } - /// Updates the value of the given column with the given value - public mutating func update(column: SQLColumn, value: SQLValue) throws { - switch column { - case Self.id: self.id = value.longValue - case Self.txt: self.txt = value.textValue - case Self.num: self.num = value.realValue - case Self.int: self.int = .init(try SQLBindingError.checkNonNull(value.longValue, column)) - case Self.dbl: self.dbl = value.realValue - case Self.blb: self.blb = value.blobValue - default: throw SQLBindingError.unknownColumn(column) - } + public init(row: SQLRow, context: SQLContext) throws { + self.id = try Self.id.longValueRequired(in: row) + self.txt = try Self.txt.textValueRequired(in: row) + self.num = Self.num.realValue(in: row) + self.int = try Int(Self.int.longValueRequired(in: row)) + self.dbl = Self.dbl.realValue(in: row) + self.blb = Self.blb.blobValue(in: row) } - /// Create an instance of this type from the given row values - public static func create(withRow row: [SQLValue], fromColumns: [SQLColumn]? = nil) throws -> Self { - try DemoTable(withRow: row, fromColumns: fromColumns) + public func encode(row: inout SQLRow) throws { + row[Self.id] = SQLValue(self.id) + row[Self.txt] = SQLValue(self.txt) + row[Self.num] = SQLValue(self.num) + row[Self.int] = SQLValue(self.int) + row[Self.dbl] = SQLValue(self.dbl) + row[Self.blb] = SQLValue(self.blb) } +} - init(withRow row: [SQLValue], fromColumns: [SQLColumn]? = nil) throws { - self.int = 0 // need to initialize any non-nil instances with placeholder values - let columns = fromColumns ?? Self.columns - if row.count != columns.count { - throw SQLBindingError.columnValuesMismatch(row.count, columns.count) - } - for (value, column) in zip(row, columns) { - try update(column: column, value: value) +public extension DemoTable { + /// Fetches the one-to-many relationship for this instance + func oneToManyRelation(in context: SQLContext) throws -> [DemoRelation] { + try context.query(DemoRelation.self, where: DemoRelation.fk.equals(SQLValue(self.id))).load() + } + + /// Fetches the many-to-many relationship for this instance + func manyToManyRelation(in context: SQLContext) throws -> [DemoTable] { + try context.query(DemoTable.self, "t0", join1: .inner, on1: DemoJoinTable.id1, DemoJoinTable.self, "t1", join2: .inner, on2: DemoJoinTable.id2, DemoTable.self, "t2", where: DemoTable.id.alias("t0").equals(SQLValue(self.id))).load().compactMap(\.2) + } + + /// Adds the given instance to the many-many relationship table + internal func addManyToManyRelation(instance: DemoTable, to context: SQLContext) throws -> DemoJoinTable? { + if let id1 = self.id, let id2 = instance.id { + return try context.insert(DemoJoinTable(id1: id1, id2: id2)) + } else { + return nil } } - public init(id: Int64? = nil, txt: String? = nil, num: Double? = nil, int: Int, dbl: Double? = nil, blb: Data? = nil) { - self.id = id - self.txt = txt - self.num = num - self.int = int - self.dbl = dbl - self.blb = blb + /// Removes the given instance from the many-many relationship table + func removeManyToManyRelation(instance: DemoTable, from context: SQLContext) throws { + try context.delete(DemoJoinTable.self, where: DemoJoinTable.id1.equals(SQLValue(self.id)).and(DemoJoinTable.id2.equals(SQLValue(instance.id)))) + } +} + +public struct DemoRelation : SQLCodable, Equatable { + public let pk: Int64? + static let pk = SQLColumn(name: "PK", type: .long, primaryKey: true, autoincrement: true) + + public let fk: Int64? + static let fk = SQLColumn(name: "FK", type: .long, references: SQLForeignKey(table: DemoTable.table, column: DemoTable.id, onDelete: .setNull)) + + public var info: String + static let info = SQLColumn(name: "INFO", type: .text, unique: true, nullable: false, index: SQLIndex(name: "IDX_TXT")) + + public static let table = SQLTable(name: "DEMO_RELATION", columns: [pk, fk, info]) + + public init(pk: Int64? = nil, fk: Int64? = nil, info: String) { + self.pk = pk + self.fk = fk + self.info = info + } + + public init(row: SQLRow, context: SQLContext) throws { + self.pk = try Self.pk.longValueRequired(in: row) + self.fk = Self.fk.longValue(in: row) + self.info = try Self.info.textValueRequired(in: row) + } + + public func encode(row: inout SQLRow) throws { + row[Self.pk] = SQLValue(self.pk) + row[Self.fk] = SQLValue(self.fk) + row[Self.info] = SQLValue(self.info) + } +} + +/// A type that can read and write its values to the `DEMO_TABLE` table. +open class DemoJoinTableBase : SQLCodable { + public let id1: Int64 + static let id1 = SQLColumn(name: "ID1", type: .long, primaryKey: true, nullable: false, references: SQLForeignKey(table: DemoTable.table, column: DemoTable.id, onDelete: .cascade)) + + public let id2: Int64 + static let id2 = SQLColumn(name: "ID2", type: .long, primaryKey: true, nullable: false, references: SQLForeignKey(table: DemoTable.table, column: DemoTable.id, onDelete: .cascade)) + + public static let table = SQLTable(name: "DEMO_JOIN_TABLE", columns: [id1, id2]) + + public init(id1: Int64, id2: Int64) { + self.id1 = id1 + self.id2 = id2 + } + + public required init(row: SQLRow, context: SQLContext) throws { + self.id1 = try Self.id1.longValueRequired(in: row) + self.id2 = try Self.id2.longValueRequired(in: row) + } + + public func encode(row: inout SQLRow) throws { + row[Self.id1] = SQLValue(self.id1) + row[Self.id2] = SQLValue(self.id2) + } +} + +extension DemoJoinTable : Equatable { + public static func == (lhs: DemoJoinTable, rhs: DemoJoinTable) -> Bool { + lhs.id1 == rhs.id1 && lhs.id2 == rhs.id2 + } +} + +/// Demonstration that subclassing works with SQLCodable (although you can't add any properties or override the table for the type with new columns) +internal final class DemoJoinTable : DemoJoinTableBase { +// public override init(id1: Int64, id2: Int64) { +// super.init(id1: id1, id2: id2) +// } + +// public required init(row: SQLRow, in context: SQLContext) throws { +// try super.init(row: row) +// } + +} + +/// An example of a type that maintains its own context +public class SQLRefType : SQLCodable { + private let context: SQLContext + + fileprivate var rowid: Int64? + static let rowid = SQLColumn(name: "ROWID", type: .long, primaryKey: true, autoincrement: false) + + public var str: String { didSet { try? update() } } + static let str = SQLColumn(name: "STR", type: .text, nullable: false, index: SQLIndex(name: "IDX_TXT")) + + public static let table = SQLTable(name: "SQL_REF", columns: [rowid, str]) + + /// Create a new instance and insert it into the database + public init(context: SQLContext, str: String) throws { + self.context = context + self.str = str + try context.insert(self) + self.rowid = context.lastInsertRowID // fetched the inserted ID from the database + } + + public required init(row: SQLRow, context: SQLContext) throws { + self.context = context + self.rowid = try Self.rowid.longValueRequired(in: row) + self.str = try Self.str.textValueRequired(in: row) + } + + public func encode(row: inout SQLRow) throws { + row[Self.rowid] = SQLValue(self.rowid) + row[Self.str] = SQLValue(self.str) + } + + public func update() throws { + try context.update(self) + } + + public func delete() throws { + try context.delete(instances: [self]) } } From fb9dec3911cd6f300980ce49bc47f36607429488 Mon Sep 17 00:00:00 2001 From: Marc Prud'hommeaux Date: Tue, 29 Jul 2025 23:12:04 +0200 Subject: [PATCH 2/9] Add feature check for right and full outer joins --- Sources/SkipSQL/SQLCodable.swift | 4 ++-- Sources/SkipSQL/SQLContext.swift | 11 ++++++++++ Sources/SkipSQL/SQLite.swift | 25 +++++++++++++++++++++++ Sources/SkipSQL/SQLiteCLibrary.swift | 4 ++++ Sources/SkipSQL/SQLiteJLibrary.swift | 1 + Sources/SkipSQL/SQLiteLibrary.swift | 2 ++ Sources/SkipSQLPlus/SQLPlusCLibrary.swift | 4 ++++ Sources/SkipSQLPlus/SQLPlusJLibrary.swift | 1 + Tests/SkipSQLTests/SQLContextTests.swift | 6 +++--- 9 files changed, 53 insertions(+), 5 deletions(-) diff --git a/Sources/SkipSQL/SQLCodable.swift b/Sources/SkipSQL/SQLCodable.swift index a81eae2..ffa04bf 100644 --- a/Sources/SkipSQL/SQLCodable.swift +++ b/Sources/SkipSQL/SQLCodable.swift @@ -744,8 +744,8 @@ public enum SQLOrder { /// A type of join public enum SQLJoinType { case left - case right - case full + case right // needs 3.39.0+ + case full // needs 3.39.0+ case inner case cross diff --git a/Sources/SkipSQL/SQLContext.swift b/Sources/SkipSQL/SQLContext.swift index 40febb9..faafbd5 100644 --- a/Sources/SkipSQL/SQLContext.swift +++ b/Sources/SkipSQL/SQLContext.swift @@ -24,6 +24,13 @@ public class SQLContext { SQLite3.sqlite3_changes(db) } + /// Returns a number signifying the major, minor, and patch release of the underlying SQLite library. + /// + /// E.g., 3001002 == 3.1.2 + public var versionNumber: Int32 { + SQLite3.sqlite3_libversion_number() + } + /// The total number of rows inserted, modified or deleted by all [INSERT], [UPDATE] or [DELETE] statements completed since the database connection was opened, including those executed as part of triggers. public var totalChanges: Int32 { SQLite3.sqlite3_total_changes(db) @@ -67,6 +74,10 @@ public class SQLContext { return db } + public func supports(feature: SQLiteFeature) -> Bool { + self.versionNumber >= feature.minimumSupportedVersion + } + public struct OpenFlags: OptionSet { public let rawValue: Int32 diff --git a/Sources/SkipSQL/SQLite.swift b/Sources/SkipSQL/SQLite.swift index 6c3f8ea..be2d845 100644 --- a/Sources/SkipSQL/SQLite.swift +++ b/Sources/SkipSQL/SQLite.swift @@ -49,6 +49,31 @@ public enum SQLAction : Int32 { } } +public enum SQLiteFeature { + case rightJoin // RIGHT JOIN + case fullOuterJoin // FULL OUTER JOIN + case jsonFunction // JSON() + case selectReturning // SELECT ... RETURNING + case partialIntegrityCheck // PRAGMA integrity_check(table) + case sqliteSchemaTable // sqlite_master => sqlite_schema + case dropColumn // ALTER TABLE ... DROP COLUMN + case renameColumn // ALTER TABLE ... RENAME COLUMN + + /// The minimum SQLite version for the given feature + public var minimumSupportedVersion: Int32 { + switch self { + case .rightJoin: return 3_039_000 + case .fullOuterJoin: return 3_039_000 + case .jsonFunction: return 3_038_000 // 2022-02-22 + case .selectReturning: return 3_035_000 + case .partialIntegrityCheck: return 3_033_000 + case .sqliteSchemaTable: return 3_033_000 + case .dropColumn: return 3_035_000 + case .renameColumn: return 3_025_000 + } + } +} + /// The return value of `sqlite3_column_type()` can be used to decide which /// of the first six interface should be used to extract the column value. /// The value returned by `sqlite3_column_type()` is only meaningful if no diff --git a/Sources/SkipSQL/SQLiteCLibrary.swift b/Sources/SkipSQL/SQLiteCLibrary.swift index 34f90ee..ed0a03a 100644 --- a/Sources/SkipSQL/SQLiteCLibrary.swift +++ b/Sources/SkipSQL/SQLiteCLibrary.swift @@ -211,6 +211,10 @@ final class SQLiteCLibrary : SQLiteLibrary { SQLite3.sqlite3_shutdown() } + func sqlite3_libversion_number() -> Int32 { + SQLite3.sqlite3_libversion_number() + } + func sqlite3_extended_result_codes(_ db: OpaquePointer, _ on: Int32) -> Int32 { SQLite3.sqlite3_extended_result_codes(db, on) } diff --git a/Sources/SkipSQL/SQLiteJLibrary.swift b/Sources/SkipSQL/SQLiteJLibrary.swift index 765a59d..8115a01 100644 --- a/Sources/SkipSQL/SQLiteJLibrary.swift +++ b/Sources/SkipSQL/SQLiteJLibrary.swift @@ -80,6 +80,7 @@ internal final class SQLiteJNALibrary : SQLiteLibrary { /* SKIP INSERT: external */ func sqlite3_backup_pagecount(_ backup: OpaquePointer) -> Int32 /* SKIP INSERT: external */ func sqlite3_initialize() -> Int32 /* SKIP INSERT: external */ func sqlite3_shutdown() -> Int32 + /* SKIP INSERT: external */ func sqlite3_libversion_number() -> Int32 /* SKIP INSERT: external */ func sqlite3_extended_result_codes(_ db: OpaquePointer, _ on: Int32) -> Int32 /* SKIP INSERT: external */ func sqlite3_free(_ ptr: OpaquePointer) /* SKIP INSERT: external */ func sqlite3_db_mutex(_ db: OpaquePointer?) -> OpaquePointer? diff --git a/Sources/SkipSQL/SQLiteLibrary.swift b/Sources/SkipSQL/SQLiteLibrary.swift index 34058a8..41550ec 100644 --- a/Sources/SkipSQL/SQLiteLibrary.swift +++ b/Sources/SkipSQL/SQLiteLibrary.swift @@ -107,6 +107,8 @@ public protocol SQLiteLibrary : NativeLibrary { // Other Functions func sqlite3_initialize() -> Int32 func sqlite3_shutdown() -> Int32 + func sqlite3_libversion_number() -> Int32 + //func sqlite3_config(option: Int32, values: Object...) -> Int32 func sqlite3_extended_result_codes(_ db: OpaquePointer, _ on: Int32) -> Int32 #if SKIP diff --git a/Sources/SkipSQLPlus/SQLPlusCLibrary.swift b/Sources/SkipSQLPlus/SQLPlusCLibrary.swift index 4f7f8a7..a56eb6d 100644 --- a/Sources/SkipSQLPlus/SQLPlusCLibrary.swift +++ b/Sources/SkipSQLPlus/SQLPlusCLibrary.swift @@ -197,6 +197,10 @@ internal final class SQLPlusCLibrary : SQLiteLibrary { SQLExt.sqlite3_shutdown() } + func sqlite3_libversion_number() -> Int32 { + SQLExt.sqlite3_libversion_number() + } + func sqlite3_extended_result_codes(_ db: OpaquePointer, _ on: Int32) -> Int32 { SQLExt.sqlite3_extended_result_codes(db, on) } diff --git a/Sources/SkipSQLPlus/SQLPlusJLibrary.swift b/Sources/SkipSQLPlus/SQLPlusJLibrary.swift index 443bb2c..78d30d9 100644 --- a/Sources/SkipSQLPlus/SQLPlusJLibrary.swift +++ b/Sources/SkipSQLPlus/SQLPlusJLibrary.swift @@ -63,6 +63,7 @@ internal final class SQLPlusJNALibrary : SQLiteLibrary { /* SKIP INSERT: external */ func sqlite3_backup_pagecount(_ backup: OpaquePointer) -> Int32 /* SKIP INSERT: external */ func sqlite3_initialize() -> Int32 /* SKIP INSERT: external */ func sqlite3_shutdown() -> Int32 + /* SKIP INSERT: external */ func sqlite3_libversion_number() -> Int32 /* SKIP INSERT: external */ func sqlite3_extended_result_codes(_ db: OpaquePointer, _ on: Int32) -> Int32 /* SKIP INSERT: external */ func sqlite3_free(_ ptr: OpaquePointer) /* SKIP INSERT: external */ func sqlite3_db_mutex(_ db: OpaquePointer?) -> OpaquePointer? diff --git a/Tests/SkipSQLTests/SQLContextTests.swift b/Tests/SkipSQLTests/SQLContextTests.swift index d41290e..3cf7b61 100644 --- a/Tests/SkipSQLTests/SQLContextTests.swift +++ b/Tests/SkipSQLTests/SQLContextTests.swift @@ -653,7 +653,7 @@ final class SQLContextTests: XCTestCase { XCTAssertEqual(#"SELECT "ID", "TXT", "NUM", "INT", "DBL", "BLB", "ID1", "ID2" FROM "DEMO_TABLE" INNER JOIN "DEMO_JOIN_TABLE" ON "DEMO_TABLE"."ID" = "DEMO_JOIN_TABLE"."ID2""#, statements.last) } - do { // a three-way RIGHT/LEFT join + if sqlite.supports(feature: .rightJoin) { // a three-way RIGHT/LEFT join let rightLeftJoined = try sqlite.query(DemoTable.self, "t0", join1: .right, on1: DemoJoinTable.id1, DemoJoinTable.self, "t1", @@ -671,7 +671,7 @@ final class SQLContextTests: XCTestCase { XCTAssertEqual(#"SELECT t0."ID", t0."TXT", t0."NUM", t0."INT", t0."DBL", t0."BLB", t1."ID1", t1."ID2", t2."ID", t2."TXT", t2."NUM", t2."INT", t2."DBL", t2."BLB" FROM "DEMO_TABLE" AS t0 RIGHT OUTER JOIN "DEMO_JOIN_TABLE" AS t1 ON t0."ID" = t1."ID1" LEFT OUTER JOIN "DEMO_TABLE" AS t2 ON t2."ID" = t1."ID2""#, statements.last) } - do { // a three-way LEFT/RIGHT join (where some items will be expected to be nil) + if sqlite.supports(feature: .rightJoin) { // a three-way LEFT/RIGHT join (where some items will be expected to be nil) let leftRightJoined = try sqlite.query(DemoTable.self, "t0", join1: .left, on1: DemoJoinTable.id1, DemoJoinTable.self, "t1", @@ -691,7 +691,7 @@ final class SQLContextTests: XCTestCase { XCTAssertEqual(#"SELECT t0."ID", t0."TXT", t0."NUM", t0."INT", t0."DBL", t0."BLB", t1."ID1", t1."ID2", t2."ID", t2."TXT", t2."NUM", t2."INT", t2."DBL", t2."BLB" FROM "DEMO_TABLE" AS t0 LEFT OUTER JOIN "DEMO_JOIN_TABLE" AS t1 ON t0."ID" = t1."ID1" RIGHT OUTER JOIN "DEMO_TABLE" AS t2 ON t2."ID" = t1."ID2" WHERE t2."INT" IS NOT NULL"#, statements.last) } - do { // a three-way full outer join + if sqlite.supports(feature: .fullOuterJoin) { // a three-way full outer join let leftRightJoined = try sqlite.query(DemoTable.self, "t0", join1: .full, on1: DemoJoinTable.id1, DemoJoinTable.self, "t1", From f3877b95a907c8c3c6f8829df6e71199f6fa384b Mon Sep 17 00:00:00 2001 From: Marc Prud'hommeaux Date: Wed, 30 Jul 2025 00:14:49 +0200 Subject: [PATCH 3/9] Add feature check for row values support and fall back to compound query when missing for compound primary keys --- Sources/SkipSQL/SQLCodable.swift | 18 ++++++++++++++---- Sources/SkipSQL/SQLite.swift | 2 ++ Tests/SkipSQLTests/SQLContextTests.swift | 6 +++++- 3 files changed, 21 insertions(+), 5 deletions(-) diff --git a/Sources/SkipSQL/SQLCodable.swift b/Sources/SkipSQL/SQLCodable.swift index ffa04bf..84e9d07 100644 --- a/Sources/SkipSQL/SQLCodable.swift +++ b/Sources/SkipSQL/SQLCodable.swift @@ -292,10 +292,20 @@ public extension SQLContext { return SQLPredicate.in(pkColumn, pks.map({ $0 })) } } else { - let columnsTuple: SQLRepresentable = SQLTuple(columns: pkColumns) - let valuesTuples: [SQLRepresentable] = pkValues.map({ SQLTuple(values: $0) }) - // multiple primary keys: query based on the tuple - return SQLPredicate.in(columnsTuple, valuesTuples) + if supports(feature: .rowValueSyntax) { + let columnsTuple: SQLRepresentable = SQLTuple(columns: pkColumns) + let valuesTuples: [SQLRepresentable] = pkValues.map({ SQLTuple(values: $0) }) + // multiple primary keys: query based on the tuple + return SQLPredicate.in(columnsTuple, valuesTuples) + } else { + // no support for tuple IN queries, so we need to fall back to: (ID1 = X1 AND ID2 = Y1) OR (ID1 = X2 AND ID2 = Y2)… + var equalsQueries: [SQLPredicate] = [] + for pkValueTuple in pkValues { + let parts = zip(pkColumns, pkValueTuple).map({ $0.equals($1) }) + equalsQueries.append(SQLPredicate.and(parts)) + } + return SQLPredicate.or(equalsQueries) + } } } diff --git a/Sources/SkipSQL/SQLite.swift b/Sources/SkipSQL/SQLite.swift index be2d845..20b5ee8 100644 --- a/Sources/SkipSQL/SQLite.swift +++ b/Sources/SkipSQL/SQLite.swift @@ -58,6 +58,7 @@ public enum SQLiteFeature { case sqliteSchemaTable // sqlite_master => sqlite_schema case dropColumn // ALTER TABLE ... DROP COLUMN case renameColumn // ALTER TABLE ... RENAME COLUMN + case rowValueSyntax // (a,b) IN ((1,2), (3,4)) /// The minimum SQLite version for the given feature public var minimumSupportedVersion: Int32 { @@ -70,6 +71,7 @@ public enum SQLiteFeature { case .sqliteSchemaTable: return 3_033_000 case .dropColumn: return 3_035_000 case .renameColumn: return 3_025_000 + case .rowValueSyntax: return 3_015_000 // https://sqlite.org/rowvalue.html#backwards_compatibility } } } diff --git a/Tests/SkipSQLTests/SQLContextTests.swift b/Tests/SkipSQLTests/SQLContextTests.swift index 3cf7b61..9c2a32e 100644 --- a/Tests/SkipSQLTests/SQLContextTests.swift +++ b/Tests/SkipSQLTests/SQLContextTests.swift @@ -731,7 +731,11 @@ final class SQLContextTests: XCTestCase { try checkJoin(count: 0) // ID 4 has 2 join rows which should have both cascaded try sqlite.delete(instances: [joinOb1, joinOb2, joinOb3]) // delete with compound primary key (already deleted, but we are just checking the SQL) - XCTAssertEqual(#"DELETE FROM "DEMO_JOIN_TABLE" WHERE ("ID1", "ID2") IN ((1, 1), (2, 4), (4, 6))"#, statements.last) + if sqlite.supports(feature: .rowValueSyntax) { + XCTAssertEqual(#"DELETE FROM "DEMO_JOIN_TABLE" WHERE ("ID1", "ID2") IN ((1, 1), (2, 4), (4, 6))"#, statements.last) + } else { + XCTAssertEqual(#"DELETE FROM "DEMO_JOIN_TABLE" WHERE (("ID1" = 1 AND "ID2" = 1) OR ("ID1" = 2 AND "ID2" = 4) OR ("ID1" = 4 AND "ID2" = 6))"#, statements.last) + } XCTAssertEqual(0, sqlite.changes, "delete with no matching instances should not have reported changes") do { From 1c8f35a8f6dfee550d85ba9e312c8cd0d55f190b Mon Sep 17 00:00:00 2001 From: Marc Prud'hommeaux Date: Wed, 30 Jul 2025 09:23:51 +0200 Subject: [PATCH 4/9] Add rowValueInSyntax feature case --- Sources/SkipSQL/SQLCodable.swift | 2 +- Sources/SkipSQL/SQLite.swift | 38 +++++++++++++----------- Tests/SkipSQLTests/SQLContextTests.swift | 3 +- 3 files changed, 23 insertions(+), 20 deletions(-) diff --git a/Sources/SkipSQL/SQLCodable.swift b/Sources/SkipSQL/SQLCodable.swift index 84e9d07..02d75fb 100644 --- a/Sources/SkipSQL/SQLCodable.swift +++ b/Sources/SkipSQL/SQLCodable.swift @@ -292,7 +292,7 @@ public extension SQLContext { return SQLPredicate.in(pkColumn, pks.map({ $0 })) } } else { - if supports(feature: .rowValueSyntax) { + if supports(feature: .rowValueInSyntax) { let columnsTuple: SQLRepresentable = SQLTuple(columns: pkColumns) let valuesTuples: [SQLRepresentable] = pkValues.map({ SQLTuple(values: $0) }) // multiple primary keys: query based on the tuple diff --git a/Sources/SkipSQL/SQLite.swift b/Sources/SkipSQL/SQLite.swift index 20b5ee8..30f276f 100644 --- a/Sources/SkipSQL/SQLite.swift +++ b/Sources/SkipSQL/SQLite.swift @@ -50,28 +50,30 @@ public enum SQLAction : Int32 { } public enum SQLiteFeature { - case rightJoin // RIGHT JOIN - case fullOuterJoin // FULL OUTER JOIN - case jsonFunction // JSON() - case selectReturning // SELECT ... RETURNING - case partialIntegrityCheck // PRAGMA integrity_check(table) - case sqliteSchemaTable // sqlite_master => sqlite_schema - case dropColumn // ALTER TABLE ... DROP COLUMN - case renameColumn // ALTER TABLE ... RENAME COLUMN - case rowValueSyntax // (a,b) IN ((1,2), (3,4)) + case rowValueSyntax // WHERE (a,b) = (1,2) + case rowValueInSyntax // WHERE (a,b) IN ((1,2), (3,4)) + case renameColumn // ALTER TABLE ... RENAME COLUMN + case partialIntegrityCheck // PRAGMA integrity_check(table) + case sqliteSchemaTable // sqlite_master => sqlite_schema + case selectReturning // SELECT ... RETURNING + case dropColumn // ALTER TABLE ... DROP COLUMN + case jsonFunction // JSON() + case rightJoin // RIGHT JOIN + case fullOuterJoin // FULL OUTER JOIN /// The minimum SQLite version for the given feature public var minimumSupportedVersion: Int32 { switch self { - case .rightJoin: return 3_039_000 - case .fullOuterJoin: return 3_039_000 - case .jsonFunction: return 3_038_000 // 2022-02-22 - case .selectReturning: return 3_035_000 - case .partialIntegrityCheck: return 3_033_000 - case .sqliteSchemaTable: return 3_033_000 - case .dropColumn: return 3_035_000 - case .renameColumn: return 3_025_000 - case .rowValueSyntax: return 3_015_000 // https://sqlite.org/rowvalue.html#backwards_compatibility + case .rowValueSyntax: return 3_015_000 // https://sqlite.org/rowvalue.html#backwards_compatibility + case .rowValueInSyntax: return 3_024_000 + case .renameColumn: return 3_025_000 + case .partialIntegrityCheck: return 3_033_000 + case .sqliteSchemaTable: return 3_033_000 + case .selectReturning: return 3_035_000 + case .dropColumn: return 3_035_000 + case .jsonFunction: return 3_038_000 // 2022-02-22 + case .rightJoin: return 3_039_000 + case .fullOuterJoin: return 3_039_000 } } } diff --git a/Tests/SkipSQLTests/SQLContextTests.swift b/Tests/SkipSQLTests/SQLContextTests.swift index 9c2a32e..c8f6197 100644 --- a/Tests/SkipSQLTests/SQLContextTests.swift +++ b/Tests/SkipSQLTests/SQLContextTests.swift @@ -17,7 +17,6 @@ final class SQLContextTests: XCTestCase { func testSQLiteTrace() throws { let ctx = SQLContext(configuration: .test) - // track executed SQL statements var sql: [String] = [] ctx.trace { sql.append($0) } @@ -33,6 +32,7 @@ final class SQLContextTests: XCTestCase { func testSQLite() throws { let sqlite = SQLContext(configuration: .test) + logger.info("connected to SQLite version: \(sqlite.versionNumber)") _ = try sqlite.selectAll(sql: "SELECT 1") _ = try sqlite.selectAll(sql: "SELECT CURRENT_TIMESTAMP") @@ -443,6 +443,7 @@ final class SQLContextTests: XCTestCase { ob.id = nil // auto-assign the next row try sqlite.inserted(&ob) let ob7 = ob + let _ = ob7 XCTAssertEqual(7, ob.id) ob.txt = "NMO" From 640e14a1244c0e042a524c94e2d3342aa08d8d89 Mon Sep 17 00:00:00 2001 From: Marc Prud'hommeaux Date: Wed, 30 Jul 2025 10:31:11 +0200 Subject: [PATCH 5/9] Fix version supporting rowValueInSyntax feature --- Sources/SkipSQL/SQLite.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Sources/SkipSQL/SQLite.swift b/Sources/SkipSQL/SQLite.swift index 30f276f..e3d215a 100644 --- a/Sources/SkipSQL/SQLite.swift +++ b/Sources/SkipSQL/SQLite.swift @@ -51,7 +51,6 @@ public enum SQLAction : Int32 { public enum SQLiteFeature { case rowValueSyntax // WHERE (a,b) = (1,2) - case rowValueInSyntax // WHERE (a,b) IN ((1,2), (3,4)) case renameColumn // ALTER TABLE ... RENAME COLUMN case partialIntegrityCheck // PRAGMA integrity_check(table) case sqliteSchemaTable // sqlite_master => sqlite_schema @@ -60,12 +59,12 @@ public enum SQLiteFeature { case jsonFunction // JSON() case rightJoin // RIGHT JOIN case fullOuterJoin // FULL OUTER JOIN + case rowValueInSyntax // WHERE (a,b) IN ((1,2), (3,4)) /// The minimum SQLite version for the given feature public var minimumSupportedVersion: Int32 { switch self { case .rowValueSyntax: return 3_015_000 // https://sqlite.org/rowvalue.html#backwards_compatibility - case .rowValueInSyntax: return 3_024_000 case .renameColumn: return 3_025_000 case .partialIntegrityCheck: return 3_033_000 case .sqliteSchemaTable: return 3_033_000 @@ -74,6 +73,7 @@ public enum SQLiteFeature { case .jsonFunction: return 3_038_000 // 2022-02-22 case .rightJoin: return 3_039_000 case .fullOuterJoin: return 3_039_000 + case .rowValueInSyntax: return 3_039_000 } } } From 32cc3cbe5925b956fb1ae754434c7f13f277b7b5 Mon Sep 17 00:00:00 2001 From: Marc Prud'hommeaux Date: Wed, 30 Jul 2025 12:12:20 +0200 Subject: [PATCH 6/9] Add test for SQLite version --- Sources/SkipSQL/SQLite.swift | 2 +- Tests/SkipSQLTests/SQLContextTests.swift | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/Sources/SkipSQL/SQLite.swift b/Sources/SkipSQL/SQLite.swift index e3d215a..032044a 100644 --- a/Sources/SkipSQL/SQLite.swift +++ b/Sources/SkipSQL/SQLite.swift @@ -73,7 +73,7 @@ public enum SQLiteFeature { case .jsonFunction: return 3_038_000 // 2022-02-22 case .rightJoin: return 3_039_000 case .fullOuterJoin: return 3_039_000 - case .rowValueInSyntax: return 3_039_000 + case .rowValueInSyntax: return 3_039_000 // https://sqlite.org/rowvalue.html#rvinop } } } diff --git a/Tests/SkipSQLTests/SQLContextTests.swift b/Tests/SkipSQLTests/SQLContextTests.swift index c8f6197..cd3270a 100644 --- a/Tests/SkipSQLTests/SQLContextTests.swift +++ b/Tests/SkipSQLTests/SQLContextTests.swift @@ -30,6 +30,12 @@ final class SQLContextTests: XCTestCase { try ctx.close() } + func testSQLiteVersion() throws { + let sqlite = SQLContext(configuration: .test) + logger.info("connected to SQLite version: \(sqlite.versionNumber)") + throw XCTSkip("Skip test for SQLite version: \(sqlite.versionNumber)") + } + func testSQLite() throws { let sqlite = SQLContext(configuration: .test) logger.info("connected to SQLite version: \(sqlite.versionNumber)") From dfd1d024b1be390c7706cec75f1114eaf3490302 Mon Sep 17 00:00:00 2001 From: Marc Prud'hommeaux Date: Wed, 30 Jul 2025 13:43:57 +0200 Subject: [PATCH 7/9] Auto-assign primary key when autoincrement column is set to 0 --- Sources/SkipSQL/SQLCodable.swift | 56 ++++++++++++++---------- Sources/SkipSQL/SQLite.swift | 2 +- Tests/SkipSQLTests/SQLContextTests.swift | 23 ++++++---- 3 files changed, 49 insertions(+), 32 deletions(-) diff --git a/Sources/SkipSQL/SQLCodable.swift b/Sources/SkipSQL/SQLCodable.swift index 02d75fb..0436f41 100644 --- a/Sources/SkipSQL/SQLCodable.swift +++ b/Sources/SkipSQL/SQLCodable.swift @@ -231,6 +231,15 @@ public extension SQLCodable { } } + /// Returns true if this is a new instance without a primary key value assigned, or nil if it is unknown (i.e., no primary key values) + var isNewInstance: Bool? { + get throws { + let pks = try self.primaryKeyValues + if pks.isEmpty { return nil } + return pks.allSatisfy({ $0 == .null || $0 == .defaultPrimaryKeyValue }) + } + } + static func selectSQL(alias: String? = nil) -> SQLExpression { let aliasName = alias == nil ? "" : alias! let aliasSuffix = alias == nil ? "" : (" AS " + aliasName) @@ -320,22 +329,23 @@ public extension SQLContext { let allBindings = allColumns.map({ row[$0] ?? .null }) var columns: [SQLColumn] = [] var bindings: [SQLValue] = [] - if explicitNulls { - columns = allColumns - bindings = allBindings - } else { - // filter out any NULL values so that defaults defined in the column are used - for (col, value) in zip(allColumns, allBindings) { + let update = upsert == nil + + // filter out any NULL values so that defaults defined in the column are used + for (col, value) in zip(allColumns, allBindings) { + if !update { + if col.primaryKey && col.autoincrement && value == SQLValue.defaultPrimaryKeyValue { + // for insert with autoincrement primary key values, filter out zero so that pk fields don't need to be null + continue + } if value == SQLValue.null { continue } - columns.append(col) - bindings.append(value) } + columns.append(col) + bindings.append(value) } - let update = upsert == nil - var expression = SQLExpression("") if update { expression.append("UPDATE \(tableName) SET ") @@ -401,18 +411,17 @@ public extension SQLContext { var rowMap = try _createSQLRow(columns, columns.map({ row[$0] ?? .null })) var changedFields = 0 for col in columns { - if row[col] == .null { - if col.primaryKey && col.autoincrement { - // get the last inserted row id and update it in the object - if rowMap[col] != .long(lastInsertRowID) { - rowMap[col] = .long(lastInsertRowID) - changedFields += 1 - } - } else if let defaultValue = col.defaultValue { - if rowMap[col] != defaultValue { - rowMap[col] = defaultValue - changedFields += 1 - } + if col.primaryKey && col.autoincrement && (row[col] == .null || row[col] == SQLValue.defaultPrimaryKeyValue) { + // get the last inserted row id and update it in the object + let lastID = SQLValue(lastInsertRowID) + if rowMap[col] != lastID { + rowMap[col] = lastID + changedFields += 1 + } + } else if let defaultValue = col.defaultValue, row[col] == .null { + if rowMap[col] != defaultValue { + rowMap[col] = defaultValue + changedFields += 1 } } } @@ -690,6 +699,9 @@ extension SQLColumn : SQLRepresentable { } extension SQLValue : SQLRepresentable { + /// The empty primary key value, signifying that the primary key should be assigned + public static let defaultPrimaryKeyValue = SQLValue.long(0) + public func apply(to expression: inout SQLExpression) { expression.append("?", self) } diff --git a/Sources/SkipSQL/SQLite.swift b/Sources/SkipSQL/SQLite.swift index 032044a..2ecaf4c 100644 --- a/Sources/SkipSQL/SQLite.swift +++ b/Sources/SkipSQL/SQLite.swift @@ -73,7 +73,7 @@ public enum SQLiteFeature { case .jsonFunction: return 3_038_000 // 2022-02-22 case .rightJoin: return 3_039_000 case .fullOuterJoin: return 3_039_000 - case .rowValueInSyntax: return 3_039_000 // https://sqlite.org/rowvalue.html#rvinop + case .rowValueInSyntax: return 3_039_000 // https://sqlite.org/rowvalue.html#rvinop, supposedly 3.24, but observed to fail in 3.28 } } } diff --git a/Tests/SkipSQLTests/SQLContextTests.swift b/Tests/SkipSQLTests/SQLContextTests.swift index cd3270a..3ba7880 100644 --- a/Tests/SkipSQLTests/SQLContextTests.swift +++ b/Tests/SkipSQLTests/SQLContextTests.swift @@ -33,6 +33,7 @@ final class SQLContextTests: XCTestCase { func testSQLiteVersion() throws { let sqlite = SQLContext(configuration: .test) logger.info("connected to SQLite version: \(sqlite.versionNumber)") + // this is just to get the Android CI to output the SQLite version number it is currently using throw XCTSkip("Skip test for SQLite version: \(sqlite.versionNumber)") } @@ -718,7 +719,10 @@ final class SQLContextTests: XCTestCase { } // 1-to-many relation - var relOb = try sqlite.insert(DemoRelation(fk: ob1.id, info: "XYZ")) + var relOb = DemoRelation(fk: ob1.id, info: "XYZ") + XCTAssertEqual(true, try relOb.isNewInstance) + relOb = try sqlite.insert(relOb) + XCTAssertEqual(false, try relOb.isNewInstance) XCTAssertEqual(Int64(1), relOb.pk) XCTAssertEqual([relOb], try ob1.oneToManyRelation(in: sqlite), "relation fetch should have returned relations") @@ -729,7 +733,7 @@ final class SQLContextTests: XCTestCase { XCTAssertEqual(ob1.id, relOb.fk) try sqlite.refresh(&relOb) - XCTAssertEqual(nil, relOb.fk) // delete should have nulled the foreign key relation + XCTAssertEqual(nil, relOb.fk, "delete should have nulled the foreign key relation") try check(count: 5) try checkJoin(count: 2) // delete should have cascaded to join table @@ -738,7 +742,7 @@ final class SQLContextTests: XCTestCase { try checkJoin(count: 0) // ID 4 has 2 join rows which should have both cascaded try sqlite.delete(instances: [joinOb1, joinOb2, joinOb3]) // delete with compound primary key (already deleted, but we are just checking the SQL) - if sqlite.supports(feature: .rowValueSyntax) { + if sqlite.supports(feature: .rowValueInSyntax) { XCTAssertEqual(#"DELETE FROM "DEMO_JOIN_TABLE" WHERE ("ID1", "ID2") IN ((1, 1), (2, 4), (4, 6))"#, statements.last) } else { XCTAssertEqual(#"DELETE FROM "DEMO_JOIN_TABLE" WHERE (("ID1" = 1 AND "ID2" = 1) OR ("ID1" = 2 AND "ID2" = 4) OR ("ID1" = 4 AND "ID2" = 6))"#, statements.last) @@ -794,10 +798,10 @@ final class SQLContextTests: XCTestCase { XCTAssertEqual(#"DELETE FROM "SQL_REF" WHERE "ROWID" = 1"#, statements.last) let ref2 = try SQLRefType(context: sqlite, str: "ABC") - XCTAssertEqual(1, ref2.rowid, "non-autoicrement rowid should have been reused after delete") + XCTAssertEqual(2, ref2.rowid, "autoincrement rowid should not have been reused after delete") let ref3 = try SQLRefType(context: sqlite, str: "ABC") - XCTAssertEqual(2, ref3.rowid) + XCTAssertEqual(3, ref3.rowid) try sqlite.exec(SQLRefType.table.dropTableSQL()) } @@ -880,7 +884,7 @@ public extension DemoTable { } public struct DemoRelation : SQLCodable, Equatable { - public let pk: Int64? + public let pk: Int64 static let pk = SQLColumn(name: "PK", type: .long, primaryKey: true, autoincrement: true) public let fk: Int64? @@ -891,7 +895,7 @@ public struct DemoRelation : SQLCodable, Equatable { public static let table = SQLTable(name: "DEMO_RELATION", columns: [pk, fk, info]) - public init(pk: Int64? = nil, fk: Int64? = nil, info: String) { + public init(pk: Int64 = 0, fk: Int64? = nil, info: String) { self.pk = pk self.fk = fk self.info = info @@ -958,8 +962,8 @@ internal final class DemoJoinTable : DemoJoinTableBase { public class SQLRefType : SQLCodable { private let context: SQLContext - fileprivate var rowid: Int64? - static let rowid = SQLColumn(name: "ROWID", type: .long, primaryKey: true, autoincrement: false) + fileprivate var rowid: Int64 + static let rowid = SQLColumn(name: "ROWID", type: .long, primaryKey: true, autoincrement: true) public var str: String { didSet { try? update() } } static let str = SQLColumn(name: "STR", type: .text, nullable: false, index: SQLIndex(name: "IDX_TXT")) @@ -968,6 +972,7 @@ public class SQLRefType : SQLCodable { /// Create a new instance and insert it into the database public init(context: SQLContext, str: String) throws { + self.rowid = 0 // zero means it is unassigned self.context = context self.str = str try context.insert(self) From 71d7a0be6a1044bf5fe8885856a7837b14bf1eda Mon Sep 17 00:00:00 2001 From: Marc Prud'hommeaux Date: Wed, 30 Jul 2025 14:31:55 +0200 Subject: [PATCH 8/9] Add SQLContext.count() function --- Sources/SkipSQL/SQLCodable.swift | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/Sources/SkipSQL/SQLCodable.swift b/Sources/SkipSQL/SQLCodable.swift index 0436f41..143977c 100644 --- a/Sources/SkipSQL/SQLCodable.swift +++ b/Sources/SkipSQL/SQLCodable.swift @@ -265,6 +265,16 @@ public extension SQLContext { return stmnt } + @inline(__always) func count(_ type: T.Type, where: SQLPredicate? = nil) throws -> Int64 { + // SKIP INSERT: val T = T::class.companionObjectInstance as SQLCodableCompanion // needed to access statics in generic constrained type + var countSQL = SQLExpression("SELECT COUNT(*) FROM " + T.table.quotedName) + if let `where` { + countSQL.append(" WHERE ") + `where`.apply(to: &countSQL) + } + return try cursor(countSQL).map({ try $0.get() }).first?.first?.longValue ?? 0 + } + /// Delete the given instances from the database. Instances must have at least one primary key defined. @inline(__always) func delete(instances: [T]) throws { try delete(T.self, where: primaryKeyQuery(instances)) From adef465010da6b16ae2422a895cb00ef79a67fe2 Mon Sep 17 00:00:00 2001 From: Marc Prud'hommeaux Date: Sat, 2 Aug 2025 01:19:56 +0200 Subject: [PATCH 9/9] Update schema creation functions --- README.md | 72 +++++++++++++++++++++++- Sources/SkipSQL/SQLCodable.swift | 36 ++++++++---- Sources/SkipSQL/SQLite.swift | 2 +- Tests/SkipSQLTests/SQLContextTests.swift | 18 ++++-- 4 files changed, 110 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index 8f69c21..b7e101e 100644 --- a/README.md +++ b/README.md @@ -123,7 +123,7 @@ SkipSQL includes a basic mechanism for mapping Swift types to tables through the ```swift /// A struct that can read and write its values to the `DEMO_TABLE` table. public struct DemoTable : SQLCodable, Equatable { - public var id: Int64? + public var id: Int64 static let id = SQLColumn(name: "ID", type: .long, primaryKey: true, autoincrement: true) public var txt: String? @@ -143,7 +143,7 @@ public struct DemoTable : SQLCodable, Equatable { public static let table = SQLTable(name: "DEMO_TABLE", columns: [id, txt, num, int, dbl, blb]) - public init(id: Int64? = nil, txt: String? = nil, num: Double? = nil, int: Int, dbl: Double? = nil, blb: Data? = nil) { + public init(id: Int64 = 0, txt: String? = nil, num: Double? = nil, int: Int, dbl: Double? = nil, blb: Data? = nil) { self.id = id self.txt = txt self.num = num @@ -190,6 +190,74 @@ while let row = cursor.next() { } ``` +### Primary keys and auto-increment columns + +SkipSQL supports primary keys that work with SQLite's ROWID mechanism, +such that when an `INTEGER` column (i.e., `SQLValue.long`) is the primary +key, the same storage is used as the underlying `ROWID` that all tables +automatically have. + +The property that be either an optional `Int64?`, or if it marked with +`autoincrement: true` and the type is a non-optional `Int64`, then inserting +a value with the id property set to `0` will automatically assign the +primary key when `.insert(ob)` is called. This enables a table to +have a required primary key (which is useful when implementing `Identifiable`) +with the special sentinal calue of `0` that indicates that it is a new instance. + +```swift +public var id: Int64 +static let id = SQLColumn(name: "ID", type: .long, primaryKey: true, autoincrement: true) +``` + +If the primary key is not marked with `autoincrement: true` and the +property is not optional, then it is assumed that the primary key +is manually assigned by the developer and care must be taken to +ensure that duplicate values are not inserted. + +### Relations and joins + +SkipSQL is not a complete object-relational mapping (ORM) package, +but it does contain the ability to perform joins across multiple +`SQLCodable` tables. + +```swift +/// A struct that can read and write its values to the `DEMO_TABLE` table. +public struct DemoParent : SQLCodable { + public var id: Int64 + static let id = SQLColumn(name: "ID", type: .long, primaryKey: true, autoincrement: true) + + public var parentInfo: String? + static let parentInfo = SQLColumn(name: "PARENT_INFO", type: .text) + + public static let table = SQLTable(name: "DEMO_TABLE", columns: [id, parentInfo]) +} + +public struct DemoChild : SQLCodable { + public var id: Int64 + static let id = SQLColumn(name: "ID", type: .long, primaryKey: true, autoincrement: true) + + public var parentID: Int64 + static let parentID = SQLColumn(name: "PARENT_ID", type: .long, references: SQLForeignKey(table: DemoParent.table, column: DemoParent.id, onDelete: .cascade)) + + public var childInfo: String? + static let childInfo = SQLColumn(name: "CHILD_INFO", type: .text) + + public static let table = SQLTable(name: "DEMO_CHILD", columns: [id, parentID, childInfo]) +} + +// perform a join between all the parents and children +let joined2: [(DemoParent?, DemoChild?)] = try sqlite.query(DemoParent.self, "t0", + join: .inner, on: DemoChild.parentID, + DemoChild.self, "t1").load() + +``` + +This operation will perform a one-to-many inner join from the `DemoParent` +to the `DemoChild` tables, and return a list of tuples between the matching +instances. Note that the tuple values are types as optionals, because for +outer join types, it is possible to have empty rows, which would map to +`nil` values. + ## Implementation SkipSQL speaks directly to the low-level SQLite3 C library that is pre-installed on all iOS and Android devices. diff --git a/Sources/SkipSQL/SQLCodable.swift b/Sources/SkipSQL/SQLCodable.swift index 143977c..908e501 100644 --- a/Sources/SkipSQL/SQLCodable.swift +++ b/Sources/SkipSQL/SQLCodable.swift @@ -42,19 +42,22 @@ public struct SQLTable : Hashable, Sendable { } /// Returns the SQL to create this table. - public func createTableSQL(ifNotExists: Bool = false, clauses additionalClauses: [String] = []) -> SQLExpression { + public func createTableSQL(ifNotExists: Bool = false, withIndexes: Bool = true, columns: [SQLColumn]? = nil, additionalClauses: [String] = []) -> [SQLExpression] { var sql = "CREATE TABLE " if ifNotExists { sql += "IF NOT EXISTS " } + + let columns = columns ?? self.columns + var clauses: [String] = [] - let pkColumns = self.columns.filter(\.primaryKey) + let pkColumns = columns.filter(\.primaryKey) if pkColumns.count >= 2 { // primary key clause added to the end only when there are multiple PKs for the table clauses.append("PRIMARY KEY (\(pkColumns.map(\.quotedName).joined(separator: ", ")))") } - let fkColumns = self.columns.filter({ $0.references != nil }) + let fkColumns = columns.filter({ $0.references != nil }) for fkColumn in fkColumns { // add in any foreign key clauses if let reference = fkColumn.references { @@ -67,18 +70,32 @@ public struct SQLTable : Hashable, Sendable { sql += self.quotedName sql += " (" - sql += (self.columns.map({ col in + sql += (columns.map({ col in col.definition(withPrimaryKey: pkColumns.count == 1) }) + clauses).joined(separator: ", ") sql += ")" + return [SQLExpression(sql)] + (withIndexes ? createIndexSQL(ifNotExists: ifNotExists, columns: columns) : []) + } + + /// Returns the SQL to add a column to the given table + public func addColumnSQL(column: SQLColumn, withIndexes: Bool = true) -> [SQLExpression] { + var sql = "ALTER TABLE \(self.quotedName) ADD COLUMN " + sql += column.definition(withPrimaryKey: false) + return [SQLExpression(sql)] + (withIndexes ? createIndexSQL(columns: [column]) : []) + } + + /// Returns the SQL to add a column to the given table + public func dropColumnSQL(column: SQLColumn) -> SQLExpression { + var sql = "ALTER TABLE \(self.quotedName) DROP COLUMN " + sql += column.quotedName return SQLExpression(sql) } /// Returns the SQL to create any indices on this table. - public func createIndexSQL(ifNotExists: Bool = false) -> [SQLExpression] { + public func createIndexSQL(ifNotExists: Bool = false, columns: [SQLColumn]? = nil) -> [SQLExpression] { var stmnts: [SQLExpression] = [] - for column in self.columns { + for column in columns ?? self.columns { if let index = column.index { var sql = "CREATE INDEX " if ifNotExists { @@ -387,11 +404,10 @@ public extension SQLContext { expression.append(")") } - if update == false, - upsert == true, - let pkColumn = columns.first(where: { $0.primaryKey == true }) { + let pkColumns = T.primaryKeyColumns + if update == false, upsert == true, !pkColumns.isEmpty { expression.append(" ON CONFLICT(") - expression.append(pkColumn.quotedName) + expression.append(pkColumns.map(\.quotedName).joined(separator: ", ")) expression.append(") DO UPDATE SET ") for (index, col) in columns.enumerated() { if index != 0 { diff --git a/Sources/SkipSQL/SQLite.swift b/Sources/SkipSQL/SQLite.swift index 2ecaf4c..bde11dc 100644 --- a/Sources/SkipSQL/SQLite.swift +++ b/Sources/SkipSQL/SQLite.swift @@ -147,7 +147,7 @@ public enum SQLValue : Hashable, Sendable, CustomStringConvertible { case .null: return "NULL" } } - + public var longValue: Int64? { switch self { case .long(let long): return long diff --git a/Tests/SkipSQLTests/SQLContextTests.swift b/Tests/SkipSQLTests/SQLContextTests.swift index 3ba7880..201cbb0 100644 --- a/Tests/SkipSQLTests/SQLContextTests.swift +++ b/Tests/SkipSQLTests/SQLContextTests.swift @@ -392,7 +392,9 @@ final class SQLContextTests: XCTestCase { try sqlite.prepare(sql: "SELECT COUNT(\(distinct ? "DISTINCT" : "") \(columns)) FROM \"\(table)\"").nextValues(close: true)?.first } - try sqlite.exec(DemoTable.table.createTableSQL()) + for ddl in DemoTable.table.createTableSQL(withIndexes: false) { + try sqlite.exec(ddl) + } XCTAssertEqual(#"CREATE TABLE "DEMO_TABLE" ("ID" INTEGER PRIMARY KEY AUTOINCREMENT, "TXT" TEXT UNIQUE NOT NULL, "NUM" REAL, "INT" INTEGER NOT NULL, "DBL" REAL DEFAULT 3.141592653589793, "BLB" BLOB)"#, statements.last) try check(count: 0) @@ -569,13 +571,19 @@ final class SQLContextTests: XCTestCase { try check(count: 5, .equals(DemoTable.dbl, SQLValue(Double.pi)), sql: #"SELECT "ID", "TXT", "NUM", "INT", "DBL", "BLB" FROM "DEMO_TABLE" WHERE "DBL" = 3.14159265358979"#) - try sqlite.exec(DemoRelation.table.createTableSQL()) + for ddl in DemoRelation.table.createTableSQL(withIndexes: false) { + try sqlite.exec(ddl) + } XCTAssertEqual(#"CREATE TABLE "DEMO_RELATION" ("PK" INTEGER PRIMARY KEY AUTOINCREMENT, "FK" INTEGER, "INFO" TEXT UNIQUE NOT NULL, FOREIGN KEY ("FK") REFERENCES "DEMO_TABLE"("ID") ON DELETE SET NULL)"#, statements.last) - try sqlite.exec(DemoJoinTable.table.createTableSQL()) + for ddl in DemoJoinTable.table.createTableSQL(withIndexes: false) { + try sqlite.exec(ddl) + } XCTAssertEqual(#"CREATE TABLE "DEMO_JOIN_TABLE" ("ID1" INTEGER NOT NULL, "ID2" INTEGER NOT NULL, PRIMARY KEY ("ID1", "ID2"), FOREIGN KEY ("ID1") REFERENCES "DEMO_TABLE"("ID") ON DELETE CASCADE, FOREIGN KEY ("ID2") REFERENCES "DEMO_TABLE"("ID") ON DELETE CASCADE)"#, statements.last) - try DemoTable.table.createIndexSQL().forEach { try sqlite.exec($0) } + try DemoTable.table.createIndexSQL().forEach { + try sqlite.exec($0) + } XCTAssertEqual(#"CREATE INDEX "IDX_DBL" ON "DEMO_TABLE"("DBL")"#, statements.last) let joinOb1 = try sqlite.insert(DemoJoinTable(id1: 1, id2: 1)) @@ -780,7 +788,7 @@ final class SQLContextTests: XCTestCase { statements.append(sql) } - try ([SQLRefType.table.createTableSQL()] + SQLRefType.table.createIndexSQL()).forEach { + try (SQLRefType.table.createTableSQL(withIndexes: true)).forEach { try sqlite.exec($0) }