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
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 cihatksm, https://cihatksm.com/
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,45 @@
1
+ #### Module Download
2
+
3
+ ```bash
4
+ npm install easy-postgresql
5
+ ```
6
+
7
+ #### Simple Usage
8
+ ```js
9
+ const config = require('./config');
10
+
11
+ const { Connect, Table, Request } = require('easy-postgresql');
12
+
13
+ const date = () => new Date();
14
+ console.log(date(), 'System opened!');
15
+
16
+ Connect(config.sql);
17
+
18
+ setTimeout(async () => {
19
+ // const user = await Table('company').findOne({ id: 1 });
20
+ // console.log(user);
21
+
22
+ // const info = await Table('company').functions.info();
23
+ // console.log(info);
24
+
25
+ // const procedure = await Request.procedure('GetCompany', { companyId: 1 });
26
+ // console.log(procedure);
27
+
28
+ // const query = await Request.query('SELECT * FROM company');
29
+ // console.log(query);
30
+
31
+ // const simple_scheme = require('./simple_scheme');
32
+ // const createdTable = await Table('company').functions.create(simple_scheme.dataTypes);
33
+ // console.log(createdTable);
34
+
35
+ // const removedTable = await Table('company').functions.remove();
36
+ // console.log(removedTable);
37
+ }, 1000);
38
+
39
+ ```
40
+
41
+ [![MIT License](https://img.shields.io/badge/License-MIT-green.svg)](https://choosealicense.com/licenses/mit/)
42
+
43
+ #### Feedback
44
+
45
+ **E-mail:** me@cihatksm.com
package/SECURITY.md ADDED
@@ -0,0 +1,15 @@
1
+ # Security Policy
2
+
3
+ ## Reporting a Vulnerability
4
+
5
+ Use this section to tell people how to report a vulnerability.
6
+ Tell them where to go, how often they can expect to get an update on a reported vulnerability, what to expect if the vulnerability is accepted or declined, etc.
7
+
8
+ To report a vulnerability, please visit our support website at cihatksm.com.
9
+ We take full responsibility for all rights and ensure continuous support throughout the process.
10
+ Once you submit a vulnerability, you can expect regular updates on its status.
11
+ If the vulnerability is accepted, appropriate actions will be taken to address it.
12
+ If it is declined, we will provide an explanation. Thank you for your cooperation.
13
+
14
+ All rights reserved.
15
+ cihatksm.com, 2025 © cihatksm
@@ -0,0 +1,129 @@
1
+ import { executeProcedure } from '../operations/procedure_execute';
2
+ import { sqlTypes } from '../operations/data_types';
3
+ import { config } from '../operations/config';
4
+ import { Query } from './query';
5
+ import { log } from '../operations/log';
6
+
7
+ interface ProcedureInfo {
8
+ name: string;
9
+ type: string;
10
+ date: string | null;
11
+ }
12
+
13
+ interface ProcedureOutput {
14
+ name: string;
15
+ type: string;
16
+ }
17
+
18
+ interface ProcedureResult {
19
+ status: number;
20
+ message: string;
21
+ data: any[] | null;
22
+ }
23
+
24
+ interface ProcedureReference {
25
+ [key: string]: any;
26
+ }
27
+
28
+ /**
29
+ * All functions in the procedure are defined in this class.
30
+ *
31
+ * @param name - The name of the procedure to be added to the procedure
32
+ * @returns Object containing procedure methods
33
+ */
34
+ export function Procedure(name = '') {
35
+ /**
36
+ * Returns information about the procedure in the database.
37
+ * @returns Promise<ProcedureInfo | null> - Information about the procedure
38
+ */
39
+ async function Info(): Promise<ProcedureInfo | null> {
40
+ if (!name) return null;
41
+
42
+ const queryString = `SELECT routine_name FROM information_schema.routines WHERE routine_type = 'FUNCTION' AND routine_schema = 'public' AND LOWER(routine_name) = LOWER($1)`;
43
+ const queryOutput = await Query(queryString, [name]);
44
+ if (queryOutput?.status !== 200) {
45
+ if (config.get.logingMode()) log('Procedure', 'Info', `The ${name} procedure not found.`)
46
+ return null;
47
+ }
48
+
49
+ const data = queryOutput?.data?.[0] || null;
50
+ if (!data) return null;
51
+
52
+ return {
53
+ name: data.routine_name,
54
+ type: 'Function',
55
+ date: null
56
+ };
57
+ }
58
+
59
+ /**
60
+ * Returns information about all procedures in the database.
61
+ * @returns Promise<ProcedureInfo[] | null> - Information about all procedures
62
+ */
63
+ async function AllInfo(): Promise<ProcedureInfo[] | null> {
64
+ const queryString = `SELECT routine_name FROM information_schema.routines WHERE routine_type = 'FUNCTION' AND routine_schema = 'public'`;
65
+ const queryOutput = await Query(queryString);
66
+ if (queryOutput?.status !== 200) {
67
+ if (config.get.logingMode()) log('Procedure', 'All Info', 'Procedures not found.')
68
+ return null;
69
+ }
70
+
71
+ const data = queryOutput?.data || [];
72
+ if (!data) return null;
73
+
74
+ return data.map(m => ({
75
+ name: m.routine_name,
76
+ type: 'Function',
77
+ date: null
78
+ }));
79
+ }
80
+
81
+ /**
82
+ * Gets the output schema of the procedure in the database.
83
+ * @returns Promise<Record<string, string>> - The output schema of the procedure
84
+ */
85
+ async function SimpleOutput(): Promise<Record<string, string>> {
86
+ if (!name) return {};
87
+ return {};
88
+ }
89
+
90
+ /**
91
+ * Executes the procedure in the database
92
+ *
93
+ * @param reference - The reference parameters to be executed in the database
94
+ * @param useRecordsets - If true, returns result?.recordsets; otherwise returns result?.recordset (default: false)
95
+ * @returns Promise<ProcedureResult> - The result of the procedure execution
96
+ */
97
+ async function Execute(reference: ProcedureReference = {}, useRecordsets: boolean = false): Promise<ProcedureResult> {
98
+ let procedureOutput = await executeProcedure(name, reference, useRecordsets);
99
+ if (procedureOutput?.status !== 200) {
100
+ if (config.get.logingMode()) log('Procedure', 'Execute', `The ${name} procedure could not be executed.`);
101
+ return { status: 501, message: 'The procedure could not be executed.', data: [] };
102
+ }
103
+
104
+ let data = procedureOutput?.data || null;
105
+
106
+ if (Array.isArray(data) && data.length > 0 && useRecordsets == false) {
107
+ const schema = await SimpleOutput();
108
+ if (schema && Object.keys(schema).length > 0) {
109
+ data = data.map(m => {
110
+ const keys = Object.keys(m);
111
+ if (keys.length !== Object.keys(schema).length) return null;
112
+ const new_data: Record<string, any> = {};
113
+ keys.forEach(key => new_data[key] = sqlTypes[schema[key]](m[key]));
114
+ return new_data;
115
+ }).filter(f => f !== null);
116
+ }
117
+ }
118
+
119
+ procedureOutput.data = data;
120
+ return procedureOutput;
121
+ }
122
+
123
+ return {
124
+ Execute,
125
+ Info,
126
+ AllInfo,
127
+ SimpleOutput
128
+ };
129
+ }
@@ -0,0 +1,78 @@
1
+ import { getPool } from '../operations/connect_to_server';
2
+ import { config } from '../operations/config';
3
+ import { log } from '../operations/log';
4
+
5
+ export interface QueryResult {
6
+ status: number;
7
+ message: string;
8
+ data: any[] | null;
9
+ }
10
+
11
+ function pgTypeOf(value: any): string {
12
+ if (value === null || value === undefined) return 'text';
13
+ if (typeof value === 'number') return Number.isInteger(value) ? 'integer' : 'float8';
14
+ if (typeof value === 'boolean') return 'boolean';
15
+ if (value instanceof Date) return 'timestamp';
16
+ if (Buffer.isBuffer(value)) return 'bytea';
17
+ return 'text';
18
+ }
19
+
20
+ function convertNamedToPositional(query: string, inputs: Record<string, any>): { text: string; values: any[] } {
21
+ const paramRegex = /@(\w+)/g;
22
+ const params: string[] = [];
23
+ let match;
24
+ while ((match = paramRegex.exec(query)) !== null) {
25
+ if (!params.includes(match[1])) {
26
+ params.push(match[1]);
27
+ }
28
+ }
29
+
30
+ let text = query;
31
+ params.forEach((param, i) => {
32
+ const type = pgTypeOf(inputs[param]);
33
+ text = text.replace(new RegExp(`@${param}\\b`, 'g'), `$${i + 1}::${type}`);
34
+ });
35
+
36
+ const values = params.map(p => inputs[p] !== undefined ? inputs[p] : null);
37
+ return { text, values };
38
+ }
39
+
40
+ /**
41
+ * Executes a raw SQL query with optional parameterized inputs.
42
+ *
43
+ * @param query - The SQL query to execute. Use @paramName for named parameters or $1, $2 for positional.
44
+ * @param inputs - Optional key/value map of named parameters (Record) or ordered values array
45
+ * @returns Promise<QueryResult>
46
+ */
47
+ export const Query = async (query: string, inputs?: Record<string, any> | any[]): Promise<QueryResult> => {
48
+ try {
49
+ let text: string;
50
+ let values: any[];
51
+
52
+ if (Array.isArray(inputs)) {
53
+ text = query;
54
+ values = inputs;
55
+ } else if (inputs && typeof inputs === 'object') {
56
+ const converted = convertNamedToPositional(query, inputs);
57
+ text = converted.text;
58
+ values = converted.values;
59
+ } else {
60
+ text = query;
61
+ values = [];
62
+ }
63
+
64
+ const pool = getPool();
65
+ const client = await pool.connect();
66
+ try {
67
+ const result = await client.query(text, values);
68
+ return { status: 200, message: 'Success', data: result.rows || null };
69
+ } finally {
70
+ client.release();
71
+ }
72
+ } catch (err) {
73
+ if (config.get.logingMode()) {
74
+ log('Query', null, `${query} : ${err instanceof Error ? err.message : String(err)}`);
75
+ }
76
+ return { status: 500, message: String(err), data: null };
77
+ }
78
+ };
@@ -0,0 +1,52 @@
1
+ /**
2
+ * This object contains the SQL data types.
3
+ * @file sql_types.d.ts
4
+ * @description This file contains the SQL data types.
5
+ * @module
6
+ */
7
+
8
+ interface SqlTypeOptions {
9
+ notNull: () => string;
10
+ primaryKey: () => string;
11
+ unique: () => string;
12
+ autoIncrement: () => string;
13
+ default: (value?: any) => string;
14
+ check: (value?: any) => string;
15
+ foreignKey: (table?: string, column?: string) => string;
16
+ }
17
+
18
+ interface SqlTypes {
19
+ varchar: (length?: number) => string;
20
+ nvarchar: (length?: number) => string;
21
+ int: () => string;
22
+ bigint: () => string;
23
+ smallint: () => string;
24
+ tinyint: () => string;
25
+ bit: () => string;
26
+ float: () => string;
27
+ real: () => string;
28
+ decimal: (precision?: number, scale?: number) => string;
29
+ numeric: () => string;
30
+ money: () => string;
31
+ smallmoney: () => string;
32
+ date: () => string;
33
+ time: () => string;
34
+ datetime: () => string;
35
+ datetime2: () => string;
36
+ smalldatetime: () => string;
37
+ timestamp: () => string;
38
+ char: () => string;
39
+ nchar: () => string;
40
+ text: () => string;
41
+ ntext: () => string;
42
+ binary: () => string;
43
+ varbinary: () => string;
44
+ image: () => string;
45
+ uniqueidentifier: () => string;
46
+ sql_variant: () => string;
47
+ xml: () => string;
48
+ options: SqlTypeOptions;
49
+ }
50
+
51
+ declare const sqlTypes: SqlTypes;
52
+ export { sqlTypes, SqlTypes, SqlTypeOptions };
@@ -0,0 +1,90 @@
1
+ /**
2
+ * This object contains the SQL data types.
3
+ * @file sql_types.ts
4
+ * @description This file contains the SQL data types.
5
+ * @module
6
+ */
7
+
8
+ export interface SqlTypeOptions {
9
+ notNull: () => string;
10
+ primaryKey: () => string;
11
+ unique: () => string;
12
+ autoIncrement: () => string;
13
+ default: (value?: any) => string;
14
+ check: (value?: any) => string;
15
+ foreignKey: (table?: string, column?: string) => string;
16
+ }
17
+
18
+ export interface SqlTypes {
19
+ varchar: (length?: number) => string;
20
+ nvarchar: (length?: number) => string;
21
+ int: () => string;
22
+ bigint: () => string;
23
+ smallint: () => string;
24
+ tinyint: () => string;
25
+ bit: () => string;
26
+ float: () => string;
27
+ real: () => string;
28
+ decimal: (precision?: number, scale?: number) => string;
29
+ numeric: () => string;
30
+ money: () => string;
31
+ smallmoney: () => string;
32
+ date: () => string;
33
+ time: () => string;
34
+ datetime: () => string;
35
+ datetime2: () => string;
36
+ smalldatetime: () => string;
37
+ timestamp: () => string;
38
+ char: () => string;
39
+ nchar: () => string;
40
+ text: () => string;
41
+ ntext: () => string;
42
+ binary: () => string;
43
+ varbinary: () => string;
44
+ image: () => string;
45
+ uniqueidentifier: () => string;
46
+ sql_variant: () => string;
47
+ xml: () => string;
48
+ options: SqlTypeOptions;
49
+ }
50
+
51
+ export const sqlTypes: SqlTypes = {
52
+ varchar: (length = 255) => typeof length === 'number' ? `VARCHAR(${length})` : 'VARCHAR(255)',
53
+ nvarchar: (length = 255) => typeof length === 'number' ? `VARCHAR(${length})` : 'VARCHAR(255)',
54
+ int: () => 'INT',
55
+ bigint: () => 'BIGINT',
56
+ smallint: () => 'SMALLINT',
57
+ tinyint: () => 'SMALLINT',
58
+ bit: () => 'BOOLEAN',
59
+ float: () => 'FLOAT',
60
+ real: () => 'REAL',
61
+ decimal: (precision = 18, scale = 0) => typeof precision === 'number' && typeof scale === 'number' ? `DECIMAL(${precision}, ${scale})` : 'DECIMAL(18, 0)',
62
+ numeric: () => 'NUMERIC',
63
+ money: () => 'NUMERIC(19,4)',
64
+ smallmoney: () => 'NUMERIC(10,4)',
65
+ date: () => 'DATE',
66
+ time: () => 'TIME',
67
+ datetime: () => 'TIMESTAMP',
68
+ datetime2: () => 'TIMESTAMP',
69
+ smalldatetime: () => 'TIMESTAMP',
70
+ timestamp: () => 'BYTEA',
71
+ char: () => 'CHAR',
72
+ nchar: () => 'CHAR',
73
+ text: () => 'TEXT',
74
+ ntext: () => 'TEXT',
75
+ binary: () => 'BYTEA',
76
+ varbinary: () => 'BYTEA',
77
+ image: () => 'BYTEA',
78
+ uniqueidentifier: () => 'UUID',
79
+ sql_variant: () => 'TEXT',
80
+ xml: () => 'XML',
81
+ options: {
82
+ notNull: () => ' ' + 'NOT NULL',
83
+ primaryKey: () => ' ' + 'PRIMARY KEY',
84
+ unique: () => ' ' + 'UNIQUE',
85
+ autoIncrement: () => ' ' + 'GENERATED ALWAYS AS IDENTITY',
86
+ default: (value?: any) => value !== undefined ? (' ' + `DEFAULT ${value}`) : '',
87
+ check: (value?: any) => value !== undefined ? (' ' + `CHECK(${value})`) : '',
88
+ foreignKey: (table?: string, column?: string) => table !== undefined && column !== undefined ? (' ' + `REFERENCES ${table}(${column})`) : ''
89
+ }
90
+ };