70 lines
1.7 KiB
TypeScript
70 lines
1.7 KiB
TypeScript
/**
|
|
* Drizzle ORM Database Client for Turso/libSQL.
|
|
*
|
|
* Provides the configured drizzle instance and convenience helpers.
|
|
* Reads DATABASE_URL and DATABASE_TOKEN from environment.
|
|
*/
|
|
|
|
import { sql } from "drizzle-orm";
|
|
import { drizzle, type LibSQLDatabase } from "drizzle-orm/libsql";
|
|
import { createClient } from "@libsql/client";
|
|
import * as schema from "./schema";
|
|
|
|
export type {
|
|
PlantRow,
|
|
PlantInsert,
|
|
DiseaseRow,
|
|
DiseaseInsert,
|
|
FlaggedContentRow,
|
|
FlaggedContentInsert,
|
|
} from "./schema";
|
|
|
|
export { schema };
|
|
|
|
let _db: LibSQLDatabase<typeof schema> | null = null;
|
|
let _client: ReturnType<typeof createClient> | null = null;
|
|
|
|
/** Get or create the Drizzle database instance (singleton). */
|
|
export function getDb(): LibSQLDatabase<typeof schema> {
|
|
if (_db) return _db;
|
|
|
|
const url = process.env.DATABASE_URL;
|
|
const token = process.env.DATABASE_TOKEN;
|
|
|
|
if (!url) {
|
|
throw new Error(
|
|
"DATABASE_URL is not set. Check your .env.development or .env.production file.",
|
|
);
|
|
}
|
|
if (!token) {
|
|
throw new Error(
|
|
"DATABASE_TOKEN is not set. Check your .env.development or .env.production file.",
|
|
);
|
|
}
|
|
|
|
_client = createClient({ url, authToken: token });
|
|
_db = drizzle(_client, { schema });
|
|
return _db;
|
|
}
|
|
|
|
/** Check database connectivity. */
|
|
export async function checkConnection(): Promise<boolean> {
|
|
try {
|
|
const db = getDb();
|
|
const result = await db.run(sql`SELECT 1 AS ok`);
|
|
return result.rowsAffected >= 0;
|
|
} catch (err) {
|
|
console.error("[DB] Connection failed:", err);
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/** Close the client connection. */
|
|
export function closeDb() {
|
|
if (_client) {
|
|
_client.close();
|
|
_client = null;
|
|
_db = null;
|
|
}
|
|
}
|