npm: @powersync/drizzle-driver

This package enables using Drizzle with the PowerSync React Native and JavaScript Web SDKs.

Setup

Set up the PowerSync Database and wrap it with Drizzle.

Currently, you need to create the Drizzle schema manually, and it should match the table definitions of your PowerSync client-side schema.

import { wrapPowerSyncWithDrizzle } from "@powersync/drizzle-driver";
import { PowerSyncDatabase } from "@powersync/web";
import { relations } from "drizzle-orm";
import { index, integer, sqliteTable, text } from "drizzle-orm/sqlite-core";
import { appSchema } from "./schema";

// Define Drizzle schema
export const lists = sqliteTable("lists", {
  id: text("id"),
  name: text("name"),
});

export const todos = sqliteTable("todos", {
  id: text("id"),
  description: text("description"),
  list_id: text("list_id"),
  created_at: text("created_at"),
});

export const listsRelations = relations(lists, ({ one, many }) => ({
  todos: many(todos),
}));

export const todosRelations = relations(todos, ({ one, many }) => ({
  list: one(lists, {
    fields: [todos.list_id],
    references: [lists.id],
  }),
}));

export const drizzleSchema = {
  lists,
  todos,
  listsRelations,
  todosRelations,
};

// Existing PowerSync database constructor
export const powerSyncDb = new PowerSyncDatabase({
  database: {
    dbFilename: "test.sqlite",
  },
  schema: appSchema,
});

// Wrap the database with Drizzle
// Provide the Drizzle schema you created above
export const db = wrapPowerSyncWithDrizzle(powerSyncDb, {
  schema: drizzleSchema,
});

Compilable queries

To use Drizzle queries in your hooks and composables, they currently need to be converted using toCompilableQuery.

import { toCompilableQuery } from "@powersync/drizzle-driver";

const query = db.select().from(users);
const { data: listRecords, isLoading } = useQuery(toCompilableQuery(query));

Usage Examples

Below are examples comparing Drizzle and PowerSync syntax for common database operations.

Select Operations

Insert Operations

Delete Operations

Update Operations

Watched Queries

Transactions