mirror of
https://github.com/kunkunsh/kunkun.git
synced 2025-04-20 05:29:17 +00:00
66 lines
1.5 KiB
TypeScript
66 lines
1.5 KiB
TypeScript
import * as schema from "@kksh/drizzle/schema"
|
|
import * as dbCmd from "@kunkunapi/src/commands/db"
|
|
import Database from "@tauri-apps/plugin-sql"
|
|
import { drizzle } from "drizzle-orm/sqlite-proxy"
|
|
|
|
/**
|
|
* Represents the result of a SELECT query.
|
|
*/
|
|
export type SelectQueryResult = {
|
|
[key: string]: any
|
|
}
|
|
|
|
/**
|
|
* Loads the sqlite database via the Tauri Proxy.
|
|
*/
|
|
// export const sqlite = await Database.load("sqlite:test.db");
|
|
|
|
/**
|
|
* The drizzle database instance.
|
|
*/
|
|
export const db = drizzle<typeof schema>(
|
|
async (sql, params, method) => {
|
|
let rows: any = []
|
|
let results = []
|
|
console.log({
|
|
sql,
|
|
params,
|
|
method
|
|
})
|
|
// If the query is a SELECT, use the select method
|
|
if (isSelectQuery(sql)) {
|
|
rows = await dbCmd.select(sql, params).catch((e) => {
|
|
console.error("SQL Error:", e)
|
|
return []
|
|
})
|
|
} else {
|
|
// Otherwise, use the execute method
|
|
rows = await dbCmd.execute(sql, params).catch((e) => {
|
|
console.error("SQL Error:", e)
|
|
return []
|
|
})
|
|
return { rows: [] }
|
|
}
|
|
|
|
rows = rows.map((row: any) => {
|
|
return Object.values(row)
|
|
})
|
|
|
|
// If the method is "all", return all rows
|
|
results = method === "all" ? rows : rows[0]
|
|
return { rows: results }
|
|
},
|
|
// Pass the schema to the drizzle instance
|
|
{ schema: schema, logger: true }
|
|
)
|
|
|
|
/**
|
|
* Checks if the given SQL query is a SELECT query.
|
|
* @param sql The SQL query to check.
|
|
* @returns True if the query is a SELECT query, false otherwise.
|
|
*/
|
|
function isSelectQuery(sql: string): boolean {
|
|
const selectRegex = /^\s*SELECT\b/i
|
|
return selectRegex.test(sql)
|
|
}
|