generatedAs(sql:_:)
Defines the column as a generated column.
- iOS
- 15+
- macOS
- 12+
- tvOS
- 15+
- watchOS
- 8+
@discardableResult func generatedAs(sql: String, _ qualification: GeneratedColumnQualification = .virtual) -> Self
Parameters
- sql
An SQL expression.
- qualification
The generated column’s qualification, which defaults to
virtual
.
Returns
self
so that you can further refine the column definition.
For example:
// CREATE TABLE player(
// id INTEGER PRIMARY KEY AUTOINCREMENT,
// score INTEGER NOT NULL,
// bonus INTEGER NOT NULL,
// totalScore INTEGER GENERATED ALWAYS AS (score + bonus) VIRTUAL
// )
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("score", .integer).notNull()
t.column("bonus", .integer).notNull()
t.column("totalScore", .integer).generatedAs(sql: "score + bonus")
}
To remove the generated columns from the selection of record types, define their databaseSelection
:
struct Player: Codable {
// No property for `totalScore`
var id: Int64
var score: Int
var bonus: Int
}
extension Player: FetchableRecord, PersistableRecord {
static var databaseSelection: [any SQLSelectable] {
// Option 1
[Column("id"), Column("score"), Column("bonus")]
// Option 2
[.allColumns(excluding: ["totalScore"])]
}
}
// SELECT id, score, bonus FROM player
let players = try dbQueue.read { db in
try Player.fetchAll(db)
}
Related SQLite documentation: https://sqlite.org/gencol.html