bomberpac/sqlog/init.fnl
Jeremy Penner fd3fcbd978 integrate sqlite, reorganize code
* diet-sqlite - a cleaned-up, slightly updated, and de-ooped version of
  https://github.com/Wiladams/LJIT2SQLite
* rename waltz -> sqlog
* separate compiler from driver
* introduce uniform syntax for actions
2022-03-29 13:24:34 -04:00

59 lines
2 KiB
Fennel

(local Compiler (require :sqlog.compiler))
(local sqlite (require :diet-sqlite))
(local Object (require :core.object))
(local {: SQLITE_ROW} (require :diet-sqlite.codes))
(local Sqlog (Object:extend))
(fn Sqlog.new [self]
(set self.compiler (Compiler)))
(fn Sqlog.connect [self dbname]
(set self.db (sqlite.assert (sqlite.open dbname))))
(fn Sqlog.deftable [self name ...] (self:execute (self.compiler:deftable name ...)))
(fn Sqlog.defrule [self head ...] (self.compiler:defrule head ...))
(fn Sqlog.defrules [self ...] (self.compiler:defrules ...))
(fn Sqlog.compile-sql [self analysis]
(when (= analysis.stmt nil)
(let [stmt (sqlite.assert (sqlite.prepare self.db analysis.query))]
(sqlite.bind stmt analysis.constants)
(set analysis.stmt stmt)))
analysis)
(fn Sqlog.execute [self analysis ?collect-results]
(self:compile-sql analysis)
(sqlite.reset analysis.stmt)
(if ?collect-results
(let [result []]
(while (= SQLITE_ROW (sqlite.step analysis.stmt))
(table.insert result (collect [icol expr (ipairs analysis.selection)]
(match expr
[:as _ name] name
_ icol)
(sqlite.column analysis.stmt icol))))
result)
(sqlite.step analysis.stmt)))
(fn Sqlog.compile-action [self action]
(self:compile-sql
(match action
[:!+ & insert] (self.compiler:insert (table.unpack insert))
[:literal] (self.compiler:insert action)
[:!- & delete] (self.compiler:delete (table.unpack delete))
[:!= & update] (self.compiler:update (table.unpack update)))))
(fn Sqlog.compile-query [self ...] (self:compile-sql (self.compiler:query ...)))
(fn Sqlog.specify [self action ...]
(when (not= action nil)
(match action
[:* & rule] (self:defrule (table.unpack rule))
_ (self:execute (self:compile-action action)))
(self:specify ...)))
(fn Sqlog.query [self ...] (self:execute (self:compile-query ...) true))
Sqlog