npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

sqlite-model

v1.0.0

Published

Extend this class to easily create your data models based on sqlite3

Downloads

13

Readme

sqlite-model

Build Status

Extend this class to easily create your data models based on sqlite3

Install

npm install sqlite-model

Usage example

This library provides a base class with the basics method to access a SQLite database and promisified statement.

The easiest way to use the class, is extending it when implementing your model class.

To show it, we are going to implement a small model to get and set jsonified values, which will use the following data definition and SQL queries:

-- table definition
CREATE TABLE IF NOT EXISTS example (
  key text NOT NULL PRIMARY KEY,
  value text NOT NULL,
);

-- query to set data
INSERT INTO example VALUES(?, ?);

-- query to get data
SELECT value FROM example WHERE key = ?;

-- if the value already exists, update it
UPDATE example SET value = ? WHERE key = ?;

The implementation for this model would be the following one:

import { SqliteModel } from '../src';

type Query = 'set' | 'get' | 'update';

export class Example extends SqliteModel<Query> {
  // we usually don't want to expose all the model options, so our constructor will have a different interface
  constructor(dbPath: string) {
    super({
      // `dbPath` is exposed for testing purposes
      dbPath,
      // This is the list of SQL statements that will be available in `this.stmt` to be used by the methods of your model
      queries: {
        set: 'INSERT INTO example VALUES(?, ?);',
        get: 'SELECT value FROM example WHERE key = ?;',
        update: 'UPDATE example SET value = ? WHERE key = ?;',
      },
      // This SQL will be executed only when the database is created the first time
      createDbSql: [`
        CREATE TABLE IF NOT EXISTS example (
          key text NOT NULL PRIMARY KEY,
          value text NOT NULL
        );
      `],
    });
  }

  /**
   * Set or update a `value` to a `key`
   *
   * @return Promise resolved when the operation is finished
   */
  public async set<T>(key: string, data: T): Promise<void> {
    // wait for the database to be ready
    // if your application makes sure that the model is not used until is ready, this line wouldn't be required, but it doesn't hurt to have it
    await this.isReady();

    let json: string;

    try {
      json = JSON.stringify(data);
    } catch (error) {
      throw new Error(`An error happened while trying to stringify ${key}`);
    }

    // if `set` fails it means that the primary key already exists, so we just try to update it
    try {
      await this.stmt.set.run(key, json);
    } catch (error) {
      await this.stmt.update.run(json, key);
    }
  }

  /**
   * Get the value associated to the specified `key`
   *
   * @return Promise resolved to the stored value or `undefined` if not found
   */
  public async get<T>(key: string): Promise<T> {
    // wait for the database to be ready
    // if your application makes sure that the model is not used until is ready, this line wouldn't be required, but it doesn't hurt to have it
    await this.isReady();

    try {
      const { row } = await this.stmt.get.get<{ value: string }>(key);
      const res = row && JSON.parse(row.value) as T;
      return res;
    } catch (error) {
      throw new Error(`An error happened while trying to get ${key} [${error}]`);
    }
  }
}

And that's all.

As you can see, with this class as a base, you only need to implement the logic of your model without worrying about database operations, preparing statements or dirty old-styled callbacks returned by the statement functions.