import { QueryBuilder } from '../query-builders/query-builder' import type { DatabaseDriver } from '../drivers/database-driver' export class Transaction { private driver: DatabaseDriver /** * Creates a new Transaction instance * @param {DatabaseDriver} [driver] */ constructor(driver: DatabaseDriver) { this.driver = driver } /** * @description Select from a table * @param {string} table * @param {string} [alias] * @returns {QueryBuilder} */ public from(table: string, alias?: string): QueryBuilder { return new QueryBuilder(this.driver).from(table, alias) } /** * Creates a query builder with table specification within the transaction * @param {string} table - Table name to query from * @param {string} [alias] - Optional table alias * @returns {QueryBuilder} Query builder instance */ public table(table: string, alias?: string): QueryBuilder { return new QueryBuilder(this.driver).table(table, alias) } /** * Inserts a new record/records into the database * @param {Record | Record[]} [data] - Data to insert * @returns {QueryBuilder} Query builder instance */ public async insert(data: Record | Record[]): Promise { const queryBuilder = new QueryBuilder(this.driver) return await queryBuilder.insert(data) } /** * Creates a new record in the database * @param {Record} data - Data to insert * @returns {Promise} Inserted records */ public create(data: Record): Promise { return this.insert(data) } /** * Executes raw SQL query within the transaction * @param {string} sql - Raw SQL query string * @param {any[]} [params=[]] - Query parameters * @returns {Promise} Query results * @throws {Error} When transaction has already been committed or rolled back */ public async rawQuery(sql: string, params: any[] = []): Promise { return await this.getDriver().runQuery(sql, params) } /** * Gets the transaction context * @returns {Bun.SQL} Transaction context */ public getDriver(): DatabaseDriver { if (!this.driver) throw new Error('Driver is required') return this.driver } /** * Commits the transaction * @returns {Promise} */ public async commit(): Promise { await this.getDriver().commit() } /** * Rolls back the transaction * @returns {Promise} */ public async rollback(): Promise { await this.getDriver().rollback() } }