Lighter-swift / Lighter

Swift APIs for SQLite: Type-safe down to the schema. Very, very, fast. Dependency free.
https://lighter-swift.github.io/documentation/lighter/
MIT License
460 stars 12 forks source link

Add an option to generate raw API that throws (vs returning the error code) #35

Open helje5 opened 1 month ago

helje5 commented 1 month ago

There was a request to generate raw API that throws vs returning the SQLite error code.

E.g. instead of:

func sqlite3_person_insert(_ db: OpaquePointer!, _ record: inout Person)
  -> Int32

this:

func sqlite3_person_insert(_ db: OpaquePointer!, _ record: inout Person) throws

Even in raw mode Enlighter already generates a nested SQLError structure into the Database structure, which could be used in the throwing versions:

public struct Database {
  public struct SQLError : Swift.Error, Equatable {
    public let code : Int32
    public let message : String?

Documented here: https://lighter-swift.github.io/documentation/lighter/sqliteapi#Handling-Errors

Notably there are raw functions that currently return nil on error and expect the caller to check the db handle for errors on its own. E.g.:

public func sqlite3_people_fetch(
  _ db: OpaquePointer!,
  sql customSQL: String? = nil,
  orderBy orderBySQL: String? = nil,
  limit: Int? = nil
) -> [ Person ]?
{
...
  guard sqlite3_prepare_v2(db, sql, -1, &handle, nil) == SQLITE_OK,
        let statement = handle else { return nil }
...
    else if rc != SQLITE_ROW {
      return nil
    }

I don't think this is very "hard" to add, but it affects quite a lot of code, i.e. it is quite a bit of work :-)

Created a feature/throwing-raw-1 that adds the option and an insert generator that does sth.