stephencelis / SQLite.swift

A type-safe, Swift-language layer over SQLite3.
MIT License
9.67k stars 1.56k forks source link

Feature request: Add table schema validation #931

Open bdorfman opened 5 years ago

bdorfman commented 5 years ago

There doesn't seem to be any easy way to do schema validation in the current version of the framework. All the migration docs just say to store a version number, but I would like to have more concrete assurances about the format of my database before I start trying to read/write things. (Additionally all the doc examples are heavily weighted on the "creating a new db" side, and it might be helpful to have more examples for best practices around opening and reading from an existing database).

Ideally this new feature would use the Expression types piped under the hood to the results of PRAGMA table_info to get a type safe validation that the schema of the table is what you expect before you start writing or reading values from it.

Using the columns set up in the examples in the docs, I would propose something that looks like : swift try db.run(users.validate { t in t.column(id, primaryKey: true) t.column(email, unique: true) t.column(name) })

the implementation of which would then call something like let tableInfo = Array(db.prepare("PRAGMA table_info(users)")) // check that Expressions listed match the table info returned

Ideally the validate func could be wrapped up into the create func for easy set up of databases (eg. a func that is: "validate this schema, create the table if it doesnt exist, and if it does exist and doesnt match, call this error handler" would be a convenient setup func you could just always call when opening the database)