Become a Gold Sponsor

Drizzle <> SQLite

Drizzle 原生支持使用 libsqlbetter-sqlite3 驱动程序连接 SQLite。

在使用这两种驱动程序并将其与 Drizzle ORM 集成时,我们发现它们之间有一些差异。例如:

在驱动程序层面,这两者之间可能没有太多差异,但主要的区别在于 libSQL 可以连接到 SQLite 文件和 Turso 远程数据库。LibSQL 是 SQLite 的一个分支,提供了比标准 SQLite 更多的功能,例如:

libsql

第一步 - 安装包

npm
yarn
pnpm
bun
npm i drizzle-orm @libsql/client
npm i -D drizzle-kit

第二步 - 初始化驱动程序并执行查询

Drizzle 原生支持所有 @libsql/client 驱动程序变体:

@libsql/clientdefaults to node import, automatically changes to web if target or platofrm is set for bundler, e.g. esbuild --platform=browser
@libsql/client/nodenode compatible module, supports :memory:, file, wss, http and turso conneciton protocols
@libsql/client/webmodule for fullstack web frameworks like next, nuxt, astro, etc.
@libsql/client/httpmodule for http and https connection protocols
@libsql/client/wsmodule for ws and wss conneciton protocols
@libsql/client/sqlite3module for :memory: and file conneciton protocols
@libsql/client-wasmSeparate experimental package for WASM

default
node
web
http
web sockets
wasm
import { drizzle } from 'drizzle-orm/libsql';

const db = drizzle({ connection: {
  url: process.env.DATABASE_URL, 
  authToken: process.env.DATABASE_AUTH_TOKEN 
}});

Step 3 - make a query

libsql
libsql with config
import { drizzle } from 'drizzle-orm/libsql';

const db = drizzle(process.env.DATABASE_URL);
 
const result = await db.execute('select 1');

如果您需要同步连接,可以使用我们的额外连接 API, 在该 API 中您指定驱动程序连接并将其传递给 Drizzle 实例。

import { drizzle } from 'drizzle-orm/libsql';
import { createClient } from '@libsql/client';

const client = createClient({ url: process.env.DATABASE_URL, authToken: process.env.DATABASE_AUTH_TOKEN });
const db = drizzle(client);

const result = await db.execute('select 1');

better-sqlite3

第一步 - 安装包

npm
yarn
pnpm
bun
npm i drizzle-orm better-sqlite3
npm i -D drizzle-kit @types/better-sqlite3

第二步 - 初始化驱动程序并执行查询

better-sqlite3
better-sqlite3 with config
import { drizzle } from 'drizzle-orm/better-sqlite3';

const db = drizzle(process.env.DATABASE_URL);

const result = await db.execute('select 1');

如果您需要提供现有的驱动程序:

import { drizzle } from 'drizzle-orm/better-sqlite3';
import Database from 'better-sqlite3';

const sqlite = new Database('sqlite.db');
const db = drizzle({ client: sqlite });

const result = await db.execute('select 1');

下一步是什么?