← Files RivetARCHIVED FILE

node_modules/drizzle-orm/sqlite-core/async/session.cjs

11.5 KB · Nov 5, 2026 · 12:09 UTC

↓ Download file

Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const require_runtime = require('../../_virtual/_rolldown/runtime.cjs');
const require_sqlite_core_async_db = require('./db.cjs');
let __entity_ts = require("../../entity.cjs");
let __utils_ts = require("../../utils.cjs");
let __sql_sql_ts = require("../../sql/sql.cjs");
let __query_promise_ts = require("../../query-promise.cjs");
let __errors_ts = require("../../errors.cjs");
let __migrator_utils_ts = require("../../migrator.utils.cjs");
let __up_migrations_sqlite_ts = require("../../up-migrations/sqlite.cjs");
let __cache_core_cache_ts = require("../../cache/core/cache.cjs");
let __sqlite_core_session_ts = require("../session.cjs");

//#region src/sqlite-core/async/session.ts
var ExecuteResultSync = class extends __query_promise_ts.QueryPromise {
	static [__entity_ts.entityKind] = "ExecuteResultSync";
	constructor(resultCb) {
		super();
		this.resultCb = resultCb;
	}
	async execute() {
		return this.resultCb();
	}
	sync() {
		return this.resultCb();
	}
};
var SQLiteAsyncPreparedQuery = class extends __sqlite_core_session_ts.SQLitePreparedQuery {
	static [__entity_ts.entityKind] = "SQLiteAsyncPreparedQuery";
	fastPath;
	constructor(resultKind, executeMethod = "all", executors, query, mapper, mode, logger, cache, queryMetadata, cacheConfig) {
		super(executeMethod, query, mapper, mode);
		this.resultKind = resultKind;
		this.executors = executors;
		this.logger = logger;
		this.cache = cache;
		this.queryMetadata = queryMetadata;
		this.cacheConfig = cacheConfig;
		if (cache && cache.strategy() === "all" && cacheConfig === void 0) this.cacheConfig = {
			enabled: true,
			autoInvalidate: true
		};
		if (!this.cacheConfig?.enabled) this.cacheConfig = void 0;
		this.fastPath = cacheConfig === void 0 && (cache === void 0 || (0, __entity_ts.is)(cache, __cache_core_cache_ts.NoopCache));
	}
	/** @internal */
	async queryWithCache(queryString, params, executeMethod, query) {
		const cacheStrat = this.cache !== void 0 && !(0, __entity_ts.is)(this.cache, __cache_core_cache_ts.NoopCache) ? await (0, __cache_core_cache_ts.strategyFor)(queryString, params, this.queryMetadata, this.cacheConfig) : { type: "skip" };
		if (cacheStrat.type === "skip") return query().catch((e) => {
			throw new __errors_ts.DrizzleQueryError(queryString, params, e);
		});
		const cache = this.cache;
		if (cacheStrat.type === "invalidate") return Promise.all([query(), cache.onMutate({ tables: cacheStrat.tables })]).then((res) => res[0]).catch((e) => {
			throw new __errors_ts.DrizzleQueryError(queryString, params, e);
		});
		if (cacheStrat.type === "try") {
			const { tables, key: _key, isTag, autoInvalidate, config } = cacheStrat;
			const key = `${executeMethod}_${_key}`;
			const fromCache = await cache.get(key, tables, isTag, autoInvalidate);
			if (fromCache === void 0) {
				const result = await query().catch((e) => {
					throw new __errors_ts.DrizzleQueryError(queryString, params, e);
				});
				await cache.put(key, result, autoInvalidate ? tables : [], isTag, config);
				return result;
			}
			return fromCache;
		}
		(0, __utils_ts.assertUnreachable)(cacheStrat);
	}
	run(placeholderValues = {}) {
		const { query, logger, executors, fastPath, resultKind } = this;
		const sql = query._sql ? query._sql.join(" ") : query.sql;
		const params = query.params.length === 0 ? query.params : (0, __sql_sql_ts.fillPlaceholders)(query.params, placeholderValues);
		logger.logQuery(sql, params);
		if (resultKind === "sync") try {
			return executors.run(params);
		} catch (e) {
			throw new __errors_ts.DrizzleQueryError(sql, params, e);
		}
		return fastPath ? executors.run(params).catch((e) => {
			throw new __errors_ts.DrizzleQueryError(sql, params, e);
		}) : this.queryWithCache(sql, params, "run", () => executors.run(params));
	}
	all(placeholderValues = {}) {
		const { query, logger, executors, mapper, fastPath, resultKind } = this;
		const sql = query._sql ? query._sql.join(" ") : query.sql;
		const params = query.params.length === 0 ? query.params : (0, __sql_sql_ts.fillPlaceholders)(query.params, placeholderValues);
		logger.logQuery(sql, params);
		if (resultKind === "sync") {
			let res;
			try {
				res = executors.all(params);
			} catch (e) {
				throw new __errors_ts.DrizzleQueryError(sql, params, e);
			}
			if (!mapper) return res;
			return mapper(res);
		}
		const res = fastPath ? executors.all(params).catch((e) => {
			throw new __errors_ts.DrizzleQueryError(sql, params, e);
		}) : this.queryWithCache(sql, params, "all", () => executors.all(params));
		if (!mapper) return res;
		return res.then((rows) => mapper(rows));
	}
	get(placeholderValues = {}) {
		const { query, logger, executors, mapper, fastPath, resultKind } = this;
		const sql = query._sql ? query._sql.join(" ") : query.sql;
		const params = query.params.length === 0 ? query.params : (0, __sql_sql_ts.fillPlaceholders)(query.params, placeholderValues);
		logger.logQuery(sql, params);
		if (resultKind === "sync") {
			let res;
			try {
				res = executors.get(params);
			} catch (e) {
				throw new __errors_ts.DrizzleQueryError(sql, params, e);
			}
			if (!res) return void 0;
			if (!mapper) return res;
			return mapper([res])[0];
		}
		const res = fastPath ? executors.get(params).catch((e) => {
			throw new __errors_ts.DrizzleQueryError(sql, params, e);
		}) : this.queryWithCache(sql, params, "get", () => executors.get(params));
		if (!mapper) return res.then((row) => row ? row : void 0);
		return res.then((row) => row ? mapper([row])[0] : void 0);
	}
	values(placeholderValues = {}) {
		const { query, logger, executors, fastPath, resultKind } = this;
		const sql = query._sql ? query._sql.join(" ") : query.sql;
		const params = query.params.length === 0 ? query.params : (0, __sql_sql_ts.fillPlaceholders)(query.params, placeholderValues);
		logger.logQuery(sql, params);
		if (resultKind === "sync") try {
			return executors.values(params);
		} catch (e) {
			throw new __errors_ts.DrizzleQueryError(sql, params, e);
		}
		return fastPath ? executors.values(params).catch((e) => {
			throw new __errors_ts.DrizzleQueryError(sql, params, e);
		}) : this.queryWithCache(sql, params, "values", () => executors.values(params));
	}
	execute(placeholderValues) {
		if (this.resultKind === "async") return this[this.executeMethod](placeholderValues);
		return new ExecuteResultSync(() => this[this.executeMethod](placeholderValues));
	}
};
var SQLiteAsyncSession = class extends __sqlite_core_session_ts.SQLiteSession {
	static [__entity_ts.entityKind] = "SQLiteAsyncSession";
	constructor(dialect, resultKind) {
		super(dialect);
		this.resultKind = resultKind;
	}
	run(query) {
		return this.prepareQuery(this.dialect.sqlToQuery(query), "raw", false).run();
	}
	objects(query) {
		return this.prepareQuery(this.dialect.sqlToQuery(query), "objects", false).all();
	}
	object(query) {
		return this.prepareQuery(this.dialect.sqlToQuery(query), "objects", false).get();
	}
	arrays(query) {
		return this.prepareQuery(this.dialect.sqlToQuery(query), "arrays", false).all();
	}
	array(query) {
		return this.prepareQuery(this.dialect.sqlToQuery(query), "arrays", false).get();
	}
};
var SQLiteAsyncTransaction = class extends require_sqlite_core_async_db.SQLiteAsyncDatabase {
	static [__entity_ts.entityKind] = "SQLiteAsyncTransaction";
	constructor(resultType, dialect, session, relations, nestedIndex = 0, forbidJsonb) {
		super(resultType, dialect, session, relations, forbidJsonb);
		this.nestedIndex = nestedIndex;
	}
	rollback() {
		throw new __errors_ts.TransactionRollbackError();
	}
};
function migrateSync(migrations, session, config) {
	const migrationsTable = config === void 0 ? "__drizzle_migrations" : typeof config === "string" ? "__drizzle_migrations" : config.migrationsTable ?? "__drizzle_migrations";
	const { newDb } = (0, __up_migrations_sqlite_ts.upgradeSyncIfNeeded)(migrationsTable, session, migrations);
	if (newDb) {
		const migrationTableCreate = __sql_sql_ts.sql`
			CREATE TABLE IF NOT EXISTS ${__sql_sql_ts.sql.identifier(migrationsTable)} (
				id INTEGER PRIMARY KEY,
				hash text NOT NULL,
				created_at numeric,
				name text,
				applied_at TEXT
			)`;
		session.run(migrationTableCreate);
	}
	const dbMigrations = session.objects(__sql_sql_ts.sql`SELECT id, hash, created_at, name FROM ${__sql_sql_ts.sql.identifier(migrationsTable)}`);
	if (typeof config === "object" && config.init) {
		if (dbMigrations.length) return { exitCode: "databaseMigrations" };
		if (migrations.length > 1) return { exitCode: "localMigrations" };
		const [migration] = migrations;
		if (!migration) return;
		session.run(__sql_sql_ts.sql`insert into ${__sql_sql_ts.sql.identifier(migrationsTable)} ("hash", "created_at", "name", "applied_at") values(${migration.hash}, ${migration.folderMillis}, ${migration.name}, ${(/* @__PURE__ */ new Date()).toISOString()})`);
		return;
	}
	const migrationsToRun = (0, __migrator_utils_ts.getMigrationsToRun)({
		localMigrations: migrations,
		dbMigrations
	});
	session.run(__sql_sql_ts.sql`BEGIN`);
	try {
		for (const migration of migrationsToRun) {
			for (const stmt of migration.sql) session.run(__sql_sql_ts.sql.raw(stmt));
			session.run(__sql_sql_ts.sql`INSERT INTO ${__sql_sql_ts.sql.identifier(migrationsTable)} ("hash", "created_at", "name", "applied_at") values(${migration.hash}, ${migration.folderMillis}, ${migration.name}, ${(/* @__PURE__ */ new Date()).toISOString()})`);
		}
		session.run(__sql_sql_ts.sql`COMMIT`);
	} catch (e) {
		session.run(__sql_sql_ts.sql`ROLLBACK`);
		throw e;
	}
}
async function migrateAsync(migrations, db, config) {
	const migrationsTable = config === void 0 ? "__drizzle_migrations" : typeof config === "string" ? "__drizzle_migrations" : config.migrationsTable ?? "__drizzle_migrations";
	const { newDb } = await (0, __up_migrations_sqlite_ts.upgradeAsyncIfNeeded)(migrationsTable, db, migrations);
	if (newDb) {
		const migrationTableCreate = __sql_sql_ts.sql`
			CREATE TABLE IF NOT EXISTS ${__sql_sql_ts.sql.identifier(migrationsTable)} (
				id INTEGER PRIMARY KEY,
				hash text NOT NULL,
				created_at numeric,
				name text,
				applied_at TEXT
			)
		`;
		await db.session.run(migrationTableCreate);
	}
	const dbMigrations = await db.session.objects(__sql_sql_ts.sql`SELECT id, hash, created_at, name FROM ${__sql_sql_ts.sql.identifier(migrationsTable)};`);
	if (typeof config === "object" && config.init) {
		if (dbMigrations.length) return { exitCode: "databaseMigrations" };
		if (migrations.length > 1) return { exitCode: "localMigrations" };
		const [migration] = migrations;
		if (!migration) return;
		await db.session.run(__sql_sql_ts.sql`insert into ${__sql_sql_ts.sql.identifier(migrationsTable)} ("hash", "created_at", "name", "applied_at") values(${migration.hash}, ${migration.folderMillis}, ${migration.name}, ${(/* @__PURE__ */ new Date()).toISOString()})`);
		return;
	}
	const migrationsToRun = (0, __migrator_utils_ts.getMigrationsToRun)({
		localMigrations: migrations,
		dbMigrations
	});
	await db.session.transaction(async (tx) => {
		for (const migration of migrationsToRun) {
			for (const stmt of migration.sql) await tx.run(__sql_sql_ts.sql.raw(stmt));
			await tx.run(__sql_sql_ts.sql`insert into ${__sql_sql_ts.sql.identifier(migrationsTable)} ("hash", "created_at", "name", "applied_at") values(${migration.hash}, ${migration.folderMillis}, ${migration.name}, ${(/* @__PURE__ */ new Date()).toISOString()})`);
		}
	});
}

//#endregion
exports.ExecuteResultSync = ExecuteResultSync;
exports.SQLiteAsyncPreparedQuery = SQLiteAsyncPreparedQuery;
exports.SQLiteAsyncSession = SQLiteAsyncSession;
exports.SQLiteAsyncTransaction = SQLiteAsyncTransaction;
exports.migrateAsync = migrateAsync;
exports.migrateSync = migrateSync;
//# sourceMappingURL=session.cjs.map

SHA-256: be8b485c760063ffe09c1df8764f4eb140e6396623d1e6847e373003a2b6c6f4