/ Check-in [bd26a2d361]
DEMO | DOWNLOAD | DEPLOY | SEARCH
Login

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Release "2.8.19". Finish sample CData example DBI.
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1:bd26a2d361232b613f376017743a5964cabf97e2
User & Date: pmacdona 2019-04-12 03:39:00
Context
2019-04-12
13:23
CData: generalize idconf to any XXconf with struct CMD_XX Leaf check-in: 4cdaa72811 user: pmacdona tags: trunk
03:39
Release "2.8.19". Finish sample CData example DBI. check-in: bd26a2d361 user: pmacdona tags: trunk
2019-04-10
22:45
Release "2.8.18" CData: fix config memory handling. check-in: 2ea4655166 user: pmacdona tags: trunk
Changes

Changes to DBI/DBI.jsc.

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
..
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
...
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
...
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
...
335
336
337
338
339
340
341

342
343
344
345
346
347
348
#!/usr/local/bin/jsish -c %s
// The libDBI object.  Create with "new DBI()"

code Header = {
#include <dbi/dbi.h>
};

enum dbi_resType = {
    rows, arrays, array1d, list, column, json,
    json2, html, csv, insert, line, tabs, id, none
};














struct DBI_ = { // Module struct (optional), will be per-interp if no DBI_Data var.
    bool loaded;        // <RO> Module load count.
    int activeCnt;      // Count of active objects.
    int newCnt;         // Total number of new.
    int init;           // is init
    dbi_inst _dbi;      //  db instance
};

struct DBI = {              // Per-object struct
    Jsi_Interp* interp;     // Note: must add interp field for object command.
    DBI_* _;                // Ptr to DBI_ defined above
    const char* driver;     // <IO> Name of driver (sqlite)
    const char* sqlite_dbdir;// File path: for sqlite
    const char* username;   // Userid for login
    const char* password;   // Password for login
    const char* dbname;     // Database
    const char* host;       // Hostname
    const char* encoding;   // Char encoding (UTF-8)
    int port;               // Timeout.
    int sqlite_timeout;     // Timeout for sqlite.
    int timeout;            // Timeout.

    int version;

    bool isopen;            // <RO> Is database connection open.

    OBJ drvOpts;            // Other driver options.
    FUNC callback;          // <IO; FUNC(str:string, id:number)> Callback function for queries.




    dbi_conn  _db;          // The database connection
    int _idx;
    Jsi_Hash* _resHash;
};

struct DBI_toArray = {
    double Max;
    int Cnt;
};


struct DBI_query = {
    dbi_resType mode;       // Output mode.
    OBJ params;             // Input parameters.
};
        
struct DBI_id = {
    int id;
    Jsi_HashEntry* _hPtr;
    dbi_result _res;
    DBI* _cmdPtr;
    bool onrecord;
    int resultCount;
    int fieldCount;
    short* _fieldTypes;
    char** _fieldNames;
};

vars DBIVars = {
    DBI_query DBI_query_Data;
    DBI_ DBI_Data; // ie. Module struct is not per-interp.
................................................................................
    
    function _() {
        /* C code for Init/Done */
        _->init += (isRelease?-1:1);
        if (isRelease) {
            if (_->init == 0)
                dbi_shutdown_r(_->_dbi);
            puts("Unloading DBI");
        } else {
            if (_->init==1)
                dbi_initialize_r(NULL, &_->_dbi);
            puts("Loading DBI");
        }
    }
    
    function ~() {
        /* C code for Object free */
        puts("CLOSING");
        cmdPtr->_->activeCnt--;
        if (cmdPtr->_resHash)
            Jsi_HashDelete(cmdPtr->_resHash);
        if (cmdPtr->_db)
            dbi_conn_close(cmdPtr->_db);
    }
    
    function DBI(options:object=void):userobj { // DBI constructor
        /* C code. */

        Jsi_RC rc = JSI_OK;

        cmdPtr->interp = interp;
        cmdPtr->version = LIBDBI_VERSION;
        if (!cmdPtr->driver)
            cmdPtr->driver = "sqlite";

        cmdPtr->_db = dbi_conn_new_r( cmdPtr->driver, cmdPtr->_->_dbi );
        if (!cmdPtr->_db)
            return Jsi_LogError("connection failed");
        const char *msg = "N/A";
#define MYDBI_OPT_SET(name,typ) \
        if (cmdPtr->name) \
            if (dbi_conn_set_option##typ( cmdPtr->_db, #name, cmdPtr->name )) { \
                msg = #name; \
                goto bail; \
            }
                
        MYDBI_OPT_SET(username,)
        MYDBI_OPT_SET(password,)
        MYDBI_OPT_SET(dbname,)
................................................................................
            Jsi_TreeSearch search;
            Jsi_Tree *tp = Jsi_TreeFromValue(interp, dargs);
            if (!tp)
                goto bail;
            
            for (tPtr = Jsi_TreeSearchFirst(tp, &search, 0, NULL);
                tPtr != NULL; tPtr = Jsi_TreeSearchNext(&search)) {
                const char *arg =(char*) Jsi_TreeKeyGet(tPtr);
                Jsi_Value *optval = (Jsi_Value*)Jsi_TreeValueGet(tPtr);
                
                if( Jsi_ValueIsString(interp, optval) )
                {
                    // Set as string option:
                    const char *vstr = Jsi_ValueString(interp, optval, 0);
                    if (dbi_conn_set_option( cmdPtr->_db, arg, vstr ))

                        rc = Jsi_LogWarn("option set failed: ", arg);
                }

                else if( Jsi_ValueIsNumber(interp, optval) )
                {
                    // Set as numeric option:
                    int vnum = Jsi_ValueToNumberInt(interp, optval, 1);
                    if (dbi_conn_set_option_numeric( cmdPtr->_db, arg, vnum ))
                        rc = Jsi_LogWarn("option set failed: ", arg);

                }
                else
                    rc = Jsi_LogWarn("expected int or string");




            }
            Jsi_TreeSearchDone(&search);
            if (rc != JSI_OK)
                goto bail;
        }







        cmdPtr->_resHash = Jsi_HashNew(interp, JSI_KEYS_ONEWORD, DBI_IdErase);
        cmdPtr->_->newCnt++;
        cmdPtr->_->activeCnt++;
        return JSI_OK;
bail:


        return Jsi_LogError("failed to create DBI: %s", msg);
    }

    function conf(options:object|string=void):any { // Function to configure DBI options
        /* C code. */
    }































    function begin():boolean { // Open a transaction
        /* C-code. */
        int rval = dbi_conn_transaction_begin( cmdPtr->_db );
        bool b = (rval == 0 ? 1 : 0);
        RETURN(b);
    }
    
    function commit():boolean { // Commit a transaction
        /* C-code. */
        int rval = dbi_conn_transaction_commit( cmdPtr->_db );
        bool b = (rval == 0 ? 1 : 0);
        RETURN(b);
    }
    
    function rollback():boolean { // Rollback a transaction
        /* C-code. */
        int rval = dbi_conn_transaction_rollback( cmdPtr->_db );
        bool b = (rval == 0 ? 1 : 0);
        RETURN(b);
    }
    
    function open():boolean { // Open connection
        /* C-code. */
        bool b = (0 == dbi_conn_connect(cmdPtr->_db));
        cmdPtr->isopen = b;
        RETURN(b);
    }
    
    function error():object { // Return the last error on this connection
        /* C-code. */
        const char *errstr;
        int errnum = dbi_conn_error(cmdPtr->_db, &errstr);
        Jsi_Obj *nobj = Jsi_ObjNew(interp);
        Jsi_ValueMakeObject(interp, ret, nobj);
        Jsi_ValueInsert(interp, *ret, "number", Jsi_ValueNewBlob(interp, (uchar*)errstr, Jsi_Strlen(errstr)), 0);
        Jsi_ValueInsert(interp, *ret, "text", Jsi_ValueNewNumber(interp, errnum), 0);
        return JSI_OK;
    }
    
    function use(dbname:string):boolean { // Use a database 
        int rval = dbi_conn_select_db(cmdPtr->_db, dbname);
        bool b = (rval == 0 ? 1 : 0);


        RETURN(b);
    }

    function lastseq(seqname:string=void):number { // Fetch the last sequence ID assigned if supported
        const char *seqname = Jsi_ValueArrayIndexToStr(interp, args, 0, NULL);
        Jsi_Number n = dbi_conn_sequence_last(cmdPtr->_db, seqname);
        RETURN(n);
................................................................................
        const char *unquoted = Jsi_ValueArrayIndexToStr(interp, args, 0, &bufLength);
        int newLength = dbi_conn_quote_binary_copy(cmdPtr->_db, (const unsigned char *)unquoted,
            bufLength, (unsigned char **)&quoted );
        Jsi_ValueMakeBlob(interp, ret, (unsigned char *)quoted, newLength);
        return JSI_OK;
    }
    

































    function query(query:string, options:object=void):number { // Run query and return id
        /* C-code. */
        Jsi_DString dStr = {};
        Jsi_Value *params = dPtr->params;

        if (!params || !Jsi_ValueGetLength(interp, params))
            Jsi_DSAppendLen(&dStr, query, queryLen);
        else
            if (DBI_AddArgs(cmdPtr, &dStr, query, queryLen, params) != JSI_OK)
                return JSI_ERROR;

        dbi_result res = dbi_conn_query( cmdPtr->_db, Jsi_DSValue(&dStr));
        Jsi_DSFree(&dStr);
        if (!res) {
            const char *msg = "N/A";
            int num = dbi_conn_error(cmdPtr->_db, &msg);

            return Jsi_LogError("query failure: %d %s", num, msg);
        }
        DBI_id *pss = DBI_IdGet(cmdPtr, -1, 1);

        if (!pss) {
            dbi_result_free(res);

            return JSI_ERROR;
        }

        pss->onrecord = dbi_result_first_row(res);
        pss->resultCount = dbi_result_get_numrows( res );
        pss->fieldCount = dbi_result_get_numfields( res );
        pss->_fieldTypes = (short*)Jsi_Calloc( pss->fieldCount, sizeof(unsigned short) );
        pss->_fieldNames = (char**)Jsi_Calloc( pss->fieldCount, sizeof(char *) );
        for( int x=0; x < pss->fieldCount; x++ )
        {
            const char *fieldname = dbi_result_get_field_name( res, x+1 );
            pss->_fieldTypes[x] = dbi_result_get_field_type_idx( res, x+1 );
            pss->_fieldNames[x] = (char*)Jsi_KeyAdd(interp, fieldname);
        }

        pss->_res = res;
        int id = pss->id;



        RETURN(id);







    }
    
    function ids():array { // Return list of query ids
        /* C code. */
        Jsi_DString dStr;
        Jsi_DSInit(&dStr);
        Jsi_DSAppend(&dStr, "{", NULL);
        DBI_id *pss = NULL;
        Jsi_HashEntry *hPtr;
        Jsi_HashSearch cursor;
        int cnt = 0;
        for (hPtr = Jsi_HashSearchFirst(cmdPtr->_resHash, &cursor);
            hPtr != NULL; hPtr = Jsi_HashSearchNext(&cursor)) {
            pss = (DBI_id *)Jsi_HashValueGet(hPtr);
            Jsi_DSPrintf(&dStr, "%s%d", cnt++?",":"", pss->id);
        }
        Jsi_DSAppend(&dStr, "}", NULL);
        Jsi_RC rc = Jsi_JSONParse(interp, Jsi_DSValue(&dStr), ret, 0);
        Jsi_DSFree(&dStr);
        return rc;
    }

    function idconf(id:number, options:object|string=void):any { // Function to configure query id options
        /* C code. */
................................................................................
        int i;
        for (i=0; i<pss->fieldCount; i++) {
            Jsi_Value *v = Jsi_ValueNew(interp);
            if (JSI_OK != DBI_IdValue(interp, pss, &v, i))
                Jsi_ValueMakeNull(interp, &v);
            Jsi_ObjInsert(interp, res, pss->_fieldNames[i], v, JSI_OM_READONLY );
        }

        return JSI_OK;
    }

    function free(id:number):void { // Delete query id
        /* C code. */
        DBI_id *pss = DBI_IdGet(cmdPtr, id, 0);
        if (!pss)







|

|


>
>
>
>
>
>
>
>
>
>
>
>
>









<
<
|
|
|
|
|
|
|
|
|
|
>
|
>
|
>
|

>
>
>
>




|
|
|
|
|
<
>
|
|
<
<
|
<
<



<
<
<







 







|



|





|









>

>
|


|
>
|





|







 







|


|
<


|
>
|
|
>
|
<


|
|
>
|
|
<
>
>
>
>





>
>
>
>
>
>
>



<

>
>




|


>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>


|






|






|




<
<
<
<
<
<
<













|
>
>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>



<
>
|


|


|
<



>


<
>

<
>


|
<
|
<
<
<
<
<
<
<
<
<
<
<
|
>
>
>
|
>
>
>
>
>
>
>






|









|







 







>







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
..
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
...
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
...
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
...
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
#!/usr/local/bin/jsish -c %s
// The libDBI object.  Create with "new DBI()"

code Header = {
#include <dbi/dbi.h>
};

enum DBI_mode = {
    rows, arrays, array1d, list, column, json,
    json2, html, csv, insert, line, tabs, cursor, none
};


struct DBI_query = { // Options for queries.
    DBI_mode mode;          // Output mode.
    OBJ values;             // Input parameters.
    ARRAY widths;           // In column mode, set column widths
    int limit;              // Maximum number of returned values.
    bool headers;           // First row returned contains column labels
    const char* nullvalue;  // Null string output (for non-json mode)
    const char* separator;  // Separator string (for csv and text mode)
    const char* table;      // Table name for mode=insert
    FUNC callback;          // <FUNC(values:object)> Function to call with each row result.
};
    
struct DBI_ = { // Module struct (optional), will be per-interp if no DBI_Data var.
    bool loaded;        // <RO> Module load count.
    int activeCnt;      // Count of active objects.
    int newCnt;         // Total number of new.
    int init;           // is init
    dbi_inst _dbi;      //  db instance
};

struct DBI = {              // Per-object struct


    const char* driver;     // <IO> Name of driver (sqlite3)
    const char* sqlite_dbdir;//<IO> File path, obviously only for sqlite
    const char* username;   // <IO> Userid for login
    const char* password;   // <IO> Password for login
    const char* dbname;     // <IO> Database
    const char* host;       // <IO> Hostname
    const char* encoding;   // <IO> Char encoding (UTF-8)
    int port;               // <IO> Timeout.
    int sqlite_timeout;     // <IO> Timeout for sqlite.
    int timeout;            // <IO> Timeout.
    int verbosity;          // <IO> Verbosity level
    int version;            // <RO> Version
    int engineVersion;      // <RO> Version of db engine
    int socket;             // <RO> Socket handle
    bool isSqlite;          // <RO> True if using sqlite.
    OBJ drvOpts;            // <IO> Other driver options.
    FUNC callback;          // <IO; FUNC(str:string, id:number)> Callback function for queries.
    DBI_query queryOpts;    // Options to use for all queries.
    
    Jsi_Interp* _interp;     // Note: must add interp field for object command.
    DBI_* _;                // Ptr to DBI_ defined above
    dbi_conn  _db;          // The database connection
    int _idx;
    Jsi_Hash* _resHash;
};
    
struct DBI_id = {
    int id;                 // <RO> Index id.
    bool onrecord;          // <RO> True if on a record.
    int resultCount;        // <RO> Number of rows in result.

    int fieldCount;         // <RO> Number of fields.
    int curInd;             // <RO> Current result row index, staring from 0.
    STRING sql;             // <RO> Expanded sql from query.





    Jsi_HashEntry* _hPtr;
    dbi_result _res;
    DBI* _cmdPtr;



    short* _fieldTypes;
    char** _fieldNames;
};

vars DBIVars = {
    DBI_query DBI_query_Data;
    DBI_ DBI_Data; // ie. Module struct is not per-interp.
................................................................................
    
    function _() {
        /* C code for Init/Done */
        _->init += (isRelease?-1:1);
        if (isRelease) {
            if (_->init == 0)
                dbi_shutdown_r(_->_dbi);
            //puts("Unloading DBI");
        } else {
            if (_->init==1)
                dbi_initialize_r(NULL, &_->_dbi);
            //puts("Loading DBI");
        }
    }
    
    function ~() {
        /* C code for Object free */
        //puts("CLOSING");
        cmdPtr->_->activeCnt--;
        if (cmdPtr->_resHash)
            Jsi_HashDelete(cmdPtr->_resHash);
        if (cmdPtr->_db)
            dbi_conn_close(cmdPtr->_db);
    }
    
    function DBI(options:object=void):userobj { // DBI constructor
        /* C code. */
        const char *cp;
        Jsi_RC rc = JSI_OK;
        dbi_set_verbosity_r(cmdPtr->verbosity, cmdPtr->_->_dbi);
        cmdPtr->_interp = interp;
        cmdPtr->version = LIBDBI_VERSION;
        if (!cmdPtr->driver)
            cmdPtr->driver = "sqlite3";
        cmdPtr->isSqlite = !Jsi_Strcmp(cmdPtr->driver, "sqlite3");
        cmdPtr->_db = dbi_conn_new_r(cmdPtr->driver, cmdPtr->_->_dbi);
        if (!cmdPtr->_db)
            return Jsi_LogError("connection failed");
        const char *msg = "N/A";
#define MYDBI_OPT_SET(name,typ) \
        if (cmdPtr->name) \
            if (dbi_conn_set_option##typ(cmdPtr->_db, #name, cmdPtr->name)) { \
                msg = #name; \
                goto bail; \
            }
                
        MYDBI_OPT_SET(username,)
        MYDBI_OPT_SET(password,)
        MYDBI_OPT_SET(dbname,)
................................................................................
            Jsi_TreeSearch search;
            Jsi_Tree *tp = Jsi_TreeFromValue(interp, dargs);
            if (!tp)
                goto bail;
            
            for (tPtr = Jsi_TreeSearchFirst(tp, &search, 0, NULL);
                tPtr != NULL; tPtr = Jsi_TreeSearchNext(&search)) {
                msg =(char*) Jsi_TreeKeyGet(tPtr);
                Jsi_Value *optval = (Jsi_Value*)Jsi_TreeValueGet(tPtr);
                
                if (Jsi_ValueIsString(interp, optval)) {

                    // Set as string option:
                    const char *vstr = Jsi_ValueString(interp, optval, 0);
                    if (dbi_conn_set_option(cmdPtr->_db, msg, vstr)) {
                        rc = JSI_ERROR;
                        break;
                    }
                }
                else if (Jsi_ValueIsNumber(interp, optval)) {

                    // Set as numeric option:
                    int vnum = Jsi_ValueToNumberInt(interp, optval, 1);
                    if (dbi_conn_set_option_numeric(cmdPtr->_db, msg, vnum)) {
                        rc = JSI_ERROR;
                        break;
                    }
                } else {

                    rc = JSI_ERROR;
                    msg = "option must be int or string";
                    break;
                }
            }
            Jsi_TreeSearchDone(&search);
            if (rc != JSI_OK)
                goto bail;
        }
        if (dbi_conn_connect(cmdPtr->_db))
            return Jsi_LogError("DBI connect failed");
        cmdPtr->engineVersion = dbi_conn_get_engine_version(cmdPtr->_db);
        cp = dbi_conn_get_encoding(cmdPtr->_db);
        if (cp)
            cmdPtr->encoding = Jsi_KeyAdd(interp, cp);
        cmdPtr->socket = dbi_conn_get_socket(cmdPtr->_db);
        cmdPtr->_resHash = Jsi_HashNew(interp, JSI_KEYS_ONEWORD, DBI_IdErase);
        cmdPtr->_->newCnt++;
        cmdPtr->_->activeCnt++;

bail:
        if (rc == JSI_OK)
            return JSI_OK;
        return Jsi_LogError("failed to create DBI: %s", msg);
    }

    function conf(options:object|string=void):any { // Function to configure DBI options
        /* Builtin. */
    }

    function options():array { // Return list of options
        const char *cur = NULL;
        Jsi_Obj *o = Jsi_ObjNewType(interp, JSI_OT_ARRAY);
        Jsi_ValueMakeArrayObject(interp, ret, o);
        while ((cur=dbi_conn_get_option_list(cmdPtr->_db, cur)))
            Jsi_ObjArrayAdd(interp, o, Jsi_ValueNewStringDup(interp, cur));
        return JSI_OK;
    }

    function capability(capname:string):number { // Return capability
        Jsi_Number n = dbi_conn_cap_get(cmdPtr->_db, capname);
        RETURN(n);
    }
    
    function driver():object { // Return driver info
        dbi_driver d = dbi_conn_get_driver(cmdPtr->_db);
        if (!d)
            return Jsi_LogError("failed to get driver info");
        Jsi_Obj *o = Jsi_ObjNew(interp);
        Jsi_ValueMakeObject(interp, ret, o);
        Jsi_ValueInsert(interp, *ret, "name", Jsi_ValueNewStringDup(interp, dbi_driver_get_name(d)), 0);
        Jsi_ValueInsert(interp, *ret, "file", Jsi_ValueNewStringDup(interp, dbi_driver_get_filename(d)), 0);
        Jsi_ValueInsert(interp, *ret, "description", Jsi_ValueNewStringDup(interp, dbi_driver_get_description(d)), 0);
        Jsi_ValueInsert(interp, *ret, "maintainer", Jsi_ValueNewStringDup(interp, dbi_driver_get_maintainer(d)), 0);
        Jsi_ValueInsert(interp, *ret, "url", Jsi_ValueNewStringDup(interp, dbi_driver_get_url(d)), 0);
        Jsi_ValueInsert(interp, *ret, "version", Jsi_ValueNewStringDup(interp, dbi_driver_get_version(d)), 0);
        Jsi_ValueInsert(interp, *ret, "date_compiled", Jsi_ValueNewStringDup(interp, dbi_driver_get_date_compiled(d)), 0);
        return JSI_OK;
    }
    
    function begin():boolean { // Open a transaction
        /* C-code. */
        int rval = dbi_conn_transaction_begin(cmdPtr->_db);
        bool b = (rval == 0 ? 1 : 0);
        RETURN(b);
    }
    
    function commit():boolean { // Commit a transaction
        /* C-code. */
        int rval = dbi_conn_transaction_commit(cmdPtr->_db);
        bool b = (rval == 0 ? 1 : 0);
        RETURN(b);
    }
    
    function rollback():boolean { // Rollback a transaction
        /* C-code. */
        int rval = dbi_conn_transaction_rollback(cmdPtr->_db);
        bool b = (rval == 0 ? 1 : 0);
        RETURN(b);
    }
    







    function error():object { // Return the last error on this connection
        /* C-code. */
        const char *errstr;
        int errnum = dbi_conn_error(cmdPtr->_db, &errstr);
        Jsi_Obj *nobj = Jsi_ObjNew(interp);
        Jsi_ValueMakeObject(interp, ret, nobj);
        Jsi_ValueInsert(interp, *ret, "number", Jsi_ValueNewBlob(interp, (uchar*)errstr, Jsi_Strlen(errstr)), 0);
        Jsi_ValueInsert(interp, *ret, "text", Jsi_ValueNewNumber(interp, errnum), 0);
        return JSI_OK;
    }
    
    function use(dbname:string):boolean { // Use a database 
        int rval = dbi_conn_select_db(cmdPtr->_db, dbname);
        bool b = !rval;
        if (b)
            cmdPtr->dbname = Jsi_KeyAdd(interp, dbname);
        RETURN(b);
    }

    function lastseq(seqname:string=void):number { // Fetch the last sequence ID assigned if supported
        const char *seqname = Jsi_ValueArrayIndexToStr(interp, args, 0, NULL);
        Jsi_Number n = dbi_conn_sequence_last(cmdPtr->_db, seqname);
        RETURN(n);
................................................................................
        const char *unquoted = Jsi_ValueArrayIndexToStr(interp, args, 0, &bufLength);
        int newLength = dbi_conn_quote_binary_copy(cmdPtr->_db, (const unsigned char *)unquoted,
            bufLength, (unsigned char **)&quoted );
        Jsi_ValueMakeBlob(interp, ret, (unsigned char *)quoted, newLength);
        return JSI_OK;
    }
    
    function tables(pattern:string=''):number { // Return tables in current database
        dbi_result res = dbi_conn_get_table_list(cmdPtr->_db, cmdPtr->dbname, pattern);
        if (!res) {
            const char *msg = "N/A";
            int num = dbi_conn_error(cmdPtr->_db, &msg);
            return Jsi_LogWarn("tables failed: %d %s", num, msg);
        }
        DBI_id *pss = DbiQueryNew(interp, cmdPtr, res);
        if (!pss)
            return JSI_ERROR;
        DBI_query *q = &cmdPtr->queryOpts;
        DBI_mode om = q->mode;
        q->mode = array1d;
        Jsi_RC rc = DbiQueryCmd(interp, args, _this, ret, funcPtr, pss, q, false);
        q->mode = om;
        return rc;
    }
    
    function databases(pattern:string=''):number { // Return available databases
        dbi_result res = dbi_conn_get_db_list(cmdPtr->_db, pattern);
        if (!res)
            return Jsi_LogWarn("databases unsupported");
        DBI_id *pss = DbiQueryNew(interp, cmdPtr, res);
        if (!pss)
            return JSI_ERROR;
        DBI_query *q = &cmdPtr->queryOpts;
        DBI_mode om = q->mode;
        q->mode = array1d;
        Jsi_RC rc = DbiQueryCmd(interp, args, _this, ret, funcPtr, pss, q, false);
        q->mode = om;
        return rc;
    }
        
    function query(query:string, options:object=void):number { // Run query and return id
        /* C-code. */
        Jsi_DString dStr = {};

        Jsi_Value *values = options->values;
        if (!values || !Jsi_ValueGetLength(interp, values))
            Jsi_DSAppendLen(&dStr, query, queryLen);
        else
            if (DBI_AddArgs(cmdPtr, &dStr, query, queryLen, values) != JSI_OK)
                return JSI_ERROR;

        dbi_result res = dbi_conn_query(cmdPtr->_db, Jsi_DSValue(&dStr));

        if (!res) {
            const char *msg = "N/A";
            int num = dbi_conn_error(cmdPtr->_db, &msg);
            Jsi_DSFree(&dStr);
            return Jsi_LogError("query failure: %d %s", num, msg);
        }

        DBI_id *pss = DbiQueryNew(interp, cmdPtr, res);
        if (!pss) {

            Jsi_DSFree(&dStr);
            return JSI_ERROR;
        }
        

        if (options->mode == cursor) {











            int id = pss->id;
            pss->sql = Jsi_ValueNewStringDup(interp, Jsi_DSValue(&dStr));
            Jsi_IncrRefCount(interp, pss->sql);
            Jsi_DSFree(&dStr);
            RETURN(id);
        }
        Jsi_DSFree(&dStr);
        // Handle special case of options->mode is rows (0), and DB.queryOpts.mode got set to non-zero.
        bool ovmode = JSI_CDATA_OPTION_CHANGED(mode);
        Jsi_RC rc = DbiQueryCmd(interp, args, _this, ret, funcPtr, pss, options, ovmode);
        Jsi_HashEntryDelete(pss->_hPtr);
        return rc;
    }
    
    function ids():array { // Return list of query ids
        /* C code. */
        Jsi_DString dStr;
        Jsi_DSInit(&dStr);
        Jsi_DSAppend(&dStr, "[", NULL);
        DBI_id *pss = NULL;
        Jsi_HashEntry *hPtr;
        Jsi_HashSearch cursor;
        int cnt = 0;
        for (hPtr = Jsi_HashSearchFirst(cmdPtr->_resHash, &cursor);
            hPtr != NULL; hPtr = Jsi_HashSearchNext(&cursor)) {
            pss = (DBI_id *)Jsi_HashValueGet(hPtr);
            Jsi_DSPrintf(&dStr, "%s%d", cnt++?",":"", pss->id);
        }
        Jsi_DSAppend(&dStr, "]", NULL);
        Jsi_RC rc = Jsi_JSONParse(interp, Jsi_DSValue(&dStr), ret, 0);
        Jsi_DSFree(&dStr);
        return rc;
    }

    function idconf(id:number, options:object|string=void):any { // Function to configure query id options
        /* C code. */
................................................................................
        int i;
        for (i=0; i<pss->fieldCount; i++) {
            Jsi_Value *v = Jsi_ValueNew(interp);
            if (JSI_OK != DBI_IdValue(interp, pss, &v, i))
                Jsi_ValueMakeNull(interp, &v);
            Jsi_ObjInsert(interp, res, pss->_fieldNames[i], v, JSI_OM_READONLY );
        }
        pss->onrecord = dbi_result_seek_row(pss->_res, ++pss->curInd);
        return JSI_OK;
    }

    function free(id:number):void { // Delete query id
        /* C code. */
        DBI_id *pss = DBI_IdGet(cmdPtr, id, 0);
        if (!pss)

Changes to DBI/DBIinc.c.

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
..
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











































































































































































































































































































































































































































































































































































































































































































































































































































    }
    return pss;
}

static Jsi_RC DBI_IdErase(Jsi_Interp *interp, Jsi_HashEntry* hPtr, void *ptr) {
    DBI_id *pss = (DBI_id *)ptr;
    if (pss) {
        printf("FREEPSS: %d\n", pss->id);
        pss->_hPtr = NULL;
        if (pss->_res)
            dbi_result_free(pss->_res);
        if (pss->_fieldTypes)
            Jsi_Free(pss->_fieldTypes);
        if (pss->_fieldNames)
            Jsi_Free(pss->_fieldNames);


        Jsi_Free(pss);
        //sockDeletePss(pss);
    }
    return JSI_OK;
}

static Jsi_RC DBI_AddArgs(DBI *cmdPtr, Jsi_DString *dStr, const char *query, int qlen, Jsi_Value *args) {
    Jsi_Interp *interp = cmdPtr->interp;
    int n, idx, len, argc = Jsi_ValueGetLength(interp, args);
    Jsi_Value *val;
    char *str, *cp, *qp = (char*)query;
    
    while ((cp = Jsi_Strchr(qp, '%'))) {
        if (cp[1] == '%') {
            Jsi_DSAppendLen(dStr, qp, cp-qp+1);
................................................................................
            continue;
        }
        Jsi_DSAppendLen(dStr, qp, cp-qp);
        n = 0;
        while (isdigit(cp[n])) n++;
        idx = atoi(cp+1);
        qp = cp + n + 2;
        if( idx <= 0 || idx > argc || !(val = Jsi_ValueArrayIndex(interp, args, idx-1)))
            return Jsi_LogError("failure in DBI_AddArgs");

        if (Jsi_ValueIsNumber(interp, val)) {
            Jsi_Number num;
            Jsi_ValueGetNumber(interp, val, &num);
            Jsi_DSPrintf(dStr, "%g", num);
        } else if ((str = (char*)Jsi_ValueToString(interp, val, &len)) && len) {
            uchar quoted[len*2+100], *qp = quoted;
            len = dbi_conn_quote_binary_copy( cmdPtr->_db, (const uchar*)str, len, &qp );
            if( len <= 0 )
                return Jsi_LogError("quote failure in DBI_AddArgs");
            Jsi_DSAppendLen(dStr, (char*)qp, len);
            free(qp);
        } else
            Jsi_DSAppend(dStr, "null", 0);
    }
    Jsi_DSAppend(dStr, qp, 0);
    return JSI_OK;
}

static Jsi_RC DBI_IdValue(Jsi_Interp *interp, DBI_id *pss, Jsi_Value **ret, int idx)
{
    if( idx < 0 || idx >= pss->fieldCount || !pss->onrecord )
        return Jsi_LogError("index out of range");
    int fidx = pss->_fieldTypes[idx];
    char *str = NULL;

    if (dbi_result_field_is_null_idx(pss->_res, idx+1))
        Jsi_ValueMakeNull(interp, ret);
    else
        switch (fidx)
        {
            case DBI_TYPE_DATETIME:
                Jsi_ValueMakeNumber(interp, ret, dbi_result_get_datetime_idx( pss->_res, idx+1));
                break;
            case DBI_TYPE_INTEGER:
                Jsi_ValueMakeNumber(interp, ret, dbi_result_get_longlong_idx(pss->_res, idx+1 ));
                break;
            case DBI_TYPE_DECIMAL:
                Jsi_ValueMakeNumber(interp, ret, dbi_result_get_double_idx( pss->_res, idx+1 ));
                break;
            case DBI_TYPE_BINARY:
                str = (char*)dbi_result_get_binary_copy_idx( pss->_res, idx+1 );;
            case DBI_TYPE_STRING:
                if (!str) 
                    str = dbi_result_get_string_copy_idx( pss->_res, idx+1 );
                Jsi_ValueMakeBlob(interp, ret, (unsigned char *)str,
                    dbi_result_get_field_length_idx(pss->_res, idx+1));
        }

    return JSI_OK;
}


















































































































































































































































































































































































































































































































































































































































































































































































































































|







>
>







|







 







|








|
|




|

|





|










|


|


|





|






>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
..
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
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
    }
    return pss;
}

static Jsi_RC DBI_IdErase(Jsi_Interp *interp, Jsi_HashEntry* hPtr, void *ptr) {
    DBI_id *pss = (DBI_id *)ptr;
    if (pss) {
        //LogDebug("FREEPSS: %d\n", pss->id);
        pss->_hPtr = NULL;
        if (pss->_res)
            dbi_result_free(pss->_res);
        if (pss->_fieldTypes)
            Jsi_Free(pss->_fieldTypes);
        if (pss->_fieldNames)
            Jsi_Free(pss->_fieldNames);
        if (pss->sql)
            Jsi_DecrRefCount(interp, pss->sql);
        Jsi_Free(pss);
        //sockDeletePss(pss);
    }
    return JSI_OK;
}

static Jsi_RC DBI_AddArgs(DBI *cmdPtr, Jsi_DString *dStr, const char *query, int qlen, Jsi_Value *args) {
    Jsi_Interp *interp = cmdPtr->_interp;
    int n, idx, len, argc = Jsi_ValueGetLength(interp, args);
    Jsi_Value *val;
    char *str, *cp, *qp = (char*)query;
    
    while ((cp = Jsi_Strchr(qp, '%'))) {
        if (cp[1] == '%') {
            Jsi_DSAppendLen(dStr, qp, cp-qp+1);
................................................................................
            continue;
        }
        Jsi_DSAppendLen(dStr, qp, cp-qp);
        n = 0;
        while (isdigit(cp[n])) n++;
        idx = atoi(cp+1);
        qp = cp + n + 2;
        if (idx <= 0 || idx > argc || !(val = Jsi_ValueArrayIndex(interp, args, idx-1)))
            return Jsi_LogError("failure in DBI_AddArgs");

        if (Jsi_ValueIsNumber(interp, val)) {
            Jsi_Number num;
            Jsi_ValueGetNumber(interp, val, &num);
            Jsi_DSPrintf(dStr, "%g", num);
        } else if ((str = (char*)Jsi_ValueToString(interp, val, &len)) && len) {
            uchar quoted[len*2+100], *qp = quoted;
            len = dbi_conn_quote_binary_copy(cmdPtr->_db, (const uchar*)str, len, &qp);
            if (len <= 0)
                return Jsi_LogError("quote failure in DBI_AddArgs");
            Jsi_DSAppendLen(dStr, (char*)qp, len);
            free(qp);
        } else
            Jsi_DSAppend(dStr, "null", NULL);
    }
    Jsi_DSAppend(dStr, qp, NULL);
    return JSI_OK;
}

static Jsi_RC DBI_IdValue(Jsi_Interp *interp, DBI_id *pss, Jsi_Value **ret, int idx)
{
    if (idx < 0 || idx >= pss->fieldCount || !pss->onrecord)
        return Jsi_LogError("index out of range");
    int fidx = pss->_fieldTypes[idx];
    char *str = NULL;

    if (dbi_result_field_is_null_idx(pss->_res, idx+1))
        Jsi_ValueMakeNull(interp, ret);
    else
        switch (fidx)
        {
            case DBI_TYPE_DATETIME:
                Jsi_ValueMakeNumber(interp, ret, dbi_result_get_datetime_idx(pss->_res, idx+1));
                break;
            case DBI_TYPE_INTEGER:
                Jsi_ValueMakeNumber(interp, ret, dbi_result_get_longlong_idx(pss->_res, idx+1));
                break;
            case DBI_TYPE_DECIMAL:
                Jsi_ValueMakeNumber(interp, ret, dbi_result_get_double_idx( pss->_res, idx+1));
                break;
            case DBI_TYPE_BINARY:
                str = (char*)dbi_result_get_binary_copy_idx( pss->_res, idx+1 );;
            case DBI_TYPE_STRING:
                if (!str) 
                    str = dbi_result_get_string_copy_idx(pss->_res, idx+1);
                Jsi_ValueMakeBlob(interp, ret, (unsigned char *)str,
                    dbi_result_get_field_length_idx(pss->_res, idx+1));
        }

    return JSI_OK;
}

static const char jdbi_needCsvQuote[] = {
  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   
  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   
  1, 0, 1, 0, 0, 0, 0, 1,   0, 0, 0, 0, 0, 0, 0, 0, 
  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0, 
  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0, 
  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0, 
  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 0, 
  0, 0, 0, 0, 0, 0, 0, 0,   0, 0, 0, 0, 0, 0, 0, 1, 
  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   
  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   
  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   
  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   
  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   
  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   
  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   
  1, 1, 1, 1, 1, 1, 1, 1,   1, 1, 1, 1, 1, 1, 1, 1,   
};

/*
** Output a single term of CSV.  Actually, p->separator is used for
** the separator, which may or may not be a comma.  p->nullvalue is
** the null value.  Strings are quoted if necessary.
*/
static void mdbOutputCsv(DBI_query *p, const char *z, Jsi_DString *dStr, int bSep)
{
    if( z==0 ) {
        Jsi_DSAppend(dStr,  p->nullvalue?p->nullvalue:"", NULL);
    } else {
        int i;
        int nSep = Jsi_Strlen(p->separator);
        for(i=0; z[i]; i++) {
            if(jdbi_needCsvQuote[((unsigned char*)z)[i]] || 
                (z[i]==p->separator[0] && (nSep==1 || memcmp(z, p->separator, nSep)==0)) ) {
                i = 0;
                break;
            }
        }
        if( i==0 ) {
            Jsi_DSAppend(dStr, "\"", NULL);
            for(i=0; z[i]; i++) {
                if( z[i]=='"' ) Jsi_DSAppend(dStr, "\"", NULL);
                Jsi_DSAppendLen(dStr, z+i, 1);
            }
            Jsi_DSAppend(dStr, "\"", NULL);
        } else {
            Jsi_DSAppend(dStr, z, NULL);
        }
    }
    if( bSep ) {
        Jsi_DSAppend(dStr, p->separator, NULL);
    }
}

static void mdbOutputHtmlString(DBI_query *p, const char *z, Jsi_DString *dStr)
{
    while( *z ) {
        switch (*z) {
        case '<':
            Jsi_DSAppend(dStr, "&lt;", NULL);
            break;
        case '>':
            Jsi_DSAppend(dStr, "&gt;", NULL);
            break;
        case '&':
            Jsi_DSAppend(dStr, "&amp;", NULL);
            break;
        case '\"':
            Jsi_DSAppend(dStr, "&quot;", NULL);
            break;
        case '\'':
            Jsi_DSAppend(dStr, "&#39;", NULL);
            break;
        default:
            Jsi_DSAppendLen(dStr, z, 1);
            break;
        }
        z++;
    }
}

static void mdbOutputQuotedString(Jsi_DString *dStr, const char *z) {
    int i;
    int nSingle = 0;
    for(i=0; z[i]; i++) {
        if( z[i]=='\'' ) nSingle++;
    }
    if( nSingle==0 ) {
        Jsi_DSAppend(dStr,"'", z, "'", NULL);
    } else {
        Jsi_DSAppend(dStr,"'", NULL);
        while( *z ) {
            for(i=0; z[i] && z[i]!='\''; i++) {}
            if( i==0 ) {
                Jsi_DSAppend(dStr,"''", NULL);
                z++;
            } else if( z[i]=='\'' ) {
                Jsi_DSAppendLen(dStr,z, i);
                Jsi_DSAppend(dStr,"''", NULL);
                z += i+1;
            } else {
                Jsi_DSAppend(dStr, z, NULL);
                break;
            }
        }
        Jsi_DSAppend(dStr,"'", NULL);
    }
}



Jsi_RC mdbEvalStep(DBI_id *pss) {
    int ind = pss->curInd++;
    if (ind>=pss->resultCount) return JSI_BREAK;
    if (ind)
        pss->onrecord = dbi_result_seek_row(pss->_res, ind+1);
    return JSI_OK;
}

static void mdbEvalRowInfo(DBI_id *pss, int *pnCol, char ***papColName, short **papColType) {
    *papColName =pss->_fieldNames;
    *papColType = pss->_fieldTypes;
    *pnCol = pss->fieldCount;
}


static void mdbEvalSetColumnJSON(DBI_id *pss, int idx, Jsi_DString *dStr, DBI_query* optPtr) {
    Jsi_Interp *interp = pss->_cmdPtr->_interp;
    char nbuf[200];
    const char *str = NULL;
    int len, fidx = pss->_fieldTypes[idx];
    Jsi_Number num;
    switch(fidx) {
        case DBI_TYPE_BINARY:
                str = (char*)dbi_result_get_binary_idx( pss->_res, idx+1 );;
        case DBI_TYPE_STRING:
            if (!str) 
                    str = dbi_result_get_string_idx( pss->_res, idx+1 );
            len = dbi_result_get_field_length_idx(pss->_res, idx+1);
            if( !str ) {
                const char *nv = optPtr->nullvalue;
                Jsi_DSAppend(dStr, nv?nv:"null", NULL);
                return;
            }
            Jsi_JSONQuote(interp, str, len, dStr);
            break;
        case DBI_TYPE_DATETIME:
            num = dbi_result_get_datetime_idx( pss->_res, idx+1);
            Jsi_NumberToString(interp, num, nbuf, sizeof(nbuf));
            Jsi_DSAppend(dStr, nbuf, NULL);
            break;
        case DBI_TYPE_INTEGER:
            snprintf(nbuf, sizeof(nbuf), "%lld", dbi_result_get_longlong_idx(pss->_res, idx+1 ));
            Jsi_DSAppend(dStr, nbuf, NULL);
            break;
        case DBI_TYPE_DECIMAL:
            Jsi_NumberToString(interp, dbi_result_get_double_idx( pss->_res, idx+1 ), nbuf, sizeof(nbuf));
            Jsi_DSAppend(dStr, nbuf, NULL);
            break;
        default:
            Jsi_LogWarn("unknown type: %d", fidx);
    
    }
}

static void mdbEvalSetColumn(DBI_id *pss, int idx, Jsi_DString *dStr, DBI_query* optPtr) {
    Jsi_Interp *interp = pss->_cmdPtr->_interp;
    char nbuf[200];
    const char *str = NULL;
    int len, fidx = pss->_fieldTypes[idx];
    Jsi_Number num;
    switch(fidx) {
        case DBI_TYPE_BINARY:
                str = (char*)dbi_result_get_binary_idx( pss->_res, idx+1 );;
        case DBI_TYPE_STRING:
            if (!str) 
                    str = dbi_result_get_string_idx( pss->_res, idx+1 );
            len = dbi_result_get_field_length_idx(pss->_res, idx+1);
            if( !str ) {
                const char *nv = optPtr->nullvalue;
                Jsi_DSAppend(dStr, nv?nv:"null", NULL);
                return;
            }
            Jsi_DSAppendLen(dStr, str, len);
            break;
        case DBI_TYPE_DATETIME:
            num = dbi_result_get_datetime_idx( pss->_res, idx+1);
            Jsi_NumberToString(interp, num, nbuf, sizeof(nbuf));
            Jsi_DSAppend(dStr, nbuf, NULL);
            break;
        case DBI_TYPE_INTEGER:
            snprintf(nbuf, sizeof(nbuf), "%lld", dbi_result_get_longlong_idx(pss->_res, idx+1 ));
            Jsi_DSAppend(dStr, nbuf, NULL);
            break;
        case DBI_TYPE_DECIMAL:
            Jsi_NumberToString(interp, dbi_result_get_double_idx( pss->_res, idx+1 ), nbuf, sizeof(nbuf));
            Jsi_DSAppend(dStr, nbuf, NULL);
            break;
        default:
            Jsi_LogWarn("unknown type: %d", fidx);
    
    }
}

#if 1
static Jsi_RC mdbEvalCallCmd(DBI_id *pss, Jsi_Interp *interp, Jsi_RC result, DBI_query* optPtr, Jsi_Value *callback)
{
    int cnt = 0;
    Jsi_RC rc = result;
    Jsi_Value *varg1;
    Jsi_Obj *argso;
    char **apColName = NULL;
    short *apColType = NULL;
    //if (p->jdb->debug & mdbTMODE_EVAL)
    //    JSI_DBQUERY_PRINTF( "DEBUG: eval\n");

    while( (rc==JSI_OK) && JSI_OK==(rc = mdbEvalStep(pss)) ) {
        int i;
        int nCol;

        cnt++;
        mdbEvalRowInfo(pss, &nCol, &apColName, &apColType);
        if (nCol<=0)
            continue;
        if (Jsi_ValueIsNull(interp, callback))
            continue;
        /* Single object containing sql result members. */
        varg1 = Jsi_ValueMakeObject(interp, NULL, argso = Jsi_ObjNew(interp));
        for(i=0; i<nCol; i++) {
            Jsi_Value *vcur = Jsi_ValueNew(interp);
            rc = DBI_IdValue(interp, pss, &vcur, i);
            //Jsi_Value *nnv = dbi EvalSetColumnValue(p, i, NULL);
            Jsi_ObjInsert(interp, argso, apColName[i], vcur, 0);
        }
        Jsi_IncrRefCount(interp, varg1);
        bool rb = Jsi_FunctionInvokeBool(interp, callback, varg1);
        if (Jsi_InterpGone(interp))
            return JSI_ERROR;
        Jsi_DecrRefCount(interp, varg1);
        if (rb)
            break;
    }
    //mdbEvalFinalize(p);

    if( rc==JSI_OK || rc==JSI_BREAK ) {
        //Jsi_ResetResult(interp);
        rc = JSI_OK;
    }
    return rc;
}

#endif

static Jsi_RC DbiQueryCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,
     Jsi_Value **ret, Jsi_Func *funcPtr, DBI_id *pss, DBI_query* qopts, bool modeor)
{
    Jsi_RC rc = JSI_OK;
    DBI* cmdPtr = pss->_cmdPtr;
    Jsi_DString eStr = {};
    JSI_DSTRING_VAR(dStr, 8192);
    int cnt = 0;
    char **apColName = NULL;
    short *apColType = NULL;
    DBI_query opts, *optPtr = &opts, *copts = &cmdPtr->queryOpts;
    opts = *qopts;
    if (qopts != copts) {
#define JDBI_OOPTS(n) if (!opts.n) opts.n = copts->n
        JDBI_OOPTS(callback);
        JDBI_OOPTS(widths);
        JDBI_OOPTS(headers);
        JDBI_OOPTS(limit);
        JDBI_OOPTS(nullvalue);
        JDBI_OOPTS(separator);
        if (!modeor)
            JDBI_OOPTS(mode);
    }
        
    //optPtr->callback = NULL;
    //optPtr->width = NULL;
    Jsi_Value *callback = optPtr->callback, *width = optPtr->widths;
            
#if 0
    if (arg) {
        if (Jsi_ValueIsNull(interp,arg)) {
        } else if (Jsi_ValueIsFunction(interp,arg)) {
            callback = optPtr->callback = arg;
        } else if (Jsi_ValueIsObjType(interp, arg, JSI_OT_OBJECT)) {
            isopts = 1;
        } else 
            return Jsi_LogError("argument must be null, a function, or options");
    }

    if (isopts) {
        if (Jsi_OptionsProcess(interp, QueryFmtOptions, &opts, arg, 0) < 0)
            return JSI_ERROR;
        callback = (optPtr->callback ? optPtr->callback : jdb->queryOpts.callback);
        width = (optPtr->width ? optPtr->width : jdb->queryOpts.width);
    }
/*    if (jdb->queryOpts.CData) {
        char *cdata = (char*)jdb->queryOpts.CData;
        MySqlObjMultipleBind* copts = Jsi_CarrayLookup(interp, cdata);
        if (!copts) 
            return Jsi_LogError("unknown CData option: %s", jdb->queryOpts.CData);
        int n = MySqlObjQuery(jdb, copts->opts, copts->data, copts->numData, zSql, copts->flags);
        Jsi_ValueMakeNumber(interp, ret, (Jsi_Number)n);
        return JSI_OK;
    } */

    Jsi_DString sStr;
    Jsi_DSInit(&sStr);
    sEval.nocache = optPtr->nocache;
    if (mdbEvalInit(interp, &sEval, jdb, zSql, &sStr, 0, 0) != JSI_OK) {
        rc = JSI_ERROR;
        goto bail;
    }
    sEval.namedParams = (optPtr->noNamedParams==0 && !optPtr->values);
    sEval.ret = *ret;
    oEopt = jdb->optPtr;
    jdb->optPtr = &opts;
    
    if (sEval.namedParams) {
        rc = mdbEvalPrep(&sEval);
        if (rc == JSI_ERROR)
            goto bail;
        if (rc == JSI_BREAK) {
            rc = JSI_OK;
            goto bail;
        }
    }
#endif
    if (!optPtr->separator) {
        switch (optPtr->mode) {
            case list: optPtr->separator = "|"; break;
            case column: optPtr->separator = " "; break;
            case tabs: optPtr->separator = "\t"; break;
            default: optPtr->separator = ",";
        }
    }

    if (callback) {
        if (optPtr->mode != rows)
            rc = Jsi_LogError("'mode' must be 'rows' with 'callback'");
        else 
            rc = mdbEvalCallCmd(pss, interp, JSI_OK, optPtr, callback);
        goto bail;
    }
    switch (optPtr->mode) {
        case cursor:
            goto bail;
        case none:
            goto bail;
            break;
        case rows:
        {
            Jsi_Value *vcur, *vrow;
            int cnt = 0;
            Jsi_Obj *oall, *ocur;
            Jsi_ValueMakeArrayObject(interp, ret, oall = Jsi_ObjNewType(interp, JSI_OT_ARRAY));
    
            while( JSI_OK==(rc = mdbEvalStep(pss)) ) {
                int i;
                int nCol;
                mdbEvalRowInfo(pss, &nCol, &apColName, &apColType);
                ocur = Jsi_ObjNewType(interp, JSI_OT_OBJECT);
                vrow = Jsi_ValueMakeObject(interp, NULL, ocur);
                for(i=0; i<nCol && rc==JSI_OK; i++) {
                    vcur = Jsi_ValueNew(interp);
                    rc = DBI_IdValue(interp, pss, &vcur, i);
                    //vcur = dbiEvalSetColumnValue(pss, i, NULL);
                    Jsi_ObjInsert(interp, ocur, apColName[i], vcur, 0);
                }
                Jsi_ObjArrayAdd(interp, oall, vrow);
                cnt++;
                if (optPtr->limit && cnt>=optPtr->limit) break;
            }
            //mdbEvalFinalize(&sEval);
            if (rc != JSI_ERROR)
                rc = JSI_OK;
            goto bail;
            break;
        }
        case json:
            if (optPtr->headers) {
                Jsi_DSAppend(dStr, "[ ", NULL);
                while( JSI_OK==(rc = mdbEvalStep(pss)) ) {
                    int i;
                    int nCol;
                    mdbEvalRowInfo(pss, &nCol, &apColName, &apColType);
                    if (cnt == 0) {
                        Jsi_DSAppend(dStr, "[", NULL);
                        for(i=0; i<nCol; i++) {
                            if (i)
                                Jsi_DSAppend(dStr, ", ", NULL);
                            Jsi_JSONQuote(interp, apColName[i], -1, dStr);
                        }
                        Jsi_DSAppend(dStr, "]", NULL);
                        cnt++;
                    }
                    if (cnt)
                        Jsi_DSAppend(dStr, ", ", NULL);
                    Jsi_DSAppend(dStr, "[", NULL);
                    for(i=0; i<nCol; i++) {
                        if (i)
                            Jsi_DSAppend(dStr, ", ", NULL);
                        mdbEvalSetColumnJSON(pss, i, dStr, optPtr);
                    }
                    Jsi_DSAppend(dStr, "]", NULL);
                    cnt++;
                    if (optPtr->limit && cnt>optPtr->limit) break;
                }
                Jsi_DSAppend(dStr, " ]", NULL);
                
            } else {
                Jsi_DSAppend(dStr, "[ ", NULL);
                while( JSI_OK==(rc = mdbEvalStep(pss)) ) {
                    int i;
                    int nCol;
                    mdbEvalRowInfo(pss, &nCol, &apColName, &apColType);
                    if (cnt)
                        Jsi_DSAppend(dStr, ", ", NULL);
                    Jsi_DSAppend(dStr, "{", NULL);
                    for(i=0; i<nCol; i++) {
                        if (i)
                            Jsi_DSAppend(dStr, ", ", NULL);
                        Jsi_JSONQuote(interp, apColName[i], -1, dStr);
                        Jsi_DSAppend(dStr, ":", NULL);
                        mdbEvalSetColumnJSON(pss, i, dStr, optPtr);
                    }
                    Jsi_DSAppend(dStr, "}", NULL);
                    cnt++;
                    if (optPtr->limit && cnt>=optPtr->limit) break;
                }
                Jsi_DSAppend(dStr, " ]", NULL);
            }
            break;
            
        case json2: {
                while( JSI_OK==(rc = mdbEvalStep(pss)) ) {
                    int i;
                    int nCol;
                    mdbEvalRowInfo(pss, &nCol, &apColName, &apColType);
                    if (cnt == 0 && 1) {
                        Jsi_DSAppend(dStr, "{ \"names\": [ ", NULL);
                        for(i=0; i<nCol; i++) {
                            if (i)
                                Jsi_DSAppend(dStr, ", ", NULL);
                            Jsi_JSONQuote(interp, apColName[i], -1, dStr);
                        }
                        Jsi_DSAppend(dStr, " ], \"values\": [ ", NULL);
                    }
                    if (cnt)
                        Jsi_DSAppend(dStr, ", ", NULL);
                    Jsi_DSAppend(dStr, "[", NULL);
                    for(i=0; i<nCol; i++) {
                        if (i)
                            Jsi_DSAppend(dStr, ", ", NULL);
                        mdbEvalSetColumnJSON(pss, i, dStr, optPtr);
                    }
                    Jsi_DSAppend(dStr, " ]", NULL);
                    cnt++;
                    if (optPtr->limit && cnt>=optPtr->limit) break;
                }
                if (cnt)
                    Jsi_DSAppend(dStr, " ] } ", NULL);
            }
            break;
            
        case list:
            while( JSI_OK==(rc = mdbEvalStep(pss)) ) {
                int i;
                int nCol;
                mdbEvalRowInfo(pss, &nCol, &apColName, &apColType);
                if (cnt == 0 && optPtr->headers) {
                    for(i=0; i<nCol; i++) {
                        if (i)
                            Jsi_DSAppend(dStr, optPtr->separator, NULL);
                        Jsi_DSAppend(dStr, apColName[i], NULL);
                    }
                }
    
                if (cnt || optPtr->headers)
                    Jsi_DSAppend(dStr, "\n", NULL);
                for(i=0; i<nCol; i++) {
                    if (i)
                        Jsi_DSAppend(dStr, optPtr->separator, NULL);
                    mdbEvalSetColumn(pss, i, dStr, optPtr);
                }
                cnt++;
                if (optPtr->limit && cnt>=optPtr->limit) break;
            }
            break;
            
        case column: {
            int *wids = NULL;
            Jsi_DString vStr = {};
            while( JSI_OK==(rc = mdbEvalStep(pss)) ) {
                int i, w;
                int nCol;
                
                mdbEvalRowInfo(pss, &nCol, &apColName, &apColType);
                if (cnt == 0 && nCol>0) {
                    Jsi_DString sStr;
                    wids = (int*)Jsi_Calloc(nCol, sizeof(int));
                    Jsi_DSInit(&sStr);
                    for(i=0; i<nCol; i++) {
                        int j = Jsi_Strlen(apColName[i]);
                        wids[i] = (j<10?10:j);
                        if (width) {
                            Jsi_Value *wv = Jsi_ValueArrayIndex(interp, width, i);
                            if (wv) {
                                Jsi_Number dv;
                                Jsi_ValueGetNumber(interp, wv, &dv);
                                if (dv>0)
                                    wids[i] = (int)dv;
                            }
                        }
                        w = (j<wids[i] ? j : wids[i]);
                        Jsi_DSAppendLen(dStr, apColName[i], w);
                        w = (j<wids[i] ? wids[i]-j+1 : 0);
                        while (w-- > 0)
                            Jsi_DSAppend(dStr, " ", NULL);
                    }
                    for(i=0; i<nCol && optPtr->headers; i++) {
                        w = wids[i];
                        w -= Jsi_Strlen(apColName[i]);
                        if (i) {
                            Jsi_DSAppend(dStr, optPtr->separator, NULL);
                            Jsi_DSAppend(&sStr, optPtr->separator, NULL);
                        }
                        w = wids[i];
                        while (w-- > 0)
                            Jsi_DSAppend(&sStr, "-", NULL);
                    }
                    if (optPtr->headers)
                        Jsi_DSAppend(dStr, "\n", Jsi_DSValue(&sStr), "\n", NULL);
                    Jsi_DSFree(&sStr);
                }
    
                if (cnt)
                    Jsi_DSAppend(dStr, "\n", NULL);
                for(i=0; i<nCol; i++) {
                    if (i)
                        Jsi_DSAppend(dStr, optPtr->separator, NULL);
                    Jsi_DSSetLength(&vStr, 0);
                    mdbEvalSetColumn(pss, i, &vStr, optPtr);
                    int nl = Jsi_DSLength(&vStr);
                    if (nl > wids[i]) {
                        Jsi_DSSetLength(&vStr, wids[i]);
                        w = 0;
                    } else {
                        w = wids[i]-nl;
                    }
                    Jsi_DSAppend(dStr, Jsi_DSValue(&vStr), NULL);
                    while (w-- > 0)
                        Jsi_DSAppend(dStr, " ", NULL);
                }
                cnt++;
                if (optPtr->limit && cnt>=optPtr->limit) break;
            }
            Jsi_DSFree(&vStr);
            if (wids)
                Jsi_Free(wids);
            break;
        }
        
        case insert: {
            Jsi_DString vStr = {};    
            while( JSI_OK==(rc = mdbEvalStep(pss)) ) {
                int i;
                int nCol;
                const char *tbl = (optPtr->table ? optPtr->table : "table");
                if (cnt)
                    Jsi_DSAppend(dStr, "\n", NULL);
                Jsi_DSAppend(dStr, "INSERT INTO ", tbl, " VALUES(", NULL);
                mdbEvalRowInfo(pss, &nCol, &apColName, &apColType);
                for(i=0; i<nCol; i++) {
                    Jsi_Number dv;
                    const char *azArg;
                    Jsi_DSSetLength(&vStr, 0);
                    mdbEvalSetColumn(pss, i, &vStr, optPtr);
                    
                    int ptype = pss->_fieldTypes[i];
                    
                    azArg = Jsi_DSValue(&vStr);
                    const char *zSep = i>0 ? ",": "";
                    if (azArg[i]==0 && ptype != JSI_OPTION_STRING) {
                      Jsi_DSAppend(dStr, zSep, "NULL", NULL);
                    } else if( ptype == DBI_TYPE_STRING) {
                      if( zSep[0] ) Jsi_DSAppend(dStr,zSep, NULL);
                      mdbOutputQuotedString(dStr, azArg);
                    } else if ( ptype ==DBI_TYPE_DECIMAL) {
                      Jsi_DSAppend(dStr, zSep, azArg, NULL);
                    } else if( Jsi_GetDouble(interp, azArg, &dv) == JSI_OK ) {
                      Jsi_DSAppend(dStr, zSep, azArg, NULL);
                    } else {
                      if( zSep[0] ) Jsi_DSAppend(dStr,zSep, NULL);
                      mdbOutputQuotedString(dStr, azArg);
                    }
                }
                Jsi_DSAppend(dStr, ");", NULL);
                cnt++;
                if (optPtr->limit && cnt>=optPtr->limit) break;
            }
            Jsi_DSFree(&vStr);
        }
    
        case tabs:
        case csv: {
            Jsi_DString vStr = {};  
            while( JSI_OK==(rc = mdbEvalStep(pss)) ) {
                int i;
                int nCol;
                mdbEvalRowInfo(pss, &nCol, &apColName, &apColType);
                if (cnt == 0 && optPtr->headers) {
                    for(i=0; i<nCol; i++) {
                        if (i)
                            Jsi_DSAppend(dStr, optPtr->separator, NULL);
                        Jsi_DSAppend(dStr, apColName[i], NULL);
                    }
                }
    
                if (cnt || optPtr->headers)
                    Jsi_DSAppend(dStr, "\n", NULL);
                for(i=0; i<nCol; i++) {
                    if (i)
                        Jsi_DSAppend(dStr, optPtr->separator, NULL);
                    Jsi_DSSetLength(&vStr, 0);
                    mdbEvalSetColumn(pss, i, &vStr, optPtr);
                    if (optPtr->mode == csv)
                        mdbOutputCsv(optPtr, Jsi_DSValue(&vStr), dStr, 0);
                    else
                        Jsi_DSAppend(dStr, Jsi_DSValue(&vStr), NULL);
                }
                cnt++;
                if (optPtr->limit && cnt>=optPtr->limit) break;
            }
            Jsi_DSFree(&vStr);
            break;
        }
            
        case line: {
            int i, w = 5, ww;
            int nCol;
            Jsi_DString vStr = {};   
            while( JSI_OK==(rc = mdbEvalStep(pss)) ) {
                mdbEvalRowInfo(pss, &nCol, &apColName, &apColType);
                if (cnt == 0) {
                    for(i=0; i<nCol; i++) {
                        ww = Jsi_Strlen(apColName[i]);
                        if (ww>w)
                            w = ww;
                    }
                }
    
                for(i=0; i<nCol; i++) {
                    Jsi_DString eStr;
                    Jsi_DSInit(&eStr);
                    Jsi_DSSetLength(&vStr, 0);
                    mdbEvalSetColumn(pss, i, &vStr, optPtr);
                    Jsi_DSPrintf(&eStr, "%*s = %s", w, apColName[i], Jsi_DSValue(&vStr));
                    Jsi_DSAppend(dStr, (cnt?"\n":""), Jsi_DSValue(&eStr), NULL);
                    Jsi_DSFree(&eStr);
                }
                cnt++;
                if (optPtr->limit && cnt>=optPtr->limit) break;
            }
            Jsi_DSFree(&vStr);
            break;
        }

        case html: {
            Jsi_DString vStr = {};   
            while( JSI_OK==(rc = mdbEvalStep(pss)) ) {
                int i;
                int nCol;
                mdbEvalRowInfo(pss, &nCol, &apColName, &apColType);
                if (cnt == 0 && optPtr->headers) {
                    Jsi_DSAppend(dStr, "<TR>", NULL);
                    for(i=0; i<nCol; i++) {
                        Jsi_DSAppend(dStr, "<TH>", NULL);
                        mdbOutputHtmlString(optPtr, apColName[i], dStr);
                        Jsi_DSAppend(dStr, "</TH>", NULL);
                    }
                    Jsi_DSAppend(dStr, "</TR>", NULL);
                }
                if (cnt || optPtr->headers)
                    Jsi_DSAppend(dStr, "\n", NULL);
                Jsi_DSAppend(dStr, "<TR>", NULL);
                for(i=0; i<nCol; i++) {
                    Jsi_DSAppend(dStr, "<TD>", NULL);
                    Jsi_DSSetLength(&vStr, 0);
                    mdbEvalSetColumn(pss, i, &vStr, optPtr);
                    mdbOutputHtmlString(optPtr, Jsi_DSValue(&vStr), dStr);
                    Jsi_DSAppend(dStr, "</TD>", NULL);
                }
                Jsi_DSAppend(dStr, "</TR>", NULL);
                cnt++;
                if (optPtr->limit && cnt>=optPtr->limit) break;
            }
            Jsi_DSFree(&vStr);
            break;
        }

        case arrays:
        {
            Jsi_Value *vcur, *vrow;
            int cnt = 0;
            Jsi_Obj *oall, *ocur;
            Jsi_ValueMakeArrayObject(interp, ret, oall = Jsi_ObjNewType(interp, JSI_OT_ARRAY));
    
            while( JSI_OK==(rc = mdbEvalStep(pss)) ) {
                int i;
                int nCol;
                mdbEvalRowInfo(pss, &nCol, &apColName, &apColType);
                if (cnt == 0 && optPtr->headers) {
                    vrow = Jsi_ValueMakeArrayObject(interp, NULL, ocur = Jsi_ObjNewType(interp, JSI_OT_ARRAY));
                    for(i=0; i<nCol; i++) {
                        vcur = Jsi_ValueNewStringDup(interp, apColName[i]);
                        Jsi_ObjArrayAdd(interp, ocur, vcur);
                    }
                    Jsi_ObjArrayAdd(interp, oall, vrow);
                }
                vrow = Jsi_ValueMakeArrayObject(interp, NULL, ocur = Jsi_ObjNewType(interp, JSI_OT_ARRAY));
                for(i=0; i<nCol && rc==JSI_OK; i++) {
                    vcur = Jsi_ValueNew(interp);
                    rc = DBI_IdValue(interp, pss, &vcur, i);
                    //vcur = dbiEvalSetColumnValue(pss, i, NULL);
                    Jsi_ObjArrayAdd(interp, ocur, vcur);
                }
                Jsi_ObjArrayAdd(interp, oall, vrow);
                cnt++;
                if (optPtr->limit && cnt>=optPtr->limit) break;
            }
            //mdbEvalFinalize(&sEval);
            if (rc != JSI_ERROR)
                rc = JSI_OK;
            goto bail;
            break;
        }
        case array1d:
        {
            Jsi_Value *vcur;
            int cnt = 0;
            Jsi_Obj *oall;
            Jsi_ValueMakeArrayObject(interp, ret, oall = Jsi_ObjNewType(interp, JSI_OT_ARRAY));
    
            while( JSI_OK==(rc = mdbEvalStep(pss)) ) {
                int i;
                int nCol;
                mdbEvalRowInfo(pss, &nCol, &apColName, &apColType);
                if (cnt == 0 && optPtr->headers) {
                    for(i=0; i<nCol; i++) {
                        vcur = Jsi_ValueNewStringDup(interp, apColName[i]);
                        Jsi_ObjArrayAdd(interp, oall, vcur);
                    }
                }
                for(i=0; i<nCol && rc==JSI_OK; i++) {
                    vcur = Jsi_ValueNew(interp);
                    rc = DBI_IdValue(interp, pss, &vcur, i);
                    //vcur = dbiEvalSetColumnValue(pss, i, NULL);
                    Jsi_ObjArrayAdd(interp, oall, vcur);
                }
                cnt++;
                if (optPtr->limit && cnt>=optPtr->limit) break;
            }
            //mdbEvalFinalize(&sEval);
            if (rc != JSI_ERROR)
                rc = JSI_OK;
            goto bail;
            break;
        }
    }
    if( rc==JSI_BREAK ) {
        rc = JSI_OK;
    }
    Jsi_ValueMakeStringDup(interp, ret, Jsi_DSValue(dStr));
bail:
   /* //mdbEvalFinalize(&sEval);
    if (isopts) {
        Jsi_OptionsFree(interp, QueryFmtOptions, &opts, 0);
    }*/
    Jsi_DSFree(dStr);
    Jsi_DSFree(&eStr);
    //jdb->optPtr = oEopt;

    return rc;
}


static DBI_id* DbiQueryNew(Jsi_Interp *interp, DBI* cmdPtr, dbi_result res)
{
    DBI_id *pss = DBI_IdGet(cmdPtr, -1, true);
    if (!pss) {
        dbi_result_free(res);
        return NULL;
    }
    pss->onrecord = dbi_result_first_row(res);
    pss->resultCount = dbi_result_get_numrows(res);
    pss->fieldCount = dbi_result_get_numfields(res);
    pss->_fieldTypes = (short*)Jsi_Calloc( pss->fieldCount, sizeof(unsigned short) );
    pss->_fieldNames = (char**)Jsi_Calloc( pss->fieldCount, sizeof(char *) );
    for (int x=0; x < pss->fieldCount; x++) {
        const char *fieldname = dbi_result_get_field_name(res, x+1);
        pss->_fieldTypes[x] = dbi_result_get_field_type_idx(res, x+1);
        pss->_fieldNames[x] = (char*)Jsi_KeyAdd(interp, fieldname);
    }

    pss->_res = res;
    return pss;
}

Changes to DBI/Makefile.

1
2
3
4
5
6
7
8
9
10
11





12
13
14
15
16
CDCMD=../jsish -c
#CDCMD=../jsish ../lib/Jsi_CData.jsi
CDOPTS= -noline true
#CC=cc -fsanitize=address 

DBI.so: DBI.c
	$(CC)  `$(CDCMD) -cflags true DBI.so` -ldbi

DBI.c: DBI.jsc DBIinc.c
	$(CDCMD) $(CDOPTS)  DBI.jsc






test:
	../jsish --U dbi_mysql.jsi

clean:
	rm -f DBI.c DBI.so DBI DBIsh


|








>
>
>
>
>





1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
CDCMD=../jsish -c
#CDCMD=../jsish ../lib/Jsi_CData.jsi
#CDOPTS= -noline true
#CC=cc -fsanitize=address 

DBI.so: DBI.c
	$(CC)  `$(CDCMD) -cflags true DBI.so` -ldbi

DBI.c: DBI.jsc DBIinc.c
	$(CDCMD) $(CDOPTS)  DBI.jsc

DBIsh: DBI.c
	$(CC)  `$(CDCMD) -cflags true DBI` -ldbi
	rm -f DBIsh
	jsish -z zvfs DBI

test:
	../jsish --U dbi_mysql.jsi

clean:
	rm -f DBI.c DBI.so DBI DBIsh

Changes to DBI/dbi_mysql.jsi.

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
#!/usr/bin/env jsish

require('DBI');

var opts = { driver:'mysql', username:'jsish', password:'abc', dbname:'jsitest', host:'localhost', port:3306  }; 
//var opts = { driver:'sqlite', dbname:'test2.db', sqlite_dbdir:'/tmp' }; 






var id, db = new DBI(opts);








;db.open();


;db.check();
;db.conf();




;id = db.query('SELECT * FROM test1;', {mode:'id'});
;db.idconf(id);
;db.column(id,0);
;db.row(id);

;id = db.query('SELECT * FROM test1 WHERE last=%1;', {params:['Box'], mode:'id'});
;db.ids();
;db.idconf(id);


;db.row(id);
;db.seek(id,3);
;db.row(id);
;db.free(id);














;db.query('SELECT * FROM test1 WHERE last=%1;', {params:['Box'], mode:'rows'});


;' --- FAIL TESTS ---- ';
;// db.conf({driver:'sqlite'});
;// db.conf({isopen:false});
;//db.query('SELECT * FROM test1;', {params:['Box'], qag:9});
;//db.query('SELECT * FROM test1;', {bag:9});
;//db.query('SELECT * FROM test1;', {mode:'xx'});

delete db;


/*
=!EXPECTSTART!=
db.open() ==> true











db.check() ==> true
db.conf() ==> { callback:null, dbname:"jsitest", driver:"mysql", drvOpts:null, encoding:null, host:"localhost", isopen:true, password:"abc", port:3306, sqlite_dbdir:null, sqlite_timeout:0, timeout:0, username:"jsish", version:900 }










































































db.conf({driver:'sqlite'}) ==>
PASS!: err = Error can not update option: "driver"
db.conf({isopen:false}) ==>
PASS!: err = Error option is readonly: "isopen"



id = db.query('SELECT * FROM test1;') ==> 1
db.idconf(id) ==> { fieldCount:3, id:1, onrecord:true, resultCount:26 }
db.column(id,0) ==> 44
db.row(id) ==> { id:44, last:"Box", name:"Barry" }

id = db.query('SELECT * FROM test1 WHERE last=%1;', ['Box']) ==> 2
db.ids() ==> { 1:2 }
db.idconf(id) ==> { fieldCount:3, id:2, onrecord:true, resultCount:26 }
db.row(id) ==> { id:44, last:"Box", name:"Barry" }
db.seek(id,3) ==> true
db.row(id) ==> { id:44, last:"Box", name:"Barry" }
db.free(id) ==> undefined

=!EXPECTEND!=
*/
|



|
|
>

>
>
>
>
|
>
>
>
>
>
>
>
>
|
>
>


>

>

|




|
<

>
>

|



>
>
>
>
>
>
>
>
>
>
>
>
>
|

>
|


|
|
|


>



<
>
>
>
>
>
>
>
>
>
>
>

|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>



<
>
>
>
|
<
<
<
>
|
<
<
<
<
<
<
>


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
#!/usr/local/bin/jsish --U %s

require('DBI');

var opts = { driver:'mysql', username:'jsish', password:'abc', host:'localhost', port:3306  }; 
//Seems sqlite does not work on Ubuntu.
//var opts = { driver:'sqlite3', dbname:'test3.db', sqlite_dbdir:'/tmp', verbosity:255 };

var id, modes, db;

;'\n';
;'  ==== Dump databases  ====   ';
;db = new DBI(opts);
;db.databases();
delete db;

;opts.dbname='jsitest';
;db = new DBI(opts);

;db.databases();
;db.tables();
;db.options();
;db.driver();

;db.check();
;db.conf();
;db.conf({queryOpts:{limit:4}});

;db.query('SELECT * FROM test3;');

;id = db.query('SELECT * FROM test3;', {mode:'cursor'});
;db.idconf(id);
;db.column(id,0);
;db.row(id);

;id = db.query('SELECT * FROM test3 WHERE last=%1;', {values:['Fax'], mode:'cursor'});

;db.idconf(id);
;db.ids();
;db.seek(id,0);
;db.row(id);
;db.seek(id,1);
;db.row(id);
;db.free(id);

;'\n';
;'   ==== OUTPUT MODES ====   ';
;modes = CEnum.names('DBI_mode');
for (var mode of modes) {
   if (mode=='cursor') continue;
;'  ===================  ';
;   mode;
;   db.query('SELECT * FROM test3 WHERE last=%1;', {values:['Fax'], mode:mode, limit:5});
}

;'\n';
;'   ==== FORCE BACK TO rows (0) ====   ';
;db.conf({queryOpts:{mode:'list'}});
;db.query('SELECT * FROM test3 WHERE last=%1;', {values:['Fax'], mode:'row'});

;'\n';
;'   ==== FAIL TESTS ====   ';
;// db.conf({driver:'sqlite'});
;// db.conf({isopen:false});
;//db.query('SELECT * FROM test3;', {values:['Box'], qag:9});
;//db.query('SELECT * FROM test3;', {bag:9});
;//db.query('SELECT * FROM test3;', {mode:'xx'});

delete db;
return;

/*
=!EXPECTSTART!=

'
'
'  ==== Dump databases  ====   '
db = new DBI(opts) ==> "#DBI_1"
db.databases() ==> [ "jsitest" ]
opts.dbname='jsitest' ==> jsitest
db = new DBI(opts) ==> "#DBI_2"
db.databases() ==> [ "jsitest" ]
db.tables() ==> [ "test1", "test2", "test3", "xx" ]
db.options() ==> [ "username", "password", "dbname", "host", "port" ]
db.driver() ==> { date_compiled:"Apr 12 2016", description:"MySQL database support (using libmysqlclient)", file:"/usr/lib/x86_64-linux-gnu/dbd/libdbdmysql.so", maintainer:"Mark M. Tobenkin <mark@brentwoodradio.com>", name:"mysql", url:"http://libdbi-drivers.sourceforge.net", version:"dbd_mysql v0.9.0" }
db.check() ==> true
db.conf() ==> { callback:null, dbname:"jsitest", driver:"mysql", drvOpts:null, encoding:"ISO-8859-1", engineVersion:0, host:"localhost", isSqlite:false, password:"abc", port:3306, queryOpts:{ callback:null, headers:false, limit:0, mode:"rows", nullvalue:null, separator:null, table:null, values:null, widths:null }, socket:5, sqlite_dbdir:null, sqlite_timeout:0, timeout:0, username:"jsish", verbosity:0, version:900 }
db.conf({queryOpts:{limit:4}}) ==> undefined
db.query('SELECT * FROM test3;') ==> [ { dat:28801, last:"Fax", name:"Furry" }, { dat:28801, last:"Fax", name:"Figgy" }, { dat:0, last:"b", name:"a" }, { dat:0, last:"d", name:"c" } ]
id = db.query('SELECT * FROM test3;', {mode:'cursor'}) ==> 4
db.idconf(id) ==> { curInd:0, fieldCount:3, id:4, onrecord:true, resultCount:5, sql:"SELECT * FROM test3;" }
db.column(id,0) ==> 28801
db.row(id) ==> { dat:28801, last:"Fax", name:"Furry" }
id = db.query('SELECT * FROM test3 WHERE last=%1;', {values:['Fax'], mode:'cursor'}) ==> 5
db.idconf(id) ==> { curInd:0, fieldCount:3, id:5, onrecord:true, resultCount:2, sql:"SELECT * FROM test3 WHERE last=\'Fax\';" }
db.ids() ==> [ 4, 5, 1, 2 ]
db.seek(id,0) ==> true
db.row(id) ==> { dat:28801, last:"Fax", name:"Furry" }
db.seek(id,1) ==> true
db.row(id) ==> { dat:28801, last:"Fax", name:"Figgy" }
db.free(id) ==> undefined
'
'
'   ==== OUTPUT MODES ====   '
modes = CEnum.names('DBI_mode') ==> [ "rows", "arrays", "array1d", "list", "column", "json", "json2", "html", "csv", "insert", "line", "tabs", "cursor", "none" ]
'  ===================  '
mode ==> rows
db.query('SELECT * FROM test3 WHERE last=%1;', {values:['Fax'], mode:mode, limit:5}) ==> [ { dat:28801, last:"Fax", name:"Furry" }, { dat:28801, last:"Fax", name:"Figgy" } ]
'  ===================  '
mode ==> arrays
db.query('SELECT * FROM test3 WHERE last=%1;', {values:['Fax'], mode:mode, limit:5}) ==> [ [ 28801, "Furry", "Fax" ], [ 28801, "Figgy", "Fax" ] ]
'  ===================  '
mode ==> array1d
db.query('SELECT * FROM test3 WHERE last=%1;', {values:['Fax'], mode:mode, limit:5}) ==> [ 28801, "Furry", "Fax", 28801, "Figgy", "Fax" ]
'  ===================  '
mode ==> list
db.query('SELECT * FROM test3 WHERE last=%1;', {values:['Fax'], mode:mode, limit:5}) ==> 28801|Furry|Fax
28801|Figgy|Fax
'  ===================  '
mode ==> column
db.query('SELECT * FROM test3 WHERE last=%1;', {values:['Fax'], mode:mode, limit:5}) ==> dat        name       last       28801      Furry      Fax       
28801      Figgy      Fax       
'  ===================  '
mode ==> json
db.query('SELECT * FROM test3 WHERE last=%1;', {values:['Fax'], mode:mode, limit:5}) ==> [ {"dat":28801, "name":"Furry", "last":"Fax"}, {"dat":28801, "name":"Figgy", "last":"Fax"} ]
'  ===================  '
mode ==> json2
db.query('SELECT * FROM test3 WHERE last=%1;', {values:['Fax'], mode:mode, limit:5}) ==> { "names": [ "dat", "name", "last" ], "values": [ [28801, "Furry", "Fax" ], [28801, "Figgy", "Fax" ] ] } 
'  ===================  '
mode ==> html
db.query('SELECT * FROM test3 WHERE last=%1;', {values:['Fax'], mode:mode, limit:5}) ==> <TR><TD>28801</TD><TD>Furry</TD><TD>Fax</TD></TR>
<TR><TD>28801</TD><TD>Figgy</TD><TD>Fax</TD></TR>
'  ===================  '
mode ==> csv
db.query('SELECT * FROM test3 WHERE last=%1;', {values:['Fax'], mode:mode, limit:5}) ==> 28801,Furry,Fax
28801,Figgy,Fax
'  ===================  '
mode ==> insert
db.query('SELECT * FROM test3 WHERE last=%1;', {values:['Fax'], mode:mode, limit:5}) ==> INSERT INTO table VALUES(28801,'Furry','Fax');
INSERT INTO table VALUES(28801,'Figgy','Fax');
'  ===================  '
mode ==> line
db.query('SELECT * FROM test3 WHERE last=%1;', {values:['Fax'], mode:mode, limit:5}) ==>   dat = 28801 name = Furry last = Fax
  dat = 28801
 name = Figgy
 last = Fax
'  ===================  '
mode ==> tabs
db.query('SELECT * FROM test3 WHERE last=%1;', {values:['Fax'], mode:mode, limit:5}) ==> 28801	Furry	Fax
28801	Figgy	Fax
'  ===================  '
mode ==> none
db.query('SELECT * FROM test3 WHERE last=%1;', {values:['Fax'], mode:mode, limit:5}) ==> undefined
'
'
'   ==== FORCE BACK TO rows (0) ====   '
db.conf({queryOpts:{mode:'list'}}) ==> undefined
db.query('SELECT * FROM test3 WHERE last=%1;', {values:['Fax'], mode:'row'}) ==> [ { dat:28801, last:"Fax", name:"Furry" }, { dat:28801, last:"Fax", name:"Figgy" } ]
'
'
'   ==== FAIL TESTS ====   '
db.conf({driver:'sqlite'}) ==>
PASS!: err = Error can not update option: "driver"
db.conf({isopen:false}) ==>

PASS!: err = unknown option "isopen" not one of: driver sqlite_dbdir username password dbname host encoding port sqlite_timeout timeout verbosity version engineVersion socket isSqlite drvOpts callback queryOpts 
db.query('SELECT * FROM test3;', {values:['Box'], qag:9}) ==>
PASS!: err = unknown option "qag" not one of: mode values widths limit headers nullvalue separator table callback 
db.query('SELECT * FROM test3;', {bag:9}) ==>



PASS!: err = unknown option "bag" not one of: mode values widths limit headers nullvalue separator table callback 
db.query('SELECT * FROM test3;', {mode:'xx'}) ==>






PASS!: err = unknown enum "xx" not one of: rows arrays array1d list column json json2 html csv insert line tabs cursor none 
=!EXPECTEND!=
*/

Changes to c-demos/cdata/Bag.jsc.

20
21
22
23
24
25
26
27
28
29
30
31
32
33
        return rc;
    }

    function ranger(options:object=void):array { // Fill a range using config
        /* C code. */
        Jsi_Value *a = Jsi_ValueMakeArrayObject(interp, ret, NULL);
        Jsi_RC rc = JSI_OK;
        int n=data.size-1, i=data.start+n*data.step;
        for (; n>=0&&rc==JSI_OK; i-=data.step, n--)
            rc = Jsi_ValueInsertArray(interp, a, n, Jsi_ValueNewNumber(interp, i), 0);
        return rc;
    }

};







|
|





20
21
22
23
24
25
26
27
28
29
30
31
32
33
        return rc;
    }

    function ranger(options:object=void):array { // Fill a range using config
        /* C code. */
        Jsi_Value *a = Jsi_ValueMakeArrayObject(interp, ret, NULL);
        Jsi_RC rc = JSI_OK;
        int n=options->size-1, i=options->start+n*options->step;
        for (; n>=0&&rc==JSI_OK; i-=options->step, n--)
            rc = Jsi_ValueInsertArray(interp, a, n, Jsi_ValueNewNumber(interp, i), 0);
        return rc;
    }

};

Changes to c-demos/cdata/Baker.jsc.

34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
    function conf(options:object|string=void):any { // Function to configure Baker options
        /* No C code is required for "conf()". */
    }

    function kneed(name:string, options:object=void):void { // Kneed the dough
        /* C code. */
        cmdPtr->kneedCnt++;
        cmdPtr->kneedMins += data.minutes;
        RETURN();
    }

    function slice(loafType:number, options:object=void):number { // Function to add values
        /* C code. */
        Jsi_Number n = loafType+100;
        RETURN(n);







|







34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
    function conf(options:object|string=void):any { // Function to configure Baker options
        /* No C code is required for "conf()". */
    }

    function kneed(name:string, options:object=void):void { // Kneed the dough
        /* C code. */
        cmdPtr->kneedCnt++;
        cmdPtr->kneedMins += options->minutes;
        RETURN();
    }

    function slice(loafType:number, options:object=void):number { // Function to add values
        /* C code. */
        Jsi_Number n = loafType+100;
        RETURN(n);

Changes to c-demos/cdata/Car.jsc.

11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
struct Car_ = { // Module struct (optional), will be per-interp if no Car_Data var.
    bool loaded;
    int activeCnt; // Count of active objects.
    int newCnt;  // Total number of new.
};

struct Car = { // Per-object struct
    Jsi_Interp* interp; // Note: must add interp field for object command.
    int maxSpeed=120;
    int gear;
    int shiftCnt;
    uchar* _myPtr; // Stuff
    FUNC callback;
    Car_* _;    // Ptr to Car_ defined above
};







|







11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
struct Car_ = { // Module struct (optional), will be per-interp if no Car_Data var.
    bool loaded;
    int activeCnt; // Count of active objects.
    int newCnt;  // Total number of new.
};

struct Car = { // Per-object struct
    Jsi_Interp* _interp; // Note: must add _interp field for object command.
    int maxSpeed=120;
    int gear;
    int shiftCnt;
    uchar* _myPtr; // Stuff
    FUNC callback;
    Car_* _;    // Ptr to Car_ defined above
};

Changes to lib/Jsi_CData.jsi.

22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
...
335
336
337
338
339
340
341


342
343
344
345
346
347
348
...
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
....
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
        varSuffix   :'_Data'// Suffix to add to data used for object config.
    };

    var self = {
        pre:'', pre0:'', pre1:'', out0:'', out1:'', out:'', iout:'',
        init:[], types:'',  structs:'', enums:'', vars:'', cmds:'',
        varnames:[], mapnames:[], cmdnames:[], 
        structmap:{}, enummap:{}, enumzero:{},
        vardefs:'',  siglst:[], varinits:'', mapinits:'', enumIni:{},
        portlst:[], statlst:[], cmddefs:'', cmddef:'',
        enumvals:{}, indata:'', infile:'', outFile:null, rootname:null,
        lnstart:0, setCons:0, icode:[], outcode:'',
        preface: '// DO NOT EDIT: file generated by Jsi_CData.jsi'
    };
    self.pkg = require('Jsi_CData', 0);
................................................................................
                    sinit = "\""+f.init+"\"";
            } else if (f.asize) {
                sinit = "{}";
            } else if (f.init !== undefined) {
                sinit = f.init;
            } else if (self.structmap[type]) {
                sinit = "JSI_INI_DEFN_"+type;


            }
            var otype = st;
            
            var issubopt = (self.structmap[type] !== undefined);
            var isenum = (self.enummap[type] !== undefined);
            if (isenum && !self.enumzero[type])
                LogWarn(name, '.', fname, ': enum ', type, "does not define a zero value");
................................................................................
                    if (fname === 'conf') {
                        if (isObj || intData)
                            iodnam = 'cmdPtr';
                        else
                            iodnam = '&'+name+self.varSuffix;
                    } else if (fname === 'idconf') {
                        // Cmd-local options.
                        iodnam = 'dPtr';
                        ifpre += '  '+iopnam + ' *dPtr = '+name+'_IdGet(cmdPtr, id, 0);\n';
                    } else {
                        // Cmd-local options.
                        iodnam = 'dPtr';
                        ifpostarg += '  '+iopnam + ' data = {}; vr.data = (void*)&data;\n';
                        ifpre += '  '+iopnam + ' *dPtr = ('+iopnam+'*)vrPtr->data;\n';


                    }
                    if (fname === 'conf') {
                        if (i>0) throw("Conf command takes only a single argument");
                        ifpre += '  return Jsi_OptionsConf(interp, (Jsi_OptionSpec*)'+iopnamS+', '+iodnam+', '+voao+', ret, 0);\n';
                    } else if (fname === 'idconf') {
                        ifpre += '  if (!dPtr || Jsi_OptionsConf(interp, (Jsi_OptionSpec*)'+iopnamS+', '+iodnam+', '+voao+', ret, 0) < 0) return JSI_ERROR;\n';
                    } else {
                        if (!fconstr)
                            ifpre += '  if ('+voao+') { vrPtr->spec = (Jsi_OptionSpec*)'+iopnamS+'; }\n';
                        ifpre += '  if ('+voao+' && Jsi_OptionsProcess(interp, (Jsi_OptionSpec*)'+iopnamS+', '+iodnam+', '+voao+', 0) < 0) return JSI_ERROR;\n';
                    }
                }

................................................................................

// Start of template code for object commands.

static Jsi_CmdSpec DemoCmds[];

static void DemoObjErase(Demo *cmdPtr)
{
    if (!cmdPtr->interp)
        return;
    Jsi_OptionsFree(cmdPtr->interp, Demo_Specs, cmdPtr, 0);
    memset(cmdPtr, 0, sizeof(*cmdPtr));;
}

static Jsi_RC DemoObjFree(Jsi_Interp *interp, void *data)
{
    Demo *cmdPtr = (Demo *)data;
    %s /* FREE_OBJ */







|







 







>
>







 







|
|


|

|
>
>





|







 







|

|







22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
...
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
...
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
....
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
        varSuffix   :'_Data'// Suffix to add to data used for object config.
    };

    var self = {
        pre:'', pre0:'', pre1:'', out0:'', out1:'', out:'', iout:'',
        init:[], types:'',  structs:'', enums:'', vars:'', cmds:'',
        varnames:[], mapnames:[], cmdnames:[], 
        structmap:{}, enummap:{}, enumzero:{}, structfieldmap:{},
        vardefs:'',  siglst:[], varinits:'', mapinits:'', enumIni:{},
        portlst:[], statlst:[], cmddefs:'', cmddef:'',
        enumvals:{}, indata:'', infile:'', outFile:null, rootname:null,
        lnstart:0, setCons:0, icode:[], outcode:'',
        preface: '// DO NOT EDIT: file generated by Jsi_CData.jsi'
    };
    self.pkg = require('Jsi_CData', 0);
................................................................................
                    sinit = "\""+f.init+"\"";
            } else if (f.asize) {
                sinit = "{}";
            } else if (f.init !== undefined) {
                sinit = f.init;
            } else if (self.structmap[type]) {
                sinit = "JSI_INI_DEFN_"+type;
                if (fname.match(/Opts$/))
                    self.structfieldmap[name+'.'+type] = fname;
            }
            var otype = st;
            
            var issubopt = (self.structmap[type] !== undefined);
            var isenum = (self.enummap[type] !== undefined);
            if (isenum && !self.enumzero[type])
                LogWarn(name, '.', fname, ': enum ', type, "does not define a zero value");
................................................................................
                    if (fname === 'conf') {
                        if (isObj || intData)
                            iodnam = 'cmdPtr';
                        else
                            iodnam = '&'+name+self.varSuffix;
                    } else if (fname === 'idconf') {
                        // Cmd-local options.
                        iodnam = 'options';
                        ifpre += '  '+iopnam + ' *options = '+name+'_IdGet(cmdPtr, id, 0);\n';
                    } else {
                        // Cmd-local options.
                        iodnam = 'options';
                        ifpostarg += '  '+iopnam + ' data = {}; vr.data = (void*)&data;\n';
                        ifpre += '  '+iopnam + ' *options = ('+iopnam+'*)vrPtr->data;\n';
                        //if (self.structfieldmap[name+'.'+iopnam])
                        //   ifpre += '  *options = cmdPtr->'+self.structfieldmap[name+'.'+iopnam]+';\n';
                    }
                    if (fname === 'conf') {
                        if (i>0) throw("Conf command takes only a single argument");
                        ifpre += '  return Jsi_OptionsConf(interp, (Jsi_OptionSpec*)'+iopnamS+', '+iodnam+', '+voao+', ret, 0);\n';
                    } else if (fname === 'idconf') {
                        ifpre += '  if (!options || Jsi_OptionsConf(interp, (Jsi_OptionSpec*)'+iopnamS+', '+iodnam+', '+voao+', ret, 0) < 0) return JSI_ERROR;\n';
                    } else {
                        if (!fconstr)
                            ifpre += '  if ('+voao+') { vrPtr->spec = (Jsi_OptionSpec*)'+iopnamS+'; }\n';
                        ifpre += '  if ('+voao+' && Jsi_OptionsProcess(interp, (Jsi_OptionSpec*)'+iopnamS+', '+iodnam+', '+voao+', 0) < 0) return JSI_ERROR;\n';
                    }
                }

................................................................................

// Start of template code for object commands.

static Jsi_CmdSpec DemoCmds[];

static void DemoObjErase(Demo *cmdPtr)
{
    if (!cmdPtr->_interp)
        return;
    Jsi_OptionsFree(cmdPtr->_interp, Demo_Specs, cmdPtr, 0);
    memset(cmdPtr, 0, sizeof(*cmdPtr));;
}

static Jsi_RC DemoObjFree(Jsi_Interp *interp, void *data)
{
    Demo *cmdPtr = (Demo *)data;
    %s /* FREE_OBJ */

Changes to md/Coding.md.

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
Coding
====
<div id="sectmenu"></div>

Modules
----
Jsi Modules are convenient in that are usable from both the command-line and problematically.

The simplest module is a function whose name is the same *basename* as the file:

    $ echo 'function hello() { return "Hello World!"; }' > hello.jsi
    $ jsish -m hello

==>

    Hello World!

Add an explicit **runModule** and the "-m" is no longer needed.

    echo 'runModule(hello);' >> hello.jsi
    $ jsish hello.jsi
    


Modules can also be [generated](#Templates).


### Arguments
Modules handle arguments via an array parameter:

    function add(args) { return args.join(', '); }
    jsish -m add.jsi Able Baker Charlie







|

|

|
|
|



|
<

<
<
<
<
<
<
>







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
Coding
====
<div id="sectmenu"></div>

Modules
----
Jsi Modules can be used either from code or the command-line.

Here is a simple module:

    echo 'function hello() { return "Hello World!"; }; runModule(hello);' > hello.jsi
    $ jsish hello.jsi
 
==>

    Hello World!
   








more complete modules can be with [templates](#Templates).

### Arguments
Modules handle arguments via an array parameter:

    function add(args) { return args.join(', '); }
    jsish -m add.jsi Able Baker Charlie

Changes to src/jsi.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
....
1408
1409
1410
1411
1412
1413
1414





1415
1416
1417
1418
1419
1420
1421
/* jsi.h : External API header file for Jsi. */
#ifndef __JSI_H__
#define __JSI_H__

#define JSI_VERSION_MAJOR   2
#define JSI_VERSION_MINOR   8
#define JSI_VERSION_RELEASE 18

#define JSI_VERSION (JSI_VERSION_MAJOR + ((Jsi_Number)JSI_VERSION_MINOR/100.0) + ((Jsi_Number)JSI_VERSION_RELEASE/10000.0))

#ifndef JSI_EXTERN
#define JSI_EXTERN extern
#endif

................................................................................
JSI_EXTERN void* Jsi_DbHandle(Jsi_Interp *interp, Jsi_Db* db); /*STUB = 399*/

/* -- */


/* --CData-- */






typedef struct Jsi_CData_Static {
    const char* name;
    Jsi_StructSpec* structs;
    Jsi_EnumSpec* enums;
    Jsi_VarSpec *vars;
    Jsi_OptionTypedef* types;
    struct Jsi_CData_Static* nextPtr;






|







 







>
>
>
>
>







1
2
3
4
5
6
7
8
9
10
11
12
13
14
....
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
/* jsi.h : External API header file for Jsi. */
#ifndef __JSI_H__
#define __JSI_H__

#define JSI_VERSION_MAJOR   2
#define JSI_VERSION_MINOR   8
#define JSI_VERSION_RELEASE 19

#define JSI_VERSION (JSI_VERSION_MAJOR + ((Jsi_Number)JSI_VERSION_MINOR/100.0) + ((Jsi_Number)JSI_VERSION_RELEASE/10000.0))

#ifndef JSI_EXTERN
#define JSI_EXTERN extern
#endif

................................................................................
JSI_EXTERN void* Jsi_DbHandle(Jsi_Interp *interp, Jsi_Db* db); /*STUB = 399*/

/* -- */


/* --CData-- */

#define  JSI_CDATA_OPTION_CHANGED(name) \
        (vrPtr->spec && Jsi_OptionsChanged(interp, vrPtr->spec, #name, NULL))
#define  JSI_CDATA_OPTION_RESET(name) \
        (cmdPtr->queryOpts.mode && !options->name && JSI_CDATA_OPTION_CHANGED(name))
 
typedef struct Jsi_CData_Static {
    const char* name;
    Jsi_StructSpec* structs;
    Jsi_EnumSpec* enums;
    Jsi_VarSpec *vars;
    Jsi_OptionTypedef* types;
    struct Jsi_CData_Static* nextPtr;

Changes to src/jsi.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
....
1408
1409
1410
1411
1412
1413
1414





1415
1416
1417
1418
1419
1420
1421
/* jsi.h : External API header file for Jsi. */
#ifndef __JSI_H__
#define __JSI_H__

#define JSI_VERSION_MAJOR   2
#define JSI_VERSION_MINOR   8
#define JSI_VERSION_RELEASE 18

#define JSI_VERSION (JSI_VERSION_MAJOR + ((Jsi_Number)JSI_VERSION_MINOR/100.0) + ((Jsi_Number)JSI_VERSION_RELEASE/10000.0))

#ifndef JSI_EXTERN
#define JSI_EXTERN extern
#endif

................................................................................
JSI_EXTERN void* Jsi_DbHandle(Jsi_Interp *interp, Jsi_Db* db); /*STUB = 399*/

/* -- */


/* --CData-- */






typedef struct Jsi_CData_Static {
    const char* name;
    Jsi_StructSpec* structs;
    Jsi_EnumSpec* enums;
    Jsi_VarSpec *vars;
    Jsi_OptionTypedef* types;
    struct Jsi_CData_Static* nextPtr;






|







 







>
>
>
>
>







1
2
3
4
5
6
7
8
9
10
11
12
13
14
....
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
/* jsi.h : External API header file for Jsi. */
#ifndef __JSI_H__
#define __JSI_H__

#define JSI_VERSION_MAJOR   2
#define JSI_VERSION_MINOR   8
#define JSI_VERSION_RELEASE 19

#define JSI_VERSION (JSI_VERSION_MAJOR + ((Jsi_Number)JSI_VERSION_MINOR/100.0) + ((Jsi_Number)JSI_VERSION_RELEASE/10000.0))

#ifndef JSI_EXTERN
#define JSI_EXTERN extern
#endif

................................................................................
JSI_EXTERN void* Jsi_DbHandle(Jsi_Interp *interp, Jsi_Db* db); /*STUB = 399*/

/* -- */


/* --CData-- */

#define  JSI_CDATA_OPTION_CHANGED(name) \
        (vrPtr->spec && Jsi_OptionsChanged(interp, vrPtr->spec, #name, NULL))
#define  JSI_CDATA_OPTION_RESET(name) \
        (cmdPtr->queryOpts.mode && !options->name && JSI_CDATA_OPTION_CHANGED(name))
 
typedef struct Jsi_CData_Static {
    const char* name;
    Jsi_StructSpec* structs;
    Jsi_EnumSpec* enums;
    Jsi_VarSpec *vars;
    Jsi_OptionTypedef* types;
    struct Jsi_CData_Static* nextPtr;

Changes to tools/protos.jsi.

1
2
3
4
5
6
7
8
//JSI Command Prototypes: version 2.8.18
throw("NOT EXECUTABLE: USE FILE IN GEANY EDITOR FOR CMD LINE COMPLETION + GOTO TAG");

var Array = function(cmd,args) {};
Array.prototype.concat = function(...):array {};
Array.prototype.every = function(callback:function):any {};
Array.prototype.fill = function(value:any, start:number=0, end:number=-1):array {};
Array.prototype.filter = function(callback:function, this:object=void):array {};
|







1
2
3
4
5
6
7
8
//JSI Command Prototypes: version 2.8.19
throw("NOT EXECUTABLE: USE FILE IN GEANY EDITOR FOR CMD LINE COMPLETION + GOTO TAG");

var Array = function(cmd,args) {};
Array.prototype.concat = function(...):array {};
Array.prototype.every = function(callback:function):any {};
Array.prototype.fill = function(value:any, start:number=0, end:number=-1):array {};
Array.prototype.filter = function(callback:function, this:object=void):array {};