Skip to content

Instantly share code, notes, and snippets.

@defndaines
Last active March 19, 2024 22:35
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save defndaines/58277fb975475ac2f522a2b1f1b849c8 to your computer and use it in GitHub Desktop.
Save defndaines/58277fb975475ac2f522a2b1f1b849c8 to your computer and use it in GitHub Desktop.
Attempt to Use SQLite3 from ClojureScript
;; Attempting to access an SQLite DB from Loom.
;; SQLite3 is installed and npm installed.
(def sqlite (js/require "sqlite3"))
(defn on-error [err]
(when err
(js/console.error err.message)))
;; Existing DB with 8 test records.
(def db
(new sqlite.Database "./resources/public/db/database.db" sqlite.OPEN_READONLY on-error))
(def id "901680220")
(defn query-handler [err, row]
(if err
(js/console.error err.message)
(js/console.error row)))
(.get db "SELECT last_name, first_name FROM voters WHERE id = ?" [id] query-handler)
;; => SQLITE_RANGE: bind or column index out of range
;; SOLUTION:
(.get db "SELECT last_name, first_name FROM voters WHERE id = ?" #js[id] query-handler)
=> { last_name: 'Heaton', first_name: 'Carl' }
@defndaines
Copy link
Author

I used

npm install --save-dev electron-builder
npm install --save sqlite3
npm run postinstall

(per https://stackoverflow.com/a/46254399) to get things available from the app and loom.

@defndaines
Copy link
Author

I'm using http://www.sqlitetutorial.net/sqlite-nodejs/connect/ as a reference for getting things going. My goal is to get it working, then to clean up the interface afterward to make it more "elegant".

@defndaines
Copy link
Author

Problem solved, thanks to Joel Sánchez and noisesmith on Slack.

The [id] is not being handled correctly (object vs. expect parameters): https://github.com/mapbox/node-sqlite3/wiki/API#databaserunsql-param--callback

[id] needs to be passed as either:

  • #js[id] (seems to be preferred approach)
  • (clj->js [id])

@defndaines
Copy link
Author

So query:

(.get db "SELECT last_name, first_name FROM voters WHERE id = ?" #js[id] query-handler)
=> { last_name: 'Heaton', first_name: 'Carl' }

@defndaines
Copy link
Author

Another useful post related to this (tip from Mike Fikes): Checked Array Access

This is important for getting data out of the results, using ((goog.object/get result "last_name")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment