Compare commits

...
15 Commits
Author SHA1 Message Date
Gwendal Roué 77b85bed25 Merge branch 'development' 2024-03-23 14:06:22 +01:00
Gwendal Roué bb8323b91d v6.26.0 2024-03-23 14:06:05 +01:00
Gwendal Roué d804b5ed9c Bump performance dependencies 2024-03-23 14:06:05 +01:00
Gwendal Roué 2af60cb324 CHANGELOG 2024-03-23 11:46:44 +01:00
Gwendal Roué 0434567f30 Merge pull request #1515 from groue/dev/cast
Support for the CAST SQLite function
2024-03-23 11:42:56 +01:00
Gwendal Roué 155a16bef8 CHANGELOG 2024-03-23 10:52:28 +01:00
Gwendal Roué 2ad1f37d2b Documentation for cast function 2024-03-23 10:48:20 +01:00
Gwendal Roué 32642d566b Test cast function 2024-03-23 10:47:57 +01:00
Gwendal Roué 1f4d5ac61a Fix test ambiguity 2024-03-23 10:47:49 +01:00
Gwendal Roué 87fdd9a66f cast function 2024-03-23 10:47:19 +01:00
Gwendal Roué 79d82337b2 CAST expression 2024-03-23 10:47:13 +01:00
Gwendal Roué fab4638fc9 Database.StorageClass 2024-03-23 10:46:52 +01:00
Gwendal Roué a49fd85627 Regression tests for #1512 2024-03-21 14:25:12 +01:00
Gwendal Roué ac8c4aea63 Report correct error when decoding NULL into Date or Data
Fixes #1512
2024-03-21 14:25:12 +01:00
Gwendal Roué 5413dcfeeb Remove jsonErrorPosition unless GRDBCUSTOMSQLITE || GRDBCIPHER
For some reason, if #available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *) has stopped being able to skip the test (WTF?)
2024-03-19 12:15:47 +01:00
20 changed files with 290 additions and 48 deletions

No files matched your search

+6 -1
View File
@@ -7,6 +7,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
#### 6.x Releases
- `6.26.x` Releases - [6.26.0](#6260)
- `6.25.x` Releases - [6.25.0](#6250)
- `6.24.x` Releases - [6.24.0](#6240) - [6.24.1](#6241) - [6.24.2](#6242)
- `6.23.x` Releases - [6.23.0](#6230)
@@ -123,12 +124,16 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
---
## Next Release
## 6.26.0
Released March 23, 2024
- **New**: [#1503](https://github.com/groue/GRDB.swift/pull/1503) by [@simba909](https://github.com/simba909): Conform Database.ColumnType to Sendable
- **New**: [#1510](https://github.com/groue/GRDB.swift/pull/1510) by [@groue](https://github.com/groue): Add Sendable conformances and unavailabilities
- **New**: [#1511](https://github.com/groue/GRDB.swift/pull/1511) by [@groue](https://github.com/groue): Database schema dump
- **New**: [#1515](https://github.com/groue/GRDB.swift/pull/1515) by [@groue](https://github.com/groue): Support for the CAST SQLite function
- **Fixed**: [#1508](https://github.com/groue/GRDB.swift/pull/1508) by [@groue](https://github.com/groue): Fix ValueObservation mishandling of database schema modification
- **Fixed**: [#1512](https://github.com/groue/GRDB.swift/issues/1512): Decoding errors are now correctly reported when decoding NULL into a non-optional property of type `Data` or `Date`.
## 6.25.0
+1 -1
View File
@@ -2661,7 +2661,7 @@ Aggregates can be modified and combined with Swift operators:
let request = Team.annotated(with: Team.players.min(Column("score")) ?? 0)
```
- SQL functions `ABS` and `LENGTH` are available as the `abs` and `length` Swift functions:
- SQL functions `ABS`, `CAST`, and `LENGTH` are available as the `abs`, `cast`, and `length` Swift functions:
<details>
<summary>SQL</summary>
+1 -1
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '6.25.0'
s.version = '6.26.0'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
+27
View File
@@ -115,6 +115,7 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
/// - ``trace(options:_:)``
/// - ``CheckpointMode``
/// - ``DatabaseBackupProgress``
/// - ``StorageClass``
/// - ``TraceEvent``
/// - ``TracingOptions``
public final class Database: CustomStringConvertible, CustomDebugStringConvertible {
@@ -2005,6 +2006,32 @@ extension Database {
/// An error log function that takes an error code and message.
public typealias LogErrorFunction = (_ resultCode: ResultCode, _ message: String) -> Void
/// An SQLite storage class.
///
/// For more information, see
/// [Datatypes In SQLite](https://www.sqlite.org/datatype3.html).
public struct StorageClass: RawRepresentable, Hashable, Sendable {
/// The SQL for the storage class (`"INTEGER"`, `"REAL"`, etc.)
public let rawValue: String
/// Creates an SQL storage class.
public init(rawValue: String) {
self.rawValue = rawValue
}
/// The `INTEGER` storage class.
public static let integer = StorageClass(rawValue: "INTEGER")
/// The `REAL` storage class.
public static let real = StorageClass(rawValue: "REAL")
/// The `TEXT` storage class.
public static let text = StorageClass(rawValue: "TEXT")
/// The `BLOB` storage class.
public static let blob = StorageClass(rawValue: "BLOB")
}
/// An option for the SQLite tracing feature.
///
/// You use `TracingOptions` with the `Database`
-1
View File
@@ -147,5 +147,4 @@ The `->` and `->>` SQL operators are available on the ``SQLJSONExpressible`` pro
### Validate JSON values at the SQL level
- ``Database/jsonErrorPosition(_:)``
- ``Database/jsonIsValid(_:)``
-15
View File
@@ -521,21 +521,6 @@ extension Database {
.function("JSON_ARRAY_LENGTH", [value.sqlExpression, path.sqlExpression])
}
/// The `JSON_ERROR_POSITION` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_ERROR_POSITION(info)
/// Database.jsonErrorPosition(Column("info"))
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jerr>
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func jsonErrorPosition(_ value: some SQLExpressible) -> SQLExpression {
.function("JSON_ERROR_POSITION", [value.sqlExpression])
}
/// The `JSON_EXTRACT` SQL function.
///
/// For example:
@@ -835,7 +835,7 @@ extension AssociationAggregate {
}
}
// MARK: - IFNULL(...)
// MARK: - Functions
extension AssociationAggregate {
/// The `IFNULL` SQL function.
@@ -854,8 +854,6 @@ extension AssociationAggregate {
}
}
// MARK: - ABS(...)
/// The `ABS` SQL function.
public func abs<RowDecoder>(_ aggregate: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
@@ -863,7 +861,18 @@ public func abs<RowDecoder>(_ aggregate: AssociationAggregate<RowDecoder>)
aggregate.map(abs)
}
// MARK: - LENGTH(...)
/// The `CAST` SQL function.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_expr.html#castexpr>
public func cast<RowDecoder>(
_ aggregate: AssociationAggregate<RowDecoder>,
as storageClass: Database.StorageClass)
-> AssociationAggregate<RowDecoder>
{
aggregate
.map { cast($0, as: storageClass) }
.with { $0.key = aggregate.key } // Preserve key
}
/// The `LENGTH` SQL function.
public func length<RowDecoder>(_ aggregate: AssociationAggregate<RowDecoder>)
@@ -90,6 +90,11 @@ public struct SQLExpression {
/// A literal SQL expression
case literal(SQL)
/// The `CAST(expr AS storage-class)` expression.
///
/// See <https://www.sqlite.org/lang_expr.html#castexpr>.
indirect case cast(SQLExpression, Database.StorageClass)
/// The `BETWEEN` and `NOT BETWEEN` operators.
///
/// <expression> BETWEEN <lowerBound> AND <upperBound>
@@ -224,6 +229,9 @@ public struct SQLExpression {
case let .literal(sqlLiteral):
return .literal(sqlLiteral.qualified(with: alias))
case let .cast(expression, storageClass):
return .cast(expression.qualified(with: alias), storageClass)
case let .between(
expression: expression,
lowerBound: lowerBound,
@@ -1092,6 +1100,13 @@ extension SQLExpression {
self.init(impl: .isEmpty(expression, isNegated: isNegated))
}
/// The `CAST(expr AS storage-class)` expression.
///
/// See <https://www.sqlite.org/lang_expr.html#castexpr>.
static func cast(_ expression: SQLExpression, as storageClass: Database.StorageClass) -> Self {
self.init(impl: .cast(expression, storageClass))
}
// MARK: Deferred
// TODO: replace with something that can work for WITHOUT ROWID table with a multi-columns primary key.
@@ -1269,6 +1284,9 @@ extension SQLExpression {
}
return resultSQL
case let .cast(expression, storageClass):
return try "CAST(\(expression.sql(context, wrappedInParenthesis: false)) AS \(storageClass.rawValue))"
case let .between(expression: expression, lowerBound: lowerBound, upperBound: upperBound, isNegated: isNegated):
var resultSQL = try """
\(expression.sql(context, wrappedInParenthesis: true)) \
@@ -1822,6 +1840,9 @@ extension SQLExpression {
let .associativeBinary(_, expressions):
return expressions.allSatisfy(\.isConstantInRequest)
case let .cast(expression, _):
return expression.isConstantInRequest
case let .between(expression: expression, lowerBound: lowerBound, upperBound: upperBound, isNegated: _):
return expression.isConstantInRequest
&& lowerBound.isConstantInRequest
@@ -57,6 +57,20 @@ public func average(_ value: some SQLSpecificExpressible) -> SQLExpression {
}
#endif
/// The `CAST` SQL function.
///
/// For example:
///
/// ```swift
/// // CAST(value AS REAL)
/// cast(Column("value"), as: .real)
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_expr.html#castexpr>
public func cast(_ expression: some SQLSpecificExpressible, as storageClass: Database.StorageClass) -> SQLExpression {
.cast(expression.sqlExpression, as: storageClass)
}
/// The `COUNT` SQL function.
///
/// For example:
+21 -1
View File
@@ -591,9 +591,19 @@ extension DatabaseDataDecodingStrategy {
fileprivate func decode(fromRow row: Row, atUncheckedIndex index: Int) throws -> Data {
if let sqliteStatement = row.sqliteStatement {
let statementIndex = CInt(index)
if sqlite3_column_type(sqliteStatement, statementIndex) == SQLITE_NULL {
throw RowDecodingError.valueMismatch(
Data.self,
sqliteStatement: sqliteStatement,
index: statementIndex,
context: RowDecodingContext(row: row, key: .columnIndex(index)))
}
return try decode(
fromStatement: sqliteStatement,
atUncheckedIndex: CInt(index),
atUncheckedIndex: statementIndex,
context: RowDecodingContext(row: row, key: .columnIndex(index)))
} else {
return try decode(
@@ -690,6 +700,16 @@ extension DatabaseDateDecodingStrategy {
fileprivate func decode(fromRow row: Row, atUncheckedIndex index: Int) throws -> Date {
if let sqliteStatement = row.sqliteStatement {
let statementIndex = CInt(index)
if sqlite3_column_type(sqliteStatement, statementIndex) == SQLITE_NULL {
throw RowDecodingError.valueMismatch(
Date.self,
sqliteStatement: sqliteStatement,
index: statementIndex,
context: RowDecodingContext(row: row, key: .columnIndex(index)))
}
return try decode(
fromStatement: sqliteStatement,
atUncheckedIndex: CInt(index),
+12 -1
View File
@@ -15,7 +15,7 @@
<a href="https://github.com/groue/GRDB.swift/actions/workflows/CI.yml"><img alt="CI Status" src="https://github.com/groue/GRDB.swift/actions/workflows/CI.yml/badge.svg?branch=master"></a>
</p>
**Latest release**: February 25, 2024 • [version 6.25.0](https://github.com/groue/GRDB.swift/tree/v6.25.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md)
**Latest release**: March 23, 2024 • [version 6.26.0](https://github.com/groue/GRDB.swift/tree/v6.26.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md)
**Requirements**: iOS 11.0+ / macOS 10.13+ / tvOS 11.0+ / watchOS 4.0+ &bull; SQLite 3.19.3+ &bull; Swift 5.7+ / Xcode 14+
@@ -4291,6 +4291,17 @@ GRDB comes with a Swift version of many SQLite [built-in functions](https://sqli
For more information about the functions `dateTime` and `julianDay`, see [Date And Time Functions](https://www.sqlite.org/lang_datefunc.html).
- `CAST`
Use the `cast` Swift function:
```swift
// SELECT (CAST(wins AS REAL) / games) AS successRate FROM player
Player.select((cast(winsColumn, as: .real) / gamesColumn).forKey("successRate"))
```
See [CAST expressions](https://www.sqlite.org/lang_expr.html#castexpr) for more information about SQLite conversions.
- `IFNULL`
Use the Swift `??` operator:
+1 -1
View File
@@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>6.25.0</string>
<string>6.26.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
@@ -1511,6 +1511,30 @@ class AssociationAggregateTests: GRDBTestCase {
}
}
func testCast() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.read { db in
do {
let request = Team.annotated(with: cast(Team.players.count, as: .real))
try assertEqualSQL(db, request, """
SELECT "team".*, CAST(COUNT(DISTINCT "player"."id") AS REAL) AS "playerCount" \
FROM "team" \
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
GROUP BY "team"."id"
""")
}
do {
let request = Team.annotated(with: cast(Team.players.count, as: .real).forKey("foo"))
try assertEqualSQL(db, request, """
SELECT "team".*, CAST(COUNT(DISTINCT "player"."id") AS REAL) AS "foo" \
FROM "team" \
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
GROUP BY "team"."id"
""")
}
}
}
func testLength() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.read { db in
@@ -263,14 +263,130 @@ extension FetchableRecordDecodableTests {
extension FetchableRecordDecodableTests {
func testStructWithData() throws {
struct StructWithData : FetchableRecord, Decodable {
let data: Data
}
let dbQueue = try makeDatabaseQueue()
do {
let data = "foo".data(using: .utf8)
do {
let value = try StructWithData(row: ["data": data])
XCTAssertEqual(value.data, data)
}
do {
let value = try dbQueue.read {
try StructWithData.fetchOne($0, sql: "SELECT ? AS data", arguments: [data])!
}
XCTAssertEqual(value.data, data)
}
}
do {
do {
_ = try StructWithData(row: ["data": nil])
XCTFail("Expected Error")
} catch let error as RowDecodingError {
switch error {
case .valueMismatch:
XCTAssertEqual(error.description, """
could not decode Data from database value NULL - \
column: "data", \
column index: 0, \
row: [data:NULL]
""")
default:
XCTFail("Unexpected Error")
}
}
do {
try dbQueue.read {
_ = try StructWithData.fetchOne($0, sql: "SELECT NULL AS data")
}
XCTFail("Expected Error")
} catch let error as RowDecodingError {
switch error {
case .valueMismatch:
XCTAssertEqual(error.description, """
could not decode Data from database value NULL - \
column: "data", \
column index: 0, \
row: [data:NULL], \
sql: `SELECT NULL AS data`, \
arguments: []
""")
default:
XCTFail("Unexpected Error")
}
}
}
}
func testStructWithDate() throws {
struct StructWithDate : FetchableRecord, Decodable {
let date: Date
}
let date = Date()
let value = try StructWithDate(row: ["date": date])
XCTAssert(abs(value.date.timeIntervalSince(date)) < 0.001)
let dbQueue = try makeDatabaseQueue()
do {
let date = Date()
do {
let value = try StructWithDate(row: ["date": date])
XCTAssert(abs(value.date.timeIntervalSince(date)) < 0.001)
}
do {
let value = try dbQueue.read {
try StructWithDate.fetchOne($0, sql: "SELECT ? AS date", arguments: [date])!
}
XCTAssert(abs(value.date.timeIntervalSince(date)) < 0.001)
}
}
do {
do {
_ = try StructWithDate(row: ["date": nil])
XCTFail("Expected Error")
} catch let error as RowDecodingError {
switch error {
case .valueMismatch:
XCTAssertEqual(error.description, """
could not decode Date from database value NULL - \
column: "date", \
column index: 0, \
row: [date:NULL]
""")
default:
XCTFail("Unexpected Error")
}
}
do {
try dbQueue.read {
_ = try StructWithDate.fetchOne($0, sql: "SELECT NULL AS date")
}
XCTFail("Expected Error")
} catch let error as RowDecodingError {
switch error {
case .valueMismatch:
XCTAssertEqual(error.description, """
could not decode Date from database value NULL - \
column: "date", \
column index: 0, \
row: [date:NULL], \
sql: `SELECT NULL AS date`, \
arguments: []
""")
default:
XCTFail("Unexpected Error")
}
}
}
}
func testStructWithURL() throws {
+3 -5
View File
@@ -358,11 +358,6 @@ final class JSONExpressionsTests: GRDBTestCase {
guard sqlite3_libversion_number() >= 3042000 else {
throw XCTSkip("JSON_ERROR_JSON is not available")
}
#else
guard #available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *) else {
throw XCTSkip("JSON_ERROR_JSON is not available")
}
#endif
try makeDatabaseQueue().inDatabase { db in
try db.create(table: "player") { t in
@@ -385,6 +380,9 @@ final class JSONExpressionsTests: GRDBTestCase {
SELECT JSON_ERROR_POSITION("info") FROM "player"
""")
}
#else
throw XCTSkip("JSON_ERROR_JSON is not available")
#endif
}
func test_Database_jsonExtract_atPath() throws {
@@ -1526,7 +1526,15 @@ class QueryInterfaceExpressionsTests: GRDBTestCase {
sql(dbQueue, tableRequest.select(average(Col.age / 2, filter: Col.age > 0))),
"SELECT AVG(\"age\" / 2) FILTER (WHERE \"age\" > 0) FROM \"readers\"")
}
func testCastExpression() throws {
let dbQueue = try makeDatabaseQueue()
XCTAssertEqual(
sql(dbQueue, tableRequest.select(cast(Col.name, as: .blob))),
"SELECT CAST(\"name\" AS BLOB) FROM \"readers\"")
}
func testLengthExpression() throws {
let dbQueue = try makeDatabaseQueue()
@@ -1,7 +1,7 @@
import XCTest
import GRDB
private func cast<T: SQLExpressible>(_ value: T, as type: Database.ColumnType) -> SQLExpression {
private func myCast<T: SQLExpressible>(_ value: T, as type: Database.ColumnType) -> SQLExpression {
SQL("CAST(\(value) AS \(sql: type.rawValue))").sqlExpression
}
@@ -19,7 +19,7 @@ class QueryInterfaceExtensibilityTests: GRDBTestCase {
try db.execute(sql: "INSERT INTO records (text) VALUES (?)", arguments: ["foo"])
do {
let request = Record.select(cast(Column("text"), as: .blob))
let request = Record.select(myCast(Column("text"), as: .blob))
let dbValue = try DatabaseValue.fetchOne(db, request)!
switch dbValue.storage {
case .blob:
@@ -30,7 +30,7 @@ class QueryInterfaceExtensibilityTests: GRDBTestCase {
XCTAssertEqual(self.lastSQLQuery, "SELECT CAST(\"text\" AS BLOB) FROM \"records\" LIMIT 1")
}
do {
let request = Record.select(cast(Column("text"), as: .blob) && true)
let request = Record.select(myCast(Column("text"), as: .blob) && true)
_ = try DatabaseValue.fetchOne(db, request)!
XCTAssertEqual(self.lastSQLQuery, "SELECT (CAST(\"text\" AS BLOB)) AND 1 FROM \"records\" LIMIT 1")
}
@@ -274,6 +274,10 @@ class SQLExpressionIsConstantTests: GRDBTestCase {
XCTAssertFalse((Column("a") - 2.databaseValue).isConstantInRequest)
XCTAssertFalse((1.databaseValue - Column("a")).isConstantInRequest)
// CAST
XCTAssertTrue(cast(1.databaseValue, as: .real).isConstantInRequest)
XCTAssertFalse(cast(Column("a"), as: .real).isConstantInRequest)
// SQLExpressionCollate
XCTAssertTrue("foo".databaseValue.collating(.binary).isConstantInRequest)
XCTAssertFalse(Column("a").collating(.binary).isConstantInRequest)
@@ -3,7 +3,7 @@
archiveVersion = 1;
classes = {
};
objectVersion = 52;
objectVersion = 54;
objects = {
/* Begin PBXBuildFile section */
@@ -1,12 +1,13 @@
{
"originHash" : "8d182a38fc35b0d50c198e0cbd39dc7fa5922eae5336ff3b0c73c2d51bcba752",
"pins" : [
{
"identity" : "fmdb",
"kind" : "remoteSourceControl",
"location" : "https://github.com/ccgus/fmdb.git",
"state" : {
"revision" : "61e51fde7f7aab6554f30ab061cc588b28a97d04",
"version" : "2.7.7"
"revision" : "47a2fa12a242b5a2fe13b916c22f2212e426055c",
"version" : "2.7.9"
}
},
{
@@ -14,8 +15,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/realm/realm-core.git",
"state" : {
"revision" : "f0045b71f9d3e9a6d82c711828f14222811fa6e9",
"version" : "13.9.4"
"revision" : "374dd672af357732dccc135fecc905406fec3223",
"version" : "14.4.1"
}
},
{
@@ -23,8 +24,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/realm/realm-swift.git",
"state" : {
"revision" : "00e098a61acdf5e8cee4e2a6292c9ec6762ba1b4",
"version" : "10.38.3"
"revision" : "e0c2fbb442979fbf1e4be80e01d142f310a9c762",
"version" : "10.49.1"
}
},
{
@@ -32,10 +33,10 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/stephencelis/SQLite.swift.git",
"state" : {
"revision" : "7a2e3cd27de56f6d396e84f63beefd0267b55ccb",
"version" : "0.14.1"
"revision" : "e78ae0220e17525a15ac68c697a155eb7a672a8e",
"version" : "0.15.0"
}
}
],
"version" : 2
"version" : 3
}