@onurege3467/zerohelper 8.0.0 → 9.0.0

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 (48) hide show
  1. package/README.md +292 -612
  2. package/dist/database/IDatabase.d.ts +77 -0
  3. package/dist/database/IDatabase.js +10 -0
  4. package/dist/database/cacheWrapper.d.ts +31 -0
  5. package/dist/database/cacheWrapper.js +228 -0
  6. package/dist/database/index.d.ts +11 -0
  7. package/dist/database/index.js +94 -0
  8. package/dist/database/json.d.ts +32 -0
  9. package/dist/database/json.js +210 -0
  10. package/dist/database/migration.d.ts +21 -0
  11. package/dist/database/migration.js +97 -0
  12. package/dist/database/mongodb.d.ts +24 -0
  13. package/dist/database/mongodb.js +153 -0
  14. package/dist/database/mysql.d.ts +31 -0
  15. package/dist/database/mysql.js +385 -0
  16. package/dist/database/pg.d.ts +30 -0
  17. package/dist/database/pg.js +300 -0
  18. package/dist/database/redis.d.ts +23 -0
  19. package/dist/database/redis.js +157 -0
  20. package/dist/database/sqlite.d.ts +25 -0
  21. package/dist/database/sqlite.js +273 -0
  22. package/dist/database/types.d.ts +76 -0
  23. package/dist/database/types.js +2 -0
  24. package/dist/database/zpack.d.ts +59 -0
  25. package/dist/database/zpack.js +462 -0
  26. package/dist/functions/index.d.ts +183 -0
  27. package/dist/functions/index.js +636 -0
  28. package/dist/functions/temp_isphone.d.ts +1 -0
  29. package/dist/functions/temp_isphone.js +7 -0
  30. package/dist/index.d.ts +8 -0
  31. package/dist/index.js +45 -0
  32. package/dist/test.d.ts +1 -0
  33. package/dist/test.js +55 -0
  34. package/dist/test_zpack.d.ts +1 -0
  35. package/dist/test_zpack.js +64 -0
  36. package/package.json +23 -6
  37. package/database/IDatabase.js +0 -92
  38. package/database/cacheWrapper.js +0 -585
  39. package/database/index.js +0 -72
  40. package/database/json.js +0 -281
  41. package/database/migration.js +0 -227
  42. package/database/mongodb.js +0 -203
  43. package/database/mysql.js +0 -526
  44. package/database/pg.js +0 -527
  45. package/database/redis.js +0 -342
  46. package/database/sqlite.js +0 -551
  47. package/functions/index.js +0 -705
  48. package/index.js +0 -7
@@ -0,0 +1,385 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.MySQLDatabase = void 0;
7
+ const IDatabase_1 = require("./IDatabase");
8
+ const promise_1 = __importDefault(require("mysql2/promise"));
9
+ class MySQLDatabase extends IDatabase_1.IDatabase {
10
+ constructor(config) {
11
+ super();
12
+ this.pool = null;
13
+ this._queue = [];
14
+ this._connected = false;
15
+ this.config = config;
16
+ this._connectionPromise = new Promise(async (resolve, reject) => {
17
+ try {
18
+ const connection = await promise_1.default.createConnection({
19
+ host: config.host,
20
+ port: config.port || 3306,
21
+ user: config.user,
22
+ password: config.password,
23
+ typeCast: (field, next) => {
24
+ if (field.type === 'TINY' && field.length === 1) {
25
+ return (field.string() === '1');
26
+ }
27
+ if (['INT', 'DECIMAL', 'NEWDECIMAL', 'FLOAT', 'DOUBLE'].includes(field.type)) {
28
+ return Number(field.string());
29
+ }
30
+ return next();
31
+ }
32
+ });
33
+ await connection.query(`CREATE DATABASE IF NOT EXISTS
34
+ ${config.database}
35
+ `);
36
+ await connection.end();
37
+ this.pool = promise_1.default.createPool({
38
+ host: config.host,
39
+ port: config.port || 3306,
40
+ user: config.user,
41
+ password: config.password,
42
+ database: config.database,
43
+ waitForConnections: true,
44
+ connectionLimit: config.connectionLimit || 10,
45
+ queueLimit: 0,
46
+ typeCast: (field, next) => {
47
+ if (field.type === 'TINY' && field.length === 1) {
48
+ return (field.string() === '1');
49
+ }
50
+ if (['INT', 'DECIMAL', 'NEWDECIMAL', 'FLOAT', 'DOUBLE'].includes(field.type)) {
51
+ return Number(field.string());
52
+ }
53
+ return next();
54
+ }
55
+ });
56
+ this._connected = true;
57
+ resolve(this.pool);
58
+ this._processQueue();
59
+ }
60
+ catch (error) {
61
+ console.error("MySQL connection error:", error);
62
+ reject(error);
63
+ }
64
+ });
65
+ }
66
+ _getColumnType(value) {
67
+ if (value === null || value === undefined)
68
+ return 'TEXT';
69
+ if (typeof value === 'boolean')
70
+ return 'BOOLEAN';
71
+ if (typeof value === 'number') {
72
+ if (Number.isInteger(value)) {
73
+ if (value >= -128 && value <= 127)
74
+ return 'TINYINT';
75
+ if (value >= -32768 && value <= 32767)
76
+ return 'SMALLINT';
77
+ if (value >= -2147483648 && value <= 2147483647)
78
+ return 'INT';
79
+ return 'BIGINT';
80
+ }
81
+ return 'DOUBLE';
82
+ }
83
+ if (typeof value === 'string') {
84
+ const length = value.length;
85
+ if (length <= 255)
86
+ return 'VARCHAR(255)';
87
+ if (length <= 65535)
88
+ return 'TEXT';
89
+ if (length <= 16777215)
90
+ return 'MEDIUMTEXT';
91
+ return 'LONGTEXT';
92
+ }
93
+ if (typeof value === 'object') {
94
+ const jsonString = JSON.stringify(value);
95
+ return jsonString.length <= 65535 ? 'JSON' : 'LONGTEXT';
96
+ }
97
+ if (value instanceof Date)
98
+ return 'DATETIME';
99
+ return 'TEXT';
100
+ }
101
+ _getBestColumnType(values) {
102
+ const types = values.map(val => this._getColumnType(val));
103
+ const uniqueTypes = [...new Set(types)];
104
+ if (uniqueTypes.length === 1)
105
+ return uniqueTypes[0];
106
+ const typePriority = {
107
+ 'LONGTEXT': 10, 'MEDIUMTEXT': 9, 'TEXT': 8, 'JSON': 7, 'VARCHAR(255)': 6,
108
+ 'DATETIME': 5, 'DOUBLE': 4, 'BIGINT': 3, 'INT': 2, 'SMALLINT': 1, 'TINYINT': 0, 'BOOLEAN': -1
109
+ };
110
+ return uniqueTypes.sort((a, b) => (typePriority[b] || 0) - (typePriority[a] || 0))[0];
111
+ }
112
+ async _ensureMissingColumns(table, data) {
113
+ const existingColumns = await this.query(`DESCRIBE
114
+ ${table}
115
+ `).catch(() => []);
116
+ const existingColumnNames = existingColumns.map((col) => col.Field);
117
+ for (const key of Object.keys(data)) {
118
+ if (!existingColumnNames.includes(key)) {
119
+ const columnType = this._getColumnType(data[key]);
120
+ await this.query(`ALTER TABLE
121
+ ${table}
122
+ ADD COLUMN
123
+ ${key}
124
+ ${columnType}`);
125
+ }
126
+ }
127
+ }
128
+ async _queueRequest(operation) {
129
+ if (this._connected) {
130
+ return operation();
131
+ }
132
+ else {
133
+ return new Promise((resolve, reject) => {
134
+ this._queue.push({ operation, resolve, reject });
135
+ });
136
+ }
137
+ }
138
+ async _processQueue() {
139
+ if (!this._connected)
140
+ return;
141
+ while (this._queue.length > 0) {
142
+ const item = this._queue.shift();
143
+ if (item) {
144
+ try {
145
+ const result = await item.operation();
146
+ item.resolve(result);
147
+ }
148
+ catch (error) {
149
+ item.reject(error);
150
+ }
151
+ }
152
+ }
153
+ }
154
+ async query(sql, params = []) {
155
+ return this._queueRequest(async () => {
156
+ const pool = await this._connectionPromise;
157
+ const [rows] = await pool.execute(sql, params);
158
+ return rows;
159
+ });
160
+ }
161
+ async ensureTable(table, data = {}) {
162
+ return this._queueRequest(async () => {
163
+ const escapedTable = promise_1.default.escape(table);
164
+ const tables = await this.query(`SHOW TABLES LIKE ${escapedTable}`);
165
+ if (tables.length === 0) {
166
+ const columnDefinitions = Object.keys(data).map(col => {
167
+ const columnType = this._getColumnType(data[col]);
168
+ return `
169
+ ${col}
170
+ ${columnType}`;
171
+ });
172
+ const columnsPart = columnDefinitions.length > 0 ? ', ' + columnDefinitions.join(", ") : '';
173
+ const createTableSQL = `
174
+ CREATE TABLE
175
+ ${table}
176
+ (
177
+ _id INT PRIMARY KEY AUTO_INCREMENT
178
+ ${columnsPart}
179
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
180
+ `;
181
+ await this.query(createTableSQL);
182
+ }
183
+ });
184
+ }
185
+ async insert(table, data) {
186
+ return this._queueRequest(async () => {
187
+ const copy = { ...data };
188
+ await this.ensureTable(table, copy);
189
+ await this._ensureMissingColumns(table, copy);
190
+ const existingColumns = await this.query(`DESCRIBE
191
+ ${table}
192
+ `);
193
+ const primaryKeyColumn = existingColumns.find(col => col.Key === 'PRI' && col.Extra.includes('auto_increment'));
194
+ if (primaryKeyColumn && copy[primaryKeyColumn.Field] !== undefined) {
195
+ delete copy[primaryKeyColumn.Field];
196
+ }
197
+ const keys = Object.keys(copy);
198
+ const placeholders = keys.map(() => "?").join(",");
199
+ const values = Object.values(copy).map(value => this._serializeValue(value));
200
+ const sql = `INSERT INTO
201
+ ${table}
202
+ (${keys.map(k => `
203
+ ${k}
204
+ `).join(",")}) VALUES (${placeholders})`;
205
+ const result = await this.query(sql, values);
206
+ return result.insertId;
207
+ });
208
+ }
209
+ async update(table, data, where) {
210
+ return this._queueRequest(async () => {
211
+ await this.ensureTable(table, { ...data, ...where });
212
+ await this._ensureMissingColumns(table, { ...data, ...where });
213
+ const setString = Object.keys(data).map(k => `
214
+ ${k}
215
+ = ?`).join(", ");
216
+ const whereString = Object.keys(where).map(k => `
217
+ ${k}
218
+ = ?`).join(" AND ");
219
+ const sql = `UPDATE
220
+ ${table}
221
+ SET ${setString} WHERE ${whereString}`;
222
+ const values = [...Object.values(data).map(v => this._serializeValue(v)), ...Object.values(where).map(v => this._serializeValue(v))];
223
+ const result = await this.query(sql, values);
224
+ return result.affectedRows;
225
+ });
226
+ }
227
+ async delete(table, where) {
228
+ return this._queueRequest(async () => {
229
+ if (!where || Object.keys(where).length === 0)
230
+ return 0;
231
+ await this.ensureTable(table, { ...where });
232
+ await this._ensureMissingColumns(table, where);
233
+ const whereString = Object.keys(where).map(k => `
234
+ ${k}
235
+ = ?`).join(" AND ");
236
+ const sql = `DELETE FROM
237
+ ${table}
238
+ WHERE ${whereString}`;
239
+ const result = await this.query(sql, Object.values(where).map(v => this._serializeValue(v)));
240
+ return result.affectedRows;
241
+ });
242
+ }
243
+ async select(table, where = null) {
244
+ return this._queueRequest(async () => {
245
+ await this.ensureTable(table, where || {});
246
+ if (where && Object.keys(where).length > 0) {
247
+ await this._ensureMissingColumns(table, where);
248
+ }
249
+ let sql = `SELECT * FROM
250
+ ${table}
251
+ `;
252
+ let params = [];
253
+ if (where && Object.keys(where).length > 0) {
254
+ const whereString = Object.keys(where).map(k => `
255
+ ${k}
256
+ = ?`).join(" AND ");
257
+ sql += ` WHERE ${whereString}`;
258
+ params = Object.values(where).map(v => this._serializeValue(v));
259
+ }
260
+ const rows = await this.query(sql, params);
261
+ return rows.map((row) => {
262
+ const newRow = {};
263
+ for (const key in row) {
264
+ newRow[key] = this._deserializeValue(row[key]);
265
+ }
266
+ return newRow;
267
+ });
268
+ });
269
+ }
270
+ async set(table, data, where) {
271
+ return this._queueRequest(async () => {
272
+ const existing = await this.select(table, where);
273
+ if (existing.length === 0) {
274
+ return await this.insert(table, { ...where, ...data });
275
+ }
276
+ else {
277
+ return await this.update(table, data, where);
278
+ }
279
+ });
280
+ }
281
+ async selectOne(table, where = null) {
282
+ const results = await this.select(table, where);
283
+ return results[0] || null;
284
+ }
285
+ async bulkInsert(table, dataArray) {
286
+ return this._queueRequest(async () => {
287
+ if (!Array.isArray(dataArray) || dataArray.length === 0)
288
+ return 0;
289
+ await this.ensureTable(table, dataArray[0]);
290
+ const existingColumns = await this.query(`DESCRIBE
291
+ ${table}
292
+ `);
293
+ const existingColumnNames = existingColumns.map((col) => col.Field);
294
+ const allKeys = new Set();
295
+ dataArray.forEach(obj => Object.keys(obj).forEach(key => allKeys.add(key)));
296
+ for (const key of allKeys) {
297
+ if (!existingColumnNames.includes(key)) {
298
+ const columnValues = dataArray.map(obj => obj[key]).filter(val => val !== undefined && val !== null);
299
+ const columnType = columnValues.length > 0 ? this._getBestColumnType(columnValues) : 'TEXT';
300
+ await this.query(`ALTER TABLE
301
+ ${table}
302
+ ADD COLUMN
303
+ ${key}
304
+ ${columnType}`);
305
+ }
306
+ }
307
+ const keys = Array.from(allKeys);
308
+ const placeholders = dataArray.map(() => `(${keys.map(() => '?').join(',')})`).join(',');
309
+ const values = dataArray.flatMap(obj => keys.map(k => this._serializeValue(obj[k])));
310
+ const sql = `INSERT INTO
311
+ ${table}
312
+ (${keys.map(k => `
313
+ ${k}
314
+ `).join(",")}) VALUES ${placeholders}`;
315
+ const result = await this.query(sql, values);
316
+ return result.affectedRows;
317
+ });
318
+ }
319
+ async close() {
320
+ if (this.pool)
321
+ await this.pool.end();
322
+ }
323
+ _serializeValue(value) {
324
+ if (value instanceof Date)
325
+ return value.toISOString().slice(0, 19).replace('T', ' ');
326
+ if (Array.isArray(value) || (typeof value === 'object' && value !== null))
327
+ return JSON.stringify(value);
328
+ return value;
329
+ }
330
+ _deserializeValue(value) {
331
+ try {
332
+ if (typeof value === 'string' && (value.startsWith('[') || value.startsWith('{'))) {
333
+ const parsed = JSON.parse(value);
334
+ if (typeof parsed === 'object' && parsed !== null)
335
+ return parsed;
336
+ }
337
+ }
338
+ catch (e) { }
339
+ return value;
340
+ }
341
+ async increment(table, increments, where = {}) {
342
+ return this._queueRequest(async () => {
343
+ const incrementClauses = Object.keys(increments).map(field => `
344
+ ${field}
345
+ =
346
+ ${field}
347
+ + ?`).join(', ');
348
+ const incrementValues = Object.values(increments);
349
+ const { whereClause, values: whereValues } = this._buildWhereClause(where);
350
+ const sql = `UPDATE
351
+ ${table}
352
+ SET ${incrementClauses}${whereClause}`;
353
+ const result = await this.query(sql, [...incrementValues, ...whereValues]);
354
+ return result.affectedRows;
355
+ });
356
+ }
357
+ async decrement(table, decrements, where = {}) {
358
+ return this._queueRequest(async () => {
359
+ const decrementClauses = Object.keys(decrements).map(field => `
360
+ ${field}
361
+ =
362
+ ${field}
363
+ + ?`).join(', ');
364
+ const decrementValues = Object.values(decrements);
365
+ const { whereClause, values: whereValues } = this._buildWhereClause(where);
366
+ const sql = `UPDATE
367
+ ${table}
368
+ SET ${decrementClauses}${whereClause}`;
369
+ const result = await this.query(sql, [...decrementValues, ...whereValues]);
370
+ return result.affectedRows;
371
+ });
372
+ }
373
+ _buildWhereClause(where = {}) {
374
+ const conditions = Object.keys(where);
375
+ if (conditions.length === 0)
376
+ return { whereClause: '', values: [] };
377
+ const whereClause = ' WHERE ' + conditions.map(key => `
378
+ ${key}
379
+ = ?`).join(' AND ');
380
+ const values = Object.values(where).map(v => this._serializeValue(v));
381
+ return { whereClause, values };
382
+ }
383
+ }
384
+ exports.MySQLDatabase = MySQLDatabase;
385
+ exports.default = MySQLDatabase;
@@ -0,0 +1,30 @@
1
+ import { IDatabase } from './IDatabase';
2
+ import { PostgreSQLConfig } from './types';
3
+ export declare class PostgreSQLDatabase extends IDatabase {
4
+ private config;
5
+ private pool;
6
+ private _queue;
7
+ private _connected;
8
+ private _connectionPromise;
9
+ constructor(config: PostgreSQLConfig);
10
+ private _getColumnType;
11
+ private _getBestColumnType;
12
+ private _ensureMissingColumns;
13
+ private _queueRequest;
14
+ private _processQueue;
15
+ query(sql: string, params?: any[]): Promise<any>;
16
+ ensureTable(table: string, data?: Record<string, any>): Promise<void>;
17
+ insert(table: string, data: Record<string, any>): Promise<any>;
18
+ update(table: string, data: Record<string, any>, where: Record<string, any>): Promise<number>;
19
+ delete(table: string, where: Record<string, any>): Promise<number>;
20
+ select<T = any>(table: string, where?: Record<string, any> | null): Promise<T[]>;
21
+ set(table: string, data: Record<string, any>, where: Record<string, any>): Promise<any>;
22
+ selectOne<T = any>(table: string, where?: Record<string, any> | null): Promise<T | null>;
23
+ bulkInsert(table: string, dataArray: Record<string, any>[]): Promise<number>;
24
+ close(): Promise<void>;
25
+ private _serializeValue;
26
+ increment(table: string, increments: Record<string, number>, where?: Record<string, any>): Promise<number>;
27
+ decrement(table: string, decrements: Record<string, number>, where?: Record<string, any>): Promise<number>;
28
+ private _buildWhereClause;
29
+ }
30
+ export default PostgreSQLDatabase;