0.16.1 • Published 1 year ago

drizzle-orm-sqlite v0.16.1

Weekly downloads
-
License
Apache-2.0
Repository
github
Last release
1 year ago

Drizzle ORM | SQLite

DrizzleORM is a tiny, blazingly fast TypeScript ORM library with a drizzle-kit CLI companion for automatic SQL migrations generation. Here you can find extensive docs for SQLite module. We support better-sqlite3, node-sqlite, bun:sqlite, Cloudflare D1, Fly.io LiteFS drivers.

💾 Installation

npm install drizzle-orm drizzle-orm-sqlite better-sqlite3
## opt-in automatic migrations generator
npm install -D drizzle-kit 

🚀 Quick start

Default SQLite connector is using better-sqlite3 database driver

import { SQLiteConnector, sqliteTable, text, integer } from "drizzle-orm-sqlite";
import Database from "better-sqlite3";

const users = sqliteTable("users", {
  id: integer("id").primaryKey(),
  fullName: text('full_name'),
})

const sqlite = new Database("sqlite.db");
const connector = new SQLiteConnector(sqlite);
const db = connector.connect();

const users = db.select(users).all();

Connecting to databases

// better-sqlite3 or fly.io LiteFS
import { SQLiteConnector, SQLiteDatabase } from "drizzle-orm-sqlite";
import Database from "better-sqlite3";

const sqlite = new Database("sqlite.db");
const connector = new SQLiteConnector(sqlite);
const db: SQLiteDatabase = connector.connect();
const result = db.select(users).all()

// bun js embedded sqlite connector
import { SQLiteBunConnector, SQLiteBunDatabase } from "drizzle-orm-sqlite/bun";
import { Database } from "bun:sqlite";

const sqlite = new Database("nw.sqlite");
const db: SQLiteBunDatabase = new SQLiteBunConnector(sqlite).connect();
const result = db.select(users).all()

// Cloudflare D1 connector
import { SQLiteD1Connector, SQLiteD1Database } from 'drizzle-orm-sqlite/d1';

// env.DB from cloudflare worker environment
const db: SQLiteD1Database = new SQLiteD1Connector(env.DB).connect();
const result = await db.select(users).all() // pay attention this one is async

SQL schema declaration

With drizzle-orm you declare SQL schema in TypeScript. You can have either one schema.ts file with all declarations or you can group them logically in multiple files. We prefer to use single file schema.

📦project
 ├ 📂src
 │ ├ 📂data
 │ │ └ 📜schema.ts
 │ └ ...
 ├ ...
 └ 📜package.json
 
## or multiple schema files
├ 📂data
  ├ 📜users.ts
  ├ 📜countries.ts
  ├ 📜cities.ts
  ├ 📜products.ts
  ├ 📜clients.ts
  ├ 📜enums.ts
  └ 📜etc.ts

This is how you declare SQL schema in schema.ts. You can declare tables, indexes and constraints, foreign keys and enums. Please pay attention to export keyword, they are mandatory if you'll be using drizzle-kit SQL migrations generator.

import { sqliteTable, text, integer, uniqueIndex } from "drizzle-orm-sqlite";

export const countries = sqliteTable("countries", {
    id: integer("id").primaryKey(),
    name: text("name"),
  }, (table) => ({
    nameIdx: uniqueIndex("nameIdx").on(table.name),
  })
);

export const cities = sqliteTable("cities", {
  id: integer("id").primaryKey(),
  name: text("name"),
  countryId: integer("country_id").references(() => countries.id),
})

Database and table entity types

import { SQLiteConnector, InferModel, text, integer, sqliteTable } from "drizzle-orm-sqlite";

const users = sqliteTable("users", {
  id: integer('id').primaryKey(),
  fullName: text('full_name'),
  phone: text('phone'),
})

export type User = InferModel<typeof users> // return type when queried
export type InsertUser = InferModel<typeof users, "insert"> // insert type
...

import { SQLiteConnector } from "drizzle-orm-sqlite";
import Database from "better-sqlite3";

const sqlite = new Database("sqlite.db");
const connector = new SQLiteConnector(sqlite);
const db: SQLiteDatabase = connector.connect();

const result: User[] = await db.select(users).all()

const insertUser = (user: InsertUser) => {
  return db.insert(users).values(user).run()
}

The list of all column types. You can also create custom types - !!see here!!.

integer("...")
integer("...", { mode: "number" | "timestamp" | "bigint" })
real("...")
text("...");
text<"union" | "string" | "type">("...");

blob("...");
blob("...", { mode: "json" | "buffer" });
blob<{ foo: string }>("...");

column.primaryKey()
column.notNull()
column.default(...)

Declaring indexes and foreign keys

import { sqliteTable, foreignKey, text, integer, index, uniqueIndex } from "drizzle-orm-sqlite";

export const countries = sqliteTable("countries", {
    id: integer("id").primaryKey(),
    name: text("name", { length: 256 }),
    population: integer("population"),
  }, (table) => ({
    nameIdx: index("name_idx").on(table.name), // one column
    namePopulationIdx: index("name_population_idx").on(table.name, table.population), // multiple columns
    uniqueIdx: uniqueIndex("unique_idx").on(table.name), // unique index
  })
);

export const cities = sqliteTable("cities", {
  id: integer("id").primaryKey(),
  name: text("name", { length: 256 }),
  countryId: integer("country_id").references(() => countries.id), // inline foreign key
  countryName: text("country_id"),
}, (table) => ({
  // explicit foreign key with 1 column
  countryFk: foreignKey(() => ({
    columns: [table.countryId],
    foreignColumns: [countries.id],
  })),
  // explicit foreign key with multiple columns
  countryIdNameFk: foreignKey(() => ({
    columns: [table.countryId, table.countryName],
    foreignColumns: [countries.id, countries.name],
  })),
}));

// you can have .where() on indexes
index("name_idx").on(table.name).where(sql``)

Create Read Update Delete

Querying, sorting and filtering. We also support partial select.

...
import { sqliteTable, text, integer } from "drizzle-orm-sqlite";
import { and, asc, desc, eq, or } from "drizzle-orm/expressions"
import { SQLiteConnector } from "drizzle-orm-sqlite";
import Database from "better-sqlite3";

const users = sqliteTable("users", {
  id: integer("id").primaryKey(),
  name: text("full_name"),
});

const sqlite = new Database("sqlite.db");
const connector = new SQLiteConnector(sqlite);
const db = connector.connect();

db.select(users).all();
db.select(users).where(eq(users.id, 42)).get();

// you can combine filters with and(...) or or(...)
db.select(users).where(and(eq(users.id, 42), eq(users.name, "Dan"))).all();

db.select(users).where(or(eq(users.id, 42), eq(users.id, 1))).all();

// partial select
const result = db.select(users).fields({
    field1: users.id,
    field2: users.name,
  }).all();
const { field1, field2 } = result[0];

// limit offset & order by
db.select(users).limit(10).offset(10).all();
db.select(users).orderBy(asc(users.name)).all();
db.select(users).orderBy(desc(users.name)).all();
// you can pass multiple order args
db.select(users).orderBy(asc(users.name), desc(users.name)).all();

// list of all filter operators
eq(column, value)
eq(column1, column2)
ne(column, value)
ne(column1, column2)

notEq(column, value)
less(column, value)
lessEq(column, value)

gt(column, value)
gt(column1, column2)
gte(column, value)
gte(column1, column2)
lt(column, value)
lt(column1, column2)
lte(column, value)
lte(column1, column2)

isNull(column)
isNotNull(column)

inArray(column, values[])
inArray(column, sqlSubquery)
notInArray(column, values[])
notInArray(column, sqlSubquery)

exists(sqlSubquery)
notExists(sqlSubquery)

between(column, min, max)
notBetween(column, min, max)

like(column, value)
like(column, value)
ilike(column, value)
notIlike(column, value)

not(sqlExpression)

and(exressions: Expr[])
or(exressions: Expr[])

Inserting

import { sqliteTable, text, integer } from "drizzle-orm-sqlite";
import { SQLiteConnector } from "drizzle-orm-sqlite";
import Database from "better-sqlite3";

const sqlite = new Database("sqlite.db");
const connector = new SQLiteConnector(sqlite);
const db = connector.connect();

const users = sqliteTable("users", {
  id: integer("id").primaryKey(),
  name: text("name"),
  createdAt: integer("created_at", { mode: "timestamp" }),
});

db.insert(users).values({ name: "Andrew", createdAt: +new Date() }).run();

// insert multiple users
db.insert(users).values({
      name: "Andrew",
      createdAt: +new Date(),
    },{
      name: "Dan",
      createdAt: +new Date(),
    }).run();

// insert with returning
const insertedUser = db.insert(users).values({ name: "Dan", createdAt: +new Date() }).returning().get()

Update and Delete

db.update(users)
  .set({ name: 'Mr. Dan' })
  .where(eq(usersTable.name, 'Dan'))
  .run();
	
db.delete(users)
  .where(eq(usersTable.name, 'Dan'))
  .run();

Aggregations

They work just like they do in SQL, but you have them fully type safe

const orders = sqliteTable("order", {
  id: integer("id").primaryKey(),
  orderDate: integer("order_date", { mode: "timestamp" }).notNull(),
  requiredDate: integer("required_date", { mode: "timestamp" }).notNull(),
  shippedDate: integer("shipped_date", { mode: "timestamp" }),
  shipVia: integer("ship_via").notNull(),
  freight: numeric("freight").notNull(),
  shipName: text("ship_name").notNull(),
  shipCity: text("ship_city").notNull(),
  shipRegion: text("ship_region"),
  shipPostalCode: text("ship_postal_code"),
  shipCountry: text("ship_country").notNull(),
  customerId: text("customer_id").notNull(),
  employeeId: integer("employee_id").notNull(),
});

const details = sqliteTable("order_detail", {
  unitPrice: numeric("unit_price").notNull(),
  quantity: integer("quantity").notNull(),
  discount: numeric("discount").notNull(),
  orderId: integer("order_id").notNull(),
  productId: integer("product_id").notNull(),
});


db.select(orders).fields({
    id: orders.id,
    shippedDate: orders.shippedDate,
    shipName: orders.shipName,
    shipCity: orders.shipCity,
    shipCountry: orders.shipCountry,
    productsCount: sql`count(${details.productId})`.as<number>(),
    quantitySum: sql`sum(${details.quantity})`.as<number>(),
    totalPrice: sql`sum(${details.quantity} * ${details.unitPrice})`.as<number>(),
  })
  .leftJoin(details, eq(orders.id, details.orderId))
  .groupBy(orders.id)
  .orderBy(asc(orders.id))
  .all();

Joins

Last but not least. Probably the most powerful feature in the library🚀

Many-to-one

import { sqliteTable, text, integer } from "drizzle-orm-sqlite";
import { SQLiteConnector } from "drizzle-orm-sqlite";

const cities = sqliteTable("cities", {
  id: integer("id").primaryKey(),
  name: text("name"),
});

const users = sqliteTable("users", {
  id: integer("id").primaryKey(),
  name: text("name"),
  cityId: integer("city_id").references(() => cities.id)
});

const db = new SQLiteConnector(sqlite).connect();

const result = db.select(cities).leftJoin(users, eq(cities2.id, users2.cityId)).all()

Many-to-many

const users = sqliteTable("users", {
  id: integer("id").primaryKey(),
  name: text("name"),
});

const chatGroups = sqliteTable("chat_groups", {
  id: integer("id").primaryKey(),
  name: text("name"),
});

const usersToChatGroups = sqliteTable("usersToChatGroups", {
  userId: integer("user_id").notNull().references(() => users.id),
  groupId: integer("group_id").notNull().references(() => chatGroups.id),
});

...
const db = new SQLiteConnector(...).connect();

// querying user group with id 1 and all the participants(users)
db.select(usersToChatGroups)
  .leftJoin(users, eq(usersToChatGroups.userId, users.id))
  .leftJoin(chatGroups, eq(usersToChatGroups.groupId, chatGroups.id))
  .where(eq(chatGroups.id, 1))
  .all();

Join aliases and selfjoins

import { ..., alias } from "drizzle-orm-sqlite";

export const files = sqliteTable("folders", {
  name: text("name").notNull(),
  parent: text("parent_folder")
})

...
const db = new SQLiteConnector(...).connect();

const nestedFiles = alias(files, "nested_files");
db.select(files)
  .leftJoin(nestedFiles, eq(files.name, nestedFiles.name))
  .where(eq(files.parent, "/"))
  .all();
// will return files and folers and nested files for each folder at root dir

Join using partial field select

Join Cities with Users getting only needed fields form request

db.select(cities).fields({
  id: cities.id,
  cityName: cities.name
  userId: users.id
}).leftJoin(users, eq(users.cityId, cities.id))
  .all();

⚡️ Performance and prepared statements

With Drizzle ORM you can go faster than better-sqlite3 driver by utilizing our prepared statements and placeholder APIs

import { placeholder } from "drizzle-orm/sql";

const db = new SQLiteConnector(...).connect();

const q = db.select(customers).prepare();
q.all() // SELECT * FROM customers

const q = db.select(customers).where(eq(customers.id, placeholder("id"))).prepare()

q.get({ id: 10 }) // SELECT * FROM customers WHERE id = 10
q.get({ id: 12 }) // SELECT * FROM customers WHERE id = 12

const q = db.select(customers)
  .where(sql`lower(${customers.name}) like ${placeholder("name")}`)
  .prepare();

q.all({ name: "%an%" }) // SELECT * FROM customers WHERE name ilike '%an%'

🗄 Migrations

Automatic SQL migrations generation with drizzle-kit

DrizzleKit - is a CLI migrator tool for DrizzleORM. It is probably one and only tool that lets you completely automatically generate SQL migrations and covers ~95% of the common cases like delitions and renames by prompting user input.\ Check out the docs for DrizzleKit

For schema file:

import { index, integer, sqliteTable, text } from "drizzle-orm-sqlite";

export const users = sqliteTable("users", {
  id: serial("id").primaryKey(),
  fullName: text("full_name"),
}, (table)=>({
  nameIdx: index("name_idx", table.fullName),
}));

export const authOtps = sqliteTable("auth_otp", {
  id: integer("id").primaryKey(),
  phone: text("phone"),
  userId: integer("user_id").references(() => users.id),
}

It will generate:

CREATE TABLE IF NOT EXISTS auth_otp (
	"id" INTEGER PRIMARY KEY,
	"phone" TEXT,
	"user_id" INTEGER
);

CREATE TABLE IF NOT EXISTS users (
	"id" INTEGER PRIMARY KEY,
	"full_name" TEXT
);

DO $$ BEGIN
 ALTER TABLE auth_otp ADD CONSTRAINT auth_otp_user_id_fkey FOREIGN KEY ("user_id") REFERENCES users(id);
EXCEPTION
 WHEN duplicate_object THEN null;
END $$;

CREATE INDEX IF NOT EXISTS users_full_name_index ON users (full_name);

And you can run migrations manually or using our embedded migrations module

import { SQLiteConnector } from "drizzle-orm-sqlite";
import Database from "better-sqlite3";

const sqlite = new Database("sqlite.db");
const connector = new SQLiteConnector(sqlite);
const db = connector.connect();

// this will automatically run needed migrations on the database
connector.migrate({ migrationsFolder: "./drizzle" })

Utility stuff

Printing SQL query

const query = db.select(users)
		.fields({ id: users.id, name: users.name })
		.groupBy(users.id)
		.toSQL();
// query:
{
  sql: 'select "id", "name" from "users" group by "users"."id"',
  params: [],
}

Raw query usage

// it will automatically run a parametrized query!
const res: QueryResult<any> = await db.run(sql`SELECT * FROM users WHERE user.id = ${userId}`)
0.15.4-1f6c448

1 year ago

0.16.0-ddf4681

1 year ago

0.15.0-2e1e5b2

1 year ago

0.15.3-0dcbb16

1 year ago

0.16.0-b9e9ba0

1 year ago

0.15.4-36368e7

1 year ago

0.15.0-60954a3

1 year ago

0.15.0-3548c99

1 year ago

0.15.3-1e62a3e

1 year ago

0.15.0-7d17618

1 year ago

0.15.0-19c5c02

1 year ago

0.16.0-56d16f9

1 year ago

0.15.4-71be15e

1 year ago

0.15.0-80901ff

1 year ago

0.15.3-844cb31

1 year ago

0.15.4-b422bc1

1 year ago

0.15.0-4a5b2e3

1 year ago

0.15.4-30915c1

1 year ago

0.15.3-72fb2c0

1 year ago

0.14.5

1 year ago

0.15.3-98b2097

1 year ago

0.15.3-adba448

1 year ago

0.16.0-c522f26

1 year ago

0.15.3-335d188

1 year ago

0.16.0-11f7ff3

1 year ago

0.16.0-af45b90

1 year ago

0.15.4-b3dd40c

1 year ago

0.15.0-9728cc6

1 year ago

0.15.3-1c43305

1 year ago

0.16.1-78fb61e

1 year ago

0.16.1-60d4ce6

1 year ago

0.15.4-f77c6c2

1 year ago

0.15.0-2b4d90d

1 year ago

0.15.4

1 year ago

0.16.0-51c77ba

1 year ago

0.16.0-b4b5a09

1 year ago

0.15.0-88523f9

1 year ago

0.15.0

1 year ago

0.15.2

1 year ago

0.15.3

1 year ago

0.15.0-1766537

1 year ago

0.15.0-a1b76f5

1 year ago

0.15.3-c675dde

1 year ago

0.16.0-484a8ae

1 year ago

0.16.0-cf5a510

1 year ago

0.14.5-59f0a3a

1 year ago

0.16.0-97f9977

1 year ago

0.15.0-6879c1d

1 year ago

0.15.2-52e75f5

1 year ago

0.15.0-f67dd9d

1 year ago

0.16.0

1 year ago

0.16.1

1 year ago

0.15.0-656bcc3

1 year ago

0.15.4-d8f67aa

1 year ago

0.16.0-2c4c5b1

1 year ago

0.16.0-4124cf0

1 year ago

0.16.0-3e17d6e

1 year ago

0.15.3-23baedd

1 year ago

0.16.1-43776eb

1 year ago

0.15.3-bbe577c

1 year ago

0.15.0-a90d3bc

1 year ago

0.15.0-07f606f

1 year ago

0.14.4

1 year ago

0.14.4-1bcee50

1 year ago

0.14.3-67805d4

1 year ago

0.14.3-dd27c86

1 year ago

0.14.3-4e3a5b9

1 year ago

0.14.3-5ce7d69

1 year ago

0.14.3

1 year ago

0.14.3-9ba6169

1 year ago

0.14.2-5b14ef4

1 year ago

0.13.0-671a09e

1 year ago

0.13.0-d68193c

1 year ago

0.13.0-a486088

1 year ago

0.13.0-099a94f

1 year ago

0.13.0-b8ae68d

1 year ago

0.14.2-314c1fa

1 year ago

0.14.2-cce4cab

1 year ago

0.14.2-f8d0d46

1 year ago

0.14.2-6f226c1

1 year ago

0.14.2-e295848

1 year ago

0.14.2-c153bbf

1 year ago

0.14.2-1e42665

1 year ago

0.14.2-4eada6d

1 year ago

0.14.2-01c3d82

1 year ago

0.14.2-c7344a5

1 year ago

0.14.2-cc06fec

1 year ago

0.14.2-5514014

1 year ago

0.13.0-9f4af29

1 year ago

0.14.2-e902ba8

1 year ago

0.14.2-3967f06

1 year ago

0.14.2

1 year ago

0.14.2-3793d78

1 year ago

0.14.1-c5dca58

1 year ago

0.14.1-f617bb6

1 year ago

0.14.1-1d98f11

1 year ago

0.14.1-1c58471

1 year ago

0.14.1-1f44b00

1 year ago

0.14.1-7d1d823

1 year ago

0.14.1-f92529c

1 year ago

0.14.1-bad61c5

1 year ago

0.14.1

1 year ago

0.13.0-03f651b

1 year ago

0.13.0-f115120

1 year ago

0.13.0-efa4dda

1 year ago

0.14.0-beta.2

1 year ago

0.14.0-beta.1

1 year ago

0.14.0

1 year ago

0.13.0-cd3f5e4

1 year ago

0.13.0-a7bfec3

1 year ago

0.13.0-6a923f2

1 year ago

0.13.0-a61a883

1 year ago

0.13.0-7d422f2

1 year ago

0.13.0

1 year ago

0.12.0-beta.21

1 year ago

0.12.0-beta.20

1 year ago

0.12.0-beta.19

1 year ago

0.12.0-beta.18

1 year ago

0.12.0-beta.17

1 year ago

0.12.0-beta.16

1 year ago

0.12.0-beta.15

1 year ago

0.12.0-beta.14

1 year ago

0.12.0-beta.13

1 year ago

0.12.0-beta.12

1 year ago

0.12.0-beta.11

2 years ago

0.12.0-beta.10

2 years ago

0.12.0-beta.9

2 years ago

0.12.0-beta.8

2 years ago

0.12.0-beta.7

2 years ago

0.12.0-beta.6

2 years ago

0.12.0-beta.5

2 years ago

0.12.0-beta.4

2 years ago

0.12.0-beta.3

2 years ago

0.12.0-beta.2

2 years ago

0.12.0-beta.1

2 years ago