Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/yanun0323/sworm
The fantastic ORM library of SQLite for Swift, makes life easier.
https://github.com/yanun0323/sworm
orm sqlite swift swiftui
Last synced: about 2 months ago
JSON representation
The fantastic ORM library of SQLite for Swift, makes life easier.
- Host: GitHub
- URL: https://github.com/yanun0323/sworm
- Owner: yanun0323
- Created: 2023-06-27T14:46:34.000Z (over 1 year ago)
- Default Branch: master
- Last Pushed: 2024-06-13T09:52:38.000Z (7 months ago)
- Last Synced: 2024-06-13T12:45:12.857Z (7 months ago)
- Topics: orm, sqlite, swift, swiftui
- Language: Swift
- Homepage:
- Size: 37.1 KB
- Stars: 4
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Sworm
The fantastic SQLite ORM library for Swift base on [SQLite](https://github.com/stephencelis/SQLite.swift).
### Sample Code
#### Definition
```swift
// implement Model protocol
extension Element: Model {
static let id = Expression("id")
static let name = Expression("name")
static let value = Expression("value")
static var table: Tablex { .init("elements") }
static func migrate(_ db: DB) throws {
try db.run(table.create(ifNotExists: true) { t in
t.column(id, primaryKey: .autoincrement)
t.column(name, unique: true)
t.column(value)
})
try db.run(table.createIndex(name, ifNotExists: true))
}
static func parse(_ r: Row) throws -> Element {
return Element(
id: try r.get(id),
name: try r.get(name),
value: try r.get(value)
)
}// setter is for quick insert/update/upsert
// ** please DO NOT set primary key in setter **
func setter() -> [Setter] {
return [
Element.name <- name,
Element.age <- age
]
}
}
```#### Usage
```swift
// initialize SQLite database and migrate tables with structures
// before you do every thing
func setup() {
let db = Sworm.setup(dbName: "database", isMock: false)
db.migrate(Element.self, Record.self)
}// query
func getElement(_ id: Int64) throws -> Element? {
return try Sworm.db.query(Element.self) { $0.where(Element.id == id) }.first
}func listElements() throws -> [Element] {
return try Sworm.db.query(Element.self) { $0 }
}// insert
func createElement(_ elem: Element) throws -> Int64 {
return try Sworm.db.insert(elem)
}// update
func updateElement(_ elem: Element) throws -> Int {
return try Sworm.db.update(elem) { $0.where(Element.id == elem.id) }
}// upsert
func upsertElement(_ elem: Element) throws -> Int64 {
return try Sworm.db.upsert(elem, Element.id) { $0.where(Element.id == elem.id) }
}// delete
func deleteElement(_ id: Int64) throws -> Int {
return try Sworm.db.delete(Element.self) { $0.where(Element.id == id)
}
```