node-sqlite3 icon indicating copy to clipboard operation
node-sqlite3 copied to clipboard

Confused and not clear docs about `serialize`

Open vitonsky opened this issue 2 years ago • 1 comments

Issue Summary

I need to execute few SQL queries and wrap it in transaction, to ensure data consistency. I see DB have method serialize and i've read the docs https://github.com/tryghost/node-sqlite3/wiki/Control-Flow

It is absolutely not clear how this method works technically. Some questions i have after read:

  • How works this wrapper? Why SQL queries inside callback will executes one by one?
  • Can i wrap callbacks to promises? Is it will still executes one by one?
  • How to wrap to promises to make my code with complex request inside transaction are flatten?

Steps to Reproduce

  • Go to https://github.com/tryghost/node-sqlite3/wiki/Control-Flow
  • Read the docs and try to understand how serialize works under the hood, and how to create flat async code with few SQL queries inside transaction

Version

5.1.6

Node.js Version

v18.16.0

How did you install the library?

npm i sqlite3

vitonsky avatar Jul 09 '23 13:07 vitonsky

For promises, I created prun using p/deferred from the promesa library in clojurescript:

(defn- prun [db sql & [args]]
  (let [p (p/deferred)]
    #_(js/console.debug (format "running sql: %s with args: %s" sql args))
    (.run db sql (if args (clj->js args) #js [])
          (fn [err]
            (if err
              (p/reject! p (js->clj err))
              (p/resolve! p (this-as t {:last-id (.-lastID t)
                                        :changes (.-changes t)})))))
      p))

You could do similarly in plain JavaScript.

johanatan avatar Sep 10 '23 19:09 johanatan