{"id":14155170,"url":"https://github.com/kriasoft/node-sqlite","last_synced_at":"2025-05-14T15:09:31.095Z","repository":{"id":3479637,"uuid":"48945089","full_name":"kriasoft/node-sqlite","owner":"kriasoft","description":"SQLite client wrapper around sqlite3 for Node.js applications with SQL-based migrations API written in Typescript","archived":false,"fork":false,"pushed_at":"2025-04-28T23:03:33.000Z","size":901,"stargazers_count":920,"open_issues_count":7,"forks_count":95,"subscribers_count":15,"default_branch":"master","last_synced_at":"2025-05-07T18:52:58.279Z","etag":null,"topics":["async","database","db","es7-async","migrate","migration","migrations","nodejs","sql","sqlite","typescript"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/kriasoft.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2016-01-03T12:37:42.000Z","updated_at":"2025-04-16T15:22:39.000Z","dependencies_parsed_at":"2025-05-07T18:38:54.325Z","dependency_job_id":"752161ae-27d0-407c-ae6e-d76e4b9116ce","html_url":"https://github.com/kriasoft/node-sqlite","commit_stats":{"total_commits":214,"total_committers":44,"mean_commits":4.863636363636363,"dds":0.4672897196261683,"last_synced_commit":"f86c213863353d3701d71d8993975a04138dbe99"},"previous_names":[],"tags_count":47,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kriasoft%2Fnode-sqlite","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kriasoft%2Fnode-sqlite/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kriasoft%2Fnode-sqlite/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kriasoft%2Fnode-sqlite/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/kriasoft","download_url":"https://codeload.github.com/kriasoft/node-sqlite/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254170046,"owners_count":22026219,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["async","database","db","es7-async","migrate","migration","migrations","nodejs","sql","sqlite","typescript"],"created_at":"2024-08-17T08:02:19.949Z","updated_at":"2025-05-14T15:09:31.071Z","avatar_url":"https://github.com/kriasoft.png","language":"TypeScript","readme":"# SQLite Client for Node.js Apps\n\n[![NPM version](https://img.shields.io/npm/v/sqlite.svg?style=flat-square)](https://www.npmjs.com/package/sqlite)\n[![CircleCI](https://circleci.com/gh/kriasoft/node-sqlite.svg?style=svg)](https://circleci.com/gh/kriasoft/node-sqlite) \n![built with typescript](https://camo.githubusercontent.com/92e9f7b1209bab9e3e9cd8cdf62f072a624da461/68747470733a2f2f666c61742e62616467656e2e6e65742f62616467652f4275696c74253230576974682f547970655363726970742f626c7565) \n[![JavaScript Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg)](https://standardjs.com)\n\n\u003e A wrapper library written in Typescript with **ZERO** dependencies that adds ES6 promises \n\u003e and SQL-based migrations API to [sqlite3](https://github.com/mapbox/node-sqlite3/) ([docs](https://github.com/mapbox/node-sqlite3/wiki)).\n\n**note** v4 of `sqlite` has breaking changes compared to v3! Please see `CHANGELOG.md` for more details.\n\n\u003c!-- TOC --\u003e\n\n- [Installation](#installation)\n  - [Install `sqlite3`](#install-sqlite3)\n  - [Install `sqlite`](#install-sqlite)\n- [Usage](#usage)\n  - [Opening the database](#opening-the-database)\n    - [Without caching](#without-caching)\n    - [With caching](#with-caching)\n    - [Enable verbose / debug mode](#enable-verbose--debug-mode)\n    - [Tracing SQL errors](#tracing-sql-errors)\n    - [With a custom driver](#with-a-custom-driver)\n    - [Opening multiple databases](#opening-multiple-databases)\n    - [`open` config params](#open-config-params)\n  - [Examples](#examples)\n    - [Creating a table and inserting data](#creating-a-table-and-inserting-data)\n    - [Getting a single row](#getting-a-single-row)\n    - [Getting many rows](#getting-many-rows)\n    - [Inserting rows](#inserting-rows)\n    - [Updating rows](#updating-rows)\n    - [Prepared statement](#prepared-statement)\n    - [`each()`](#each)\n    - [Get the driver instance](#get-the-driver-instance)\n    - [Closing the database](#closing-the-database)\n  - [ES6 tagged template strings](#es6-tagged-template-strings)\n  - [Migrations](#migrations)\n- [Typescript tricks](#typescript-tricks)\n  - [Import interfaces from sqlite](#import-interfaces-from-sqlite)\n  - [Specify typings for a specific database driver](#specify-typings-for-a-specific-database-driver)\n  - [Use generics to get better typings on your rows](#use-generics-to-get-better-typings-on-your-rows)\n    - [Get example](#get-example)\n    - [All example](#all-example)\n- [API Documentation](#api-documentation)\n- [Management Tools](#management-tools)\n- [Alternative SQLite libraries](#alternative-sqlite-libraries)\n- [References](#references)\n- [License](#license)\n\n\u003c!-- TOC END --\u003e\n\n## Installation\n\n### Install `sqlite3`\n\nMost people who use this library will use [sqlite3](https://github.com/mapbox/node-sqlite3/) \nas the database driver. \n\nAny library that conforms to the `sqlite3` ([API](https://github.com/mapbox/node-sqlite3/wiki/API)) \nshould also work.\n\n`$ npm install sqlite3 --save`\n\n### Install `sqlite`\n\n```sh\n# v4 of sqlite is targeted for nodejs 10 and on.\n$ npm install sqlite --save\n\n# If you need a legacy version for an older version of nodejs\n# install v3 instead, and look at the v3 branch readme for usage details\n$ npm install sqlite@3 --save\n```\n\n## Usage\n\nThis module has the same API as the original `sqlite3` library ([docs](https://github.com/mapbox/node-sqlite3/wiki/API)),\nexcept that all its API methods return ES6 Promises and do not accept callback arguments (with the exception of `each()`).\n\n### Opening the database\n\n#### Without caching\n\n```typescript\nimport sqlite3 from 'sqlite3'\nimport { open } from 'sqlite'\n\n// this is a top-level await \n(async () =\u003e {\n    // open the database\n    const db = await open({\n      filename: '/tmp/database.db',\n      driver: sqlite3.Database\n    })\n})()\n```\nor\n\n```typescript\nimport sqlite3 from 'sqlite3'\nimport { open } from 'sqlite'\n\nopen({\n  filename: '/tmp/database.db',\n  driver: sqlite3.Database\n}).then((db) =\u003e {\n  // do your thing\n})\n```\n\nor\n\n```typescript\nimport sqlite3 from 'sqlite3'\nimport { open } from 'sqlite'\n\n// you would have to import / invoke this in another file\nexport async function openDb () {\n  return open({\n    filename: '/tmp/database.db',\n    driver: sqlite3.Database\n  })\n}\n```\n\n#### With caching\n\nIf you want to enable the [database object cache](https://github.com/mapbox/node-sqlite3/wiki/Caching)\n\n```typescript\nimport sqlite3 from 'sqlite3'\nimport { open } from 'sqlite'\n\n(async () =\u003e {\n    const db = await open({\n      filename: '/tmp/database.db',\n      driver: sqlite3.cached.Database\n    })\n})()\n```\n\n#### Enable verbose / debug mode\n\n```typescript\nimport sqlite3 from 'sqlite3'\n\nsqlite3.verbose()\n```\n\n#### Tracing SQL errors\n\nFor more info, see this [doc](https://github.com/mapbox/node-sqlite3/wiki/Debugging#databaseontrace-callback).\n\n```typescript\ndb.on('trace', (data) =\u003e {\n  \n})\n```\n\n#### With a custom driver\n\nYou can use an alternative library to `sqlite3` as long as it conforms to the `sqlite3` [API](https://github.com/mapbox/node-sqlite3/wiki/API).\n\nFor example, using `sqlite3-offline-next`:\n\n```typescript\nimport sqlite3Offline from 'sqlite3-offline-next'\nimport { open } from 'sqlite'\n\n(async () =\u003e {\n    const db = await open({\n      filename: '/tmp/database.db',\n      driver: sqlite3Offline.Database\n    })\n})()\n```\n\n#### Opening multiple databases\n\n```typescript\nimport sqlite3 from 'sqlite3'\nimport { open } from 'sqlite'\n\n(async () =\u003e {\n  const [db1, db2] = await Promise.all([\n    open({\n      filename: '/tmp/database.db',\n      driver: sqlite3.Database\n    }),\n    open({\n      filename: '/tmp/database2.db',\n      driver: sqlite3.Database\n    }),\n  ])\n\n  await db1.migrate({\n    migrationsPath: '...'\n  })\n\n  await db2.migrate({\n    migrationsPath: '...'\n  })\n})()\n```\n\n#### `open` config params\n\n```typescript\n\n// db is an instance of `sqlite#Database`\n// which is a wrapper around `sqlite3#Database`\nconst db = await open({\n  /**\n   * Valid values are filenames, \":memory:\" for an anonymous in-memory\n   * database and an empty string for an anonymous disk-based database.\n   * Anonymous databases are not persisted and when closing the database\n   * handle, their contents are lost.\n   */\n  filename: string\n\n  /**\n   * One or more of sqlite3.OPEN_READONLY, sqlite3.OPEN_READWRITE and\n   * sqlite3.OPEN_CREATE. The default value is OPEN_READWRITE | OPEN_CREATE.\n   */\n  mode?: number\n\n  /**\n   * The database driver. Most will install `sqlite3` and use the `Database` class from it.\n   * As long as the library you are using conforms to the `sqlite3` API, you can use it as\n   * the driver.\n   *\n   * @example\n   *\n   * ```\n   * import sqlite from 'sqlite3'\n   *\n   * const driver = sqlite.Database\n   * ```\n   */\n  driver: any\n})\n```\n\n### Examples\n\n- See the `src/**/__tests__` directory for more example usages\n- See the `docs/` directory for full documentation.\n- Also visit the `sqlite3` library [API docs](https://github.com/mapbox/node-sqlite3/wiki/API)\n\n#### Creating a table and inserting data\n\n```typescript\nawait db.exec('CREATE TABLE tbl (col TEXT)')\nawait db.exec('INSERT INTO tbl VALUES (\"test\")')\n```\n\n#### Getting a single row\n\n```typescript\nconst result = await db.get('SELECT col FROM tbl WHERE col = ?', 'test')\n\n// { col: 'test' }\n```\n\n```typescript\nconst result = await db.get('SELECT col FROM tbl WHERE col = ?', ['test'])\n\n// { col: 'test' }\n```\n\n```typescript\nconst result = await db.get('SELECT col FROM tbl WHERE col = :test', {\n  ':test': 'test'\n})\n\n// { col: 'test' }\n```\n\n#### Getting many rows\n\n```typescript\nconst result = await db.all('SELECT col FROM tbl')\n\n// [{ col: 'test' }]\n```\n\n#### Inserting rows\n\n```typescript\nconst result = await db.run(\n  'INSERT INTO tbl (col) VALUES (?)',\n  'foo'\n)\n\n/*\n{\n  // row ID of the inserted row\n  lastID: 1,\n  // instance of `sqlite#Statement`\n  // which is a wrapper around `sqlite3#Statement`\n  stmt: \u003cStatement\u003e\n}\n*/\n```\n\n```typescript\nconst result = await db.run('INSERT INTO tbl(col) VALUES (:col)', {\n  ':col': 'something'\n})\n```\n\n#### Updating rows\n\n```typescript\nconst result = await db.run(\n  'UPDATE tbl SET col = ? WHERE col = ?',\n  'foo',\n  'test'\n)\n\n/*\n{\n  // number of rows changed\n  changes: 1,\n  // instance of `sqlite#Statement`\n  // which is a wrapper around `sqlite3#Statement`\n  stmt: \u003cStatement\u003e\n}\n*/\n```\n\n#### Prepared statement\n\n```typescript\n// stmt is an instance of `sqlite#Statement`\n// which is a wrapper around `sqlite3#Statement`\nconst stmt = await db.prepare('SELECT col FROM tbl WHERE 1 = ? AND 5 = ?5')\nawait stmt.bind({ 1: 1, 5: 5 })\nlet result = await stmt.get()\n// { col: 'some text' }\n```\n\n```typescript\nconst stmt = await db.prepare(\n  'SELECT col FROM tbl WHERE 13 = @thirteen ORDER BY col DESC'\n)\n\nconst result = await stmt.all({ '@thirteen': 13 })\n```\n\n#### `each()`\n\n`each()` is a bit different compared to the other operations due to its underlying [implementation](https://github.com/TryGhost/node-sqlite3/wiki/API#databaseeachsql-param--callback-complete).\n\nThe function signature looks like this:\n\n`async each (sql, [...params], callback)`\n\n- `callback(err, row)` is triggered when the database has a row to return\n- The promise resolves when all rows have returned with the number of rows returned.\n\n```typescript\ntry {\n  // You need to wrap this in a try / catch for SQL parse / connection errors\n  const rowsCount = await db.each(\n    'SELECT col FROM tbl WHERE ROWID = ?',\n    [2],\n    (err, row) =\u003e {\n      if (err) {\n        // This would be if there is an error specific to the row result\n        throw err\n      }\n\n      // row = { col: 'other thing' }\n    }\n  )\n} catch (e) {\n  throw e\n}\n\n// rowsCount = 1\n```\n\n#### Get the driver instance\n\nUseful if you need to call methods that are not supported yet.\n\n```typescript\nconst rawDb = db.getDatabaseInstance()\nconst rawStatement = stmt.getStatementInstance()\n```\n\n#### Closing the database\n\n```typescript\nawait db.close()\n```\n\n### ES6 tagged template strings\n\nThis module is compatible with [sql-template-strings](https://www.npmjs.com/package/sql-template-strings).\n\n```js\nimport SQL from 'sql-template-strings'\n\nconst book = 'harry potter';\nconst author = 'J. K. Rowling';\n\nconst data = await db.all(SQL`SELECT author FROM books WHERE name = ${book} AND author = ${author}`);\n```\n\n### Migrations\n\nThis module comes with a lightweight migrations API that works with [SQL-based migration files](https://github.com/kriasoft/node-sqlite/tree/master/migrations)\n\nWith default configuration, you can create a `migrations/` directory in your project with SQL files,\nand call the `migrate()` method to run the SQL in the directory against the database.\n\nSee this project's `migrations/` folder for examples.\n\n```typescript\nawait db.migrate({    \n    /**\n    * If true, will force the migration API to rollback and re-apply the latest migration over\n    * again each time when Node.js app launches.\n    */\n    force?: boolean\n    /**\n    * Migrations table name. Default is 'migrations'\n    */\n    table?: string\n    /**\n    * Path to the migrations folder. Default is `path.join(process.cwd(), 'migrations')`\n    */\n    migrationsPath?: string\n})\n```\n\n## Typescript tricks\n\n### Import interfaces from sqlite\n\n`import { ISqlite, IMigrate } from 'sqlite'`\n\nSee the definitions for more details.\n\n### Specify typings for a specific database driver\n\n```typescript\n// Assuming you have @types/sqlite3 installed\nimport sqlite3 from 'sqlite3'\n\n// sqlite3.Database, sqlite3.Statement is the default if no explicit generic is specified\nawait open\u003csqlite3.Database, sqlite3.Statement\u003e({\n  filename: ':memory'\n})\n```\n\n### Use generics to get better typings on your rows\n\nMost methods allow for the use of [generics](https://www.typescriptlang.org/docs/handbook/generics.html)\nto specify the data type of your returned data. This allows your IDE to perform better autocomplete\nand the typescript compiler to perform better static type analysis.\n\n#### Get example\n\n```typescript\n\ninterface Row {\n  col: string\n}\n\n// result will be of type Row, allowing Typescript supported IDEs to autocomplete on the properties!\nconst result = await db.get\u003cRow\u003e('SELECT col FROM tbl WHERE col = ?', 'test')\n```\n\n#### All example\n\n```typescript\ninterface Row {\n  col: string\n}\n\n// Result is an array of rows, you can now have array-autocompletion data\nconst result = await db.all\u003cRow[]\u003e('SELECT col FROM tbl')\n\nresult.each((row) =\u003e {\n  // row should have type information now!\n})\n```\n\n## API Documentation\n\nSee the [`docs`](docs/globals.md) directory for full documentation.\n\n## Management Tools\n\n- [Beekeeper Studio](https://www.beekeeperstudio.io/): Open Source SQL Editor and Database Manager\n- [DB Browser for SQLite](https://github.com/sqlitebrowser/sqlitebrowser): Desktop-based browser.\n- [datasette](https://github.com/simonw/datasette): Datasette is a tool for exploring and publishing \ndata. Starts up a server that provides a web interface to your SQLite data.\n- [SQLite Studio](https://github.com/pawelsalawa/sqlitestudio): A free, open source, multi-platform SQLite database manager written in C++, with use of Qt framework.\n- [HeidiSQL](https://www.heidisql.com/): Full-featured database editor.\n- [DBeaver](https://dbeaver.io/): Full-featured multi-platform database tool and designer.   \n\n## Alternative SQLite libraries\n\nThis library and the library it primarily supports, `sqlite3`, may not be the best library that\nfits your use-case. You might want to try these other SQLite libraries:\n\n- [better-sqlite3](https://github.com/JoshuaWise/better-sqlite3): Totes itself as the fastest and \nsimplest library for SQLite3 in Node.js.\n- [Bun sqlite3](https://github.com/Jarred-Sumner/bun#bunsqlite-sqlite3-module): `bun:sqlite` is a high-performance builtin SQLite3 module for `bun.js`.\n- [sql.js](https://github.com/sql-js/sql.js): SQLite compiled to Webassembly.\n- [sqlite3-offline-next](https://github.com/nicolaiort/sqlite3-offline-next): Offers pre-compiled `sqlite3` \nbinaries if your machine cannot compile it. Should be mostly compatible with this library.\n\nIf you know of any others, feel free to open a PR to add them to the list.\n\n## References\n\n* [Using SQLite with Node.js for Rapid Prototyping](https://medium.com/@tarkus/node-js-and-sqlite-for-rapid-prototyping-bc9cf1f26f10) on Medium.com\n* [SQLite Documentation](https://www.sqlite.org/docs.html), e.g. [SQL Syntax](https://www.sqlite.org/lang.html), [Data Types](https://www.sqlite.org/datatype3.html) etc. on SQLite.org\n* ES6 tagged [sql-template-strings](https://www.npmjs.com/package/sql-template-strings).\n\n## License\n\nThe MIT License © 2020-present Kriasoft / Theo Gravity. All rights reserved.\n\n---\nMade with ♥ by [Konstantin Tarkus](https://github.com/koistya) ([@koistya](https://twitter.com/koistya)), [Theo Gravity](https://github.com/theogravity) and [contributors](https://github.com/kriasoft/node-sqlite/graphs/contributors)\n","funding_links":[],"categories":["typescript"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkriasoft%2Fnode-sqlite","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkriasoft%2Fnode-sqlite","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkriasoft%2Fnode-sqlite/lists"}