import { Knex } from 'knex' import { KnexDatabase } from './KnexDatabase.js' import { Database } from '../../Database.js' import { DatabaseTransaction } from '../../DatabaseTransaction.js' /** * Represents a Knex transaction, combining the functionality of KnexTransactionImpl * and Knex.Transaction types. */ export type KnexTransaction = KnexTransactionImpl & Knex.Transaction /** * Represents a Knex database transaction implementation that extends DatabaseTransaction. * @class */ export class KnexTransactionImpl extends DatabaseTransaction { /** * The Knex instance used for writing operations. * @type {Knex} */ public readonly writer!: Knex /** * Represents a transaction in Knex, a SQL query builder for Node.js. * This property is used to perform a series of database operations as a single unit of work. * @type {Knex.Transaction} - The transaction object provided by Knex. */ protected transaction!: Knex.Transaction /** * A protected property representing the database connection using KnexTransaction. * @type {Database} */ protected database!: Database /** * Constructs a new instance of the class with the provided Knex writer and database. * @param {Knex} writer - The Knex instance used for writing to the database. * @param {KnexDatabase} database - The KnexDatabase instance used for database operations. * @returns None */ private constructor(writer: Knex, database: KnexDatabase) { super(writer, database) } /** * Creates a new database transaction using the provided Knex instance and database configuration. * @param {Knex} write - The Knex instance used for read and write operations. * @param {KnexDatabase} database - The database configuration for the transaction. * @returns {Promise} A promise that resolves to a new database transaction. */ public static async newTransaction( write: Knex, database: KnexDatabase ): Promise { const tx = new KnexTransactionImpl(write, database) await tx.begin() return DatabaseTransaction.proxyInstance(tx) as any } /** * Initiates a transaction using the writer and assigns it to the 'transaction' property. * @returns {Promise} A promise that resolves to the transaction object. */ protected doBegin = async () => { this.transaction = await this.writer.transaction() return this.transaction } /** * Commits the current transaction. * @returns None */ protected doCommit = () => { return this.transaction.commit() } /** * Rollback the current transaction. * @returns The result of the rollback operation. */ protected doRollback = () => { return this.transaction.rollback() } }