https://github.com/valentindebon/sqlcodable
https://github.com/valentindebon/sqlcodable
Last synced: 3 months ago
JSON representation
- Host: GitHub
- URL: https://github.com/valentindebon/sqlcodable
- Owner: ValentinDebon
- License: bsd-3-clause
- Created: 2021-01-23T09:43:14.000Z (over 4 years ago)
- Default Branch: master
- Last Pushed: 2021-06-05T21:05:12.000Z (almost 4 years ago)
- Last Synced: 2024-12-29T16:58:29.083Z (5 months ago)
- Language: Swift
- Size: 55.7 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# SQLCodable
Manipulate SQL databases using the SQL language. And interface with Swift using Codable.
## Why?
In Swift, lots of ORMs and bindings exists. But none of them allows you to write raw SQL and directly interface with the database.
SQLCodable provides an Opaque Interface to the database and statement management. It doesn't manage nested containers, but encodes
your type in a prepared statement, and decodes each row using the parameters/columns names.## Example
Let's say you're a teacher and want to keep track of every students and the average of their marks for the semester.
The following sample illustrates how to create a DAO and interface for and SQLite-backed database.```swift
import SQLiteCodable
import SQLCodablestruct Student : Codable {
let firstname: String
let lastname: String
let average: Double
}final class StudentDAO : SQLDataAccessObject {
let database: SQLDatabaseinit(database: SQLDatabase) throws {
self.database = databasetry self.query("""
create table if not exists students (
firstname text,
lastname text,
average real,primary key (firstname, lastname)
)
""").next()
}func add(student: Student) throws {
try self.query("insert into students values (:firstname, :lastname, :average)", with: student).next()
}func findStudent(firstname: String, lastname: String) throws -> Student? {
try self.query("select * from students where firstname = ?1 and lastname = ?2", with: firstname, lastname).next()
}func validStudents(minimum average: Double = 10.0) throws -> [Student] {
try Array(self.query("select * from students where average >= ?1 order by average desc", with: average))
}
}let studentDAO = try StudentDAO(database: SQLiteDatabase())
try studentDAO.add(student: Student(firstname: "Nino", lastname: "Quincampoix", average: 9.0))
try studentDAO.add(student: Student(firstname: "Raphaël", lastname: "Poulain", average: 7.0))
try studentDAO.add(student: Student(firstname: "Dominique", lastname: "Bretodeau", average: 12.0))
try studentDAO.add(student: Student(firstname: "Raymond", lastname: "Dufayel", average: 17.0))try print(studentDAO.findStudent(firstname: "Dominique", lastname: "Bretodeau")!)
try print(studentDAO.validStudents())
```