import { Injectable } from '@nestjs/common'; import * as oracledb from 'oracledb'; import { OracleDBService } from 'src/db/db.service'; import { CreateCarnetSequenceDTO, GetCarnetSequenceDTO, } from './carnet-sequence.dto'; @Injectable() export class CarnetSequenceService { constructor(private readonly oracleDBService: OracleDBService) {} async createCarnetSequence(body: CreateCarnetSequenceDTO) { let connection; try { connection = await this.oracleDBService.getConnection(); if (!connection) { throw new Error('No DB Connected'); } const result = await connection.execute( `BEGIN USCIB_Managed_Pkg.CreateCarnetSequence( :p_spid, :p_regionid, :p_startnumber, :p_endnumber, :p_carnettype, :p_cursor); END;`, { p_spid: { val: body.p_spid, type: oracledb.DB_TYPE_NUMBER, }, p_regionid: { val: body.p_regionid, type: oracledb.DB_TYPE_NUMBER, }, p_startnumber: { val: body.p_startnumber, type: oracledb.DB_TYPE_NUMBER, }, p_endnumber: { val: body.p_endnumber, type: oracledb.DB_TYPE_NUMBER, }, p_carnettype: { val: body.p_carnettype, type: oracledb.DB_TYPE_VARCHAR, }, p_cursor: { type: oracledb.CURSOR, dir: oracledb.BIND_OUT, }, }, { outFormat: oracledb.OUT_FORMAT_OBJECT, }, ); await connection.commit(); const fres = await result.outBinds.p_cursor.getRows(); await result.outBinds.p_cursor.close(); return fres; } catch (err) { if (err instanceof Error) { return { error: err.message }; } else { return { error: 'An unknown error occurred' }; } } finally { if (connection) { try { await connection.close(); } catch (closeErr) { console.error('Failed to close connection:', closeErr); } } } } async getCarnetSequence(body: GetCarnetSequenceDTO) { let connection; let rows = []; try { // Connect to the Oracle database using oracledb connection = await this.oracleDBService.getConnection(); if (!connection) { throw new Error('No DB Connected'); } const result = await connection.execute( `BEGIN USCIB_Managed_Pkg.GetCarnetSequence(:p_spid,:p_cursor); END;`, { p_spid: { val: body.p_spid, type: oracledb.DB_TYPE_NUMBER, }, p_cursor: { type: oracledb.CURSOR, dir: oracledb.BIND_OUT, }, }, { outFormat: oracledb.OUT_FORMAT_OBJECT, }, ); if (result.outBinds && result.outBinds.p_cursor) { const cursor = result.outBinds.p_cursor; let rowsBatch; do { rowsBatch = await cursor.getRows(100); // Fetch 100 rows at a time rows = rows.concat(rowsBatch); } while (rowsBatch.length > 0); await cursor.close(); } else { throw new Error('No cursor returned from the stored procedure'); } return rows; } catch (err) { if (err instanceof Error) { return { error: err.message }; } else { return { error: 'An unknown error occurred' }; } } finally { if (connection) { try { await connection.close(); } catch (closeErr) { console.error('Failed to close connection:', closeErr); } } } } }