Skip to content

Instantly share code, notes, and snippets.

@wernst
Last active February 25, 2025 11:56
Show Gist options
  • Save wernst/9a1a42a7bb95bc2268b38612e9ee4339 to your computer and use it in GitHub Desktop.
Save wernst/9a1a42a7bb95bc2268b38612e9ee4339 to your computer and use it in GitHub Desktop.
Triplit op-sqlite storage
import { OPSQLiteConnection, open } from '@op-engineering/op-sqlite';
import {
AsyncSQLiteAdapter,
AsyncSQLiteExecutor,
AsyncAdapterSQLiteStorage
} from '@triplit/db/storage/adapter-sqlite';
import { AsyncTupleStorageApi } from '@triplit/tuple-database';
// Create DB instance
const db = open({ name: 'triplit.db' });
// Create adapter
const adapter = new OPSQLiteAdapter(db);
// Create storage provider
export const storage = new AsyncAdapterSQLiteStorage(adapter);
class OPSQLiteAdapter implements AsyncSQLiteAdapter {
constructor(private db: OPSQLiteConnection) {}
async execute(sql: string, args?: any[] | undefined) {
return this.db.execute(sql, args);
}
normalizeResults(results: any): { key: string; value: string }[] {
if (!results.rows) return [];
return results.rows._array as { key: string; value: string }[];
}
async transact(fn: (adapter: AsyncSQLiteExecutor) => Promise<void>) {
await this.db.transaction(async (tx) => {
await fn({
execute: (sql, args) => {
return tx.execute(sql, args);
},
});
tx.commit();
});
}
async close() {
this.db.close();
}
}
@sgup
Copy link

sgup commented Feb 4, 2025

updated to work with "@op-engineering/op-sqlite": "^11.4.4",

import { OPSQLiteConnection, open } from "@op-engineering/op-sqlite";
import {
  AsyncSQLiteAdapter,
  AsyncSQLiteExecutor,
  AsyncAdapterSQLiteStorage,
} from "@triplit/db/storage/adapter-sqlite";

// Create DB instance
export function createDBStorage(name: string) {
  const db = open({ name });
  const adapter = new OPSQLiteAdapter(db);
  const storage = new AsyncAdapterSQLiteStorage(adapter);
  return storage;
}

class OPSQLiteAdapter implements AsyncSQLiteAdapter {
  constructor(private db: OPSQLiteConnection) {}
  async execute(sql: string, args?: any[] | undefined) {
    return this.db.execute(sql, args);
  }
  normalizeResults(results: any): { key: string; value: string }[] {
    if (!results.rows) return [];
    return results.rows as { key: string; value: string }[];
  }
  async transact(fn: (adapter: AsyncSQLiteExecutor) => Promise<void>) {
    await this.db.transaction(async (tx) => {
      await fn({
        execute: (sql, args) => {
          return tx.execute(sql, args);
        },
      });
      await tx.commit();
    });
  }
  async close() {
    this.db.close();
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment