bonsaif 1.10.39 → 1.10.40

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.
@@ -1,85 +0,0 @@
1
- /**
2
- * Pruebas de conexiones MariaDB/MySQL
3
- * Ejecutar: node tests/test-mariadb.js
4
- *
5
- * NOTA: Requiere tabla de prueba. Ejecutar primero:
6
- * CREATE DATABASE IF NOT EXISTS test;
7
- * USE test;
8
- * CREATE TABLE IF NOT EXISTS test_users (
9
- * id INT AUTO_INCREMENT PRIMARY KEY,
10
- * name VARCHAR(100),
11
- * email VARCHAR(100),
12
- * created TIMESTAMP DEFAULT CURRENT_TIMESTAMP
13
- * );
14
- */
15
-
16
- const config = require('./config');
17
- const mariadb = require('../lib/hookup/mariadb');
18
-
19
- console.log('=== INICIANDO PRUEBAS MARIADB ===\n');
20
-
21
- async function testMariaDB() {
22
- const db = config.mariadb.options.db;
23
-
24
- try {
25
- // Test 1: INSERT
26
- console.log('1. Probando INSERT...');
27
- const insertQuery = "INSERT INTO test_users (name, email) VALUES ('Test User', 'test@example.com')";
28
- const insertResult = await mariadb.api(config.mariadb, db, insertQuery, 'insert', '127.0.0.1', 'test');
29
- console.log(' ✓ INSERT exitoso:', insertResult.result);
30
- const insertId = insertResult.data?.[0]?.insert_id;
31
-
32
- // Test 2: SELECT
33
- console.log('\n2. Probando SELECT...');
34
- const selectQuery = `SELECT * FROM test_users WHERE id = ${insertId}`;
35
- const selectResult = await mariadb.api(config.mariadb, db, selectQuery, 'select', '127.0.0.1', 'test');
36
- console.log(' ✓ SELECT exitoso:', selectResult.result);
37
- console.log(' Datos:', selectResult.data?.[0]);
38
-
39
- // Test 3: UPDATE
40
- console.log('\n3. Probando UPDATE...');
41
- const updateQuery = `UPDATE test_users SET email = 'updated@example.com' WHERE id = ${insertId}`;
42
- const updateResult = await mariadb.api(config.mariadb, db, updateQuery, 'update', '127.0.0.1', 'test');
43
- console.log(' ✓ UPDATE exitoso:', updateResult.result);
44
-
45
- // Test 4: SELECT con WHERE
46
- console.log('\n4. Probando SELECT con WHERE...');
47
- const selectWhereQuery = "SELECT * FROM test_users WHERE name LIKE '%Test%' LIMIT 10";
48
- const selectWhereResult = await mariadb.api(config.mariadb, db, selectWhereQuery, 'select', '127.0.0.1', 'test');
49
- console.log(' ✓ SELECT WHERE exitoso:', {
50
- count: selectWhereResult.data?.length,
51
- headers: selectWhereResult.result.headers
52
- });
53
-
54
- // Test 5: COUNT
55
- console.log('\n5. Probando COUNT...');
56
- const countQuery = "SELECT COUNT(*) as total FROM test_users";
57
- const countResult = await mariadb.api(config.mariadb, db, countQuery, 'select', '127.0.0.1', 'test');
58
- console.log(' ✓ COUNT exitoso:', countResult.data?.[0]);
59
-
60
- // Test 6: Stored Procedure (si existe)
61
- console.log('\n6. Probando CALL (stored procedure)...');
62
- try {
63
- const callQuery = "CALL sp_test_procedure()"; // Ajustar según tus SPs
64
- const callResult = await mariadb.api(config.mariadb, db, callQuery, 'call', '127.0.0.1', 'test');
65
- console.log(' ✓ CALL exitoso:', callResult.result);
66
- } catch(e) {
67
- console.log(' ⚠ CALL omitido (procedimiento no existe)');
68
- }
69
-
70
- // Cleanup
71
- console.log('\n7. Limpiando datos de prueba...');
72
- const deleteQuery = `DELETE FROM test_users WHERE id = ${insertId}`;
73
- const deleteResult = await mariadb.api(config.mariadb, db, deleteQuery, 'delete', '127.0.0.1', 'test');
74
- console.log(' ✓ Limpieza completada:', deleteResult.result);
75
-
76
- console.log('\n=== ✓ TODAS LAS PRUEBAS MARIADB EXITOSAS ===\n');
77
-
78
- } catch (error) {
79
- console.error('\n=== ✗ ERROR EN PRUEBAS MARIADB ===');
80
- console.error(error);
81
- process.exit(1);
82
- }
83
- }
84
-
85
- testMariaDB();
@@ -1,133 +0,0 @@
1
- /**
2
- * Pruebas de conexiones MongoDB
3
- * Ejecutar: node tests/test-mongodb.js
4
- */
5
-
6
- const config = require('./config');
7
- const mongodb = require('../lib/hookup/mongodb');
8
-
9
- console.log('=== INICIANDO PRUEBAS MONGODB ===\n');
10
-
11
- async function testMongoDB() {
12
- const dbName = 'test_bonsaif';
13
- const collection = 'test_collection';
14
-
15
- try {
16
- // Test 1: INSERT
17
- console.log('1. Probando INSERT...');
18
- const insertResult = await mongodb.insert(
19
- config.mongodb,
20
- dbName,
21
- collection,
22
- {name: 'Test User', email: 'test@example.com', created: new Date()}
23
- );
24
- console.log(' ✓ INSERT exitoso:', insertResult);
25
- const insertId = insertResult.result.insertId;
26
-
27
- // Test 2: FIND
28
- console.log('\n2. Probando FIND...');
29
- const findResult = await mongodb.find(
30
- config.mongodb,
31
- dbName,
32
- collection,
33
- {name: 'Test User'},
34
- {created: -1},
35
- 10
36
- );
37
- console.log(' ✓ FIND exitoso:', {
38
- count: findResult.data?.length,
39
- data: findResult.data?.[0]
40
- });
41
-
42
- // Test 3: UPDATE
43
- console.log('\n3. Probando UPDATE...');
44
- const updateResult = await mongodb.update(
45
- config.mongodb,
46
- dbName,
47
- collection,
48
- {email: 'updated@example.com', updated: new Date()},
49
- {_id: insertId}
50
- );
51
- console.log(' ✓ UPDATE exitoso:', updateResult);
52
-
53
- // Test 4: COUNT
54
- console.log('\n4. Probando COUNT...');
55
- const countResult = await mongodb.count(
56
- config.mongodb,
57
- dbName,
58
- collection,
59
- {filter: {name: 'Test User'}}
60
- );
61
- console.log(' ✓ COUNT exitoso:', countResult);
62
-
63
- // Test 5: COMMAND (find)
64
- console.log('\n5. Probando COMMAND...');
65
- const commandResult = await mongodb.command(
66
- config.mongodb,
67
- dbName,
68
- {find: collection, filter: {name: 'Test User'}, limit: 5}
69
- );
70
- console.log(' ✓ COMMAND exitoso:', {
71
- count: commandResult.data?.length
72
- });
73
-
74
- // Test 6: UPSERT (update existing)
75
- console.log('\n6. Probando UPSERT (update)...');
76
- const upsertUpdateResult = await mongodb.upsert(
77
- config.mongodb,
78
- dbName,
79
- collection,
80
- {name: 'Test User', email: 'upserted@example.com'},
81
- {_id: insertId}
82
- );
83
- console.log(' ✓ UPSERT (update) exitoso:', upsertUpdateResult);
84
-
85
- // Test 7: UPSERT (insert new)
86
- console.log('\n7. Probando UPSERT (insert)...');
87
- const upsertInsertResult = await mongodb.upsert(
88
- config.mongodb,
89
- dbName,
90
- collection,
91
- {name: 'New User', email: 'new@example.com'},
92
- {name: 'New User'}
93
- );
94
- console.log(' ✓ UPSERT (insert) exitoso:', upsertInsertResult);
95
-
96
- // Test 8: DBS
97
- console.log('\n8. Probando DBS...');
98
- const dbsResult = await mongodb.dbs(config.mongodb);
99
- console.log(' ✓ DBS exitoso:', {
100
- totalSize: dbsResult.results?.totalSize,
101
- dbCount: dbsResult.data?.length
102
- });
103
-
104
- // Test 9: COLLECTIONS
105
- console.log('\n9. Probando COLLECTIONS...');
106
- const collectionsResult = await mongodb.collections(config.mongodb, dbName);
107
- console.log(' ✓ COLLECTIONS exitoso:', {
108
- count: collectionsResult.data?.length,
109
- collections: collectionsResult.data?.map(c => c.name).slice(0, 5)
110
- });
111
-
112
- // Cleanup
113
- console.log('\n10. Limpiando datos de prueba...');
114
- const deleteResult = await mongodb.api(
115
- config.mongodb,
116
- dbName,
117
- {
118
- deleteMany: collection,
119
- filter: {$or: [{name: 'Test User'}, {name: 'New User'}]}
120
- }
121
- );
122
- console.log(' ✓ Limpieza completada:', deleteResult.result);
123
-
124
- console.log('\n=== ✓ TODAS LAS PRUEBAS MONGODB EXITOSAS ===\n');
125
-
126
- } catch (error) {
127
- console.error('\n=== ✗ ERROR EN PRUEBAS MONGODB ===');
128
- console.error(error);
129
- process.exit(1);
130
- }
131
- }
132
-
133
- testMongoDB();
@@ -1,408 +0,0 @@
1
- /**
2
- * Test Mongoose - Bonsaif
3
- * Prueba las operaciones de Mongoose con schemas dinámicos
4
- */
5
-
6
- const bonsaif = require('../index');
7
- const config = require('./config');
8
-
9
- const testCollection = 'mongoose_test_collection';
10
-
11
- // Schema de ejemplo para validaciones
12
- const userSchema = {
13
- name: {
14
- type: 'String',
15
- required: true,
16
- minlength: 3,
17
- maxlength: 50
18
- },
19
- email: {
20
- type: 'String',
21
- required: true,
22
- unique: true,
23
- lowercase: true,
24
- match: '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$'
25
- },
26
- age: {
27
- type: 'Number',
28
- min: 18,
29
- max: 100
30
- },
31
- status: {
32
- type: 'String',
33
- enum: ['active', 'inactive', 'pending'],
34
- default: 'active'
35
- }
36
- };
37
-
38
- const runTests = async () => {
39
- console.log('\n===================================');
40
- console.log(' MONGOOSE TESTS');
41
- console.log('===================================\n');
42
-
43
- let passedTests = 0;
44
- let totalTests = 0;
45
-
46
- const testResult = (testName, passed, details = '') => {
47
- totalTests++;
48
- if (passed) {
49
- passedTests++;
50
- console.log(`✅ ${testName}`);
51
- } else {
52
- console.log(`❌ ${testName}`);
53
- if (details) console.log(` Details: ${details}`);
54
- }
55
- };
56
-
57
- try {
58
- // Limpiar colecciones antes de comenzar
59
- await bonsaif.query({
60
- endpoint: config.mongoose.endpoint,
61
- options: { ...config.mongoose.options, db: 'test' },
62
- query: {
63
- dml: 'deleteMany',
64
- collection: testCollection,
65
- filter: {}
66
- }
67
- });
68
-
69
- await bonsaif.query({
70
- endpoint: config.mongoose.endpoint,
71
- options: { ...config.mongoose.options, db: 'test' },
72
- query: {
73
- dml: 'deleteMany',
74
- collection: testCollection + '_schema',
75
- filter: {}
76
- }
77
- });
78
-
79
- console.log('🧹 Colecciones limpiadas\n');
80
-
81
- // Test 1: INSERT con schema genérico (sin validaciones)
82
- totalTests++;
83
- const insertResult = await bonsaif.query({
84
- endpoint: config.mongoose.endpoint,
85
- options: { ...config.mongoose.options, db: 'test' },
86
- query: {
87
- dml: 'insert',
88
- collection: testCollection,
89
- document: {
90
- name: 'John Doe',
91
- email: 'john@example.com',
92
- age: 30
93
- }
94
- }
95
- });
96
- if (insertResult?.error === 0 && insertResult.irows > 0) {
97
- passedTests++;
98
- const insertedId = insertResult.rows[0]?._id || 'N/A';
99
- console.log(`✅ Test 1: INSERT sin schema (insertados: ${insertResult.irows}, _id: ${insertedId})`);
100
- } else {
101
- console.log('❌ Test 1: INSERT sin schema');
102
- console.log(' Result:', JSON.stringify(insertResult, null, 2));
103
- }
104
-
105
- // Test 2: INSERT con schema y validaciones
106
- totalTests++;
107
- const insertWithSchemaResult = await bonsaif.query({
108
- endpoint: config.mongoose.endpoint,
109
- options: { ...config.mongoose.options, db: 'test' },
110
- query: {
111
- dml: 'insert',
112
- collection: testCollection + '_schema',
113
- schema: userSchema,
114
- document: {
115
- name: 'Jane Smith',
116
- email: 'jane@example.com',
117
- age: 25,
118
- status: 'active'
119
- }
120
- }
121
- });
122
- if (insertWithSchemaResult?.error === 0) {
123
- passedTests++;
124
- const insertedId = insertWithSchemaResult.rows[0]?._id || 'N/A';
125
- console.log(`✅ Test 2: INSERT con schema y validaciones (insertados: ${insertWithSchemaResult.irows}, _id: ${insertedId})`);
126
- } else {
127
- console.log('❌ Test 2: INSERT con schema y validaciones');
128
- console.log(' Result:', JSON.stringify(insertWithSchemaResult, null, 2));
129
- }
130
-
131
- // Test 3: INSERTMANY - Insertar múltiples documentos
132
- totalTests++;
133
- const insertManyResult = await bonsaif.query({
134
- endpoint: config.mongoose.endpoint,
135
- options: { ...config.mongoose.options, db: 'test' },
136
- query: {
137
- dml: 'insertMany',
138
- collection: testCollection,
139
- documents: [
140
- { name: 'User 1', email: 'user1@test.com', age: 28 },
141
- { name: 'User 2', email: 'user2@test.com', age: 32 },
142
- { name: 'User 3', email: 'user3@test.com', age: 45 }
143
- ]
144
- }
145
- });
146
- if (insertManyResult?.error === 0 && insertManyResult.irows === 3) {
147
- passedTests++;
148
- console.log(`✅ Test 3: INSERTMANY (insertados: ${insertManyResult.irows})`);
149
- } else {
150
- console.log('❌ Test 3: INSERTMANY');
151
- console.log(' Result:', JSON.stringify(insertManyResult, null, 2));
152
- }
153
-
154
- // Test 4: FIND - Buscar documentos
155
- totalTests++;
156
- const findResult = await bonsaif.query({
157
- endpoint: config.mongoose.endpoint,
158
- options: { ...config.mongoose.options, db: 'test' },
159
- query: {
160
- dml: 'find',
161
- collection: testCollection,
162
- filter: { age: { $gte: 30 } },
163
- sort: { age: -1 },
164
- limit: 10
165
- }
166
- });
167
- if (findResult?.error === 0 && Array.isArray(findResult.rows)) {
168
- passedTests++;
169
- console.log(`✅ Test 4: FIND (encontrados: ${findResult.irows})`);
170
- } else {
171
- console.log('❌ Test 4: FIND');
172
- console.log(' Result:', JSON.stringify(findResult, null, 2));
173
- }
174
-
175
- // Test 5: FINDONE - Buscar un documento
176
- totalTests++;
177
- const findOneResult = await bonsaif.query({
178
- endpoint: config.mongoose.endpoint,
179
- options: { ...config.mongoose.options, db: 'test' },
180
- query: {
181
- dml: 'findOne',
182
- collection: testCollection,
183
- filter: { email: 'john@example.com' }
184
- }
185
- });
186
- if (findOneResult?.error === 0 && findOneResult.irows > 0) {
187
- passedTests++;
188
- const foundDoc = findOneResult.rows[0];
189
- console.log(`✅ Test 5: FINDONE (encontrado: ${foundDoc?.name || 'N/A'}, email: ${foundDoc?.email || 'N/A'})`);
190
- } else {
191
- console.log('❌ Test 5: FINDONE');
192
- console.log(' Result:', JSON.stringify(findOneResult, null, 2));
193
- }
194
-
195
- // Test 6: COUNT - Contar documentos
196
- totalTests++;
197
- const countResult = await bonsaif.query({
198
- endpoint: config.mongoose.endpoint,
199
- options: { ...config.mongoose.options, db: 'test' },
200
- query: {
201
- dml: 'count',
202
- collection: testCollection,
203
- filter: {}
204
- }
205
- });
206
- if (countResult?.error === 0 && countResult.rows?.count >= 4) {
207
- passedTests++;
208
- console.log(`✅ Test 6: COUNT (total: ${countResult.rows.count})`);
209
- } else {
210
- console.log('❌ Test 6: COUNT');
211
- console.log(' Result:', JSON.stringify(countResult, null, 2));
212
- }
213
-
214
- // Test 7: UPDATE - Actualizar un documento
215
- totalTests++;
216
- const updateResult = await bonsaif.query({
217
- endpoint: config.mongoose.endpoint,
218
- options: { ...config.mongoose.options, db: 'test' },
219
- query: {
220
- dml: 'update',
221
- collection: testCollection,
222
- filter: { email: 'john@example.com' },
223
- update: { $set: { age: 31, status: 'updated' } }
224
- }
225
- });
226
- if (updateResult?.error === 0 && updateResult?.rows.modifiedCount >= 0) {
227
- passedTests++;
228
- const matched = updateResult.rows?.matchedCount || 0;
229
- const modified = updateResult.rows?.modifiedCount || 0;
230
- console.log(`✅ Test 7: UPDATE (coincidencias: ${matched}, modificados: ${modified})`);
231
- } else {
232
- console.log('❌ Test 7: UPDATE');
233
- console.log(' Result:', JSON.stringify(updateResult, null, 2));
234
- }
235
-
236
- // Test 8: UPDATEMANY - Actualizar múltiples documentos
237
- totalTests++;
238
- const updateManyResult = await bonsaif.query({
239
- endpoint: config.mongoose.endpoint,
240
- options: { ...config.mongoose.options, db: 'test' },
241
- query: {
242
- dml: 'updateMany',
243
- collection: testCollection,
244
- filter: { age: { $gte: 30 } },
245
- update: { $set: { category: 'senior' } }
246
- }
247
- });
248
- if (updateManyResult?.error === 0) {
249
- passedTests++;
250
- console.log(`✅ Test 8: UPDATEMANY (modificados: ${updateManyResult?.rows.modifiedCount || 0})`);
251
- } else {
252
- console.log('❌ Test 8: UPDATEMANY');
253
- console.log(' Result:', JSON.stringify(updateManyResult, null, 2));
254
- }
255
-
256
- // Test 9: UPSERT - Actualizar o insertar
257
- totalTests++;
258
- const upsertResult = await bonsaif.query({
259
- endpoint: config.mongoose.endpoint,
260
- options: { ...config.mongoose.options, db: 'test' },
261
- query: {
262
- dml: 'upsert',
263
- collection: testCollection,
264
- filter: { email: 'newuser@example.com' },
265
- document: {
266
- name: 'New User',
267
- email: 'newuser@example.com',
268
- age: 27,
269
- status: 'upserted'
270
- }
271
- }
272
- });
273
- if (upsertResult?.error === 0 && upsertResult?.code === 200) {
274
- passedTests++;
275
- const upsertedDoc = upsertResult.rows[0];
276
- const docName = upsertedDoc?.name || 'N/A';
277
- const docId = upsertedDoc?._id || 'N/A';
278
- console.log(`✅ Test 9: UPSERT (documento: ${docName}, _id: ${docId})`);
279
- } else {
280
- console.log('❌ Test 9: UPSERT');
281
- console.log(' Result:', JSON.stringify(upsertResult, null, 2));
282
- }
283
-
284
- // Test 10: AGGREGATE - Pipeline de agregación
285
- totalTests++;
286
- const aggregateResult = await bonsaif.query({
287
- endpoint: config.mongoose.endpoint,
288
- options: { ...config.mongoose.options, db: 'test' },
289
- query: {
290
- dml: 'aggregate',
291
- collection: testCollection,
292
- pipeline: [
293
- { $match: { age: { $gte: 25 } } },
294
- { $group: { _id: '$status', count: { $sum: 1 }, avgAge: { $avg: '$age' } } },
295
- { $sort: { count: -1 } }
296
- ]
297
- }
298
- });
299
- if (aggregateResult?.error === 0 && Array.isArray(aggregateResult.rows)) {
300
- passedTests++;
301
- console.log(`✅ Test 10: AGGREGATE (grupos: ${aggregateResult.irows})`);
302
- } else {
303
- console.log('❌ Test 10: AGGREGATE');
304
- console.log(' Result:', JSON.stringify(aggregateResult, null, 2));
305
- }
306
-
307
- // Test 11: DISTINCT - Valores únicos
308
- totalTests++;
309
- const distinctResult = await bonsaif.query({
310
- endpoint: config.mongoose.endpoint,
311
- options: { ...config.mongoose.options, db: 'test' },
312
- query: {
313
- dml: 'distinct',
314
- collection: testCollection,
315
- field: 'status',
316
- filter: {}
317
- }
318
- });
319
- if (distinctResult?.error === 0 && Array.isArray(distinctResult.rows)) {
320
- passedTests++;
321
- console.log(`✅ Test 11: DISTINCT (valores únicos: ${distinctResult.irows})`);
322
- } else {
323
- console.log('❌ Test 11: DISTINCT');
324
- console.log(' Result:', JSON.stringify(distinctResult, null, 2));
325
- }
326
-
327
- // Test 12: DELETE - Eliminar un documento
328
- totalTests++;
329
- const deleteResult = await bonsaif.query({
330
- endpoint: config.mongoose.endpoint,
331
- options: { ...config.mongoose.options, db: 'test' },
332
- query: {
333
- dml: 'delete',
334
- collection: testCollection,
335
- filter: { email: 'newuser@example.com' }
336
- }
337
- });
338
- if (deleteResult?.error === 0) {
339
- passedTests++;
340
- console.log(`✅ Test 12: DELETE (eliminados: ${deleteResult.rows?.deletedCount || 0})`);
341
- } else {
342
- console.log('❌ Test 12: DELETE');
343
- console.log(' Result:', JSON.stringify(deleteResult, null, 2));
344
- }
345
-
346
- // Test 13: DELETEMANY - Eliminar múltiples documentos
347
- totalTests++;
348
- const deleteManyResult = await bonsaif.query({
349
- endpoint: config.mongoose.endpoint,
350
- options: { ...config.mongoose.options, db: 'test' },
351
- query: {
352
- dml: 'deleteMany',
353
- collection: testCollection,
354
- filter: {}
355
- }
356
- });
357
- if (deleteManyResult?.error === 0) {
358
- passedTests++;
359
- console.log(`✅ Test 13: DELETEMANY (eliminados: ${deleteManyResult.rows?.deletedCount || 0})`);
360
- } else {
361
- console.log('❌ Test 13: DELETEMANY');
362
- console.log(' Result:', JSON.stringify(deleteManyResult, null, 2));
363
- }
364
-
365
- // Test 14: Limpiar colección con schema
366
- totalTests++;
367
- const cleanupSchemaResult = await bonsaif.query({
368
- endpoint: config.mongoose.endpoint,
369
- options: { ...config.mongoose.options, db: 'test' },
370
- query: {
371
- dml: 'deleteMany',
372
- collection: testCollection + '_schema',
373
- filter: {}
374
- }
375
- });
376
- if (cleanupSchemaResult?.error === 0) {
377
- passedTests++;
378
- console.log(`✅ Test 14: CLEANUP (eliminados: ${cleanupSchemaResult.rows?.deletedCount || 0})`);
379
- } else {
380
- console.log('❌ Test 14: CLEANUP');
381
- }
382
-
383
- // Resumen
384
- console.log('\n===================================');
385
- console.log(` RESULTADOS: ${passedTests}/${totalTests} tests pasados`);
386
- console.log('===================================\n');
387
-
388
- return { passed: passedTests, total: totalTests };
389
-
390
- } catch (e) {
391
- console.error('Error en tests de Mongoose:', e);
392
- throw e;
393
- }
394
- };
395
-
396
- // Ejecutar tests si se llama directamente
397
- if (require.main === module) {
398
- runTests()
399
- .then(result => {
400
- process.exit(result.passed === result.total ? 0 : 1);
401
- })
402
- .catch(e => {
403
- console.error('Error fatal:', e);
404
- process.exit(1);
405
- });
406
- }
407
-
408
- module.exports = { runTests };