~ubuntu-branches/ubuntu/hardy/sqlite3/hardy

« back to all changes in this revision

Viewing changes to src/test8.c

  • Committer: Bazaar Package Importer
  • Author(s): Laszlo Boszormenyi (GCS)
  • Date: 2006-10-12 21:55:37 UTC
  • mfrom: (1.1.5 upstream)
  • Revision ID: james.westby@ubuntu.com-20061012215537-mgvrxoq8ee4nqxzh
Tags: 3.3.8-1
* New upstream version.
* Create lang_* files for documentation (closes: #310603).
* Enable column metadata functions (closes: #375352).

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/*
 
2
** 2006 June 10
 
3
**
 
4
** The author disclaims copyright to this source code.  In place of
 
5
** a legal notice, here is a blessing:
 
6
**
 
7
**    May you do good and not evil.
 
8
**    May you find forgiveness for yourself and forgive others.
 
9
**    May you share freely, never taking more than you give.
 
10
**
 
11
*************************************************************************
 
12
** Code for testing the virtual table interfaces.  This code
 
13
** is not included in the SQLite library.  It is used for automated
 
14
** testing of the SQLite library.
 
15
**
 
16
** $Id: test8.c,v 1.43 2006/10/08 18:56:57 drh Exp $
 
17
*/
 
18
#include "sqliteInt.h"
 
19
#include "tcl.h"
 
20
#include "os.h"
 
21
#include <stdlib.h>
 
22
#include <string.h>
 
23
 
 
24
#ifndef SQLITE_OMIT_VIRTUALTABLE
 
25
 
 
26
typedef struct echo_vtab echo_vtab;
 
27
typedef struct echo_cursor echo_cursor;
 
28
 
 
29
/*
 
30
** The test module defined in this file uses two global Tcl variables to
 
31
** commicate with test-scripts:
 
32
**
 
33
**     $::echo_module
 
34
**     $::echo_module_sync_fail
 
35
**     $::echo_module_begin_fail
 
36
**
 
37
** The variable ::echo_module is a list. Each time one of the following
 
38
** methods is called, one or more elements are appended to the list.
 
39
** This is used for automated testing of virtual table modules.
 
40
**
 
41
** The ::echo_module_sync_fail variable is set by test scripts and read
 
42
** by code in this file. If it is set to the name of a real table in the
 
43
** the database, then all xSync operations on echo virtual tables that
 
44
** use the named table as a backing store will fail.
 
45
*/
 
46
 
 
47
/* 
 
48
** An echo virtual-table object.
 
49
**
 
50
** echo.vtab.aIndex is an array of booleans. The nth entry is true if 
 
51
** the nth column of the real table is the left-most column of an index
 
52
** (implicit or otherwise). In other words, if SQLite can optimize
 
53
** a query like "SELECT * FROM real_table WHERE col = ?".
 
54
**
 
55
** Member variable aCol[] contains copies of the column names of the real
 
56
** table.
 
57
*/
 
58
struct echo_vtab {
 
59
  sqlite3_vtab base;
 
60
  Tcl_Interp *interp;     /* Tcl interpreter containing debug variables */
 
61
  sqlite3 *db;            /* Database connection */
 
62
 
 
63
  char *zTableName;       /* Name of the real table */
 
64
  char *zLogName;         /* Name of the log table */
 
65
  int nCol;               /* Number of columns in the real table */
 
66
  int *aIndex;            /* Array of size nCol. True if column has an index */
 
67
  char **aCol;            /* Array of size nCol. Column names */
 
68
};
 
69
 
 
70
/* An echo cursor object */
 
71
struct echo_cursor {
 
72
  sqlite3_vtab_cursor base;
 
73
  sqlite3_stmt *pStmt;
 
74
};
 
75
 
 
76
/*
 
77
** Retrieve the column names for the table named zTab via database
 
78
** connection db. SQLITE_OK is returned on success, or an sqlite error
 
79
** code otherwise.
 
80
**
 
81
** If successful, the number of columns is written to *pnCol. *paCol is
 
82
** set to point at sqliteMalloc()'d space containing the array of
 
83
** nCol column names. The caller is responsible for calling sqliteFree
 
84
** on *paCol.
 
85
*/
 
86
static int getColumnNames(
 
87
  sqlite3 *db, 
 
88
  const char *zTab,
 
89
  char ***paCol, 
 
90
  int *pnCol
 
91
){
 
92
  char **aCol = 0;
 
93
  char *zSql;
 
94
  sqlite3_stmt *pStmt = 0;
 
95
  int rc = SQLITE_OK;
 
96
  int nCol = 0;
 
97
 
 
98
  /* Prepare the statement "SELECT * FROM <tbl>". The column names
 
99
  ** of the result set of the compiled SELECT will be the same as
 
100
  ** the column names of table <tbl>.
 
101
  */
 
102
  zSql = sqlite3MPrintf("SELECT * FROM %Q", zTab);
 
103
  if( !zSql ){
 
104
    rc = SQLITE_NOMEM;
 
105
    goto out;
 
106
  }
 
107
  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
 
108
  sqliteFree(zSql);
 
109
 
 
110
  if( rc==SQLITE_OK ){
 
111
    int ii;
 
112
    int nBytes;
 
113
    char *zSpace;
 
114
    nCol = sqlite3_column_count(pStmt);
 
115
 
 
116
    /* Figure out how much space to allocate for the array of column names 
 
117
    ** (including space for the strings themselves). Then allocate it.
 
118
    */
 
119
    nBytes = sizeof(char *) * nCol;
 
120
    for(ii=0; ii<nCol; ii++){
 
121
      nBytes += (strlen(sqlite3_column_name(pStmt, ii)) + 1);
 
122
    }
 
123
    aCol = (char **)sqliteMalloc(nBytes);
 
124
    if( !aCol ){
 
125
      rc = SQLITE_NOMEM;
 
126
      goto out;
 
127
    }
 
128
 
 
129
    /* Copy the column names into the allocated space and set up the
 
130
    ** pointers in the aCol[] array.
 
131
    */
 
132
    zSpace = (char *)(&aCol[nCol]);
 
133
    for(ii=0; ii<nCol; ii++){
 
134
      aCol[ii] = zSpace;
 
135
      zSpace += sprintf(zSpace, "%s", sqlite3_column_name(pStmt, ii));
 
136
      zSpace++;
 
137
    }
 
138
    assert( (zSpace-nBytes)==(char *)aCol );
 
139
  }
 
140
 
 
141
  *paCol = aCol;
 
142
  *pnCol = nCol;
 
143
 
 
144
out:
 
145
  sqlite3_finalize(pStmt);
 
146
  return rc;
 
147
}
 
148
 
 
149
/*
 
150
** Parameter zTab is the name of a table in database db with nCol 
 
151
** columns. This function allocates an array of integers nCol in 
 
152
** size and populates it according to any implicit or explicit 
 
153
** indices on table zTab.
 
154
**
 
155
** If successful, SQLITE_OK is returned and *paIndex set to point 
 
156
** at the allocated array. Otherwise, an error code is returned.
 
157
**
 
158
** See comments associated with the member variable aIndex above 
 
159
** "struct echo_vtab" for details of the contents of the array.
 
160
*/
 
161
static int getIndexArray(
 
162
  sqlite3 *db,             /* Database connection */
 
163
  const char *zTab,        /* Name of table in database db */
 
164
  int nCol,
 
165
  int **paIndex
 
166
){
 
167
  sqlite3_stmt *pStmt = 0;
 
168
  int *aIndex = 0;
 
169
  int rc;
 
170
  char *zSql;
 
171
 
 
172
  /* Allocate space for the index array */
 
173
  aIndex = (int *)sqliteMalloc(sizeof(int) * nCol);
 
174
  if( !aIndex ){
 
175
    rc = SQLITE_NOMEM;
 
176
    goto get_index_array_out;
 
177
  }
 
178
 
 
179
  /* Compile an sqlite pragma to loop through all indices on table zTab */
 
180
  zSql = sqlite3MPrintf("PRAGMA index_list(%s)", zTab);
 
181
  if( !zSql ){
 
182
    rc = SQLITE_NOMEM;
 
183
    goto get_index_array_out;
 
184
  }
 
185
  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
 
186
  sqliteFree(zSql);
 
187
 
 
188
  /* For each index, figure out the left-most column and set the 
 
189
  ** corresponding entry in aIndex[] to 1.
 
190
  */
 
191
  while( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
 
192
    const char *zIdx = (const char *)sqlite3_column_text(pStmt, 1);
 
193
    sqlite3_stmt *pStmt2 = 0;
 
194
    zSql = sqlite3MPrintf("PRAGMA index_info(%s)", zIdx);
 
195
    if( !zSql ){
 
196
      rc = SQLITE_NOMEM;
 
197
      goto get_index_array_out;
 
198
    }
 
199
    rc = sqlite3_prepare(db, zSql, -1, &pStmt2, 0);
 
200
    sqliteFree(zSql);
 
201
    if( pStmt2 && sqlite3_step(pStmt2)==SQLITE_ROW ){
 
202
      int cid = sqlite3_column_int(pStmt2, 1);
 
203
      assert( cid>=0 && cid<nCol );
 
204
      aIndex[cid] = 1;
 
205
    }
 
206
    if( pStmt2 ){
 
207
      rc = sqlite3_finalize(pStmt2);
 
208
    }
 
209
    if( rc!=SQLITE_OK ){
 
210
      goto get_index_array_out;
 
211
    }
 
212
  }
 
213
 
 
214
 
 
215
get_index_array_out:
 
216
  if( pStmt ){
 
217
    int rc2 = sqlite3_finalize(pStmt);
 
218
    if( rc==SQLITE_OK ){
 
219
      rc = rc2;
 
220
    }
 
221
  }
 
222
  if( rc!=SQLITE_OK ){
 
223
    sqliteFree(aIndex);
 
224
    aIndex = 0;
 
225
  }
 
226
  *paIndex = aIndex;
 
227
  return rc;
 
228
}
 
229
 
 
230
/*
 
231
** Global Tcl variable $echo_module is a list. This routine appends
 
232
** the string element zArg to that list in interpreter interp.
 
233
*/
 
234
static void appendToEchoModule(Tcl_Interp *interp, const char *zArg){
 
235
  int flags = (TCL_APPEND_VALUE | TCL_LIST_ELEMENT | TCL_GLOBAL_ONLY);
 
236
  Tcl_SetVar(interp, "echo_module", (zArg?zArg:""), flags);
 
237
}
 
238
 
 
239
/*
 
240
** This function is called from within the echo-modules xCreate and
 
241
** xConnect methods. The argc and argv arguments are copies of those 
 
242
** passed to the calling method. This function is responsible for
 
243
** calling sqlite3_declare_vtab() to declare the schema of the virtual
 
244
** table being created or connected.
 
245
**
 
246
** If the constructor was passed just one argument, i.e.:
 
247
**
 
248
**   CREATE TABLE t1 AS echo(t2);
 
249
**
 
250
** Then t2 is assumed to be the name of a *real* database table. The
 
251
** schema of the virtual table is declared by passing a copy of the 
 
252
** CREATE TABLE statement for the real table to sqlite3_declare_vtab().
 
253
** Hence, the virtual table should have exactly the same column names and 
 
254
** types as the real table.
 
255
*/
 
256
static int echoDeclareVtab(
 
257
  echo_vtab *pVtab, 
 
258
  sqlite3 *db, 
 
259
  int argc, 
 
260
  const char *const*argv
 
261
){
 
262
  int rc = SQLITE_OK;
 
263
 
 
264
  if( argc>=4 ){
 
265
    sqlite3_stmt *pStmt = 0;
 
266
    sqlite3_prepare(db, 
 
267
        "SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?",
 
268
        -1, &pStmt, 0);
 
269
    sqlite3_bind_text(pStmt, 1, argv[3], -1, 0);
 
270
    if( sqlite3_step(pStmt)==SQLITE_ROW ){
 
271
      const char *zCreateTable = (const char *)sqlite3_column_text(pStmt, 0);
 
272
      sqlite3_declare_vtab(db, zCreateTable);
 
273
      rc = sqlite3_finalize(pStmt);
 
274
    } else {
 
275
      rc = sqlite3_finalize(pStmt);
 
276
      if( rc==SQLITE_OK ){ 
 
277
        rc = SQLITE_ERROR;
 
278
      }
 
279
    }
 
280
 
 
281
    if( rc==SQLITE_OK ){
 
282
      rc = getColumnNames(db, argv[3], &pVtab->aCol, &pVtab->nCol);
 
283
    }
 
284
    if( rc==SQLITE_OK ){
 
285
      rc = getIndexArray(db, argv[3], pVtab->nCol, &pVtab->aIndex);
 
286
    }
 
287
  }
 
288
 
 
289
  return rc;
 
290
}
 
291
 
 
292
/*
 
293
** This function frees all runtime structures associated with the virtual
 
294
** table pVtab.
 
295
*/
 
296
static int echoDestructor(sqlite3_vtab *pVtab){
 
297
  echo_vtab *p = (echo_vtab*)pVtab;
 
298
  sqliteFree(p->aIndex);
 
299
  sqliteFree(p->aCol);
 
300
  sqliteFree(p->zTableName);
 
301
  sqliteFree(p->zLogName);
 
302
  sqliteFree(p);
 
303
  return 0;
 
304
}
 
305
 
 
306
/*
 
307
** This function is called to do the work of the xConnect() method -
 
308
** to allocate the required in-memory structures for a newly connected
 
309
** virtual table.
 
310
*/
 
311
static int echoConstructor(
 
312
  sqlite3 *db,
 
313
  void *pAux,
 
314
  int argc, const char *const*argv,
 
315
  sqlite3_vtab **ppVtab,
 
316
  char **pzErr
 
317
){
 
318
  int i;
 
319
  echo_vtab *pVtab;
 
320
 
 
321
  /* Allocate the sqlite3_vtab/echo_vtab structure itself */
 
322
  pVtab = sqliteMalloc( sizeof(*pVtab) );
 
323
  if( !pVtab ){
 
324
    return SQLITE_NOMEM;
 
325
  }
 
326
  pVtab->interp = (Tcl_Interp *)pAux;
 
327
  pVtab->db = db;
 
328
 
 
329
  /* Allocate echo_vtab.zTableName */
 
330
  pVtab->zTableName = sqlite3MPrintf("%s", argv[3]);
 
331
  if( !pVtab->zTableName ){
 
332
    echoDestructor((sqlite3_vtab *)pVtab);
 
333
    return SQLITE_NOMEM;
 
334
  }
 
335
 
 
336
  /* Log the arguments to this function to Tcl var ::echo_module */
 
337
  for(i=0; i<argc; i++){
 
338
    appendToEchoModule(pVtab->interp, argv[i]);
 
339
  }
 
340
 
 
341
  /* Invoke sqlite3_declare_vtab and set up other members of the echo_vtab
 
342
  ** structure. If an error occurs, delete the sqlite3_vtab structure and
 
343
  ** return an error code.
 
344
  */
 
345
  if( echoDeclareVtab(pVtab, db, argc, argv) ){
 
346
    echoDestructor((sqlite3_vtab *)pVtab);
 
347
    return SQLITE_ERROR;
 
348
  }
 
349
 
 
350
  /* Success. Set *ppVtab and return */
 
351
  *ppVtab = &pVtab->base;
 
352
  return SQLITE_OK;
 
353
}
 
354
 
 
355
/* 
 
356
** Echo virtual table module xCreate method.
 
357
*/
 
358
static int echoCreate(
 
359
  sqlite3 *db,
 
360
  void *pAux,
 
361
  int argc, const char *const*argv,
 
362
  sqlite3_vtab **ppVtab,
 
363
  char **pzErr
 
364
){
 
365
  int rc = SQLITE_OK;
 
366
  appendToEchoModule((Tcl_Interp *)(pAux), "xCreate");
 
367
  rc = echoConstructor(db, pAux, argc, argv, ppVtab, pzErr);
 
368
 
 
369
  /* If there were two arguments passed to the module at the SQL level 
 
370
  ** (i.e. "CREATE VIRTUAL TABLE tbl USING echo(arg1, arg2)"), then 
 
371
  ** the second argument is used as a table name. Attempt to create
 
372
  ** such a table with a single column, "logmsg". This table will
 
373
  ** be used to log calls to the xUpdate method. It will be deleted
 
374
  ** when the virtual table is DROPed.
 
375
  **
 
376
  ** Note: The main point of this is to test that we can drop tables
 
377
  ** from within an xDestroy method call.
 
378
  */
 
379
  if( rc==SQLITE_OK && argc==5 ){
 
380
    char *zSql;
 
381
    echo_vtab *pVtab = *(echo_vtab **)ppVtab;
 
382
    pVtab->zLogName = sqlite3MPrintf("%s", argv[4]);
 
383
    zSql = sqlite3MPrintf("CREATE TABLE %Q(logmsg)", pVtab->zLogName);
 
384
    rc = sqlite3_exec(db, zSql, 0, 0, 0);
 
385
    sqliteFree(zSql);
 
386
  }
 
387
 
 
388
  return rc;
 
389
}
 
390
 
 
391
/* 
 
392
** Echo virtual table module xConnect method.
 
393
*/
 
394
static int echoConnect(
 
395
  sqlite3 *db,
 
396
  void *pAux,
 
397
  int argc, const char *const*argv,
 
398
  sqlite3_vtab **ppVtab,
 
399
  char **pzErr
 
400
){
 
401
  appendToEchoModule((Tcl_Interp *)(pAux), "xConnect");
 
402
  return echoConstructor(db, pAux, argc, argv, ppVtab, pzErr);
 
403
}
 
404
 
 
405
/* 
 
406
** Echo virtual table module xDisconnect method.
 
407
*/
 
408
static int echoDisconnect(sqlite3_vtab *pVtab){
 
409
  appendToEchoModule(((echo_vtab *)pVtab)->interp, "xDisconnect");
 
410
  return echoDestructor(pVtab);
 
411
}
 
412
 
 
413
/* 
 
414
** Echo virtual table module xDestroy method.
 
415
*/
 
416
static int echoDestroy(sqlite3_vtab *pVtab){
 
417
  int rc = SQLITE_OK;
 
418
  echo_vtab *p = (echo_vtab *)pVtab;
 
419
  appendToEchoModule(((echo_vtab *)pVtab)->interp, "xDestroy");
 
420
 
 
421
  /* Drop the "log" table, if one exists (see echoCreate() for details) */
 
422
  if( p && p->zLogName ){
 
423
    char *zSql;
 
424
    zSql = sqlite3MPrintf("DROP TABLE %Q", p->zLogName);
 
425
    rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
 
426
    sqliteFree(zSql);
 
427
  }
 
428
 
 
429
  if( rc==SQLITE_OK ){
 
430
    rc = echoDestructor(pVtab);
 
431
  }
 
432
  return rc;
 
433
}
 
434
 
 
435
/* 
 
436
** Echo virtual table module xOpen method.
 
437
*/
 
438
static int echoOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
 
439
  echo_cursor *pCur;
 
440
  pCur = sqliteMalloc(sizeof(echo_cursor));
 
441
  *ppCursor = (sqlite3_vtab_cursor *)pCur;
 
442
  return (pCur ? SQLITE_OK : SQLITE_NOMEM);
 
443
}
 
444
 
 
445
/* 
 
446
** Echo virtual table module xClose method.
 
447
*/
 
448
static int echoClose(sqlite3_vtab_cursor *cur){
 
449
  int rc;
 
450
  echo_cursor *pCur = (echo_cursor *)cur;
 
451
  sqlite3_stmt *pStmt = pCur->pStmt;
 
452
  pCur->pStmt = 0;
 
453
  sqliteFree(pCur);
 
454
  rc = sqlite3_finalize(pStmt);
 
455
  return rc;
 
456
}
 
457
 
 
458
/*
 
459
** Return non-zero if the cursor does not currently point to a valid record
 
460
** (i.e if the scan has finished), or zero otherwise.
 
461
*/
 
462
static int echoEof(sqlite3_vtab_cursor *cur){
 
463
  return (((echo_cursor *)cur)->pStmt ? 0 : 1);
 
464
}
 
465
 
 
466
/* 
 
467
** Echo virtual table module xNext method.
 
468
*/
 
469
static int echoNext(sqlite3_vtab_cursor *cur){
 
470
  int rc;
 
471
  echo_cursor *pCur = (echo_cursor *)cur;
 
472
  rc = sqlite3_step(pCur->pStmt);
 
473
 
 
474
  if( rc==SQLITE_ROW ){
 
475
    rc = SQLITE_OK;
 
476
  }else{
 
477
    rc = sqlite3_finalize(pCur->pStmt);
 
478
    pCur->pStmt = 0;
 
479
  }
 
480
 
 
481
  return rc;
 
482
}
 
483
 
 
484
/* 
 
485
** Echo virtual table module xColumn method.
 
486
*/
 
487
static int echoColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
 
488
  int iCol = i + 1;
 
489
  sqlite3_stmt *pStmt = ((echo_cursor *)cur)->pStmt;
 
490
  if( !pStmt ){
 
491
    sqlite3_result_null(ctx);
 
492
  }else{
 
493
    assert( sqlite3_data_count(pStmt)>iCol );
 
494
    sqlite3_result_value(ctx, sqlite3_column_value(pStmt, iCol));
 
495
  }
 
496
  return SQLITE_OK;
 
497
}
 
498
 
 
499
/* 
 
500
** Echo virtual table module xRowid method.
 
501
*/
 
502
static int echoRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
 
503
  sqlite3_stmt *pStmt = ((echo_cursor *)cur)->pStmt;
 
504
  *pRowid = sqlite3_column_int64(pStmt, 0);
 
505
  return SQLITE_OK;
 
506
}
 
507
 
 
508
/*
 
509
** Compute a simple hash of the null terminated string zString.
 
510
**
 
511
** This module uses only sqlite3_index_info.idxStr, not 
 
512
** sqlite3_index_info.idxNum. So to test idxNum, when idxStr is set
 
513
** in echoBestIndex(), idxNum is set to the corresponding hash value.
 
514
** In echoFilter(), code assert()s that the supplied idxNum value is
 
515
** indeed the hash of the supplied idxStr.
 
516
*/
 
517
static int hashString(const char *zString){
 
518
  int val = 0;
 
519
  int ii;
 
520
  for(ii=0; zString[ii]; ii++){
 
521
    val = (val << 3) + (int)zString[ii];
 
522
  }
 
523
  return val;
 
524
}
 
525
 
 
526
/* 
 
527
** Echo virtual table module xFilter method.
 
528
*/
 
529
static int echoFilter(
 
530
  sqlite3_vtab_cursor *pVtabCursor, 
 
531
  int idxNum, const char *idxStr,
 
532
  int argc, sqlite3_value **argv
 
533
){
 
534
  int rc;
 
535
  int i;
 
536
 
 
537
  echo_cursor *pCur = (echo_cursor *)pVtabCursor;
 
538
  echo_vtab *pVtab = (echo_vtab *)pVtabCursor->pVtab;
 
539
  sqlite3 *db = pVtab->db;
 
540
 
 
541
  /* Check that idxNum matches idxStr */
 
542
  assert( idxNum==hashString(idxStr) );
 
543
 
 
544
  /* Log arguments to the ::echo_module Tcl variable */
 
545
  appendToEchoModule(pVtab->interp, "xFilter");
 
546
  appendToEchoModule(pVtab->interp, idxStr);
 
547
  for(i=0; i<argc; i++){
 
548
    appendToEchoModule(pVtab->interp, (const char*)sqlite3_value_text(argv[i]));
 
549
  }
 
550
 
 
551
  sqlite3_finalize(pCur->pStmt);
 
552
  pCur->pStmt = 0;
 
553
 
 
554
  /* Prepare the SQL statement created by echoBestIndex and bind the
 
555
  ** runtime parameters passed to this function to it.
 
556
  */
 
557
  rc = sqlite3_prepare(db, idxStr, -1, &pCur->pStmt, 0);
 
558
  assert( pCur->pStmt || rc!=SQLITE_OK );
 
559
  for(i=0; rc==SQLITE_OK && i<argc; i++){
 
560
    sqlite3_bind_value(pCur->pStmt, i+1, argv[i]);
 
561
  }
 
562
 
 
563
  /* If everything was successful, advance to the first row of the scan */
 
564
  if( rc==SQLITE_OK ){
 
565
    rc = echoNext(pVtabCursor);
 
566
  }
 
567
 
 
568
  return rc;
 
569
}
 
570
 
 
571
 
 
572
/*
 
573
** A helper function used by echoUpdate() and echoBestIndex() for
 
574
** manipulating strings in concert with the sqlite3_mprintf() function.
 
575
**
 
576
** Parameter pzStr points to a pointer to a string allocated with
 
577
** sqlite3_mprintf. The second parameter, zAppend, points to another
 
578
** string. The two strings are concatenated together and *pzStr
 
579
** set to point at the result. The initial buffer pointed to by *pzStr
 
580
** is deallocated via sqlite3_free().
 
581
**
 
582
** If the third argument, doFree, is true, then sqlite3_free() is
 
583
** also called to free the buffer pointed to by zAppend.
 
584
*/
 
585
static void string_concat(char **pzStr, char *zAppend, int doFree){
 
586
  char *zIn = *pzStr;
 
587
  if( zIn ){
 
588
    char *zTemp = zIn;
 
589
    zIn = sqlite3_mprintf("%s%s", zIn, zAppend);
 
590
    sqlite3_free(zTemp);
 
591
  }else{
 
592
    zIn = sqlite3_mprintf("%s", zAppend);
 
593
  }
 
594
  *pzStr = zIn;
 
595
  if( doFree ){
 
596
    sqlite3_free(zAppend);
 
597
  }
 
598
}
 
599
 
 
600
/*
 
601
** The echo module implements the subset of query constraints and sort
 
602
** orders that may take advantage of SQLite indices on the underlying
 
603
** real table. For example, if the real table is declared as:
 
604
**
 
605
**     CREATE TABLE real(a, b, c);
 
606
**     CREATE INDEX real_index ON real(b);
 
607
**
 
608
** then the echo module handles WHERE or ORDER BY clauses that refer
 
609
** to the column "b", but not "a" or "c". If a multi-column index is
 
610
** present, only it's left most column is considered. 
 
611
**
 
612
** This xBestIndex method encodes the proposed search strategy as
 
613
** an SQL query on the real table underlying the virtual echo module 
 
614
** table and stores the query in sqlite3_index_info.idxStr. The SQL
 
615
** statement is of the form:
 
616
**
 
617
**   SELECT rowid, * FROM <real-table> ?<where-clause>? ?<order-by-clause>?
 
618
**
 
619
** where the <where-clause> and <order-by-clause> are determined
 
620
** by the contents of the structure pointed to by the pIdxInfo argument.
 
621
*/
 
622
static int echoBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
 
623
  int ii;
 
624
  char *zQuery = 0;
 
625
  char *zNew;
 
626
  int nArg = 0;
 
627
  const char *zSep = "WHERE";
 
628
  echo_vtab *pVtab = (echo_vtab *)tab;
 
629
  sqlite3_stmt *pStmt = 0;
 
630
 
 
631
  int nRow;
 
632
  int useIdx = 0;
 
633
  int rc = SQLITE_OK;
 
634
 
 
635
  /* Determine the number of rows in the table and store this value in local
 
636
  ** variable nRow. The 'estimated-cost' of the scan will be the number of
 
637
  ** rows in the table for a linear scan, or the log (base 2) of the 
 
638
  ** number of rows if the proposed scan uses an index.  
 
639
  */
 
640
  zQuery = sqlite3_mprintf("SELECT count(*) FROM %Q", pVtab->zTableName);
 
641
  rc = sqlite3_prepare(pVtab->db, zQuery, -1, &pStmt, 0);
 
642
  if( rc!=SQLITE_OK ){
 
643
    return rc;
 
644
  }
 
645
  sqlite3_step(pStmt);
 
646
  nRow = sqlite3_column_int(pStmt, 0);
 
647
  rc = sqlite3_finalize(pStmt);
 
648
  if( rc!=SQLITE_OK ){
 
649
    return rc;
 
650
  }
 
651
 
 
652
  zQuery = sqlite3_mprintf("SELECT rowid, * FROM %Q", pVtab->zTableName);
 
653
  for(ii=0; ii<pIdxInfo->nConstraint; ii++){
 
654
    const struct sqlite3_index_constraint *pConstraint;
 
655
    struct sqlite3_index_constraint_usage *pUsage;
 
656
    int iCol;
 
657
 
 
658
    pConstraint = &pIdxInfo->aConstraint[ii];
 
659
    pUsage = &pIdxInfo->aConstraintUsage[ii];
 
660
 
 
661
    iCol = pConstraint->iColumn;
 
662
    if( pVtab->aIndex[iCol] ){
 
663
      char *zCol = pVtab->aCol[iCol];
 
664
      char *zOp = 0;
 
665
      useIdx = 1;
 
666
      if( iCol<0 ){
 
667
        zCol = "rowid";
 
668
      }
 
669
      switch( pConstraint->op ){
 
670
        case SQLITE_INDEX_CONSTRAINT_EQ:
 
671
          zOp = "="; break;
 
672
        case SQLITE_INDEX_CONSTRAINT_LT:
 
673
          zOp = "<"; break;
 
674
        case SQLITE_INDEX_CONSTRAINT_GT:
 
675
          zOp = ">"; break;
 
676
        case SQLITE_INDEX_CONSTRAINT_LE:
 
677
          zOp = "<="; break;
 
678
        case SQLITE_INDEX_CONSTRAINT_GE:
 
679
          zOp = ">="; break;
 
680
        case SQLITE_INDEX_CONSTRAINT_MATCH:
 
681
          zOp = "LIKE"; break;
 
682
      }
 
683
      if( zOp[0]=='L' ){
 
684
        zNew = sqlite3_mprintf(" %s %s LIKE (SELECT '%%'||?||'%%')", 
 
685
                               zSep, zCol);
 
686
      } else {
 
687
        zNew = sqlite3_mprintf(" %s %s %s ?", zSep, zCol, zOp);
 
688
      }
 
689
      string_concat(&zQuery, zNew, 1);
 
690
 
 
691
      zSep = "AND";
 
692
      pUsage->argvIndex = ++nArg;
 
693
      pUsage->omit = 1;
 
694
    }
 
695
  }
 
696
 
 
697
  /* If there is only one term in the ORDER BY clause, and it is
 
698
  ** on a column that this virtual table has an index for, then consume 
 
699
  ** the ORDER BY clause.
 
700
  */
 
701
  if( pIdxInfo->nOrderBy==1 && pVtab->aIndex[pIdxInfo->aOrderBy->iColumn] ){
 
702
    int iCol = pIdxInfo->aOrderBy->iColumn;
 
703
    char *zCol = pVtab->aCol[iCol];
 
704
    char *zDir = pIdxInfo->aOrderBy->desc?"DESC":"ASC";
 
705
    if( iCol<0 ){
 
706
      zCol = "rowid";
 
707
    }
 
708
    zNew = sqlite3_mprintf(" ORDER BY %s %s", zCol, zDir);
 
709
    string_concat(&zQuery, zNew, 1);
 
710
    pIdxInfo->orderByConsumed = 1;
 
711
  }
 
712
 
 
713
  appendToEchoModule(pVtab->interp, "xBestIndex");;
 
714
  appendToEchoModule(pVtab->interp, zQuery);
 
715
 
 
716
  pIdxInfo->idxNum = hashString(zQuery);
 
717
  pIdxInfo->idxStr = zQuery;
 
718
  pIdxInfo->needToFreeIdxStr = 1;
 
719
  if( useIdx ){
 
720
    /* Approximation of log2(nRow). */
 
721
    for( ii=0; ii<(sizeof(int)*8); ii++ ){
 
722
      if( nRow & (1<<ii) ){
 
723
        pIdxInfo->estimatedCost = (double)ii;
 
724
      }
 
725
    }
 
726
  } else {
 
727
    pIdxInfo->estimatedCost = (double)nRow;
 
728
  }
 
729
  return rc;
 
730
}
 
731
 
 
732
/*
 
733
** The xUpdate method for echo module virtual tables.
 
734
** 
 
735
**    apData[0]  apData[1]  apData[2..]
 
736
**
 
737
**    INTEGER                              DELETE            
 
738
**
 
739
**    INTEGER    NULL       (nCol args)    UPDATE (do not set rowid)
 
740
**    INTEGER    INTEGER    (nCol args)    UPDATE (with SET rowid = <arg1>)
 
741
**
 
742
**    NULL       NULL       (nCol args)    INSERT INTO (automatic rowid value)
 
743
**    NULL       INTEGER    (nCol args)    INSERT (incl. rowid value)
 
744
**
 
745
*/
 
746
int echoUpdate(
 
747
  sqlite3_vtab *tab, 
 
748
  int nData, 
 
749
  sqlite3_value **apData, 
 
750
  sqlite_int64 *pRowid
 
751
){
 
752
  echo_vtab *pVtab = (echo_vtab *)tab;
 
753
  sqlite3 *db = pVtab->db;
 
754
  int rc = SQLITE_OK;
 
755
 
 
756
  sqlite3_stmt *pStmt;
 
757
  char *z = 0;               /* SQL statement to execute */
 
758
  int bindArgZero = 0;       /* True to bind apData[0] to sql var no. nData */
 
759
  int bindArgOne = 0;        /* True to bind apData[1] to sql var no. 1 */
 
760
  int i;                     /* Counter variable used by for loops */
 
761
 
 
762
  assert( nData==pVtab->nCol+2 || nData==1 );
 
763
 
 
764
  /* If apData[0] is an integer and nData>1 then do an UPDATE */
 
765
  if( nData>1 && sqlite3_value_type(apData[0])==SQLITE_INTEGER ){
 
766
    char *zSep = " SET";
 
767
    z = sqlite3_mprintf("UPDATE %Q", pVtab->zTableName);
 
768
 
 
769
    bindArgOne = (apData[1] && sqlite3_value_type(apData[1])==SQLITE_INTEGER);
 
770
    bindArgZero = 1;
 
771
 
 
772
    if( bindArgOne ){
 
773
       string_concat(&z, " SET rowid=?1 ", 0);
 
774
       zSep = ",";
 
775
    }
 
776
    for(i=2; i<nData; i++){
 
777
      if( apData[i]==0 ) continue;
 
778
      string_concat(&z, sqlite3_mprintf(
 
779
          "%s %Q=?%d", zSep, pVtab->aCol[i-2], i), 1);
 
780
      zSep = ",";
 
781
    }
 
782
    string_concat(&z, sqlite3_mprintf(" WHERE rowid=?%d", nData), 0);
 
783
  }
 
784
 
 
785
  /* If apData[0] is an integer and nData==1 then do a DELETE */
 
786
  else if( nData==1 && sqlite3_value_type(apData[0])==SQLITE_INTEGER ){
 
787
    z = sqlite3_mprintf("DELETE FROM %Q WHERE rowid = ?1", pVtab->zTableName);
 
788
    bindArgZero = 1;
 
789
  }
 
790
 
 
791
  /* If the first argument is NULL and there are more than two args, INSERT */
 
792
  else if( nData>2 && sqlite3_value_type(apData[0])==SQLITE_NULL ){
 
793
    int ii;
 
794
    char *zInsert = 0;
 
795
    char *zValues = 0;
 
796
  
 
797
    zInsert = sqlite3_mprintf("INSERT INTO %Q (", pVtab->zTableName);
 
798
    if( sqlite3_value_type(apData[1])==SQLITE_INTEGER ){
 
799
      bindArgOne = 1;
 
800
      zValues = sqlite3_mprintf("?");
 
801
      string_concat(&zInsert, "rowid", 0);
 
802
    }
 
803
 
 
804
    assert((pVtab->nCol+2)==nData);
 
805
    for(ii=2; ii<nData; ii++){
 
806
      string_concat(&zInsert, 
 
807
          sqlite3_mprintf("%s%Q", zValues?", ":"", pVtab->aCol[ii-2]), 1);
 
808
      string_concat(&zValues, 
 
809
          sqlite3_mprintf("%s?%d", zValues?", ":"", ii), 1);
 
810
    }
 
811
 
 
812
    string_concat(&z, zInsert, 1);
 
813
    string_concat(&z, ") VALUES(", 0);
 
814
    string_concat(&z, zValues, 1);
 
815
    string_concat(&z, ")", 0);
 
816
  }
 
817
 
 
818
  /* Anything else is an error */
 
819
  else{
 
820
    assert(0);
 
821
    return SQLITE_ERROR;
 
822
  }
 
823
 
 
824
  rc = sqlite3_prepare(db, z, -1, &pStmt, 0);
 
825
  assert( rc!=SQLITE_OK || pStmt );
 
826
  sqlite3_free(z);
 
827
  if( rc==SQLITE_OK ) {
 
828
    if( bindArgZero ){
 
829
      sqlite3_bind_value(pStmt, nData, apData[0]);
 
830
    }
 
831
    if( bindArgOne ){
 
832
      sqlite3_bind_value(pStmt, 1, apData[1]);
 
833
    }
 
834
    for(i=2; i<nData; i++){
 
835
      if( apData[i] ) sqlite3_bind_value(pStmt, i, apData[i]);
 
836
    }
 
837
    sqlite3_step(pStmt);
 
838
    rc = sqlite3_finalize(pStmt);
 
839
  }
 
840
 
 
841
  if( pRowid && rc==SQLITE_OK ){
 
842
    *pRowid = sqlite3_last_insert_rowid(db);
 
843
  }
 
844
 
 
845
  return rc;
 
846
}
 
847
 
 
848
/*
 
849
** xBegin, xSync, xCommit and xRollback callbacks for echo module
 
850
** virtual tables. Do nothing other than add the name of the callback
 
851
** to the $::echo_module Tcl variable.
 
852
*/
 
853
static int echoTransactionCall(sqlite3_vtab *tab, const char *zCall){
 
854
  char *z;
 
855
  echo_vtab *pVtab = (echo_vtab *)tab;
 
856
  z = sqlite3_mprintf("echo(%s)", pVtab->zTableName);
 
857
  appendToEchoModule(pVtab->interp, zCall);
 
858
  appendToEchoModule(pVtab->interp, z);
 
859
  sqlite3_free(z);
 
860
  return SQLITE_OK;
 
861
}
 
862
static int echoBegin(sqlite3_vtab *tab){
 
863
  echo_vtab *pVtab = (echo_vtab *)tab;
 
864
  Tcl_Interp *interp = pVtab->interp;
 
865
  const char *zVal; 
 
866
 
 
867
  echoTransactionCall(tab, "xBegin");
 
868
 
 
869
  /* Check if the $::echo_module_begin_fail variable is defined. If it is,
 
870
  ** and it is set to the name of the real table underlying this virtual
 
871
  ** echo module table, then cause this xSync operation to fail.
 
872
  */
 
873
  zVal = Tcl_GetVar(interp, "echo_module_begin_fail", TCL_GLOBAL_ONLY);
 
874
  if( zVal && 0==strcmp(zVal, pVtab->zTableName) ){
 
875
    return SQLITE_ERROR;
 
876
  }
 
877
  return SQLITE_OK;
 
878
}
 
879
static int echoSync(sqlite3_vtab *tab){
 
880
  echo_vtab *pVtab = (echo_vtab *)tab;
 
881
  Tcl_Interp *interp = pVtab->interp;
 
882
  const char *zVal; 
 
883
 
 
884
  echoTransactionCall(tab, "xSync");
 
885
 
 
886
  /* Check if the $::echo_module_sync_fail variable is defined. If it is,
 
887
  ** and it is set to the name of the real table underlying this virtual
 
888
  ** echo module table, then cause this xSync operation to fail.
 
889
  */
 
890
  zVal = Tcl_GetVar(interp, "echo_module_sync_fail", TCL_GLOBAL_ONLY);
 
891
  if( zVal && 0==strcmp(zVal, pVtab->zTableName) ){
 
892
    return -1;
 
893
  }
 
894
  return SQLITE_OK;
 
895
}
 
896
static int echoCommit(sqlite3_vtab *tab){
 
897
  return echoTransactionCall(tab, "xCommit");
 
898
}
 
899
static int echoRollback(sqlite3_vtab *tab){
 
900
  return echoTransactionCall(tab, "xRollback");
 
901
}
 
902
 
 
903
/*
 
904
** Implementation of "GLOB" function on the echo module.  Pass
 
905
** all arguments to the ::echo_glob_overload procedure of TCL
 
906
** and return the result of that procedure as a string.
 
907
*/
 
908
static void overloadedGlobFunction(
 
909
  sqlite3_context *pContext,
 
910
  int nArg,
 
911
  sqlite3_value **apArg
 
912
){
 
913
  Tcl_Interp *interp = sqlite3_user_data(pContext);
 
914
  Tcl_DString str;
 
915
  int i;
 
916
  int rc;
 
917
  Tcl_DStringInit(&str);
 
918
  Tcl_DStringAppendElement(&str, "::echo_glob_overload");
 
919
  for(i=0; i<nArg; i++){
 
920
    Tcl_DStringAppendElement(&str, (char*)sqlite3_value_text(apArg[i]));
 
921
  }
 
922
  rc = Tcl_Eval(interp, Tcl_DStringValue(&str));
 
923
  Tcl_DStringFree(&str);
 
924
  if( rc ){
 
925
    sqlite3_result_error(pContext, Tcl_GetStringResult(interp), -1);
 
926
  }else{
 
927
    sqlite3_result_text(pContext, Tcl_GetStringResult(interp),
 
928
                        -1, SQLITE_TRANSIENT);
 
929
  }
 
930
  Tcl_ResetResult(interp);
 
931
}
 
932
 
 
933
/*
 
934
** This is the xFindFunction implementation for the echo module.
 
935
** SQLite calls this routine when the first argument of a function
 
936
** is a column of an echo virtual table.  This routine can optionally
 
937
** override the implementation of that function.  It will choose to
 
938
** do so if the function is named "glob", and a TCL command named
 
939
** ::echo_glob_overload exists.
 
940
*/
 
941
static int echoFindFunction(
 
942
  sqlite3_vtab *vtab,
 
943
  int nArg,
 
944
  const char *zFuncName,
 
945
  void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
 
946
  void **ppArg
 
947
){
 
948
  echo_vtab *pVtab = (echo_vtab *)vtab;
 
949
  Tcl_Interp *interp = pVtab->interp;
 
950
  Tcl_CmdInfo info;
 
951
  if( strcmp(zFuncName,"glob")!=0 ){
 
952
    return 0;
 
953
  }
 
954
  if( Tcl_GetCommandInfo(interp, "::echo_glob_overload", &info)==0 ){
 
955
    return 0;
 
956
  }
 
957
  *pxFunc = overloadedGlobFunction;
 
958
  *ppArg = interp;
 
959
  return 1;
 
960
}
 
961
 
 
962
/*
 
963
** A virtual table module that merely "echos" the contents of another
 
964
** table (like an SQL VIEW).
 
965
*/
 
966
static sqlite3_module echoModule = {
 
967
  0,                         /* iVersion */
 
968
  echoCreate,
 
969
  echoConnect,
 
970
  echoBestIndex,
 
971
  echoDisconnect, 
 
972
  echoDestroy,
 
973
  echoOpen,                  /* xOpen - open a cursor */
 
974
  echoClose,                 /* xClose - close a cursor */
 
975
  echoFilter,                /* xFilter - configure scan constraints */
 
976
  echoNext,                  /* xNext - advance a cursor */
 
977
  echoEof,                   /* xEof */
 
978
  echoColumn,                /* xColumn - read data */
 
979
  echoRowid,                 /* xRowid - read data */
 
980
  echoUpdate,                /* xUpdate - write data */
 
981
  echoBegin,                 /* xBegin - begin transaction */
 
982
  echoSync,                  /* xSync - sync transaction */
 
983
  echoCommit,                /* xCommit - commit transaction */
 
984
  echoRollback,              /* xRollback - rollback transaction */
 
985
  echoFindFunction,          /* xFindFunction - function overloading */
 
986
};
 
987
 
 
988
/*
 
989
** Decode a pointer to an sqlite3 object.
 
990
*/
 
991
static int getDbPointer(Tcl_Interp *interp, const char *zA, sqlite3 **ppDb){
 
992
  *ppDb = (sqlite3*)sqlite3TextToPtr(zA);
 
993
  return TCL_OK;
 
994
}
 
995
 
 
996
/*
 
997
** Register the echo virtual table module.
 
998
*/
 
999
static int register_echo_module(
 
1000
  ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
 
1001
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
 
1002
  int objc,              /* Number of arguments */
 
1003
  Tcl_Obj *CONST objv[]  /* Command arguments */
 
1004
){
 
1005
  sqlite3 *db;
 
1006
  if( objc!=2 ){
 
1007
    Tcl_WrongNumArgs(interp, 1, objv, "DB");
 
1008
    return TCL_ERROR;
 
1009
  }
 
1010
  if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
 
1011
  sqlite3_create_module(db, "echo", &echoModule, (void *)interp);
 
1012
  return TCL_OK;
 
1013
}
 
1014
 
 
1015
/*
 
1016
** Tcl interface to sqlite3_declare_vtab, invoked as follows from Tcl:
 
1017
**
 
1018
** sqlite3_declare_vtab DB SQL
 
1019
*/
 
1020
static int declare_vtab(
 
1021
  ClientData clientData, /* Pointer to sqlite3_enable_XXX function */
 
1022
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
 
1023
  int objc,              /* Number of arguments */
 
1024
  Tcl_Obj *CONST objv[]  /* Command arguments */
 
1025
){
 
1026
  sqlite3 *db;
 
1027
  int rc;
 
1028
  if( objc!=3 ){
 
1029
    Tcl_WrongNumArgs(interp, 1, objv, "DB SQL");
 
1030
    return TCL_ERROR;
 
1031
  }
 
1032
  if( getDbPointer(interp, Tcl_GetString(objv[1]), &db) ) return TCL_ERROR;
 
1033
  rc = sqlite3_declare_vtab(db, Tcl_GetString(objv[2]));
 
1034
  if( rc!=SQLITE_OK ){
 
1035
    Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE);
 
1036
    return TCL_ERROR;
 
1037
  }
 
1038
  return TCL_OK;
 
1039
}
 
1040
 
 
1041
#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
 
1042
 
 
1043
/*
 
1044
** Register commands with the TCL interpreter.
 
1045
*/
 
1046
int Sqlitetest8_Init(Tcl_Interp *interp){
 
1047
  static struct {
 
1048
     char *zName;
 
1049
     Tcl_ObjCmdProc *xProc;
 
1050
     void *clientData;
 
1051
  } aObjCmd[] = {
 
1052
#ifndef SQLITE_OMIT_VIRTUALTABLE
 
1053
     { "register_echo_module",   register_echo_module, 0 },
 
1054
     { "sqlite3_declare_vtab",   declare_vtab, 0 },
 
1055
#endif
 
1056
  };
 
1057
  int i;
 
1058
  for(i=0; i<sizeof(aObjCmd)/sizeof(aObjCmd[0]); i++){
 
1059
    Tcl_CreateObjCommand(interp, aObjCmd[i].zName, 
 
1060
        aObjCmd[i].xProc, aObjCmd[i].clientData, 0);
 
1061
  }
 
1062
  return TCL_OK;
 
1063
}