From bebb751b3c40b528e87cea70e9aec82bb5732dab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 22 Jun 2023 20:20:52 +0200 Subject: [PATCH] Create and drop view --- GRDB/Documentation.docc/DatabaseSchema.md | 7 + .../SQLInterpolation+QueryInterface.swift | 9 ++ .../Schema/TableDefinition.swift | 130 +++++++++++++++++- Tests/GRDBTests/TableDefinitionTests.swift | 95 +++++++++++++ 4 files changed, 238 insertions(+), 3 deletions(-) diff --git a/GRDB/Documentation.docc/DatabaseSchema.md b/GRDB/Documentation.docc/DatabaseSchema.md index 35636c104..a106c591d 100644 --- a/GRDB/Documentation.docc/DatabaseSchema.md +++ b/GRDB/Documentation.docc/DatabaseSchema.md @@ -372,6 +372,13 @@ extension Team: TableRecord { - ``TableOptions`` - ``VirtualTableModule`` +### Database Views + +- ``Database/create(view:options:columns:as:)`` +- ``Database/create(view:options:columns:asLiteral:)`` +- ``Database/drop(view:)`` +- ``ViewOptions`` + ### Database Indexes - ``Database/create(indexOn:columns:options:condition:)`` diff --git a/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift b/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift index 6f2bbb419..eb161ab8b 100644 --- a/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift +++ b/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift @@ -38,6 +38,15 @@ extension SQLInterpolation { appendInterpolation(type(of: record)) } + /// Appends a quoted identifier. + /// + /// // INSERT INTO "group" ... + /// let tableName = "group" + /// let request: SQLRequest = "INSERT INTO \(identifier: tableName) ..." + public mutating func appendInterpolation(identifier: String) { + appendLiteral(identifier.quotedDatabaseIdentifier) + } + /// Appends the table name of the record. /// /// // INSERT INTO player ... diff --git a/GRDB/QueryInterface/Schema/TableDefinition.swift b/GRDB/QueryInterface/Schema/TableDefinition.swift index 911fa8094..66a18645c 100644 --- a/GRDB/QueryInterface/Schema/TableDefinition.swift +++ b/GRDB/QueryInterface/Schema/TableDefinition.swift @@ -320,6 +320,117 @@ extension Database { try execute(sql: "DROP TABLE \(name.quotedDatabaseIdentifier)") } + /// Creates a database view. + /// + /// You can create a view with an ``SQLRequest``: + /// + /// ```swift + /// // CREATE VIEW hero AS SELECT * FROM player WHERE isHero == 1 + /// try db.create(view: "hero", as: SQLRequest(literal: """ + /// SELECT * FROM player WHERE isHero == 1 + /// """) + /// ``` + /// + /// You can also create a view with a ``QueryInterfaceRequest``: + /// + /// ```swift + /// // CREATE VIEW hero AS SELECT * FROM player WHERE isHero == 1 + /// try db.create( + /// view: "hero", + /// as: Player.filter(Column("isHero") == true)) + /// ``` + /// + /// When creating views in , it is not recommended to + /// use record types defined in the application. Instead of the `Player` + /// record type, prefer `Table("player")`: + /// + /// ```swift + /// // RECOMMENDED IN MIGRATIONS + /// try db.create( + /// view: "hero", + /// as: Table("player").filter(Column("isHero") == true)) + /// ``` + /// + /// Related SQLite documentation: + /// + /// - parameters: + /// - view: The view name. + /// - options: View creation options. + /// - columns: The columns of the view. If nil, the columns are the + /// columns of the request. + /// - request: The request that feeds the view. + public func create( + view name: String, + options: ViewOptions = [], + columns: [String]? = nil, + as request: SQLSubqueryable) + throws { + var literal: SQL = "CREATE " + + if options.contains(.temporary) { + literal += "TEMPORARY " + } + + literal += "VIEW " + + if options.contains(.ifNotExists) { + literal += "IF NOT EXISTS " + } + + literal += "\(identifier: name) " + + if let columns { + literal += "(" + literal += columns.map { "\(identifier: $0)" }.joined(separator: ", ") + literal += ") " + } + + literal += "AS \(request)" + + // CREATE VIEW does not support arguments, so make sure we use + // literal values. + let context = SQLGenerationContext(self, argumentsSink: .literalValues) + let sql = try literal.sql(context) + try execute(sql: sql) + } + + /// Creates a database view. + /// + /// For example: + /// + /// ```swift + /// // CREATE VIEW hero AS SELECT * FROM player WHERE isHero == 1 + /// try db.create(view: "hero", asLiteral: """ + /// SELECT * FROM player WHERE isHero == 1 + /// """) + /// ``` + /// + /// Related SQLite documentation: + /// + /// - parameters: + /// - view: The view name. + /// - options: View creation options. + /// - columns: The columns of the view. If nil, the columns are the + /// columns of the request. + /// - sqlLiteral: An `SQL` literal. + public func create( + view name: String, + options: ViewOptions = [], + columns: [String]? = nil, + asLiteral sqlLiteral: SQL) + throws { + try create(view: name, options: options, columns: columns, as: SQLRequest(literal: sqlLiteral)) + } + + /// Deletes a database view. + /// + /// Related SQLite documentation: + /// + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. + public func drop(view name: String) throws { + try execute(sql: "DROP VIEW \(name.quotedDatabaseIdentifier)") + } + /// Creates an index. /// /// For example: @@ -554,6 +665,19 @@ public struct TableOptions: OptionSet { #endif } +/// View creation options +public struct ViewOptions: OptionSet { + public let rawValue: Int + + public init(rawValue: Int) { self.rawValue = rawValue } + + /// Only creates the view if it does not already exist. + public static let ifNotExists = ViewOptions(rawValue: 1 << 0) + + /// Creates a temporary view. + public static let temporary = ViewOptions(rawValue: 1 << 1) +} + /// A `TableDefinition` lets you define the components of a database table. /// /// See the documentation of the `Database` @@ -628,7 +752,7 @@ public final class TableDefinition { case let .definition(def): return try def.sql(db, tableName: tableName, primaryKeyColumns: primaryKeyColumns) case let .literal(sqlLiteral): - let context = SQLGenerationContext(db, argumentsSink: .forRawSQL) + let context = SQLGenerationContext(db, argumentsSink: .literalValues) return try sqlLiteral.sql(context) } } @@ -1212,7 +1336,7 @@ public final class TableDefinition { } for literal in literalConstraints { - let context = SQLGenerationContext(db, argumentsSink: .forRawSQL) + let context = SQLGenerationContext(db, argumentsSink: .literalValues) try items.append(literal.sql(context)) } @@ -1439,7 +1563,7 @@ public final class TableAlteration { chunks.append("ALTER TABLE") chunks.append(name.quotedDatabaseIdentifier) chunks.append("ADD COLUMN") - let context = SQLGenerationContext(db, argumentsSink: .forRawSQL) + let context = SQLGenerationContext(db, argumentsSink: .literalValues) try chunks.append(sqlLiteral.sql(context)) let statement = chunks.joined(separator: " ") statements.append(statement) diff --git a/Tests/GRDBTests/TableDefinitionTests.swift b/Tests/GRDBTests/TableDefinitionTests.swift index dc8db3832..9b73b2a57 100644 --- a/Tests/GRDBTests/TableDefinitionTests.swift +++ b/Tests/GRDBTests/TableDefinitionTests.swift @@ -1033,4 +1033,99 @@ class TableDefinitionTests: GRDBTestCase { assertEqualSQL(lastSQLQuery!, "REINDEX swiftLocalizedCompare") } } + + func testCreateView() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("name") + t.column("score") + } + + do { + let request = SQLRequest(literal: """ + SELECT * FROM player WHERE name = \("O'Brien") + """) + try db.create(view: "view1", as: request) + assertEqualSQL(lastSQLQuery!, """ + CREATE VIEW "view1" AS SELECT * FROM player WHERE name = 'O''Brien' + """) + } + + do { + let request = Table("player").filter(Column("name") == "O'Brien") + try db.create(view: "view2", as: request) + assertEqualSQL(lastSQLQuery!, """ + CREATE VIEW "view2" AS SELECT * FROM "player" WHERE "name" = 'O''Brien' + """) + } + + do { + let sql: SQL = """ + SELECT * FROM player WHERE name = \("O'Brien") + """ + try db.create(view: "view3", asLiteral: sql) + assertEqualSQL(lastSQLQuery!, """ + CREATE VIEW "view3" AS SELECT * FROM player WHERE name = 'O''Brien' + """) + } + } + } + + func testCreateViewOptions() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("name") + t.column("score") + } + + let request = SQLRequest(literal: """ + SELECT * FROM player WHERE name = \("O'Brien") + """) + + do { + try db.create(view: "view1", options: .ifNotExists, as: request) + assertEqualSQL(lastSQLQuery!, """ + CREATE VIEW IF NOT EXISTS "view1" AS SELECT * FROM player WHERE name = 'O''Brien' + """) + } + + do { + try db.create(view: "view2", options: .temporary, as: request) + assertEqualSQL(lastSQLQuery!, """ + CREATE TEMPORARY VIEW "view2" AS SELECT * FROM player WHERE name = 'O''Brien' + """) + } + + do { + try db.create(view: "view3", options: [.temporary, .ifNotExists], as: request) + assertEqualSQL(lastSQLQuery!, """ + CREATE TEMPORARY VIEW IF NOT EXISTS "view3" AS SELECT * FROM player WHERE name = 'O''Brien' + """) + } + + do { + try db.create(view: "view4", columns: ["a", "b", "c"], as: request) + assertEqualSQL(lastSQLQuery!, """ + CREATE VIEW "view4" ("a", "b", "c") AS SELECT * FROM player WHERE name = 'O''Brien' + """) + } + } + } + + func testDropView() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(view: "test", as: SQLRequest(literal: "SELECT 'test', 42")) + XCTAssertTrue(try db.viewExists("test")) + XCTAssertEqual(try db.columns(in: "test").count, 2) + + try db.drop(view: "test") + assertEqualSQL(lastSQLQuery!, "DROP VIEW \"test\"") + XCTAssertFalse(try db.viewExists("test")) + } + } }