How to use better-sqlite3 - 10 common examples

To help you get started, we’ve selected a few better-sqlite3 examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github bengotow / electron-RxDB / src / rx-database.js View on Github external
_openDatabase(ready) {
    if (this._db) {
      ready();
      return;
    }

    this._db = new Sqlite3(this._options.databasePath, {});

    this._db.on('close', (err) => {
      this._handleSetupError(err);
    })

    this._db.on('open', () => {
      // Note: These are properties of the connection, so they must be set regardless
      // of whether the database setup queries are run.

      // https://www.sqlite.org/wal.html
      // WAL provides more concurrency as readers do not block writers and a writer
      // does not block readers. Reading and writing can proceed concurrently.
      this._db.pragma(`journal_mode = WAL`);

      // https://www.sqlite.org/intern-v-extern-blob.html
      // A database page size of 8192 or 16384 gives the best performance for large BLOB I/O.
github eez-open / studio / packages / eez-studio-shared / db.ts View on Github external
export let getDbPath: () => string;
export let setDbPath: (dbPath: string) => void;

if (isRenderer()) {
    getDbPath = function() {
        return EEZStudio.electron.ipcRenderer.sendSync("getDbPath");
    };

    setDbPath = function(dbPath: string) {
        EEZStudio.electron.ipcRenderer.send("setDbPath", dbPath);
    };
} else {
    ({ getDbPath, setDbPath } = require("main/settings") as typeof MainSettingsModule);
}

export let db = new Database(getDbPath());
db.defaultSafeIntegers();

// // DB query is executed in Main process
// if (!isRenderer()) {
//     const { ipcMain } = require("electron");

//     ipcMain.on(
//         "dbQueryTask",
//         (event: Electron.Event, taskId: string, query: string, ...args: any[]) => {
//             try {
//                 const rows = db.prepare(query).all(...args);
//                 event.sender.send("dbQueryTask" + taskId, null, rows);
//             } catch (err) {
//                 event.sender.send("dbQueryTask" + taskId, err);
//             }
//         }
github Foundry376 / Mailspring / app / src / flux / stores / database-store.ts View on Github external
const database = await new Promise((resolve, reject) => {
      const db = new Sqlite3(dbPath, { readonly: true }) as Sqlite3.Database & EventEmitter;
      db.on('close', reject);
      db.on('open', () => {
        // https://www.sqlite.org/wal.html
        // WAL provides more concurrency as readers do not block writers and a writer
        // does not block readers. Reading and writing can proceed concurrently.
        db.pragma(`journal_mode = WAL`);

        // Note: These are properties of the connection, so they must be set regardless
        // of whether the database setup queries are run.

        // https://www.sqlite.org/intern-v-extern-blob.html
        // A database page size of 8192 or 16384 gives the best performance for large BLOB I/O.
        db.pragma(`main.page_size = 8192`);
        db.pragma(`main.cache_size = 20000`);
        db.pragma(`main.synchronous = NORMAL`);
github kmteras / timenaut / src / services / database.ts View on Github external
memory: false
            // verbose: log.debug
        };

        let databaseFileName = process.env.WEBPACK_DEV_SERVER_URL ? 'timenaut_dev.dat' : 'timenaut.dat';

        let databaseFile = "timenaut.db";

        if (test) {
            option.memory = true;
        } else {
            databaseFile = path.join(app.getPath('userData'), databaseFileName);
            log.info(`Opening database at ${databaseFile}`);
        }

        this.db = await new Sqlite(databaseFile, option);
        this.db.pragma('journal_mode = WAL');
        this.db.pragma('synchronous = 1');
        this.db.pragma('foreign_keys = ON');
    }
github nylas-mail-lives / nylas-mail / packages / client-app / src / database-helpers.es6 View on Github external
const database = await new Promise((resolve, reject) => {
      const db = new Sqlite3(dbPath, {});
      db.on('close', reject)
      db.on('open', () => {
        // https://www.sqlite.org/wal.html
        // WAL provides more concurrency as readers do not block writers and a writer
        // does not block readers. Reading and writing can proceed concurrently.
        db.pragma(`journal_mode = WAL`);

        // Note: These are properties of the connection, so they must be set regardless
        // of whether the database setup queries are run.

        // https://www.sqlite.org/intern-v-extern-blob.html
        // A database page size of 8192 or 16384 gives the best performance for large BLOB I/O.
        db.pragma(`main.page_size = 8192`);
        db.pragma(`main.cache_size = 20000`);
        db.pragma(`main.synchronous = NORMAL`);
github redxtech / devmod-v4 / src / commands / warn.js View on Github external
"Can't Warn Member",
          'You are not allowed' + ' to warn that member.'
        )
        return message.util.send({ embed })
      }

      await message.delete(1)

      const user = args.member.user
      const reason = args.reason
      const executor = message.member.user

      try {
        // Add warning into database & check numbers of previous warnings.
        // Ban user if configs says to do so & warns is over limit.
        const db = new Database(dbFile)
        await db
          .prepare(
            'INSERT INTO warnings (discord_id, reason, date, mod_id) VALUES (?, ?, CURRENT_TIMESTAMP, ?)'
          )
          .run(user.id, reason, executor.id)

        const row = db
          .prepare(
            'SELECT COUNT(*) AS count FROM warnings WHERE discord_id = ?'
          )
          .get(user.id)

        let color = colours.yellow
        if (row.count === 2) {
          color = colours.orange
        } else if (row.count >= 3) {
github sourcecred / sourcecred / src / graphql / demo.js View on Github external
console.error("  TYPENAME: GraphQL typename of the root object");
    console.error("  ID: GraphQL ID for an object to fetch");
    console.error("  TTL_SECONDS: Fetch updates if more than this old");
    console.error("Required environment variables:");
    const url = "https://github.com/settings/tokens";
    console.error(`  SOURCECRED_GITHUB_TOKEN: ${url}`);
    console.error("Optional environment variables:");
    console.error("  NODES_LIMIT: positive integer (default 100)");
    console.error("  CONNECTION_PAGE_SIZE: integer 1..100 (default) inclusive");
    console.error("  CONNECTION_LIMIT: positive integer (default 100)");
    process.exitCode = 1;
    return;
  }
  const [dbFilename, typename, id, ttlSecondsString] = args;

  const db = new Database(dbFilename);
  const mirror = new Mirror(db, schema());
  console.warn("Registering...");
  mirror.registerObject({typename, id});
  console.warn("Updating...");
  await mirror.update(
    async (payload) => {
      console.warn("[Posting query...]");
      console.warn(
        JSON.stringify({
          type: "REQUEST",
          graphql: Queries.stringify.body(payload.body, Queries.inlineLayout()),
        })
      );
      const result = await postQuery(payload, token);
      console.warn("[Processing result...]");
      console.warn(JSON.stringify({type: "RESPONSE", result}));
github redxtech / devmod-v4 / src / commands / warnList.js View on Github external
async exec (message, args) {
    try {
      if (!args.member) {
        await message.react('❌')
        const embed = errorMessage(
          'Member Not Found',
          'No member found with' + ' that name.'
        )
        return message.util.send({ embed })
      }

      await message.delete(1)

      try {
        const user = args.member.user
        const db = new Database(dbFile)

        const embed = {
          title: `Warnings for ${user.tag}`,
          color: colours.blue,
          fields: [],
          author: {
            name: message.member.user.username,
            icon_url: message.member.user.avatarURL
          }
        }
        let count = 0
        let warnings = []

        const row = db
          .prepare('SELECT * FROM warnings WHERE discord_id = ?')
          .get(user.id)
github automerge / hypermerge / src / SqlStore.ts View on Github external
constructor(storage: string) {
    this.db = sqlite3(storage, { memory: storage === IN_MEMORY_DB })
    this.migrate()
  }
  migrate() {
github eez-open / studio / packages / eez-studio-shared / db.ts View on Github external
query,
                args
            });

            if (err) {
                throw err;
            } else {
                for (const row of rows) {
                    for (const key in row) {
                        if (row.hasOwnProperty(key)) {
                            const value = row[key];
                            if (value && typeof value === "object") {
                                const low = row[key].low;
                                const high = row[key].high;
                                if (low !== undefined && high !== undefined) {
                                    row[key] = Database.Integer.fromBits(low, high);
                                }
                            }
                        }
                    }
                }

                return rows;
            }
        }
    };

better-sqlite3

The fastest and simplest library for SQLite3 in Node.js.

MIT
Latest version published 14 days ago

Package Health Score

85 / 100
Full package analysis

Popular better-sqlite3 functions