easy-postgresql 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +45 -0
  3. package/SECURITY.md +15 -0
  4. package/database/procedure.ts +129 -0
  5. package/database/query.ts +78 -0
  6. package/database/sql_types.d.ts +52 -0
  7. package/database/sql_types.ts +90 -0
  8. package/database/table.ts +378 -0
  9. package/database.ts +26 -0
  10. package/dist/database/procedure.d.ts +26 -0
  11. package/dist/database/procedure.js +107 -0
  12. package/dist/database/procedure.js.map +1 -0
  13. package/dist/database/query.d.ts +13 -0
  14. package/dist/database/query.js +79 -0
  15. package/dist/database/query.js.map +1 -0
  16. package/dist/database/sql_types.d.ts +48 -0
  17. package/dist/database/sql_types.js +50 -0
  18. package/dist/database/sql_types.js.map +1 -0
  19. package/dist/database/table.d.ts +54 -0
  20. package/dist/database/table.js +308 -0
  21. package/dist/database/table.js.map +1 -0
  22. package/dist/database.d.ts +24 -0
  23. package/dist/database.js +28 -0
  24. package/dist/database.js.map +1 -0
  25. package/dist/operations/config.d.ts +22 -0
  26. package/dist/operations/config.js +30 -0
  27. package/dist/operations/config.js.map +1 -0
  28. package/dist/operations/connect_to_server.d.ts +28 -0
  29. package/dist/operations/connect_to_server.js +108 -0
  30. package/dist/operations/connect_to_server.js.map +1 -0
  31. package/dist/operations/data_types.d.ts +6 -0
  32. package/dist/operations/data_types.js +120 -0
  33. package/dist/operations/data_types.js.map +1 -0
  34. package/dist/operations/get_pieces.d.ts +29 -0
  35. package/dist/operations/get_pieces.js +56 -0
  36. package/dist/operations/get_pieces.js.map +1 -0
  37. package/dist/operations/log.d.ts +12 -0
  38. package/dist/operations/log.js +27 -0
  39. package/dist/operations/log.js.map +1 -0
  40. package/dist/operations/procedure_execute.d.ts +18 -0
  41. package/dist/operations/procedure_execute.js +53 -0
  42. package/dist/operations/procedure_execute.js.map +1 -0
  43. package/operations/config.ts +28 -0
  44. package/operations/connect_to_server.ts +111 -0
  45. package/operations/data_types.ts +129 -0
  46. package/operations/get_pieces.ts +63 -0
  47. package/operations/log.ts +27 -0
  48. package/operations/procedure_execute.ts +58 -0
  49. package/package.json +55 -0
  50. package/simple/advanced-test.js +631 -0
  51. package/simple/config.simple.js +9 -0
  52. package/simple/config.simple.ts +9 -0
  53. package/simple/test.js +398 -0
  54. package/simple/test.ts +392 -0
  55. package/tsconfig.json +21 -0
@@ -0,0 +1,108 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.connectToServer = exports.isConnected = void 0;
4
+ exports.getPool = getPool;
5
+ const pg_1 = require("pg");
6
+ const config_1 = require("./config");
7
+ const log_1 = require("./log");
8
+ let pool = null;
9
+ function getPool() {
10
+ if (!pool)
11
+ throw new Error('Database not connected. Call Connect() first.');
12
+ return pool;
13
+ }
14
+ /**
15
+ * This function checks if the database connection is active
16
+ *
17
+ * @returns Promise<boolean> - Returns true if connection is active, false otherwise
18
+ */
19
+ const isConnected = async () => {
20
+ try {
21
+ const p = getPool();
22
+ const client = await p.connect();
23
+ try {
24
+ await client.query('SELECT 1');
25
+ }
26
+ finally {
27
+ client.release();
28
+ }
29
+ return { status: 200, message: 'OK' };
30
+ }
31
+ catch (err) {
32
+ return { status: 500, message: 'Error: ' + String(err) };
33
+ }
34
+ };
35
+ exports.isConnected = isConnected;
36
+ /**
37
+ * This function is used to connect to the database.
38
+ *
39
+ * @param sqlConfig - The PostgreSQL configuration to connect to the database
40
+ * @param run - Optional callback function to be executed after the connection is established
41
+ * @returns Promise<boolean> - Returns true if connection is successful, false otherwise
42
+ */
43
+ const connectToServer = async (sqlConfig, run) => {
44
+ if (!sqlConfig || typeof sqlConfig !== 'object') {
45
+ if (config_1.config.get.logingMode())
46
+ (0, log_1.log)('Connection', null, 'The sqlConfig parameter is not an object.');
47
+ return false;
48
+ }
49
+ const required = { user: "string", password: "string", host: "string", database: "string" };
50
+ for (const key in required) {
51
+ if (!sqlConfig[key] || typeof sqlConfig[key] !== required[key]) {
52
+ if (config_1.config.get.logingMode())
53
+ (0, log_1.log)('Connection', null, `The ${key} parameter is not a ${required[key]}.`);
54
+ return false;
55
+ }
56
+ }
57
+ pool = new pg_1.Pool({
58
+ user: sqlConfig.user,
59
+ password: sqlConfig.password,
60
+ host: sqlConfig.host,
61
+ port: sqlConfig.port || 5432,
62
+ database: sqlConfig.database,
63
+ });
64
+ const maxRetries = 3;
65
+ const retryInterval = 2500;
66
+ let retryCount = 0;
67
+ const tryConnect = async () => {
68
+ try {
69
+ const client = await pool.connect();
70
+ try {
71
+ await client.query('SELECT 1');
72
+ }
73
+ finally {
74
+ client.release();
75
+ }
76
+ if (run && typeof run === 'function') {
77
+ run(sqlConfig);
78
+ }
79
+ if (config_1.config.get.logingMode())
80
+ (0, log_1.log)('Connection', null, 'Success');
81
+ return true;
82
+ }
83
+ catch (err) {
84
+ if (config_1.config.get.logingMode())
85
+ (0, log_1.log)('Connection', 'Attempt', `${retryCount + 1}: ${err instanceof Error ? err.message : String(err)}`);
86
+ if (run && typeof run === 'function') {
87
+ run(sqlConfig, err instanceof Error ? err : new Error(String(err)));
88
+ }
89
+ return false;
90
+ }
91
+ };
92
+ while (retryCount < maxRetries) {
93
+ const result = await tryConnect();
94
+ if (result)
95
+ return true;
96
+ retryCount++;
97
+ if (retryCount < maxRetries) {
98
+ if (config_1.config.get.logingMode())
99
+ (0, log_1.log)('Connection', 'Retry', `Retrying in 2.5s... (Attempt ${retryCount + 1}/${maxRetries})`);
100
+ await new Promise(resolve => setTimeout(resolve, retryInterval));
101
+ }
102
+ }
103
+ if (config_1.config.get.logingMode())
104
+ (0, log_1.log)('Connection', null, `Failed after ${maxRetries} attempts`);
105
+ return false;
106
+ };
107
+ exports.connectToServer = connectToServer;
108
+ //# sourceMappingURL=connect_to_server.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"connect_to_server.js","sourceRoot":"","sources":["../../operations/connect_to_server.ts"],"names":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AO,KAAK,CAAC;AACjB,CAAC,CAAC;AA7DW,QAAA,eAAe,GAAf,eAAe,CA6D1B"}
@@ -0,0 +1,6 @@
1
+ type TypeConverter = (value: any) => any;
2
+ /**
3
+ * This object contains the data types of PostgreSQL and their corresponding JavaScript data type converters.
4
+ */
5
+ export declare const sqlTypes: Record<string, TypeConverter>;
6
+ export {};
@@ -0,0 +1,120 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.sqlTypes = void 0;
4
+ /**
5
+ * This class is used to create an object of any data type.
6
+ */
7
+ class Any {
8
+ constructor(value) {
9
+ this.value = value;
10
+ }
11
+ }
12
+ /**
13
+ * This function is used to check if the value is null.
14
+ *
15
+ * @param value - The data to be checked
16
+ * @returns boolean - Returns true if the value is null, false otherwise
17
+ */
18
+ const isNull = (value) => value === null;
19
+ /**
20
+ * This object contains functions to convert values to specific data types.
21
+ */
22
+ const types = {
23
+ /**
24
+ * Converts a value to a string.
25
+ * @param value - The value to be converted
26
+ * @returns string | null - The converted string value or null
27
+ */
28
+ string: (value) => {
29
+ return isNull(value) ? null : String(value);
30
+ },
31
+ /**
32
+ * Converts a value to a number.
33
+ * @param value - The value to be converted
34
+ * @returns number | null - The converted number value or null
35
+ */
36
+ number: (value) => {
37
+ return isNull(value) ? null : Number(value);
38
+ },
39
+ /**
40
+ * Converts a value to a boolean.
41
+ * @param value - The value to be converted
42
+ * @returns boolean | null - The converted boolean value or null
43
+ */
44
+ boolean: (value) => {
45
+ return isNull(value) ? null : Boolean(value);
46
+ },
47
+ /**
48
+ * Converts a value to a Date.
49
+ * @param value - The value to be converted
50
+ * @returns Date | null - The converted Date value or null
51
+ */
52
+ date: (value) => {
53
+ return isNull(value) ? null : new Date(value);
54
+ },
55
+ /**
56
+ * Converts a value to a Buffer.
57
+ * @param value - The value to be converted
58
+ * @returns Buffer | null - The converted Buffer value or null
59
+ */
60
+ buffer: (value) => {
61
+ return isNull(value) ? null : Buffer.from(String(value));
62
+ },
63
+ /**
64
+ * Converts a value to an Array.
65
+ * @param value - The value to be converted
66
+ * @returns any[] | null - The converted Array value or null
67
+ */
68
+ array: (value) => {
69
+ return isNull(value) ? null : Array.isArray(value) ? value : [value];
70
+ },
71
+ /**
72
+ * Wraps a value in an Any object.
73
+ * @param value - The value to be wrapped
74
+ * @returns Any | null - The wrapped value or null
75
+ */
76
+ any: (value) => {
77
+ return isNull(value) ? null : new Any(value);
78
+ }
79
+ };
80
+ /**
81
+ * This object contains the data types of PostgreSQL and their corresponding JavaScript data type converters.
82
+ */
83
+ exports.sqlTypes = {
84
+ "char": types.string,
85
+ "character": types.string,
86
+ "varchar": types.string,
87
+ "character varying": types.string,
88
+ "text": types.string,
89
+ "bytea": types.buffer,
90
+ "bool": types.boolean,
91
+ "boolean": types.boolean,
92
+ "int2": types.number,
93
+ "smallint": types.number,
94
+ "int4": types.number,
95
+ "integer": types.number,
96
+ "int8": types.number,
97
+ "bigint": types.number,
98
+ "decimal": types.number,
99
+ "numeric": types.number,
100
+ "float4": types.number,
101
+ "real": types.number,
102
+ "float8": types.number,
103
+ "double precision": types.number,
104
+ "money": types.number,
105
+ "timestamp": types.date,
106
+ "timestamptz": types.date,
107
+ "timestamp without time zone": types.date,
108
+ "timestamp with time zone": types.date,
109
+ "date": types.date,
110
+ "time": types.string,
111
+ "timetz": types.string,
112
+ "time without time zone": types.string,
113
+ "time with time zone": types.string,
114
+ "uuid": types.string,
115
+ "xml": types.string,
116
+ "json": types.any,
117
+ "jsonb": types.any,
118
+ "ARRAY": types.array,
119
+ };
120
+ //# sourceMappingURL=data_types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"data_types.js","sourceRoot":"","sources":["../../operations/data_types.ts"],"names":[],"mappings":";;;AAAA;;GAEG;AACH,MAAM,GAAG;IAGL,YAAY,KAAU;QAClB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACvB,CAAC;CACJ;AAED;;;;;GAKG;AACH,MAAM,MAAM,GAAG,CAAC,KA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AAC,MAAM;IACpB,QAAQ,EAAE,KAAK,CAAC,MAAM;IACtB,wBAAwB,EAAE,KAAK,CAAC,MAAM;IACtC,qBAAqB,EAAE,KAAK,CAAC,MAAM;IACnC,MAAM,EAAE,KAAK,CAAC,MAAM;IACpB,KAAK,EAAE,KAAK,CAAC,MAAM;IACnB,MAAM,EAAE,KAAK,CAAC,GAAG;IACjB,OAAO,EAAE,KAAK,CAAC,GAAG;IAClB,OAAO,EAAE,KAAK,CAAC,KAAK;CACvB,CAAC"}
@@ -0,0 +1,29 @@
1
+ export interface ParameterizedPieces {
2
+ condition: string;
3
+ inputs: any[];
4
+ }
5
+ export interface InsertPieces {
6
+ columns: string;
7
+ values: string;
8
+ inputs: any[];
9
+ }
10
+ /**
11
+ * Converts an object into a parameterized WHERE/SET condition string.
12
+ * Generates $1, $2... positional placeholders to prevent SQL injection.
13
+ *
14
+ * @param data - The key/value pairs to parameterize
15
+ * @param startIndex - Starting positional index for parameters (default: 0, meaning first param is $1)
16
+ * @returns Parameterized condition and ordered input values array
17
+ */
18
+ export declare const getConditionPieces: (data?: Record<string, any>, startIndex?: number) => ParameterizedPieces;
19
+ /**
20
+ * Converts an object into a parameterized INSERT fragment.
21
+ *
22
+ * @param data - The key/value pairs to insert
23
+ * @returns Column names, positional placeholders ($1, $2...), and ordered input values
24
+ */
25
+ export declare const getInsertPieces: (data?: Record<string, any>) => InsertPieces;
26
+ /**
27
+ * Validates that a SQL identifier (table/column name) contains only safe characters.
28
+ */
29
+ export declare const isValidIdentifier: (name: string) => boolean;
@@ -0,0 +1,56 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isValidIdentifier = exports.getInsertPieces = exports.getConditionPieces = void 0;
4
+ /**
5
+ * Converts an object into a parameterized WHERE/SET condition string.
6
+ * Generates $1, $2... positional placeholders to prevent SQL injection.
7
+ *
8
+ * @param data - The key/value pairs to parameterize
9
+ * @param startIndex - Starting positional index for parameters (default: 0, meaning first param is $1)
10
+ * @returns Parameterized condition and ordered input values array
11
+ */
12
+ const getConditionPieces = (data = {}, startIndex = 0) => {
13
+ const keys = Object.keys(data).filter(key => (0, exports.isValidIdentifier)(key));
14
+ const condition = keys.map((key, i) => `${key} = $${startIndex + i + 1}`).join(' AND ');
15
+ const inputs = keys.map(key => sanitizeValue(data[key]));
16
+ return { condition, inputs };
17
+ };
18
+ exports.getConditionPieces = getConditionPieces;
19
+ /**
20
+ * Converts an object into a parameterized INSERT fragment.
21
+ *
22
+ * @param data - The key/value pairs to insert
23
+ * @returns Column names, positional placeholders ($1, $2...), and ordered input values
24
+ */
25
+ const getInsertPieces = (data = {}) => {
26
+ const keys = Object.keys(data).filter(key => (0, exports.isValidIdentifier)(key));
27
+ const columns = keys.join(', ');
28
+ const values = keys.map((_, i) => `$${i + 1}`).join(', ');
29
+ const inputs = keys.map(key => sanitizeValue(data[key]));
30
+ return { columns, values, inputs };
31
+ };
32
+ exports.getInsertPieces = getInsertPieces;
33
+ /**
34
+ * Validates that a SQL identifier (table/column name) contains only safe characters.
35
+ */
36
+ const isValidIdentifier = (name) => {
37
+ return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name);
38
+ };
39
+ exports.isValidIdentifier = isValidIdentifier;
40
+ /**
41
+ * Sanitizes a value for use as a SQL parameter.
42
+ * Converts undefined/NaN to null, booleans to true/false, bigint to string.
43
+ */
44
+ function sanitizeValue(value) {
45
+ if (value === undefined || value === null || (typeof value === 'number' && isNaN(value))) {
46
+ return null;
47
+ }
48
+ if (typeof value === 'boolean') {
49
+ return value;
50
+ }
51
+ if (typeof value === 'bigint') {
52
+ return value.toString();
53
+ }
54
+ return value;
55
+ }
56
+ //# sourceMappingURL=get_pieces.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"get_pieces.js","sourceRoot":"","sources":["../../operations/get_pieces.ts"],"names":[],"mappings":";;;AAWA;;;;;;;GAOG;AACI,MAAM,kBAAkB,GAAG,CAAC,IAAI,GAAwB,EAAE,EAAE,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AAE,MAAM,EAAE,CAAC;AACvC,CAAC,CAAC;AANW,QAAA,eAAe,GAAf,eAAe,CAM1B;AAEF;;GAEG;AACI,MAAM,iBAAiB,GAAG,CAAC,IAAY,EAAW,EAAE;IACvD,OAAO,0BAA0B,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACjD,CAAC,CAAC;AAFW,QAAA,iBAAiB,GAAjB,iBAAiB,CAE5B;AAEF;;;GAGG;AACH,SAAS,aAAa,CAAC,KAAU;IAC7B,IAAI,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC;QACvF,OAAO,IAAI,CAAC;IAChB,CAAC;IACD,IAAI,OAAO,KAAK,KAAK,SAAS,EAAE,CAAC;QAC7B,OAAO,KAAK,CAAC;IACjB,CAAC;IACD,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QAC5B,OAAO,KAAK,CAAC,QAAQ,EAAE,CAAC;IAC5B,CAAC;IACD,OAAO,KAAK,CAAC;AACjB,CAAC"}
@@ -0,0 +1,12 @@
1
+ import 'colors';
2
+ /**
3
+ * This function is used to display logs in the console.
4
+ *
5
+ * @param title - The title of the log.
6
+ * @param alt - The alternative title of the log.
7
+ * @param description - The description of the log.
8
+ * @param file - The file of the log.
9
+ */
10
+ declare function Log(title: string | null, alt: string | null, description: string | null, file?: string | null): void;
11
+ export declare const log: typeof Log;
12
+ export {};
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.log = void 0;
4
+ require("colors");
5
+ /**
6
+ * This function is used to display logs in the console.
7
+ *
8
+ * @param title - The title of the log.
9
+ * @param alt - The alternative title of the log.
10
+ * @param description - The description of the log.
11
+ * @param file - The file of the log.
12
+ */
13
+ function Log(title, alt, description, file = null) {
14
+ title = title ? (title.length > 20 ? title.substring(0, 20) + '...' : title) : null;
15
+ alt = alt ? (alt.length > 20 ? alt.substring(0, 20) + '...' : alt) : null;
16
+ description = description ? (description.length > 50 ? description.substring(0, 50) + '...' : description) : null;
17
+ file = file ? (file.length > 20 ? file.substring(0, 20) + '...' : file) : null;
18
+ let time = (new Date().toLocaleTimeString()).gray;
19
+ title = title ? ('[' + title.trim() + ']').cyan.bold : null;
20
+ alt = alt ? ('(' + alt.trim() + ')').magenta : null;
21
+ description = description ? description.trim().green : null;
22
+ file = file ? ('[' + file.trim() + ']').gray : 'easy-postgresql'.gray;
23
+ const data = [time, title, alt, description, file].filter(f => f !== null && f !== undefined);
24
+ console.log(data.join(' '));
25
+ }
26
+ exports.log = Log;
27
+ //# sourceMappingURL=log.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"log.js","sourceRoot":"","sources":["../../operations/log.ts"],"names":[],"mappings":";;;AAAA,kBAAgB;AAEhB;;;;;;;OAOO;AACP,SAAS,GAAG,CAAC,KAAoB,EAAE,GAAkB,EAAE,WAA0B,EAAE,IAAI,GAAkB,IAAI;IACzG,KAAK,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,GAAG,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;IACpF,GAAG,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,MAAM,GAAG,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;IAC1E,WAAW,GAAG,WAAW,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC,MAAM,GAAG,EAAE,CAAC,CAAC,CAAC,WAAW,CAAC,SAAS,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG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Y,QAAA,GAAG,GAAG,GAAG,CAAC"}
@@ -0,0 +1,18 @@
1
+ interface ProcedureResult {
2
+ status: number;
3
+ message: string;
4
+ data: any[] | any | null;
5
+ }
6
+ interface ProcedureReference {
7
+ [key: string]: any;
8
+ }
9
+ /**
10
+ * Executes a stored procedure/function in the database.
11
+ *
12
+ * @param procedureName - The name of the stored procedure/function
13
+ * @param reference - The input parameters for the procedure
14
+ * @param useRecordsets - If true, wraps rows in array; otherwise returns rows directly
15
+ * @returns Promise<ProcedureResult>
16
+ */
17
+ export declare const executeProcedure: (procedureName: string, reference?: ProcedureReference, useRecordsets?: boolean) => Promise<ProcedureResult>;
18
+ export {};
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.executeProcedure = void 0;
4
+ const connect_to_server_1 = require("./connect_to_server");
5
+ const config_1 = require("./config");
6
+ const log_1 = require("./log");
7
+ function pgTypeOf(value) {
8
+ if (value === null || value === undefined)
9
+ return 'text';
10
+ if (typeof value === 'number')
11
+ return Number.isInteger(value) ? 'integer' : 'float8';
12
+ if (typeof value === 'boolean')
13
+ return 'boolean';
14
+ if (value instanceof Date)
15
+ return 'timestamp';
16
+ if (Buffer.isBuffer(value))
17
+ return 'bytea';
18
+ return 'text';
19
+ }
20
+ /**
21
+ * Executes a stored procedure/function in the database.
22
+ *
23
+ * @param procedureName - The name of the stored procedure/function
24
+ * @param reference - The input parameters for the procedure
25
+ * @param useRecordsets - If true, wraps rows in array; otherwise returns rows directly
26
+ * @returns Promise<ProcedureResult>
27
+ */
28
+ const executeProcedure = async (procedureName, reference = {}, useRecordsets = false) => {
29
+ try {
30
+ const keys = Object.keys(reference);
31
+ const values = keys.map(k => reference[k]);
32
+ const params = keys.map((_, i) => `$${i + 1}::${pgTypeOf(values[i])}`).join(', ');
33
+ const queryText = `SELECT * FROM ${procedureName}(${params})`;
34
+ const pool = (0, connect_to_server_1.getPool)();
35
+ const client = await pool.connect();
36
+ try {
37
+ const result = await client.query(queryText, values);
38
+ const data = useRecordsets ? [result.rows] : result.rows;
39
+ return { status: 200, message: 'Success', data };
40
+ }
41
+ finally {
42
+ client.release();
43
+ }
44
+ }
45
+ catch (err) {
46
+ if (config_1.config.get.logingMode()) {
47
+ (0, log_1.log)('Procedure', procedureName, err instanceof Error ? err.message : String(err));
48
+ }
49
+ return { status: 500, message: 'Error', data: null };
50
+ }
51
+ };
52
+ exports.executeProcedure = executeProcedure;
53
+ //# sourceMappingURL=procedure_execute.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"procedure_execute.js","sourceRoot":"","sources":["../../operations/procedure_execute.ts"],"names":[],"mappings":";;;AAAA,2DAA8C;AAC9C,qCAAkC;AAClC,+BAA4B;AAY5B,SAAS,QAAQ,CAAC,KAAU;IACxB,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS;QAAE,OAAO,MAAM,CAAC;IACzD,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,QAAQ,CAAC;IACrF,IAAI,OAAO,KAAK,KAAK,SAAS;QAAE,OAAO,SAAS,CAAC;IACjD,IAAI,KAAK,YAAY,IAAI;QAAE,OAAO,WAAW,CAAC;IAC9C,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC;QAAE,OAAO,OAAO,CAAC;IAC3C,OAAO,MAAM,CAAC;AAClB,CAAC;AAED;;;;;;;GAOG;AACI,MAAM,gBAAgB,GAAG,KAAK,EACjC,aAAqB,EACrB,SAAS,GAAuB,EAAE,EAClC,aAAa,GAAY,KAAK,EACN,EAAE;IAC1B,IAAI,CAAC;QACD,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QACpC,MAAM,MAAM,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,SAAS,CAAC,CA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0,0 +1,28 @@
1
+ import 'colors';
2
+
3
+ let logingMode = false;
4
+
5
+ /**
6
+ * This function is used to set the output format of the query result.
7
+ *
8
+ * @param mode - This parameter is used to set the output format of the query result.
9
+ */
10
+ function setLogingMode(mode = false): void {
11
+ if (typeof mode !== 'boolean') throw new Error('Invalid parameter type. Expected boolean.');
12
+ logingMode = mode;
13
+ }
14
+
15
+ /**
16
+ * This function is used to get the current output format of the query result.
17
+ * @file config.ts
18
+ * @description This file contains the configuration operations.
19
+ * @module
20
+ */
21
+ export const config = {
22
+ get: {
23
+ logingMode: (): boolean => logingMode,
24
+ },
25
+ set: {
26
+ logingMode: setLogingMode
27
+ }
28
+ };
@@ -0,0 +1,111 @@
1
+ import { Pool, PoolConfig } from 'pg';
2
+ import { config } from './config';
3
+ import { log } from './log';
4
+
5
+ export interface SqlConfig {
6
+ user?: string;
7
+ password?: string;
8
+ host?: string;
9
+ port?: number;
10
+ database?: string;
11
+ [key: string]: any;
12
+ }
13
+
14
+ export type RunCallback = (sqlConfig: SqlConfig, err?: Error) => void;
15
+
16
+ let pool: Pool | null = null;
17
+
18
+ export function getPool(): Pool {
19
+ if (!pool) throw new Error('Database not connected. Call Connect() first.');
20
+ return pool;
21
+ }
22
+
23
+ /**
24
+ * This function checks if the database connection is active
25
+ *
26
+ * @returns Promise<boolean> - Returns true if connection is active, false otherwise
27
+ */
28
+ export const isConnected = async (): Promise<{ status: number, message: string }> => {
29
+ try {
30
+ const p = getPool();
31
+ const client = await p.connect();
32
+ try {
33
+ await client.query('SELECT 1');
34
+ } finally {
35
+ client.release();
36
+ }
37
+ return { status: 200, message: 'OK' }
38
+ } catch (err) {
39
+ return { status: 500, message: 'Error: ' + String(err) }
40
+ }
41
+ };
42
+
43
+ /**
44
+ * This function is used to connect to the database.
45
+ *
46
+ * @param sqlConfig - The PostgreSQL configuration to connect to the database
47
+ * @param run - Optional callback function to be executed after the connection is established
48
+ * @returns Promise<boolean> - Returns true if connection is successful, false otherwise
49
+ */
50
+ export const connectToServer = async (sqlConfig: SqlConfig, run?: RunCallback): Promise<boolean> => {
51
+ if (!sqlConfig || typeof sqlConfig !== 'object') {
52
+ if (config.get.logingMode()) log('Connection', null, 'The sqlConfig parameter is not an object.');
53
+ return false;
54
+ }
55
+
56
+ const required: Record<string, string> = { user: "string", password: "string", host: "string", database: "string" };
57
+ for (const key in required) {
58
+ if (!sqlConfig[key as keyof SqlConfig] || typeof sqlConfig[key as keyof SqlConfig] !== required[key]) {
59
+ if (config.get.logingMode()) log('Connection', null, `The ${key} parameter is not a ${required[key]}.`);
60
+ return false;
61
+ }
62
+ }
63
+
64
+ pool = new Pool({
65
+ user: sqlConfig.user,
66
+ password: sqlConfig.password,
67
+ host: sqlConfig.host,
68
+ port: sqlConfig.port || 5432,
69
+ database: sqlConfig.database,
70
+ });
71
+
72
+ const maxRetries = 3;
73
+ const retryInterval = 2500;
74
+ let retryCount = 0;
75
+
76
+ const tryConnect = async (): Promise<boolean> => {
77
+ try {
78
+ const client = await pool!.connect();
79
+ try {
80
+ await client.query('SELECT 1');
81
+ } finally {
82
+ client.release();
83
+ }
84
+ if (run && typeof run === 'function') {
85
+ run(sqlConfig);
86
+ }
87
+ if (config.get.logingMode()) log('Connection', null, 'Success');
88
+ return true;
89
+ } catch (err) {
90
+ if (config.get.logingMode()) log('Connection', 'Attempt', `${retryCount + 1}: ${err instanceof Error ? err.message : String(err)}`);
91
+ if (run && typeof run === 'function') {
92
+ run(sqlConfig, err instanceof Error ? err : new Error(String(err)));
93
+ }
94
+ return false;
95
+ }
96
+ };
97
+
98
+ while (retryCount < maxRetries) {
99
+ const result = await tryConnect();
100
+ if (result) return true;
101
+
102
+ retryCount++;
103
+ if (retryCount < maxRetries) {
104
+ if (config.get.logingMode()) log('Connection', 'Retry', `Retrying in 2.5s... (Attempt ${retryCount + 1}/${maxRetries})`);
105
+ await new Promise(resolve => setTimeout(resolve, retryInterval));
106
+ }
107
+ }
108
+
109
+ if (config.get.logingMode()) log('Connection', null, `Failed after ${maxRetries} attempts`);
110
+ return false;
111
+ };