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

@andrewitsover/midnight

v2.0.0

Published

An ORM for SQLite

Readme

🌒 Midnight

⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠸⠁⠸⢳⡄⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢠⠃⠀⠀⢸⠸⠀⡠⣄⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⡠⠃⠀⠀⢠⣞⣀⡿⠀⠀⣧⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣠⡖⠁⠀⠀⠀⢸⠈⢈⡇⠀⢀⡏⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⡴⠩⢠⡴⠀⠀⠀⠀⠀⠈⡶⠉⠀⠀⡸⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⢀⠎⢠⣇⠏⠀⠀⠀⠀⠀⠀⠀⠁⠀⢀⠄⡇⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⢠⠏⠀⢸⣿⣴⠀⠀⠀⠀⠀⠀⣆⣀⢾⢟⠴⡇⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⢀⣿⠀⠠⣄⠸⢹⣦⠀⠀⡄⠀⠀⢋⡟⠀⠀⠁⣇⠀⠀⠀⠀⠀
⠀⠀⠀⠀⢀⡾⠁⢠⠀⣿⠃⠘⢹⣦⢠⣼⠀⠀⠉⠀⠀⠀⠀⢸⡀⠀⠀⠀⠀
⠀⠀⢀⣴⠫⠤⣶⣿⢀⡏⠀⠀⠘⢸⡟⠋⠀⠀⠀⠀⠀⠀⠀⠀⢳⠀⠀⠀⠀
⠐⠿⢿⣿⣤⣴⣿⣣⢾⡄⠀⠀⠀⠀⠳⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢣⠀⠀⠀
⠀⠀⠀⣨⣟⡍⠉⠚⠹⣇⡄⠀⠀⠀⠀⠀⠀⠀⠀⠈⢦⠀⠀⢀⡀⣾⡇⠀⠀
⠀⠀⢠⠟⣹⣧⠃⠀⠀⢿⢻⡀⢄⠀⠀⠀⠀⠐⣦⡀⣸⣆⠀⣾⣧⣯⢻⠀⠀
⠀⠀⠘⣰⣿⣿⡄⡆⠀⠀⠀⠳⣼⢦⡘⣄⠀⠀⡟⡷⠃⠘⢶⣿⡎⠻⣆⠀⠀
⠀⠀⠀⡟⡿⢿⡿⠀⠀⠀⠀⠀⠙⠀⠻⢯⢷⣼⠁⠁⠀⠀⠀⠙⢿⡄⡈⢆⠀
⠀⠀⠀⠀⡇⣿⡅⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠙⠦⠀⠀⠀⠀⠀⠀⡇⢹⢿⡀
⠀⠀⠀⠀⠁⠛⠓⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠼⠇⠁

The time after the 11th hour. Midnight is a NodeJS ORM for SQLite with full TypeScript support without needing to generate any code. Even complex SQL queries can be written inside of JavaScript.

Tables are written in JavaScript like this:

class Forests extends Table {
  name = this.Text;
  address = this.Text;

  displayName = this.Concat(this.name, ' - ', this.address);
}

class Trees extends Table {
  name;
  planted = this.Index(this.Date);
  forestId = this.Cascade(Forests);
  alive = this.True;
}

There are two levels of API. The first is a table-level syntax for basic queries.

const tree = db.trees.get({ 
  id: 1,
  alive: true
});

The second type of syntax is much like SQL and builds on many of the new features that JavaScript has added to its language in recent times.

const trees = db.query(c => {
  const {
    forests: f,
    trees: t
  } = c;
  return {
    select: {
      ...t,
      forest: f.name
    },
    join: [t.forestId, f.id],
    where: {
      [t.id]: [1, 2, 3]
    }
  }
});

This syntax allows you to perform queries that usually aren't possible in ORMs.

Getting started

Prerequists

Make sure you have installed Node.js version 22.13.1 or higher.

Creating a project

Create a directory for your project and initialise it with npm:

mkdir forests
cd forests
npm init -y
npm install @andrewitsover/midnight
touch main.js

In the package.json, change the following lines:

{
  "main": "main.js",
  "type": "module"
}

Paste the code below into the main.js file.

This example will create a clouds table in a database named forest.db and then insert and read some rows.

import { SQLiteDatabase, Table } from '@andrewitsover/midnight';

const database = new SQLiteDatabase('forest.db');

class Clouds extends Table {
  name;
};

const db = database.getClient({ Clouds });
const sql = db.diff();
db.migrate(sql);

db.clouds.insert({ name: 'Nimbus' });
const clouds = db.clouds.many();
console.log(clouds);

To run it, you can use node main.js from the project root directory.

See the sample project for a more complete setup.

It is a good idea to set any SQLite database that you have created to pragma journal_mode=WAL. You can do this yourself after the database has been created. See here for more details.

The API

Every table has get, many, first, query, update, upsert, insert, insertMany, and delete methods available to it.

Insert

insert inserts a row into the database. For batch inserts you can use insertMany, which takes an array of objects.

const id = db.moons.insert({
  name: 'Europa',
  orbit: 'Retrograde'
});

Update

update takes an object with an optional where property, and a set property. It returns a number representing the number of rows that were affected by the query. For example:

db.moons.update({
  where: { id: 100 }, 
  set: { orbit: 'Prograde' }
});

If you want to update columns based on their existing value, you can pass a function into the set properties like this:

db.moons.update({
  set: {
    orbit: (c, f) => f.concat(c.orbit, ' - Circular')
  },
  where: {
    id: 3
  }
});

All of the built-in SQLite functions are available, in addition to the mathematical operators plus, minus, divide, and multiply.

Upsert

upsert will update the row if the target's uniqueness contraint is violated by the insert. If target or set are not provided, the upsert will do nothing when there is a conflict. upsert returns the primary key of the inserted or updated row.

const id = db.forests.upsert({
  values: {
    id: 1,
    name: 'Daisy Hill Forest',
    address: 'Brisbane'
  },
  target: 'id',
  set: {
    address: 'Brisbane'
  }
});

Get and Many

get and many take two optional arguments. The first argument represents the where clause. For example:

const trees = db.trees.many({ 
  forestId: 9,
  alive: true
});

If an array is passed in, an in clause is used, such as:

const trees = db.trees.many({
  forestId: [1, 2, 3]
});

If null is passed in as the value, the SQL will use is null.

The second argument to get or many selects which columns to return. It can be one of the following:

  1. a string representing a column to select. In this case, the result returned is a single value or array of single values, depending on whether get or many is used.
const planted = db.trees.get({ id: 3 }, 'planted');
  1. an array of strings, representing the columns to select.
const tree = db.trees.get({ id: 3 }, ['id', 'born']);

Query and First

You can use the query or first syntax for more complex queries. query returns an array in the same way as many, and first returns an object or undefined if nothing is found. The additional keywords are:

select: an array of strings representing the columns to select.

return: a string representing the column to select.

omit: a string or array of strings representing the columns to omit. All of the other columns will be selected.

const rangers = db.rangers.query({
  omit: 'password',
  where: {
    id: [1, 2, 3]
  }
});

orderBy: a string or an array representing the column or columns to order the result by. This can also be a function that utilises the built-in SQLite functions.

const trees = db.trees.query({
  where: {
    category: 'Evergreen'
  },
  orderBy: (c, f) => f.lower(c.name)
});

desc: set to true when using orderBy if you want the results in descending order.

limit and offset: corresponding to the SQL keywords with the same name.

distinct: adds the distinct keywords to the start of the select clause.

For example:

const trees = db.trees.query({
  where: { 
    alive: true 
  }, 
  select: ['name', 'category'],
  orderBy: 'id',
  limit: 10
});

While the default interpretation of the query parameters is =, you can pass in a function to use not, gt, gte, lt, lte, like, match or glob.

For example:

const excluded = [1, 2, 3];
const moons = db.moons.many({ id: c => c.not(excluded) });
const count = db.moons.count({
  where: {
    id: c => c.gt(10)
  }
});

Complex filtering

If you need to perform complex logic in the where clause, you can use the and or or properties. For example:

const wolves = db.animals.query({
  where: {
    or: [
      { name: c => c.like('Gray%') },
      { id: c => c.lt(10) },
      {
        and: [
          { tagged: c => c.gt(time) },
          { name: c => c.like('Red%') }
        ]
      }
    ]
  }
});

You should only include one condition per object.

Aggregate functions

There are multiple functions that aggregate the results into a single value. These include count, avg, min, max, and sum. Despite its name, sum uses the SQLite function total to determine the results.

All of these functions take three arguments:

where: the where clause

column: the column to aggregate. This is optional for count.

distinct: the same as column but it aggregates by distinct values.

const count = db.trees.count({
  where: {
    native: true
  }
});

There is also an exists function that takes one argument representing the where clause.

const exists = db.moons.exists({ 
  name: 'Cumulus'
});

GroupBy

You can write group by statements like this:

const trees = db.fighters
  .groupBy('forestId')
  .avg({
    column: {
      height: 'heightCm'
    },
    where: {
      avg: c => c.gt(170)
    },
    limit: 3
  });

An aggregate function should come after the groupBy method. distinct can be used instead of column to aggregate by distinct values. distinct or column needs to be an object with a single property representing the alias for the aggregrate function, and the column to aggregate by.

In addition to aggregate functions such as avg or count, there is also an array function that simply groups the rows into an array. The select option takes an object with a single property representing the name of the resulting array, and the column or columns to select.

const trees = db.trees
  .groupBy('forestId')
  .array({
    select: {
      planted: 'planted'
    },
    limit: 3
  });

Delete

delete takes one argument representing the where clause and returns the number of rows affected by the query.

const changes = db.moons.delete({ id: 100 });

Transactions

Transactions allow all operations to succeed or fail together so that the database is not left in an incorrect state. Make sure you do not await on any functions while performing a transaction as this will allow other operations outside of the transaction to run and therefore be included in the transaction unintentionally. In other words, there should be no await statement between the begin and commit functions.

try {
  db.begin();
  const animalId = db.animals.insert({
    name: 'Gray Wolf',
    speed: 73
  });
  const personId = db.people.get({ name: c => c.like('Andrew%') }, 'id');
  db.sightings.insert({
    personId,
    animalId
  });
  db.commit();
}
catch (e) {
  db.rollback();
  throw e;
}

Migrations

The client returned from getClient has three methods that can be used to create a migration system. This includes:

getSchema: return the tables loaded into the getClient method in a format suitable for saving as JSON.

diff: takes a saved schema and diffs it with the currently loaded schema to create a migration.

migrate: takes a SQL string representing the migration. This method defers the foreign keys and wraps the SQL in a transaction.

See the sample project for an example of how to use these functions to create a migration system.

Creating tables

In addition to the built-in SQLite types of Integer, Real, Text, and Blob, Midnight adds a few extra types. Boolean is stored in the database as a 1 or a 0, Date is stored as an ISO8601 string, and Json is a JSONB blob.

To create a table, you simply extend either Table, FTSTable, or BaseTable. Table automatically defines an integer primary key called id. ````FTSTable``` is used for defining fts5 tables. Columns start with a lowercase letter.

class Moons extends BaseTable {
  id = this.IntPrimary;
  name = this.Unique(this.Text);
  planetId = this.Cascade(Planets);
  discovered = this.Now;
}

To specify the primary key, you use one of the modified types that has Primary at the end.

Column types can be wrapped in many different methods:

Null: assert that the column can contain nulls.

Index: add an index to the column.

Unique: add a unique index to the column.

Default: define a default value. You can often simply use a literal instead.

Check constraints

Constraints can be represented as either an array of valid values, or one or more comparison functions.

class Trees extends Table {
  height = this.Int;
  leaves = this.Check(this.Int, this.Gte(0));
  alive = true;
}

Constraints can also be defined in the Attributes function and span across multiple columns.

class Rangers extends Table {
  admin = this.False;
  staffLimit = this.Default(3);
  createdAt = this.Now;

  Attributes = () => {
    this.Check({
      or: [
        { [this.admin]: true },
        { [this.staffLimit]: this.Gt(0) }
      ]
    });
  }
}

Foreign keys

Foreign keys do not need to specify a column type, as the type will be determined by the table that is referenced.

By default, an index is created for the foreign key, and the column is set to not null. Also, the related column in the referenced table is assumed to be the primary key of that table.

class Sightings extends Table {
  personId = this.Cascade(People);
  animalId = this.Cascade(Animals);
  date = this.Now;
}

class Animals extends Table {
  name = this.Text;
  ownerId = this.References(Sightings, {
    column: 'personId',
    notNull: false,
    index: false,
    onDelete: 'set null',
    onUpdate: 'cascade'
  });
}

Cascade is simply a shorthand version of References that has the onDelete property set to cascade.

Indexes

For indexes that span multiple columns or are based on expressions, you can define an Attributes function on the class.

class Trees extends Table {
  id = this.IntPrimary;
  name;
  category;
  planted = this.Now;

  Attributes = () => {
    const computed = this.Cast(this.StrfTime('%Y', this.planted), 'integer');
    this.Index(computed);
    this.Unique(this.name, this.category);
  }
}

Partial indexes

Partial indexes can be defined on a class field.

class Animals extends Table {
  id = this.IntPrimary;
  name = this.Index(this.Text, name => {
    return {
      [name]: this.Like('%Wolf')
    }
  });
}

Indexes can also be defined inside the Attributes function if they span across multiple columns.

class Trees extends Table {
  id = this.IntPrimary;
  name;
  forestId = this.References(Forests);
  alive = this.True;

  Attributes = () => {
    this.Index(this.name, {
      [this.alive]: true
    });
  }
}

The above example applies a partial index on name where alive is true.

Computed fields

Computed fields use the built-in SQLite functions and therefore can be used in any part of a query.

class Trees extends Table {
  id = this.IntPrimary;
  name = this.Text;
  category = this.Text;

  displayName = this.Concat(this.name, ' (', this.category, ')');
}

SQL queries in JavaScript

Midnight alllows you to create complex SQL queries without leaving JavaScript.

The following query uses a window function to rank trees by their height.

const trees = db.query(c => {
  const { 
    id,
    name,
    height
  } = c.trees;
  return {
    select: {
      id,
      name,
      rank: c.rowNumber({
        orderBy: height,
        desc: true
      })
    },
    where: {
      [height]: c.gt(1)
    }
  }
});

The built-in SQLite functions are just JavaScript functions. This query gets the tree planted the furthest time away from the supplied date.

const tree = db.first(c => {
  const { id, name, planted } = c.trees;
  const now = new Date();
  const max = c.max(c.timeDiff(planted, now));
  return {
    select: {
      id,
      name,
      max
    },
    orderBy: max,
    desc: true
  }
});

The c parameter of the query represents the context of the database, including both tables and functions.

The group function represents json_group_array or json_group_object depending on the number of parameters supplied to the function.

const moons = db.subquery(c => {
  const { id, name, planetId } = c.moons;
  return {
    select: {
      planetId,
      moons: c.group({
        id,
        name
      })
    },
    groupBy: planetId,
    having: {
      [c.count()]: c.gt(1)
    }
  }
});

If you want to create a subquery for use in many different queries, you can use the subquery method.

The query below creates a list of people that have sighted a particular animalId.

const sighted = db.subquery(c => {
  const { personId, animalId } = c.sightings;
  const p = c.people;
  return {
    select: {
      animalId,
      sightedBy: c.group(p)
    },
    join: [personId, p.id],
    groupBy: animalId
  }
});

You can now use this subquery in other queries.

const animals = db.query(c => {
  const { animalId, sightedBy } = c.use(sighted);
  const a = c.animals;
  return {
    select: {
      ...a,
      sightedBy
    },
    where: {
      [c.length(a.name)]: c.gt(10)
    },
    join: [a.id, animalId, 'left']
  }
});

Subqueries can also be used instead of tables in the standard API with the use method.

const sightings = db.use(sighted).exists({ animalId: 1 });

The object returned from the query and subquery methods can include the following:

select, optional, distinct, join, where, groupBy, having, orderBy, desc, limit, and offset.

optional: the same as select but provides hints to TypeScript that these columns may be null. This is useful for columns that come from a left join.

const planets = db.query(c => {
  const { planets: p, moons: m } = c;
  return {
    select: p,
    optional: {
      moon: m.name
    },
    join: [p.id, m.planetId, 'left']
  }
});

In the above example, moon will be of type string or null even though it is normally not null.

distinct: used instead of select when you want the results to be distinct.

join: a tuple or array of tuples representing the keys to join on.

Full-text search

The below example creates a fts5 table with three columns, one of which is only used for referencing other tables and so is removed from indexing.

class Emails extends FTSTable {
  uuid = this.Unindexed;
  to;
  body;
}

As all columns in a fts5 table are text, there is no need to specify the column type.

Specific tokenizers such as Unicode61, Ascii, and Trigram can be imported and passed into the Tokenizer field of the table class.

To define a fts5 table based on another table, you can do this:

export class Forests extends Table {
  name;
  otherName;
}

const forest = new Forests();

export class ForestSearches extends ExternalFTSTable {
  name = forest.name;
  otherName = forest.otherName;
}

You can now query the table like this:

const matches = db.forestSearches.match({
  startsWith: 'Mount'
});

If you want to search a specific column, you can do:

const matches = db.forstSearches.match({
  where: {
    otherName: {
      near: ['Mount', 'Park', 2]
    }
  },
  limit: 3
});

The above query finds any forest with an otherName that contains the word "Mount" followed by a maximum of 2 tokens, and then the word "Park". As in, "Mount" is near "Park".

The match API allows you to search an fts5 table in a number of different ways.

phrase: match an exact phrase

startsWith: the specified column or any of the columns starts with a particular string.

prefix: any token starts with a particular string.

near: takes an array of two or more strings with the last value being a number that specifies the maximum number of tokens allowed between the matching strings.

and, or, and not: takes an array of strings.

You can also query fts5 tables with the basic API like this:

const results = db.forestSearches.query({
  where: { 
    forestSearches: 'Mount'
  },
  highlight: {
    column: 'name',
    tags: ['<b>', '</b>']
  },
  bm25: {
    name: 1,
    otherName: 10
  },
  limit: 5
});

or the SQL-like API like this:

const results = db.query(c => {
  const { 
    forests: f,
    forestSearches: s
  } = c;
  return {
    select: {
      name: f.name
    },
    where: {
      [s.forestSearches]: 'Mount'
    },
    bm25: {
      [s.name]: 1,
      [s.otherName]: 10
    },
    join: [f.id, s.rowid],
    limit: 5
  }
});

You can also use the rank keyword.