Better-sqlite3: db.transaction() not working?

Created on 19 Oct 2018  路  2Comments  路  Source: JoshuaWise/better-sqlite3

scratch.js

var better_sql = require("better-sqlite3");

const test = () => {
  var db = new better_sql("./database/dev.db");

  const insert = db.prepare(
    "INSERT INTO scan (fid, name) VALUES (@name, @fid)"
  );

  const insertMany = () => {
    console.log("INSERTMANY"); // showing
    db.transaction(cats => {
      for (const cat of cats) {
        console.log(cat); // NOT showing
        insert.run(cat);
      }
      console.log("TRANSACTION"); // NOT showing
    });
  };

  insertMany([
    { name: "Joey", fid: 2 },
    { name: "Sally", fid: 4 },
    { name: "Junior", fid: 1 }
  ]);
};
test();

Output:

$ node scratch.js
INSERTMANY
question

Most helpful comment

You misunderstood the documentation. The db.transaction() method returns a function (which is a wrapper around the function you provide to it). You must then invoke that returned function to actually get anything done.

const test = () => {
  var db = new better_sql("./database/dev.db");

  const insert = db.prepare(
    "INSERT INTO scan (fid, name) VALUES (@name, @fid)"
  );

  const insertMany = db.transaction((cats) => {
    console.log("BEGIN TRANSACTION");
    for (const cat of cats) {
      console.log(cat);
      insert.run(cat);
    }
    console.log("COMMIT TRANSACTION");
  });

  insertMany([
    { name: "Joey", fid: 2 },
    { name: "Sally", fid: 4 },
    { name: "Junior", fid: 1 }
  ]);
};
test();

All 2 comments

You misunderstood the documentation. The db.transaction() method returns a function (which is a wrapper around the function you provide to it). You must then invoke that returned function to actually get anything done.

const test = () => {
  var db = new better_sql("./database/dev.db");

  const insert = db.prepare(
    "INSERT INTO scan (fid, name) VALUES (@name, @fid)"
  );

  const insertMany = db.transaction((cats) => {
    console.log("BEGIN TRANSACTION");
    for (const cat of cats) {
      console.log(cat);
      insert.run(cat);
    }
    console.log("COMMIT TRANSACTION");
  });

  insertMany([
    { name: "Joey", fid: 2 },
    { name: "Sally", fid: 4 },
    { name: "Junior", fid: 1 }
  ]);
};
test();

I see it now. Thank you for the response

Was this page helpful?
0 / 5 - 0 ratings

Related issues

DrDonkeyPunch picture DrDonkeyPunch  路  5Comments

instagendleg picture instagendleg  路  4Comments

BobbyT picture BobbyT  路  3Comments

mann-david picture mann-david  路  5Comments

ccpwcn picture ccpwcn  路  4Comments