driftsql 1.0.19 → 1.0.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/drivers/libsql.d.ts +23 -0
- package/dist/drivers/mysql.d.ts +20 -0
- package/dist/drivers/postgres.d.ts +26 -0
- package/dist/drivers/sqlite.d.ts +25 -0
- package/dist/index.d.ts +54 -0
- package/dist/index.js +48 -0
- package/dist/pull.d.ts +28 -0
- package/dist/types.d.ts +49 -0
- package/package.json +4 -16
- package/tsconfig.json +24 -10
- package/src/drivers/bobsql.ts +0 -43
- package/src/drivers/libsql.ts +0 -70
- package/src/drivers/mysql.ts +0 -70
- package/src/drivers/neon.ts +0 -0
- package/src/drivers/postgres.ts +0 -112
- package/src/drivers/sqlite.ts +0 -122
- package/src/index.ts +0 -225
- package/src/pull.ts +0 -318
- package/src/types.ts +0 -73
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { DatabaseDriver, QueryResult, TransactionCapable } from '../types';
|
|
2
|
+
export interface LibSQLConfig {
|
|
3
|
+
url: string;
|
|
4
|
+
authToken?: string;
|
|
5
|
+
useTursoServerlessDriver?: boolean;
|
|
6
|
+
}
|
|
7
|
+
export declare class LibSQLDriver implements DatabaseDriver, TransactionCapable {
|
|
8
|
+
private client;
|
|
9
|
+
constructor(config: LibSQLConfig);
|
|
10
|
+
query<T = any>(sql: string, params?: any[]): Promise<QueryResult<T>>;
|
|
11
|
+
transaction<T>(callback: (driver: DatabaseDriver) => Promise<T>): Promise<T>;
|
|
12
|
+
findFirst<T = any>(table: string, where?: Record<string, any>): Promise<QueryResult<T> | null>;
|
|
13
|
+
findMany<T = any>(table: string, options?: {
|
|
14
|
+
where?: Record<string, any>;
|
|
15
|
+
limit?: number;
|
|
16
|
+
offset?: number;
|
|
17
|
+
}): Promise<QueryResult<T>>;
|
|
18
|
+
insert<T = any>(table: string, data: Record<string, any>): Promise<QueryResult<T>>;
|
|
19
|
+
update<T = any>(table: string, data: Record<string, any>, where: Record<string, any>): Promise<QueryResult<T>>;
|
|
20
|
+
delete(table: string, where: Record<string, any>): Promise<number>;
|
|
21
|
+
close(): Promise<void>;
|
|
22
|
+
private convertLibsqlResult;
|
|
23
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { DatabaseDriver, QueryResult, TransactionCapable } from '../types';
|
|
2
|
+
export interface MySQLConfig {
|
|
3
|
+
connectionString: string;
|
|
4
|
+
}
|
|
5
|
+
export declare class MySQLDriver implements DatabaseDriver, TransactionCapable {
|
|
6
|
+
private client;
|
|
7
|
+
constructor(config: MySQLConfig);
|
|
8
|
+
query<T = any>(sql: string, params?: any[]): Promise<QueryResult<T>>;
|
|
9
|
+
transaction<T>(callback: (driver: DatabaseDriver) => Promise<T>): Promise<T>;
|
|
10
|
+
findFirst<T = any>(table: string, where?: Record<string, any>): Promise<QueryResult<T> | null>;
|
|
11
|
+
findMany<T = any>(table: string, options?: {
|
|
12
|
+
where?: Record<string, any>;
|
|
13
|
+
limit?: number;
|
|
14
|
+
offset?: number;
|
|
15
|
+
}): Promise<QueryResult<T>>;
|
|
16
|
+
insert<T = any>(table: string, data: Record<string, any>): Promise<QueryResult<T>>;
|
|
17
|
+
update<T = any>(table: string, data: Record<string, any>, where: Record<string, any>): Promise<QueryResult<T>>;
|
|
18
|
+
delete(table: string, where: Record<string, any>): Promise<number>;
|
|
19
|
+
close(): Promise<void>;
|
|
20
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { DatabaseDriver, QueryResult, TransactionCapable } from '../types';
|
|
2
|
+
export interface PostgresConfig {
|
|
3
|
+
connectionString?: string;
|
|
4
|
+
experimental?: {
|
|
5
|
+
http?: {
|
|
6
|
+
url: string;
|
|
7
|
+
apiKey?: string;
|
|
8
|
+
};
|
|
9
|
+
};
|
|
10
|
+
}
|
|
11
|
+
export declare class PostgresDriver implements DatabaseDriver, TransactionCapable {
|
|
12
|
+
private client;
|
|
13
|
+
constructor(config: PostgresConfig);
|
|
14
|
+
query<T = any>(sql: string, params?: any[]): Promise<QueryResult<T>>;
|
|
15
|
+
transaction<T>(callback: (driver: DatabaseDriver) => Promise<T>): Promise<T>;
|
|
16
|
+
findFirst<T = any>(table: string, where?: Record<string, any>): Promise<QueryResult<T> | null>;
|
|
17
|
+
findMany<T = any>(table: string, options?: {
|
|
18
|
+
where?: Record<string, any>;
|
|
19
|
+
limit?: number;
|
|
20
|
+
offset?: number;
|
|
21
|
+
}): Promise<QueryResult<T>>;
|
|
22
|
+
insert<T = any>(table: string, data: Record<string, any>): Promise<QueryResult<T>>;
|
|
23
|
+
update<T = any>(table: string, data: Record<string, any>, where: Record<string, any>): Promise<QueryResult<T>>;
|
|
24
|
+
delete<T = any>(table: string, where: Record<string, any>): Promise<number>;
|
|
25
|
+
close(): Promise<void>;
|
|
26
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { DatabaseDriver, QueryResult, TransactionCapable, PreparedStatementCapable, PreparedStatement } from '../types';
|
|
2
|
+
export interface SqliteConfig {
|
|
3
|
+
filename: string;
|
|
4
|
+
readonly?: boolean;
|
|
5
|
+
}
|
|
6
|
+
export declare class SqliteDriver implements DatabaseDriver, TransactionCapable, PreparedStatementCapable {
|
|
7
|
+
private client;
|
|
8
|
+
constructor(config: SqliteConfig);
|
|
9
|
+
query<T = any>(sql: string, params?: any[]): Promise<QueryResult<T>>;
|
|
10
|
+
transaction<T>(callback: (driver: DatabaseDriver) => Promise<T>): Promise<T>;
|
|
11
|
+
prepare(sql: string): Promise<PreparedStatement>;
|
|
12
|
+
findFirst<T = any>(table: string, where?: Record<string, any>): Promise<QueryResult<T> | null>;
|
|
13
|
+
findMany<T = any>(table: string, options?: {
|
|
14
|
+
where?: Record<string, any>;
|
|
15
|
+
limit?: number;
|
|
16
|
+
offset?: number;
|
|
17
|
+
}): Promise<QueryResult<T>>;
|
|
18
|
+
insert<T = any>(table: string, data: Record<string, any>): Promise<QueryResult<T>>;
|
|
19
|
+
update<T = any>(table: string, data: Record<string, any>, where: Record<string, any>): Promise<QueryResult<T>>;
|
|
20
|
+
delete(table: string, where: Record<string, any>): Promise<number>;
|
|
21
|
+
close(): Promise<void>;
|
|
22
|
+
exec(sql: string): void;
|
|
23
|
+
backup(filename: string): Promise<void>;
|
|
24
|
+
pragma(pragma: string): any;
|
|
25
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import type { DatabaseDriver, QueryResult } from './types';
|
|
2
|
+
export type { DatabaseDriver, QueryResult, QueryError, QueryField, ConnectionError } from './types';
|
|
3
|
+
export { PostgresDriver } from './drivers/postgres';
|
|
4
|
+
export { LibSQLDriver } from './drivers/libsql';
|
|
5
|
+
export { MySQLDriver } from './drivers/mysql';
|
|
6
|
+
export { SqliteDriver } from './drivers/sqlite';
|
|
7
|
+
export { inspectDB, inspectPostgres, inspectLibSQL, inspectMySQL, inspectSQLite } from './pull';
|
|
8
|
+
export interface ClientOptions<T extends DatabaseDriver = DatabaseDriver> {
|
|
9
|
+
driver: T;
|
|
10
|
+
fallbackDrivers?: DatabaseDriver[];
|
|
11
|
+
}
|
|
12
|
+
export declare class SQLClient<DT = any> {
|
|
13
|
+
private primaryDriver;
|
|
14
|
+
private fallbackDrivers;
|
|
15
|
+
constructor(options: ClientOptions);
|
|
16
|
+
query<T = any>(sql: string, params?: any[]): Promise<QueryResult<T>>;
|
|
17
|
+
transaction<T>(callback: (client: SQLClient<DT>) => Promise<T>): Promise<T>;
|
|
18
|
+
prepare(sql: string): Promise<import("./types").PreparedStatement>;
|
|
19
|
+
findFirst<K extends keyof DT>(table: K, where?: Partial<DT[K]>): Promise<DT[K] | null>;
|
|
20
|
+
findMany<K extends keyof DT>(table: K, options?: {
|
|
21
|
+
where?: Partial<DT[K]>;
|
|
22
|
+
limit?: number;
|
|
23
|
+
offset?: number;
|
|
24
|
+
}): Promise<DT[K][]>;
|
|
25
|
+
insert<K extends keyof DT>(table: K, data: Partial<DT[K]>): Promise<DT[K]>;
|
|
26
|
+
update<K extends keyof DT>(table: K, data: Partial<DT[K]>, where: Partial<DT[K]>): Promise<DT[K] | null>;
|
|
27
|
+
delete<K extends keyof DT>(table: K, where: Partial<DT[K]>): Promise<number>;
|
|
28
|
+
getDriver(): DatabaseDriver;
|
|
29
|
+
supportsTransactions(): boolean;
|
|
30
|
+
supportsPreparedStatements(): boolean;
|
|
31
|
+
close(): Promise<void>;
|
|
32
|
+
}
|
|
33
|
+
export declare function createPostgresClient<DT = any>(config: {
|
|
34
|
+
connectionString?: string;
|
|
35
|
+
experimental?: {
|
|
36
|
+
http?: {
|
|
37
|
+
url: string;
|
|
38
|
+
apiKey?: string;
|
|
39
|
+
};
|
|
40
|
+
};
|
|
41
|
+
}): SQLClient<DT>;
|
|
42
|
+
export declare function createLibSQLClient<DT = any>(config: {
|
|
43
|
+
url: string;
|
|
44
|
+
authToken?: string;
|
|
45
|
+
useTursoServerlessDriver?: boolean;
|
|
46
|
+
}): SQLClient<DT>;
|
|
47
|
+
export declare function createMySQLClient<DT = any>(config: {
|
|
48
|
+
connectionString: string;
|
|
49
|
+
}): SQLClient<DT>;
|
|
50
|
+
export declare function createSqliteClient<DT = any>(config: {
|
|
51
|
+
filename: string;
|
|
52
|
+
readonly?: boolean;
|
|
53
|
+
}): SQLClient<DT>;
|
|
54
|
+
export declare const DriftSQLClient: typeof SQLClient;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import consola2 from"consola";function hasTransactionSupport(driver){return"transaction"in driver&&typeof driver.transaction==="function"}function hasPreparedStatementSupport(driver){return"prepare"in driver&&typeof driver.prepare==="function"}class DatabaseError extends Error{driverType;originalError;constructor(message,driverType,originalError){super(message);this.driverType=driverType;this.originalError=originalError;this.name="DatabaseError"}}class QueryError extends DatabaseError{constructor(driverType,sql,originalError){super(`Query failed: ${sql}`,driverType,originalError);this.name="QueryError"}}class ConnectionError extends DatabaseError{constructor(driverType,originalError){super(`Failed to connect to ${driverType}`,driverType,originalError);this.name="ConnectionError"}}import postgres from"postgres";import ky from"ky";class PostgresDriver{client;constructor(config){try{if(config.experimental?.http){this.client=new PostgresHTTPDriver(config.experimental.http)}else{this.client=postgres(config.connectionString||"")}}catch(error){throw new ConnectionError("postgres",error)}}async query(sql,params){try{if(this.client instanceof PostgresHTTPDriver){return await this.client.query(sql,params)}const result=await this.client.unsafe(sql,params||[]);return{rows:result,rowCount:Array.isArray(result)?result.length:0,command:undefined}}catch(error){throw new QueryError("postgres",sql,error)}}async transaction(callback){if(this.client instanceof PostgresHTTPDriver){throw new Error("Transactions not supported with HTTP driver")}const result=await this.client.begin(async(sql)=>{const transactionDriver=new PostgresDriver({connectionString:""});transactionDriver.client=sql;return await callback(transactionDriver)});return result}async findFirst(table,where){const whereEntries=Object.entries(where||{});let sql=`SELECT * FROM ${table}`;let params=[];if(whereEntries.length>0){const whereClause=whereEntries.map((_,index)=>`${whereEntries[index]?.[0]} = $${index+1}`).join(" AND ");sql+=` WHERE ${whereClause}`;params=whereEntries.map(([,value])=>value)}sql+=" LIMIT 1";const result=await this.query(sql,params);return result.rows.length>0?result:null}async findMany(table,options){if(this.client instanceof PostgresHTTPDriver){return await this.client.findMany(table,options)}const{where,limit,offset}=options||{};const whereEntries=Object.entries(where||{});let sql=`SELECT * FROM ${table}`;let params=[];if(whereEntries.length>0){const whereClause=whereEntries.map((_,index)=>`${whereEntries[index]?.[0]} = $${index+1}`).join(" AND ");sql+=` WHERE ${whereClause}`;params=whereEntries.map(([,value])=>value)}if(typeof limit==="number"&&limit>0){sql+=` LIMIT $${params.length+1}`;params.push(limit)}if(typeof offset==="number"&&offset>0){sql+=` OFFSET $${params.length+1}`;params.push(offset)}return this.query(sql,params)}async insert(table,data){const tableName=String(table);const keys=Object.keys(data);const values=Object.values(data);if(keys.length===0){throw new Error("No data provided for insert")}const placeholders=keys.map((_,index)=>`$${index+1}`).join(", ");const sql=`INSERT INTO ${tableName} (${keys.join(", ")}) VALUES (${placeholders}) RETURNING *`;const result=await this.query(sql,values);if(!result.rows[0]){throw new Error("Insert failed: No data returned")}return result}async update(table,data,where){const tableName=String(table);const setEntries=Object.entries(data);const whereEntries=Object.entries(where);if(setEntries.length===0){throw new Error("No data provided for update")}if(whereEntries.length===0){throw new Error("No conditions provided for update")}const setClause=setEntries.map((_,index)=>`${setEntries[index]?.[0]} = $${index+1}`).join(", ");const whereClause=whereEntries.map((_,index)=>`${whereEntries[index]?.[0]} = $${setEntries.length+index+1}`).join(" AND ");const sql=`UPDATE ${tableName} SET ${setClause} WHERE ${whereClause} RETURNING *`;const params=[...setEntries.map(([,value])=>value),...whereEntries.map(([,value])=>value)];const result=await this.query(sql,params);return result.rows.length>0?result:result}async delete(table,where){const tableName=String(table);const whereEntries=Object.entries(where);if(whereEntries.length===0){throw new Error("No conditions provided for delete")}const whereClause=whereEntries.map((_,index)=>`${whereEntries[index]?.[0]} = $${index+1}`).join(" AND ");const sql=`DELETE FROM ${tableName} WHERE ${whereClause}`;const params=whereEntries.map(([,value])=>value);const result=await this.query(sql,params);return result.rowCount}async close(){try{if(this.client instanceof PostgresHTTPDriver){return await this.client.close()}await this.client.end()}catch(error){console.error("Error closing Postgres client:",error)}}}class PostgresHTTPDriver{httpClient;constructor(config){this.httpClient=ky.create({prefixUrl:config.url,headers:{Authorization:`Bearer ${config.apiKey||""}`}})}async query(sql,params){try{const response=await this.httpClient.post("query",{json:{query:sql,args:params}}).json();return{rows:response.rows,rowCount:response.rowCount,command:undefined}}catch(error){throw new QueryError("postgres-http",sql,error)}}async findFirst(table,where){const whereEntries=Object.entries(where||{});let sql=`SELECT * FROM ${table}`;let params=[];if(whereEntries.length>0){const whereClause=whereEntries.map((_,index)=>`${whereEntries[index]?.[0]} = $${index+1}`).join(" AND ");sql+=` WHERE ${whereClause}`;params=whereEntries.map(([,value])=>value)}sql+=" LIMIT 1";const result=await this.query(sql,params);return result.rows.length>0?result:null}async findMany(table,options){const{where,limit,offset}=options||{};const whereEntries=Object.entries(where||{});let sql=`SELECT * FROM ${table}`;let params=[];if(whereEntries.length>0){const whereClause=whereEntries.map((_,index)=>`${whereEntries[index]?.[0]} = $${index+1}`).join(" AND ");sql+=` WHERE ${whereClause}`;params=whereEntries.map(([,value])=>value)}if(typeof limit==="number"&&limit>0){sql+=` LIMIT $${params.length+1}`;params.push(limit)}if(typeof offset==="number"&&offset>0){sql+=` OFFSET $${params.length+1}`;params.push(offset)}return this.query(sql,params)}async insert(table,data){const tableName=String(table);const keys=Object.keys(data);const values=Object.values(data);if(keys.length===0){throw new Error("No data provided for insert")}const placeholders=keys.map((_,index)=>`$${index+1}`).join(", ");const sql=`INSERT INTO ${tableName} (${keys.join(", ")}) VALUES (${placeholders}) RETURNING *`;const result=await this.query(sql,values);if(!result.rows[0]){throw new Error("Insert failed: No data returned")}return result}async update(table,data,where){const tableName=String(table);const setEntries=Object.entries(data);const whereEntries=Object.entries(where);if(setEntries.length===0){throw new Error("No data provided for update")}if(whereEntries.length===0){throw new Error("No conditions provided for update")}const setClause=setEntries.map((_,index)=>`${setEntries[index]?.[0]} = $${index+1}`).join(", ");const whereClause=whereEntries.map((_,index)=>`${whereEntries[index]?.[0]} = $${setEntries.length+index+1}`).join(" AND ");const sql=`UPDATE ${tableName} SET ${setClause} WHERE ${whereClause} RETURNING *`;const params=[...setEntries.map(([,value])=>value),...whereEntries.map(([,value])=>value)];const result=await this.query(sql,params);return result.rows.length>0?result:result}async delete(table,where){const tableName=String(table);const whereEntries=Object.entries(where);if(whereEntries.length===0){throw new Error("No conditions provided for delete")}const whereClause=whereEntries.map((_,index)=>`${whereEntries[index]?.[0]} = $${index+1}`).join(" AND ");const sql=`DELETE FROM ${tableName} WHERE ${whereClause}`;const params=whereEntries.map(([,value])=>value);const result=await this.query(sql,params);return result.rowCount}async close(){return Promise.resolve()}}import{createClient}from"@libsql/client";import{createClient as tursoServerLessClient}from"@tursodatabase/serverless/compat";class LibSQLDriver{client;constructor(config){try{this.client=config.useTursoServerlessDriver?tursoServerLessClient({url:config.url,...config.authToken?{authToken:config.authToken}:{}}):createClient({url:config.url,...config.authToken?{authToken:config.authToken}:{}})}catch(error){throw new ConnectionError("libsql",error)}}async query(sql,params){try{const result=await this.client.execute(sql,params);return this.convertLibsqlResult(result)}catch(error){throw new QueryError("libsql",sql,error)}}async transaction(callback){const transactionDriver=new LibSQLDriver({url:"",authToken:""});transactionDriver.client=this.client;return await callback(transactionDriver)}async findFirst(table,where){const whereEntries=Object.entries(where||{});let sql=`SELECT * FROM ${table}`;let params=[];if(whereEntries.length>0){const whereClause=whereEntries.map((_,index)=>`${whereEntries[index]?.[0]} = ?`).join(" AND ");sql+=` WHERE ${whereClause}`;params=whereEntries.map(([,value])=>value)}sql+=" LIMIT 1";const result=await this.query(sql,params);return result.rows.length>0?result:null}async findMany(table,options){const{where,limit,offset}=options||{};const whereEntries=Object.entries(where||{});let sql=`SELECT * FROM ${table}`;let params=[];if(whereEntries.length>0){const whereClause=whereEntries.map((_,index)=>`${whereEntries[index]?.[0]} = ?`).join(" AND ");sql+=` WHERE ${whereClause}`;params=whereEntries.map(([,value])=>value)}if(typeof limit==="number"&&limit>0){sql+=` LIMIT ?`;params.push(limit)}if(typeof offset==="number"&&offset>0){sql+=` OFFSET ?`;params.push(offset)}return this.query(sql,params)}async insert(table,data){const tableName=String(table);const keys=Object.keys(data);const values=Object.values(data);if(keys.length===0){throw new Error("No data provided for insert")}const placeholders=keys.map(()=>"?").join(", ");const sql=`INSERT INTO ${tableName} (${keys.join(", ")}) VALUES (${placeholders})`;try{const result=await this.client.execute(sql,values);if(result.lastInsertRowid){try{const selectSql=`SELECT * FROM ${tableName} WHERE rowid = ?`;const insertedRow=await this.query(selectSql,[result.lastInsertRowid]);return{rows:insertedRow.rows,rowCount:result.rowsAffected||0,command:undefined,fields:insertedRow.fields}}catch{return{rows:[],rowCount:result.rowsAffected||0,command:undefined,fields:[]}}}return{rows:[],rowCount:result.rowsAffected||0,command:undefined,fields:[]}}catch(error){throw new QueryError("libsql",sql,error)}}async update(table,data,where){const tableName=String(table);const setEntries=Object.entries(data);const whereEntries=Object.entries(where);if(setEntries.length===0){throw new Error("No data provided for update")}if(whereEntries.length===0){throw new Error("No conditions provided for update")}const setClause=setEntries.map(([key])=>`${key} = ?`).join(", ");const whereClause=whereEntries.map(([key])=>`${key} = ?`).join(" AND ");const sql=`UPDATE ${tableName} SET ${setClause} WHERE ${whereClause}`;const params=[...setEntries.map(([,value])=>value),...whereEntries.map(([,value])=>value)];try{const result=await this.client.execute(sql,params);const selectSql=`SELECT * FROM ${tableName} WHERE ${whereClause}`;const selectParams=whereEntries.map(([,value])=>value);const updatedRows=await this.query(selectSql,selectParams);return{rows:updatedRows.rows,rowCount:result.rowsAffected||0,command:undefined,fields:updatedRows.fields}}catch(error){throw new QueryError("libsql",sql,error)}}async delete(table,where){const tableName=String(table);const whereEntries=Object.entries(where);if(whereEntries.length===0){throw new Error("No conditions provided for delete")}const whereClause=whereEntries.map(([key])=>`${key} = ?`).join(" AND ");const sql=`DELETE FROM ${tableName} WHERE ${whereClause}`;const params=whereEntries.map(([,value])=>value);try{const result=await this.client.execute(sql,params);return result.rowsAffected||0}catch(error){throw new QueryError("libsql",sql,error)}}async close(){try{this.client.close()}catch(error){console.error("Error closing LibSQL client:",error)}}convertLibsqlResult(result){const rows=result.rows.map((row)=>{const obj={};result.columns.forEach((col,index)=>{obj[col]=row[index]});return obj});return{rows,rowCount:result.rowsAffected||rows.length,command:undefined,fields:result.columns.map((col)=>({name:col,dataTypeID:0}))}}}import consola from"consola";import*as mysql from"mysql2/promise";class MySQLDriver{client;constructor(config){consola.warn("MySQL client is experimental and may not be compatible with the helper functions, since they originally designed for PostgreSQL and libsql. But .query() method should work.");try{this.client=mysql.createConnection(config.connectionString)}catch(error){throw new ConnectionError("mysql",error)}}async query(sql,params){try{const[rows,fields]=await(await this.client).execute(sql,params||[]);const rowCount=Array.isArray(rows)?rows.length:0;const normalizedFields=fields.map((field)=>({name:field.name,dataTypeID:field.columnType}));return{rows,rowCount,command:undefined,fields:normalizedFields}}catch(error){throw new QueryError("mysql",sql,error)}}async transaction(callback){const connection=await this.client;try{await connection.beginTransaction();const transactionDriver=new MySQLDriver({connectionString:""});transactionDriver.client=Promise.resolve(connection);const result=await callback(transactionDriver);await connection.commit();return result}catch(error){await connection.rollback();throw error}}async findFirst(table,where){const whereEntries=Object.entries(where||{});let sql=`SELECT * FROM ${table}`;let params=[];if(whereEntries.length>0){const whereClause=whereEntries.map(([key])=>`${key} = ?`).join(" AND ");sql+=` WHERE ${whereClause}`;params=whereEntries.map(([,value])=>value)}sql+=" LIMIT 1";const result=await this.query(sql,params);return result.rows.length>0?result:null}async findMany(table,options){const{where,limit,offset}=options||{};const whereEntries=Object.entries(where||{});let sql=`SELECT * FROM ${table}`;let params=[];if(whereEntries.length>0){const whereClause=whereEntries.map(([key])=>`${key} = ?`).join(" AND ");sql+=` WHERE ${whereClause}`;params=whereEntries.map(([,value])=>value)}if(typeof limit==="number"&&limit>0){sql+=` LIMIT ?`;params.push(limit)}if(typeof offset==="number"&&offset>0){sql+=` OFFSET ?`;params.push(offset)}return this.query(sql,params)}async insert(table,data){const tableName=String(table);const keys=Object.keys(data);const values=Object.values(data);if(keys.length===0){throw new Error("No data provided for insert")}const placeholders=keys.map(()=>"?").join(", ");const sql=`INSERT INTO ${tableName} (${keys.join(", ")}) VALUES (${placeholders})`;try{const connection=await this.client;const[result]=await connection.execute(sql,values);const insertResult=result;if(insertResult.insertId){try{const selectSql=`SELECT * FROM ${tableName} WHERE id = ?`;const insertedRow=await this.query(selectSql,[insertResult.insertId]);return{rows:insertedRow.rows,rowCount:insertResult.affectedRows||0,command:undefined,fields:insertedRow.fields}}catch{return{rows:[],rowCount:insertResult.affectedRows||0,command:undefined,fields:[]}}}return{rows:[],rowCount:insertResult.affectedRows||0,command:undefined,fields:[]}}catch(error){throw new QueryError("mysql",sql,error)}}async update(table,data,where){const tableName=String(table);const setEntries=Object.entries(data);const whereEntries=Object.entries(where);if(setEntries.length===0){throw new Error("No data provided for update")}if(whereEntries.length===0){throw new Error("No conditions provided for update")}const setClause=setEntries.map(([key])=>`${key} = ?`).join(", ");const whereClause=whereEntries.map(([key])=>`${key} = ?`).join(" AND ");const sql=`UPDATE ${tableName} SET ${setClause} WHERE ${whereClause}`;const params=[...setEntries.map(([,value])=>value),...whereEntries.map(([,value])=>value)];try{const connection=await this.client;const[result]=await connection.execute(sql,params);const selectSql=`SELECT * FROM ${tableName} WHERE ${whereClause}`;const selectParams=whereEntries.map(([,value])=>value);const updatedRows=await this.query(selectSql,selectParams);const updateResult=result;return{rows:updatedRows.rows,rowCount:updateResult.affectedRows||0,command:undefined,fields:updatedRows.fields}}catch(error){throw new QueryError("mysql",sql,error)}}async delete(table,where){const tableName=String(table);const whereEntries=Object.entries(where);if(whereEntries.length===0){throw new Error("No conditions provided for delete")}const whereClause=whereEntries.map(([key])=>`${key} = ?`).join(" AND ");const sql=`DELETE FROM ${tableName} WHERE ${whereClause}`;const params=whereEntries.map(([,value])=>value);try{const connection=await this.client;const[result]=await connection.execute(sql,params);const deleteResult=result;return deleteResult.affectedRows||0}catch(error){throw new QueryError("mysql",sql,error)}}async close(){try{await(await this.client).end()}catch(error){consola.error("Error closing MySQL client:",error)}}}import Database from"better-sqlite3";class SqliteDriver{client;constructor(config){try{this.client=new Database(config.filename,{readonly:config.readonly||false,fileMustExist:config.readonly||false})}catch(error){throw new ConnectionError("sqlite",error)}}async query(sql,params){try{const stmt=this.client.prepare(sql);const rows=stmt.all(params||[]);const fields=rows.length>0&&typeof rows[0]==="object"&&rows[0]!==null?Object.keys(rows[0]).map((name)=>({name,dataTypeID:0})):[];return{rows,rowCount:rows.length,command:undefined,fields}}catch(error){throw new QueryError("sqlite",sql,error)}}async transaction(callback){const transaction=this.client.transaction(()=>{const transactionDriver=new SqliteDriver({filename:""});transactionDriver.client=this.client;return callback(transactionDriver)});return await transaction()}async prepare(sql){return new SqlitePreparedStatement(this.client.prepare(sql))}async findFirst(table,where){const whereEntries=Object.entries(where||{});let sql=`SELECT * FROM ${table}`;let params=[];if(whereEntries.length>0){const whereClause=whereEntries.map((_,index)=>`${whereEntries[index]?.[0]} = ?`).join(" AND ");sql+=` WHERE ${whereClause}`;params=whereEntries.map(([,value])=>value)}sql+=" LIMIT 1";const result=await this.query(sql,params);return result.rows.length>0?result:null}async findMany(table,options){const{where,limit,offset}=options||{};const whereEntries=Object.entries(where||{});let sql=`SELECT * FROM ${table}`;let params=[];if(whereEntries.length>0){const whereClause=whereEntries.map((_,index)=>`${whereEntries[index]?.[0]} = ?`).join(" AND ");sql+=` WHERE ${whereClause}`;params=whereEntries.map(([,value])=>value)}if(typeof limit==="number"&&limit>0){sql+=` LIMIT ?`;params.push(limit)}if(typeof offset==="number"&&offset>0){sql+=` OFFSET ?`;params.push(offset)}return this.query(sql,params)}async insert(table,data){const tableName=String(table);const keys=Object.keys(data);const values=Object.values(data);if(keys.length===0){throw new Error("No data provided for insert")}const placeholders=keys.map(()=>"?").join(", ");const sql=`INSERT INTO ${tableName} (${keys.join(", ")}) VALUES (${placeholders})`;try{const stmt=this.client.prepare(sql);const result=stmt.run(values);if(result.lastInsertRowid){const selectSql=`SELECT * FROM ${tableName} WHERE rowid = ?`;const insertedRow=await this.query(selectSql,[result.lastInsertRowid]);return{rows:insertedRow.rows,rowCount:result.changes,command:undefined,fields:insertedRow.fields}}return{rows:[],rowCount:result.changes,command:undefined,fields:[]}}catch(error){throw new QueryError("sqlite",sql,error)}}async update(table,data,where){const tableName=String(table);const setEntries=Object.entries(data);const whereEntries=Object.entries(where);if(setEntries.length===0){throw new Error("No data provided for update")}if(whereEntries.length===0){throw new Error("No conditions provided for update")}const setClause=setEntries.map(([key])=>`${key} = ?`).join(", ");const whereClause=whereEntries.map(([key])=>`${key} = ?`).join(" AND ");const sql=`UPDATE ${tableName} SET ${setClause} WHERE ${whereClause}`;const params=[...setEntries.map(([,value])=>value),...whereEntries.map(([,value])=>value)];try{const stmt=this.client.prepare(sql);const result=stmt.run(params);const selectSql=`SELECT * FROM ${tableName} WHERE ${whereClause}`;const selectParams=whereEntries.map(([,value])=>value);const updatedRows=await this.query(selectSql,selectParams);return{rows:updatedRows.rows,rowCount:result.changes,command:undefined,fields:updatedRows.fields}}catch(error){throw new QueryError("sqlite",sql,error)}}async delete(table,where){const tableName=String(table);const whereEntries=Object.entries(where);if(whereEntries.length===0){throw new Error("No conditions provided for delete")}const whereClause=whereEntries.map(([key])=>`${key} = ?`).join(" AND ");const sql=`DELETE FROM ${tableName} WHERE ${whereClause}`;const params=whereEntries.map(([,value])=>value);try{const stmt=this.client.prepare(sql);const result=stmt.run(params);return result.changes}catch(error){throw new QueryError("sqlite",sql,error)}}async close(){try{this.client.close()}catch(error){console.error("Error closing SQLite client:",error)}}exec(sql){this.client.exec(sql)}backup(filename){return new Promise((resolve,reject)=>{try{this.client.backup(filename);resolve()}catch(error){reject(error)}})}pragma(pragma){return this.client.pragma(pragma)}}class SqlitePreparedStatement{stmt;constructor(stmt){this.stmt=stmt}async execute(params){try{const rows=this.stmt.all(params||[]);const fields=rows.length>0&&typeof rows[0]==="object"&&rows[0]!==null?Object.keys(rows[0]).map((name)=>({name,dataTypeID:0})):[];return{rows,rowCount:rows.length,command:undefined,fields}}catch(error){throw new QueryError("sqlite","prepared statement",error)}}async finalize(){return Promise.resolve()}run(params){return this.stmt.run(params||[])}get(params){return this.stmt.get(params||[])}all(params){return this.stmt.all(params||[])}}import fs from"node:fs/promises";var withTimeout=(promise,timeoutMs=30000)=>{return Promise.race([promise,new Promise((_,reject)=>setTimeout(()=>reject(new Error(`Query timeout after ${timeoutMs}ms`)),timeoutMs))])};var retryQuery=async(queryFn,maxRetries=3,baseDelay=1000)=>{for(let attempt=1;attempt<=maxRetries;attempt++){try{return await queryFn()}catch(error){if(attempt===maxRetries){throw error}const delay=baseDelay*Math.pow(2,attempt-1);console.warn(`Query attempt ${attempt} failed, retrying in ${delay}ms...`,error);await new Promise((resolve)=>setTimeout(resolve,delay))}}throw new Error("Max retries exceeded")};var mapDatabaseTypeToTypeScript=(dataType,isNullable=false,driverType="postgres")=>{const nullable=isNullable?" | null":"";const lowerType=dataType.toLowerCase();switch(lowerType){case"uuid":{return`string${nullable}`}case"character varying":case"varchar":case"text":case"char":case"character":case"longtext":case"mediumtext":case"tinytext":{return`string${nullable}`}case"integer":case"int":case"int4":case"smallint":case"int2":case"bigint":case"int8":case"serial":case"bigserial":case"numeric":case"decimal":case"real":case"float4":case"double precision":case"float8":case"tinyint":case"mediumint":case"float":case"double":{return`number${nullable}`}case"boolean":case"bool":case"bit":{return`boolean${nullable}`}case"timestamp":case"timestamp with time zone":case"timestamp without time zone":case"timestamptz":case"date":case"time":case"time with time zone":case"time without time zone":case"timetz":case"interval":case"datetime":case"year":{return`Date${nullable}`}case"json":case"jsonb":{return`any${nullable}`}case"array":{return`any[]${nullable}`}case"bytea":case"binary":case"varbinary":case"blob":case"longblob":case"mediumblob":case"tinyblob":{return`Buffer${nullable}`}case"enum":case"set":{return`string${nullable}`}default:{console.warn(`Unknown ${driverType} type: ${dataType}, defaulting to 'any'`);return`any${nullable}`}}};var getDriverType=(driver)=>{if(driver instanceof PostgresDriver)return"postgres";if(driver instanceof LibSQLDriver)return"libsql";if(driver instanceof MySQLDriver)return"mysql";if(driver instanceof SqliteDriver)return"sqlite";return"unknown"};var inspectDB=async(options)=>{const{driver,outputFile="db-types.ts"}=options;const driverType=getDriverType(driver);console.log(`Inspecting database using ${driverType} driver`);const client=new SQLClient({driver});let generatedTypes="";try{let tablesQuery;let tableSchemaFilter;if(driverType==="mysql"){const dbResult=await withTimeout(retryQuery(()=>client.query("SELECT DATABASE() as `database`",[])),1e4);const currentDatabase=dbResult.rows[0]?.database;if(!currentDatabase){throw new Error("Could not determine current MySQL database name")}console.log(`Using MySQL database: ${currentDatabase}`);tablesQuery=`SELECT TABLE_NAME as table_name
|
|
2
|
+
FROM information_schema.tables
|
|
3
|
+
WHERE TABLE_SCHEMA = ?
|
|
4
|
+
AND TABLE_TYPE = 'BASE TABLE'
|
|
5
|
+
ORDER BY TABLE_NAME`;tableSchemaFilter=currentDatabase}else if(driverType==="postgres"){tablesQuery=`SELECT table_name
|
|
6
|
+
FROM information_schema.tables
|
|
7
|
+
WHERE table_schema = $1
|
|
8
|
+
AND table_type = 'BASE TABLE'
|
|
9
|
+
ORDER BY table_name`;tableSchemaFilter="public"}else if(driverType==="libsql"||driverType==="sqlite"){tablesQuery=`SELECT name as table_name
|
|
10
|
+
FROM sqlite_master
|
|
11
|
+
WHERE type = 'table'
|
|
12
|
+
ORDER BY name`;tableSchemaFilter=undefined}else{throw new Error(`Unsupported driver type: ${driverType}`)}const tables=await withTimeout(retryQuery(()=>client.query(tablesQuery,tableSchemaFilter?[tableSchemaFilter]:[])),30000);console.log("Tables in the database:",tables.rows.map((t)=>t.table_name).join(", "));let processedTables=0;const totalTables=tables.rows.length;for(const table of tables.rows){const tableName=table.table_name;processedTables++;console.log(`[${processedTables}/${totalTables}] Inspecting table: ${tableName}`);try{let columnsQuery;let queryParams;if(driverType==="mysql"){columnsQuery=`
|
|
13
|
+
SELECT
|
|
14
|
+
COLUMN_NAME as column_name,
|
|
15
|
+
DATA_TYPE as data_type,
|
|
16
|
+
IS_NULLABLE as is_nullable,
|
|
17
|
+
COLUMN_DEFAULT as column_default
|
|
18
|
+
FROM information_schema.columns
|
|
19
|
+
WHERE TABLE_NAME = ?
|
|
20
|
+
AND TABLE_SCHEMA = ?
|
|
21
|
+
ORDER BY ORDINAL_POSITION
|
|
22
|
+
`;queryParams=[tableName,tableSchemaFilter]}else if(driverType==="postgres"){columnsQuery=`
|
|
23
|
+
SELECT
|
|
24
|
+
column_name,
|
|
25
|
+
data_type,
|
|
26
|
+
is_nullable,
|
|
27
|
+
column_default
|
|
28
|
+
FROM information_schema.columns
|
|
29
|
+
WHERE table_name = $1
|
|
30
|
+
AND table_schema = $2
|
|
31
|
+
ORDER BY ordinal_position
|
|
32
|
+
`;queryParams=[tableName,tableSchemaFilter]}else{columnsQuery=`
|
|
33
|
+
SELECT
|
|
34
|
+
name as column_name,
|
|
35
|
+
type as data_type,
|
|
36
|
+
CASE WHEN "notnull" = 0 THEN 'YES' ELSE 'NO' END as is_nullable,
|
|
37
|
+
dflt_value as column_default
|
|
38
|
+
FROM pragma_table_info(?)
|
|
39
|
+
ORDER BY cid
|
|
40
|
+
`;queryParams=[tableName]}const columns=await withTimeout(retryQuery(()=>client.query(columnsQuery,queryParams)),15000);if(columns.rows.length===0){console.log(`No columns found for table: ${tableName}`);continue}console.log(`Columns in ${tableName}:`,columns.rows.map((c)=>`${c.column_name} (${c.data_type}${c.is_nullable==="YES"?", nullable":""})`).join(", "));const uniqueColumns=new Map;columns.rows.forEach((col)=>{if(!uniqueColumns.has(col.column_name)){uniqueColumns.set(col.column_name,col)}});generatedTypes+=`export interface ${tableName.charAt(0).toUpperCase()+tableName.slice(1)} {
|
|
41
|
+
`;for(const col of uniqueColumns.values()){const tsType=mapDatabaseTypeToTypeScript(col.data_type,col.is_nullable==="YES",driverType);generatedTypes+=` ${col.column_name}: ${tsType};
|
|
42
|
+
`}generatedTypes+=`}
|
|
43
|
+
|
|
44
|
+
`}catch(error){console.error(`Failed to process table ${tableName}:`,error);console.log(`Skipping table ${tableName} and continuing...`);continue}}generatedTypes+=`export interface Database {
|
|
45
|
+
`;for(const table of tables.rows){const interfaceName=table.table_name.charAt(0).toUpperCase()+table.table_name.slice(1);generatedTypes+=` ${table.table_name}: ${interfaceName};
|
|
46
|
+
`}generatedTypes+=`}
|
|
47
|
+
|
|
48
|
+
`;await fs.writeFile(outputFile,generatedTypes,"utf8");console.log(`TypeScript types written to ${outputFile}`);console.log(`Successfully processed ${processedTables} tables`)}catch(error){console.error("Fatal error during database inspection:",error);throw error}finally{await client.close()}};var inspectPostgres=async(config,outputFile)=>{const driver=new PostgresDriver(config);return inspectDB({driver,outputFile})};var inspectLibSQL=async(config,outputFile)=>{const driver=new LibSQLDriver(config);return inspectDB({driver,outputFile})};var inspectMySQL=async(config,outputFile)=>{const driver=new MySQLDriver(config);return inspectDB({driver,outputFile})};var inspectSQLite=async(config,outputFile)=>{const driver=new SqliteDriver(config);return inspectDB({driver,outputFile})};class SQLClient{primaryDriver;fallbackDrivers;constructor(options){this.primaryDriver=options.driver;this.fallbackDrivers=options.fallbackDrivers||[]}async query(sql,params){const drivers=[this.primaryDriver,...this.fallbackDrivers];let lastError;for(const driver of drivers){try{return await driver.query(sql,params)}catch(error){lastError=error;consola2.warn(`Query failed with ${driver.constructor.name}:`,error);continue}}throw lastError||new DatabaseError("All drivers failed to execute query","unknown")}async transaction(callback){if(!hasTransactionSupport(this.primaryDriver)){throw new DatabaseError("Primary driver does not support transactions",this.primaryDriver.constructor.name)}return await this.primaryDriver.transaction(async(transactionDriver)=>{const transactionClient=new SQLClient({driver:transactionDriver,fallbackDrivers:[]});return await callback(transactionClient)})}async prepare(sql){if(!hasPreparedStatementSupport(this.primaryDriver)){throw new DatabaseError("Primary driver does not support prepared statements",this.primaryDriver.constructor.name)}return await this.primaryDriver.prepare(sql)}async findFirst(table,where){if(!this.primaryDriver.findFirst)throw new DatabaseError("Primary driver does not support findFirst",this.primaryDriver.constructor.name);try{const response=await this.primaryDriver.findFirst(table,where);return response.rows[0]||null}catch(error){throw new QueryError("findFirst",`Error finding first in ${String(table)}`,error)}}async findMany(table,options){if(!this.primaryDriver.findMany)throw new DatabaseError("Primary driver does not support findMany",this.primaryDriver.constructor.name);try{const response=await this.primaryDriver.findMany(table,options);return response.rows}catch(error){throw new QueryError("findMany",`Error finding many in ${String(table)}`,error)}}async insert(table,data){if(!this.primaryDriver.insert)throw new DatabaseError("Primary driver does not support insert",this.primaryDriver.constructor.name);try{const response=await this.primaryDriver.insert(table,data);return response.rows[0]}catch(error){throw new QueryError("insert",`Error inserting into ${String(table)}`,error)}}async update(table,data,where){if(!this.primaryDriver.update)throw new DatabaseError("Primary driver does not support update",this.primaryDriver.constructor.name);try{const response=await this.primaryDriver.update(table,data,where);return response.rows[0]||null}catch(error){throw new QueryError("update",`Error updating ${String(table)}`,error)}}async delete(table,where){if(!this.primaryDriver.delete)throw new DatabaseError("Primary driver does not support delete",this.primaryDriver.constructor.name);try{const affectedRows=await this.primaryDriver.delete(table,where);return affectedRows}catch(error){throw new QueryError("delete",`Error deleting from ${String(table)}`,error)}}getDriver(){return this.primaryDriver}supportsTransactions(){return hasTransactionSupport(this.primaryDriver)}supportsPreparedStatements(){return hasPreparedStatementSupport(this.primaryDriver)}async close(){const drivers=[this.primaryDriver,...this.fallbackDrivers];await Promise.all(drivers.map((driver)=>driver.close().catch((err)=>consola2.warn(`Error closing ${driver.constructor.name}:`,err))))}}function createPostgresClient(config){return new SQLClient({driver:new PostgresDriver(config)})}function createLibSQLClient(config){return new SQLClient({driver:new LibSQLDriver(config)})}function createMySQLClient(config){return new SQLClient({driver:new MySQLDriver(config)})}function createSqliteClient(config){return new SQLClient({driver:new SqliteDriver(config)})}var DriftSQLClient=SQLClient;export{inspectSQLite,inspectPostgres,inspectMySQL,inspectLibSQL,inspectDB,createSqliteClient,createPostgresClient,createMySQLClient,createLibSQLClient,SqliteDriver,SQLClient,PostgresDriver,MySQLDriver,LibSQLDriver,DriftSQLClient};
|
package/dist/pull.d.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { DatabaseDriver } from './types';
|
|
2
|
+
interface InspectOptions {
|
|
3
|
+
driver: DatabaseDriver;
|
|
4
|
+
outputFile?: string;
|
|
5
|
+
}
|
|
6
|
+
export declare const inspectDB: (options: InspectOptions) => Promise<void>;
|
|
7
|
+
export declare const inspectPostgres: (config: {
|
|
8
|
+
connectionString?: string;
|
|
9
|
+
experimental?: {
|
|
10
|
+
http?: {
|
|
11
|
+
url: string;
|
|
12
|
+
apiKey?: string;
|
|
13
|
+
};
|
|
14
|
+
};
|
|
15
|
+
}, outputFile?: string) => Promise<void>;
|
|
16
|
+
export declare const inspectLibSQL: (config: {
|
|
17
|
+
url: string;
|
|
18
|
+
authToken?: string;
|
|
19
|
+
useTursoServerlessDriver?: boolean;
|
|
20
|
+
}, outputFile?: string) => Promise<void>;
|
|
21
|
+
export declare const inspectMySQL: (config: {
|
|
22
|
+
connectionString: string;
|
|
23
|
+
}, outputFile?: string) => Promise<void>;
|
|
24
|
+
export declare const inspectSQLite: (config: {
|
|
25
|
+
filename: string;
|
|
26
|
+
readonly?: boolean;
|
|
27
|
+
}, outputFile?: string) => Promise<void>;
|
|
28
|
+
export default inspectDB;
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
export interface QueryResult<T = any> {
|
|
2
|
+
rows: T[];
|
|
3
|
+
rowCount: number;
|
|
4
|
+
command?: string;
|
|
5
|
+
fields?: QueryField[];
|
|
6
|
+
}
|
|
7
|
+
export interface QueryField {
|
|
8
|
+
name: string;
|
|
9
|
+
dataTypeID: number;
|
|
10
|
+
}
|
|
11
|
+
export interface DatabaseDriver {
|
|
12
|
+
query<T = any>(sql: string, params?: any[]): Promise<QueryResult<T>>;
|
|
13
|
+
findFirst?(table: string, where?: Record<string, any>): Promise<QueryResult<any> | null>;
|
|
14
|
+
findMany?(table: string, options?: {
|
|
15
|
+
where?: Record<string, any>;
|
|
16
|
+
limit?: number;
|
|
17
|
+
offset?: number;
|
|
18
|
+
}): Promise<QueryResult<any>>;
|
|
19
|
+
insert?(table: string, data: Record<string, any>): Promise<QueryResult<any>>;
|
|
20
|
+
update?(table: string, data: Record<string, any>, where: Record<string, any>): Promise<QueryResult<any>>;
|
|
21
|
+
delete?(table: string, where: Record<string, any>): Promise<number>;
|
|
22
|
+
close(): Promise<void>;
|
|
23
|
+
}
|
|
24
|
+
export interface TransactionCapable {
|
|
25
|
+
transaction<T>(callback: (driver: DatabaseDriver) => Promise<T>): Promise<T>;
|
|
26
|
+
}
|
|
27
|
+
export interface PreparedStatementCapable {
|
|
28
|
+
prepare(sql: string): Promise<PreparedStatement>;
|
|
29
|
+
}
|
|
30
|
+
export interface PreparedStatement {
|
|
31
|
+
execute<T = any>(params?: any[]): Promise<QueryResult<T>>;
|
|
32
|
+
finalize(): Promise<void>;
|
|
33
|
+
}
|
|
34
|
+
export declare function hasTransactionSupport(driver: DatabaseDriver): driver is DatabaseDriver & TransactionCapable;
|
|
35
|
+
export declare function hasPreparedStatementSupport(driver: DatabaseDriver): driver is DatabaseDriver & PreparedStatementCapable;
|
|
36
|
+
export declare class DatabaseError extends Error {
|
|
37
|
+
readonly driverType: string;
|
|
38
|
+
readonly originalError?: Error | undefined;
|
|
39
|
+
constructor(message: string, driverType: string, originalError?: Error | undefined);
|
|
40
|
+
}
|
|
41
|
+
export declare class QueryError extends DatabaseError {
|
|
42
|
+
constructor(driverType: string, sql: string, originalError?: Error);
|
|
43
|
+
}
|
|
44
|
+
export declare class ConnectionError extends DatabaseError {
|
|
45
|
+
constructor(driverType: string, originalError?: Error);
|
|
46
|
+
}
|
|
47
|
+
export interface DriverOptions {
|
|
48
|
+
[key: string]: any;
|
|
49
|
+
}
|
package/package.json
CHANGED
|
@@ -1,16 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "driftsql",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.21",
|
|
4
|
+
"main": "dist/index.js",
|
|
4
5
|
"description": "A lightweight SQL client for TypeScript",
|
|
5
6
|
"scripts": {
|
|
6
|
-
"build": "
|
|
7
|
-
"dev": "vitest dev",
|
|
8
|
-
"lint": "eslint . && prettier -c .",
|
|
9
|
-
"lint:fix": "automd && eslint . --fix && prettier -w .",
|
|
10
|
-
"prepack": "pnpm build",
|
|
11
|
-
"release": "pnpm test && changelogen --release && npm publish && git push --follow-tags",
|
|
12
|
-
"test": "pnpm lint && pnpm test:types && vitest run --coverage",
|
|
13
|
-
"test:types": "tsc --noEmit --skipLibCheck"
|
|
7
|
+
"build": "bun build.ts"
|
|
14
8
|
},
|
|
15
9
|
"author": "lasse vestergaard",
|
|
16
10
|
"license": "MIT",
|
|
@@ -22,7 +16,7 @@
|
|
|
22
16
|
"@types/pg": "^8.15.4",
|
|
23
17
|
"better-sqlite3": "^12.2.0",
|
|
24
18
|
"consola": "^3.4.2",
|
|
25
|
-
"driftsql": "^
|
|
19
|
+
"driftsql": "^1.0.19",
|
|
26
20
|
"drizzle-orm": "^0.44.2",
|
|
27
21
|
"ky": "^1.8.1",
|
|
28
22
|
"mysql2": "^3.14.1",
|
|
@@ -42,11 +36,5 @@
|
|
|
42
36
|
"typescript": "^5.8.3",
|
|
43
37
|
"unbuild": "^3.5.0",
|
|
44
38
|
"vitest": "^3.2.4"
|
|
45
|
-
},
|
|
46
|
-
"unbuild": {
|
|
47
|
-
"entries": [
|
|
48
|
-
"./src/index"
|
|
49
|
-
],
|
|
50
|
-
"outDir": "dist"
|
|
51
39
|
}
|
|
52
40
|
}
|
package/tsconfig.json
CHANGED
|
@@ -1,20 +1,34 @@
|
|
|
1
1
|
{
|
|
2
2
|
"compilerOptions": {
|
|
3
|
+
// Enable latest features
|
|
4
|
+
"lib": ["ESNext", "DOM", "DOM.Iterable"],
|
|
3
5
|
"target": "ESNext",
|
|
4
6
|
"module": "Preserve",
|
|
5
|
-
"moduleResolution": "bundler",
|
|
6
7
|
"moduleDetection": "force",
|
|
7
|
-
"esModuleInterop": true,
|
|
8
|
-
"allowSyntheticDefaultImports": true,
|
|
9
|
-
"allowJs": true,
|
|
10
8
|
"resolveJsonModule": true,
|
|
11
|
-
"strict": true,
|
|
12
9
|
"isolatedModules": true,
|
|
13
|
-
"
|
|
14
|
-
"
|
|
15
|
-
|
|
10
|
+
"jsx": "react-jsx",
|
|
11
|
+
"allowJs": true,
|
|
12
|
+
// Bundler mode
|
|
13
|
+
"moduleResolution": "bundler",
|
|
16
14
|
"allowImportingTsExtensions": true,
|
|
15
|
+
"verbatimModuleSyntax": true,
|
|
16
|
+
// Best practices
|
|
17
|
+
"strict": true,
|
|
18
|
+
"skipLibCheck": true,
|
|
19
|
+
"noFallthroughCasesInSwitch": true,
|
|
20
|
+
// Some stricter flags (disabled by default)
|
|
21
|
+
"noUnusedLocals": false,
|
|
22
|
+
"noImplicitAny": true,
|
|
17
23
|
"noImplicitOverride": true,
|
|
18
|
-
"
|
|
19
|
-
|
|
24
|
+
"noImplicitThis": true,
|
|
25
|
+
"noUnusedParameters": false,
|
|
26
|
+
"noPropertyAccessFromIndexSignature": false,
|
|
27
|
+
// Output declarations
|
|
28
|
+
"declaration": true,
|
|
29
|
+
"declarationDir": "dist",
|
|
30
|
+
"emitDeclarationOnly": true,
|
|
31
|
+
"stripInternal": true
|
|
32
|
+
},
|
|
33
|
+
"include": ["src"]
|
|
20
34
|
}
|
package/src/drivers/bobsql.ts
DELETED
|
@@ -1,43 +0,0 @@
|
|
|
1
|
-
import type { DatabaseDriver, QueryResult } from '../types'
|
|
2
|
-
import ky from 'ky'
|
|
3
|
-
|
|
4
|
-
export interface BobSQLConfig {
|
|
5
|
-
url: string
|
|
6
|
-
authToken?: string
|
|
7
|
-
}
|
|
8
|
-
|
|
9
|
-
export class BobSQLDriver implements DatabaseDriver {
|
|
10
|
-
private httpClient: typeof ky
|
|
11
|
-
|
|
12
|
-
constructor(config: BobSQLConfig) {
|
|
13
|
-
this.httpClient = ky.create({
|
|
14
|
-
prefixUrl: config.url,
|
|
15
|
-
...(config.authToken ? { headers: { Authorization: `Bearer ${config.authToken}` } } : {}),
|
|
16
|
-
})
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
async query<T = any>(sql: string, params?: any[]): Promise<QueryResult<T>> {
|
|
20
|
-
try {
|
|
21
|
-
if (params) {
|
|
22
|
-
throw new Error('BobSQL does not support args at this moment.')
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
const response = await this.httpClient
|
|
26
|
-
.post('query', {
|
|
27
|
-
json: { sql },
|
|
28
|
-
})
|
|
29
|
-
.json<{ rows: T[] }>()
|
|
30
|
-
|
|
31
|
-
return {
|
|
32
|
-
rows: response.rows,
|
|
33
|
-
rowCount: response.rows.length,
|
|
34
|
-
}
|
|
35
|
-
} catch (error) {
|
|
36
|
-
throw new Error(`Query failed: ${error}`)
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
async close(): Promise<void> {
|
|
41
|
-
return Promise.resolve()
|
|
42
|
-
}
|
|
43
|
-
}
|
package/src/drivers/libsql.ts
DELETED
|
@@ -1,70 +0,0 @@
|
|
|
1
|
-
import { createClient, type ResultSet } from '@libsql/client'
|
|
2
|
-
import { createClient as tursoServerLessClient, type ResultSet as tursoServerLessResultSet } from '@tursodatabase/serverless/compat'
|
|
3
|
-
import type { DatabaseDriver, QueryResult, TransactionCapable } from '../types'
|
|
4
|
-
import { QueryError, ConnectionError } from '../types'
|
|
5
|
-
|
|
6
|
-
export interface LibSQLConfig {
|
|
7
|
-
url: string
|
|
8
|
-
authToken?: string
|
|
9
|
-
useTursoServerlessDriver?: boolean
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
export class LibSQLDriver implements DatabaseDriver, TransactionCapable {
|
|
13
|
-
private client: ReturnType<typeof createClient> | ReturnType<typeof tursoServerLessClient>
|
|
14
|
-
|
|
15
|
-
constructor(config: LibSQLConfig) {
|
|
16
|
-
try {
|
|
17
|
-
this.client = config.useTursoServerlessDriver
|
|
18
|
-
? tursoServerLessClient({
|
|
19
|
-
url: config.url,
|
|
20
|
-
...(config.authToken ? { authToken: config.authToken } : {}),
|
|
21
|
-
})
|
|
22
|
-
: createClient({
|
|
23
|
-
url: config.url,
|
|
24
|
-
...(config.authToken ? { authToken: config.authToken } : {}),
|
|
25
|
-
})
|
|
26
|
-
} catch (error) {
|
|
27
|
-
throw new ConnectionError('libsql', error as Error)
|
|
28
|
-
}
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
async query<T = any>(sql: string, params?: any[]): Promise<QueryResult<T>> {
|
|
32
|
-
try {
|
|
33
|
-
const result = await this.client.execute(sql, params)
|
|
34
|
-
return this.convertLibsqlResult<T>(result)
|
|
35
|
-
} catch (error) {
|
|
36
|
-
throw new QueryError('libsql', sql, error as Error)
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
async transaction<T>(callback: (driver: DatabaseDriver) => Promise<T>): Promise<T> {
|
|
41
|
-
const transactionDriver = new LibSQLDriver({ url: '', authToken: '' })
|
|
42
|
-
;(transactionDriver as any).client = this.client
|
|
43
|
-
return await callback(transactionDriver)
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
async close(): Promise<void> {
|
|
47
|
-
try {
|
|
48
|
-
this.client.close()
|
|
49
|
-
} catch (error) {
|
|
50
|
-
console.error('Error closing LibSQL client:', error)
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
private convertLibsqlResult<T = any>(result: ResultSet | tursoServerLessResultSet): QueryResult<T> {
|
|
55
|
-
const rows = result.rows.map((row) => {
|
|
56
|
-
const obj: Record<string, any> = {}
|
|
57
|
-
result.columns.forEach((col, index) => {
|
|
58
|
-
obj[col] = row[index]
|
|
59
|
-
})
|
|
60
|
-
return obj as T
|
|
61
|
-
})
|
|
62
|
-
|
|
63
|
-
return {
|
|
64
|
-
rows,
|
|
65
|
-
rowCount: result.rowsAffected || rows.length,
|
|
66
|
-
command: undefined,
|
|
67
|
-
fields: result.columns.map((col) => ({ name: col, dataTypeID: 0 })),
|
|
68
|
-
}
|
|
69
|
-
}
|
|
70
|
-
}
|
package/src/drivers/mysql.ts
DELETED
|
@@ -1,70 +0,0 @@
|
|
|
1
|
-
import consola from 'consola'
|
|
2
|
-
import * as mysql from 'mysql2/promise'
|
|
3
|
-
import type { DatabaseDriver, QueryResult, TransactionCapable } from '../types'
|
|
4
|
-
import { QueryError, ConnectionError } from '../types'
|
|
5
|
-
|
|
6
|
-
export interface MySQLConfig {
|
|
7
|
-
connectionString: string
|
|
8
|
-
}
|
|
9
|
-
|
|
10
|
-
export class MySQLDriver implements DatabaseDriver, TransactionCapable {
|
|
11
|
-
private client: ReturnType<typeof mysql.createConnection>
|
|
12
|
-
|
|
13
|
-
constructor(config: MySQLConfig) {
|
|
14
|
-
consola.warn('MySQL client is experimental and may not be compatible with the helper functions, since they originally designed for PostgreSQL and libsql. But .query() method should work.')
|
|
15
|
-
|
|
16
|
-
try {
|
|
17
|
-
this.client = mysql.createConnection(config.connectionString)
|
|
18
|
-
} catch (error) {
|
|
19
|
-
throw new ConnectionError('mysql', error as Error)
|
|
20
|
-
}
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
async query<T = any>(sql: string, params?: any[]): Promise<QueryResult<T>> {
|
|
24
|
-
try {
|
|
25
|
-
const [rows, fields] = await (await this.client).execute(sql, params || [])
|
|
26
|
-
const rowCount = Array.isArray(rows) ? rows.length : 0
|
|
27
|
-
|
|
28
|
-
const normalizedFields = fields.map((field: any) => ({
|
|
29
|
-
name: field.name,
|
|
30
|
-
dataTypeID: field.columnType,
|
|
31
|
-
}))
|
|
32
|
-
|
|
33
|
-
return {
|
|
34
|
-
rows: rows as T[],
|
|
35
|
-
rowCount,
|
|
36
|
-
command: undefined,
|
|
37
|
-
fields: normalizedFields,
|
|
38
|
-
}
|
|
39
|
-
} catch (error) {
|
|
40
|
-
throw new QueryError('mysql', sql, error as Error)
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
async transaction<T>(callback: (driver: DatabaseDriver) => Promise<T>): Promise<T> {
|
|
45
|
-
const connection = await this.client
|
|
46
|
-
|
|
47
|
-
try {
|
|
48
|
-
await connection.beginTransaction()
|
|
49
|
-
|
|
50
|
-
const transactionDriver = new MySQLDriver({ connectionString: '' })
|
|
51
|
-
transactionDriver.client = Promise.resolve(connection)
|
|
52
|
-
|
|
53
|
-
const result = await callback(transactionDriver)
|
|
54
|
-
|
|
55
|
-
await connection.commit()
|
|
56
|
-
return result
|
|
57
|
-
} catch (error) {
|
|
58
|
-
await connection.rollback()
|
|
59
|
-
throw error
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
async close(): Promise<void> {
|
|
64
|
-
try {
|
|
65
|
-
await (await this.client).end()
|
|
66
|
-
} catch (error) {
|
|
67
|
-
consola.error('Error closing MySQL client:', error)
|
|
68
|
-
}
|
|
69
|
-
}
|
|
70
|
-
}
|
package/src/drivers/neon.ts
DELETED
|
File without changes
|