moquilang 0.1.1

A WebAssembly module for entity operations and service calls with a database (default to a SQLite integration)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>WebAssembly Test</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        .result {
            margin-top: 20px;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            background-color: #f9f9f9;
            overflow-wrap: break-word;
            white-space: pre-wrap;
        }
        button {
            padding: 8px 16px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-right: 10px;
        }
        input {
            padding: 8px;
            margin-right: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        textarea {
            min-height: 80px;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            width: 100%;
            resize: vertical;
            overflow: auto;
            box-sizing: border-box;
        }
        .auto-expand {
            overflow: hidden;
            resize: none;
        }
    </style>
</head>
<body>
    <h1>Rust WebAssembly Demo</h1>
    
    <div>
        <h2>Database Schema</h2>
        <button id="export-schema-btn">Export Database Schema</button>
        <div id="schema-result" class="result" style="white-space: pre-wrap;"></div>
    </div>

    <div>
        <h2>Entity Operations</h2>
        
        <div style="margin-bottom: 20px;">
            <h3>Create Entity</h3>
            <input type="text" id="create-entity-type" placeholder="Entity type" value="UserAccount">
            <textarea id="create-entity-data" placeholder="Entity data (JSON)" rows="5" style="width: 100%; margin-top: 10px;">{
  "username": "johndoe",
  "userFullName": "John Doe",
  "emailAddress": "john@example.com",
  "currentPassword": "password123",
  "disabled": "N"
}</textarea>
            <button id="create-entity-btn" style="margin-top: 10px;">Create Entity</button>
            <div id="create-entity-result" class="result" style="white-space: pre-wrap;"></div>
        </div>
        
        <div style="margin-bottom: 20px;">
            <h3>Update Entity</h3>
            <input type="text" id="update-entity-type" placeholder="Entity type" value="UserAccount">
            <textarea id="update-entity-data" placeholder="Entity data (JSON)" rows="4" style="width: 100%; margin-top: 10px;">{
  "userId": "your-user-id-here",
  "userFullName": "John Smith",
  "emailAddress": "johnsmith@example.com"
}</textarea>
            <button id="update-entity-btn" style="margin-top: 10px;">Update Entity</button>
            <div id="update-entity-result" class="result" style="white-space: pre-wrap;"></div>
        </div>
        
        <div style="margin-bottom: 20px;">
            <h3>Delete Entity</h3>
            <input type="text" id="delete-entity-type" placeholder="Entity type" value="UserAccount">
            <textarea id="delete-entity-data" placeholder="Entity data (JSON)" rows="2" style="width: 100%; margin-top: 10px;">{
  "userId": "your-user-id-here"
}</textarea>
            <button id="delete-entity-btn" style="margin-top: 10px;">Delete Entity</button>
            <div id="delete-entity-result" class="result" style="white-space: pre-wrap;"></div>
        </div>
        
        <div style="margin-bottom: 20px;">
            <h3>Find One Entity</h3>
            <input type="text" id="find-one-entity-type" placeholder="Entity type" value="UserAccount">
            <textarea id="find-one-query" placeholder="Query (JSON)" rows="2" style="width: 100%; margin-top: 10px;">{
  "userId": "your-user-id-here"
}</textarea>
            <button id="find-one-btn" style="margin-top: 10px;">Find One</button>
            <div id="find-one-result" class="result" style="white-space: pre-wrap;"></div>
        </div>
        
        <div style="margin-bottom: 20px;">
            <h3>Find Many Entities</h3>
            <input type="text" id="find-many-entity-type" placeholder="Entity type" value="UserAccount">
            <textarea id="find-many-query" placeholder="Query (JSON)" rows="4" style="width: 100%; margin-top: 10px;">{
  "_limit": 10,
  "_offset": 0,
  "_orderBy": "username",
  "_orderDir": "ASC"
}</textarea>
            <div style="margin-top: 10px;">
                <button id="find-many-btn">Find Many</button>
                <button id="example1-btn" style="background-color: #2196F3;">Example: Filter by Role</button>
                <button id="example2-btn" style="background-color: #FF9800;">Example: Pagination</button>
                <button id="example3-btn" style="background-color: #9C27B0;">Example: Sorting</button>
            </div>
            <div id="find-many-result" class="result" style="white-space: pre-wrap;"></div>
        </div>
        <div>
            <h2>Call Service Function</h2>
            <input type="text" id="service-name" placeholder="Service name" value="userService">
            <textarea id="service-params" placeholder="JSON Parameters" rows="5" style="width: 100%; margin-top: 10px;">{
      "userId": 123,
      "action": "getProfile",
      "options": {
        "includeDetails": true,
        "format": "full"
      }
    }</textarea>
            <button id="service-btn" style="margin-top: 10px;">Call Service</button>
            <div id="service-result" class="result" style="white-space: pre-wrap;"></div>
        </div>
        
    </div>

    <script src="./static/sqlite3.js"></script>
    <script type="module">
        import init, { callService, createEntity, updateEntity, deleteEntity, findOne, findMany, exportDatabaseSchema } from './pkg/moquilang.js';
        
        // Define the entity operations namespace
        window.entityOps = {
            // Create a new entity with schema validation
            createEntity: (entityName, entityData) => {
                console.log(`[CREATE] Entity: ${entityName}`, entityData);
                
                try {
                    const db = window.db;
                    if (!db) {
                        throw new Error("Database not initialized");
                    }

                    // Find the table in schema that matches the entity name
                    const tableSchema = schema.tables.find(table => 
                        table.name.toLowerCase() === entityName.toLowerCase());
                    
                    if (!tableSchema) {
                        throw new Error(`Table schema not found for entity ${entityName}`);
                    }
                    
                    // Check for primary key field
                    const primaryKeyColumns = tableSchema.columns.filter(col => col.primary_key);
                    const hasSingleTextPK = primaryKeyColumns.length === 1 && 
                                           primaryKeyColumns[0].data_type.toUpperCase() === 'TEXT';
                    
                    // Auto-generate ID if it's a single TEXT primary key
                    if (hasSingleTextPK) {
                        const pkField = primaryKeyColumns[0].name;
                        if (!entityData[pkField]) {
                            // Generate UUID
                            entityData[pkField] = crypto.randomUUID();
                            console.log(`Auto-generated ID for ${pkField}: ${entityData[pkField]}`);
                        }
                    }
                    
                    // Prepare column names and values for SQL
                    const columnNames = [];
                    const placeholders = [];
                    const values = [];
                    
                    for (const column of tableSchema.columns) {
                        if (entityData[column.name] !== undefined) {
                            columnNames.push(column.name);
                            placeholders.push('?');
                            values.push(entityData[column.name]);
                        }
                    }
                    
                    // Create the SQL statement
                    const sql = `INSERT INTO ${tableSchema.name} (${columnNames.join(', ')}) VALUES (${placeholders.join(', ')})`;
                    console.log(`Executing SQL: ${sql}`, values);
                    
                    // Execute the SQL statement
                    try {
                        db.exec({
                            sql: sql,
                            bind: values
                        });
                    } catch (sqlError) {
                        console.error("SQL execution error:", sqlError);
                        throw new Error(`SQL error: ${sqlError.message || sqlError}`);
                    }
                    
                    return entityData;
                } catch (error) {
                    console.error(`Error creating entity ${entityName}:`, error);
                    throw new Error(`Failed to create ${entityName}: ${error.message || error}`);
                }
            },
            
            // Update an existing entity
            updateEntity: (entityName, entityData) => {
                console.log(`[UPDATE] Entity: ${entityName}`, entityData);
                
                try {
                    const db = window.db;
                    if (!db) {
                        throw new Error("Database not initialized");
                    }
                    
                    // Find the table in schema that matches the entity name
                    const tableSchema = schema.tables.find(table => 
                        table.name.toLowerCase() === entityName.toLowerCase());
                    
                    if (!tableSchema) {
                        throw new Error(`Table schema not found for entity ${entityName}`);
                    }
                    
                    // Require all primary keys to be present in the update data
                    const primaryKeyColumns = tableSchema.columns.filter(col => col.primary_key);
                    if (primaryKeyColumns.length > 0) {
                        // Check that all primary keys are in the input data
                        for (const pkColumn of primaryKeyColumns) {
                            if (entityData[pkColumn.name] === undefined) {
                                throw new Error(`Primary key '${pkColumn.name}' is required for updating ${entityName}`);
                            }
                        }
                    } else {
                        throw new Error(`Entity ${entityName} has no primary key defined in schema`);
                    }
                    
                    // Separate primary key fields from update fields
                    const updateFields = [];
                    const updateValues = [];
                    const pkConditions = [];
                    const pkValues = [];
                    
                    // Process all fields in the entity data
                    for (const [key, value] of Object.entries(entityData)) {
                        const column = tableSchema.columns.find(col => col.name === key);
                        if (!column) {
                            console.warn(`Ignoring unknown field: ${key}`);
                            continue;
                        }
                        
                        if (column.primary_key) {
                            // Add to primary key conditions
                            pkConditions.push(`${key} = ?`);
                            pkValues.push(value);
                        } else {
                            // Add to update fields
                            updateFields.push(`${key} = ?`);
                            updateValues.push(value);
                        }
                    }
                    
                    // Check if there are any fields to update
                    if (updateFields.length === 0) {
                        throw new Error("No fields to update");
                    }
                    
                    // Create the SQL statement
                    const setClause = updateFields.join(", ");
                    const whereClause = pkConditions.join(" AND ");
                    const sql = `UPDATE ${tableSchema.name} SET ${setClause} WHERE ${whereClause}`;
                    
                    // Combine update values and primary key values
                    const allValues = [...updateValues, ...pkValues];
                    
                    console.log(`Executing SQL: ${sql}`, allValues);
                    
                    // Execute the SQL statement
                    try {
                        db.exec({
                            sql: sql,
                            bind: allValues
                        });
                        
                        // Check if any rows were affected
                        const rowsAffected = db.changes();
                        if (rowsAffected === 0) {
                            throw new Error(`No ${entityName} found with the specified primary key(s)`);
                        }
                        
                        // Return the updated entity data
                        return entityData;
                    } catch (sqlError) {
                        console.error("SQL execution error:", sqlError);
                        throw new Error(`SQL error: ${sqlError.message || sqlError}`);
                    }
                } catch (error) {
                    console.error(`Error updating entity ${entityName}:`, error);
                    throw new Error(`Failed to update ${entityName}: ${error.message || error}`);
                }
            },
            
            // Delete an entity
            deleteEntity: (entityName, entityData) => {
                console.log(`[DELETE] Entity: ${entityName}`, entityData);
                
                try {
                    const db = window.db;
                    if (!db) {
                        throw new Error("Database not initialized");
                    }
                    
                    // Find the table in schema that matches the entity name
                    const tableSchema = schema.tables.find(table => 
                        table.name.toLowerCase() === entityName.toLowerCase());
                    
                    if (!tableSchema) {
                        throw new Error(`Table schema not found for entity ${entityName}`);
                    }
                    
                    // Require all primary keys to be present in the delete data
                    const primaryKeyColumns = tableSchema.columns.filter(col => col.primary_key);
                    if (primaryKeyColumns.length > 0) {
                        // Check that all primary keys are in the input data
                        for (const pkColumn of primaryKeyColumns) {
                            if (entityData[pkColumn.name] === undefined) {
                                throw new Error(`Primary key '${pkColumn.name}' is required for deleting ${entityName}`);
                            }
                        }
                    } else {
                        throw new Error(`Entity ${entityName} has no primary key defined in schema`);
                    }
                    
                    // Build the WHERE clause for primary keys
                    const pkConditions = [];
                    const pkValues = [];
                    
                    for (const pkColumn of primaryKeyColumns) {
                        pkConditions.push(`${pkColumn.name} = ?`);
                        pkValues.push(entityData[pkColumn.name]);
                    }

                    // Create and execute the DELETE statement
                    const deleteSql = `DELETE FROM ${tableSchema.name} WHERE ${pkConditions.join(" AND ")}`;
                    console.log(`Executing SQL: ${deleteSql}`, pkValues);
                    
                    try {
                        db.exec({
                            sql: deleteSql,
                            bind: pkValues
                        });
                        
                        // Check if any rows were affected
                        const rowsAffected = db.changes();
                        if (rowsAffected === 0) {
                            throw new Error(`No ${entityName} found with the specified primary key(s)`);
                        }
                        
                        // Return success with the primary key data
                        return {
                            success: true,
                            entityName,
                            ...entityData
                        };
                    } catch (sqlError) {
                        console.error("SQL execution error during delete:", sqlError);
                        throw new Error(`SQL error during delete: ${sqlError.message || sqlError}`);
                    }
                } catch (error) {
                    console.error(`Error deleting entity ${entityName}:`, error);
                    throw new Error(`Failed to delete ${entityName}: ${error.message || error}`);
                }
            },
            
            // Find one entity matching the query
            findOne: (entityName, query) => {
                console.log(`[FIND_ONE] Entity: ${entityName}`, query);
                
                try {
                    const db = window.db;
                    if (!db) {
                        throw new Error("Database not initialized");
                    }
                    
                    // Find the table in schema that matches the entity name
                    const schema = window.schema;
                    if (!schema || !schema.tables) {
                        throw new Error("Schema not available for validation");
                    }
                    
                    const tableSchema = schema.tables.find(table => 
                        table.name.toLowerCase() === entityName.toLowerCase());
                    
                    if (!tableSchema) {
                        throw new Error(`Table schema not found for entity ${entityName}`);
                    }
                    
                    // Require all primary keys to be present in the query
                    const primaryKeyColumns = tableSchema.columns.filter(col => col.primary_key);
                    if (primaryKeyColumns.length > 0) {
                        // Check that all primary keys are in the query
                        for (const pkColumn of primaryKeyColumns) {
                            if (query[pkColumn.name] === undefined) {
                                throw new Error(`Primary key '${pkColumn.name}' is required in the query`);
                            }
                        }
                        
                        // Build the primary key WHERE clause
                        const pkConditions = primaryKeyColumns.map(col => `${col.name} = ?`);
                        const pkValues = primaryKeyColumns.map(col => query[col.name]);
                        
                        const whereClause = pkConditions.join(" AND ");
                        const sql = `SELECT * FROM ${tableSchema.name} WHERE ${whereClause}`;
                        console.log(`Executing SQL: ${sql}`, pkValues);
                        
                        try {
                            let result = null;
                            db.exec({
                                sql: sql,
                                bind: pkValues,
                                callback: function(row) {
                                    if (!result) {
                                        result = {};
                                        // Get column names from the schema
                                        for (let i = 0; i < row.length; i++) {
                                            // Use column index if we can't get the name
                                            const columnName = tableSchema.columns[i]?.name || `column${i}`;
                                            result[columnName] = row[i];
                                        }
                                    }
                                }
                            });
                            
                            if (result) {
                                return result;
                            }
                            
                            throw new Error(`Entity ${entityName} with primary key(s) not found`);
                        } catch (sqlError) {
                            console.error("SQL execution error:", sqlError);
                            throw new Error(`SQL error: ${sqlError.message || sqlError}`);
                        }
                    } else {
                        throw new Error(`Entity ${entityName} has no primary key defined in schema`);
                    }
                } catch (error) {
                    console.error(`Error finding entity ${entityName}:`, error);
                    throw new Error(`Failed to find ${entityName}: ${error.message || error}`);
                }
            },
            
            // Find multiple entities matching the query
            findMany: (entityName, query) => {
                console.log(`[FIND_MANY] Entity: ${entityName}`, query);
                
                try {
                    const db = window.db;
                    if (!db) {
                        throw new Error("Database not initialized");
                    }
                    
                    // Find the table in schema that matches the entity name
                    const tableSchema = schema.tables.find(table => 
                        table.name.toLowerCase() === entityName.toLowerCase());
                    
                    if (!tableSchema) {
                        throw new Error(`Table schema not found for entity ${entityName}`);
                    }
                    
                    // Extract pagination parameters if provided
                    const limit = query._limit || 100;  // Default limit to 100 records
                    const offset = query._offset || 0;
                    const orderBy = query._orderBy || (tableSchema.primary_key.length > 0 ? tableSchema.primary_key[0] : null);
                    const orderDir = query._orderDir || 'ASC';
                    
                    // Remove special parameters from query
                    const cleanQuery = {...query};
                    delete cleanQuery._limit;
                    delete cleanQuery._offset;
                    delete cleanQuery._orderBy;
                    delete cleanQuery._orderDir;
                    
                    // Build query conditions
                    const conditions = [];
                    const values = [];
                    
                    for (const [key, value] of Object.entries(cleanQuery)) {
                        const column = tableSchema.columns.find(col => col.name === key);
                        if (column) {
                            conditions.push(`${key} = ?`);
                            values.push(value);
                        } else {
                            console.warn(`Ignoring unknown field in query: ${key}`);
                        }
                    }
                    
                    // Create the SQL statement
                    let sql = `SELECT * FROM ${tableSchema.name}`;
                    
                    if (conditions.length > 0) {
                        sql += ` WHERE ${conditions.join(" AND ")}`;
                    }
                    
                    // Add ORDER BY clause if specified
                    if (orderBy) {
                        // Validate the orderBy column exists
                        const orderByColumn = tableSchema.columns.find(col => col.name === orderBy);
                        if (orderByColumn) {
                            sql += ` ORDER BY ${orderBy} ${orderDir === 'DESC' ? 'DESC' : 'ASC'}`;
                        }
                    }
                    
                    // Add LIMIT and OFFSET
                    sql += ` LIMIT ${limit} OFFSET ${offset}`;
                    
                    console.log(`Executing SQL: ${sql}`, values);
                    
                    // Execute the SQL statement
                    try {
                        const results = [];
                        
                        db.exec({
                            sql: sql,
                            bind: values,
                            callback: function(row) {
                                const entity = {};
                                
                                // Map row values to column names
                                for (let i = 0; i < row.length; i++) {
                                    const columnName = tableSchema.columns[i]?.name || `column${i}`;
                                    entity[columnName] = row[i];
                                }
                                
                                results.push(entity);
                            }
                        });
                        
                        return results;
                    } catch (sqlError) {
                        console.error("SQL execution error:", sqlError);
                        throw new Error(`SQL error: ${sqlError.message || sqlError}`);
                    }
                } catch (error) {
                    console.error(`Error finding entities ${entityName}:`, error);
                    throw new Error(`Failed to find ${entityName} entities: ${error.message || error}`);
                }
            }
        };

        async function run() {
            // Initialize the WASM modules
            await init();
            
            // Initialize SQLite
            try {
                console.log("Initializing SQLite...");
                const sqlite3 = await window.sqlite3InitModule();
                console.log("SQLite initialized:", sqlite3);
                
                // Create an in-memory database
                const db = new sqlite3.oo1.DB(":memory:");
                
                // Store SQLite instance for later use
                window.sqlite3 = sqlite3;
                window.db = db;
                
                // Create tables based on schema if they don't exist
                try {
                    const schema = await exportDatabaseSchema();
                    window.schema = schema;
                    console.log("Creating tables from schema:", schema);
                    
                    // Process each table in the schema
                    for (const table of schema.tables) {
                        // Build CREATE TABLE statement
                        let createTableSQL = `CREATE TABLE IF NOT EXISTS ${table.name} (`;
                        
                        // Add columns
                        const columnDefs = table.columns.map(col => {
                            let colDef = `${col.name} ${col.data_type}`;
                            
                            // Add constraints
                            if (col.primary_key) {
                                colDef += " PRIMARY KEY";
                            }
                            if (!col.nullable) {
                                colDef += " NOT NULL";
                            }
                            if (col.default_value) {
                                colDef += ` DEFAULT ${col.default_value}`;
                            }
                            
                            return colDef;
                        });
                        
                        createTableSQL += columnDefs.join(", ");
                        
                        // Add unique constraints for indexes
                        if (table.indexes && table.indexes.length > 0) {
                            for (const index of table.indexes) {
                                if (index.unique) {
                                    createTableSQL += `, UNIQUE (${index.column_names.join(", ")})`;
                                }
                            }
                        }
                        
                        createTableSQL += ")";
                        
                        // Execute the CREATE TABLE statement
                        console.log(`Executing SQL: ${createTableSQL}`);
                        db.exec(createTableSQL);
                        
                        // Create non-unique indexes separately
                        if (table.indexes && table.indexes.length > 0) {
                            for (const index of table.indexes) {
                                if (!index.unique) {
                                    const createIndexSQL = 
                                        `CREATE INDEX IF NOT EXISTS ${index.name} ON ${table.name} (${index.column_names.join(", ")})`;
                                    console.log(`Executing SQL: ${createIndexSQL}`);
                                    db.exec(createIndexSQL);
                                }
                            }
                        }
                    }                    
                } catch (error) {
                    console.error("Error creating tables from schema:", error);
                }
            } catch (error) {
                console.error("SQLite initialization error:", error);
            }

            document.getElementById('service-btn').addEventListener('click', async () => {
                try {
                    const serviceName = document.getElementById('service-name').value;
                    const paramsText = document.getElementById('service-params').value;
                    const params = JSON.parse(paramsText);
                    
                    const result = await callService(serviceName, params);
                    document.getElementById('service-result').textContent = 
                        JSON.stringify(result, null, 2);
                } catch (error) {
                    document.getElementById('service-result').textContent = 
                        `Error: ${error.message || error}`;
                }
            });
            
            // Entity operation event listeners
            
            // Create Entity
            document.getElementById('create-entity-btn').addEventListener('click', async () => {
                try {
                    const entityName = document.getElementById('create-entity-type').value;
                    const entityDataText = document.getElementById('create-entity-data').value;
                    const entityData = JSON.parse(entityDataText);
                    
                    const result = await createEntity(entityName, entityData);
                    document.getElementById('create-entity-result').textContent = 
                        JSON.stringify(result, null, 2);
                } catch (error) {
                    document.getElementById('create-entity-result').textContent = 
                        `Error: ${error.message || error}`;
                }
            });
            
            // Update Entity
            document.getElementById('update-entity-btn').addEventListener('click', async () => {
                try {
                    const entityName = document.getElementById('update-entity-type').value;
                    const entityDataText = document.getElementById('update-entity-data').value;
                    const entityData = JSON.parse(entityDataText);
                    

                    const result = await updateEntity(entityName, entityData);
                    document.getElementById('update-entity-result').textContent = 
                        JSON.stringify(result, null, 2);
                } catch (error) {
                    document.getElementById('update-entity-result').textContent = 
                        `Error: ${error.message || error}`;
                }
            });
            
            // Delete Entity
            document.getElementById('delete-entity-btn').addEventListener('click', async () => {
                try {
                    const entityName = document.getElementById('delete-entity-type').value;
                    const entityDataText = document.getElementById('delete-entity-data').value;
                    const entityData = JSON.parse(entityDataText);
                    
                    // Check if primary key is included
                    const schema = window.schema;
                    if (schema && schema.tables) {
                        const tableSchema = schema.tables.find(table => 
                            table.name.toLowerCase() === entityName.toLowerCase());
                        
                        if (tableSchema) {
                            const primaryKeyColumns = tableSchema.columns.filter(col => col.primary_key);
                            if (primaryKeyColumns.length > 0) {
                                const pkField = primaryKeyColumns[0].name;
                                if (!entityData[pkField]) {
                                    throw new Error(`Primary key field '${pkField}' is required for delete`);
                                }
                            }
                        }
                    }
                    
                    const result = await deleteEntity(entityName, entityData);
                    document.getElementById('delete-entity-result').textContent = 
                        JSON.stringify(result, null, 2);
                } catch (error) {
                    document.getElementById('delete-entity-result').textContent = 
                        `Error: ${error.message || error}`;
                }
            });
            
            // Find One Entity
            document.getElementById('find-one-btn').addEventListener('click', async () => {
                try {
                    const entityName = document.getElementById('find-one-entity-type').value;
                    const queryText = document.getElementById('find-one-query').value;
                    const query = JSON.parse(queryText);
                    
                    const result = await findOne(entityName, query);
                    document.getElementById('find-one-result').textContent = 
                        JSON.stringify(result, null, 2);
                    
                    // No need to update separate ID fields anymore
                } catch (error) {
                    document.getElementById('find-one-result').textContent = 
                        `Error: ${error.message || error}`;
                }
            });
            
            // Find Many Entities
            document.getElementById('find-many-btn').addEventListener('click', async () => {
                try {
                    const entityName = document.getElementById('find-many-entity-type').value;
                    const queryText = document.getElementById('find-many-query').value;
                    const query = JSON.parse(queryText);
                    
                    const result = await findMany(entityName, query);
                    document.getElementById('find-many-result').textContent = 
                        JSON.stringify(result, null, 2);
                } catch (error) {
                    document.getElementById('find-many-result').textContent = 
                        `Error: ${error.message || error}`;
                }
            });
            
            // Example 1: Filter by specific field
            document.getElementById('example1-btn').addEventListener('click', () => {
                const exampleQuery = {
                    "disabled": "N",  // Only active users
                    "_orderBy": "username",
                    "_orderDir": "ASC",
                    "_limit": 5
                };
                document.getElementById('find-many-query').value = JSON.stringify(exampleQuery, null, 2);
                document.getElementById('find-many-query').style.height = 'auto';
                document.getElementById('find-many-query').style.height = 
                    document.getElementById('find-many-query').scrollHeight + 'px';
            });
            
            // Example 2: Pagination example
            document.getElementById('example2-btn').addEventListener('click', () => {
                const exampleQuery = {
                    "_limit": 3,      // Show only 3 results
                    "_offset": 3,      // Skip the first 3 results (page 2)
                    "_orderBy": "userId"  // Order by userId
                };
                document.getElementById('find-many-query').value = JSON.stringify(exampleQuery, null, 2);
                document.getElementById('find-many-query').style.height = 'auto';
                document.getElementById('find-many-query').style.height = 
                    document.getElementById('find-many-query').scrollHeight + 'px';
            });
            
            // Example 3: Sorting example
            document.getElementById('example3-btn').addEventListener('click', () => {
                const exampleQuery = {
                    "_orderBy": "passwordSetDate",  // Sort by password set date
                    "_orderDir": "DESC",            // Newest first
                    "_limit": 10
                };
                document.getElementById('find-many-query').value = JSON.stringify(exampleQuery, null, 2);
                document.getElementById('find-many-query').style.height = 'auto';
                document.getElementById('find-many-query').style.height = 
                    document.getElementById('find-many-query').scrollHeight + 'px';
            });
            
            // Export Database Schema
            document.getElementById('export-schema-btn').addEventListener('click', async () => {
                try {
                    const schema = await exportDatabaseSchema();
                    document.getElementById('schema-result').textContent = 
                        JSON.stringify(schema, null, 2);
                } catch (error) {
                    document.getElementById('schema-result').textContent = 
                        `Error: ${error.message || error}`;
                }
            });
        }

        // Function to make textareas auto-expand
        function setupAutoExpandingTextareas() {
            const textareas = document.querySelectorAll('textarea');
            
            textareas.forEach(textarea => {
                // Add auto-expand class
                textarea.classList.add('auto-expand');
                
                // Set initial height
                textarea.style.height = 'auto';
                textarea.style.height = textarea.scrollHeight + 'px';
                
                // Add input event listener to adjust height as content changes
                textarea.addEventListener('input', function() {
                    this.style.height = 'auto';
                    this.style.height = this.scrollHeight + 'px';
                });
                
                // Also trigger on window resize
                window.addEventListener('resize', function() {
                    textarea.style.height = 'auto';
                    textarea.style.height = textarea.scrollHeight + 'px';
                });
            });
        }
        
        // Wait for DOM to be fully loaded before running
        document.addEventListener('DOMContentLoaded', () => {
            run().catch(console.error).finally(() => {
                // Setup auto-expanding textareas after everything is loaded
                setupAutoExpandingTextareas();
            });
        });
    </script>
</body>
</html>