UNPKG

kysely-solarsystem

Version:

💫 Kysely dialect for SolarSystemDB

96 lines (95 loc) • 3.11 kB
import { attempt } from '@jill64/attempt'; import { SqliteAdapter, SqliteIntrospector, SqliteQueryCompiler } from 'kysely'; export class SolarSystemDialect { config; constructor(config) { this.config = config; } createAdapter() { return new SqliteAdapter(); } createDriver() { return new SolarSystemDriver(this.config); } createQueryCompiler() { return new SqliteQueryCompiler(); } createIntrospector(db) { return new SqliteIntrospector(db); } } class SolarSystemDriver { config; constructor(config) { this.config = config; } async init() { } async acquireConnection() { return new SolarSystemConnection(this.config); } async beginTransaction(conn) { return await conn.beginTransaction(); } async commitTransaction(conn) { return await conn.commitTransaction(); } async rollbackTransaction(conn) { return await conn.rollbackTransaction(); } async releaseConnection() { } async destroy() { } } class SolarSystemConnection { config; constructor(config) { this.config = config; } async executeQuery(compiledQuery) { const res = await fetch('https://api.solarsystemdb.com/query', { method: 'POST', headers: { Authorization: `Bearer ${this.config.apiKey}` }, body: JSON.stringify({ team_name: this.config.teamName, cluster_name: this.config.clusterName, branch_name: this.config.branchName, sql: compiledQuery.sql, params: compiledQuery.parameters }) }); const text = await res.text(); const results = attempt(() => JSON.parse(text), (e, o) => { throw new Error(`[SolarSystemDialect]: Failed to parse JSON response. ${res.status} | ${res.statusText} ${e?.message ?? JSON.stringify(o, null, 2)} ${text} `); }); const firstResult = results.result?.length ? results.result[0] : null; const numAffectedRows = firstResult && firstResult.meta.changes > 0 ? BigInt(firstResult.meta.changes) : undefined; return { insertId: firstResult?.meta.last_row_id === undefined || firstResult.meta.last_row_id === null ? undefined : BigInt(firstResult.meta.last_row_id), rows: (firstResult?.results ?? []), numAffectedRows, numUpdatedOrDeletedRows: numAffectedRows }; } async beginTransaction() { throw new Error('[SolarSystemDialect]: beginTransaction are not supported.'); } async commitTransaction() { throw new Error('[SolarSystemDialect]: commitTransaction are not supported.'); } async rollbackTransaction() { throw new Error('[SolarSystemDialect]: rollbackTransaction are not supported.'); } async *streamQuery() { throw new Error('[SolarSystemDialect]: streamQuery is not supported.'); } }