{"id":21920673,"url":"https://github.com/litdb/litdb","last_synced_at":"2025-04-11T23:14:43.381Z","repository":{"id":260639541,"uuid":"881921668","full_name":"litdb/litdb","owner":"litdb","description":"Lightweight RDBMS agnostic TypeScript/JS abstraction for SQLite, PostgreSQL and MySQL","archived":false,"fork":false,"pushed_at":"2025-03-13T02:52:30.000Z","size":253,"stargazers_count":306,"open_issues_count":0,"forks_count":3,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-04-11T23:14:39.372Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"bsd-3-clause","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/litdb.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"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}},"created_at":"2024-11-01T13:58:41.000Z","updated_at":"2025-03-27T11:48:29.000Z","dependencies_parsed_at":"2024-11-01T15:17:33.161Z","dependency_job_id":"af06f1f1-2797-4419-86ee-f54a6b532804","html_url":"https://github.com/litdb/litdb","commit_stats":{"total_commits":148,"total_committers":2,"mean_commits":74.0,"dds":0.006756756756756799,"last_synced_commit":"65dcafb96fd2ead09e33825e6b088a192411841f"},"previous_names":["litdb/litdb"],"tags_count":33,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/litdb%2Flitdb","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/litdb%2Flitdb/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/litdb%2Flitdb/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/litdb%2Flitdb/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/litdb","download_url":"https://codeload.github.com/litdb/litdb/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248492884,"owners_count":21113163,"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":[],"created_at":"2024-11-28T20:15:46.554Z","updated_at":"2025-04-11T23:14:43.357Z","avatar_url":"https://github.com/litdb.png","language":"TypeScript","readme":"# litdb\n\nlitdb contains LINQ-like type-safe SQL builders for TypeScript/JavaScript for writing type-safe expressive SQL that's parameterized \u0026 portable across SQLite, MySQL \u0026 PostgreSQL.\n\nWebsite: https://litdb.dev\n\n[![](https://litdb.dev/img/bg-video.png)](https://youtu.be/4s3-K-hggmg)\n\nhttps://youtu.be/4s3-K-hggmg\n\n## SQL-like\n\nlitdb lets you write familiar SQL you know using its type-safe expressions and query builders that's safe by default.\n\nAPIs are designed to keep a close affinity to SQL making it clear what SQL is being generated, expressions utilize tagged templates to take away the tedium of maintaining table and column references, parameterizing values and catering for different SQL dialects to retain the expressive freedom of SQL, but portable across multiple RDBMS's.\n\nThe primary difference between SQL is how queries are constructed, where the SELECT Query Builder wants queries to be constructed in the order they're run, by specifying the data sources first, i.e. the FROM table first, followed by any JOINs (just like LINQ) which allows litdb query builders to provide type safety and intellisense for the rest of the query.\n\n![](https://litdb.dev/img/sql-queries.jpeg)\n\n## Small\n\n- **9kb** .min + .zip\n- **36kb** .min\n- **0** dependencies\n\n## Install\n\nTo use litdb with your favorite ORM, no driver is required. Just use the `litdb` package directly:\n\n```sh\nnpm install litdb\n```\n\n`litdb` is also available as a module, where it can be used directly in the browser:\n\n```html\n\u003cscript type=\"module\"\u003e\nimport { sqlite as $ } from \"https://unpkg.com/litdb/dist/index.min.js\"\n    \nconst { sql, params } = $.from(Contact).select(c =\u003e $`${c.name}`).build()\n\u003c/script\u003e\n```\n\nTo get the most out of `litdb` we recommend using text editors that supports TypeScript definitions \n(e.g. VS Code, JetBrains IDEs, neovim, etc.)\n\n# LitDB Drivers\n\nLightweight drivers with native support for its typed SQL Builders and parameterized SQL Expressions \nare also available for the popular databases:\n\n### Bun SQLite\n\nUse with [Bun's native SQLite3 driver](https://bun.sh/docs/api/sqlite):\n\n```sh\nbun install @litdb/bun-sqlite\n```\n\n### Node better-sqlite\n\nUse with Node [better-sqlite3](https://github.com/WiseLibs/better-sqlite3):\n\n```sh\nnpm install @litdb/better-sqlite\n```\n\n### PostgreSQL\n\nUse with [postgres.js](https://github.com/porsager/postgres) client:\n\n```sh\nnpm install @litdb/postgres\n```\n\n### MySql\n\nUse with [node-mysql2](https://github.com/sidorares/node-mysql2) client:\n\n```sh\nnpm install @litdb/mysql\n```\n\n### Request a Driver\n\nIf you'd like to see a driver for a specific client, please open or vote for a feature request on litdb's \n[GitHub Discussions](https://github.com/litdb/litdb/discussions/categories/ideas).\n\n## Driver Usage\n\nlitdb drivers are lightweight data adapters providing a number of convenience APIs for executing SQL and parameters. \nThey can be used with or without litdb SQL Builders, but offer the most value when used together. \n\nThe same APIs are available across all drivers, so you can easily switch between them. They include both **sync** APIs\nrecommended for SQLite libraries that use SQLite's native blocking APIs, whilst **async** APIs should be used for \nall other databases, e.g. PostgreSQL and MySQL.\n\nThis is an example of using the Bun SQLite driver:\n\n**db.ts**\n\n```ts\nimport { connect } from \"./drivers/sqlite\"\n\nexport const connection = connect(\"app.db\") // WAL enabled by default\nexport const { $, sync:db, async, native } = connection\n```\n\n\u003e When needed use `native` to access underlying driver\n\n**app.ts**\n\n```ts\nimport { $, db } from \"./db\"\nimport { Contact } from \"./models\"\n\ndb.dropTable(Contact)\ndb.createTable(Contact)\ndb.insertAll([\n    new Contact({ name:\"John Doe\", email:\"john@mail.org\" }),\n    new Contact({ name:\"Jane Doe\", email:\"jane@mail.org\" }),\n])\n\nconst janeEmail = 'jane@mail.org'\nconst jane = db.one\u003cContact\u003e($.from(Contact).where(c =\u003e $`${c.email} = ${janeEmail}`))!\n\n// Insert examples\nconst {lastInsertRowid:bobId} = db.insert(new Contact({ name:\"Bob\", email:\"bob@mail.org\" }))\nconst {lastInsertRowid} = db.exec`INSERT INTO Contact(name,email) VALUES('Jo','jo@doe.org')`\nconst name = 'Alice', email = 'alice@mail.org'\ndb.exec`INSERT INTO Contact(name,email) VALUES (${name}, ${email})`\n\n// Typed SQL fragment with named param example\nconst hasId = \u003cTable extends { id:number }\u003e(id:number|bigint) =\u003e\n    (x:Table) =\u003e $.sql($`${x.id} = $id`, { id })\n\nconst contacts = db.all($.from(Contact).into(Contact))                // =\u003e Contact[]\nconst bob = db.one($.from(Contact).where(hasId(bobId)).into(Contact)) // =\u003e Contact    \nconst contactsCount = db.value($.from(Contact).select`COUNT(*)`)      // =\u003e number\nconst emails = db.column($.from(Contact).select(c =\u003e $`${c.email}`))  // =\u003e string[]\nconst contactsArray = db.arrays($.from(Contact))                      // =\u003e any[][]\nconst bobArray = db.array($.from(Contact).where(hasId(bobId)))        // =\u003e any[]\n\n// Update examples\njane.email = 'jane@doe.org'\ndb.update(jane)                           // Update all properties\ndb.update(jane, { onlyProps:['email'] })  // Update only email\ndb.exec($.update(Contact).set({ email:jane.email }).where(hasId(jane.id))) // query builder\n\n// Delete examples\ndb.delete(jane)\ndb.exec($.deleteFrom(Contact).where(hasId(jane.id))) // query builder\n```\n\n## Type Safe\n\nGet productive intelli-sense for quickly accessing properties that exist your data model or design-time type-checking and compile-time static analysis errors for those that don't.\n\n![](https://litdb.dev/img/features/typesafe.png)\n\nOnly reference table and columns that are included in your query, quickly identify missing tables, columns and any typos:\n\n![](https://litdb.dev/img/features/typesafe2.png)\n\n## Safe Refactoring\n\nSince all references are statically typed to your models, you can safely refactor with confidence!\n\n![](https://litdb.dev/img/features/safe-refactoring.gif)\n\n## Composable\n\nQueries are highly composable where external references can be used across multiple Query Builders and SQL fragments\nto easily create and compose multiple complex queries with shared references.\n\nSQL Builders and SQL fragments can be embedded inside other query builders utilizing the full expressiveness of SQL \nwhere their SQL and parameters are merged into the parent query.\n\n```ts\n// Use external aliased table references across multiple query builders\nconst c = $.ref(Contact,'c'),\n      o = $.ref(Order,'o')\n\nconst now = new Date()\nconst monthAgo = new Date(now.setDate(now.getDate()-30)).toISOString().split('T')[0]\nconst last30Days = $.from(Order,'o2')\n    .where(o2 =\u003e $`${o2.contactId} = ${c.id}`)\n    .and(o2 =\u003e $`${o2.createdAt} \u003e= ${monthAgo}`)\n    .select(o2 =\u003e $`COUNT(${o2.id})`)\n\nconst recentOrder = $.from(Order,'o3')\n    .where(o3 =\u003e $`${o3.contactId} = ${c.id}`)\n    .select(o3 =\u003e $`MAX(${o3.createdAt})`)\n\n// Example of SQL Fragment with parameter\nconst startOfYear = `2024-01-01`\nconst o4 = $.ref(Order,'o4')\nconst totalOrders = $`SELECT SUM(${o4.total}) \n     FROM ${o4} o4 \n    WHERE ${o4.contactId} = ${c.id} \n      AND ${o4.createdAt} \u003e= ${startOfYear}`\n\n// Compose queries from multiple query builders and SQL fragments\nconst q = $.from(c)\n    .join(o, $`${c.id} = ${o.contactId}`)\n    .where`${o.createdAt} = (${recentOrder})`\n    .select`${c.id}, \n       ${c.name}, \n       ${o.createdAt}, \n       (${last30Days}) AS last30Days,\n       (${totalOrders}) AS totalOrders`\n    .orderBy`last30Days DESC`\n```\n\nGenerated SQL\n\n```sql\n\nSELECT c.\"id\", \n       c.\"name\", \n       o.\"createdAt\", \n       (SELECT COUNT(o2.\"id\")\n        FROM \"Order\" o2\n       WHERE o2.\"contactId\" = c.\"id\"\n         AND o2.\"createdAt\" \u003e= $_1) AS last30Days,\n       (SELECT SUM(o4.\"total\") \n           FROM \"Order\" o4 \n          WHERE o4.\"contactId\" = c.\"id\" \n            AND o4.\"createdAt\" \u003e= $_2) AS totalOrders\n  FROM \"Contact\" c\n  JOIN \"Order\" o ON c.\"id\" = o.\"contactId\"\n WHERE o.\"createdAt\" = (SELECT MAX(o3.\"createdAt\")\n        FROM \"Order\" o3\n       WHERE o3.\"contactId\" = c.\"id\")\n ORDER BY last30Days DESC\n```\n\nPARAMS\n\n    _1: 2024-10-12\n    _2: 2024-01-01\n","funding_links":[],"categories":["**1. Libraries**"],"sub_categories":["Database"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flitdb%2Flitdb","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flitdb%2Flitdb","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flitdb%2Flitdb/lists"}