SQLite4
Check-in [29390891c5]
Not logged in

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

Overview
Comment:Merge trunk changes into this branch.
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | read-only-clients
Files: files | file ages | folders
SHA1: 29390891c5133a83adc63a64b57e326f819bf305
User & Date: dan 2013-02-17 14:19:58
Context
2013-02-18
19:46
Add support for read-only clients reading from dormant databases using the checkpointer lock. check-in: 45e4472618 user: dan tags: read-only-clients
2013-02-17
14:19
Merge trunk changes into this branch. check-in: 29390891c5 user: dan tags: read-only-clients
2013-02-16
02:41
Fix an unsafe VM register deallocation. check-in: e9ec757186 user: drh tags: trunk
2013-02-09
19:42
Add definitions for the extra locks required for read-only clients to detect whether or not a database is live. check-in: 69f33cfa12 user: dan tags: read-only-clients
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Changes to src/alter.c.

75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
...
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
...
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
        len = sqlite4GetToken(zCsr, &token);
      } while( token==TK_SPACE );
      assert( len>0 );
    } while( token!=TK_LP && token!=TK_USING );

    zRet = sqlite4MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql, 
       zTableName, tname.z+tname.n);
    sqlite4_result_text(context, zRet, -1, SQLITE4_TRANSIENT);
    sqlite4DbFree(db, zRet);
  }
}

/*
** This C function implements an SQL user function that is used by SQL code
** generated by the ALTER TABLE ... RENAME command to modify the definition
................................................................................
        zInput = &z[n];
      }
      sqlite4DbFree(db, zParent);
    }
  }

  zResult = sqlite4MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput), 
  sqlite4_result_text(context, zResult, -1, SQLITE4_TRANSIENT);
  sqlite4DbFree(db, zOutput);
  sqlite4DbFree(db, zResult);
}
#endif

#ifndef SQLITE4_OMIT_TRIGGER
/* This function is used by SQL generated to implement the
................................................................................
    } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );

    /* Variable tname now contains the token that is the old table-name
    ** in the CREATE TRIGGER statement.
    */
    zRet = sqlite4MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql, 
       zTableName, tname.z+tname.n);
    sqlite4_result_text(context, zRet, -1, SQLITE4_TRANSIENT);
    sqlite4DbFree(db, zRet);
  }
}
#endif   /* !SQLITE4_OMIT_TRIGGER */

/*
** Register built-in functions used to help implement ALTER TABLE







|







 







|







 







|







75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
...
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
...
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
        len = sqlite4GetToken(zCsr, &token);
      } while( token==TK_SPACE );
      assert( len>0 );
    } while( token!=TK_LP && token!=TK_USING );

    zRet = sqlite4MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql, 
       zTableName, tname.z+tname.n);
    sqlite4_result_text(context, zRet, -1, SQLITE4_TRANSIENT, 0);
    sqlite4DbFree(db, zRet);
  }
}

/*
** This C function implements an SQL user function that is used by SQL code
** generated by the ALTER TABLE ... RENAME command to modify the definition
................................................................................
        zInput = &z[n];
      }
      sqlite4DbFree(db, zParent);
    }
  }

  zResult = sqlite4MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput), 
  sqlite4_result_text(context, zResult, -1, SQLITE4_TRANSIENT, 0);
  sqlite4DbFree(db, zOutput);
  sqlite4DbFree(db, zResult);
}
#endif

#ifndef SQLITE4_OMIT_TRIGGER
/* This function is used by SQL generated to implement the
................................................................................
    } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );

    /* Variable tname now contains the token that is the old table-name
    ** in the CREATE TRIGGER statement.
    */
    zRet = sqlite4MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql, 
       zTableName, tname.z+tname.n);
    sqlite4_result_text(context, zRet, -1, SQLITE4_TRANSIENT, 0);
    sqlite4DbFree(db, zRet);
  }
}
#endif   /* !SQLITE4_OMIT_TRIGGER */

/*
** Register built-in functions used to help implement ALTER TABLE

Changes to src/attach.c.

239
240
241
242
243
244
245


246
247
248
249
250
251
252
  if( pDb->pKV->iTransLevel ){
    sqlite4_snprintf(zErr,sizeof(zErr), "database %s is locked", zName);
    goto detach_error;
  }

  sqlite4KVStoreClose(pDb->pKV);
  pDb->pKV = 0;


  pDb->pSchema = 0;
  sqlite4ResetInternalSchema(db, -1);
  return;

detach_error:
  sqlite4_result_error(context, zErr, -1);
}







>
>







239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
  if( pDb->pKV->iTransLevel ){
    sqlite4_snprintf(zErr,sizeof(zErr), "database %s is locked", zName);
    goto detach_error;
  }

  sqlite4KVStoreClose(pDb->pKV);
  pDb->pKV = 0;
  sqlite4SchemaClear(db->pEnv, pDb->pSchema);
  sqlite4DbFree(db, pDb->pSchema);
  pDb->pSchema = 0;
  sqlite4ResetInternalSchema(db, -1);
  return;

detach_error:
  sqlite4_result_error(context, zErr, -1);
}

Changes to src/callback.c.

28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
    db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
    sqlite4DbFree(db, zExternal);
  }
#ifndef SQLITE4_OMIT_UTF16
  if( db->xCollNeeded16 ){
    char const *zExternal;
    sqlite4_value *pTmp = sqlite4ValueNew(db);
    sqlite4ValueSetStr(pTmp, -1, zName, SQLITE4_UTF8, SQLITE4_STATIC);
    zExternal = sqlite4ValueText(pTmp, SQLITE4_UTF16NATIVE);
    if( zExternal ){
      db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
    }
    sqlite4ValueFree(pTmp);
  }
#endif







|







28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
    db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
    sqlite4DbFree(db, zExternal);
  }
#ifndef SQLITE4_OMIT_UTF16
  if( db->xCollNeeded16 ){
    char const *zExternal;
    sqlite4_value *pTmp = sqlite4ValueNew(db);
    sqlite4ValueSetStr(pTmp, -1, zName, SQLITE4_UTF8, SQLITE4_STATIC, 0);
    zExternal = sqlite4ValueText(pTmp, SQLITE4_UTF16NATIVE);
    if( zExternal ){
      db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
    }
    sqlite4ValueFree(pTmp);
  }
#endif

Changes to src/complete.c.

265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
  int rc = SQLITE4_NOMEM;

#ifndef SQLITE4_OMIT_AUTOINIT
  rc = sqlite4_initialize(0);
  if( rc ) return rc;
#endif
  pVal = sqlite4ValueNew(0);
  sqlite4ValueSetStr(pVal, -1, zSql, SQLITE4_UTF16NATIVE, SQLITE4_STATIC);
  zSql8 = sqlite4ValueText(pVal, SQLITE4_UTF8);
  if( zSql8 ){
    rc = sqlite4_complete(zSql8);
  }else{
    rc = SQLITE4_NOMEM;
  }
  sqlite4ValueFree(pVal);
  return sqlite4ApiExit(0, rc);
}
#endif /* SQLITE4_OMIT_UTF16 */
#endif /* SQLITE4_OMIT_COMPLETE */







|











265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
  int rc = SQLITE4_NOMEM;

#ifndef SQLITE4_OMIT_AUTOINIT
  rc = sqlite4_initialize(0);
  if( rc ) return rc;
#endif
  pVal = sqlite4ValueNew(0);
  sqlite4ValueSetStr(pVal, -1, zSql, SQLITE4_UTF16NATIVE, SQLITE4_STATIC, 0);
  zSql8 = sqlite4ValueText(pVal, SQLITE4_UTF8);
  if( zSql8 ){
    rc = sqlite4_complete(zSql8);
  }else{
    rc = SQLITE4_NOMEM;
  }
  sqlite4ValueFree(pVal);
  return sqlite4ApiExit(0, rc);
}
#endif /* SQLITE4_OMIT_UTF16 */
#endif /* SQLITE4_OMIT_COMPLETE */

Changes to src/date.c.

810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
...
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
...
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
...
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
....
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
){
  DateTime x;
  if( isDate(context, argc, argv, &x)==0 ){
    char zBuf[100];
    computeYMD_HMS(&x);
    sqlite4_snprintf(zBuf,sizeof(zBuf), "%04d-%02d-%02d %02d:%02d:%02d",
                     x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
    sqlite4_result_text(context, zBuf, -1, SQLITE4_TRANSIENT);
  }
}

/*
**    time( TIMESTRING, MOD, MOD, ...)
**
** Return HH:MM:SS
................................................................................
  sqlite4_value **argv
){
  DateTime x;
  if( isDate(context, argc, argv, &x)==0 ){
    char zBuf[100];
    computeHMS(&x);
    sqlite4_snprintf(zBuf,sizeof(zBuf), "%02d:%02d:%02d", x.h, x.m, (int)x.s);
    sqlite4_result_text(context, zBuf, -1, SQLITE4_TRANSIENT);
  }
}

/*
**    date( TIMESTRING, MOD, MOD, ...)
**
** Return YYYY-MM-DD
................................................................................
  sqlite4_value **argv
){
  DateTime x;
  if( isDate(context, argc, argv, &x)==0 ){
    char zBuf[100];
    computeYMD(&x);
    sqlite4_snprintf(zBuf,sizeof(zBuf), "%04d-%02d-%02d", x.Y, x.M, x.D);
    sqlite4_result_text(context, zBuf, -1, SQLITE4_TRANSIENT);
  }
}

/*
**    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
**
** Return a string described by FORMAT.  Conversions as follows:
................................................................................
        }
        default:   z[j++] = '%'; break;
      }
    }
  }
  z[j] = 0;
  sqlite4_result_text(context, z, -1,
                      z==zBuf ? SQLITE4_TRANSIENT : SQLITE4_DYNAMIC);
}

/*
** current_time()
**
** This function returns the same value as time('now').
*/
................................................................................
  sqlite4_mutex_enter(sqlite4MutexAlloc(SQLITE4_MUTEX_STATIC_MASTER));
  pTm = gmtime(&t);
  if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
  sqlite4_mutex_leave(sqlite4MutexAlloc(SQLITE4_MUTEX_STATIC_MASTER));
#endif
  if( pTm ){
    strftime(zBuf, 20, zFormat, &sNow);
    sqlite4_result_text(context, zBuf, -1, SQLITE4_TRANSIENT);
  }
}
#endif

/*
** This function registered all of the above C functions as SQL
** functions.  This should be the only routine in this file with







|







 







|







 







|







 







|







 







|







810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
...
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
...
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
...
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
....
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
){
  DateTime x;
  if( isDate(context, argc, argv, &x)==0 ){
    char zBuf[100];
    computeYMD_HMS(&x);
    sqlite4_snprintf(zBuf,sizeof(zBuf), "%04d-%02d-%02d %02d:%02d:%02d",
                     x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
    sqlite4_result_text(context, zBuf, -1, SQLITE4_TRANSIENT, 0);
  }
}

/*
**    time( TIMESTRING, MOD, MOD, ...)
**
** Return HH:MM:SS
................................................................................
  sqlite4_value **argv
){
  DateTime x;
  if( isDate(context, argc, argv, &x)==0 ){
    char zBuf[100];
    computeHMS(&x);
    sqlite4_snprintf(zBuf,sizeof(zBuf), "%02d:%02d:%02d", x.h, x.m, (int)x.s);
    sqlite4_result_text(context, zBuf, -1, SQLITE4_TRANSIENT, 0);
  }
}

/*
**    date( TIMESTRING, MOD, MOD, ...)
**
** Return YYYY-MM-DD
................................................................................
  sqlite4_value **argv
){
  DateTime x;
  if( isDate(context, argc, argv, &x)==0 ){
    char zBuf[100];
    computeYMD(&x);
    sqlite4_snprintf(zBuf,sizeof(zBuf), "%04d-%02d-%02d", x.Y, x.M, x.D);
    sqlite4_result_text(context, zBuf, -1, SQLITE4_TRANSIENT, 0);
  }
}

/*
**    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
**
** Return a string described by FORMAT.  Conversions as follows:
................................................................................
        }
        default:   z[j++] = '%'; break;
      }
    }
  }
  z[j] = 0;
  sqlite4_result_text(context, z, -1,
                      z==zBuf ? SQLITE4_TRANSIENT : SQLITE4_DYNAMIC, 0);
}

/*
** current_time()
**
** This function returns the same value as time('now').
*/
................................................................................
  sqlite4_mutex_enter(sqlite4MutexAlloc(SQLITE4_MUTEX_STATIC_MASTER));
  pTm = gmtime(&t);
  if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
  sqlite4_mutex_leave(sqlite4MutexAlloc(SQLITE4_MUTEX_STATIC_MASTER));
#endif
  if( pTm ){
    strftime(zBuf, 20, zFormat, &sNow);
    sqlite4_result_text(context, zBuf, -1, SQLITE4_TRANSIENT, 0);
  }
}
#endif

/*
** This function registered all of the above C functions as SQL
** functions.  This should be the only routine in this file with

Changes to src/expr.c.

362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
...
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
** for this node and for the pToken argument is a single allocation
** obtained from sqlite4DbMalloc().  The calling function
** is responsible for making sure the node eventually gets freed.
**
** If dequote is true, then the token (if it exists) is dequoted.
** If dequote is false, no dequoting is performance.  The deQuote
** parameter is ignored if pToken is NULL or if the token does not
** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
** then the EP_DblQuoted flag is set on the expression node.
**
** Special case:  If op==TK_INTEGER and pToken points to a string that
** can be translated into a 32-bit integer, then the token is not
** stored in u.zToken.  Instead, the integer values is written
** into u.iValue and the EP_IntValue flag is set.  No extra storage
** is allocated to hold the integer text and the dequote flag is ignored.
*/
................................................................................
      }else{
        int c;
        pNew->u.zToken = (char*)&pNew[1];
        assert( pToken->z!=0 || pToken->n==0 );
        if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
        pNew->u.zToken[pToken->n] = 0;
        if( dequote && nExtra>=3 
             && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
          sqlite4Dequote(pNew->u.zToken);
          if( c=='"' ) pNew->flags |= EP_DblQuoted;
        }
      }
    }
#if SQLITE4_MAX_EXPR_DEPTH>0
    pNew->nHeight = 1;
#endif  
  }







|
<







 







|

<







362
363
364
365
366
367
368
369

370
371
372
373
374
375
376
...
402
403
404
405
406
407
408
409
410

411
412
413
414
415
416
417
** for this node and for the pToken argument is a single allocation
** obtained from sqlite4DbMalloc().  The calling function
** is responsible for making sure the node eventually gets freed.
**
** If dequote is true, then the token (if it exists) is dequoted.
** If dequote is false, no dequoting is performance.  The deQuote
** parameter is ignored if pToken is NULL or if the token does not
** appear to be quoted.

**
** Special case:  If op==TK_INTEGER and pToken points to a string that
** can be translated into a 32-bit integer, then the token is not
** stored in u.zToken.  Instead, the integer values is written
** into u.iValue and the EP_IntValue flag is set.  No extra storage
** is allocated to hold the integer text and the dequote flag is ignored.
*/
................................................................................
      }else{
        int c;
        pNew->u.zToken = (char*)&pNew[1];
        assert( pToken->z!=0 || pToken->n==0 );
        if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
        pNew->u.zToken[pToken->n] = 0;
        if( dequote && nExtra>=3 
             && ((c = pToken->z[0])=='\'' || c=='"' || c=='[') ){
          sqlite4Dequote(pNew->u.zToken);

        }
      }
    }
#if SQLITE4_MAX_EXPR_DEPTH>0
    pNew->nHeight = 1;
#endif  
  }

Changes to src/fts5.c.

3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
....
3419
3420
3421
3422
3423
3424
3425
3426
    if( zErr==0 ){
      zErr = sqlite4MPrintf(db, "error parsing expression: %d", rc);
    }
    goto fts5_parse_expr_out;
  }

  fts5PrintExpr(db, azCol, pExpr, &zRet);
  sqlite4_result_text(pCtx, zRet, -1, SQLITE4_TRANSIENT);
  fts5ExpressionFree(db, pExpr);
  sqlite4_free(sqlite4_db_env(db), zRet);

 fts5_parse_expr_out:
  if( p ) pTok->xDestroy(p);
  sqlite4DbFree(db, azCol);
  sqlite4_finalize(pStmt);
................................................................................
  int rc = sqlite4_create_function(
      db, "fts5_parse_expr", 3, SQLITE4_UTF8, 0, fts5_parse_expr, 0, 0
  );
  if( rc!=SQLITE4_OK ) return rc;
#endif
  return sqlite4InitFts5Func(db);
}








|







 







<
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
....
3419
3420
3421
3422
3423
3424
3425

    if( zErr==0 ){
      zErr = sqlite4MPrintf(db, "error parsing expression: %d", rc);
    }
    goto fts5_parse_expr_out;
  }

  fts5PrintExpr(db, azCol, pExpr, &zRet);
  sqlite4_result_text(pCtx, zRet, -1, SQLITE4_TRANSIENT, 0);
  fts5ExpressionFree(db, pExpr);
  sqlite4_free(sqlite4_db_env(db), zRet);

 fts5_parse_expr_out:
  if( p ) pTok->xDestroy(p);
  sqlite4DbFree(db, azCol);
  sqlite4_finalize(pStmt);
................................................................................
  int rc = sqlite4_create_function(
      db, "fts5_parse_expr", 3, SQLITE4_UTF8, 0, fts5_parse_expr, 0, 0
  );
  if( rc!=SQLITE4_OK ) return rc;
#endif
  return sqlite4InitFts5Func(db);
}

Changes to src/fts5func.c.

45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
...
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
...
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
...
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
...
666
667
668
669
670
671
672
673
struct Fts5RankCtx {
  sqlite4 *db;
  double *aAvgdl;                 /* Average document size of each field */
  int nPhrase;                    /* Number of phrases in query */
  double *aIdf;                   /* IDF weights for each phrase in query */
};

static void fts5RankFreeCtx(void *pCtx){
  if( pCtx ){
    Fts5RankCtx *p = (Fts5RankCtx *)pCtx;
    sqlite4DbFree(p->db, p);
  }
}

#define BM25_EXPLAIN  0x01
................................................................................
  if( p==0 ){
    int nPhrase;                  /* Number of phrases in query expression */
    int nByte;                    /* Number of bytes of data to allocate */

    sqlite4_mi_phrase_count(pCtx, &nPhrase);
    nByte = sizeof(Fts5RankCtx) + (nPhrase+nField) * sizeof(double);
    p = (Fts5RankCtx *)sqlite4DbMallocZero(db, nByte);
    sqlite4_set_auxdata(pCtx, 0, (void *)p, fts5RankFreeCtx);
    p = sqlite4_get_auxdata(pCtx, 0);

    if( !p ){
      rc = SQLITE4_NOMEM;
    }else{
      int N;                      /* Total number of docs in collection */
      int ni;                     /* Number of docs with phrase i */
................................................................................
  }

  if( rc==SQLITE4_OK ){
    if( bExplain ){
      zExplain = sqlite4MAppendf(
          db, zExplain, "%s</table><b>overall rank=%.2f</b>", zExplain, rank
      );
      sqlite4_result_text(pCtx, zExplain, -1, SQLITE4_TRANSIENT);
    }else{
      sqlite4_result_double(pCtx, rank);
    }
  }else{
    sqlite4_result_error_code(pCtx, rc);
  }
  sqlite4DbFree(db, zExplain);
................................................................................
        if( rc==SQLITE4_OK ){
          fts5SnippetImprove(pCtx, nTok, nSz, &aSnip[i]);
          rc = fts5SnippetText(
              pCtx, &aSnip[i], &text, nTok, zStart, zEnd, zEllipses
          );
        }
      }
      sqlite4_result_text(pCtx, text.zOut, text.nOut, SQLITE4_TRANSIENT);
      sqlite4DbFree(sqlite4_context_db_handle(pCtx), text.zOut);
      break;
    }
  }

  if( rc!=SQLITE4_OK ){
    sqlite4_result_error_code(pCtx, rc);
................................................................................
    void *p = SQLITE4_INT_TO_PTR(aRank[i].mask);
    const char *z = aRank[i].zName;
    rc = sqlite4_create_mi_function(db, z, -1, SQLITE4_UTF8, p, fts5Rank, 0);
  }

  return rc;
}








|







 







|







 







|







 







|







 







<
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
...
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
...
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
...
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
...
666
667
668
669
670
671
672

struct Fts5RankCtx {
  sqlite4 *db;
  double *aAvgdl;                 /* Average document size of each field */
  int nPhrase;                    /* Number of phrases in query */
  double *aIdf;                   /* IDF weights for each phrase in query */
};

static void fts5RankFreeCtx(void *pNotUsed, void *pCtx){
  if( pCtx ){
    Fts5RankCtx *p = (Fts5RankCtx *)pCtx;
    sqlite4DbFree(p->db, p);
  }
}

#define BM25_EXPLAIN  0x01
................................................................................
  if( p==0 ){
    int nPhrase;                  /* Number of phrases in query expression */
    int nByte;                    /* Number of bytes of data to allocate */

    sqlite4_mi_phrase_count(pCtx, &nPhrase);
    nByte = sizeof(Fts5RankCtx) + (nPhrase+nField) * sizeof(double);
    p = (Fts5RankCtx *)sqlite4DbMallocZero(db, nByte);
    sqlite4_set_auxdata(pCtx, 0, (void *)p, fts5RankFreeCtx, 0);
    p = sqlite4_get_auxdata(pCtx, 0);

    if( !p ){
      rc = SQLITE4_NOMEM;
    }else{
      int N;                      /* Total number of docs in collection */
      int ni;                     /* Number of docs with phrase i */
................................................................................
  }

  if( rc==SQLITE4_OK ){
    if( bExplain ){
      zExplain = sqlite4MAppendf(
          db, zExplain, "%s</table><b>overall rank=%.2f</b>", zExplain, rank
      );
      sqlite4_result_text(pCtx, zExplain, -1, SQLITE4_TRANSIENT, 0);
    }else{
      sqlite4_result_double(pCtx, rank);
    }
  }else{
    sqlite4_result_error_code(pCtx, rc);
  }
  sqlite4DbFree(db, zExplain);
................................................................................
        if( rc==SQLITE4_OK ){
          fts5SnippetImprove(pCtx, nTok, nSz, &aSnip[i]);
          rc = fts5SnippetText(
              pCtx, &aSnip[i], &text, nTok, zStart, zEnd, zEllipses
          );
        }
      }
      sqlite4_result_text(pCtx, text.zOut, text.nOut, SQLITE4_TRANSIENT, 0);
      sqlite4DbFree(sqlite4_context_db_handle(pCtx), text.zOut);
      break;
    }
  }

  if( rc!=SQLITE4_OK ){
    sqlite4_result_error_code(pCtx, rc);
................................................................................
    void *p = SQLITE4_INT_TO_PTR(aRank[i].mask);
    const char *z = aRank[i].zName;
    rc = sqlite4_create_mi_function(db, z, -1, SQLITE4_UTF8, p, fts5Rank, 0);
  }

  return rc;
}

Changes to src/func.c.

71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
...
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
...
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
...
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
...
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
...
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
...
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
...
826
827
828
829
830
831
832
833

834
835
836
837
838
839
840
...
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
...
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
...
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
....
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
....
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
....
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
....
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
  switch( sqlite4_value_type(argv[0]) ){
    case SQLITE4_INTEGER: z = "integer"; break;
    case SQLITE4_TEXT:    z = "text";    break;
    case SQLITE4_FLOAT:   z = "real";    break;
    case SQLITE4_BLOB:    z = "blob";    break;
    default:             z = "null";    break;
  }
  sqlite4_result_text(context, z, -1, SQLITE4_STATIC);
}


/*
** Implementation of the length() function
*/
static void lengthFunc(
................................................................................
    while( *z && p1 ){
      SQLITE4_SKIP_UTF8(z);
      p1--;
    }
    for(z2=z; *z2 && p2; p2--){
      SQLITE4_SKIP_UTF8(z2);
    }
    sqlite4_result_text(context, (char*)z, (int)(z2-z), SQLITE4_TRANSIENT);
  }else{
    if( p1+p2>len ){
      p2 = len-p1;
      if( p2<0 ) p2 = 0;
    }
    sqlite4_result_blob(context, (char*)&z[p1], (int)p2, SQLITE4_TRANSIENT);
  }
}

/*
** Implementation of the round() function
*/
#ifndef SQLITE4_OMIT_FLOATING_POINT
................................................................................
  assert( z2==(char*)sqlite4_value_text(argv[0]) );
  if( z2 ){
    z1 = contextMalloc(context, ((i64)n)+1);
    if( z1 ){
      for(i=0; i<n; i++){
        z1[i] = (char)sqlite4Toupper(z2[i]);
      }
      sqlite4_result_text(context, z1, n, SQLITE4_DYNAMIC);
    }
  }
}
static void lowerFunc(sqlite4_context *context, int argc, sqlite4_value **argv){
  char *z1;
  const char *z2;
  int i, n;
................................................................................
  assert( z2==(char*)sqlite4_value_text(argv[0]) );
  if( z2 ){
    z1 = contextMalloc(context, ((i64)n)+1);
    if( z1 ){
      for(i=0; i<n; i++){
        z1[i] = sqlite4Tolower(z2[i]);
      }
      sqlite4_result_text(context, z1, n, SQLITE4_DYNAMIC);
    }
  }
}


#if 0  /* This function is never used. */
/*
................................................................................
  n = sqlite4_value_int(argv[0]);
  if( n<1 ){
    n = 1;
  }
  p = contextMalloc(context, n);
  if( p ){
    sqlite4_randomness(sqlite4_context_env(context), n, p);
    sqlite4_result_blob(context, (char*)p, n, SQLITE4_DYNAMIC);
  }
}

/*
** Implementation of the last_insert_rowid() SQL function.  The return
** value is the same as the sqlite4_last_insert_rowid() API function.
*/
................................................................................
  sqlite4_context *context,
  int NotUsed,
  sqlite4_value **NotUsed2
){
  UNUSED_PARAMETER2(NotUsed, NotUsed2);
  /* IMP: R-48699-48617 This function is an SQL wrapper around the
  ** sqlite4_libversion() C-interface. */
  sqlite4_result_text(context, sqlite4_libversion(), -1, SQLITE4_STATIC);
}

/*
** Implementation of the sqlite_source_id() function. The result is a string
** that identifies the particular version of the source code used to build
** SQLite.
*/
................................................................................
  sqlite4_context *context,
  int NotUsed,
  sqlite4_value **NotUsed2
){
  UNUSED_PARAMETER2(NotUsed, NotUsed2);
  /* IMP: R-24470-31136 This function is an SQL wrapper around the
  ** sqlite4_sourceid() C interface. */
  sqlite4_result_text(context, sqlite4_sourceid(), -1, SQLITE4_STATIC);
}

/*
** Implementation of the sqlite_log() function.  This is a wrapper around
** sqlite4_log().  The return value is NULL.  The function exists purely for
** its side-effects.
*/
................................................................................
  int n;
  assert( argc==1 );
  UNUSED_PARAMETER(argc);
  /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
  ** is a wrapper around the sqlite4_compileoption_get() C/C++ function.
  */
  n = sqlite4_value_int(argv[0]);
  sqlite4_result_text(context, sqlite4_compileoption_get(n), -1, SQLITE4_STATIC);

}
#endif /* SQLITE4_OMIT_COMPILEOPTION_DIAGS */

/* Array for converting from half-bytes (nybbles) into ASCII hex
** digits. */
static const char hexdigits[] = {
  '0', '1', '2', '3', '4', '5', '6', '7',
................................................................................
          zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
          zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
        }
        zText[(nBlob*2)+2] = '\'';
        zText[(nBlob*2)+3] = '\0';
        zText[0] = 'x';
        zText[1] = '\'';
        sqlite4_result_text(context, zText, -1, SQLITE4_TRANSIENT);
        sqlite4_free(sqlite4_context_env(context), zText);
      }
      break;
    }
    case SQLITE4_TEXT: {
      int i,j;
      u64 n;
................................................................................
          z[j++] = zArg[i];
          if( zArg[i]=='\'' ){
            z[j++] = '\'';
          }
        }
        z[j++] = '\'';
        z[j] = 0;
        sqlite4_result_text(context, z, j, SQLITE4_DYNAMIC);
      }
      break;
    }
    default: {
      assert( sqlite4_value_type(argv[0])==SQLITE4_NULL );
      sqlite4_result_text(context, "NULL", 4, SQLITE4_STATIC);
      break;
    }
  }
}

/*
** The hex() function.  Interpret the argument as a blob.  Return
................................................................................
  if( zHex ){
    for(i=0; i<n; i++, pBlob++){
      unsigned char c = *pBlob;
      *(z++) = hexdigits[(c>>4)&0xf];
      *(z++) = hexdigits[c&0xf];
    }
    *z = 0;
    sqlite4_result_text(context, zHex, n*2, SQLITE4_DYNAMIC);
  }
}

/*
** The zeroblob(N) function returns a zero-filled blob of size N bytes.
*/
static void zeroblobFunc(
................................................................................
    }
  }
  assert( j+nStr-i+1==nOut );
  memcpy(&zOut[j], &zStr[i], nStr-i);
  j += nStr - i;
  assert( j<=nOut );
  zOut[j] = 0;
  sqlite4_result_text(context, (char*)zOut, j, SQLITE4_DYNAMIC);
}

/*
** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
*/
static void trimFunc(
................................................................................
        nIn -= len;
      }
    }
    if( zCharSet ){
      sqlite4_free(sqlite4_context_env(context), azChar);
    }
  }
  sqlite4_result_text(context, (char*)zIn, nIn, SQLITE4_TRANSIENT);
}


/* IMP: R-25361-16150 This function is omitted from SQLite by default. It
** is only available if the SQLITE4_SOUNDEX compile-time option is used
** when SQLite is built.
*/
................................................................................
        prevcode = 0;
      }
    }
    while( j<4 ){
      zResult[j++] = '0';
    }
    zResult[j] = 0;
    sqlite4_result_text(context, zResult, 4, SQLITE4_TRANSIENT);
  }else{
    /* IMP: R-64894-50321 The string "?000" is returned if the argument
    ** is NULL or contains no ASCII alphabetic characters. */
    sqlite4_result_text(context, "?000", 4, SQLITE4_STATIC);
  }
}
#endif /* SQLITE4_SOUNDEX */

#if 0 /*ndef SQLITE4_OMIT_LOAD_EXTENSION*/
/*
** A function that loads a shared-library extension then returns NULL.
................................................................................
  if( pAccum ){
    if( pAccum->tooBig ){
      sqlite4_result_error_toobig(context);
    }else if( pAccum->mallocFailed ){
      sqlite4_result_error_nomem(context);
    }else{    
      sqlite4_result_text(context, sqlite4StrAccumFinish(pAccum), -1, 
                          SQLITE4_DYNAMIC);
    }
  }
}

/*
** This routine does per-connection function registration.  Most
** of the built-in functions above are part of the global function set.







|







 







|





|







 







|







 







|







 







|







 







|







 







|







 







|
>







 







|







 







|





|







 







|







 







|







 







|







 







|



|







 







|







71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
...
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
...
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
...
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
...
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
...
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
...
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
...
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
...
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
...
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
...
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
....
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
....
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
....
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
....
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
  switch( sqlite4_value_type(argv[0]) ){
    case SQLITE4_INTEGER: z = "integer"; break;
    case SQLITE4_TEXT:    z = "text";    break;
    case SQLITE4_FLOAT:   z = "real";    break;
    case SQLITE4_BLOB:    z = "blob";    break;
    default:             z = "null";    break;
  }
  sqlite4_result_text(context, z, -1, SQLITE4_STATIC, 0);
}


/*
** Implementation of the length() function
*/
static void lengthFunc(
................................................................................
    while( *z && p1 ){
      SQLITE4_SKIP_UTF8(z);
      p1--;
    }
    for(z2=z; *z2 && p2; p2--){
      SQLITE4_SKIP_UTF8(z2);
    }
    sqlite4_result_text(context, (char*)z, (int)(z2-z), SQLITE4_TRANSIENT, 0);
  }else{
    if( p1+p2>len ){
      p2 = len-p1;
      if( p2<0 ) p2 = 0;
    }
    sqlite4_result_blob(context, (char*)&z[p1], (int)p2, SQLITE4_TRANSIENT, 0);
  }
}

/*
** Implementation of the round() function
*/
#ifndef SQLITE4_OMIT_FLOATING_POINT
................................................................................
  assert( z2==(char*)sqlite4_value_text(argv[0]) );
  if( z2 ){
    z1 = contextMalloc(context, ((i64)n)+1);
    if( z1 ){
      for(i=0; i<n; i++){
        z1[i] = (char)sqlite4Toupper(z2[i]);
      }
      sqlite4_result_text(context, z1, n, SQLITE4_DYNAMIC, 0);
    }
  }
}
static void lowerFunc(sqlite4_context *context, int argc, sqlite4_value **argv){
  char *z1;
  const char *z2;
  int i, n;
................................................................................
  assert( z2==(char*)sqlite4_value_text(argv[0]) );
  if( z2 ){
    z1 = contextMalloc(context, ((i64)n)+1);
    if( z1 ){
      for(i=0; i<n; i++){
        z1[i] = sqlite4Tolower(z2[i]);
      }
      sqlite4_result_text(context, z1, n, SQLITE4_DYNAMIC, 0);
    }
  }
}


#if 0  /* This function is never used. */
/*
................................................................................
  n = sqlite4_value_int(argv[0]);
  if( n<1 ){
    n = 1;
  }
  p = contextMalloc(context, n);
  if( p ){
    sqlite4_randomness(sqlite4_context_env(context), n, p);
    sqlite4_result_blob(context, (char*)p, n, SQLITE4_DYNAMIC, 0);
  }
}

/*
** Implementation of the last_insert_rowid() SQL function.  The return
** value is the same as the sqlite4_last_insert_rowid() API function.
*/
................................................................................
  sqlite4_context *context,
  int NotUsed,
  sqlite4_value **NotUsed2
){
  UNUSED_PARAMETER2(NotUsed, NotUsed2);
  /* IMP: R-48699-48617 This function is an SQL wrapper around the
  ** sqlite4_libversion() C-interface. */
  sqlite4_result_text(context, sqlite4_libversion(), -1, SQLITE4_STATIC, 0);
}

/*
** Implementation of the sqlite_source_id() function. The result is a string
** that identifies the particular version of the source code used to build
** SQLite.
*/
................................................................................
  sqlite4_context *context,
  int NotUsed,
  sqlite4_value **NotUsed2
){
  UNUSED_PARAMETER2(NotUsed, NotUsed2);
  /* IMP: R-24470-31136 This function is an SQL wrapper around the
  ** sqlite4_sourceid() C interface. */
  sqlite4_result_text(context, sqlite4_sourceid(), -1, SQLITE4_STATIC, 0);
}

/*
** Implementation of the sqlite_log() function.  This is a wrapper around
** sqlite4_log().  The return value is NULL.  The function exists purely for
** its side-effects.
*/
................................................................................
  int n;
  assert( argc==1 );
  UNUSED_PARAMETER(argc);
  /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
  ** is a wrapper around the sqlite4_compileoption_get() C/C++ function.
  */
  n = sqlite4_value_int(argv[0]);
  sqlite4_result_text(context, sqlite4_compileoption_get(n), -1,
                      SQLITE4_STATIC, 0);
}
#endif /* SQLITE4_OMIT_COMPILEOPTION_DIAGS */

/* Array for converting from half-bytes (nybbles) into ASCII hex
** digits. */
static const char hexdigits[] = {
  '0', '1', '2', '3', '4', '5', '6', '7',
................................................................................
          zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
          zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
        }
        zText[(nBlob*2)+2] = '\'';
        zText[(nBlob*2)+3] = '\0';
        zText[0] = 'x';
        zText[1] = '\'';
        sqlite4_result_text(context, zText, -1, SQLITE4_TRANSIENT, 0);
        sqlite4_free(sqlite4_context_env(context), zText);
      }
      break;
    }
    case SQLITE4_TEXT: {
      int i,j;
      u64 n;
................................................................................
          z[j++] = zArg[i];
          if( zArg[i]=='\'' ){
            z[j++] = '\'';
          }
        }
        z[j++] = '\'';
        z[j] = 0;
        sqlite4_result_text(context, z, j, SQLITE4_DYNAMIC, 0);
      }
      break;
    }
    default: {
      assert( sqlite4_value_type(argv[0])==SQLITE4_NULL );
      sqlite4_result_text(context, "NULL", 4, SQLITE4_STATIC, 0);
      break;
    }
  }
}

/*
** The hex() function.  Interpret the argument as a blob.  Return
................................................................................
  if( zHex ){
    for(i=0; i<n; i++, pBlob++){
      unsigned char c = *pBlob;
      *(z++) = hexdigits[(c>>4)&0xf];
      *(z++) = hexdigits[c&0xf];
    }
    *z = 0;
    sqlite4_result_text(context, zHex, n*2, SQLITE4_DYNAMIC, 0);
  }
}

/*
** The zeroblob(N) function returns a zero-filled blob of size N bytes.
*/
static void zeroblobFunc(
................................................................................
    }
  }
  assert( j+nStr-i+1==nOut );
  memcpy(&zOut[j], &zStr[i], nStr-i);
  j += nStr - i;
  assert( j<=nOut );
  zOut[j] = 0;
  sqlite4_result_text(context, (char*)zOut, j, SQLITE4_DYNAMIC, 0);
}

/*
** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
*/
static void trimFunc(
................................................................................
        nIn -= len;
      }
    }
    if( zCharSet ){
      sqlite4_free(sqlite4_context_env(context), azChar);
    }
  }
  sqlite4_result_text(context, (char*)zIn, nIn, SQLITE4_TRANSIENT, 0);
}


/* IMP: R-25361-16150 This function is omitted from SQLite by default. It
** is only available if the SQLITE4_SOUNDEX compile-time option is used
** when SQLite is built.
*/
................................................................................
        prevcode = 0;
      }
    }
    while( j<4 ){
      zResult[j++] = '0';
    }
    zResult[j] = 0;
    sqlite4_result_text(context, zResult, 4, SQLITE4_TRANSIENT, 0);
  }else{
    /* IMP: R-64894-50321 The string "?000" is returned if the argument
    ** is NULL or contains no ASCII alphabetic characters. */
    sqlite4_result_text(context, "?000", 4, SQLITE4_STATIC, 0);
  }
}
#endif /* SQLITE4_SOUNDEX */

#if 0 /*ndef SQLITE4_OMIT_LOAD_EXTENSION*/
/*
** A function that loads a shared-library extension then returns NULL.
................................................................................
  if( pAccum ){
    if( pAccum->tooBig ){
      sqlite4_result_error_toobig(context);
    }else if( pAccum->mallocFailed ){
      sqlite4_result_error_nomem(context);
    }else{    
      sqlite4_result_text(context, sqlite4StrAccumFinish(pAccum), -1, 
                          SQLITE4_DYNAMIC, 0);
    }
  }
}

/*
** This routine does per-connection function registration.  Most
** of the built-in functions above are part of the global function set.

Changes to src/main.c.

25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
....
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
#ifdef SQLITE4_ENABLE_ICU
# include "sqliteicu.h"
#endif

/*
** Dummy function used as a unique symbol for SQLITE4_DYNAMIC
*/
void sqlite4_dynamic(void *p){ (void)p; }

#ifndef SQLITE4_AMALGAMATION
/* IMPLEMENTATION-OF: R-46656-45156 The sqlite4_version[] string constant
** contains the text of SQLITE4_VERSION macro. 
*/
const char sqlite4_version[] = SQLITE4_VERSION;
#endif
................................................................................
  sqlite4_mutex_enter(db->mutex);
  if( db->mallocFailed ){
    z = (void *)outOfMem;
  }else{
    z = sqlite4_value_text16(db->pErr);
    if( z==0 ){
      sqlite4ValueSetStr(db->pErr, -1, sqlite4ErrStr(db->errCode),
           SQLITE4_UTF8, SQLITE4_STATIC);
      z = sqlite4_value_text16(db->pErr);
    }
    /* A malloc() may have failed within the call to sqlite4_value_text16()
    ** above. If this is the case, then the db->mallocFailed flag needs to
    ** be cleared before returning. Do this directly, instead of via
    ** sqlite4ApiExit(), to avoid setting the database handle error message.
    */







|







 







|







25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
....
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
#ifdef SQLITE4_ENABLE_ICU
# include "sqliteicu.h"
#endif

/*
** Dummy function used as a unique symbol for SQLITE4_DYNAMIC
*/
void sqlite4_dynamic(void *pArg,void *p){ (void)pArg; (void)p; }

#ifndef SQLITE4_AMALGAMATION
/* IMPLEMENTATION-OF: R-46656-45156 The sqlite4_version[] string constant
** contains the text of SQLITE4_VERSION macro. 
*/
const char sqlite4_version[] = SQLITE4_VERSION;
#endif
................................................................................
  sqlite4_mutex_enter(db->mutex);
  if( db->mallocFailed ){
    z = (void *)outOfMem;
  }else{
    z = sqlite4_value_text16(db->pErr);
    if( z==0 ){
      sqlite4ValueSetStr(db->pErr, -1, sqlite4ErrStr(db->errCode),
           SQLITE4_UTF8, SQLITE4_STATIC, 0);
      z = sqlite4_value_text16(db->pErr);
    }
    /* A malloc() may have failed within the call to sqlite4_value_text16()
    ** above. If this is the case, then the db->mallocFailed flag needs to
    ** be cleared before returning. Do this directly, instead of via
    ** sqlite4ApiExit(), to avoid setting the database handle error message.
    */

Changes to src/math.c.

211
212
213
214
215
216
217














218
219
220
221
222
223
224
...
237
238
239
240
241
242
243

244
245
246
247
248
249
250
...
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
...
465
466
467
468
469
470
471
472
473



474
475
476
477
478
479
480
  r.sign = A.sign ^ B.sign;
  r.approx = A.approx | B.approx;
  if( r.approx==0 && A.m%B.m!=0 ) r.approx = 1;
  r.m = A.m/B.m;
  r.e = A.e - B.e;
  return r;
}















/*
** Compare numbers A and B.  Return:
**
**    1     if A<B
**    2     if A==B
**    3     if A>B
................................................................................
    return A.sign ? 1 : 3;
  }
  if( B.e>SQLITE4_MX_EXP ){
    if( B.m==0 ) return 0;
    return B.sign ? 3 : 1;
  }
  if( A.sign!=B.sign ){

    return A.sign ? 1 : 3;
  }
  adjustExponent(&A, &B);
  if( A.sign ){
    sqlite4_num t = A;
    A = B;
    B = t;
................................................................................
    i = incr;
  }else if( zIn[0]=='+' ){
    i = incr;
  }else{
    i = 0;
  }
  if( nIn<=0 ) goto not_a_valid_number;
  if( nIn>=incr*2
   && ((c=zIn[i])=='i' || c=='I')
   && ((c=zIn[i+incr])=='n' || c=='N')
   && ((c=zIn[i+incr*2])=='f' || c=='F')
  ){
    r.e = SQLITE4_MX_EXP+1;
    r.m = nIn<=i+incr*3 || zIn[i+incr*3]==0;
    return r;
  }
  while( i<nIn && (c = zIn[i])!=0 ){
    i += incr;
    if( c>='0' && c<='9' ){
      if( c==0 && nDigit==0 ){
        if( seenRadix && r.e > -(SQLITE4_MX_EXP+1000) ) r.e--;
        continue;
      }
      nDigit++;
      if( nDigit<=18 ){
        r.m = (r.m*10) + c - '0';
        if( seenRadix ) r.e--;
      }else{
        if( c!='0' ) r.approx = 1;
        if( !seenRadix ) r.e++;
      }
    }else if( c=='.' ){
      seenRadix = 1;
    }else{
      break;
    }
  }
  if( c=='e' || c=='E' ){
    int exp = 0;
    int expsign = 0;
    int nEDigit = 0;
    if( zIn[i]=='-' ){
      expsign = 1;
      i += incr;
    }else if( zIn[i]=='+' ){
      i += incr;
    }
    if( i>=nIn ) goto not_a_valid_number;
    while( i<nIn && (c = zIn[i])!=0  ){
      i += incr;
      if( c<'0' || c>'9' ) break;
      if( c=='0' && nEDigit==0 ) continue;
      nEDigit++;
      if( nEDigit>3 ) goto not_a_valid_number;
      exp = exp*10 + c - '0';
    }
    if( expsign ) exp = -exp;
    r.e += exp;



  }
  if( c!=0 ) goto not_a_valid_number;

  return r;
  
not_a_valid_number:
  r.e = SQLITE4_MX_EXP+1;
  r.m = 0;
  return r;  
}



















/*
** Convert an integer into text in the buffer supplied. The
** text is zero-terminated and right-justified in the buffer.
** A pointer to the first character of text is returned.
**
** The buffer needs to be at least 21 bytes in length.
................................................................................
    zNum += m;
    n -= m;
    removeTrailingZeros(zNum, &n);
    if( n>0 ){
      zOut[0] = '.';
      memcpy(zOut+1, zNum, n);
      nOut += n;
    }
    zOut[n+1] = 0;



    return nOut;
  }
  if( x.e<0 && x.e >= -n-5 ){
    /* Values less than 1 and with no more than 5 subsequent zeros prior
    ** to the first significant digit.  Ex:  0.0000012345 */
    int j = -(n + x.e);
    memcpy(zOut, "0.", 2);







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







 







>







 







|











|













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







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







 







<
|
>
>
>







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
...
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
...
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
...
497
498
499
500
501
502
503

504
505
506
507
508
509
510
511
512
513
514
  r.sign = A.sign ^ B.sign;
  r.approx = A.approx | B.approx;
  if( r.approx==0 && A.m%B.m!=0 ) r.approx = 1;
  r.m = A.m/B.m;
  r.e = A.e - B.e;
  return r;
}

/*
** Test if A is infinite.
*/
int sqlite4_num_isinf(sqlite4_num A){
  return A.e>SQLITE4_MX_EXP && A.m!=0;
}

/*
** Test if A is NaN.
*/
int sqlite4_num_isnan(sqlite4_num A){
  return A.e>SQLITE4_MX_EXP && A.m==0; 
}

/*
** Compare numbers A and B.  Return:
**
**    1     if A<B
**    2     if A==B
**    3     if A>B
................................................................................
    return A.sign ? 1 : 3;
  }
  if( B.e>SQLITE4_MX_EXP ){
    if( B.m==0 ) return 0;
    return B.sign ? 3 : 1;
  }
  if( A.sign!=B.sign ){
    if ( A.m==0 && B.m==0 ) return 2;
    return A.sign ? 1 : 3;
  }
  adjustExponent(&A, &B);
  if( A.sign ){
    sqlite4_num t = A;
    A = B;
    B = t;
................................................................................
    i = incr;
  }else if( zIn[0]=='+' ){
    i = incr;
  }else{
    i = 0;
  }
  if( nIn<=0 ) goto not_a_valid_number;
  if( nIn>=incr*3
   && ((c=zIn[i])=='i' || c=='I')
   && ((c=zIn[i+incr])=='n' || c=='N')
   && ((c=zIn[i+incr*2])=='f' || c=='F')
  ){
    r.e = SQLITE4_MX_EXP+1;
    r.m = nIn<=i+incr*3 || zIn[i+incr*3]==0;
    return r;
  }
  while( i<nIn && (c = zIn[i])!=0 ){
    i += incr;
    if( c>='0' && c<='9' ){
      if( c=='0' && nDigit==0 ){
        if( seenRadix && r.e > -(SQLITE4_MX_EXP+1000) ) r.e--;
        continue;
      }
      nDigit++;
      if( nDigit<=18 ){
        r.m = (r.m*10) + c - '0';
        if( seenRadix ) r.e--;
      }else{
        if( c!='0' ) r.approx = 1;
        if( !seenRadix ) r.e++;
      }
    }else if( c=='.' ){
      seenRadix = 1;




    }else if( c=='e' || c=='E' ){
      int exp = 0;
      int expsign = 0;
      int nEDigit = 0;
      if( zIn[i]=='-' ){
        expsign = 1;
        i += incr;
      }else if( zIn[i]=='+' ){
        i += incr;
      }
      if( i>=nIn ) goto not_a_valid_number;
      while( i<nIn && (c = zIn[i])!=0 ){
        i += incr;
        if( c<'0' || c>'9' ) goto not_a_valid_number;
        if( c=='0' && nEDigit==0 ) continue;
        nEDigit++;
        if( nEDigit>3 ) goto not_a_valid_number;
        exp = exp*10 + c - '0';
      }
      if( expsign ) exp = -exp;
      r.e += exp;
      break;
    }else{
      goto not_a_valid_number;
    }

  }
  return r;
  
not_a_valid_number:
  r.e = SQLITE4_MX_EXP+1;
  r.m = 0;
  return r;  
}

/*
** Convert an sqlite4_int64 to a number and return that number.
*/
sqlite4_num sqlite4_num_from_int64(sqlite4_int64 n){
  sqlite4_num r;
  r.approx = 0;
  r.e = 0;
  r.sign = n < 0;
  if( n>=0 ){
    r.m = n;
  }else if( n!=SMALLEST_INT64 ){
    r.m = -n;
  }else{
    r.m = 1+(u64)LARGEST_INT64;
  }
  return r;
}

/*
** Convert an integer into text in the buffer supplied. The
** text is zero-terminated and right-justified in the buffer.
** A pointer to the first character of text is returned.
**
** The buffer needs to be at least 21 bytes in length.
................................................................................
    zNum += m;
    n -= m;
    removeTrailingZeros(zNum, &n);
    if( n>0 ){
      zOut[0] = '.';
      memcpy(zOut+1, zNum, n);
      nOut += n;

      zOut[n+1] = 0;
    }else{
      zOut[0] = 0;
    }
    return nOut;
  }
  if( x.e<0 && x.e >= -n-5 ){
    /* Values less than 1 and with no more than 5 subsequent zeros prior
    ** to the first significant digit.  Ex:  0.0000012345 */
    int j = -(n + x.e);
    memcpy(zOut, "0.", 2);

Changes to src/pragma.c.

73
74
75
76
77
78
79

80
81
82
83
84
85
86
#ifdef SQLITE4_DEBUG
    { "sql_trace",                SQLITE4_SqlTrace      },
    { "vdbe_listing",             SQLITE4_VdbeListing   },
    { "vdbe_trace",               SQLITE4_VdbeTrace     },
    { "kv_trace",                 SQLITE4_KvTrace       },
    { "trace",                    SQLITE4_SqlTrace | SQLITE4_VdbeListing |
                                  SQLITE4_VdbeTrace | SQLITE4_KvTrace },

#endif
#ifndef SQLITE4_OMIT_CHECK
    { "ignore_check_constraints", SQLITE4_IgnoreChecks  },
#endif
    /* The following is VERY experimental */
    { "writable_schema",          SQLITE4_WriteSchema|SQLITE4_RecoveryMode },








>







73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#ifdef SQLITE4_DEBUG
    { "sql_trace",                SQLITE4_SqlTrace      },
    { "vdbe_listing",             SQLITE4_VdbeListing   },
    { "vdbe_trace",               SQLITE4_VdbeTrace     },
    { "kv_trace",                 SQLITE4_KvTrace       },
    { "trace",                    SQLITE4_SqlTrace | SQLITE4_VdbeListing |
                                  SQLITE4_VdbeTrace | SQLITE4_KvTrace },
    { "vdbe_addoptrace",          SQLITE4_VdbeAddopTrace },
#endif
#ifndef SQLITE4_OMIT_CHECK
    { "ignore_check_constraints", SQLITE4_IgnoreChecks  },
#endif
    /* The following is VERY experimental */
    { "writable_schema",          SQLITE4_WriteSchema|SQLITE4_RecoveryMode },

Changes to src/resolve.c.

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
    ** we have a match (cnt>0) or when we run out of name contexts.
    */
    if( cnt==0 ){
      pNC = pNC->pNext;
    }
  }

  /*
  ** If X and Y are NULL (in other words if only the column name Z is
  ** supplied) and the value of Z is enclosed in double-quotes, then
  ** Z is a string literal if it doesn't match any column names.  In that
  ** case, we need to return right away and not make any changes to
  ** pExpr.
  **
  ** Because no reference was made to outer contexts, the pNC->nRef
  ** fields are not changed in any context.
  */
  if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
    pExpr->op = TK_STRING;
    pExpr->pTab = 0;
    return WRC_Prune;
  }

  /*
  ** cnt==0 means there was not match.  cnt>1 means there were two or
  ** more matches.  Either way, we have an error.
  */
  if( cnt!=1 ){
    const char *zErr;
    zErr = cnt==0 ? "no such column" : "ambiguous column name";







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







338
339
340
341
342
343
344
















345
346
347
348
349
350
351
    ** we have a match (cnt>0) or when we run out of name contexts.
    */
    if( cnt==0 ){
      pNC = pNC->pNext;
    }
  }

















  /*
  ** cnt==0 means there was not match.  cnt>1 means there were two or
  ** more matches.  Either way, we have an error.
  */
  if( cnt!=1 ){
    const char *zErr;
    zErr = cnt==0 ? "no such column" : "ambiguous column name";

Changes to src/select.c.

944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
....
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
....
2305
2306
2307
2308
2309
2310
2311
2312

2313
2314
2315
2316
2317
2318
2319
....
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
  if( p->selFlags & SF_UseSorter ){
    int regSortOut = ++pParse->nMem;
    int ptab2 = pParse->nTab++;
    sqlite4VdbeAddOp3(v, OP_OpenPseudo, ptab2, regSortOut, pOrderBy->nExpr+2);
    addr = 1 + sqlite4VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
    codeOffset(v, p, addrContinue);
    sqlite4VdbeAddOp2(v, OP_SorterData, iTab, regSortOut);
    sqlite4VdbeAddOp3(v, OP_Column, ptab2, pOrderBy->nExpr+1, regRow);
    sqlite4VdbeChangeP5(v, OPFLAG_CLEARCACHE);
  }else{
    addr = 1 + sqlite4VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
    codeOffset(v, p, addrContinue);
    /* sqlite4VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr+1, regRow); */
  }
  switch( eDest ){
    case SRT_Table:
    case SRT_EphemTab: {
      testcase( eDest==SRT_Table );
      testcase( eDest==SRT_EphemTab );
      sqlite4VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
................................................................................
  int cnt;                    /* Index added to make the name unique */
  Column *aCol, *pCol;        /* For looping over result columns */
  int nCol;                   /* Number of columns in the result set */
  Expr *p;                    /* Expression for a single result column */
  char *zName;                /* Column name */
  int nName;                  /* Size of name in zName[] */

  *pnCol = nCol = pEList->nExpr;
  aCol = *paCol = sqlite4DbMallocZero(db, sizeof(aCol[0])*nCol);
  if( aCol==0 ) return SQLITE4_NOMEM;
  for(i=0, pCol=aCol; i<nCol; i++, pCol++){
    /* Get an appropriate name for the column
    */
    p = pEList->a[i].pExpr;
    assert( p->pRight==0 || ExprHasProperty(p->pRight, EP_IntValue)
................................................................................
  ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
  */
  if( op==TK_ALL ){
    regPrev = 0;
  }else{
    int nExpr = p->pEList->nExpr;
    assert( nOrderBy>=nExpr || db->mallocFailed );
    regPrev = sqlite4GetTempRange(pParse, nExpr+1);

    sqlite4VdbeAddOp2(v, OP_Integer, 0, regPrev);
    pKeyDup = sqlite4DbMallocZero(db,
                  sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
    if( pKeyDup ){
      pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
      pKeyDup->nField = (u16)nExpr;
      pKeyDup->enc = ENC(db);
................................................................................
  */
  sqlite4VdbeResolveLabel(v, labelCmpr);
  sqlite4VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
  sqlite4VdbeAddOp4(v, OP_Compare, destA.iMem, destB.iMem, nOrderBy,
                         (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
  sqlite4VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);

  /* Release temporary registers
  */
  if( regPrev ){
    sqlite4ReleaseTempRange(pParse, regPrev, nOrderBy+1);
  }

  /* Jump to the this point in order to terminate the query.
  */
  sqlite4VdbeResolveLabel(v, labelEnd);

  /* Set the number of output columns
  */
  if( pDest->eDest==SRT_Output ){







|




|







 







|







 







|
>







 







<
<
<
<
<
<







944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
....
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
....
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
....
2487
2488
2489
2490
2491
2492
2493






2494
2495
2496
2497
2498
2499
2500
  if( p->selFlags & SF_UseSorter ){
    int regSortOut = ++pParse->nMem;
    int ptab2 = pParse->nTab++;
    sqlite4VdbeAddOp3(v, OP_OpenPseudo, ptab2, regSortOut, pOrderBy->nExpr+2);
    addr = 1 + sqlite4VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
    codeOffset(v, p, addrContinue);
    sqlite4VdbeAddOp2(v, OP_SorterData, iTab, regSortOut);
    sqlite4VdbeAddOp3(v, OP_Column, ptab2, 0, regRow);
    sqlite4VdbeChangeP5(v, OPFLAG_CLEARCACHE);
  }else{
    addr = 1 + sqlite4VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
    codeOffset(v, p, addrContinue);
    sqlite4VdbeAddOp3(v, OP_Column, iTab, 0, regRow);
  }
  switch( eDest ){
    case SRT_Table:
    case SRT_EphemTab: {
      testcase( eDest==SRT_Table );
      testcase( eDest==SRT_EphemTab );
      sqlite4VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
................................................................................
  int cnt;                    /* Index added to make the name unique */
  Column *aCol, *pCol;        /* For looping over result columns */
  int nCol;                   /* Number of columns in the result set */
  Expr *p;                    /* Expression for a single result column */
  char *zName;                /* Column name */
  int nName;                  /* Size of name in zName[] */

  *pnCol = nCol = pEList ? pEList->nExpr : 0;
  aCol = *paCol = sqlite4DbMallocZero(db, sizeof(aCol[0])*nCol);
  if( aCol==0 ) return SQLITE4_NOMEM;
  for(i=0, pCol=aCol; i<nCol; i++, pCol++){
    /* Get an appropriate name for the column
    */
    p = pEList->a[i].pExpr;
    assert( p->pRight==0 || ExprHasProperty(p->pRight, EP_IntValue)
................................................................................
  ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
  */
  if( op==TK_ALL ){
    regPrev = 0;
  }else{
    int nExpr = p->pEList->nExpr;
    assert( nOrderBy>=nExpr || db->mallocFailed );
    regPrev = pParse->nMem + 1;
    pParse->nMem += nExpr + 1;
    sqlite4VdbeAddOp2(v, OP_Integer, 0, regPrev);
    pKeyDup = sqlite4DbMallocZero(db,
                  sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
    if( pKeyDup ){
      pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
      pKeyDup->nField = (u16)nExpr;
      pKeyDup->enc = ENC(db);
................................................................................
  */
  sqlite4VdbeResolveLabel(v, labelCmpr);
  sqlite4VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
  sqlite4VdbeAddOp4(v, OP_Compare, destA.iMem, destB.iMem, nOrderBy,
                         (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
  sqlite4VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);







  /* Jump to the this point in order to terminate the query.
  */
  sqlite4VdbeResolveLabel(v, labelEnd);

  /* Set the number of output columns
  */
  if( pDest->eDest==SRT_Output ){

Changes to src/shell.c.

317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
....
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
....
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
  int argc,
  sqlite4_value **argv
){
  assert( 0==argc );
  assert( zShellStatic );
  UNUSED_PARAMETER(argc);
  UNUSED_PARAMETER(argv);
  sqlite4_result_text(context, zShellStatic, -1, SQLITE4_STATIC);
}


/*
** This routine reads a line of text from FILE in, stores
** the text in memory obtained from malloc() and returns a pointer
** to the text.  NULL is returned at end of file, or if malloc()
................................................................................
          int k;
          for(z=azCol[i], j=1, k=0; z[j]; j++){
            if( z[j]=='"' ){ j++; if( z[j]==0 ) break; }
            z[k++] = z[j];
          }
          z[k] = 0;
        }
        sqlite4_bind_text(pStmt, i+1, azCol[i], -1, SQLITE4_STATIC);
      }
      sqlite4_step(pStmt);
      rc = sqlite4_reset(pStmt);
      free(zLine);
      if( rc!=SQLITE4_OK ){
        fprintf(stderr,"Error: %s\n", sqlite4_errmsg(db));
        zCommit = "ROLLBACK";
................................................................................
    zSql = sqlite4_mprintf(0, "%z ORDER BY 1", zSql);
    rc = sqlite4_prepare(p->db, zSql, -1, &pStmt, 0);
    sqlite4_free(0, zSql);
    if( rc ) return rc;
    nRow = nAlloc = 0;
    azResult = 0;
    if( nArg>1 ){
      sqlite4_bind_text(pStmt, 1, azArg[1], -1, SQLITE4_TRANSIENT);
    }else{
      sqlite4_bind_text(pStmt, 1, "%", -1, SQLITE4_STATIC);
    }
    while( sqlite4_step(pStmt)==SQLITE4_ROW ){
      if( nRow>=nAlloc ){
        char **azNew;
        int n = nAlloc*2 + 10;
        azNew = sqlite4_realloc(0, azResult, sizeof(azResult[0])*n);
        if( azNew==0 ){







|







 







|







 







|

|







317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
....
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
....
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
  int argc,
  sqlite4_value **argv
){
  assert( 0==argc );
  assert( zShellStatic );
  UNUSED_PARAMETER(argc);
  UNUSED_PARAMETER(argv);
  sqlite4_result_text(context, zShellStatic, -1, SQLITE4_STATIC, 0);
}


/*
** This routine reads a line of text from FILE in, stores
** the text in memory obtained from malloc() and returns a pointer
** to the text.  NULL is returned at end of file, or if malloc()
................................................................................
          int k;
          for(z=azCol[i], j=1, k=0; z[j]; j++){
            if( z[j]=='"' ){ j++; if( z[j]==0 ) break; }
            z[k++] = z[j];
          }
          z[k] = 0;
        }
        sqlite4_bind_text(pStmt, i+1, azCol[i], -1, SQLITE4_STATIC, 0);
      }
      sqlite4_step(pStmt);
      rc = sqlite4_reset(pStmt);
      free(zLine);
      if( rc!=SQLITE4_OK ){
        fprintf(stderr,"Error: %s\n", sqlite4_errmsg(db));
        zCommit = "ROLLBACK";
................................................................................
    zSql = sqlite4_mprintf(0, "%z ORDER BY 1", zSql);
    rc = sqlite4_prepare(p->db, zSql, -1, &pStmt, 0);
    sqlite4_free(0, zSql);
    if( rc ) return rc;
    nRow = nAlloc = 0;
    azResult = 0;
    if( nArg>1 ){
      sqlite4_bind_text(pStmt, 1, azArg[1], -1, SQLITE4_TRANSIENT, 0);
    }else{
      sqlite4_bind_text(pStmt, 1, "%", -1, SQLITE4_STATIC, 0);
    }
    while( sqlite4_step(pStmt)==SQLITE4_ROW ){
      if( nRow>=nAlloc ){
        char **azNew;
        int n = nAlloc*2 + 10;
        azNew = sqlite4_realloc(0, azResult, sizeof(azResult[0])*n);
        if( azNew==0 ){

Changes to src/sqlite.h.in.

1829
1830
1831
1832
1833
1834
1835
1836

1837
1838
1839
1840
1841

1842

1843
1844
1845
1846
1847
1848
1849
....
2660
2661
2662
2663
2664
2665
2666
2667

2668
2669
2670
2671
2672
2673
2674
....
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
....
2794
2795
2796
2797
2798
2799
2800
2801

2802
2803
2804
2805
2806
2807
2808
2809
2810
2811

2812

2813

2814

2815
2816
2817
2818
2819
2820
2821
....
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
** [error code] if anything goes wrong.
** ^[SQLITE4_RANGE] is returned if the parameter
** index is out of range.  ^[SQLITE4_NOMEM] is returned if malloc() fails.
**
** See also: [sqlite4_bind_parameter_count()],
** [sqlite4_bind_parameter_name()], and [sqlite4_bind_parameter_index()].
*/
int sqlite4_bind_blob(sqlite4_stmt*, int, const void*, int n, void(*)(void*));

int sqlite4_bind_double(sqlite4_stmt*, int, double);
int sqlite4_bind_int(sqlite4_stmt*, int, int);
int sqlite4_bind_int64(sqlite4_stmt*, int, sqlite4_int64);
int sqlite4_bind_null(sqlite4_stmt*, int);
int sqlite4_bind_text(sqlite4_stmt*, int, const char*, int n, void(*)(void*));

int sqlite4_bind_text16(sqlite4_stmt*, int, const void*, int, void(*)(void*));

int sqlite4_bind_value(sqlite4_stmt*, int, const sqlite4_value*);
int sqlite4_bind_zeroblob(sqlite4_stmt*, int, int n);

/*
** CAPIREF: Number Of SQL Parameters
**
** ^This routine can be used to find the number of [SQL parameters]
................................................................................
** expressions that are constant at compile time. This includes literal
** values and [parameters].)^
**
** These routines must be called from the same thread in which
** the SQL function is running.
*/
void *sqlite4_get_auxdata(sqlite4_context*, int N);
void sqlite4_set_auxdata(sqlite4_context*, int N, void*, void (*)(void*));



/*
** CAPIREF: Constants Defining Special Destructor Behavior
**
** These are special values for the destructor that is passed in as the
** final argument to routines like [sqlite4_result_blob()].  ^If the destructor
................................................................................
** SQLITE4_TRANSIENT value means that the content will likely change in
** the near future and that SQLite should make its own private copy of
** the content before returning.
**
** The typedef is necessary to work around problems in certain
** C++ compilers.  See ticket #2191.
*/
typedef void (*sqlite4_destructor_type)(void*);
void sqlite4_dynamic(void*);
#define SQLITE4_STATIC      ((sqlite4_destructor_type)0)
#define SQLITE4_TRANSIENT   ((sqlite4_destructor_type)-1)
#define SQLITE4_DYNAMIC     (sqlite4_dynamic)


/*
** CAPIREF: Setting The Result Of An SQL Function
................................................................................
** [unprotected sqlite4_value] object is required, so either
** kind of [sqlite4_value] object can be used with this interface.
**
** If these routines are called from within the different thread
** than the one containing the application-defined function that received
** the [sqlite4_context] pointer, the results are undefined.
*/
void sqlite4_result_blob(sqlite4_context*, const void*, int, void(*)(void*));

void sqlite4_result_double(sqlite4_context*, double);
void sqlite4_result_error(sqlite4_context*, const char*, int);
void sqlite4_result_error16(sqlite4_context*, const void*, int);
void sqlite4_result_error_toobig(sqlite4_context*);
void sqlite4_result_error_nomem(sqlite4_context*);
void sqlite4_result_error_code(sqlite4_context*, int);
void sqlite4_result_int(sqlite4_context*, int);
void sqlite4_result_int64(sqlite4_context*, sqlite4_int64);
void sqlite4_result_null(sqlite4_context*);
void sqlite4_result_text(sqlite4_context*, const char*, int, void(*)(void*));

void sqlite4_result_text16(sqlite4_context*, const void*, int, void(*)(void*));

void sqlite4_result_text16le(sqlite4_context*, const void*, int,void(*)(void*));

void sqlite4_result_text16be(sqlite4_context*, const void*, int,void(*)(void*));

void sqlite4_result_value(sqlite4_context*, sqlite4_value*);
void sqlite4_result_zeroblob(sqlite4_context*, int n);

/*
** CAPIREF: Define New Collating Sequences
**
** ^This function adds, removes, or modifies a [collation] associated
................................................................................
** Every number in SQLite is represented in memory by an instance of
** the following object.
*/
typedef struct sqlite4_num sqlite4_num;
struct sqlite4_num {
  unsigned char sign;     /* Sign of the overall value */
  unsigned char approx;   /* True if the value is approximate */
  unsigned short e;       /* The exponent. */
  sqlite4_uint64 m;       /* The significant */
};

/*
** CAPI4REF: Operations On SQLite Number Objects
*/
sqlite4_num sqlite4_num_add(sqlite4_num, sqlite4_num);







|
>




|
>
|
>







 







|
>







 







|
|







 







|
>









|
>
|
>
|
>
|
>







 







|







1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
....
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
....
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
....
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
....
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
** [error code] if anything goes wrong.
** ^[SQLITE4_RANGE] is returned if the parameter
** index is out of range.  ^[SQLITE4_NOMEM] is returned if malloc() fails.
**
** See also: [sqlite4_bind_parameter_count()],
** [sqlite4_bind_parameter_name()], and [sqlite4_bind_parameter_index()].
*/
int sqlite4_bind_blob(sqlite4_stmt*, int, const void*, int n, 
                      void(*)(void*,void*),void*);
int sqlite4_bind_double(sqlite4_stmt*, int, double);
int sqlite4_bind_int(sqlite4_stmt*, int, int);
int sqlite4_bind_int64(sqlite4_stmt*, int, sqlite4_int64);
int sqlite4_bind_null(sqlite4_stmt*, int);
int sqlite4_bind_text(sqlite4_stmt*, int, const char*, int n,
                      void(*)(void*,void*),void*);
int sqlite4_bind_text16(sqlite4_stmt*, int, const void*, int,
                        void(*)(void*,void*),void*);
int sqlite4_bind_value(sqlite4_stmt*, int, const sqlite4_value*);
int sqlite4_bind_zeroblob(sqlite4_stmt*, int, int n);

/*
** CAPIREF: Number Of SQL Parameters
**
** ^This routine can be used to find the number of [SQL parameters]
................................................................................
** expressions that are constant at compile time. This includes literal
** values and [parameters].)^
**
** These routines must be called from the same thread in which
** the SQL function is running.
*/
void *sqlite4_get_auxdata(sqlite4_context*, int N);
void sqlite4_set_auxdata(sqlite4_context*, int N, void*,
                         void (*)(void*,void*),void*);


/*
** CAPIREF: Constants Defining Special Destructor Behavior
**
** These are special values for the destructor that is passed in as the
** final argument to routines like [sqlite4_result_blob()].  ^If the destructor
................................................................................
** SQLITE4_TRANSIENT value means that the content will likely change in
** the near future and that SQLite should make its own private copy of
** the content before returning.
**
** The typedef is necessary to work around problems in certain
** C++ compilers.  See ticket #2191.
*/
typedef void (*sqlite4_destructor_type)(void*,void*);
void sqlite4_dynamic(void*,void*);
#define SQLITE4_STATIC      ((sqlite4_destructor_type)0)
#define SQLITE4_TRANSIENT   ((sqlite4_destructor_type)-1)
#define SQLITE4_DYNAMIC     (sqlite4_dynamic)


/*
** CAPIREF: Setting The Result Of An SQL Function
................................................................................
** [unprotected sqlite4_value] object is required, so either
** kind of [sqlite4_value] object can be used with this interface.
**
** If these routines are called from within the different thread
** than the one containing the application-defined function that received
** the [sqlite4_context] pointer, the results are undefined.
*/
void sqlite4_result_blob(sqlite4_context*, const void*, int,
                         void(*)(void*,void*),void*);
void sqlite4_result_double(sqlite4_context*, double);
void sqlite4_result_error(sqlite4_context*, const char*, int);
void sqlite4_result_error16(sqlite4_context*, const void*, int);
void sqlite4_result_error_toobig(sqlite4_context*);
void sqlite4_result_error_nomem(sqlite4_context*);
void sqlite4_result_error_code(sqlite4_context*, int);
void sqlite4_result_int(sqlite4_context*, int);
void sqlite4_result_int64(sqlite4_context*, sqlite4_int64);
void sqlite4_result_null(sqlite4_context*);
void sqlite4_result_text(sqlite4_context*, const char*, int,
                         void(*)(void*,void*),void*);
void sqlite4_result_text16(sqlite4_context*, const void*, int,
                           void(*)(void*,void*),void*);
void sqlite4_result_text16le(sqlite4_context*, const void*, int,
                             void(*)(void*,void*),void*);
void sqlite4_result_text16be(sqlite4_context*, const void*, int,
                             void(*)(void*,void*),void*);
void sqlite4_result_value(sqlite4_context*, sqlite4_value*);
void sqlite4_result_zeroblob(sqlite4_context*, int n);

/*
** CAPIREF: Define New Collating Sequences
**
** ^This function adds, removes, or modifies a [collation] associated
................................................................................
** Every number in SQLite is represented in memory by an instance of
** the following object.
*/
typedef struct sqlite4_num sqlite4_num;
struct sqlite4_num {
  unsigned char sign;     /* Sign of the overall value */
  unsigned char approx;   /* True if the value is approximate */
  short e;                /* The exponent. */
  sqlite4_uint64 m;       /* The significant */
};

/*
** CAPI4REF: Operations On SQLite Number Objects
*/
sqlite4_num sqlite4_num_add(sqlite4_num, sqlite4_num);

Changes to src/sqliteInt.h.

460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
...
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
....
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
....
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
/*
** Constants for the largest and smallest possible 64-bit signed integers.
** These macros are designed to work correctly on both 32-bit and 64-bit
** compilers.
*/
#define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
#define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
#define LARGEST_UINT64  (0xffffffff|(((i64)0xffffffff)<<32))

/* 
** Round up a number to the next larger multiple of 8.  This is used
** to force 8-byte alignment on 64-bit architectures.
*/
#define ROUND8(x)     (((x)+7)&~7)

................................................................................
*/
#define ENC(db) ((db)->aDb[0].pSchema->enc)

/*
** Possible values for the sqlite4.flags.
*/
#define SQLITE4_VdbeTrace      0x00000100  /* True to trace VDBE execution */
#define SQLITE4_InternChanges  0x00000200  /* Uncommitted Hash table changes */
#define SQLITE4_CountRows      0x00001000  /* Count rows changed by INSERT, */
                                          /*   DELETE, or UPDATE and return */
                                          /*   the count using a callback. */
#define SQLITE4_SqlTrace       0x00004000  /* Debug print SQL as it executes */
#define SQLITE4_VdbeListing    0x00008000  /* Debug listings of VDBE programs */



#define SQLITE4_WriteSchema    0x00010000  /* OK to update SQLITE4_MASTER */
#define SQLITE4_KvTrace        0x00020000  /* Trace Key/value storage calls */
#define SQLITE4_IgnoreChecks   0x00040000  /* Do not enforce check constraints */
#define SQLITE4_ReadUncommitted 0x0080000  /* For shared-cache mode */
#define SQLITE4_LegacyFileFmt  0x00100000  /* Create new databases in format 1 */
#define SQLITE4_RecoveryMode   0x00800000  /* Ignore schema errors */
#define SQLITE4_ReverseOrder   0x01000000  /* Reverse unordered SELECTs */
#define SQLITE4_RecTriggers    0x02000000  /* Enable recursive triggers */
#define SQLITE4_ForeignKeys    0x04000000  /* Enforce foreign key constraints  */
#define SQLITE4_AutoIndex      0x08000000  /* Enable automatic indexes */
#define SQLITE4_PreferBuiltin  0x10000000  /* Preference to built-in funcs */
#define SQLITE4_EnableTrigger  0x40000000  /* True to enable triggers */

................................................................................
*/
#define EP_FromJoin   0x0001  /* Originated in ON or USING clause of a join */
#define EP_Agg        0x0002  /* Contains one or more aggregate functions */
#define EP_Resolved   0x0004  /* IDs have been resolved to COLUMNs */
#define EP_Error      0x0008  /* Expression contains one or more errors */
#define EP_Distinct   0x0010  /* Aggregate function with DISTINCT keyword */
#define EP_VarSelect  0x0020  /* pSelect is correlated, not constant */
#define EP_DblQuoted  0x0040  /* token.z was originally in "..." */
#define EP_InfixFunc  0x0080  /* True for an infix function: LIKE, GLOB, etc */
#define EP_ExpCollate 0x0100  /* Collating sequence specified explicitly */
#define EP_FixedDest  0x0200  /* Result needed in a specific register */
#define EP_IntValue   0x0400  /* Integer value contained in u.iValue */
#define EP_xIsSelect  0x0800  /* x.pSelect is valid (otherwise x.pList is) */
#define EP_Hint       0x1000  /* Optimizer hint. Not required for correctness */
#define EP_Reduced    0x2000  /* Expr struct is EXPR_REDUCEDSIZE bytes only */
................................................................................
# define sqlite4FileSuffix3(X,Y)
#endif
u8 sqlite4GetBoolean(const char *z);

const void *sqlite4ValueText(sqlite4_value*, u8);
int sqlite4ValueBytes(sqlite4_value*, u8);
void sqlite4ValueSetStr(sqlite4_value*, int, const void *,u8, 
                        void(*)(void*));
void sqlite4ValueFree(sqlite4_value*);
sqlite4_value *sqlite4ValueNew(sqlite4 *);
char *sqlite4Utf16to8(sqlite4 *, const void*, int, u8);
#ifdef SQLITE4_ENABLE_STAT3
char *sqlite4Utf8to16(sqlite4 *, u8, char *, int, int *);
#endif
int sqlite4ValueFromExpr(sqlite4 *, Expr *, u8, u8, sqlite4_value **);







|







 







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







 







<







 







|







460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
...
889
890
891
892
893
894
895




896
897
898
899
900
901

902


903
904
905
906
907
908
909
910
....
1648
1649
1650
1651
1652
1653
1654

1655
1656
1657
1658
1659
1660
1661
....
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
/*
** Constants for the largest and smallest possible 64-bit signed integers.
** These macros are designed to work correctly on both 32-bit and 64-bit
** compilers.
*/
#define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
#define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
#define LARGEST_UINT64  (0xffffffff|(((u64)0xffffffff)<<32))

/* 
** Round up a number to the next larger multiple of 8.  This is used
** to force 8-byte alignment on 64-bit architectures.
*/
#define ROUND8(x)     (((x)+7)&~7)

................................................................................
*/
#define ENC(db) ((db)->aDb[0].pSchema->enc)

/*
** Possible values for the sqlite4.flags.
*/
#define SQLITE4_VdbeTrace      0x00000100  /* True to trace VDBE execution */




#define SQLITE4_SqlTrace       0x00000200  /* Debug print SQL as it executes */
#define SQLITE4_VdbeListing    0x00000400  /* Debug listings of VDBE programs */
#define SQLITE4_KvTrace        0x00000800  /* Trace Key/value storage calls */
#define SQLITE4_VdbeAddopTrace 0x00001000  /* Trace sqlite4VdbeAddOp() calls */
#define SQLITE4_InternChanges  0x00010000  /* Uncommitted Hash table changes */
#define SQLITE4_WriteSchema    0x00020000  /* OK to update SQLITE4_MASTER */

#define SQLITE4_IgnoreChecks   0x00040000  /* Dont enforce check constraints */


#define SQLITE4_RecoveryMode   0x00080000  /* Ignore schema errors */
#define SQLITE4_ReverseOrder   0x01000000  /* Reverse unordered SELECTs */
#define SQLITE4_RecTriggers    0x02000000  /* Enable recursive triggers */
#define SQLITE4_ForeignKeys    0x04000000  /* Enforce foreign key constraints  */
#define SQLITE4_AutoIndex      0x08000000  /* Enable automatic indexes */
#define SQLITE4_PreferBuiltin  0x10000000  /* Preference to built-in funcs */
#define SQLITE4_EnableTrigger  0x40000000  /* True to enable triggers */

................................................................................
*/
#define EP_FromJoin   0x0001  /* Originated in ON or USING clause of a join */
#define EP_Agg        0x0002  /* Contains one or more aggregate functions */
#define EP_Resolved   0x0004  /* IDs have been resolved to COLUMNs */
#define EP_Error      0x0008  /* Expression contains one or more errors */
#define EP_Distinct   0x0010  /* Aggregate function with DISTINCT keyword */
#define EP_VarSelect  0x0020  /* pSelect is correlated, not constant */

#define EP_InfixFunc  0x0080  /* True for an infix function: LIKE, GLOB, etc */
#define EP_ExpCollate 0x0100  /* Collating sequence specified explicitly */
#define EP_FixedDest  0x0200  /* Result needed in a specific register */
#define EP_IntValue   0x0400  /* Integer value contained in u.iValue */
#define EP_xIsSelect  0x0800  /* x.pSelect is valid (otherwise x.pList is) */
#define EP_Hint       0x1000  /* Optimizer hint. Not required for correctness */
#define EP_Reduced    0x2000  /* Expr struct is EXPR_REDUCEDSIZE bytes only */
................................................................................
# define sqlite4FileSuffix3(X,Y)
#endif
u8 sqlite4GetBoolean(const char *z);

const void *sqlite4ValueText(sqlite4_value*, u8);
int sqlite4ValueBytes(sqlite4_value*, u8);
void sqlite4ValueSetStr(sqlite4_value*, int, const void *,u8, 
                        void(*)(void*,void*),void*);
void sqlite4ValueFree(sqlite4_value*);
sqlite4_value *sqlite4ValueNew(sqlite4 *);
char *sqlite4Utf16to8(sqlite4 *, const void*, int, u8);
#ifdef SQLITE4_ENABLE_STAT3
char *sqlite4Utf8to16(sqlite4 *, u8, char *, int, int *);
#endif
int sqlite4ValueFromExpr(sqlite4 *, Expr *, u8, u8, sqlite4_value **);

Changes to src/tclsqlite.c.

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
...
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
...
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
....
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
....
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
    u8 *data;
    const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
    char c = zType[0];
    if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
      /* Only return a BLOB type if the Tcl variable is a bytearray and
      ** has no string representation. */
      data = Tcl_GetByteArrayFromObj(pVar, &n);
      sqlite4_result_blob(context, data, n, SQLITE4_TRANSIENT);
    }else if( c=='b' && strcmp(zType,"boolean")==0 ){
      Tcl_GetIntFromObj(0, pVar, &n);
      sqlite4_result_int(context, n);
    }else if( c=='d' && strcmp(zType,"double")==0 ){
      double r;
      Tcl_GetDoubleFromObj(0, pVar, &r);
      sqlite4_result_double(context, r);
................................................................................
    }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
          (c=='i' && strcmp(zType,"int")==0) ){
      Tcl_WideInt v;
      Tcl_GetWideIntFromObj(0, pVar, &v);
      sqlite4_result_int64(context, v);
    }else{
      data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
      sqlite4_result_text(context, (char *)data, n, SQLITE4_TRANSIENT);
    }
  }
}

#ifndef SQLITE4_OMIT_AUTHORIZATION
/*
** This is the authentication function.  It appends the authentication
................................................................................
        char c = zType[0];
        if( zVar[0]=='@' ||
           (c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0) ){
          /* Load a BLOB type if the Tcl variable is a bytearray and
          ** it has no string representation or the host
          ** parameter name begins with "@". */
          data = Tcl_GetByteArrayFromObj(pVar, &n);
          sqlite4_bind_blob(pStmt, i, data, n, SQLITE4_STATIC);
          Tcl_IncrRefCount(pVar);
          pPreStmt->apParm[iParm++] = pVar;
        }else if( c=='b' && strcmp(zType,"boolean")==0 ){
          Tcl_GetIntFromObj(interp, pVar, &n);
          sqlite4_bind_int(pStmt, i, n);
        }else if( c=='d' && strcmp(zType,"double")==0 ){
          double r;
................................................................................
        }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
              (c=='i' && strcmp(zType,"int")==0) ){
          Tcl_WideInt v;
          Tcl_GetWideIntFromObj(interp, pVar, &v);
          sqlite4_bind_int64(pStmt, i, v);
        }else{
          data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
          sqlite4_bind_text(pStmt, i, (char *)data, n, SQLITE4_STATIC);
          Tcl_IncrRefCount(pVar);
          pPreStmt->apParm[iParm++] = pVar;
        }
      }else{
        sqlite4_bind_null(pStmt, i);
      }
    }
................................................................................
      for(i=0; i<nCol; i++){
        /* check for null data, if so, bind as null */
        if( (nNull>0 && strcmp(azCol[i], zNull)==0)
          || strlen30(azCol[i])==0 
        ){
          sqlite4_bind_null(pStmt, i+1);
        }else{
          sqlite4_bind_text(pStmt, i+1, azCol[i], -1, SQLITE4_STATIC);
        }
      }
      sqlite4_step(pStmt);
      rc = sqlite4_reset(pStmt);
      free(zLine);
      if( rc!=SQLITE4_OK ){
        Tcl_AppendResult(interp,"Error: ", sqlite4_errmsg(pDb->db), 0);
................................................................................
static void md5finalize(sqlite4_context *context){
  MD5Context *p;
  unsigned char digest[16];
  char zBuf[33];
  p = sqlite4_aggregate_context(context, sizeof(*p));
  MD5Final(digest,p);
  MD5DigestToBase16(digest, zBuf);
  sqlite4_result_text(context, zBuf, -1, SQLITE4_TRANSIENT);
}
int Md5_Register(sqlite4 *db){
  int rc = sqlite4_create_function(db, "md5sum", -1, SQLITE4_UTF8, 0, 0, 
                                 md5step, md5finalize);
  sqlite4_overload_function(db, "md5sum", -1);  /* To exercise this API */
  return rc;
}







|







 







|







 







|







 







|







 







|







 







|







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
...
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
...
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
....
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
....
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
    u8 *data;
    const char *zType = (pVar->typePtr ? pVar->typePtr->name : "");
    char c = zType[0];
    if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){
      /* Only return a BLOB type if the Tcl variable is a bytearray and
      ** has no string representation. */
      data = Tcl_GetByteArrayFromObj(pVar, &n);
      sqlite4_result_blob(context, data, n, SQLITE4_TRANSIENT, 0);
    }else if( c=='b' && strcmp(zType,"boolean")==0 ){
      Tcl_GetIntFromObj(0, pVar, &n);
      sqlite4_result_int(context, n);
    }else if( c=='d' && strcmp(zType,"double")==0 ){
      double r;
      Tcl_GetDoubleFromObj(0, pVar, &r);
      sqlite4_result_double(context, r);
................................................................................
    }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
          (c=='i' && strcmp(zType,"int")==0) ){
      Tcl_WideInt v;
      Tcl_GetWideIntFromObj(0, pVar, &v);
      sqlite4_result_int64(context, v);
    }else{
      data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
      sqlite4_result_text(context, (char *)data, n, SQLITE4_TRANSIENT, 0);
    }
  }
}

#ifndef SQLITE4_OMIT_AUTHORIZATION
/*
** This is the authentication function.  It appends the authentication
................................................................................
        char c = zType[0];
        if( zVar[0]=='@' ||
           (c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0) ){
          /* Load a BLOB type if the Tcl variable is a bytearray and
          ** it has no string representation or the host
          ** parameter name begins with "@". */
          data = Tcl_GetByteArrayFromObj(pVar, &n);
          sqlite4_bind_blob(pStmt, i, data, n, SQLITE4_STATIC, 0);
          Tcl_IncrRefCount(pVar);
          pPreStmt->apParm[iParm++] = pVar;
        }else if( c=='b' && strcmp(zType,"boolean")==0 ){
          Tcl_GetIntFromObj(interp, pVar, &n);
          sqlite4_bind_int(pStmt, i, n);
        }else if( c=='d' && strcmp(zType,"double")==0 ){
          double r;
................................................................................
        }else if( (c=='w' && strcmp(zType,"wideInt")==0) ||
              (c=='i' && strcmp(zType,"int")==0) ){
          Tcl_WideInt v;
          Tcl_GetWideIntFromObj(interp, pVar, &v);
          sqlite4_bind_int64(pStmt, i, v);
        }else{
          data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n);
          sqlite4_bind_text(pStmt, i, (char *)data, n, SQLITE4_STATIC, 0);
          Tcl_IncrRefCount(pVar);
          pPreStmt->apParm[iParm++] = pVar;
        }
      }else{
        sqlite4_bind_null(pStmt, i);
      }
    }
................................................................................
      for(i=0; i<nCol; i++){
        /* check for null data, if so, bind as null */
        if( (nNull>0 && strcmp(azCol[i], zNull)==0)
          || strlen30(azCol[i])==0 
        ){
          sqlite4_bind_null(pStmt, i+1);
        }else{
          sqlite4_bind_text(pStmt, i+1, azCol[i], -1, SQLITE4_STATIC, 0);
        }
      }
      sqlite4_step(pStmt);
      rc = sqlite4_reset(pStmt);
      free(zLine);
      if( rc!=SQLITE4_OK ){
        Tcl_AppendResult(interp,"Error: ", sqlite4_errmsg(pDb->db), 0);
................................................................................
static void md5finalize(sqlite4_context *context){
  MD5Context *p;
  unsigned char digest[16];
  char zBuf[33];
  p = sqlite4_aggregate_context(context, sizeof(*p));
  MD5Final(digest,p);
  MD5DigestToBase16(digest, zBuf);
  sqlite4_result_text(context, zBuf, -1, SQLITE4_TRANSIENT, 0);
}
int Md5_Register(sqlite4 *db){
  int rc = sqlite4_create_function(db, "md5sum", -1, SQLITE4_UTF8, 0, 0, 
                                 md5step, md5finalize);
  sqlite4_overload_function(db, "md5sum", -1);  /* To exercise this API */
  return rc;
}

Changes to src/tokenize.c.

223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
      *tokenType = TK_BITAND;
      return 1;
    }
    case '~': {
      *tokenType = TK_BITNOT;
      return 1;
    }
    case '`':
    case '\'':
    case '"': {
      int delim = z[0];
      testcase( delim=='`' );
      testcase( delim=='\'' );
      testcase( delim=='"' );
      for(i=1; (c=z[i])!=0; i++){







<







223
224
225
226
227
228
229

230
231
232
233
234
235
236
      *tokenType = TK_BITAND;
      return 1;
    }
    case '~': {
      *tokenType = TK_BITNOT;
      return 1;
    }

    case '\'':
    case '"': {
      int delim = z[0];
      testcase( delim=='`' );
      testcase( delim=='\'' );
      testcase( delim=='"' );
      for(i=1; (c=z[i])!=0; i++){

Changes to src/utf.c.

470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
...
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
**
** NULL is returned if there is an allocation error.
*/
char *sqlite4Utf16to8(sqlite4 *db, const void *z, int nByte, u8 enc){
  Mem m;
  memset(&m, 0, sizeof(m));
  m.db = db;
  sqlite4VdbeMemSetStr(&m, z, nByte, enc, SQLITE4_STATIC);
  sqlite4VdbeChangeEncoding(&m, SQLITE4_UTF8);
  if( db->mallocFailed ){
    sqlite4VdbeMemRelease(&m);
    m.z = 0;
  }
  assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
  assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
................................................................................
** flag set.
*/
#ifdef SQLITE4_ENABLE_STAT3
char *sqlite4Utf8to16(sqlite4 *db, u8 enc, char *z, int n, int *pnOut){
  Mem m;
  memset(&m, 0, sizeof(m));
  m.db = db;
  sqlite4VdbeMemSetStr(&m, z, n, SQLITE4_UTF8, SQLITE4_STATIC);
  if( sqlite4VdbeMemTranslate(&m, enc) ){
    assert( db->mallocFailed );
    return 0;
  }
  assert( m.z==m.zMalloc );
  *pnOut = m.n;
  return m.z;







|







 







|







470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
...
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
**
** NULL is returned if there is an allocation error.
*/
char *sqlite4Utf16to8(sqlite4 *db, const void *z, int nByte, u8 enc){
  Mem m;
  memset(&m, 0, sizeof(m));
  m.db = db;
  sqlite4VdbeMemSetStr(&m, z, nByte, enc, SQLITE4_STATIC, 0);
  sqlite4VdbeChangeEncoding(&m, SQLITE4_UTF8);
  if( db->mallocFailed ){
    sqlite4VdbeMemRelease(&m);
    m.z = 0;
  }
  assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
  assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
................................................................................
** flag set.
*/
#ifdef SQLITE4_ENABLE_STAT3
char *sqlite4Utf8to16(sqlite4 *db, u8 enc, char *z, int n, int *pnOut){
  Mem m;
  memset(&m, 0, sizeof(m));
  m.db = db;
  sqlite4VdbeMemSetStr(&m, z, n, SQLITE4_UTF8, SQLITE4_STATIC, 0);
  if( sqlite4VdbeMemTranslate(&m, enc) ){
    assert( db->mallocFailed );
    return 0;
  }
  assert( m.z==m.zMalloc );
  *pnOut = m.n;
  return m.z;

Changes to src/util.c.

128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
    db->errCode = err_code;
    if( zFormat ){
      char *z;
      va_list ap;
      va_start(ap, zFormat);
      z = sqlite4VMPrintf(db, zFormat, ap);
      va_end(ap);
      sqlite4ValueSetStr(db->pErr, -1, z, SQLITE4_UTF8, SQLITE4_DYNAMIC);
    }else{
      sqlite4ValueSetStr(db->pErr, 0, 0, SQLITE4_UTF8, SQLITE4_STATIC);
    }
  }
}

/*
** Add an error message to pParse->zErrMsg and increment pParse->nErr.
** The following formatting characters are allowed:







|

|







128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
    db->errCode = err_code;
    if( zFormat ){
      char *z;
      va_list ap;
      va_start(ap, zFormat);
      z = sqlite4VMPrintf(db, zFormat, ap);
      va_end(ap);
      sqlite4ValueSetStr(db->pErr, -1, z, SQLITE4_UTF8, SQLITE4_DYNAMIC, 0);
    }else{
      sqlite4ValueSetStr(db->pErr, 0, 0, SQLITE4_UTF8, SQLITE4_STATIC, 0);
    }
  }
}

/*
** Add an error message to pParse->zErrMsg and increment pParse->nErr.
** The following formatting characters are allowed:

Changes to src/vdbe.c.

880
881
882
883
884
885
886
887

888
889
890
891
892
893
894
...
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
....
2253
2254
2255
2256
2257
2258
2259
2260

2261
2262
2263
2264
2265
2266
2267
....
2343
2344
2345
2346
2347
2348
2349
2350

2351
2352
2353
2354
2355
2356
2357
....
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
....
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
....
3557
3558
3559
3560
3561
3562
3563

3564
3565
3566
3567
3568
3569
3570
....
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
....
4105
4106
4107
4108
4109
4110
4111
4112

4113
4114
4115
4116
4117
4118
4119
case OP_String8: {         /* same as TK_STRING, out2-prerelease */
  assert( pOp->p4.z!=0 );
  pOp->opcode = OP_String;
  pOp->p1 = sqlite4Strlen30(pOp->p4.z);

#ifndef SQLITE4_OMIT_UTF16
  if( encoding!=SQLITE4_UTF8 ){
    rc = sqlite4VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE4_UTF8, SQLITE4_STATIC);

    if( rc==SQLITE4_TOOBIG ) goto too_big;
    if( SQLITE4_OK!=sqlite4VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
    assert( pOut->zMalloc==pOut->z );
    assert( pOut->flags & MEM_Dyn );
    pOut->zMalloc = 0;
    pOut->flags |= MEM_Static;
    pOut->flags &= ~MEM_Dyn;
................................................................................
/* Opcode: Blob P1 P2 * P4
**
** P4 points to a blob of data P1 bytes long.  Store this
** blob in register P2.
*/
case OP_Blob: {                /* out2-prerelease */
  assert( pOp->p1 <= SQLITE4_MAX_LENGTH );
  sqlite4VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
  pOut->enc = encoding;
  UPDATE_MAX_BLOBSIZE(pOut);
  break;
}

/* Opcode: Variable P1 P2 * P4 *
**
................................................................................

  if( rc ){
    sqlite4DbFree(db, aRec);
  }else{
    if( nSeq ){
      memcpy(&aRec[nRec], &aSeq[sizeof(aSeq)-nSeq], nSeq);
    }
    rc = sqlite4VdbeMemSetStr(pOut, (char *)aRec, nRec+nSeq, 0, SQLITE4_DYNAMIC);

    REGISTER_TRACE(pOp->p3, pOut);
    UPDATE_MAX_BLOBSIZE(pOut);
  }

  break;
}

................................................................................
    aRec = 0;
    rc = sqlite4VdbeEncodeKey(db, 
        pData0, pC->pKeyInfo->nField, pC->iRoot, pC->pKeyInfo, &aRec, &nRec, 0
    );
    if( rc ){
      sqlite4DbFree(db, aRec);
    }else{
      rc = sqlite4VdbeMemSetStr(pKeyOut, (char *)aRec, nRec, 0, SQLITE4_DYNAMIC);

      REGISTER_TRACE(keyReg, pKeyOut);
      UPDATE_MAX_BLOBSIZE(pKeyOut);
    }
  }

  /* If P3 is not 0, compute the data rescord */
  if( rc==SQLITE4_OK && pOp->p3 ){
................................................................................
    pOut = &aMem[pOp->p3];
    memAboutToChange(p, pOut);
    aRec = 0;
    rc = sqlite4VdbeEncodeData(db, pData0, nField, &aRec, &nRec);
    if( rc ){
      sqlite4DbFree(db, aRec);
    }else{
      rc = sqlite4VdbeMemSetStr(pOut, (char *)aRec, nRec, 0, SQLITE4_DYNAMIC);
      REGISTER_TRACE(pOp->p3, pOut);
      UPDATE_MAX_BLOBSIZE(pOut);
    }
  }
  break;
}

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

  pIn3 = &aMem[pOp->p3];
  if( (pIn3->flags & MEM_Blob) 
   && pIn3->n==nKey && 0==memcmp(pIn3->z, aKey, nKey) 
  ){
    pc = pOp->p2-1;
  }else{
    sqlite4VdbeMemSetStr(pIn3, (const char*)aKey, nKey, 0, SQLITE4_TRANSIENT);
  }

  break;
};

/* Opcode: SorterData P1 P2 * * *
**
** Write into register P2 the current sorter data for sorter cursor P1.
*/
case OP_SorterData: {
  VdbeCursor *pC; 
  pOut = &aMem[pOp->p2];
  pC = p->apCsr[pOp->p1];
  assert( pC!=0 );
  pOp->opcode = OP_RowData;
  pc--;
  break;
}

/* Opcode: RowData P1 P2 * * *
**
** Write into register P2 the complete row data for cursor P1.
** There is no interpretation of the data.  
** It is just copied onto the P2 register exactly as 
** it is found in the database file.
**
................................................................................
** There is no interpretation of the data.  
** The key is copied onto the P3 register exactly as 
** it is found in the database file.
**
** If the P1 cursor must be pointing to a valid row (not a NULL row)
** of a real table, not a pseudo-table.
*/

case OP_RowKey:
case OP_RowData: {
  VdbeCursor *pC;
  KVCursor *pCrsr;
  const KVByteArray *pData;
  KVSize nData;

................................................................................
    rc = sqlite4KVCursorKey(pCrsr, &pData, &nData);
  }else{
    rc = sqlite4KVCursorData(pCrsr, 0, -1, &pData, &nData);
  }
  if( rc==SQLITE4_OK && nData>db->aLimit[SQLITE4_LIMIT_LENGTH] ){
    goto too_big;
  }
  sqlite4VdbeMemSetStr(pOut, (const char*)pData, nData, 0, SQLITE4_TRANSIENT);
  pOut->enc = SQLITE4_UTF8;  /* In case the blob is ever cast to text */
  UPDATE_MAX_BLOBSIZE(pOut);
  break;
}

/* Opcode: Rowid P1 P2 * * *
**
................................................................................

  CHECK_FOR_INTERRUPT;
  pIn1 = &aMem[pOp->p1];
  pOut = &aMem[pOp->p3];
  if( (pIn1->flags & MEM_RowSet)
   && (aKey = sqlite4RowSetRead(pIn1->u.pRowSet, &nKey))
  ){
    rc = sqlite4VdbeMemSetStr(pOut, (char const *)aKey, nKey, 0, SQLITE4_TRANSIENT);

    sqlite4RowSetNext(pIn1->u.pRowSet);
  }else{
    /* The RowSet is empty */
    sqlite4VdbeMemSetNull(pIn1);
    pc = pOp->p2 - 1;
  }








|
>







 







|







 







|
>







 







|
>







 







|







 







|









<
<
<
<
<
<
<
<
<
<







 







>







 







|







 







|
>







880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
...
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
....
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
....
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
....
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
....
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536










3537
3538
3539
3540
3541
3542
3543
....
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
....
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
....
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
case OP_String8: {         /* same as TK_STRING, out2-prerelease */
  assert( pOp->p4.z!=0 );
  pOp->opcode = OP_String;
  pOp->p1 = sqlite4Strlen30(pOp->p4.z);

#ifndef SQLITE4_OMIT_UTF16
  if( encoding!=SQLITE4_UTF8 ){
    rc = sqlite4VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE4_UTF8,
                              SQLITE4_STATIC, 0);
    if( rc==SQLITE4_TOOBIG ) goto too_big;
    if( SQLITE4_OK!=sqlite4VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
    assert( pOut->zMalloc==pOut->z );
    assert( pOut->flags & MEM_Dyn );
    pOut->zMalloc = 0;
    pOut->flags |= MEM_Static;
    pOut->flags &= ~MEM_Dyn;
................................................................................
/* Opcode: Blob P1 P2 * P4
**
** P4 points to a blob of data P1 bytes long.  Store this
** blob in register P2.
*/
case OP_Blob: {                /* out2-prerelease */
  assert( pOp->p1 <= SQLITE4_MAX_LENGTH );
  sqlite4VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0, 0);
  pOut->enc = encoding;
  UPDATE_MAX_BLOBSIZE(pOut);
  break;
}

/* Opcode: Variable P1 P2 * P4 *
**
................................................................................

  if( rc ){
    sqlite4DbFree(db, aRec);
  }else{
    if( nSeq ){
      memcpy(&aRec[nRec], &aSeq[sizeof(aSeq)-nSeq], nSeq);
    }
    rc = sqlite4VdbeMemSetStr(pOut, (char *)aRec, nRec+nSeq, 0,
                              SQLITE4_DYNAMIC, 0);
    REGISTER_TRACE(pOp->p3, pOut);
    UPDATE_MAX_BLOBSIZE(pOut);
  }

  break;
}

................................................................................
    aRec = 0;
    rc = sqlite4VdbeEncodeKey(db, 
        pData0, pC->pKeyInfo->nField, pC->iRoot, pC->pKeyInfo, &aRec, &nRec, 0
    );
    if( rc ){
      sqlite4DbFree(db, aRec);
    }else{
      rc = sqlite4VdbeMemSetStr(pKeyOut, (char *)aRec, nRec, 0,
                                SQLITE4_DYNAMIC, 0);
      REGISTER_TRACE(keyReg, pKeyOut);
      UPDATE_MAX_BLOBSIZE(pKeyOut);
    }
  }

  /* If P3 is not 0, compute the data rescord */
  if( rc==SQLITE4_OK && pOp->p3 ){
................................................................................
    pOut = &aMem[pOp->p3];
    memAboutToChange(p, pOut);
    aRec = 0;
    rc = sqlite4VdbeEncodeData(db, pData0, nField, &aRec, &nRec);
    if( rc ){
      sqlite4DbFree(db, aRec);
    }else{
      rc = sqlite4VdbeMemSetStr(pOut, (char *)aRec, nRec, 0, SQLITE4_DYNAMIC,0);
      REGISTER_TRACE(pOp->p3, pOut);
      UPDATE_MAX_BLOBSIZE(pOut);
    }
  }
  break;
}

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

  pIn3 = &aMem[pOp->p3];
  if( (pIn3->flags & MEM_Blob) 
   && pIn3->n==nKey && 0==memcmp(pIn3->z, aKey, nKey) 
  ){
    pc = pOp->p2-1;
  }else{
    sqlite4VdbeMemSetStr(pIn3, (const char*)aKey, nKey, 0, SQLITE4_TRANSIENT,0);
  }

  break;
};

/* Opcode: SorterData P1 P2 * * *
**
** Write into register P2 the current sorter data for sorter cursor P1.
*/










/* Opcode: RowData P1 P2 * * *
**
** Write into register P2 the complete row data for cursor P1.
** There is no interpretation of the data.  
** It is just copied onto the P2 register exactly as 
** it is found in the database file.
**
................................................................................
** There is no interpretation of the data.  
** The key is copied onto the P3 register exactly as 
** it is found in the database file.
**
** If the P1 cursor must be pointing to a valid row (not a NULL row)
** of a real table, not a pseudo-table.
*/
case OP_SorterData:
case OP_RowKey:
case OP_RowData: {
  VdbeCursor *pC;
  KVCursor *pCrsr;
  const KVByteArray *pData;
  KVSize nData;

................................................................................
    rc = sqlite4KVCursorKey(pCrsr, &pData, &nData);
  }else{
    rc = sqlite4KVCursorData(pCrsr, 0, -1, &pData, &nData);
  }
  if( rc==SQLITE4_OK && nData>db->aLimit[SQLITE4_LIMIT_LENGTH] ){
    goto too_big;
  }
  sqlite4VdbeMemSetStr(pOut, (const char*)pData, nData, 0, SQLITE4_TRANSIENT,0);
  pOut->enc = SQLITE4_UTF8;  /* In case the blob is ever cast to text */
  UPDATE_MAX_BLOBSIZE(pOut);
  break;
}

/* Opcode: Rowid P1 P2 * * *
**
................................................................................

  CHECK_FOR_INTERRUPT;
  pIn1 = &aMem[pOp->p1];
  pOut = &aMem[pOp->p3];
  if( (pIn1->flags & MEM_RowSet)
   && (aKey = sqlite4RowSetRead(pIn1->u.pRowSet, &nKey))
  ){
    rc = sqlite4VdbeMemSetStr(pOut, (char const *)aKey, nKey, 0,
                              SQLITE4_TRANSIENT, 0);
    sqlite4RowSetNext(pIn1->u.pRowSet);
  }else{
    /* The RowSet is empty */
    sqlite4VdbeMemSetNull(pIn1);
    pc = pOp->p2 - 1;
  }

Changes to src/vdbe.h.

200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
  int sqlite4VdbeAssertMayAbort(Vdbe *, int);
  void sqlite4VdbeTrace(Vdbe*,FILE*);
#endif
void sqlite4VdbeResetStepResult(Vdbe*);
void sqlite4VdbeRewind(Vdbe*);
int sqlite4VdbeReset(Vdbe*);
void sqlite4VdbeSetNumCols(Vdbe*,int);
int sqlite4VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
void sqlite4VdbeCountChanges(Vdbe*);
sqlite4 *sqlite4VdbeDb(Vdbe*);
void sqlite4VdbeSetSql(Vdbe*, const char *z, int n);
void sqlite4VdbeSwap(Vdbe*,Vdbe*);
VdbeOp *sqlite4VdbeTakeOpArray(Vdbe*, int*, int*);
sqlite4_value *sqlite4VdbeGetValue(Vdbe*, int, u8);
void sqlite4VdbeSetVarmask(Vdbe*, int);







|







200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
  int sqlite4VdbeAssertMayAbort(Vdbe *, int);
  void sqlite4VdbeTrace(Vdbe*,FILE*);
#endif
void sqlite4VdbeResetStepResult(Vdbe*);
void sqlite4VdbeRewind(Vdbe*);
int sqlite4VdbeReset(Vdbe*);
void sqlite4VdbeSetNumCols(Vdbe*,int);
int sqlite4VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*,void*));
void sqlite4VdbeCountChanges(Vdbe*);
sqlite4 *sqlite4VdbeDb(Vdbe*);
void sqlite4VdbeSetSql(Vdbe*, const char *z, int n);
void sqlite4VdbeSwap(Vdbe*,Vdbe*);
VdbeOp *sqlite4VdbeTakeOpArray(Vdbe*, int*, int*);
sqlite4_value *sqlite4VdbeGetValue(Vdbe*, int, u8);
void sqlite4VdbeSetVarmask(Vdbe*, int);

Changes to src/vdbeInt.h.

145
146
147
148
149
150
151
152

153
154
155
156
157
158
159
...
213
214
215
216
217
218
219
220

221
222
223
224
225
226
227
...
394
395
396
397
398
399
400
401

402
403
404
405
406
407
408
  u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
  u8  type;           /* One of SQLITE4_NULL, SQLITE4_TEXT, SQLITE4_INTEGER, etc */
  u8  enc;            /* SQLITE4_UTF8, SQLITE4_UTF16BE, SQLITE4_UTF16LE */
#ifdef SQLITE4_DEBUG
  Mem *pScopyFrom;    /* This Mem is a shallow copy of pScopyFrom */
  void *pFiller;      /* So that sizeof(Mem) is a multiple of 8 */
#endif
  void (*xDel)(void *);  /* If not null, call this function to delete Mem.z */

  char *zMalloc;      /* Dynamic buffer allocated by sqlite4_malloc() */
};

/* One or more of the following flags are set to indicate the validOK
** representations of the value stored in the Mem struct.
**
** If the MEM_Null flag is set, then the value is an SQL NULL value.
................................................................................
** invocations.
*/
struct VdbeFunc {
  FuncDef *pFunc;               /* The definition of the function */
  int nAux;                     /* Number of entries allocated for apAux[] */
  struct AuxData {
    void *pAux;                   /* Aux data for the i-th argument */
    void (*xDelete)(void *);      /* Destructor for the aux data */

  } apAux[1];                   /* One slot for each function argument */
};

/*
** The "context" argument for a installable function.  A pointer to an
** instance of this structure is the first argument to the routines used
** implement the SQL functions.
................................................................................
int sqlite4VdbeHalt(Vdbe*);
int sqlite4VdbeChangeEncoding(Mem *, int);
int sqlite4VdbeMemTooBig(Mem*);
int sqlite4VdbeMemCopy(Mem*, const Mem*);
void sqlite4VdbeMemShallowCopy(Mem*, const Mem*, int);
void sqlite4VdbeMemMove(Mem*, Mem*);
int sqlite4VdbeMemNulTerminate(Mem*);
int sqlite4VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));

void sqlite4VdbeMemSetInt64(Mem*, i64);
#ifdef SQLITE4_OMIT_FLOATING_POINT
# define sqlite4VdbeMemSetDouble sqlite4VdbeMemSetInt64
#else
  void sqlite4VdbeMemSetDouble(Mem*, double);
#endif
void sqlite4VdbeMemSetNull(Mem*);







|
>







 







|
>







 







|
>







145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
...
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
...
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
  u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
  u8  type;           /* One of SQLITE4_NULL, SQLITE4_TEXT, SQLITE4_INTEGER, etc */
  u8  enc;            /* SQLITE4_UTF8, SQLITE4_UTF16BE, SQLITE4_UTF16LE */
#ifdef SQLITE4_DEBUG
  Mem *pScopyFrom;    /* This Mem is a shallow copy of pScopyFrom */
  void *pFiller;      /* So that sizeof(Mem) is a multiple of 8 */
#endif
  void (*xDel)(void*,void*); /* Function to delete Mem.z */
  void *pDelArg;             /* First argument to xDel() */
  char *zMalloc;      /* Dynamic buffer allocated by sqlite4_malloc() */
};

/* One or more of the following flags are set to indicate the validOK
** representations of the value stored in the Mem struct.
**
** If the MEM_Null flag is set, then the value is an SQL NULL value.
................................................................................
** invocations.
*/
struct VdbeFunc {
  FuncDef *pFunc;               /* The definition of the function */
  int nAux;                     /* Number of entries allocated for apAux[] */
  struct AuxData {
    void *pAux;                   /* Aux data for the i-th argument */
    void (*xDelete)(void*,void*); /* Destructor for the aux data */
    void *pDeleteArg;             /* First argument to xDelete */
  } apAux[1];                   /* One slot for each function argument */
};

/*
** The "context" argument for a installable function.  A pointer to an
** instance of this structure is the first argument to the routines used
** implement the SQL functions.
................................................................................
int sqlite4VdbeHalt(Vdbe*);
int sqlite4VdbeChangeEncoding(Mem *, int);
int sqlite4VdbeMemTooBig(Mem*);
int sqlite4VdbeMemCopy(Mem*, const Mem*);
void sqlite4VdbeMemShallowCopy(Mem*, const Mem*, int);
void sqlite4VdbeMemMove(Mem*, Mem*);
int sqlite4VdbeMemNulTerminate(Mem*);
int sqlite4VdbeMemSetStr(Mem*, const char*, int, u8,
                         void(*)(void*,void*),void*);
void sqlite4VdbeMemSetInt64(Mem*, i64);
#ifdef SQLITE4_OMIT_FLOATING_POINT
# define sqlite4VdbeMemSetDouble sqlite4VdbeMemSetInt64
#else
  void sqlite4VdbeMemSetDouble(Mem*, double);
#endif
void sqlite4VdbeMemSetNull(Mem*);

Changes to src/vdbeapi.c.

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
...
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
...
587
588
589
590
591
592
593
594

595
596
597
598
599
600
601
...
610
611
612
613
614
615
616
617
618
619
620

621
622
623
624
625
626
627
628
629
630
631
632
....
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015

1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049

1050
1051
1052
1053
1054
1055
1056
1057
1058
....
1083
1084
1085
1086
1087
1088
1089
1090

1091
1092
1093
1094
1095
1096
1097
1098
1099
1100

1101
1102
1103
1104
1105
1106
1107
1108
1109
....
1113
1114
1115
1116
1117
1118
1119
1120

1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
** the function result.
**
** The setStrOrError() funtion calls sqlite4VdbeMemSetStr() to store the
** result as a string or blob but if the string or blob is too large, it
** then sets the error code to SQLITE4_TOOBIG
*/
static void setResultStrOrError(
  sqlite4_context *pCtx,  /* Function context */
  const char *z,          /* String pointer */
  int n,                  /* Bytes in string, or negative */
  u8 enc,                 /* Encoding of z.  0 for BLOBs */
  void (*xDel)(void*)     /* Destructor function */

){
  if( xDel==SQLITE4_DYNAMIC ){
    assert( sqlite4MemdebugHasType(z, MEMTYPE_HEAP) );
    assert( sqlite4MemdebugNoType(z, ~MEMTYPE_HEAP) );
    sqlite4MemdebugSetType((char*)z, MEMTYPE_DB | MEMTYPE_HEAP);
  }
  if( sqlite4VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE4_TOOBIG ){
    sqlite4_result_error_toobig(pCtx);
  }
}
void sqlite4_result_blob(
  sqlite4_context *pCtx, 
  const void *z, 
  int n, 
  void (*xDel)(void *)

){
  assert( n>=0 );
  assert( sqlite4_mutex_held(pCtx->s.db->mutex) );
  setResultStrOrError(pCtx, z, n, 0, xDel);
}
void sqlite4_result_double(sqlite4_context *pCtx, double rVal){
  assert( sqlite4_mutex_held(pCtx->s.db->mutex) );
  sqlite4VdbeMemSetDouble(&pCtx->s, rVal);
}
void sqlite4_result_error(sqlite4_context *pCtx, const char *z, int n){
  assert( sqlite4_mutex_held(pCtx->s.db->mutex) );
  pCtx->isError = SQLITE4_ERROR;
  sqlite4VdbeMemSetStr(&pCtx->s, z, n, SQLITE4_UTF8, SQLITE4_TRANSIENT);
}
#ifndef SQLITE4_OMIT_UTF16
void sqlite4_result_error16(sqlite4_context *pCtx, const void *z, int n){
  assert( sqlite4_mutex_held(pCtx->s.db->mutex) );
  pCtx->isError = SQLITE4_ERROR;
  sqlite4VdbeMemSetStr(&pCtx->s, z, n, SQLITE4_UTF16NATIVE, SQLITE4_TRANSIENT);
}
#endif
void sqlite4_result_int(sqlite4_context *pCtx, int iVal){
  assert( sqlite4_mutex_held(pCtx->s.db->mutex) );
  sqlite4VdbeMemSetInt64(&pCtx->s, (i64)iVal);
}
void sqlite4_result_int64(sqlite4_context *pCtx, i64 iVal){
................................................................................
  assert( sqlite4_mutex_held(pCtx->s.db->mutex) );
  sqlite4VdbeMemSetNull(&pCtx->s);
}
void sqlite4_result_text(
  sqlite4_context *pCtx, 
  const char *z, 
  int n,
  void (*xDel)(void *)

){
  assert( sqlite4_mutex_held(pCtx->s.db->mutex) );
  setResultStrOrError(pCtx, z, n, SQLITE4_UTF8, xDel);
}
#ifndef SQLITE4_OMIT_UTF16
void sqlite4_result_text16(
  sqlite4_context *pCtx, 
  const void *z, 
  int n, 
  void (*xDel)(void *)

){
  assert( sqlite4_mutex_held(pCtx->s.db->mutex) );
  setResultStrOrError(pCtx, z, n, SQLITE4_UTF16NATIVE, xDel);
}
void sqlite4_result_text16be(
  sqlite4_context *pCtx, 
  const void *z, 
  int n, 
  void (*xDel)(void *)

){
  assert( sqlite4_mutex_held(pCtx->s.db->mutex) );
  setResultStrOrError(pCtx, z, n, SQLITE4_UTF16BE, xDel);
}
void sqlite4_result_text16le(
  sqlite4_context *pCtx, 
  const void *z, 
  int n, 
  void (*xDel)(void *)

){
  assert( sqlite4_mutex_held(pCtx->s.db->mutex) );
  setResultStrOrError(pCtx, z, n, SQLITE4_UTF16LE, xDel);
}
#endif /* SQLITE4_OMIT_UTF16 */
void sqlite4_result_value(sqlite4_context *pCtx, sqlite4_value *pValue){
  assert( sqlite4_mutex_held(pCtx->s.db->mutex) );
  sqlite4VdbeMemCopy(&pCtx->s, pValue);
}
void sqlite4_result_zeroblob(sqlite4_context *pCtx, int n){
................................................................................
  assert( sqlite4_mutex_held(pCtx->s.db->mutex) );
  sqlite4VdbeMemSetZeroBlob(&pCtx->s, n);
}
void sqlite4_result_error_code(sqlite4_context *pCtx, int errCode){
  pCtx->isError = errCode;
  if( pCtx->s.flags & MEM_Null ){
    sqlite4VdbeMemSetStr(&pCtx->s, sqlite4ErrStr(errCode), -1, 
                         SQLITE4_UTF8, SQLITE4_STATIC);
  }
}

/* Force an SQLITE4_TOOBIG error. */
void sqlite4_result_error_toobig(sqlite4_context *pCtx){
  assert( sqlite4_mutex_held(pCtx->s.db->mutex) );
  pCtx->isError = SQLITE4_TOOBIG;
  sqlite4VdbeMemSetStr(&pCtx->s, "string or blob too big", -1, 
                       SQLITE4_UTF8, SQLITE4_STATIC);
}

/* An SQLITE4_NOMEM error. */
void sqlite4_result_error_nomem(sqlite4_context *pCtx){
  assert( sqlite4_mutex_held(pCtx->s.db->mutex) );
  sqlite4VdbeMemSetNull(&pCtx->s);
  pCtx->isError = SQLITE4_NOMEM;
................................................................................
** argument to the user-function defined by pCtx. Any previous value is
** deleted by calling the delete function specified when it was set.
*/
void sqlite4_set_auxdata(
  sqlite4_context *pCtx, 
  int iArg, 
  void *pAux, 
  void (*xDelete)(void*)

){
  struct AuxData *pAuxData;
  VdbeFunc *pVdbeFunc;
  if( iArg<0 ) goto failed;

  assert( sqlite4_mutex_held(pCtx->s.db->mutex) );
  pVdbeFunc = pCtx->pVdbeFunc;
................................................................................
    memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
    pVdbeFunc->nAux = iArg+1;
    pVdbeFunc->pFunc = pCtx->pFunc;
  }

  pAuxData = &pVdbeFunc->apAux[iArg];
  if( pAuxData->pAux && pAuxData->xDelete ){
    pAuxData->xDelete(pAuxData->pAux);
  }
  pAuxData->pAux = pAux;
  pAuxData->xDelete = xDelete;

  return;

failed:
  if( xDelete ){
    xDelete(pAux);
  }
}

#ifndef SQLITE4_OMIT_DEPRECATED
/*
** Return the number of times the Step function of a aggregate has been 
** called.
................................................................................
  return SQLITE4_OK;
}

/*
** Bind a text or BLOB value.
*/
static int bindText(
  sqlite4_stmt *pStmt,   /* The statement to bind against */
  int i,                 /* Index of the parameter to bind */
  const void *zData,     /* Pointer to the data to be bound */
  int nData,             /* Number of bytes of data to be bound */
  void (*xDel)(void*),   /* Destructor for the data */

  u8 encoding            /* Encoding for the data */
){
  Vdbe *p = (Vdbe *)pStmt;
  Mem *pVar;
  int rc;

  rc = vdbeUnbind(p, i);
  if( rc==SQLITE4_OK ){
    if( zData!=0 ){
      pVar = &p->aVar[i-1];
      rc = sqlite4VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
      if( rc==SQLITE4_OK && encoding!=0 ){
        rc = sqlite4VdbeChangeEncoding(pVar, ENC(p->db));
      }
      sqlite4Error(p->db, rc, 0);
      rc = sqlite4ApiExit(p->db, rc);
    }
    sqlite4_mutex_leave(p->db->mutex);
  }else if( xDel!=SQLITE4_STATIC && xDel!=SQLITE4_TRANSIENT ){
    xDel((void*)zData);
  }
  return rc;
}


/*
** Bind a blob value to an SQL statement variable.
*/
int sqlite4_bind_blob(
  sqlite4_stmt *pStmt, 
  int i, 
  const void *zData, 
  int nData, 
  void (*xDel)(void*)

){
  return bindText(pStmt, i, zData, nData, xDel, 0);
}
int sqlite4_bind_double(sqlite4_stmt *pStmt, int i, double rValue){
  int rc;
  Vdbe *p = (Vdbe *)pStmt;
  rc = vdbeUnbind(p, i);
  if( rc==SQLITE4_OK ){
    sqlite4VdbeMemSetDouble(&p->aVar[i-1], rValue);
................................................................................
  return rc;
}
int sqlite4_bind_text( 
  sqlite4_stmt *pStmt, 
  int i, 
  const char *zData, 
  int nData, 
  void (*xDel)(void*)

){
  return bindText(pStmt, i, zData, nData, xDel, SQLITE4_UTF8);
}
#ifndef SQLITE4_OMIT_UTF16
int sqlite4_bind_text16(
  sqlite4_stmt *pStmt, 
  int i, 
  const void *zData, 
  int nData, 
  void (*xDel)(void*)

){
  return bindText(pStmt, i, zData, nData, xDel, SQLITE4_UTF16NATIVE);
}
#endif /* SQLITE4_OMIT_UTF16 */
int sqlite4_bind_value(sqlite4_stmt *pStmt, int i, const sqlite4_value *pValue){
  int rc;
  switch( pValue->type ){
    case SQLITE4_INTEGER: {
      rc = sqlite4_bind_int64(pStmt, i, pValue->u.i);
................................................................................
      rc = sqlite4_bind_double(pStmt, i, pValue->r);
      break;
    }
    case SQLITE4_BLOB: {
      if( pValue->flags & MEM_Zero ){
        rc = sqlite4_bind_zeroblob(pStmt, i, pValue->u.nZero);
      }else{
        rc = sqlite4_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE4_TRANSIENT);

      }
      break;
    }
    case SQLITE4_TEXT: {
      rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE4_TRANSIENT,
                              pValue->enc);
      break;
    }
    default: {
      rc = sqlite4_bind_null(pStmt, i);
      break;
    }







|
|
|
|
|
>






|







|
>



|








|





|







 







|
>


|






|
>


|





|
>


|





|
>


|







 







|








|







 







|
>







 







|



>




|







 







|
|
|
|
|
>
|









|








|













|
>

|







 







|
>

|







|
>

|







 







|
>




|







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
...
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
...
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
...
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
....
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
....
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
....
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
** the function result.
**
** The setStrOrError() funtion calls sqlite4VdbeMemSetStr() to store the
** result as a string or blob but if the string or blob is too large, it
** then sets the error code to SQLITE4_TOOBIG
*/
static void setResultStrOrError(
  sqlite4_context *pCtx,     /* Function context */
  const char *z,             /* String pointer */
  int n,                     /* Bytes in string, or negative */
  u8 enc,                    /* Encoding of z.  0 for BLOBs */
  void (*xDel)(void*,void*), /* Destructor function */
  void *pDelArg              /* First argument to xDel() */
){
  if( xDel==SQLITE4_DYNAMIC ){
    assert( sqlite4MemdebugHasType(z, MEMTYPE_HEAP) );
    assert( sqlite4MemdebugNoType(z, ~MEMTYPE_HEAP) );
    sqlite4MemdebugSetType((char*)z, MEMTYPE_DB | MEMTYPE_HEAP);
  }
  if( sqlite4VdbeMemSetStr(&pCtx->s, z, n, enc, xDel,pDelArg)==SQLITE4_TOOBIG ){
    sqlite4_result_error_toobig(pCtx);
  }
}
void sqlite4_result_blob(
  sqlite4_context *pCtx, 
  const void *z, 
  int n, 
  void (*xDel)(void*,void*),
  void *pDelArg
){
  assert( n>=0 );
  assert( sqlite4_mutex_held(pCtx->s.db->mutex) );
  setResultStrOrError(pCtx, z, n, 0, xDel, pDelArg);
}
void sqlite4_result_double(sqlite4_context *pCtx, double rVal){
  assert( sqlite4_mutex_held(pCtx->s.db->mutex) );
  sqlite4VdbeMemSetDouble(&pCtx->s, rVal);
}
void sqlite4_result_error(sqlite4_context *pCtx, const char *z, int n){
  assert( sqlite4_mutex_held(pCtx->s.db->mutex) );
  pCtx->isError = SQLITE4_ERROR;
  sqlite4VdbeMemSetStr(&pCtx->s, z, n, SQLITE4_UTF8, SQLITE4_TRANSIENT, 0);
}
#ifndef SQLITE4_OMIT_UTF16
void sqlite4_result_error16(sqlite4_context *pCtx, const void *z, int n){
  assert( sqlite4_mutex_held(pCtx->s.db->mutex) );
  pCtx->isError = SQLITE4_ERROR;
  sqlite4VdbeMemSetStr(&pCtx->s, z, n, SQLITE4_UTF16NATIVE,SQLITE4_TRANSIENT,0);
}
#endif
void sqlite4_result_int(sqlite4_context *pCtx, int iVal){
  assert( sqlite4_mutex_held(pCtx->s.db->mutex) );
  sqlite4VdbeMemSetInt64(&pCtx->s, (i64)iVal);
}
void sqlite4_result_int64(sqlite4_context *pCtx, i64 iVal){
................................................................................
  assert( sqlite4_mutex_held(pCtx->s.db->mutex) );
  sqlite4VdbeMemSetNull(&pCtx->s);
}
void sqlite4_result_text(
  sqlite4_context *pCtx, 
  const char *z, 
  int n,
  void (*xDel)(void*,void*),
  void *pDelArg
){
  assert( sqlite4_mutex_held(pCtx->s.db->mutex) );
  setResultStrOrError(pCtx, z, n, SQLITE4_UTF8, xDel, pDelArg);
}
#ifndef SQLITE4_OMIT_UTF16
void sqlite4_result_text16(
  sqlite4_context *pCtx, 
  const void *z, 
  int n, 
  void (*xDel)(void*,void*),
  void *pDelArg
){
  assert( sqlite4_mutex_held(pCtx->s.db->mutex) );
  setResultStrOrError(pCtx, z, n, SQLITE4_UTF16NATIVE, xDel, pDelArg);
}
void sqlite4_result_text16be(
  sqlite4_context *pCtx, 
  const void *z, 
  int n, 
  void (*xDel)(void*,void*),
  void *pDelArg
){
  assert( sqlite4_mutex_held(pCtx->s.db->mutex) );
  setResultStrOrError(pCtx, z, n, SQLITE4_UTF16BE, xDel, pDelArg);
}
void sqlite4_result_text16le(
  sqlite4_context *pCtx, 
  const void *z, 
  int n, 
  void (*xDel)(void*,void*),
  void *pDelArg
){
  assert( sqlite4_mutex_held(pCtx->s.db->mutex) );
  setResultStrOrError(pCtx, z, n, SQLITE4_UTF16LE, xDel, pDelArg);
}
#endif /* SQLITE4_OMIT_UTF16 */
void sqlite4_result_value(sqlite4_context *pCtx, sqlite4_value *pValue){
  assert( sqlite4_mutex_held(pCtx->s.db->mutex) );
  sqlite4VdbeMemCopy(&pCtx->s, pValue);
}
void sqlite4_result_zeroblob(sqlite4_context *pCtx, int n){
................................................................................
  assert( sqlite4_mutex_held(pCtx->s.db->mutex) );
  sqlite4VdbeMemSetZeroBlob(&pCtx->s, n);
}
void sqlite4_result_error_code(sqlite4_context *pCtx, int errCode){
  pCtx->isError = errCode;
  if( pCtx->s.flags & MEM_Null ){
    sqlite4VdbeMemSetStr(&pCtx->s, sqlite4ErrStr(errCode), -1, 
                         SQLITE4_UTF8, SQLITE4_STATIC, 0);
  }
}

/* Force an SQLITE4_TOOBIG error. */
void sqlite4_result_error_toobig(sqlite4_context *pCtx){
  assert( sqlite4_mutex_held(pCtx->s.db->mutex) );
  pCtx->isError = SQLITE4_TOOBIG;
  sqlite4VdbeMemSetStr(&pCtx->s, "string or blob too big", -1, 
                       SQLITE4_UTF8, SQLITE4_STATIC, 0);
}

/* An SQLITE4_NOMEM error. */
void sqlite4_result_error_nomem(sqlite4_context *pCtx){
  assert( sqlite4_mutex_held(pCtx->s.db->mutex) );
  sqlite4VdbeMemSetNull(&pCtx->s);
  pCtx->isError = SQLITE4_NOMEM;
................................................................................
** argument to the user-function defined by pCtx. Any previous value is
** deleted by calling the delete function specified when it was set.
*/
void sqlite4_set_auxdata(
  sqlite4_context *pCtx, 
  int iArg, 
  void *pAux, 
  void (*xDelete)(void*,void*),
  void *pDeleteArg
){
  struct AuxData *pAuxData;
  VdbeFunc *pVdbeFunc;
  if( iArg<0 ) goto failed;

  assert( sqlite4_mutex_held(pCtx->s.db->mutex) );
  pVdbeFunc = pCtx->pVdbeFunc;
................................................................................
    memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
    pVdbeFunc->nAux = iArg+1;
    pVdbeFunc->pFunc = pCtx->pFunc;
  }

  pAuxData = &pVdbeFunc->apAux[iArg];
  if( pAuxData->pAux && pAuxData->xDelete ){
    pAuxData->xDelete(pAuxData->pDeleteArg, pAuxData->pAux);
  }
  pAuxData->pAux = pAux;
  pAuxData->xDelete = xDelete;
  pAuxData->pDeleteArg = pDeleteArg;
  return;

failed:
  if( xDelete ){
    xDelete(pDeleteArg, pAux);
  }
}

#ifndef SQLITE4_OMIT_DEPRECATED
/*
** Return the number of times the Step function of a aggregate has been 
** called.
................................................................................
  return SQLITE4_OK;
}

/*
** Bind a text or BLOB value.
*/
static int bindText(
  sqlite4_stmt *pStmt,       /* The statement to bind against */
  int i,                     /* Index of the parameter to bind */
  const void *zData,         /* Pointer to the data to be bound */
  int nData,                 /* Number of bytes of data to be bound */
  void (*xDel)(void*,void*), /* Destructor for the data */
  void *pDelArg,             /* First argument to xDel() */
  u8 encoding                /* Encoding for the data */
){
  Vdbe *p = (Vdbe *)pStmt;
  Mem *pVar;
  int rc;

  rc = vdbeUnbind(p, i);
  if( rc==SQLITE4_OK ){
    if( zData!=0 ){
      pVar = &p->aVar[i-1];
      rc = sqlite4VdbeMemSetStr(pVar, zData, nData, encoding, xDel, pDelArg);
      if( rc==SQLITE4_OK && encoding!=0 ){
        rc = sqlite4VdbeChangeEncoding(pVar, ENC(p->db));
      }
      sqlite4Error(p->db, rc, 0);
      rc = sqlite4ApiExit(p->db, rc);
    }
    sqlite4_mutex_leave(p->db->mutex);
  }else if( xDel!=SQLITE4_STATIC && xDel!=SQLITE4_TRANSIENT ){
    xDel(pDelArg, (void*)zData);
  }
  return rc;
}


/*
** Bind a blob value to an SQL statement variable.
*/
int sqlite4_bind_blob(
  sqlite4_stmt *pStmt, 
  int i, 
  const void *zData, 
  int nData, 
  void (*xDel)(void*,void*),
  void *pDelArg
){
  return bindText(pStmt, i, zData, nData, xDel, pDelArg, 0);
}
int sqlite4_bind_double(sqlite4_stmt *pStmt, int i, double rValue){
  int rc;
  Vdbe *p = (Vdbe *)pStmt;
  rc = vdbeUnbind(p, i);
  if( rc==SQLITE4_OK ){
    sqlite4VdbeMemSetDouble(&p->aVar[i-1], rValue);
................................................................................
  return rc;
}
int sqlite4_bind_text( 
  sqlite4_stmt *pStmt, 
  int i, 
  const char *zData, 
  int nData, 
  void (*xDel)(void*,void*),
  void *pDelArg
){
  return bindText(pStmt, i, zData, nData, xDel, pDelArg, SQLITE4_UTF8);
}
#ifndef SQLITE4_OMIT_UTF16
int sqlite4_bind_text16(
  sqlite4_stmt *pStmt, 
  int i, 
  const void *zData, 
  int nData, 
  void (*xDel)(void*,void*),
  void *pDelArg
){
  return bindText(pStmt, i, zData, nData, xDel, pDelArg, SQLITE4_UTF16NATIVE);
}
#endif /* SQLITE4_OMIT_UTF16 */
int sqlite4_bind_value(sqlite4_stmt *pStmt, int i, const sqlite4_value *pValue){
  int rc;
  switch( pValue->type ){
    case SQLITE4_INTEGER: {
      rc = sqlite4_bind_int64(pStmt, i, pValue->u.i);
................................................................................
      rc = sqlite4_bind_double(pStmt, i, pValue->r);
      break;
    }
    case SQLITE4_BLOB: {
      if( pValue->flags & MEM_Zero ){
        rc = sqlite4_bind_zeroblob(pStmt, i, pValue->u.nZero);
      }else{
        rc = sqlite4_bind_blob(pStmt, i, pValue->z, pValue->n,
                               SQLITE4_TRANSIENT, 0);
      }
      break;
    }
    case SQLITE4_TEXT: {
      rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE4_TRANSIENT, 0,
                              pValue->enc);
      break;
    }
    default: {
      rc = sqlite4_bind_null(pStmt, i);
      break;
    }

Changes to src/vdbeaux.c.

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
...
148
149
150
151
152
153
154

155

156
157
158
159
160
161
162
...
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
....
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
....
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646


1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
....
1972
1973
1974
1975
1976
1977
1978
1979

1980
1981
1982
1983
1984
1985
1986
....
2019
2020
2021
2022
2023
2024
2025
2026

2027
2028
2029
2030
2031
2032
2033
....
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
** to version 2.8.7, all this code was combined into the vdbe.c source file.
** But that file was getting too big so this subroutines were split out.
*/
#include "sqliteInt.h"
#include "vdbeInt.h"



/*
** When debugging the code generator in a symbolic debugger, one can
** set the sqlite4VdbeAddopTrace to 1 and all opcodes will be printed
** as they are added to the instruction stream.
*/
#ifdef SQLITE4_DEBUG
int sqlite4VdbeAddopTrace = 0;
#endif


/*
** Create a new virtual database engine.
*/
Vdbe *sqlite4VdbeCreate(sqlite4 *db){
  Vdbe *p;
  p = sqlite4DbMallocZero(db, sizeof(Vdbe) );
  if( p==0 ) return 0;
................................................................................
  pOp->p1 = p1;
  pOp->p2 = p2;
  pOp->p3 = p3;
  pOp->p4.p = 0;
  pOp->p4type = P4_NOTUSED;
#ifdef SQLITE4_DEBUG
  pOp->zComment = 0;

  if( sqlite4VdbeAddopTrace ) sqlite4VdbePrintOp(0, i, &p->aOp[i]);

#endif
#ifdef VDBE_PROFILE
  pOp->cycles = 0;
  pOp->cnt = 0;
#endif
  return i;
}
................................................................................
      }
      pOut->p3 = pIn->p3;
      pOut->p4type = P4_NOTUSED;
      pOut->p4.p = 0;
      pOut->p5 = 0;
#ifdef SQLITE4_DEBUG
      pOut->zComment = 0;
      if( sqlite4VdbeAddopTrace ){
        sqlite4VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
      }
#endif
    }
    p->nOp += nOp;
  }
  return addr;
................................................................................
    if( sqlite4VdbeMemGrow(pMem, 32, 0) ){            /* P4 */
      assert( p->db->mallocFailed );
      return SQLITE4_ERROR;
    }
    pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
    z = displayP4(pOp, pMem->z, 32);
    if( z!=pMem->z ){
      sqlite4VdbeMemSetStr(pMem, z, -1, SQLITE4_UTF8, 0);
    }else{
      assert( pMem->z!=0 );
      pMem->n = sqlite4Strlen30(pMem->z);
      pMem->enc = SQLITE4_UTF8;
    }
    pMem->type = SQLITE4_TEXT;
    pMem++;
................................................................................
** to by zName will be freed by sqlite4DbFree() when the vdbe is destroyed.
*/
int sqlite4VdbeSetColName(
  Vdbe *p,                         /* Vdbe being configured */
  int idx,                         /* Index of column zName applies to */
  int var,                         /* One of the COLNAME_* constants */
  const char *zName,               /* Pointer to buffer containing name */
  void (*xDel)(void*)              /* Memory management strategy for zName */
){
  int rc;
  Mem *pColName;
  assert( idx<p->nResColumn );
  assert( var<COLNAME_N );


  if( p->db->mallocFailed ){
    assert( !zName || xDel!=SQLITE4_DYNAMIC );
    return SQLITE4_NOMEM;
  }
  assert( p->aColName!=0 );
  pColName = &(p->aColName[idx+var*p->nResColumn]);
  rc = sqlite4VdbeMemSetStr(pColName, zName, -1, SQLITE4_UTF8, xDel);
  assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
  return rc;
}

/*
** Free all Savepoint structures that correspond to transaction levels
** larger than iLevel. Passing iLevel==1 deletes all Savepoint structures.
................................................................................
*/
int sqlite4VdbeTransferError(Vdbe *p){
  sqlite4 *db = p->db;
  int rc = p->rc;
  if( p->zErrMsg ){
    u8 mallocFailed = db->mallocFailed;
    sqlite4BeginBenignMalloc(db->pEnv);
    sqlite4ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE4_UTF8, SQLITE4_TRANSIENT);

    sqlite4EndBenignMalloc(db->pEnv);
    db->mallocFailed = mallocFailed;
    db->errCode = rc;
  }else{
    sqlite4Error(db, rc, 0);
  }
  return rc;
................................................................................
    if( p->runOnlyOnce ) p->expired = 1;
  }else if( p->rc && p->expired ){
    /* The expired flag was set on the VDBE before the first call
    ** to sqlite4_step(). For consistency (since sqlite4_step() was
    ** called), set the database error in this case as well.
    */
    sqlite4Error(db, p->rc, 0);
    sqlite4ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE4_UTF8, SQLITE4_TRANSIENT);

    sqlite4DbFree(db, p->zErrMsg);
    p->zErrMsg = 0;
  }

  /* Reclaim all memory used by the VDBE
  */
  Cleanup(p);
................................................................................
*/
void sqlite4VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
  int i;
  for(i=0; i<pVdbeFunc->nAux; i++){
    struct AuxData *pAux = &pVdbeFunc->apAux[i];
    if( (i>31 || !(mask&(((u32)1)<<i))) && pAux->pAux ){
      if( pAux->xDelete ){
        pAux->xDelete(pAux->pAux);
      }
      pAux->pAux = 0;
    }
  }
}

/*







<
<
<
<
<
<
<
<
<
<
<







 







>
|
>







 







|







 







|







 







|





>
>






|







 







|
>







 







|
>







 







|







14
15
16
17
18
19
20











21
22
23
24
25
26
27
...
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
...
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
....
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
....
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
....
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
....
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
....
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
** to version 2.8.7, all this code was combined into the vdbe.c source file.
** But that file was getting too big so this subroutines were split out.
*/
#include "sqliteInt.h"
#include "vdbeInt.h"













/*
** Create a new virtual database engine.
*/
Vdbe *sqlite4VdbeCreate(sqlite4 *db){
  Vdbe *p;
  p = sqlite4DbMallocZero(db, sizeof(Vdbe) );
  if( p==0 ) return 0;
................................................................................
  pOp->p1 = p1;
  pOp->p2 = p2;
  pOp->p3 = p3;
  pOp->p4.p = 0;
  pOp->p4type = P4_NOTUSED;
#ifdef SQLITE4_DEBUG
  pOp->zComment = 0;
  if( p->db->flags & SQLITE4_VdbeAddopTrace ){
    sqlite4VdbePrintOp(0, i, &p->aOp[i]);
  }
#endif
#ifdef VDBE_PROFILE
  pOp->cycles = 0;
  pOp->cnt = 0;
#endif
  return i;
}
................................................................................
      }
      pOut->p3 = pIn->p3;
      pOut->p4type = P4_NOTUSED;
      pOut->p4.p = 0;
      pOut->p5 = 0;
#ifdef SQLITE4_DEBUG
      pOut->zComment = 0;
      if( p->db->flags & SQLITE4_VdbeAddopTrace ){
        sqlite4VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
      }
#endif
    }
    p->nOp += nOp;
  }
  return addr;
................................................................................
    if( sqlite4VdbeMemGrow(pMem, 32, 0) ){            /* P4 */
      assert( p->db->mallocFailed );
      return SQLITE4_ERROR;
    }
    pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
    z = displayP4(pOp, pMem->z, 32);
    if( z!=pMem->z ){
      sqlite4VdbeMemSetStr(pMem, z, -1, SQLITE4_UTF8, 0, 0);
    }else{
      assert( pMem->z!=0 );
      pMem->n = sqlite4Strlen30(pMem->z);
      pMem->enc = SQLITE4_UTF8;
    }
    pMem->type = SQLITE4_TEXT;
    pMem++;
................................................................................
** to by zName will be freed by sqlite4DbFree() when the vdbe is destroyed.
*/
int sqlite4VdbeSetColName(
  Vdbe *p,                         /* Vdbe being configured */
  int idx,                         /* Index of column zName applies to */
  int var,                         /* One of the COLNAME_* constants */
  const char *zName,               /* Pointer to buffer containing name */
  void (*xDel)(void*,void*)        /* Memory management strategy for zName */
){
  int rc;
  Mem *pColName;
  assert( idx<p->nResColumn );
  assert( var<COLNAME_N );
  assert( xDel==SQLITE4_STATIC || xDel==SQLITE4_TRANSIENT
             || xDel==SQLITE4_DYNAMIC );
  if( p->db->mallocFailed ){
    assert( !zName || xDel!=SQLITE4_DYNAMIC );
    return SQLITE4_NOMEM;
  }
  assert( p->aColName!=0 );
  pColName = &(p->aColName[idx+var*p->nResColumn]);
  rc = sqlite4VdbeMemSetStr(pColName, zName, -1, SQLITE4_UTF8, xDel, 0);
  assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
  return rc;
}

/*
** Free all Savepoint structures that correspond to transaction levels
** larger than iLevel. Passing iLevel==1 deletes all Savepoint structures.
................................................................................
*/
int sqlite4VdbeTransferError(Vdbe *p){
  sqlite4 *db = p->db;
  int rc = p->rc;
  if( p->zErrMsg ){
    u8 mallocFailed = db->mallocFailed;
    sqlite4BeginBenignMalloc(db->pEnv);
    sqlite4ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE4_UTF8,
                       SQLITE4_TRANSIENT, 0);
    sqlite4EndBenignMalloc(db->pEnv);
    db->mallocFailed = mallocFailed;
    db->errCode = rc;
  }else{
    sqlite4Error(db, rc, 0);
  }
  return rc;
................................................................................
    if( p->runOnlyOnce ) p->expired = 1;
  }else if( p->rc && p->expired ){
    /* The expired flag was set on the VDBE before the first call
    ** to sqlite4_step(). For consistency (since sqlite4_step() was
    ** called), set the database error in this case as well.
    */
    sqlite4Error(db, p->rc, 0);
    sqlite4ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE4_UTF8,
                       SQLITE4_TRANSIENT, 0);
    sqlite4DbFree(db, p->zErrMsg);
    p->zErrMsg = 0;
  }

  /* Reclaim all memory used by the VDBE
  */
  Cleanup(p);
................................................................................
*/
void sqlite4VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
  int i;
  for(i=0; i<pVdbeFunc->nAux; i++){
    struct AuxData *pAux = &pVdbeFunc->apAux[i];
    if( (i>31 || !(mask&(((u32)1)<<i))) && pAux->pAux ){
      if( pAux->xDelete ){
        pAux->xDelete(pAux->pDeleteArg, pAux->pAux);
      }
      pAux->pAux = 0;
    }
  }
}

/*

Changes to src/vdbecodec.c.

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
      e = (int)x;
      n += sqlite4GetVarint64(p->a+ofst+n, p->n-(ofst+n), &x);
      if( n!=size ) return SQLITE4_CORRUPT;
      r = (double)x;
      if( e&1 ) r = -r;
      if( e&2 ){
        e = -(e>>2);



        while( e<=-10 ){ r /= 1.0e10; e += 10; }
        while( e<0 ){ r /= 10.0; e++; }

      }else{
        e = e>>2;
        while( e>=10 ){ r *= 1.0e10; e -= 10; }
        while( e>0 ){ r *= 10.0; e--; }
      }
      sqlite4VdbeMemSetDouble(pOut, r);
    }else if( cclass==0 ){
      if( size==0 ){
        sqlite4VdbeMemSetStr(pOut, "", 0, SQLITE4_UTF8, SQLITE4_TRANSIENT);
      }else if( p->a[ofst]>0x02 ){
        sqlite4VdbeMemSetStr(pOut, (char*)(p->a+ofst), size, 
                             SQLITE4_UTF8, SQLITE4_TRANSIENT);
      }else{
        static const u8 enc[] = {SQLITE4_UTF8,SQLITE4_UTF16LE,SQLITE4_UTF16BE };
        sqlite4VdbeMemSetStr(pOut, (char*)(p->a+ofst+1), size-1, 
                             enc[p->a[ofst]], SQLITE4_TRANSIENT);
      }
    }else{
      sqlite4VdbeMemSetStr(pOut, (char*)(p->a+ofst), size, 0,SQLITE4_TRANSIENT);

    }
  }
  testcase( i==iVal );
  testcase( i==iVal+1 );
  if( i<=iVal ){
    if( pDefault ){
      sqlite4VdbeMemShallowCopy(pOut, pDefault, MEM_Static);







>
>
>
|
|
>








|


|



|


|
>







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
      e = (int)x;
      n += sqlite4GetVarint64(p->a+ofst+n, p->n-(ofst+n), &x);
      if( n!=size ) return SQLITE4_CORRUPT;
      r = (double)x;
      if( e&1 ) r = -r;
      if( e&2 ){
        e = -(e>>2);
        if( e==0 ){
          r *= 1e+300*1e+300;
        }else{
          while( e<=-10 ){ r /= 1.0e10; e += 10; }
          while( e<0 ){ r /= 10.0; e++; }
        }
      }else{
        e = e>>2;
        while( e>=10 ){ r *= 1.0e10; e -= 10; }
        while( e>0 ){ r *= 10.0; e--; }
      }
      sqlite4VdbeMemSetDouble(pOut, r);
    }else if( cclass==0 ){
      if( size==0 ){
        sqlite4VdbeMemSetStr(pOut, "", 0, SQLITE4_UTF8, SQLITE4_TRANSIENT, 0);
      }else if( p->a[ofst]>0x02 ){
        sqlite4VdbeMemSetStr(pOut, (char*)(p->a+ofst), size, 
                             SQLITE4_UTF8, SQLITE4_TRANSIENT, 0);
      }else{
        static const u8 enc[] = {SQLITE4_UTF8,SQLITE4_UTF16LE,SQLITE4_UTF16BE };
        sqlite4VdbeMemSetStr(pOut, (char*)(p->a+ofst+1), size-1, 
                             enc[p->a[ofst]], SQLITE4_TRANSIENT, 0);
      }
    }else{
      sqlite4VdbeMemSetStr(pOut, (char*)(p->a+ofst), size, 0,
                           SQLITE4_TRANSIENT, 0);
    }
  }
  testcase( i==iVal );
  testcase( i==iVal+1 );
  if( i<=iVal ){
    if( pDefault ){
      sqlite4VdbeMemShallowCopy(pOut, pDefault, MEM_Static);

Changes to src/vdbemem.c.

89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
...
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
...
632
633
634
635
636
637
638
639
640
641
642
643

644
645
646
647
648
649
650
...
691
692
693
694
695
696
697

698
699
700
701
702
703
704
...
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
...
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
....
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021

1022
1023
1024
1025
1026
1027
1028
1029
1030
  }

  if( pMem->z && preserve && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
    memcpy(pMem->zMalloc, pMem->z, pMem->n);
  }
  if( pMem->flags&MEM_Dyn && pMem->xDel ){
    assert( pMem->xDel!=SQLITE4_DYNAMIC );
    pMem->xDel((void *)(pMem->z));
  }

  pMem->z = pMem->zMalloc;
  if( pMem->z==0 ){
    pMem->flags = MEM_Null;
  }else{
    pMem->flags &= ~(MEM_Ephem|MEM_Static);
................................................................................
  if( p->flags&MEM_Agg ){
    sqlite4VdbeMemFinalize(p, p->u.pDef);
    assert( (p->flags & MEM_Agg)==0 );
    sqlite4VdbeMemRelease(p);
  }else if( p->flags&MEM_Dyn && p->xDel ){
    assert( (p->flags&MEM_RowSet)==0 );
    assert( p->xDel!=SQLITE4_DYNAMIC );
    p->xDel((void *)p->z);
    p->xDel = 0;
  }else if( p->flags&MEM_RowSet ){
    sqlite4RowSetClear(p->u.pRowSet);
  }else if( p->flags&MEM_Frame ){
    sqlite4VdbeMemSetNull(p);
  }
}
................................................................................
** If the string is too large (if it exceeds the SQLITE4_LIMIT_LENGTH
** size limit) then no memory allocation occurs.  If the string can be
** stored without allocating memory, then it is.  If a memory allocation
** is required to store the string, then value of pMem is unchanged.  In
** either case, SQLITE4_TOOBIG is returned.
*/
int sqlite4VdbeMemSetStr(
  Mem *pMem,          /* Memory cell to set to string value */
  const char *z,      /* String pointer */
  int n,              /* Bytes in string, or negative */
  u8 enc,             /* Encoding of z.  0 for BLOBs */
  void (*xDel)(void*) /* Destructor function */

){
  int nByte = n;      /* New value for pMem->n */
  int iLimit;         /* Maximum allowed string or blob size */
  u16 flags = 0;      /* New value for pMem->flags */

  assert( pMem->db==0 || sqlite4_mutex_held(pMem->db->mutex) );
  assert( (pMem->flags & MEM_RowSet)==0 );
................................................................................
    sqlite4VdbeMemRelease(pMem);
    pMem->zMalloc = pMem->z = (char *)z;
    pMem->xDel = 0;
  }else{
    sqlite4VdbeMemRelease(pMem);
    pMem->z = (char *)z;
    pMem->xDel = xDel;

    flags |= ((xDel==SQLITE4_STATIC)?MEM_Static:MEM_Dyn);
  }

  pMem->n = nByte;
  pMem->flags = flags;
  pMem->enc = (enc==0 ? SQLITE4_UTF8 : enc);
  pMem->type = (enc==0 ? SQLITE4_BLOB : SQLITE4_TEXT);
................................................................................
    pVal = sqlite4ValueNew(db);
    if( pVal==0 ) goto no_mem;
    if( ExprHasProperty(pExpr, EP_IntValue) ){
      sqlite4VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
    }else{
      zVal = sqlite4MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
      if( zVal==0 ) goto no_mem;
      sqlite4ValueSetStr(pVal, -1, zVal, SQLITE4_UTF8, SQLITE4_DYNAMIC);
      if( op==TK_FLOAT ) pVal->type = SQLITE4_FLOAT;
    }
    if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE4_AFF_NONE ){
      sqlite4ValueApplyAffinity(pVal, SQLITE4_AFF_NUMERIC, SQLITE4_UTF8);
    }else{
      sqlite4ValueApplyAffinity(pVal, affinity, SQLITE4_UTF8);
    }
................................................................................
    assert( pExpr->u.zToken[1]=='\'' );
    pVal = sqlite4ValueNew(db);
    if( !pVal ) goto no_mem;
    zVal = &pExpr->u.zToken[2];
    nVal = sqlite4Strlen30(zVal)-1;
    assert( zVal[nVal]=='\'' );
    sqlite4VdbeMemSetStr(pVal, sqlite4HexToBlob(db, zVal, nVal), nVal/2,
                         0, SQLITE4_DYNAMIC);
  }
#endif

  if( pVal ){
    sqlite4VdbeMemStoreType(pVal);
  }
  *ppVal = pVal;
................................................................................
  return SQLITE4_NOMEM;
}

/*
** Change the string value of an sqlite4_value object
*/
void sqlite4ValueSetStr(
  sqlite4_value *v,     /* Value to be set */
  int n,                /* Length of string z */
  const void *z,        /* Text of the new string */
  u8 enc,               /* Encoding to use */
  void (*xDel)(void*)   /* Destructor for the string */

){
  if( v ) sqlite4VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
}

/*
** Free an sqlite4_value object
*/
void sqlite4ValueFree(sqlite4_value *v){
  if( !v ) return;







|







 







|







 







|
|
|
|
|
>







 







>







 







|







 







|







 







|
|
|
|
|
>

|







89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
...
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
...
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
...
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
...
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
...
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
....
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
  }

  if( pMem->z && preserve && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
    memcpy(pMem->zMalloc, pMem->z, pMem->n);
  }
  if( pMem->flags&MEM_Dyn && pMem->xDel ){
    assert( pMem->xDel!=SQLITE4_DYNAMIC );
    pMem->xDel(pMem->pDelArg, (void *)(pMem->z));
  }

  pMem->z = pMem->zMalloc;
  if( pMem->z==0 ){
    pMem->flags = MEM_Null;
  }else{
    pMem->flags &= ~(MEM_Ephem|MEM_Static);
................................................................................
  if( p->flags&MEM_Agg ){
    sqlite4VdbeMemFinalize(p, p->u.pDef);
    assert( (p->flags & MEM_Agg)==0 );
    sqlite4VdbeMemRelease(p);
  }else if( p->flags&MEM_Dyn && p->xDel ){
    assert( (p->flags&MEM_RowSet)==0 );
    assert( p->xDel!=SQLITE4_DYNAMIC );
    p->xDel(p->pDelArg, (void *)p->z);
    p->xDel = 0;
  }else if( p->flags&MEM_RowSet ){
    sqlite4RowSetClear(p->u.pRowSet);
  }else if( p->flags&MEM_Frame ){
    sqlite4VdbeMemSetNull(p);
  }
}
................................................................................
** If the string is too large (if it exceeds the SQLITE4_LIMIT_LENGTH
** size limit) then no memory allocation occurs.  If the string can be
** stored without allocating memory, then it is.  If a memory allocation
** is required to store the string, then value of pMem is unchanged.  In
** either case, SQLITE4_TOOBIG is returned.
*/
int sqlite4VdbeMemSetStr(
  Mem *pMem,                /* Memory cell to set to string value */
  const char *z,            /* String pointer */
  int n,                    /* Bytes in string, or negative */
  u8 enc,                   /* Encoding of z.  0 for BLOBs */
  void (*xDel)(void*,void*),/* Destructor function */
  void *pDelArg             /* First argument to xDel() */
){
  int nByte = n;      /* New value for pMem->n */
  int iLimit;         /* Maximum allowed string or blob size */
  u16 flags = 0;      /* New value for pMem->flags */

  assert( pMem->db==0 || sqlite4_mutex_held(pMem->db->mutex) );
  assert( (pMem->flags & MEM_RowSet)==0 );
................................................................................
    sqlite4VdbeMemRelease(pMem);
    pMem->zMalloc = pMem->z = (char *)z;
    pMem->xDel = 0;
  }else{
    sqlite4VdbeMemRelease(pMem);
    pMem->z = (char *)z;
    pMem->xDel = xDel;
    pMem->pDelArg = pDelArg;
    flags |= ((xDel==SQLITE4_STATIC)?MEM_Static:MEM_Dyn);
  }

  pMem->n = nByte;
  pMem->flags = flags;
  pMem->enc = (enc==0 ? SQLITE4_UTF8 : enc);
  pMem->type = (enc==0 ? SQLITE4_BLOB : SQLITE4_TEXT);
................................................................................
    pVal = sqlite4ValueNew(db);
    if( pVal==0 ) goto no_mem;
    if( ExprHasProperty(pExpr, EP_IntValue) ){
      sqlite4VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
    }else{
      zVal = sqlite4MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
      if( zVal==0 ) goto no_mem;
      sqlite4ValueSetStr(pVal, -1, zVal, SQLITE4_UTF8, SQLITE4_DYNAMIC, 0);
      if( op==TK_FLOAT ) pVal->type = SQLITE4_FLOAT;
    }
    if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE4_AFF_NONE ){
      sqlite4ValueApplyAffinity(pVal, SQLITE4_AFF_NUMERIC, SQLITE4_UTF8);
    }else{
      sqlite4ValueApplyAffinity(pVal, affinity, SQLITE4_UTF8);
    }
................................................................................
    assert( pExpr->u.zToken[1]=='\'' );
    pVal = sqlite4ValueNew(db);
    if( !pVal ) goto no_mem;
    zVal = &pExpr->u.zToken[2];
    nVal = sqlite4Strlen30(zVal)-1;
    assert( zVal[nVal]=='\'' );
    sqlite4VdbeMemSetStr(pVal, sqlite4HexToBlob(db, zVal, nVal), nVal/2,
                         0, SQLITE4_DYNAMIC, 0);
  }
#endif

  if( pVal ){
    sqlite4VdbeMemStoreType(pVal);
  }
  *ppVal = pVal;
................................................................................
  return SQLITE4_NOMEM;
}

/*
** Change the string value of an sqlite4_value object
*/
void sqlite4ValueSetStr(
  sqlite4_value *v,          /* Value to be set */
  int n,                     /* Length of string z */
  const void *z,             /* Text of the new string */
  u8 enc,                    /* Encoding to use */
  void (*xDel)(void*,void*), /* Destructor for the string */
  void *pDelArg              /* First argument to xDel() */
){
  if( v ) sqlite4VdbeMemSetStr((Mem *)v, z, n, enc, xDel, pDelArg);
}

/*
** Free an sqlite4_value object
*/
void sqlite4ValueFree(sqlite4_value *v){
  if( !v ) return;

Changes to src/vdbetrace.c.

126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
      }else if( pVar->flags & MEM_Str ){
#ifndef SQLITE4_OMIT_UTF16
        u8 enc = ENC(db);
        if( enc!=SQLITE4_UTF8 ){
          Mem utf8;
          memset(&utf8, 0, sizeof(utf8));
          utf8.db = db;
          sqlite4VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE4_STATIC);
          sqlite4VdbeChangeEncoding(&utf8, SQLITE4_UTF8);
          sqlite4XPrintf(&out, "'%.*q'", utf8.n, utf8.z);
          sqlite4VdbeMemRelease(&utf8);
        }else
#endif
        {
          sqlite4XPrintf(&out, "'%.*q'", pVar->n, pVar->z);







|







126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
      }else if( pVar->flags & MEM_Str ){
#ifndef SQLITE4_OMIT_UTF16
        u8 enc = ENC(db);
        if( enc!=SQLITE4_UTF8 ){
          Mem utf8;
          memset(&utf8, 0, sizeof(utf8));
          utf8.db = db;
          sqlite4VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE4_STATIC, 0);
          sqlite4VdbeChangeEncoding(&utf8, SQLITE4_UTF8);
          sqlite4XPrintf(&out, "'%.*q'", utf8.n, utf8.z);
          sqlite4VdbeMemRelease(&utf8);
        }else
#endif
        {
          sqlite4XPrintf(&out, "'%.*q'", pVar->n, pVar->z);

Changes to test/ctime.test.

68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
...
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
    SELECT sqlite_compileoption_used('SQLITE4_THREADSAFE');
  }
} {0 1}
do_test ctime-1.4.2 {
  catchsql {
    SELECT sqlite_compileoption_used('THREADSAFE');
  }
} {0 1}
do_test ctime-1.4.3 {
  catchsql {
    SELECT sqlite_compileoption_used("THREADSAFE");
  }
} {0 1}

do_test ctime-1.5 {
  set ans1 [ catchsql {
    SELECT sqlite_compileoption_used('THREADSAFE=0');
  } ]
  set ans2 [ catchsql {
................................................................................
  }
} {1 {wrong number of arguments to function sqlite_compileoption_used()}}
do_test ctime-2.1.2 {
  catchsql {
    SELECT sqlite_compileoption_used(NULL);
  }
} {0 {{}}}
do_test ctime-2.1.3 {
  catchsql {
    SELECT sqlite_compileoption_used("");
  }
} {0 0}
do_test ctime-2.1.4 {
  catchsql {
    SELECT sqlite_compileoption_used('');
  }
} {0 0}
do_test ctime-2.1.5 {
  catchsql {







<
<
<
<
<







 







<
<
<
<
<







68
69
70
71
72
73
74





75
76
77
78
79
80
81
...
113
114
115
116
117
118
119





120
121
122
123
124
125
126
    SELECT sqlite_compileoption_used('SQLITE4_THREADSAFE');
  }
} {0 1}
do_test ctime-1.4.2 {
  catchsql {
    SELECT sqlite_compileoption_used('THREADSAFE');
  }





} {0 1}

do_test ctime-1.5 {
  set ans1 [ catchsql {
    SELECT sqlite_compileoption_used('THREADSAFE=0');
  } ]
  set ans2 [ catchsql {
................................................................................
  }
} {1 {wrong number of arguments to function sqlite_compileoption_used()}}
do_test ctime-2.1.2 {
  catchsql {
    SELECT sqlite_compileoption_used(NULL);
  }
} {0 {{}}}





do_test ctime-2.1.4 {
  catchsql {
    SELECT sqlite_compileoption_used('');
  }
} {0 0}
do_test ctime-2.1.5 {
  catchsql {

Changes to test/in.test.

269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
  }
} {1 2 3 4 6 8 10}

do_test in-8.1 {
  execsql {
    SELECT b FROM t1 WHERE a IN ('hello','there')
  }
} {world}
do_test in-8.2 {
  execsql {
    SELECT b FROM t1 WHERE a IN ("hello",'there')
  }
} {world}

# Test constructs of the form:  expr IN tablename
#
do_test in-9.1 {
  execsql {
    CREATE TABLE t4 AS SELECT a FROM tb;







<
<
<
<
<







269
270
271
272
273
274
275





276
277
278
279
280
281
282
  }
} {1 2 3 4 6 8 10}

do_test in-8.1 {
  execsql {
    SELECT b FROM t1 WHERE a IN ('hello','there')
  }





} {world}

# Test constructs of the form:  expr IN tablename
#
do_test in-9.1 {
  execsql {
    CREATE TABLE t4 AS SELECT a FROM tb;

Changes to test/join.test.

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
} {1 a xxx 2 b xxx 3 c {}}

# A test for ticket #247.
#
do_test join-7.1 {
  execsql {
    CREATE TABLE t7 (x, y);
    INSERT INTO t7 VALUES ("pa1", 1);
    INSERT INTO t7 VALUES ("pa2", NULL);
    INSERT INTO t7 VALUES ("pa3", NULL);
    INSERT INTO t7 VALUES ("pa4", 2);
    INSERT INTO t7 VALUES ("pa30", 131);
    INSERT INTO t7 VALUES ("pa31", 130);
    INSERT INTO t7 VALUES ("pa28", NULL);

    CREATE TABLE t8 (a integer primary key, b);
    INSERT INTO t8 VALUES (1, "pa1");
    INSERT INTO t8 VALUES (2, "pa4");
    INSERT INTO t8 VALUES (3, NULL);
    INSERT INTO t8 VALUES (4, NULL);
    INSERT INTO t8 VALUES (130, "pa31");
    INSERT INTO t8 VALUES (131, "pa30");

    SELECT coalesce(t8.a,999) from t7 LEFT JOIN t8 on y=a;
  }
} {1 999 999 2 131 130 999}

# Make sure a left join where the right table is really a view that
# is itself a join works right.  Ticket #306.







|
|
|
|
|
|
|


|
|


|
|







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
} {1 a xxx 2 b xxx 3 c {}}

# A test for ticket #247.
#
do_test join-7.1 {
  execsql {
    CREATE TABLE t7 (x, y);
    INSERT INTO t7 VALUES ('pa1', 1);
    INSERT INTO t7 VALUES ('pa2', NULL);
    INSERT INTO t7 VALUES ('pa3', NULL);
    INSERT INTO t7 VALUES ('pa4', 2);
    INSERT INTO t7 VALUES ('pa30', 131);
    INSERT INTO t7 VALUES ('pa31', 130);
    INSERT INTO t7 VALUES ('pa28', NULL);

    CREATE TABLE t8 (a integer primary key, b);
    INSERT INTO t8 VALUES (1, 'pa1');
    INSERT INTO t8 VALUES (2, 'pa4');
    INSERT INTO t8 VALUES (3, NULL);
    INSERT INTO t8 VALUES (4, NULL);
    INSERT INTO t8 VALUES (130, 'pa31');
    INSERT INTO t8 VALUES (131, 'pa30');

    SELECT coalesce(t8.a,999) from t7 LEFT JOIN t8 on y=a;
  }
} {1 999 999 2 131 130 999}

# Make sure a left join where the right table is really a view that
# is itself a join works right.  Ticket #306.

Added test/num.test.























































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
# 2001 September 15
#
# The author disclaims copyright to this source code.  In place of
# a legal notice, here is a blessing:
#
#    May you do good and not evil.
#    May you find forgiveness for yourself and forgive others.
#    May you share freely, never taking more than you give.
#
#***********************************************************************
# This file implements regression tests for SQLite library.  The
# focus of this file is testing the sqlite_*_printf() interface.
#
# $Id: printf.test,v 1.31 2009/02/01 00:21:10 drh Exp $

set testdir [file dirname $argv0]
source $testdir/tester.tcl

do_test num-1.1.1 {
  sqlite4_num_compare 20 20 
} {equal}
do_test num-1.1.2 {
  sqlite4_num_compare 20 2e1
} {equal}
do_test num-1.1.3 {
  sqlite4_num_compare -00034 -3.4e1
} {equal}
do_test num-1.1.4 {
  sqlite4_num_compare -inf +inf
} {lesser}
do_test num-1.1.5 {
  sqlite4_num_compare -inf 0
} {lesser}
do_test num-1.1.6 {
  sqlite4_num_compare inf 4
} {greater}
do_test num-1.1.7 {
  sqlite4_num_compare nan 7
} {incomparable}
# Is +0 > -0?
#do_test num-equal-1.1.4 {
#  sqlite4_num_compare +0 -0
#} {equal}

do_test num-2.1.1 {
  sqlite4_num_to_text [sqlite4_num_from_text 37]
} {37}
do_test num-2.1.2 {
  sqlite4_num_to_text [sqlite4_num_from_text 37 2]
} {37}
do_test num-2.1.4 {
  sqlite4_num_compare [sqlite4_num_from_text 2.9e2X 5] 290
} {equal}
do_test num-2.1.5 {
  sqlite4_num_isnan [sqlite4_num_from_text inf 2]
} {true}
do_test num-2.1.6 {
  sqlite4_num_isinf [sqlite4_num_from_text inf 3]
} {true}

do_test num-3.1.1 {
  sqlite4_num_to_text [sqlite4_num_add 5 7]
} {12}

do_test num-4.1.1 {
  sqlite4_num_to_text [sqlite4_num_sub 9 3]
} {6}
do_test num-4.1.2 {
  sqlite4_num_to_text [sqlite4_num_sub 5 12]
} {-7}
do_test num-4.2.1 {
  sqlite4_num_compare [sqlite4_num_sub 1 1] [sqlite4_num_sub -1 -1]
} {equal}

do_test num-5.1.1 {
  sqlite4_num_to_text [sqlite4_num_mul 9 8]
} {72}

do_test num-6.1.1 {
  sqlite4_num_to_text [sqlite4_num_div 6 5]
} {1.2}
do_test num-6.1.2 {
  sqlite4_num_compare 2 [sqlite4_num_div 2 1]
} {equal}
do_test num-6.1.3 {
  sqlite4_num_to_text [sqlite4_num_div 2 1]
} {2}
do_test num-6.1.4 {
  sqlite4_num_to_text [sqlite4_num_div 22 10]
} {2.2}
finish_test

Changes to test/quote.test.

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
} {0 {}}
do_test quote-1.2.1 {
  catchsql {SELECT * FROM '@abc'}
} {0 {5 hello}}
do_test quote-1.2.2 {
  catchsql {SELECT * FROM [@abc]}  ;# SqlServer compatibility
} {0 {5 hello}}
do_test quote-1.2.3 {
  catchsql {SELECT * FROM `@abc`}  ;# MySQL compatibility
} {0 {5 hello}}
do_test quote-1.3 {
  catchsql {
    SELECT '@abc'.'!pqr', '@abc'.'#xyz'+5 FROM '@abc'
  }
} {0 {hello 10}}
do_test quote-1.3.1 {
  catchsql {
................................................................................
    SELECT '!pqr', '#xyz'+5 FROM '@abc'
  }
} {0 {!pqr 5}}
do_test quote-1.3.2 {
  catchsql {
    SELECT "!pqr", "#xyz"+5 FROM '@abc'
  }
} {0 {hello 10}}
do_test quote-1.3.3 {
  catchsql {
    SELECT [!pqr], `#xyz`+5 FROM '@abc'
  }
} {0 {hello 10}}
do_test quote-1.3.4 {
  set r [catch {
    execsql {SELECT '@abc'.'!pqr', '@abc'.'#xyz'+5 FROM '@abc'}
  } msg ]
  lappend r $msg
} {0 {hello 10}}







<
<
<







 







<
<
<
<
<







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
} {0 {}}
do_test quote-1.2.1 {
  catchsql {SELECT * FROM '@abc'}
} {0 {5 hello}}
do_test quote-1.2.2 {
  catchsql {SELECT * FROM [@abc]}  ;# SqlServer compatibility
} {0 {5 hello}}



do_test quote-1.3 {
  catchsql {
    SELECT '@abc'.'!pqr', '@abc'.'#xyz'+5 FROM '@abc'
  }
} {0 {hello 10}}
do_test quote-1.3.1 {
  catchsql {
................................................................................
    SELECT '!pqr', '#xyz'+5 FROM '@abc'
  }
} {0 {!pqr 5}}
do_test quote-1.3.2 {
  catchsql {
    SELECT "!pqr", "#xyz"+5 FROM '@abc'
  }





} {0 {hello 10}}
do_test quote-1.3.4 {
  set r [catch {
    execsql {SELECT '@abc'.'!pqr', '@abc'.'#xyz'+5 FROM '@abc'}
  } msg ]
  lappend r $msg
} {0 {hello 10}}

Changes to test/select6.test.

161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
  execsql2 {
    SELECT * FROM (SELECT * FROM (SELECT * FROM t1 WHERE x=3));
  }
} {x 3 y 2}
do_test select6-3.2 {
  execsql {
    SELECT * FROM
      (SELECT a.q, a.p, b.r
       FROM (SELECT count(*) as p , b as q FROM t2 GROUP BY q) AS a,
            (SELECT max(a) as r, b as s FROM t2 GROUP BY s) as b
       WHERE a.q=b.s ORDER BY a.q)
    ORDER BY "a.q"
  }
} {1 1 1 2 2 3 3 4 7 4 8 15 5 5 20}
do_test select6-3.3 {
  execsql {
    SELECT a,b,a+b FROM (SELECT avg(x) as 'a', avg(y) as 'b' FROM t1)
  }
} {10.5 3.7 14.2}







|



|







161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
  execsql2 {
    SELECT * FROM (SELECT * FROM (SELECT * FROM t1 WHERE x=3));
  }
} {x 3 y 2}
do_test select6-3.2 {
  execsql {
    SELECT * FROM
      (SELECT a.q AS x, a.p, b.r
       FROM (SELECT count(*) as p , b as q FROM t2 GROUP BY q) AS a,
            (SELECT max(a) as r, b as s FROM t2 GROUP BY s) as b
       WHERE a.q=b.s ORDER BY a.q)
    ORDER BY x
  }
} {1 1 1 2 2 3 3 4 7 4 8 15 5 5 20}
do_test select6-3.3 {
  execsql {
    SELECT a,b,a+b FROM (SELECT avg(x) as 'a', avg(y) as 'b' FROM t1)
  }
} {10.5 3.7 14.2}

Changes to test/subquery.test.

385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
    INSERT INTO t4 VALUES('four',4);
    CREATE TABLE t5(a,b);
    INSERT INTO t5 VALUES(1,11);
    INSERT INTO t5 VALUES(2,22);
    INSERT INTO t5 VALUES(3,33);
    INSERT INTO t5 VALUES(4,44);
    SELECT b FROM t5 WHERE a IN 
       (SELECT callcnt(y)+0 FROM t4 WHERE x="two")
  }
} {22}
do_test subquery-5.2 {
  # This is the key test.  The subquery should have only run once.  If
  # The double-quoted identifier "two" were causing the subquery to be
  # processed as a correlated subquery, then it would have run 4 times.
  set callcnt







|







385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
    INSERT INTO t4 VALUES('four',4);
    CREATE TABLE t5(a,b);
    INSERT INTO t5 VALUES(1,11);
    INSERT INTO t5 VALUES(2,22);
    INSERT INTO t5 VALUES(3,33);
    INSERT INTO t5 VALUES(4,44);
    SELECT b FROM t5 WHERE a IN 
       (SELECT callcnt(y)+0 FROM t4 WHERE x='two')
  }
} {22}
do_test subquery-5.2 {
  # This is the key test.  The subquery should have only run once.  If
  # The double-quoted identifier "two" were causing the subquery to be
  # processed as a correlated subquery, then it would have run 4 times.
  set callcnt

Changes to test/test_func.c.

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
...
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
...
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
...
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
...
203
204
205
206
207
208
209
210

211
212
213
214
215

216
217
218
219
220
221
222
...
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
...
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
...
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
...
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
...
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
...
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
  }
  assert( n<sizeof(zBuf) );
  sqlite4_randomness(pEnv, n, zBuf);
  for(i=0; i<n; i++){
    zBuf[i] = zSrc[zBuf[i]%(sizeof(zSrc)-1)];
  }
  zBuf[n] = 0;
  sqlite4_result_text(context, (char*)zBuf, n, SQLITE4_TRANSIENT);
}

/*
** The following two SQL functions are used to test returning a text
** result with a destructor. Function 'test_destructor' takes one argument
** and returns the same argument interpreted as TEXT. A destructor is
** passed with the sqlite4_result_text() call.
................................................................................
**
** SQL function 'test_destructor_count' returns the number of outstanding 
** allocations made by 'test_destructor';
**
** WARNING: Not threadsafe.
*/
static int test_destructor_count_var = 0;
static void destructor(void *p){
  char *zVal = (char *)p;
  assert(zVal);
  zVal--;
  sqlite4_free(0, zVal);
  test_destructor_count_var--;
}
static void test_destructor(
................................................................................
  if( !zVal ){
    return;
  }
  zVal[len+1] = 0;
  zVal[len+2] = 0;
  zVal++;
  memcpy(zVal, sqlite4_value_text(argv[0]), len);
  sqlite4_result_text(pCtx, zVal, -1, destructor);
}
#ifndef SQLITE4_OMIT_UTF16
static void test_destructor16(
  sqlite4_context *pCtx, 
  int nArg,
  sqlite4_value **argv
){
................................................................................
  if( !zVal ){
    return;
  }
  zVal[len+1] = 0;
  zVal[len+2] = 0;
  zVal++;
  memcpy(zVal, sqlite4_value_text16(argv[0]), len);
  sqlite4_result_text16(pCtx, zVal, -1, destructor);
}
#endif
static void test_destructor_count(
  sqlite4_context *pCtx, 
  int nArg,
  sqlite4_value **argv
){
................................................................................
#ifndef SQLITE4_OMIT_UTF16
  const void *z;
  sqlite4 * db = sqlite4_context_db_handle(ctx);
  sqlite4_aggregate_context(ctx, 2048);
  sqlite4BeginBenignMalloc();
  z = sqlite4_errmsg16(db);
  sqlite4EndBenignMalloc();
  sqlite4_result_text16(ctx, z, -1, SQLITE4_TRANSIENT);
#endif
}

/*
** Routines for testing the sqlite4_get_auxdata() and sqlite4_set_auxdata()
** interface.
**
................................................................................
** The test_auxdata() SQL function attempts to register each of its arguments
** as auxiliary data.  If there are no prior registrations of aux data for
** that argument (meaning the argument is not a constant or this is its first
** call) then the result for that argument is 0.  If there is a prior
** registration, the result for that argument is 1.  The overall result
** is the individual argument results separated by spaces.
*/
static void free_test_auxdata(void *p) {sqlite4_free(0, p);}


static void test_auxdata(
  sqlite4_context *pCtx, 
  int nArg,
  sqlite4_value **argv
){
  int i;
  char *zRet = testContextMalloc(pCtx, nArg*2);

  if( !zRet ) return;
  memset(zRet, 0, nArg*2);
  for(i=0; i<nArg; i++){
    char const *z = (char*)sqlite4_value_text(argv[i]);
    if( z ){
      int n;
      char *zAux = sqlite4_get_auxdata(pCtx, i);
................................................................................
      }else {
        zRet[i*2] = '0';
      }
      n = strlen(z) + 1;
      zAux = testContextMalloc(pCtx, n);
      if( zAux ){
        memcpy(zAux, z, n);
        sqlite4_set_auxdata(pCtx, i, zAux, free_test_auxdata);

      }
      zRet[i*2+1] = ' ';
    }
  }
  sqlite4_result_text(pCtx, zRet, 2*nArg-1, free_test_auxdata);

}

/*
** A function to test error reporting from user functions. This function
** returns a copy of its first argument as the error message.  If the
** second argument exists, it becomes the error code.
*/
................................................................................
    sqlite4_result_error_code(pCtx, sqlite4_value_int(argv[1]));
  }
}

/* A counter object with its destructor.  Used by counterFunc() below.
*/
struct counterObject { int cnt; sqlite4_env *pEnv; };
void counterFree(void *x){
  struct counterObject *p = (struct counterObject*)x;
  sqlite4_free(p->pEnv, p);
}

/*
** Implementation of the counter(X) function.  If X is an integer
** constant, then the first invocation will return X.  The second X+1.
................................................................................
    pCounter = sqlite4_malloc(sqlite4_context_env(pCtx), sizeof(*pCounter) );
    if( pCounter==0 ){
      sqlite4_result_error_nomem(pCtx);
      return;
    }
    pCounter->cnt = sqlite4_value_int(argv[0]);
    pCounter->pEnv = sqlite4_context_env(pCtx);
    sqlite4_set_auxdata(pCtx, 0, pCounter, counterFree);
  }else{
    pCounter->cnt++;
  }
  sqlite4_result_int(pCtx, pCounter->cnt);
}


................................................................................
  }
  if( rc ){
    char *zErr;
    sqlite4_env *pEnv = sqlite4_context_env(pCtx);
    assert( pStmt==0 );
    zErr = sqlite4_mprintf(pEnv, "sqlite4_prepare() error: %s",
                           sqlite4_errmsg(db));
    sqlite4_result_text(pCtx, zErr, -1, SQLITE4_DYNAMIC);
    sqlite4_result_error_code(pCtx, rc);
  }
}


/*
** convert one character from hex to binary
................................................................................
  n = sqlite4_value_bytes(argv[0]);
  zIn = (const char*)sqlite4_value_text(argv[0]);
  zOut = sqlite4_malloc(sqlite4_context_env(pCtx), n/2 );
  if( zOut==0 ){
    sqlite4_result_error_nomem(pCtx);
  }else{
    testHexToBin(zIn, zOut);
    sqlite4_result_text16be(pCtx, zOut, n/2, SQLITE4_DYNAMIC);
  }
}
#endif

/*
**      hex_to_utf8(HEX)
**
................................................................................
  n = sqlite4_value_bytes(argv[0]);
  zIn = (const char*)sqlite4_value_text(argv[0]);
  zOut = sqlite4_malloc(sqlite4_context_env(pCtx), n/2 );
  if( zOut==0 ){
    sqlite4_result_error_nomem(pCtx);
  }else{
    testHexToBin(zIn, zOut);
    sqlite4_result_text(pCtx, zOut, n/2, SQLITE4_DYNAMIC);
  }
}

/*
**      hex_to_utf16le(HEX)
**
** Convert the input string from HEX into binary.  Then return the
................................................................................
  n = sqlite4_value_bytes(argv[0]);
  zIn = (const char*)sqlite4_value_text(argv[0]);
  zOut = sqlite4_malloc(sqlite4_context_env(pCtx), n/2 );
  if( zOut==0 ){
    sqlite4_result_error_nomem(pCtx);
  }else{
    testHexToBin(zIn, zOut);
    sqlite4_result_text16le(pCtx, zOut, n/2, SQLITE4_DYNAMIC);
  }
}
#endif

static int registerTestFunctions(sqlite4 *db){
  static const struct {
     char *zName;







|







 







|







 







|







 







|







 







|







 







|
>
>







>







 







|
>




|
>







 







|







 







|







 







|







 







|







 







|







 







|







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
...
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
...
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
...
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
...
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
...
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
...
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
...
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
...
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
...
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
...
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
  }
  assert( n<sizeof(zBuf) );
  sqlite4_randomness(pEnv, n, zBuf);
  for(i=0; i<n; i++){
    zBuf[i] = zSrc[zBuf[i]%(sizeof(zSrc)-1)];
  }
  zBuf[n] = 0;
  sqlite4_result_text(context, (char*)zBuf, n, SQLITE4_TRANSIENT, 0);
}

/*
** The following two SQL functions are used to test returning a text
** result with a destructor. Function 'test_destructor' takes one argument
** and returns the same argument interpreted as TEXT. A destructor is
** passed with the sqlite4_result_text() call.
................................................................................
**
** SQL function 'test_destructor_count' returns the number of outstanding 
** allocations made by 'test_destructor';
**
** WARNING: Not threadsafe.
*/
static int test_destructor_count_var = 0;
static void destructor(void *pNotUsed, void *p){
  char *zVal = (char *)p;
  assert(zVal);
  zVal--;
  sqlite4_free(0, zVal);
  test_destructor_count_var--;
}
static void test_destructor(
................................................................................
  if( !zVal ){
    return;
  }
  zVal[len+1] = 0;
  zVal[len+2] = 0;
  zVal++;
  memcpy(zVal, sqlite4_value_text(argv[0]), len);
  sqlite4_result_text(pCtx, zVal, -1, destructor, 0);
}
#ifndef SQLITE4_OMIT_UTF16
static void test_destructor16(
  sqlite4_context *pCtx, 
  int nArg,
  sqlite4_value **argv
){
................................................................................
  if( !zVal ){
    return;
  }
  zVal[len+1] = 0;
  zVal[len+2] = 0;
  zVal++;
  memcpy(zVal, sqlite4_value_text16(argv[0]), len);
  sqlite4_result_text16(pCtx, zVal, -1, destructor, 0);
}
#endif
static void test_destructor_count(
  sqlite4_context *pCtx, 
  int nArg,
  sqlite4_value **argv
){
................................................................................
#ifndef SQLITE4_OMIT_UTF16
  const void *z;
  sqlite4 * db = sqlite4_context_db_handle(ctx);
  sqlite4_aggregate_context(ctx, 2048);
  sqlite4BeginBenignMalloc();
  z = sqlite4_errmsg16(db);
  sqlite4EndBenignMalloc();
  sqlite4_result_text16(ctx, z, -1, SQLITE4_TRANSIENT, 0);
#endif
}

/*
** Routines for testing the sqlite4_get_auxdata() and sqlite4_set_auxdata()
** interface.
**
................................................................................
** The test_auxdata() SQL function attempts to register each of its arguments
** as auxiliary data.  If there are no prior registrations of aux data for
** that argument (meaning the argument is not a constant or this is its first
** call) then the result for that argument is 0.  If there is a prior
** registration, the result for that argument is 1.  The overall result
** is the individual argument results separated by spaces.
*/
static void free_test_auxdata(void *pEnv, void *p){
  sqlite4_free((sqlite4_env*)pEnv, p);
}
static void test_auxdata(
  sqlite4_context *pCtx, 
  int nArg,
  sqlite4_value **argv
){
  int i;
  char *zRet = testContextMalloc(pCtx, nArg*2);
  sqlite4_env *pEnv;
  if( !zRet ) return;
  memset(zRet, 0, nArg*2);
  for(i=0; i<nArg; i++){
    char const *z = (char*)sqlite4_value_text(argv[i]);
    if( z ){
      int n;
      char *zAux = sqlite4_get_auxdata(pCtx, i);
................................................................................
      }else {
        zRet[i*2] = '0';
      }
      n = strlen(z) + 1;
      zAux = testContextMalloc(pCtx, n);
      if( zAux ){
        memcpy(zAux, z, n);
        sqlite4_set_auxdata(pCtx, i, zAux,
                            free_test_auxdata, sqlite4_context_env(pCtx));
      }
      zRet[i*2+1] = ' ';
    }
  }
  sqlite4_result_text(pCtx, zRet, 2*nArg-1,
                      free_test_auxdata, sqlite4_context_env(pCtx));
}

/*
** A function to test error reporting from user functions. This function
** returns a copy of its first argument as the error message.  If the
** second argument exists, it becomes the error code.
*/
................................................................................
    sqlite4_result_error_code(pCtx, sqlite4_value_int(argv[1]));
  }
}

/* A counter object with its destructor.  Used by counterFunc() below.
*/
struct counterObject { int cnt; sqlite4_env *pEnv; };
void counterFree(void *NotUsed, void *x){
  struct counterObject *p = (struct counterObject*)x;
  sqlite4_free(p->pEnv, p);
}

/*
** Implementation of the counter(X) function.  If X is an integer
** constant, then the first invocation will return X.  The second X+1.
................................................................................
    pCounter = sqlite4_malloc(sqlite4_context_env(pCtx), sizeof(*pCounter) );
    if( pCounter==0 ){
      sqlite4_result_error_nomem(pCtx);
      return;
    }
    pCounter->cnt = sqlite4_value_int(argv[0]);
    pCounter->pEnv = sqlite4_context_env(pCtx);
    sqlite4_set_auxdata(pCtx, 0, pCounter, counterFree, 0);
  }else{
    pCounter->cnt++;
  }
  sqlite4_result_int(pCtx, pCounter->cnt);
}


................................................................................
  }
  if( rc ){
    char *zErr;
    sqlite4_env *pEnv = sqlite4_context_env(pCtx);
    assert( pStmt==0 );
    zErr = sqlite4_mprintf(pEnv, "sqlite4_prepare() error: %s",
                           sqlite4_errmsg(db));
    sqlite4_result_text(pCtx, zErr, -1, SQLITE4_DYNAMIC, 0);
    sqlite4_result_error_code(pCtx, rc);
  }
}


/*
** convert one character from hex to binary
................................................................................
  n = sqlite4_value_bytes(argv[0]);
  zIn = (const char*)sqlite4_value_text(argv[0]);
  zOut = sqlite4_malloc(sqlite4_context_env(pCtx), n/2 );
  if( zOut==0 ){
    sqlite4_result_error_nomem(pCtx);
  }else{
    testHexToBin(zIn, zOut);
    sqlite4_result_text16be(pCtx, zOut, n/2, SQLITE4_DYNAMIC, 0);
  }
}
#endif

/*
**      hex_to_utf8(HEX)
**
................................................................................
  n = sqlite4_value_bytes(argv[0]);
  zIn = (const char*)sqlite4_value_text(argv[0]);
  zOut = sqlite4_malloc(sqlite4_context_env(pCtx), n/2 );
  if( zOut==0 ){
    sqlite4_result_error_nomem(pCtx);
  }else{
    testHexToBin(zIn, zOut);
    sqlite4_result_text(pCtx, zOut, n/2, SQLITE4_DYNAMIC, 0);
  }
}

/*
**      hex_to_utf16le(HEX)
**
** Convert the input string from HEX into binary.  Then return the
................................................................................
  n = sqlite4_value_bytes(argv[0]);
  zIn = (const char*)sqlite4_value_text(argv[0]);
  zOut = sqlite4_malloc(sqlite4_context_env(pCtx), n/2 );
  if( zOut==0 ){
    sqlite4_result_error_nomem(pCtx);
  }else{
    testHexToBin(zIn, zOut);
    sqlite4_result_text16le(pCtx, zOut, n/2, SQLITE4_DYNAMIC, 0);
  }
}
#endif

static int registerTestFunctions(sqlite4 *db){
  static const struct {
     char *zName;

Changes to test/test_kv2.c.

287
288
289
290
291
292
293
294
295













296
297
298
299
300
301
302
...
340
341
342
343
344
345
346
347
348
349
350

351
352
353
354
355
356
357
static int kvwrap_install_cmd(Tcl_Interp *interp, int objc, Tcl_Obj **objv){
  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 2, objv, "");
    return TCL_ERROR;
  }

  if( kvwg.xFactory==0 ){
    sqlite4_env_config(0, SQLITE4_ENVCONFIG_KVSTORE_GET, "main", &kvwg.xFactory);
    sqlite4_env_config(0, SQLITE4_ENVCONFIG_KVSTORE_PUSH, "main",newFileStorage);













  }
  return TCL_OK;
}

static int kvwrap_seek_cmd(Tcl_Interp *interp, int objc, Tcl_Obj **objv){
  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 2, objv, "");
................................................................................
  int objc,
  Tcl_Obj *CONST objv[]
){
  struct Subcmd {
    const char *zCmd;
    int (*xCmd)(Tcl_Interp *, int, Tcl_Obj **);
  } aSub[] = {
    { "install", kvwrap_install_cmd },
    { "step",    kvwrap_step_cmd },
    { "seek",    kvwrap_seek_cmd },
    { "reset",   kvwrap_reset_cmd },

  };
  int iSub;
  int rc;

  rc = Tcl_GetIndexFromObjStruct(
      interp, objv[1], aSub, sizeof(aSub[0]), "sub-command", 0, &iSub
  );







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







 







|
|
|
|
>







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
...
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
static int kvwrap_install_cmd(Tcl_Interp *interp, int objc, Tcl_Obj **objv){
  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 2, objv, "");
    return TCL_ERROR;
  }

  if( kvwg.xFactory==0 ){
    sqlite4_env_config(0, SQLITE4_ENVCONFIG_KVSTORE_GET,"main", &kvwg.xFactory);
    sqlite4_env_config(0, SQLITE4_ENVCONFIG_KVSTORE_PUSH,"main",newFileStorage);
  }
  return TCL_OK;
}

static int kvwrap_uninstall_cmd(Tcl_Interp *interp, int objc, Tcl_Obj **objv){
  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 2, objv, "");
    return TCL_ERROR;
  }

  if( kvwg.xFactory ){
    sqlite4_env_config(0, SQLITE4_ENVCONFIG_KVSTORE_POP,"main", &kvwg.xFactory);
    kvwg.xFactory = 0;
  }
  return TCL_OK;
}

static int kvwrap_seek_cmd(Tcl_Interp *interp, int objc, Tcl_Obj **objv){
  if( objc!=2 ){
    Tcl_WrongNumArgs(interp, 2, objv, "");
................................................................................
  int objc,
  Tcl_Obj *CONST objv[]
){
  struct Subcmd {
    const char *zCmd;
    int (*xCmd)(Tcl_Interp *, int, Tcl_Obj **);
  } aSub[] = {
    { "install",   kvwrap_install_cmd },
    { "step",      kvwrap_step_cmd },
    { "seek",      kvwrap_seek_cmd },
    { "reset",     kvwrap_reset_cmd },
    { "uninstall", kvwrap_uninstall_cmd },
  };
  int iSub;
  int rc;

  rc = Tcl_GetIndexFromObjStruct(
      interp, objv[1], aSub, sizeof(aSub[0]), "sub-command", 0, &iSub
  );

Changes to test/test_main.c.

682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
...
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
...
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
...
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
...
965
966
967
968
969
970
971
972

973
974
975
976
977
978
979
....
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
....
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
....
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
....
2385
2386
2387
2388
2389
2390
2391
2392

2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
....
2411
2412
2413
2414
2415
2416
2417
2418
2419

2420
2421
2422
2423
2424
2425
2426
....
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
....
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
....
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
....
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
....
4345
4346
4347
4348
4349
4350
4351







































































































































































































4352
4353
4354
4355
4356
4357
4358
....
4398
4399
4400
4401
4402
4403
4404
4405









4406
4407
4408
4409
4410
4411
4412
....
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
....
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
  sqlite4_value **argv
){
  int i;
  for(i=0; i<argc; i++){
    if( SQLITE4_NULL!=sqlite4_value_type(argv[i]) ){
      int n = sqlite4_value_bytes(argv[i]);
      sqlite4_result_text(context, (char*)sqlite4_value_text(argv[i]),
          n, SQLITE4_TRANSIENT);
      break;
    }
  }
}

/*
** These are test functions.    hex8() interprets its argument as
................................................................................
  int i;
  char zBuf[200];
  z = sqlite4_value_text(argv[0]);
  for(i=0; i<sizeof(zBuf)/2 - 2 && z[i]; i++){
    sprintf(&zBuf[i*2], "%02x", z[i]&0xff);
  }
  zBuf[i*2] = 0;
  sqlite4_result_text(p, (char*)zBuf, -1, SQLITE4_TRANSIENT);
}
#ifndef SQLITE4_OMIT_UTF16
static void hex16Func(sqlite4_context *p, int argc, sqlite4_value **argv){
  const unsigned short int *z;
  int i;
  char zBuf[400];
  z = sqlite4_value_text16(argv[0]);
  for(i=0; i<sizeof(zBuf)/4 - 4 && z[i]; i++){
    sprintf(&zBuf[i*4], "%04x", z[i]&0xff);
  }
  zBuf[i*4] = 0;
  sqlite4_result_text(p, (char*)zBuf, -1, SQLITE4_TRANSIENT);
}
#endif

/*
** A structure into which to accumulate text.
*/
struct dstr {
................................................................................
  sqlite4_value **argv
){
  struct dstr x;
  memset(&x, 0, sizeof(x));
  (void)sqlite4_exec((sqlite4*)sqlite4_user_data(context),
      (char*)sqlite4_value_text(argv[0]),
      execFuncCallback, &x, 0);
  sqlite4_result_text(context, x.z, x.nUsed, SQLITE4_TRANSIENT);
  sqlite4_free(0, x.z);
}

/*
** Implementation of tkt2213func(), a scalar function that takes exactly
** one argument. It has two interesting features:
**
................................................................................
  zText3 = sqlite4_value_text(argv[0]);

  if( zText1!=zText2 || zText2!=zText3 ){
    sqlite4_result_error(context, "tkt2213 is not fixed", -1);
  }else{
    char *zCopy = (char *)sqlite4_malloc(sqlite4_context_env(context),nText);
    memcpy(zCopy, zText1, nText);
    sqlite4_result_text(context, zCopy, nText, SQLITE4_DYNAMIC);
  }
}

/*
** The following SQL function takes 4 arguments.  The 2nd and
** 4th argument must be one of these strings:  'text', 'text16',
** or 'blob' corresponding to API functions
................................................................................
  /* Use the sqlite4_create_function16() API here. Mainly for fun, but also 
  ** because it is not tested anywhere else. */
  if( rc==SQLITE4_OK ){
    const void *zUtf16;
    sqlite4_value *pVal;
    sqlite4_mutex_enter(db->mutex);
    pVal = sqlite4ValueNew(db);
    sqlite4ValueSetStr(pVal, -1, "x_sqlite_exec", SQLITE4_UTF8, SQLITE4_STATIC);

    zUtf16 = sqlite4ValueText(pVal, SQLITE4_UTF16NATIVE);
    if( db->mallocFailed ){
      rc = SQLITE4_NOMEM;
    }else{
      rc = sqlite4_create_function16(db, zUtf16, 
                1, SQLITE4_UTF16, db, sqlite4ExecFunc, 0, 0);
    }
................................................................................
    if( zArg0 ){
      if( 0==sqlite4_stricmp(zArg0, "int") ){
        sqlite4_result_int(context, sqlite4_value_int(argv[1]));
      }else if( sqlite4_stricmp(zArg0,"int64")==0 ){
        sqlite4_result_int64(context, sqlite4_value_int64(argv[1]));
      }else if( sqlite4_stricmp(zArg0,"string")==0 ){
        sqlite4_result_text(context, (char*)sqlite4_value_text(argv[1]), -1,
            SQLITE4_TRANSIENT);
      }else if( sqlite4_stricmp(zArg0,"double")==0 ){
        sqlite4_result_double(context, sqlite4_value_double(argv[1]));
      }else if( sqlite4_stricmp(zArg0,"null")==0 ){
        sqlite4_result_null(context);
      }else if( sqlite4_stricmp(zArg0,"value")==0 ){
        sqlite4_result_value(context, argv[sqlite4_value_int(argv[1])]);
      }else{
................................................................................
    return TCL_ERROR;
  }
  if( getStmtPointer(interp, argv[1], &pStmt) ) return TCL_ERROR;
  if( Tcl_GetInt(interp, argv[2], &idx) ) return TCL_ERROR;
  if( strcmp(argv[4],"null")==0 ){
    rc = sqlite4_bind_null(pStmt, idx);
  }else if( strcmp(argv[4],"static")==0 ){
    rc = sqlite4_bind_text(pStmt, idx, sqlite_static_bind_value, -1, 0);
  }else if( strcmp(argv[4],"static-nbytes")==0 ){
    rc = sqlite4_bind_text(pStmt, idx, sqlite_static_bind_value,
                                       sqlite_static_bind_nbyte, 0);
  }else if( strcmp(argv[4],"normal")==0 ){
    rc = sqlite4_bind_text(pStmt, idx, argv[3], -1, SQLITE4_TRANSIENT);
  }else if( strcmp(argv[4],"blob10")==0 ){
    rc = sqlite4_bind_text(pStmt, idx, "abc\000xyz\000pq", 10, SQLITE4_STATIC);
  }else{
    Tcl_AppendResult(interp, "4th argument should be "
        "\"null\" or \"static\" or \"normal\"", 0);
    return TCL_ERROR;
  }
  if( sqlite4TestErrCode(interp, StmtToDb(pStmt), rc) ) return TCL_ERROR;
  if( rc ){
................................................................................
    default:
      assert(0);
  }

  sqlite4BeginBenignMalloc(pEnv);
  pVal = sqlite4ValueNew(0);
  if( pVal ){
    sqlite4ValueSetStr(pVal, nA, zA, encin, SQLITE4_STATIC);
    n = sqlite4_value_bytes(pVal);
    Tcl_ListObjAppendElement(i,pX,
        Tcl_NewStringObj((char*)sqlite4_value_text(pVal),n));
    sqlite4ValueSetStr(pVal, nB, zB, encin, SQLITE4_STATIC);
    n = sqlite4_value_bytes(pVal);
    Tcl_ListObjAppendElement(i,pX,
        Tcl_NewStringObj((char*)sqlite4_value_text(pVal),n));
    sqlite4ValueFree(pVal);
  }
  sqlite4EndBenignMalloc(pEnv);

................................................................................
  pX = Tcl_NewStringObj("test_function", -1);
  Tcl_IncrRefCount(pX);
  Tcl_ListObjAppendElement(interp, pX, Tcl_NewStringObj("UTF-8", -1));
  Tcl_ListObjAppendElement(interp, pX, 
      Tcl_NewStringObj((char*)sqlite4_value_text(argv[0]), -1));
  Tcl_EvalObjEx(interp, pX, 0);
  Tcl_DecrRefCount(pX);
  sqlite4_result_text(pCtx, Tcl_GetStringResult(interp), -1, SQLITE4_TRANSIENT);

  pVal = sqlite4ValueNew(0);
  sqlite4ValueSetStr(pVal, -1, Tcl_GetStringResult(interp), 
      SQLITE4_UTF8, SQLITE4_STATIC);
  sqlite4_result_text16be(pCtx, sqlite4_value_text16be(pVal),
      -1, SQLITE4_TRANSIENT);
  sqlite4ValueFree(pVal);
}
static void test_function_utf16le(
  sqlite4_context *pCtx, 
  int nArg,
  sqlite4_value **argv
){
................................................................................
  Tcl_ListObjAppendElement(interp, pX, Tcl_NewStringObj("UTF-16LE", -1));
  Tcl_ListObjAppendElement(interp, pX, 
      Tcl_NewStringObj((char*)sqlite4_value_text(argv[0]), -1));
  Tcl_EvalObjEx(interp, pX, 0);
  Tcl_DecrRefCount(pX);
  pVal = sqlite4ValueNew(0);
  sqlite4ValueSetStr(pVal, -1, Tcl_GetStringResult(interp), 
      SQLITE4_UTF8, SQLITE4_STATIC);
  sqlite4_result_text(pCtx,(char*)sqlite4_value_text(pVal),-1,SQLITE4_TRANSIENT);

  sqlite4ValueFree(pVal);
}
static void test_function_utf16be(
  sqlite4_context *pCtx, 
  int nArg,
  sqlite4_value **argv
){
................................................................................
  Tcl_ListObjAppendElement(interp, pX, Tcl_NewStringObj("UTF-16BE", -1));
  Tcl_ListObjAppendElement(interp, pX, 
      Tcl_NewStringObj((char*)sqlite4_value_text(argv[0]), -1));
  Tcl_EvalObjEx(interp, pX, 0);
  Tcl_DecrRefCount(pX);
  pVal = sqlite4ValueNew(0);
  sqlite4ValueSetStr(pVal, -1, Tcl_GetStringResult(interp), 
      SQLITE4_UTF8, SQLITE4_STATIC);
  sqlite4_result_text16(pCtx, sqlite4_value_text16le(pVal),
      -1, SQLITE4_TRANSIENT);
  sqlite4_result_text16be(pCtx, sqlite4_value_text16le(pVal),
      -1, SQLITE4_TRANSIENT);
  sqlite4_result_text16le(pCtx, sqlite4_value_text16le(pVal),
      -1, SQLITE4_TRANSIENT);
  sqlite4ValueFree(pVal);
}
#endif /* SQLITE4_OMIT_UTF16 */
static int test_function(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
................................................................................
  }

  if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
  if( Tcl_GetIntFromObj(interp, objv[2], &idx) ) return TCL_ERROR;
  value = (char*)Tcl_GetByteArrayFromObj(objv[3], &bytes);
  if( Tcl_GetIntFromObj(interp, objv[4], &bytes) ) return TCL_ERROR;

  rc = sqlite4_bind_text(pStmt, idx, value, bytes, SQLITE4_TRANSIENT);
  if( sqlite4TestErrCode(interp, StmtToDb(pStmt), rc) ) return TCL_ERROR;
  if( rc!=SQLITE4_OK ){
    Tcl_AppendResult(interp, sqlite4TestErrorName(rc), 0);
    return TCL_ERROR;
  }

  return TCL_OK;
................................................................................
  }

  if( getStmtPointer(interp, Tcl_GetString(oStmt), &pStmt) ) return TCL_ERROR;
  if( Tcl_GetIntFromObj(interp, oN, &idx) ) return TCL_ERROR;
  value = (char*)Tcl_GetByteArrayFromObj(oString, 0);
  if( Tcl_GetIntFromObj(interp, oBytes, &bytes) ) return TCL_ERROR;

  rc = sqlite4_bind_text16(pStmt, idx, (void *)value, bytes, xDel);
  if( sqlite4TestErrCode(interp, StmtToDb(pStmt), rc) ) return TCL_ERROR;
  if( rc!=SQLITE4_OK ){
    Tcl_AppendResult(interp, sqlite4TestErrorName(rc), 0);
    return TCL_ERROR;
  }

#endif /* SQLITE4_OMIT_UTF16 */
................................................................................
  }

  if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
  if( Tcl_GetIntFromObj(interp, objv[2], &idx) ) return TCL_ERROR;
  value = Tcl_GetString(objv[3]);
  if( Tcl_GetIntFromObj(interp, objv[4], &bytes) ) return TCL_ERROR;

  rc = sqlite4_bind_blob(pStmt, idx, value, bytes, xDestructor);
  if( sqlite4TestErrCode(interp, StmtToDb(pStmt), rc) ) return TCL_ERROR;
  if( rc!=SQLITE4_OK ){
    return TCL_ERROR;
  }

  return TCL_OK;
}
................................................................................
      Tcl_AppendResult(interp, " ", aOpt[i].zOptName);
    }
    return TCL_ERROR;
  }
  sqlite4_test_control(SQLITE4_TESTCTRL_OPTIMIZATIONS, db, mask);
  return TCL_OK;
}








































































































































































































/*
** Register commands with the TCL interpreter.
*/
int Sqlitetest1_Init(Tcl_Interp *interp){
  extern int sqlite4_search_count;
  extern int sqlite4_found_count;
................................................................................
     { "sqlite_set_magic",              (Tcl_CmdProc*)sqlite_set_magic      },
     { "sqlite4_interrupt",             (Tcl_CmdProc*)test_interrupt        },
     { "sqlite_delete_function",        (Tcl_CmdProc*)delete_function       },
     { "sqlite_delete_collation",       (Tcl_CmdProc*)delete_collation      },
     { "sqlite4_get_autocommit",        (Tcl_CmdProc*)get_autocommit        },
     { "sqlite4_stack_used",            (Tcl_CmdProc*)test_stack_used       },
     { "printf",                        (Tcl_CmdProc*)test_printf           },
     { "sqlite4IoTrace",              (Tcl_CmdProc*)test_io_trace         },









  };
  static struct {
     char *zName;
     Tcl_ObjCmdProc *xProc;
     void *clientData;
  } aObjCmd[] = {
     { "sqlite4_connection_pointer",    get_sqlite_pointer, 0 },
................................................................................
  extern int sqlite4_pager_writej_count;
#if SQLITE4_OS_WIN
  extern int sqlite4_os_type;
#endif
#ifdef SQLITE4_DEBUG
  extern int sqlite4WhereTrace;
  extern int sqlite4OSTrace;
  extern int sqlite4VdbeAddopTrace;
#endif
#ifdef SQLITE4_TEST
  extern char sqlite4_query_plan[];
  static char *query_plan = sqlite4_query_plan;
#ifdef SQLITE4_ENABLE_FTS3
  extern int sqlite4_fts3_enable_parentheses;
#endif
................................................................................
      (char*)&sqlite4_os_type, TCL_LINK_INT);
#endif
#ifdef SQLITE4_TEST
  Tcl_LinkVar(interp, "sqlite_query_plan",
      (char*)&query_plan, TCL_LINK_STRING|TCL_LINK_READ_ONLY);
#endif
#ifdef SQLITE4_DEBUG
  Tcl_LinkVar(interp, "sqlite_addop_trace",
      (char*)&sqlite4VdbeAddopTrace, TCL_LINK_INT);
  Tcl_LinkVar(interp, "sqlite_where_trace",
      (char*)&sqlite4WhereTrace, TCL_LINK_INT);
#endif
  Tcl_LinkVar(interp, "sqlite_static_bind_value",
      (char*)&sqlite_static_bind_value, TCL_LINK_STRING);
  Tcl_LinkVar(interp, "sqlite_static_bind_nbyte",
      (char*)&sqlite_static_bind_nbyte, TCL_LINK_INT);







|







 







|











|







 







|







 







|







 







|
>







 







|







 







|


|

|

|







 







|



|







 







|
>


|

|







 







|
|
>







 







|

|

|

|







 







|







 







|







 







|







 







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







 







|
>
>
>
>
>
>
>
>
>







 







<







 







<
<







682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
...
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
...
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
...
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
...
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
....
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
....
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
....
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
....
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
....
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
....
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
....
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
....
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
....
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
....
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
....
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
....
4730
4731
4732
4733
4734
4735
4736

4737
4738
4739
4740
4741
4742
4743
....
4784
4785
4786
4787
4788
4789
4790


4791
4792
4793
4794
4795
4796
4797
  sqlite4_value **argv
){
  int i;
  for(i=0; i<argc; i++){
    if( SQLITE4_NULL!=sqlite4_value_type(argv[i]) ){
      int n = sqlite4_value_bytes(argv[i]);
      sqlite4_result_text(context, (char*)sqlite4_value_text(argv[i]),
          n, SQLITE4_TRANSIENT, 0);
      break;
    }
  }
}

/*
** These are test functions.    hex8() interprets its argument as
................................................................................
  int i;
  char zBuf[200];
  z = sqlite4_value_text(argv[0]);
  for(i=0; i<sizeof(zBuf)/2 - 2 && z[i]; i++){
    sprintf(&zBuf[i*2], "%02x", z[i]&0xff);
  }
  zBuf[i*2] = 0;
  sqlite4_result_text(p, (char*)zBuf, -1, SQLITE4_TRANSIENT, 0);
}
#ifndef SQLITE4_OMIT_UTF16
static void hex16Func(sqlite4_context *p, int argc, sqlite4_value **argv){
  const unsigned short int *z;
  int i;
  char zBuf[400];
  z = sqlite4_value_text16(argv[0]);
  for(i=0; i<sizeof(zBuf)/4 - 4 && z[i]; i++){
    sprintf(&zBuf[i*4], "%04x", z[i]&0xff);
  }
  zBuf[i*4] = 0;
  sqlite4_result_text(p, (char*)zBuf, -1, SQLITE4_TRANSIENT, 0);
}
#endif

/*
** A structure into which to accumulate text.
*/
struct dstr {
................................................................................
  sqlite4_value **argv
){
  struct dstr x;
  memset(&x, 0, sizeof(x));
  (void)sqlite4_exec((sqlite4*)sqlite4_user_data(context),
      (char*)sqlite4_value_text(argv[0]),
      execFuncCallback, &x, 0);
  sqlite4_result_text(context, x.z, x.nUsed, SQLITE4_TRANSIENT, 0);
  sqlite4_free(0, x.z);
}

/*
** Implementation of tkt2213func(), a scalar function that takes exactly
** one argument. It has two interesting features:
**
................................................................................
  zText3 = sqlite4_value_text(argv[0]);

  if( zText1!=zText2 || zText2!=zText3 ){
    sqlite4_result_error(context, "tkt2213 is not fixed", -1);
  }else{
    char *zCopy = (char *)sqlite4_malloc(sqlite4_context_env(context),nText);
    memcpy(zCopy, zText1, nText);
    sqlite4_result_text(context, zCopy, nText, SQLITE4_DYNAMIC, 0);
  }
}

/*
** The following SQL function takes 4 arguments.  The 2nd and
** 4th argument must be one of these strings:  'text', 'text16',
** or 'blob' corresponding to API functions
................................................................................
  /* Use the sqlite4_create_function16() API here. Mainly for fun, but also 
  ** because it is not tested anywhere else. */
  if( rc==SQLITE4_OK ){
    const void *zUtf16;
    sqlite4_value *pVal;
    sqlite4_mutex_enter(db->mutex);
    pVal = sqlite4ValueNew(db);
    sqlite4ValueSetStr(pVal, -1, "x_sqlite_exec", SQLITE4_UTF8,
                       SQLITE4_STATIC, 0);
    zUtf16 = sqlite4ValueText(pVal, SQLITE4_UTF16NATIVE);
    if( db->mallocFailed ){
      rc = SQLITE4_NOMEM;
    }else{
      rc = sqlite4_create_function16(db, zUtf16, 
                1, SQLITE4_UTF16, db, sqlite4ExecFunc, 0, 0);
    }
................................................................................
    if( zArg0 ){
      if( 0==sqlite4_stricmp(zArg0, "int") ){
        sqlite4_result_int(context, sqlite4_value_int(argv[1]));
      }else if( sqlite4_stricmp(zArg0,"int64")==0 ){
        sqlite4_result_int64(context, sqlite4_value_int64(argv[1]));
      }else if( sqlite4_stricmp(zArg0,"string")==0 ){
        sqlite4_result_text(context, (char*)sqlite4_value_text(argv[1]), -1,
            SQLITE4_TRANSIENT, 0);
      }else if( sqlite4_stricmp(zArg0,"double")==0 ){
        sqlite4_result_double(context, sqlite4_value_double(argv[1]));
      }else if( sqlite4_stricmp(zArg0,"null")==0 ){
        sqlite4_result_null(context);
      }else if( sqlite4_stricmp(zArg0,"value")==0 ){
        sqlite4_result_value(context, argv[sqlite4_value_int(argv[1])]);
      }else{
................................................................................
    return TCL_ERROR;
  }
  if( getStmtPointer(interp, argv[1], &pStmt) ) return TCL_ERROR;
  if( Tcl_GetInt(interp, argv[2], &idx) ) return TCL_ERROR;
  if( strcmp(argv[4],"null")==0 ){
    rc = sqlite4_bind_null(pStmt, idx);
  }else if( strcmp(argv[4],"static")==0 ){
    rc = sqlite4_bind_text(pStmt, idx, sqlite_static_bind_value, -1, 0, 0);
  }else if( strcmp(argv[4],"static-nbytes")==0 ){
    rc = sqlite4_bind_text(pStmt, idx, sqlite_static_bind_value,
                                       sqlite_static_bind_nbyte, 0, 0);
  }else if( strcmp(argv[4],"normal")==0 ){
    rc = sqlite4_bind_text(pStmt, idx, argv[3], -1, SQLITE4_TRANSIENT, 0);
  }else if( strcmp(argv[4],"blob10")==0 ){
    rc = sqlite4_bind_text(pStmt, idx, "abc\000xyz\000pq", 10,SQLITE4_STATIC,0);
  }else{
    Tcl_AppendResult(interp, "4th argument should be "
        "\"null\" or \"static\" or \"normal\"", 0);
    return TCL_ERROR;
  }
  if( sqlite4TestErrCode(interp, StmtToDb(pStmt), rc) ) return TCL_ERROR;
  if( rc ){
................................................................................
    default:
      assert(0);
  }

  sqlite4BeginBenignMalloc(pEnv);
  pVal = sqlite4ValueNew(0);
  if( pVal ){
    sqlite4ValueSetStr(pVal, nA, zA, encin, SQLITE4_STATIC, 0);
    n = sqlite4_value_bytes(pVal);
    Tcl_ListObjAppendElement(i,pX,
        Tcl_NewStringObj((char*)sqlite4_value_text(pVal),n));
    sqlite4ValueSetStr(pVal, nB, zB, encin, SQLITE4_STATIC, 0);
    n = sqlite4_value_bytes(pVal);
    Tcl_ListObjAppendElement(i,pX,
        Tcl_NewStringObj((char*)sqlite4_value_text(pVal),n));
    sqlite4ValueFree(pVal);
  }
  sqlite4EndBenignMalloc(pEnv);

................................................................................
  pX = Tcl_NewStringObj("test_function", -1);
  Tcl_IncrRefCount(pX);
  Tcl_ListObjAppendElement(interp, pX, Tcl_NewStringObj("UTF-8", -1));
  Tcl_ListObjAppendElement(interp, pX, 
      Tcl_NewStringObj((char*)sqlite4_value_text(argv[0]), -1));
  Tcl_EvalObjEx(interp, pX, 0);
  Tcl_DecrRefCount(pX);
  sqlite4_result_text(pCtx, Tcl_GetStringResult(interp), -1,
                      SQLITE4_TRANSIENT, 0);
  pVal = sqlite4ValueNew(0);
  sqlite4ValueSetStr(pVal, -1, Tcl_GetStringResult(interp), 
      SQLITE4_UTF8, SQLITE4_STATIC, 0);
  sqlite4_result_text16be(pCtx, sqlite4_value_text16be(pVal),
      -1, SQLITE4_TRANSIENT, 0);
  sqlite4ValueFree(pVal);
}
static void test_function_utf16le(
  sqlite4_context *pCtx, 
  int nArg,
  sqlite4_value **argv
){
................................................................................
  Tcl_ListObjAppendElement(interp, pX, Tcl_NewStringObj("UTF-16LE", -1));
  Tcl_ListObjAppendElement(interp, pX, 
      Tcl_NewStringObj((char*)sqlite4_value_text(argv[0]), -1));
  Tcl_EvalObjEx(interp, pX, 0);
  Tcl_DecrRefCount(pX);
  pVal = sqlite4ValueNew(0);
  sqlite4ValueSetStr(pVal, -1, Tcl_GetStringResult(interp), 
      SQLITE4_UTF8, SQLITE4_STATIC, 0);
  sqlite4_result_text(pCtx, (char*)sqlite4_value_text(pVal), -1,
                      SQLITE4_TRANSIENT, 0);
  sqlite4ValueFree(pVal);
}
static void test_function_utf16be(
  sqlite4_context *pCtx, 
  int nArg,
  sqlite4_value **argv
){
................................................................................
  Tcl_ListObjAppendElement(interp, pX, Tcl_NewStringObj("UTF-16BE", -1));
  Tcl_ListObjAppendElement(interp, pX, 
      Tcl_NewStringObj((char*)sqlite4_value_text(argv[0]), -1));
  Tcl_EvalObjEx(interp, pX, 0);
  Tcl_DecrRefCount(pX);
  pVal = sqlite4ValueNew(0);
  sqlite4ValueSetStr(pVal, -1, Tcl_GetStringResult(interp), 
      SQLITE4_UTF8, SQLITE4_STATIC, 0);
  sqlite4_result_text16(pCtx, sqlite4_value_text16le(pVal),
      -1, SQLITE4_TRANSIENT, 0);
  sqlite4_result_text16be(pCtx, sqlite4_value_text16le(pVal),
      -1, SQLITE4_TRANSIENT, 0);
  sqlite4_result_text16le(pCtx, sqlite4_value_text16le(pVal),
      -1, SQLITE4_TRANSIENT, 0);
  sqlite4ValueFree(pVal);
}
#endif /* SQLITE4_OMIT_UTF16 */
static int test_function(
  void * clientData,
  Tcl_Interp *interp,
  int objc,
................................................................................
  }

  if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
  if( Tcl_GetIntFromObj(interp, objv[2], &idx) ) return TCL_ERROR;
  value = (char*)Tcl_GetByteArrayFromObj(objv[3], &bytes);
  if( Tcl_GetIntFromObj(interp, objv[4], &bytes) ) return TCL_ERROR;

  rc = sqlite4_bind_text(pStmt, idx, value, bytes, SQLITE4_TRANSIENT, 0);
  if( sqlite4TestErrCode(interp, StmtToDb(pStmt), rc) ) return TCL_ERROR;
  if( rc!=SQLITE4_OK ){
    Tcl_AppendResult(interp, sqlite4TestErrorName(rc), 0);
    return TCL_ERROR;
  }

  return TCL_OK;
................................................................................
  }

  if( getStmtPointer(interp, Tcl_GetString(oStmt), &pStmt) ) return TCL_ERROR;
  if( Tcl_GetIntFromObj(interp, oN, &idx) ) return TCL_ERROR;
  value = (char*)Tcl_GetByteArrayFromObj(oString, 0);
  if( Tcl_GetIntFromObj(interp, oBytes, &bytes) ) return TCL_ERROR;

  rc = sqlite4_bind_text16(pStmt, idx, (void *)value, bytes, xDel, 0);
  if( sqlite4TestErrCode(interp, StmtToDb(pStmt), rc) ) return TCL_ERROR;
  if( rc!=SQLITE4_OK ){
    Tcl_AppendResult(interp, sqlite4TestErrorName(rc), 0);
    return TCL_ERROR;
  }

#endif /* SQLITE4_OMIT_UTF16 */
................................................................................
  }

  if( getStmtPointer(interp, Tcl_GetString(objv[1]), &pStmt) ) return TCL_ERROR;
  if( Tcl_GetIntFromObj(interp, objv[2], &idx) ) return TCL_ERROR;
  value = Tcl_GetString(objv[3]);
  if( Tcl_GetIntFromObj(interp, objv[4], &bytes) ) return TCL_ERROR;

  rc = sqlite4_bind_blob(pStmt, idx, value, bytes, xDestructor, 0);
  if( sqlite4TestErrCode(interp, StmtToDb(pStmt), rc) ) return TCL_ERROR;
  if( rc!=SQLITE4_OK ){
    return TCL_ERROR;
  }

  return TCL_OK;
}
................................................................................
      Tcl_AppendResult(interp, " ", aOpt[i].zOptName);
    }
    return TCL_ERROR;
  }
  sqlite4_test_control(SQLITE4_TESTCTRL_OPTIMIZATIONS, db, mask);
  return TCL_OK;
}

#define NUM_FORMAT "sign:%d approx:%d e:%d m:%lld"

/* Append a return value representing a sqlite4_num.
*/
static void append_num_result( Tcl_Interp *interp, sqlite4_num A ){
  char buf[100];
  sprintf( buf, NUM_FORMAT, A.sign, A.approx, A.e, A.m );
  Tcl_AppendResult(interp, buf, 0);
}

/* Convert a string either representing a sqlite4_num (listing its fields as
** returned by append_num_result) or that can be parsed as one. Invalid
** strings become NaN.
*/
static sqlite4_num test_parse_num( char *arg ){
  sqlite4_num A;
  int sign, approx, e;
  if( sscanf( arg, NUM_FORMAT, &sign, &approx, &e, &A.m)==4 ){
    A.sign = sign;
    A.approx = approx;
    A.e = e;
    return A;
  } else {
    return sqlite4_num_from_text(arg, -1, 0);
  }
}

/* Convert return values of sqlite4_num to strings that will be readable in
** the tests.
*/
static char *describe_num_comparison( int code ){
  switch( code ){
    case 0: return "incomparable";
    case 1: return "lesser";
    case 2: return "equal";
    case 3: return "greater";
    default: return "error"; 
  }
}

/* Compare two numbers A and B. Returns "incomparable", "lesser", "equal",
** "greater", or "error".
*/
static int test_num_compare(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  char **argv            /* Text of each argument */
){
  sqlite4_num A, B;
  int cmp;
  if( argc!=3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
       " NUM NUM\"", 0);
    return TCL_ERROR;
  }
  
  A = test_parse_num( argv[1] );
  B = test_parse_num( argv[2] );
  cmp = sqlite4_num_compare(A, B);
  Tcl_AppendResult( interp, describe_num_comparison( cmp ), 0);
  return TCL_OK; 
}

/* Create a sqlite4_num from a string. The optional second argument specifies
** how many bytes may be read.
*/
static int test_num_from_text(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  char **argv            /* Text of each argument */
){
  sqlite4_num A;
  int len;
  if( argc!=2 && argc!=3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
      " STRING\" or \"", argv[0], " STRING INTEGER\"", 0);
    return TCL_ERROR;
  }

  if( argc==3 ){
    if ( Tcl_GetInt(interp, argv[2], &len) ) return TCL_ERROR; 
  }else{
    len = -1;
  }

  A = sqlite4_num_from_text( argv[1], len, 0 );
  append_num_result(interp, A);
  return TCL_OK;
}

static int test_num_to_text(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  char **argv            /* Text of each argument */
){
  char text[30];
  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
      " NUM\"", 0);
    return TCL_ERROR;
  }
  sqlite4_num_to_text( test_parse_num( argv[1] ), text );
  Tcl_AppendResult( interp, text, 0 );
  return TCL_OK;
}

static int test_num_binary_op(
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  char **argv,            /* Text of each argument */
  sqlite4_num (*op) (sqlite4_num, sqlite4_num)
){
  sqlite4_num A, B, R;
  if( argc!=3 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
      " NUM NUM\"", 0);
    return TCL_ERROR;
  }
  A = test_parse_num(argv[1]);
  B = test_parse_num(argv[2]);
  R = op(A, B);
  append_num_result(interp, R);
  return TCL_OK;
}

static int test_num_add(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  char **argv            /* Text of each argument */
){
  return test_num_binary_op( interp, argc, argv, sqlite4_num_add );
}

static int test_num_sub(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  char **argv            /* Text of each argument */
){
  return test_num_binary_op( interp, argc, argv, sqlite4_num_sub );
}

static int test_num_mul(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  char **argv            /* Text of each argument */
){
  return test_num_binary_op( interp, argc, argv, sqlite4_num_mul );
}

static int test_num_div(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  char **argv            /* Text of each argument */
){
  return test_num_binary_op( interp, argc, argv, sqlite4_num_div );
}

static int test_num_predicate(
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  char **argv,            /* Text of each argument */
  int (*pred) (sqlite4_num)
){
  sqlite4_num A;
  if( argc!=2 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
      " NUM\"", 0);
    return TCL_ERROR;
  }
  A = test_parse_num(argv[1]);
  Tcl_AppendResult(interp, pred(A) ? "true" : "false", 0);  
  return TCL_OK;
}

static int test_num_isinf(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  char **argv            /* Text of each argument */
){
  return test_num_predicate( interp, argc, argv, sqlite4_num_isinf );
}

static int test_num_isnan(
  void *NotUsed,
  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
  int argc,              /* Number of arguments */
  char **argv            /* Text of each argument */
){
  return test_num_predicate( interp, argc, argv, sqlite4_num_isnan );
}

/*
** Register commands with the TCL interpreter.
*/
int Sqlitetest1_Init(Tcl_Interp *interp){
  extern int sqlite4_search_count;
  extern int sqlite4_found_count;
................................................................................
     { "sqlite_set_magic",              (Tcl_CmdProc*)sqlite_set_magic      },
     { "sqlite4_interrupt",             (Tcl_CmdProc*)test_interrupt        },
     { "sqlite_delete_function",        (Tcl_CmdProc*)delete_function       },
     { "sqlite_delete_collation",       (Tcl_CmdProc*)delete_collation      },
     { "sqlite4_get_autocommit",        (Tcl_CmdProc*)get_autocommit        },
     { "sqlite4_stack_used",            (Tcl_CmdProc*)test_stack_used       },
     { "printf",                        (Tcl_CmdProc*)test_printf           },
     { "sqlite4IoTrace",                (Tcl_CmdProc*)test_io_trace         },
     { "sqlite4_num_compare",           (Tcl_CmdProc*)test_num_compare      }, 
     { "sqlite4_num_from_text",         (Tcl_CmdProc*)test_num_from_text    }, 
     { "sqlite4_num_to_text",           (Tcl_CmdProc*)test_num_to_text      },
     { "sqlite4_num_add",               (Tcl_CmdProc*)test_num_add          },
     { "sqlite4_num_sub",               (Tcl_CmdProc*)test_num_sub          },
     { "sqlite4_num_mul",               (Tcl_CmdProc*)test_num_mul          },
     { "sqlite4_num_div",               (Tcl_CmdProc*)test_num_div          },
     { "sqlite4_num_isinf",             (Tcl_CmdProc*)test_num_isinf        },
     { "sqlite4_num_isnan",             (Tcl_CmdProc*)test_num_isnan        },
  };
  static struct {
     char *zName;
     Tcl_ObjCmdProc *xProc;
     void *clientData;
  } aObjCmd[] = {
     { "sqlite4_connection_pointer",    get_sqlite_pointer, 0 },
................................................................................
  extern int sqlite4_pager_writej_count;
#if SQLITE4_OS_WIN
  extern int sqlite4_os_type;
#endif
#ifdef SQLITE4_DEBUG
  extern int sqlite4WhereTrace;
  extern int sqlite4OSTrace;

#endif
#ifdef SQLITE4_TEST
  extern char sqlite4_query_plan[];
  static char *query_plan = sqlite4_query_plan;
#ifdef SQLITE4_ENABLE_FTS3
  extern int sqlite4_fts3_enable_parentheses;
#endif
................................................................................
      (char*)&sqlite4_os_type, TCL_LINK_INT);
#endif
#ifdef SQLITE4_TEST
  Tcl_LinkVar(interp, "sqlite_query_plan",
      (char*)&query_plan, TCL_LINK_STRING|TCL_LINK_READ_ONLY);
#endif
#ifdef SQLITE4_DEBUG


  Tcl_LinkVar(interp, "sqlite_where_trace",
      (char*)&sqlite4WhereTrace, TCL_LINK_INT);
#endif
  Tcl_LinkVar(interp, "sqlite_static_bind_value",
      (char*)&sqlite_static_bind_value, TCL_LINK_STRING);
  Tcl_LinkVar(interp, "sqlite_static_bind_nbyte",
      (char*)&sqlite_static_bind_nbyte, TCL_LINK_INT);

Changes to test/test_utf.c.

112
113
114
115
116
117
118
119


120
121
122
123
124
125
126
...
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
...
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
  }
  if( pEnc->enc==SQLITE4_UTF16 ){
    return SQLITE4_UTF16NATIVE;
  }
  return pEnc->enc;
}

static void freeStr(void *pStr){ sqlite4_free(0, pStr); }



/*
** Usage:   test_translate <string/blob> <from enc> <to enc> ?<transient>?
**
*/
static int test_translate(
  void * clientData,
................................................................................
){
  u8 enc_from;
  u8 enc_to;
  sqlite4_value *pVal;

  char *z;
  int len;
  void (*xDel)(void *p) = SQLITE4_STATIC;

  if( objc!=4 && objc!=5 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"",
        Tcl_GetStringFromObj(objv[0], 0), 
        " <string/blob> <from enc> <to enc>", 0
    );
    return TCL_ERROR;
................................................................................
  pVal = sqlite4ValueNew(0);

  if( enc_from==SQLITE4_UTF8 ){
    z = Tcl_GetString(objv[1]);
    if( objc==5 ){
      z = sqlite4_mprintf(0, "%s", z);
    }
    sqlite4ValueSetStr(pVal, -1, z, enc_from, xDel);
  }else{
    z = (char*)Tcl_GetByteArrayFromObj(objv[1], &len);
    if( objc==5 ){
      char *zTmp = z;
      z = sqlite4_malloc(0, len);
      memcpy(z, zTmp, len);
    }
    sqlite4ValueSetStr(pVal, -1, z, enc_from, xDel);
  }

  z = (char *)sqlite4ValueText(pVal, enc_to);
  len = sqlite4ValueBytes(pVal, enc_to) + (enc_to==SQLITE4_UTF8?1:2);
  Tcl_SetObjResult(interp, Tcl_NewByteArrayObj((u8*)z, len));

  sqlite4ValueFree(pVal);







|
>
>







 







|







 







|







|







112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
...
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
...
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
  }
  if( pEnc->enc==SQLITE4_UTF16 ){
    return SQLITE4_UTF16NATIVE;
  }
  return pEnc->enc;
}

static void freeStr(void *pEnv, void *pStr){
  sqlite4_free((sqlite4_env*)pEnv, pStr);
}

/*
** Usage:   test_translate <string/blob> <from enc> <to enc> ?<transient>?
**
*/
static int test_translate(
  void * clientData,
................................................................................
){
  u8 enc_from;
  u8 enc_to;
  sqlite4_value *pVal;

  char *z;
  int len;
  void (*xDel)(void*,void*) = SQLITE4_STATIC;

  if( objc!=4 && objc!=5 ){
    Tcl_AppendResult(interp, "wrong # args: should be \"",
        Tcl_GetStringFromObj(objv[0], 0), 
        " <string/blob> <from enc> <to enc>", 0
    );
    return TCL_ERROR;
................................................................................
  pVal = sqlite4ValueNew(0);

  if( enc_from==SQLITE4_UTF8 ){
    z = Tcl_GetString(objv[1]);
    if( objc==5 ){
      z = sqlite4_mprintf(0, "%s", z);
    }
    sqlite4ValueSetStr(pVal, -1, z, enc_from, xDel, 0);
  }else{
    z = (char*)Tcl_GetByteArrayFromObj(objv[1], &len);
    if( objc==5 ){
      char *zTmp = z;
      z = sqlite4_malloc(0, len);
      memcpy(z, zTmp, len);
    }
    sqlite4ValueSetStr(pVal, -1, z, enc_from, xDel, 0);
  }

  z = (char *)sqlite4ValueText(pVal, enc_to);
  len = sqlite4ValueBytes(pVal, enc_to) + (enc_to==SQLITE4_UTF8?1:2);
  Tcl_SetObjResult(interp, Tcl_NewByteArrayObj((u8*)z, len));

  sqlite4ValueFree(pVal);

Changes to test/tester.tcl.

758
759
760
761
762
763
764

765
766
767
768
769
770
771
    puts "all of the test failures above might be a result from this defect"
    puts "in your TCL build."
    puts "******************************************************************"
  }
  if {$::cmdlinearg(binarylog)} {
    vfslog finalize binarylog
  }

  if {[lindex [sqlite4_env_status SQLITE4_ENVSTATUS_MALLOC_COUNT 0] 1]>0 ||
              [sqlite4_memory_used]>0} {
    puts "Unfreed memory: [sqlite4_memory_used] bytes in\
         [lindex [sqlite4_env_status SQLITE4_ENVSTATUS_MALLOC_COUNT 0] 1] allocations"
    incr nErr
    ifcapable memdebug||mem5||(mem3&&debug) {
      puts "Writing unfreed memory log to \"./memleak.txt\""







>







758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
    puts "all of the test failures above might be a result from this defect"
    puts "in your TCL build."
    puts "******************************************************************"
  }
  if {$::cmdlinearg(binarylog)} {
    vfslog finalize binarylog
  }
  kvwrap uninstall
  if {[lindex [sqlite4_env_status SQLITE4_ENVSTATUS_MALLOC_COUNT 0] 1]>0 ||
              [sqlite4_memory_used]>0} {
    puts "Unfreed memory: [sqlite4_memory_used] bytes in\
         [lindex [sqlite4_env_status SQLITE4_ENVSTATUS_MALLOC_COUNT 0] 1] allocations"
    incr nErr
    ifcapable memdebug||mem5||(mem3&&debug) {
      puts "Writing unfreed memory log to \"./memleak.txt\""

Changes to test/tkt3442.test.

45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# These tests perform an EXPLAIN QUERY PLAN on both versions of the 
# SELECT referenced in ticket #3442 (both '5000' and "5000") 
# and verify that the query plan is the same.
#
ifcapable explain {
  do_test tkt3442-1.2 {
    EQP { SELECT node FROM listhash WHERE id='5000' LIMIT 1; }
  } {0 0 0 {SEARCH TABLE listhash USING INDEX ididx (id=?) (~1 rows)}}
  do_test tkt3442-1.3 {
    EQP { SELECT node FROM listhash WHERE id="5000" LIMIT 1; }
  } {0 0 0 {SEARCH TABLE listhash USING INDEX ididx (id=?) (~1 rows)}}
}


# Some extra tests testing other permutations of 5000.
#
ifcapable explain {







<
<
<







45
46
47
48
49
50
51



52
53
54
55
56
57
58
# These tests perform an EXPLAIN QUERY PLAN on both versions of the 
# SELECT referenced in ticket #3442 (both '5000' and "5000") 
# and verify that the query plan is the same.
#
ifcapable explain {
  do_test tkt3442-1.2 {
    EQP { SELECT node FROM listhash WHERE id='5000' LIMIT 1; }



  } {0 0 0 {SEARCH TABLE listhash USING INDEX ididx (id=?) (~1 rows)}}
}


# Some extra tests testing other permutations of 5000.
#
ifcapable explain {

Changes to test/tkt3841.test.

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
}

do_test tkt3841.1 {
  execsql {
    CREATE TABLE table2 (key TEXT, x TEXT);
    CREATE TABLE list (key TEXT, value TEXT);
  
    INSERT INTO table2 VALUES ("a", "alist");
    INSERT INTO table2 VALUES ("b", "blist");
    INSERT INTO list VALUES ("a", 1);
    INSERT INTO list VALUES ("a", 2);
    INSERT INTO list VALUES ("a", 3);
    INSERT INTO list VALUES ("b", 4);
    INSERT INTO list VALUES ("b", 5);
    INSERT INTO list VALUES ("b", 6);

    SELECT
      table2.x,
      (SELECT group_concat(list.value)
        FROM list
        WHERE list.key = table2.key)
    FROM table2;
  }
} {alist 1,2,3 blist 4,5,6}

finish_test







|
|
|
|
|
|
|
|











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
}

do_test tkt3841.1 {
  execsql {
    CREATE TABLE table2 (key TEXT, x TEXT);
    CREATE TABLE list (key TEXT, value TEXT);
  
    INSERT INTO table2 VALUES ('a', 'alist');
    INSERT INTO table2 VALUES ('b', 'blist');
    INSERT INTO list VALUES ('a', 1);
    INSERT INTO list VALUES ('a', 2);
    INSERT INTO list VALUES ('a', 3);
    INSERT INTO list VALUES ('b', 4);
    INSERT INTO list VALUES ('b', 5);
    INSERT INTO list VALUES ('b', 6);

    SELECT
      table2.x,
      (SELECT group_concat(list.value)
        FROM list
        WHERE list.key = table2.key)
    FROM table2;
  }
} {alist 1,2,3 blist 4,5,6}

finish_test