Fixed and ported functions mariadb > postgre

almost.
This commit is contained in:
SolPuffy 2025-01-07 11:08:44 +02:00
parent 2f7de2cf8f
commit 6b3fa6cf22
3 changed files with 209 additions and 168 deletions

View file

@ -228,6 +228,24 @@ function currentIntervals(): Record<string, boolean> {
return currentAsyncIntervals; return currentAsyncIntervals;
} }
function threadTimeout(miliseconds: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve,miliseconds));
}
function unifyArrays<T1, T2>(array1: any[], array2: any[]): Promise<{ x: any[]; y: any[] }> {
return Promise.resolve({ x: [...array1], y: [...array2] });
}
function randomArray(item_count: number,range_scale: number): any {
let random_array: any[] = [];
for(let i: number = 0;i<item_count;i++)
{
random_array.push(randomNumber(range_scale));
}
return random_array;
}
function randomNumber(range_scale: number): number {
return Math.floor(Math.random() * (Math.pow(10, range_scale) - Math.pow(10, range_scale - 1))) + Math.pow(10, range_scale - 1);
}
// Exports // Exports
export { export {
addNotation, addNotation,
@ -238,4 +256,8 @@ export {
asyncInterval, asyncInterval,
stopAsyncInterval, stopAsyncInterval,
currentIntervals, currentIntervals,
threadTimeout,
unifyArrays,
randomArray,
randomNumber
}; };

View file

@ -1,52 +0,0 @@
import { SqlSystem } from './sqlFunctions';
class SqlCommands {
private static async InsertDummyData() {
console.log("Inserting random numbers into Pool");
let dummy_auctionid: string[] = this.randomArray(10,8),dummy_lbin: number[] = this.randomArray(10,5);
await SqlSystem.Upsert(dummy_auctionid,dummy_lbin)
}
private static async RequestDummyData() {
console.log("Requesting All from table auctions");
console.log(await SqlSystem.Query("SELECT * FROM auctions"));
}
public static async main(): Promise<void> {
const command_args = process.argv.slice(2);
if(arguments.length===0) return;
switch(command_args[0].toString()) {
case "insdummy": {
this.InsertDummyData();
break;
}
case "reqdummy": {
this.RequestDummyData();
break;
}
default:break;
}
}
private static randomArray(item_count: number,range_scale: number): any {
let random_array: any[] = [];
for(let i: number = 0;i<item_count;i++)
{
random_array.push(this.randomNumber(range_scale));
}
return random_array;
}
private static randomNumber(range_scale: number): number {
return Math.floor(Math.random() * (Math.pow(10, range_scale) - Math.pow(10, range_scale - 1))) + Math.pow(10, range_scale - 1);
}
//example
// scale 1 returns a number from 0 to 9
// scale 2 returns a number from 10 to 99
// scale 3 returns a number from 100 to 999
// ...
// scale 64 returns a crash
}
SqlCommands.main();

View file

@ -1,5 +1,6 @@
import { Pool, PoolClient } from 'pg'; import { Pool, PoolClient, Query, QueryResult, QueryResultRow } from 'pg';
import { loadConfig } from './configLoader'; import { loadConfig } from './configLoader';
import { unifyArrays, randomArray } from './helperFunctions'
const config = loadConfig(); const config = loadConfig();
class SqlSystem { class SqlSystem {
@ -129,17 +130,201 @@ class SqlSystem {
END; END;
$outer$; $outer$;
`); `);
//await this.TimeoutThread(10000)
await conn.query('BEGIN');
console.log("Inserting random numbers into Pool SETUP");
let dummy_auctionid: string[] = randomArray(10,8),dummy_lbin: number[] = randomArray(10,5);
await this.Upsert(dummy_auctionid,dummy_lbin);
await conn.query('COMMIT');
console.log("Requesting All from table auctions PRE REMOVE");
console.log(await this.Query("SELECT * FROM auctions",false));
await conn.query('BEGIN');
await this.RemoveAll()
await conn.query('COMMIT')
console.log("Requesting All from table auctions POST REMOVE");
console.log(await this.Query("SELECT * FROM auctions",false));
} }
catch (error) { catch (error) {
console.error("InitDB Error: ", error); console.error("InitDB Error: ", error);
if (conn) await conn.query('ROLLBACK');
throw error; throw error;
} }
finally { finally {
if (conn) conn.release(); if (conn) conn.release();
} }
} }
public static async Upsert(auctionid: string|string[], lbin:number|number[])
{
let conn: PoolClient | undefined;
try
{
conn = await this.pool.connect();
await conn.query('BEGIN');
if(Array.isArray(auctionid) && Array.isArray(lbin))
if(auctionid.length === lbin.length) {
await conn.query(`
INSERT INTO auctions (id, auctionid, lbin)
SELECT uuid_generate_v4()::UUID, unnest($1::text[]), unnest($2::decimal[])
ON CONFLICT (auctionid)
DO UPDATE SET lbin = EXCLUDED.lbin;
`,[auctionid,lbin]);
}
else if(Array.isArray(auctionid) || Array.isArray(lbin))
throw Error(`Upsert SQL Function error - cannot unify collection ${Array.isArray(auctionid) ? auctionid : lbin} to singlet ${!Array.isArray(auctionid) ? auctionid : lbin}`);
else {
await conn.query(`
INSERT INTO auctions (id, auctionid, lbin)
VALUES uuid_generate_v4()::UUID, $1::text, $2::decimal
ON CONFLICT (auctionid)
DO UPDATE SET lbin = EXCLUDED.lbin;
`, [auctionid, lbin]);
}
await conn.query('COMMIT');
}
catch(error)
{
console.error("message_before_error: ", error);
if (conn) await conn.query('ROLLBACK');
throw error;
}
finally
{
if (conn) conn.release();
}
}
//REMOVE ALL ELEMENTS IN AUCTIONS TABLE
public static async RemoveAll() {
let conn: PoolClient | undefined;
try {
conn = await this.pool.connect();
await conn.query('BEGIN');
await conn.query('DELETE FROM auctions')
await conn.query('COMMIT');
}
catch (error) {
console.error("InitDB Error: ", error);
if (conn) await conn.query('ROLLBACK');
throw error;
}
finally {
if (conn) conn.release();
}
}
//REMOVE ELEMENT IN AUCTIONS TABLE BY AUCTION-ID
public static async RemoveByAuctionId(auctionid: string|string[]) {
let conn: PoolClient | undefined;
try {
conn = await this.pool.connect();
await conn.query('BEGIN');
if(Array.isArray(auctionid))
{
await conn.query('DELETE FROM auctions WHERE auctionid IN ($1);',[auctionid]);
}
else
{
await conn.query('DELETE FROM auctions WHERE auctionid = $1;',[auctionid]);
}
await conn.query('COMMIT');
}
catch (error) {
console.error("InitDB Error: ", error);
if (conn) await conn.query('ROLLBACK');
throw error;
}
finally {
if (conn) conn.release();
}
}
public static async Query(query:string,IsWriting:boolean = false) {
let conn: PoolClient | undefined;
let result: any;
try{
conn = await this.pool.connect()
if(IsWriting)
{
await conn.query('BEGIN');
conn.query(query);
await conn.query('COMMIT');
}
else
{
console.log('TRYING TO QUERY');
result = (await conn.query(query)).rows;
}
}
catch(error) {
console.error("InitDB Error: ", error);
if (IsWriting && conn) await conn.query('ROLLBACK');
throw error;
}
finally
{
if(conn) conn.release();
if(!IsWriting) return result;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////// NOT FIXED / UNTESTED FUNCTIONS
//MATCH PROVIDED ELEMENTS IN AUCTIONS TABLE - returns true/false
public static async Match(auctionid:string|string[],lbin:number|number[]): Promise<boolean|any> {
let conn: PoolClient | undefined;
let result;
try{
conn = await this.pool.connect();
if(Array.isArray(auctionid) && Array.isArray(lbin))
if(auctionid.length === lbin.length) {
result = await conn.query(`
CREATE TEMPORARY TABLE IF NOT EXISTS TEMP (
auctionID VARCHAR(255) PRIMARY KEY,
lbin DECIMAL(65,5)
);
INSERT INTO TEMP (auctionID, lbin) VALUES ?
SELECT tmp.*
FROM TEMP AS tmp
WHERE NOT EXISTS (
SELECT 1
FROM auctions AS auc
WHERE auc.auctionID = tmp.auctionID
AND auc.lbin = tmp.lbin);
`,[await unifyArrays(auctionid,lbin)]);
return result.rows;
}
else if(Array.isArray(auctionid) || Array.isArray(lbin))
throw Error(`Match SQL Function error - cannot unify collection ${Array.isArray(auctionid) ? auctionid : lbin} to singlet ${!Array.isArray(auctionid) ? auctionid : lbin}`);
else {
result = await conn.query(`
SELECT CASE
WHEN COUNT(*) > 0
THEN true
ELSE false
END AS user_exists
FROM auctions WHERE auctionID = ?;
`,[auctionid]);
return Boolean(result.rows.length);
}
}
catch(error)
{
console.error("message_before_error: ", error);
throw error;
}
finally
{
if (conn) conn.release();
}
}
//INSERT ELEMENT IN AUCTIONS TABLE OR UPDATE IF IT ALREADY EXISTS //INSERT ELEMENT IN AUCTIONS TABLE OR UPDATE IF IT ALREADY EXISTS
public static async Upsert(auctionid: string|string[], lbin: number|number[]) { public static async deprecated_Upsert(auctionid: string|string[], lbin: number|number[]) {
let conn: PoolClient | undefined; let conn: PoolClient | undefined;
try { try {
conn = await this.pool.connect(); conn = await this.pool.connect();
@ -176,120 +361,6 @@ class SqlSystem {
if (conn) conn.release(); if (conn) conn.release();
} }
} }
//REMOVE ELEMENT IN AUCTIONS TABLE
public static async Remove(auctionid: string|string[]) {
let conn: PoolClient | undefined;
try {
conn = await this.pool.connect();
await conn.query('BEGIN');
await conn.query(`
DELETE FROM auctions WHERE auctionid = ?
`,[auctionid]);
await conn.query('COMMIT');
}
catch (error) {
console.error("InitDB Error: ", error);
if (conn) await conn.query('ROLLBACK');
throw error;
}
finally {
if (conn) conn.release();
}
}
public static async Query(query:string,use_transaction:boolean = true) {
let conn: PoolClient | undefined;
try{
conn = await this.pool.connect()
if (use_transaction) await conn.query('BEGIN');
await conn.query(query);
if (use_transaction) await conn.query('COMMIT');
}
catch(error) {
console.error("InitDB Error: ", error);
if (use_transaction && conn) await conn.query('ROLLBACK');
throw error;
}
finally
{
if(conn) conn.release();
}
}
//MATCH PROVIDED ELEMENTS IN AUCTIONS TABLE - returns true/false
public static async Match(auctionid:string|string[],lbin:number|number[]): Promise<boolean|any> {
let conn: PoolClient | undefined;
let result;
try{
conn = await this.pool.connect();
if(Array.isArray(auctionid) && Array.isArray(lbin))
if(auctionid.length === lbin.length) {
result = await conn.query(`
CREATE TEMPORARY TABLE IF NOT EXISTS TEMP (
auctionID VARCHAR(255) PRIMARY KEY,
lbin DECIMAL(65,5)
);
INSERT INTO TEMP (auctionID, lbin) VALUES ?
SELECT tmp.*
FROM TEMP AS tmp
WHERE NOT EXISTS (
SELECT 1
FROM auctions AS auc
WHERE auc.auctionID = tmp.auctionID
AND auc.lbin = tmp.lbin);
`,[await this.UnifiedArray(auctionid,lbin)]);
return result;
}
else if(Array.isArray(auctionid) || Array.isArray(lbin))
throw Error(`Match SQL Function error - cannot unify collection ${Array.isArray(auctionid) ? auctionid : lbin} to singlet ${!Array.isArray(auctionid) ? auctionid : lbin}`);
else {
result = await conn.query(`
SELECT CASE
WHEN COUNT(*) > 0
THEN true
ELSE false
END AS user_exists
FROM auctions WHERE auctionID = ?;
`,[auctionid]);
return Boolean(result.rows.length);
}
}
catch(error)
{
console.error("message_before_error: ", error);
throw error;
}
finally
{
if (conn) conn.release();
}
}
//EXAMPLE BLOCK OF CODE FOR ADDING DATABASE FUNCTIONS
/*
public static async example_name() {
let conn:PoolClient|undefined;
try{
conn = await this.pool.connect();
await conn.query('BEGIN');
//CODE HERE//
await conn.query('COMMIT');
}
catch(error)
{
console.error("message_before_error: ", error);
if(conn) await conn.query('ROLLBACK');
throw error;
}
finally
{
if(conn) conn.release();
}
*/
private static async UnifiedArray<T1, T2>(auctionid: string[], lbin: number[]): Promise<{ x: string[], y: number[] }> {
return { x: [...auctionid], y: [...lbin] };
}
} }
export { export {
SqlSystem SqlSystem