Fossil

Diff
Login

Diff

Differences From Artifact [c3e527fc4a]:

To Artifact [f77b026787]:


16
17
18
19
20
21
22


23
24

25
26
27
28
29
30
31
32
33
34
35
36
37
16
17
18
19
20
21
22
23
24
25

26
27


28
29

30
31
32
33
34
35
36







+
+

-
+

-
-


-







*******************************************************************************
**
** This file contains an interface between the TH scripting language
** (an independent project) and fossil.
*/
#include "config.h"
#include "th_main.h"

#ifdef TH_ENABLE_QUERY
#ifndef INTERFACE
#include "blob.h"
#include "sqlite3.h"
#endif
#ifdef TH_ENABLE_SQLITE
#include "sqlite3.h"
#endif

/*#include "th_main.h"*/
/*
** Global variable counting the number of outstanding calls to malloc()
** made by the th1 implementation. This is used to catch memory leaks
** in the interpreter. Obviously, it also means th1 is not threadsafe.
*/
static int nOutstandingMalloc = 0;

48
49
50
51
52
53
54



55

56
57
58
59
60
61
62
63
64


65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89








90
91
92
93
94
95
96
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65


66
67
68
69
70
71








72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99







+
+
+

+







-
-
+
+




-
-
-
-
-
-
-
-













+
+
+
+
+
+
+
+







static void xFree(void *p){
  if( p ){
    nOutstandingMalloc--;
  }
  fossil_free(p);
}

/*
** Default Th_Vtab::xRealloc() implementation.
*/
static void *xRealloc(void * p, unsigned int n){
  assert(n>=0 && "Invalid memory (re/de)allocation size.");
  if(0 == n){
    xFree(p);
    return NULL;
  }else if(NULL == p){
    return xMalloc(n);
  }else{
    return fossil_realloc(p, n)
      /* FIXME: try to find some reasonable nOutstandingMalloc
         heuristics, e.g. if !p then ++, if !n then --, etc.
      /* In theory nOutstandingMalloc doesn't need to be updated here
         unless xRealloc() is sorely misused.
      */;
  }
}

static Th_Vtab vtab = { xRealloc, {
  NULL /*write()*/,
  NULL/*dispose()*/,
  NULL/*pState*/,
  1/*enabled*/
  }
};

/*
** Generate a TH1 trace message if debugging is enabled.
*/
void Th_Trace(const char *zFormat, ...){
  va_list ap;
  va_start(ap, zFormat);
  blob_vappendf(&g.thLog, zFormat, ap);
  va_end(ap);
}


/*
** True if output is enabled.  False if disabled.
**
** We "could" replace this with Th_OutputEnable() and friends, but
** there is a functional difference: this particular flag prohibits
** some extra escaping which would happen (but be discared, unused) if
** relied solely on that API. Also, because that API only works on the
** current Vtab_Output handler, relying soly on that handling would
** introduce incompatible behaviour with the historical enable_output
** command.
*/
static int enableOutput = 1;

/*
** TH command:     enable_output BOOLEAN
**
** Enable or disable the puts and hputs commands.
104
105
106
107
108
109
110
111
112
113
114
115



116

117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137

138
139
140
141







142
143
144
145





146
147
148
149
150
151
152
153




154
155
156
157
158
159
160
107
108
109
110
111
112
113

114
115
116
117
118
119
120

121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141

142
143
144
145
146
147
148
149
150
151
152
153
154



155
156
157
158
159
160
161
162
163
164
165
166

167
168
169
170
171
172
173
174
175
176
177







-




+
+
+
-
+




















-
+




+
+
+
+
+
+
+

-
-
-
+
+
+
+
+







-
+
+
+
+







){
  if( argc!=2 ){
    return Th_WrongNumArgs2(interp,
                            argv[0], argl[0],
                           "BOOLEAN");
  }else{
    int rc = Th_ToInt(interp, argv[1], argl[1], &enableOutput);
    vtab.out.enabled = enableOutput;
    return rc;
  }
}

/*
** Th_Output_f() impl which sends all output to cgi_append_content().
*/
int Th_output_f_cgi_content( char const * zData, int nData, void * pState ){
static int Th_Output_f_cgi_content( char const * zData, int nData, void * pState ){
  cgi_append_content(zData, nData);
  return nData;
}


/*
** Send text to the appropriate output:  Either to the console
** or to the CGI reply buffer.
*/
static void sendText(Th_Interp *pInterp, const char *z, int n, int encode){
  if(NULL == pInterp){
    pInterp = g.interp;
  }
  assert( NULL != pInterp );
  if( enableOutput && n ){
    if( n<0 ) n = strlen(z);
    if( encode ){
      z = htmlize(z, n);
      n = strlen(z);
    }
    Th_output( pInterp, z, n );
    Th_Output( pInterp, z, n );
    if( encode ) fossil_free((char*)z);
  }
}

/*
** Internal state for the putsCmd() function, allowing it to be used
** as the basis for multiple implementations with slightly different
** behaviours based on the context. An instance of this type must be
** set as the Context parameter for any putsCmd()-based script command
** binding.
*/
struct PutsCmdData {
  char escapeHtml;
  char const * sep;
  char const * eol;
  char escapeHtml;    /* If true, htmlize all output. */
  char const * sep;   /* Optional NUL-terminated separator to output
                         between arguments. May be NULL. */
  char const * eol;   /* Optional NUL-terminated end-of-line separator,
                         output after the final argument. May be NULL. */
};
typedef struct PutsCmdData PutsCmdData;

/*
** TH command:     puts STRING
** TH command:     html STRING
**
** Output STRING as HTML (html) or unchanged (puts).  
** Output STRING as HTML (html) or unchanged (puts).
**
** pConvert MUST be a (PutsCmdData [const]*). It is not modified by
** this function.
*/
static int putsCmd(
  Th_Interp *interp, 
  void *pConvert, 
  int argc, 
  const char **argv, 
  int *argl
227
228
229
230
231
232
233
234


235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252

253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268

269
270
271
272
273
274
275

276
277
278
279
280
281
282
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







-
+
+

















-
+















-
+






-
+







  zOut = htmlize((char*)argv[1], argl[1]);
  Th_SetResult(interp, zOut, -1);
  free(zOut);
  return TH_OK;
}

#if 0
/* i'm not sure we need this */
/* This is not yet needed, but something like it may become useful for
   custom page/command support, for rendering snippets/templates. */
/*
** TH command:      render STRING
**
** Render the input string as TH1.
*/
static int renderCmd(
  Th_Interp *interp, 
  void *p, 
  int argc, 
  const char **argv, 
  int *argl
){
  if( argc<2 ){
    return Th_WrongNumArgs2(interp,
                            argv[0], argl[0],
                            "STRING ?STRING...?");
  }else{
    Th_Ob_Man * man = Th_ob_manager(interp);
    Th_Ob_Manager * man = Th_Ob_GetManager(interp);
    Blob * b = NULL;
    Blob buf = empty_blob;
    int rc, i;
    /*FIXME: assert(NULL != man && man->interp==interp);*/
    man->interp = interp;
    /* Combine all inputs into one buffer so that we can use that to
       embed TH1 tags across argument boundaries.

       FIX:E optimize away buf for the 1-arg case.
     */
    for( i = 1; TH_OK==rc && i < argc; ++i ){
      char const * str = argv[i];
      blob_append( &buf, str, argl[i] );
      /*rc = Th_Render( str, Th_Render_Flags_NO_DOLLAR_DEREF );*/
    }
    rc = Th_ob_push( man, &b );
    rc = Th_Ob_Push( man, &b );
    if(rc){
      blob_reset( &buf );
      return rc;
    }
    rc = Th_Render( buf.aData, Th_Render_Flags_DEFAULT );
    blob_reset(&buf);
    b = Th_ob_pop( man );
    b = Th_Ob_Pop( man );
    if(TH_OK==rc){
      Th_SetResult( interp, b->aData, b->nUsed );
    }
    blob_reset( b );
    Th_Free( interp, b );
    return rc;
  }
542
543
544
545
546
547
548
549
550
551
552
553

554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573

574
575
576
577
578
579
580
560
561
562
563
564
565
566



567

568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587

588
589
590
591
592
593
594
595







-
-
-

-
+



















-
+







  }
  Th_SetResult(interp, g.zRepositoryName, -1);
  return TH_OK;
}


#ifdef TH_ENABLE_ARGV
extern const char *find_option(const char *zLong,
                               const char *zShort,
                               int hasArg) /* from main.c */;
/*
** TH Syntax:
** TH command:
**
** argv len
**
** Returns the number of command-line arguments.
*/
static int argvArgcCmd(
  Th_Interp *interp,
  void *p, 
  int argc, 
  const char **argv, 
  int *argl
){
  Th_SetResultInt( interp, g.argc );
  return TH_OK;
}



/*
** TH Syntax:
** TH command:
**
** argv at Index
**
** Returns the raw argument at the given index, throwing if
** out of bounds.
*/
static int argvGetAtCmd(
605
606
607
608
609
610
611
612

613
614
615
616
617
618
619
620
621
622
623
624
625
626

627
628
629
630
631
632
633
634







-
+







  }
  Th_SetResult( interp, zVal, zVal ? strlen(zVal) : 0 );
  return TH_OK;  
}


/*
** TH Syntax:
** TH command:
**
** argv getstr longName ??shortName? ?defaultValue??
**
** Functions more or less like Fossil's find_option().
** If the given argument is found then its value is returned,
** else defaultValue is returned. If that is not set
** and the option is not found, an error is thrown.
676
677
678
679
680
681
682
683

684
685
686
687

688
689
690
691
692
693
694
691
692
693
694
695
696
697

698
699
700
701

702
703
704
705
706
707
708
709







-
+



-
+







    }
  }
  Th_SetResult( interp, zVal, zVal ? strlen(zVal) : 0 );
  return TH_OK;  
}

/*
** TH Syntax:
** TH command:
**
** argv getbool longName ??shortName? ?defaultValue??
**
** Works just like argv_getstr but treats any empty value or one
** Works just like argv getstr but treats any empty value or one
** starting with the digit '0' as a boolean false.
**
** Returns the result as an integer 0 (false) or 1 (true).
*/
static int argvFindOptionBoolCmd(
  Th_Interp *interp,
  void *p, 
749
750
751
752
753
754
755
756

757
758



759
760
761
762
763
764
765
764
765
766
767
768
769
770

771
772
773
774
775
776
777
778
779
780
781
782
783







-
+


+
+
+







  }
  zVal = (zVal && *zVal && (*zVal!='0')) ? zVal : 0;
  Th_SetResultInt( interp, zVal ? 1 : 0 );
  return TH_OK;
}

/*
** TH Syntax:
** TH command:
**
** argv getint longName ?shortName? ?defaultValue?
**
** Works like argv getstr but returns the value as an integer
** (throwing an error if the argument cannot be converted).
*/
static int argvFindOptionIntCmd(
  Th_Interp *interp,
  void *p, 
  int argc, 
  const char **argv, 
  int *argl
809
810
811
812
813
814
815







816
817
818
819
820
821
822
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847







+
+
+
+
+
+
+







    }
  }
  Th_ToInt(interp, zVal, strlen(zVal), &val);
  Th_SetResultInt( interp, val );
  return TH_OK;  
}

/*
** TH command:
**
** argv subcommand
**
** This is the top-level dispatching function.
*/
static int argvTopLevelCmd(
  Th_Interp *interp,
  void *ctx, 
  int argc, 
  const char **argv, 
  int *argl
){
832
833
834
835
836
837
838
839

840
841
842
843
844
845

846
847
848
849
850
851

852
853
854
855
856
857

858
859
860
861
862
863
864
865
866
867
868
869
870
871
872

873
874
875
876
877
878
879
880






881



882
883


884




885
886
887



888
889
890
891


892
893
894
895
896
897
898
857
858
859
860
861
862
863

864
865
866
867
868
869

870
871
872
873
874
875

876
877
878
879
880
881

882
883









884
885



886
887







888
889
890
891
892
893
894
895
896
897


898
899
900
901
902
903
904



905
906
907
908
909


910
911
912
913
914
915
916
917
918







-
+





-
+





-
+





-
+

-
-
-
-
-
-
-
-
-


-
-
-
+

-
-
-
-
-
-
-
+
+
+
+
+
+

+
+
+
-
-
+
+

+
+
+
+
-
-
-
+
+
+


-
-
+
+







}

int th_register_argv(Th_Interp *interp){
  static Th_Command_Reg aCommand[] = {
    {"argv",            argvTopLevelCmd, 0 },
    {0, 0, 0}
  };
  Th_register_commands( interp, aCommand );
  Th_RegisterCommands( interp, aCommand );
}

#endif
/* end TH_ENABLE_ARGV */

#ifdef TH_ENABLE_SQLITE
#ifdef TH_ENABLE_QUERY

/*
** Adds the given prepared statement to the interpreter. Returns the
** statement's opaque identifier (a positive value). Ownerships of
** pStmt is transfered to interp and it must be cleaned up by the
** client by calling Th_FinalizeStmt(), passing it the value returned
** client by calling Th_query_FinalizeStmt(), passing it the value returned
** by this function.
**
** If interp is destroyed before all statements are finalized,
** it will finalize them but may emit a warning message.
*/
static int Th_AddStmt(Th_Interp *interp, sqlite3_stmt * pStmt);
static int Th_query_AddStmt(Th_Interp *interp, sqlite3_stmt * pStmt);

/*
** Expects stmtId to be a statement identifier returned by
** Th_AddStmt(). On success, finalizes the statement and returns 0.
** On error (statement not found) non-0 is returned. After this
** call, some subsequent call to Th_AddStmt() may return the
** same statement ID.
*/
static int Th_FinalizeStmt(Th_Interp *interp, int stmtId);
static int Th_FinalizeStmt2(Th_Interp *interp, sqlite3_stmt *);

/*
** Fetches the statement with the given ID, as returned by
** Th_AddStmt(). Returns NULL if stmtId does not refer (or no longer
** refers) to a statement added via Th_AddStmt().
** Internal state for the "query" API.
*/
static sqlite3_stmt * Th_GetStmt(Th_Interp *interp, int stmtId);


struct Th_Sqlite {
  sqlite3_stmt ** aStmt;
  int nStmt;
  int colCmdIndex;
struct Th_Query {
  sqlite3_stmt ** aStmt; /* Array of statement handles. */
  int nStmt;             /* number of entries in aStmt. */
  int colCmdIndex;       /* column index argument. Set by some top-level dispatchers
                            for their subcommands.
                         */
};
/*
** Internal key for use with Th_Data_Add().
*/
#define Th_Sqlite_KEY "Th_Sqlite"
typedef struct Th_Sqlite Th_Sqlite;
#define Th_Query_KEY "Th_Query"
typedef struct Th_Query Th_Query;

/*
** Returns the Th_Query object associated with the given interpreter,
** or 0 if there is not one.
*/
static Th_Sqlite * Th_sqlite_manager( Th_Interp * interp ){
  void * p = Th_Data_Get( interp, Th_Sqlite_KEY );
  return p ? (Th_Sqlite*)p : NULL;
static Th_Query * Th_query_manager( Th_Interp * interp ){
  void * p = Th_GetData( interp, Th_Query_KEY );
  return p ? (Th_Query*)p : NULL;
}

static int Th_AddStmt(Th_Interp *interp, sqlite3_stmt * pStmt){
  Th_Sqlite * sq = Th_sqlite_manager(interp);
static int Th_query_AddStmt(Th_Interp *interp, sqlite3_stmt * pStmt){
  Th_Query * sq = Th_query_manager(interp);
  int i, x;
  sqlite3_stmt * s;
  sqlite3_stmt ** list = sq->aStmt;
  for( i = 0; i < sq->nStmt; ++i ){
    s = list[i];
    if(NULL==s){
      list[i] = pStmt;
908
909
910
911
912
913
914







915
916


917
918
919
920
921
922
923
924
925
926
927
928
929




930
931


932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949





950
951
952



953
954
955
956
957



958
959

960
961
962
963

964
965
966
967
968
969
970
971
972

973
974
975
976
977
978
979
980
981

982
983
984
985
986
987
988
928
929
930
931
932
933
934
935
936
937
938
939
940
941


942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960


961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985



986
987
988
989
990
991
992
993
994
995
996
997

998
999
1000
1001

1002
1003
1004
1005
1006
1007
1008
1009
1010

1011
1012
1013
1014
1015
1016
1017
1018
1019

1020
1021
1022
1023
1024
1025
1026
1027







+
+
+
+
+
+
+
-
-
+
+













+
+
+
+
-
-
+
+


















+
+
+
+
+
-
-
-
+
+
+





+
+
+

-
+



-
+








-
+








-
+







  x = sq->nStmt;
  sq->nStmt = i;
  sq->aStmt = list;
  return x + 1;
}


/*
** Expects stmtId to be a statement identifier returned by
** Th_query_AddStmt(). On success, finalizes the statement and returns 0.
** On error (statement not found) non-0 is returned. After this
** call, some subsequent call to Th_query_AddStmt() may return the
** same statement ID.
*/
static int Th_FinalizeStmt(Th_Interp *interp, int stmtId){
  Th_Sqlite * sq = Th_sqlite_manager(interp);
static int Th_query_FinalizeStmt(Th_Interp *interp, int stmtId){
  Th_Query * sq = Th_query_manager(interp);
  sqlite3_stmt * st;
  int rc = 0;
  assert( stmtId>0 && stmtId<=sq->nStmt );
  st = sq->aStmt[stmtId-1];
  if(NULL != st){
    sq->aStmt[stmtId-1] = NULL;
    sqlite3_finalize(st);
    return 0;
  }else{
    return 1;
  }
}

/*
** Works like Th_query_FinalizeStmt() but takes a statement pointer, which
** must have been Th_query_AddStmt()'d to the given interpreter.
*/
static int Th_FinalizeStmt2(Th_Interp *interp, sqlite3_stmt * pSt){
  Th_Sqlite * sq = Th_sqlite_manager(interp);
static int Th_query_FinalizeStmt2(Th_Interp *interp, sqlite3_stmt * pSt){
  Th_Query * sq = Th_query_manager(interp);
  int i = 0;
  sqlite3_stmt * st = NULL;
  int rc = 0;
  for( ; i < sq->nStmt; ++i ){
    st = sq->aStmt[i];
    if(st == pSt) break;
  }
  if( st == pSt ){
    assert( i>=0 && i<sq->nStmt );
    sq->aStmt[i] = NULL;
    sqlite3_finalize(st);
    return 0;
  }else{
    return 1;
  }
}


/*
** Fetches the statement with the given ID, as returned by
** Th_query_AddStmt(). Returns NULL if stmtId does not refer (or no longer
** refers) to a statement added via Th_query_AddStmt().
*/
static sqlite3_stmt * Th_GetStmt(Th_Interp *interp, int stmtId){
  Th_Sqlite * sq = Th_sqlite_manager(interp);
  return ((stmtId<1) || (stmtId > sq->nStmt))
static sqlite3_stmt * Th_query_GetStmt(Th_Interp *interp, int stmtId){
  Th_Query * sq = Th_query_manager(interp);
  return (!sq || (stmtId<1) || (stmtId > sq->nStmt))
    ? NULL
    : sq->aStmt[stmtId-1];
}


/*
** Th_GCEntry finalizer which requires that p be a (Th_Query*).
*/
static void finalizerSqlite( Th_Interp * interp, void * p ){
  Th_Sqlite * sq = (Th_Sqlite *)p;
  Th_Query * sq = (Th_Query *)p;
  int i;
  sqlite3_stmt * st = NULL;
  if(!sq) {
    fossil_warning("Got a finalizer call for a NULL Th_Sqlite.");
    fossil_warning("Got a finalizer call for a NULL Th_Query.");
    return;
  }
  for( i = 0; i < sq->nStmt; ++i ){
    st = sq->aStmt[i];
    if(NULL != st){
      fossil_warning("Auto-finalizing unfinalized "
                     "statement id #%d: %s",
                     i+1, sqlite3_sql(st));
      Th_FinalizeStmt( interp, i+1 );
      Th_query_FinalizeStmt( interp, i+1 );
    }
  }
  Th_Free(interp, sq->aStmt);
  Th_Free(interp, sq);
}


/*
** TH Syntax:
** TH command:
**
** query prepare SQL
**
** Returns an opaque statement identifier.
*/
static int queryPrepareCmd(
  Th_Interp *interp,
1014
1015
1016
1017
1018
1019
1020
1021

1022
1023
1024
1025
1026
1027
1028
1053
1054
1055
1056
1057
1058
1059

1060
1061
1062
1063
1064
1065
1066
1067







-
+







  }
  if(SQLITE_OK!=rc){
    assert(NULL != errMsg);
    assert(NULL == pStmt);
    Th_ErrorMessage(interp, "error preparing SQL:", errMsg, -1);
    return TH_ERROR;
  }
  rc = Th_AddStmt( interp, pStmt );
  rc = Th_query_AddStmt( interp, pStmt );
  assert( rc >= 0 && "AddStmt failed.");
  Th_SetResultInt( interp, rc );
  return TH_OK;
}

/*
** Tries to convert arg, which must be argLen bytes long, to a
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
1076
1077
1078
1079
1080
1081
1082

1083
1084
1085
1086
1087
1088
1089
1090
1091
1092

1093
1094
1095
1096
1097
1098
1099
1100







-
+









-
+







static sqlite3_stmt * queryStmtHandle(Th_Interp *interp, char const * arg, int argLen, int * stmtId ){
  int rc = 0;
  sqlite3_stmt * pStmt = NULL;
  if( 0 == Th_ToInt( interp, arg, argLen, &rc ) ){
    if(stmtId){
      *stmtId = rc;
    }
    pStmt = Th_GetStmt( interp, rc );
    pStmt = Th_query_GetStmt( interp, rc );
    if(NULL==pStmt){
      Th_ErrorMessage(interp, "no such statement handle:", arg, -1);
    }
  }
  return pStmt;

}

/*
** TH Syntax:
** TH command:
**
** query finalize stmtId
** query stmtId finalize 
**
** sqlite3_finalize()s the given statement.
*/
static int queryFinalizeCmd(
1081
1082
1083
1084
1085
1086
1087
1088

1089
1090
1091
1092
1093
1094
1095
1120
1121
1122
1123
1124
1125
1126

1127
1128
1129
1130
1131
1132
1133
1134







-
+







    pStmt = queryStmtHandle(interp, arg, argl[1], &stId);
    if(!pStmt){
      Th_ErrorMessage(interp, "Not a valid statement handle argument.", NULL, 0);
      return TH_ERROR;
    }
  }
  assert( NULL != pStmt );
  rc = Th_FinalizeStmt2( interp, pStmt );
  rc = Th_query_FinalizeStmt2( interp, pStmt );
  Th_SetResultInt( interp, rc );
  return TH_OK;
}

/*
** Reports the current sqlite3_errmsg() via TH and returns TH_ERROR.
*/
1146
1147
1148
1149
1150
1151
1152
1153

1154
1155
1156
1157
1158
1159
1160
1185
1186
1187
1188
1189
1190
1191

1192
1193
1194
1195
1196
1197
1198
1199







-
+







      *pIndex = index;
    }
    return 0;
  }
}

/*
** TH Syntax:
** TH command:
**
** query step stmtId
** query stmtId step
**
** Steps the given statement handle. Returns 0 at the end of the set,
** a positive value if it fetches a row, and throws on error.
*/
1188
1189
1190
1191
1192
1193
1194








1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214

1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229

1230
1231
1232
1233
1234
1235
1236
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260

1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275

1276
1277
1278
1279
1280
1281
1282
1283







+
+
+
+
+
+
+
+



















-
+














-
+







    default:
      return queryReportDbErr( interp );
  }
  Th_SetResultInt( interp, rc );
  return TH_OK;
}

/*
** TH command:
**
** query StmtId reset
** query reset StmtId
**
** Equivalent to sqlite3_reset().
*/
static int queryResetCmd(
  Th_Interp *interp,
  void *p, 
  int argc, 
  const char **argv, 
  int *argl
){
  sqlite3_stmt * pStmt = (sqlite3_stmt*)p;
  int const rc = sqlite3_reset(pStmt);
  if(rc){
    Th_ErrorMessage(interp, "Reset of statement failed.", NULL, 0);
    return TH_ERROR;
  }else{
    return TH_OK;
  }
}


/*
** TH Syntax:
** TH command:
**
** query col string stmtId Index
** query stmtId col string Index
** query stmtId col Index string
**
** Returns the result column value at the given 0-based index.
*/
static int queryColStringCmd(
  Th_Interp *interp,
  void *p, 
  int argc, 
  const char **argv, 
  int *argl
){
  Th_Sqlite * sq = Th_sqlite_manager(interp);
  Th_Query * sq = Th_query_manager(interp);
  int index = sq->colCmdIndex;
  sqlite3_stmt * pStmt = (sqlite3_stmt*)p;
  int requireArgc = pStmt ? 2 : 3;
  char const * val;
  int valLen;
  if( index >= 0 ) --requireArgc;
  if( argc!=requireArgc ){
1249
1250
1251
1252
1253
1254
1255
1256

1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271

1272
1273
1274
1275
1276
1277
1278
1296
1297
1298
1299
1300
1301
1302

1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317

1318
1319
1320
1321
1322
1323
1324
1325







-
+














-
+







  val = sqlite3_column_text( pStmt, index );
  valLen = val ? sqlite3_column_bytes( pStmt, index ) : 0;
  Th_SetResult( interp, val, valLen );
  return TH_OK;
}

/*
** TH Syntax:
** TH command:
**
** query col int stmtId Index
** query stmtId col int Index
** query stmtId col Index int
**
** Returns the result column value at the given 0-based index.
*/
static int queryColIntCmd(
  Th_Interp *interp,
  void *p, 
  int argc, 
  const char **argv, 
  int *argl
){
  Th_Sqlite * sq = Th_sqlite_manager(interp);
  Th_Query * sq = Th_query_manager(interp);
  int index = sq->colCmdIndex;
  sqlite3_stmt * pStmt = (sqlite3_stmt*)p;
  int requireArgc = pStmt ? 2 : 3;
  int rc = 0;
  if( index >= 0 ) --requireArgc;
  if( argc!=requireArgc ){
    return Th_WrongNumArgs2(interp,
1288
1289
1290
1291
1292
1293
1294
1295

1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310

1311
1312
1313
1314
1315
1316
1317
1335
1336
1337
1338
1339
1340
1341

1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356

1357
1358
1359
1360
1361
1362
1363
1364







-
+














-
+







    return TH_ERROR;
  }
  Th_SetResultInt( interp, sqlite3_column_int( pStmt, index ) );
  return TH_OK;
}

/*
** TH Syntax:
** TH command:
**
** query col double stmtId Index
** query stmtId col double Index
** query stmtId col Index double
**
** Returns the result column value at the given 0-based index.
*/
static int queryColDoubleCmd(
  Th_Interp *interp,
  void *p, 
  int argc, 
  const char **argv, 
  int *argl
){
  Th_Sqlite * sq = Th_sqlite_manager(interp);
  Th_Query * sq = Th_query_manager(interp);
  int index = sq->colCmdIndex;
  sqlite3_stmt * pStmt = (sqlite3_stmt*)p;
  int requireArgc = pStmt ? 2 : 3;
  double rc = 0;
  if( index >= 0 ) --requireArgc;
  if( argc!=requireArgc ){
    return Th_WrongNumArgs2(interp,
1327
1328
1329
1330
1331
1332
1333
1334

1335
1336
1337

1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350

1351
1352
1353
1354
1355
1356
1357
1374
1375
1376
1377
1378
1379
1380

1381
1382
1383

1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396

1397
1398
1399
1400
1401
1402
1403
1404







-
+


-
+












-
+







    return TH_ERROR;
  }
  Th_SetResultDouble( interp, sqlite3_column_double( pStmt, index ) );
  return TH_OK;
}

/*
** TH Syntax:
** TH command:
**
** query col isnull stmtId Index
** query stmtId col is_null Index
** query stmtId col isnull Index
** query stmtId col Index isnull
**
** Returns non-0 if the given 0-based result column index contains
** an SQL NULL value, else returns 0.
*/
static int queryColIsNullCmd(
  Th_Interp *interp,
  void *p, 
  int argc, 
  const char **argv, 
  int *argl
){
  Th_Sqlite * sq = Th_sqlite_manager(interp);
  Th_Query * sq = Th_query_manager(interp);
  int index = sq->colCmdIndex;
  sqlite3_stmt * pStmt = (sqlite3_stmt*)p;
  int requireArgc = pStmt ? 2 : 3;
  if( index >= 0 ) --requireArgc;
  double rc = 0;
  if( argc!=requireArgc ){
    return Th_WrongNumArgs2(interp,
1369
1370
1371
1372
1373
1374
1375
1376

1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393

1394
1395
1396
1397
1398
1399
1400
1416
1417
1418
1419
1420
1421
1422

1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439

1440
1441
1442
1443
1444
1445
1446
1447







-
+
















-
+







  Th_SetResultInt( interp,
                   SQLITE_NULL==sqlite3_column_type( pStmt, index )
                   ? 1 : 0);
  return TH_OK;
}

/*
** TH Syntax:
** TH command:
**
** query col type stmtId Index
** query stmtId col type Index
** query stmtId col Index type
**
** Returns the sqlite type identifier for the given 0-based result
** column index. The values are available in TH as $SQLITE_NULL,
** $SQLITE_INTEGER, etc.
*/
static int queryColTypeCmd(
  Th_Interp *interp,
  void *p, 
  int argc, 
  const char **argv, 
  int *argl
){
  Th_Sqlite * sq = Th_sqlite_manager(interp);
  Th_Query * sq = Th_query_manager(interp);
  int index = sq->colCmdIndex;
  sqlite3_stmt * pStmt = (sqlite3_stmt*)p;
  int requireArgc = pStmt ? 2 : 3;
  if( index >= 0 ) --requireArgc;
  double rc = 0;
  if( argc!=requireArgc ){
    return Th_WrongNumArgs2(interp,
1410
1411
1412
1413
1414
1415
1416
1417

1418
1419
1420
1421
1422
1423
1424
1457
1458
1459
1460
1461
1462
1463

1464
1465
1466
1467
1468
1469
1470
1471







-
+







    return TH_ERROR;
  }
  Th_SetResultInt( interp, sqlite3_column_type( pStmt, index ) );
  return TH_OK;
}

/*
** TH Syntax:
** TH command:
**
** query col count stmtId
** query stmtId col count
**
** Returns the number of result columns in the query.
*/
static int queryColCountCmd(
1444
1445
1446
1447
1448
1449
1450
1451

1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466

1467
1468
1469
1470
1471
1472
1473
1491
1492
1493
1494
1495
1496
1497

1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512

1513
1514
1515
1516
1517
1518
1519
1520







-
+














-
+







  }
  rc = sqlite3_column_count( pStmt );
  Th_SetResultInt( interp, rc );
  return TH_OK;
}

/*
** TH Syntax:
** TH command:
**
** query col name stmtId Index
** query stmtId col name Index
** query stmtId col Index name 
**
** Returns the result column name at the given 0-based index.
*/
static int queryColNameCmd(
  Th_Interp *interp,
  void *p, 
  int argc, 
  const char **argv, 
  int *argl
){
  Th_Sqlite * sq = Th_sqlite_manager(interp);
  Th_Query * sq = Th_query_manager(interp);
  int index = sq->colCmdIndex;
  sqlite3_stmt * pStmt = (sqlite3_stmt*)p;
  int requireArgc = pStmt ? 2 : 3;
  char const * val;
  int rc = 0;
  if( index >= 0 ) --requireArgc;
  if( argc!=requireArgc ){
1491
1492
1493
1494
1495
1496
1497
1498

1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513

1514
1515
1516
1517
1518
1519
1520
1538
1539
1540
1541
1542
1543
1544

1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559

1560
1561
1562
1563
1564
1565
1566
1567







-
+














-
+







  }else{
    Th_SetResult( interp, val, strlen( val ) );
    return TH_OK;
  }
}

/*
** TH Syntax:
** TH command:
**
** query col time stmtId Index format
** query stmtId col name Index format
** query stmtId col Index name format
**
** Returns the result column name at the given 0-based index.
*/
static int queryColTimeCmd(
  Th_Interp *interp,
  void *ctx, 
  int argc, 
  const char **argv, 
  int *argl
){
  Th_Sqlite * sq = Th_sqlite_manager(interp);
  Th_Query * sq = Th_query_manager(interp);
  int index = sq->colCmdIndex;
  sqlite3_stmt * pStmt = (sqlite3_stmt*)ctx;
  int minArgs = pStmt ? 3 : 4;
  int argPos;
  char const * val;
  char * fval;
  int i, rc = 0;
1553
1554
1555
1556
1557
1558
1559







1560
1561
1562
1563
1564
1565
1566
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620







+
+
+
+
+
+
+







  
  blob_reset(&sql);
  Th_SetResult( interp, fval, fval ? strlen(fval) : 0 );
  fossil_free(fval);
  return 0;
}

/*
** TH command:
**
**  query strftime TimeVal ?Modifiers...?
**
** Acts as a proxy to sqlite3's strftime() SQL function.
*/
static int queryStrftimeCmd(
  Th_Interp *interp,
  void *ctx, 
  int argc, 
  const char **argv, 
  int *argl
){
1590
1591
1592
1593
1594
1595
1596
1597

1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611

1612
1613
1614
1615
1616
1617
1618
1644
1645
1646
1647
1648
1649
1650

1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664

1665
1666
1667
1668
1669
1670
1671
1672







-
+













-
+







  Th_SetResult( interp, fval, fval ? strlen(fval) : 0 );
  fossil_free(fval);
  return 0;
}


/*
** TH Syntax:
** TH command:
**
** query bind null stmtId Index
** query stmtId bind null Index
**
** Binds a value to the given 1-based parameter index.
*/
static int queryBindNullCmd(
  Th_Interp *interp,
  void *p, 
  int argc, 
  const char **argv, 
  int *argl
){
  Th_Sqlite * sq = Th_sqlite_manager(interp);
  Th_Query * sq = Th_query_manager(interp);
  int index = sq->colCmdIndex;
  sqlite3_stmt * pStmt = (sqlite3_stmt*)p;
  int requireArgc = pStmt ? 2 : 3;
  if( index > 0 ) --requireArgc;
  int rc;
  if( argc!=requireArgc ){
    return Th_WrongNumArgs2(interp,
1633
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
1661
1687
1688
1689
1690
1691
1692
1693

1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707

1708
1709
1710
1711
1712
1713
1714
1715







-
+













-
+







  }
  Th_SetResultInt( interp, 0 );
  return TH_OK;
}


/*
** TH Syntax:
** TH command:
**
** query bind string stmtId Index Value
** query stmtId bind string Index Value
**
** Binds a value to the given 1-based parameter index.
*/
static int queryBindStringCmd(
  Th_Interp *interp,
  void *p, 
  int argc, 
  const char **argv, 
  int *argl
){
  Th_Sqlite * sq = Th_sqlite_manager(interp);
  Th_Query * sq = Th_query_manager(interp);
  int index = sq->colCmdIndex;
  sqlite3_stmt * pStmt = (sqlite3_stmt*)p;
  int requireArgc = pStmt ? 3 : 4;
  int rc;
  int argPos;
  if( index > 0 ) --requireArgc;
  if( argc!=requireArgc ){
1680
1681
1682
1683
1684
1685
1686
1687

1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701

1702
1703
1704
1705
1706
1707
1708
1734
1735
1736
1737
1738
1739
1740

1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754

1755
1756
1757
1758
1759
1760
1761
1762







-
+













-
+







    return queryReportDbErr( interp );
  }
  Th_SetResultInt( interp, 0 );
  return TH_OK;
}

/*
** TH Syntax:
** TH command:
**
** query bind int stmtId Index Value
** query stmtId bind int Index Value
**
** Binds a value to the given 1-based parameter index.
*/
static int queryBindIntCmd(
  Th_Interp *interp,
  void *p, 
  int argc, 
  const char **argv, 
  int *argl
){
  Th_Sqlite * sq = Th_sqlite_manager(interp);
  Th_Query * sq = Th_query_manager(interp);
  int index = sq->colCmdIndex;
  sqlite3_stmt * pStmt = (sqlite3_stmt*)p;
  int requireArgc = pStmt ? 3 : 4;
  int rc;
  int argPos;
  int val;
  if( index > 0 ) --requireArgc;
1732
1733
1734
1735
1736
1737
1738
1739

1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753

1754
1755
1756
1757
1758
1759
1760
1786
1787
1788
1789
1790
1791
1792

1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806

1807
1808
1809
1810
1811
1812
1813
1814







-
+













-
+







    return queryReportDbErr( interp );
  }
  Th_SetResultInt( interp, 0 );
  return TH_OK;
}

/*
** TH Syntax:
** TH command:
**
** query bind double stmtId Index Value
** query stmtId bind double Index Value
**
** Binds a value to the given 1-based parameter index.
*/
static int queryBindDoubleCmd(
  Th_Interp *interp,
  void *p, 
  int argc, 
  const char **argv, 
  int *argl
){
  Th_Sqlite * sq = Th_sqlite_manager(interp);
  Th_Query * sq = Th_query_manager(interp);
  int index = sq->colCmdIndex;
  sqlite3_stmt * pStmt = (sqlite3_stmt*)p;
  int requireArgc = pStmt ? 3 : 4;
  int rc;
  int argPos;
  double val;
  if( index > 0 ) --requireArgc;
1783
1784
1785
1786
1787
1788
1789








1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805

1806
1807
1808
1809

1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824








1825
1826
1827
1828
1829
1830
1831
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866

1867
1868
1869
1870

1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901







+
+
+
+
+
+
+
+















-
+



-
+















+
+
+
+
+
+
+
+







  if(rc){
    return queryReportDbErr( interp );
  }
  Th_SetResultInt( interp, 0 );
  return TH_OK;
}

/*
** TH command:
**
** bind subcommand StmtId...
** bind StmtId subcommand...
**
** This is the top-level dispatcher for the "bind" family of commands.
*/
static int queryBindTopLevelCmd(
  Th_Interp *interp,
  void *ctx, 
  int argc, 
  const char **argv, 
  int *argl
){
  int colIndex = -1;
  static Th_SubCommand aSub[] = {
    {"int",    queryBindIntCmd},
    {"double", queryBindDoubleCmd},
    {"null",   queryBindNullCmd},
    {"string", queryBindStringCmd},
    {0, 0}
  };
  Th_Sqlite * sq = Th_sqlite_manager(interp);
  Th_Query * sq = Th_query_manager(interp);
  assert(NULL != sq);
  if( 1 == argc ){
      Th_WrongNumArgs2( interp, argv[0], argl[0],
                        "subcommand");
                        "subcommand: int|double|null|string");
      return TH_ERROR;
  }else if( 0 == Th_TryInt(interp,argv[1], argl[1], &colIndex) ){
    if(colIndex <0){
      Th_ErrorMessage( interp, "Invalid column index.", NULL, 0);
      return TH_ERROR;
    }
    ++argv;
    ++argl;
    --argc;
  }
  sq->colCmdIndex = colIndex;
  Th_CallSubCommand2( interp, ctx, argc, argv, argl, aSub );

}

/*
** TH command:
**
** query col subcommand ...
** query StmtId col subcommand ...
**
** This is the top-level dispatcher for the col subcommands.
*/
static int queryColTopLevelCmd(
  Th_Interp *interp,
  void *ctx, 
  int argc, 
  const char **argv, 
  int *argl
){
1839
1840
1841
1842
1843
1844
1845






1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856

1857
1858
1859
1860



1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876








1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892


1893
1894
1895
1896
1897
1898
1899


1900

1901
1902
1903
1904
1905
1906
1907
1908
1909
1910

1911
1912
1913

1914
1915
1916
1917
1918
1919

1920
1921
1922
1923
1924
1925
1926




1927
1928
1929
1930
1931
1932
1933
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931

1932
1933
1934
1935

1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974


1975
1976
1977
1978
1979
1980
1981
1982



1983
1984

1985
1986
1987
1988
1989
1990
1991
1992
1993
1994

1995
1996
1997

1998
1999
2000
2001
2002
2003

2004
2005
2006
2007
2008
2009
2010

2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021







+
+
+
+
+
+










-
+



-
+
+
+
















+
+
+
+
+
+
+
+












-
-


+
+




-
-
-
+
+
-
+









-
+


-
+





-
+






-
+
+
+
+







    {"int",     queryColIntCmd},
    {"string",  queryColStringCmd},
    {"time",    queryColTimeCmd},
    {"type",    queryColTypeCmd},
    {0, 0}
  };
  static Th_SubCommand aSubWithIndex[] = {
    /*
      This subset is coded to accept the column index
      either before the subcommand name or after it.
      If called like (bind StmtId subcommand) then
      only these commands will be checked.
    */
    {"is_null", queryColIsNullCmd},
    {"isnull",  queryColIsNullCmd},
    {"name",    queryColNameCmd},
    {"double",  queryColDoubleCmd},
    {"int",     queryColIntCmd},
    {"string",  queryColStringCmd},
    {"time",    queryColTimeCmd},
    {"type",    queryColTypeCmd},
    {0, 0}
  };
  Th_Sqlite * sq = Th_sqlite_manager(interp);
  Th_Query * sq = Th_query_manager(interp);
  assert(NULL != sq);
  if( 1 == argc ){
      Th_WrongNumArgs2( interp, argv[0], argl[0],
                        "subcommand");
                        "subcommand: "
                        "count|is_null|isnull|name|"
                        "double|int|string|time|type");
      return TH_ERROR;
  }else if( 0 == Th_TryInt(interp,argv[1], argl[1], &colIndex) ){
    if(colIndex <0){
      Th_ErrorMessage( interp, "Invalid column index.", NULL, 0);
      return TH_ERROR;
    }
    ++argv;
    ++argl;
    --argc;
  }
  sq->colCmdIndex = colIndex;
  Th_CallSubCommand2( interp, ctx, argc, argv, argl,
                      (colIndex<0) ? aSub : aSubWithIndex );
}


/*
** TH command:
**
** query subcommand ...
** query StmtId subcommand ...
**
** This is the top-level dispatcher for the query subcommand.
*/
static int queryTopLevelCmd(
  Th_Interp *interp,
  void *ctx, 
  int argc, 
  const char **argv, 
  int *argl
){
  int stmtId = 0;
  sqlite3_stmt * pStmt = NULL;
  static Th_SubCommand aSubAll[] = {
    {"bind",        queryBindTopLevelCmd},
    {"col",         queryColTopLevelCmd},
    {"reset",       queryResetCmd},
    {"step",        queryStepCmd},
    {"finalize",    queryFinalizeCmd},
    {"prepare",     queryPrepareCmd},
    {"reset",       queryResetCmd},
    {"step",        queryStepCmd},
    {"strftime",    queryStrftimeCmd},
    {0, 0}
  };
  static Th_SubCommand aSubWithStmt[] = {
  /* These entries are coded to deal with
     being supplied a statement via pStmt
     or via one of their args.
    /* This subset is coded to deal with being supplied a statement
       via pStmt or via one of their args. When called like (query
   */
       StmtId ...) only these subcommands will be checked.*/
    {"bind",        queryBindTopLevelCmd},
    {"col",         queryColTopLevelCmd},
    {"step",        queryStepCmd},
    {"finalize",    queryFinalizeCmd},
    {"reset",       queryResetCmd},
    {0, 0}
  };


  assert( NULL != Th_sqlite_manager(interp) );
  assert( NULL != Th_query_manager(interp) );
  if( 1 == argc ){
      Th_WrongNumArgs2( interp, argv[0], argl[0],
                        "subcommand");
                        "subcommand: bind|col|finalize|prepare|reset|step|strftime");
      return TH_ERROR;
  }else if( 0 == Th_TryInt(interp,argv[1], argl[1], &stmtId) ){
    ++argv;
    ++argl;
    --argc;
    pStmt = Th_GetStmt( interp, stmtId );
    pStmt = Th_query_GetStmt( interp, stmtId );
  }

  Th_CallSubCommand2( interp, pStmt, argc, argv, argl,
                      pStmt ? aSubWithStmt : aSubAll );
}


/*
** Registers the "query" API with the given interpreter. Returns TH_OK
** on success, TH_ERROR on error.
*/
int th_register_query(Th_Interp *interp){
  enum { BufLen = 100 };
  char buf[BufLen];
  int i, l;
#define SET(K) l = snprintf(buf, BufLen, "%d", K);      \
  Th_SetVar( interp, #K, strlen(#K), buf, l );
  SET(SQLITE_BLOB);
1941
1942
1943
1944
1945
1946
1947
1948

1949
1950

1951
1952
1953
1954
1955
1956
1957


1958
1959
1960
1961
1962
1963
1964

1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987









1988
1989
1990
1991
1992
1993
1994
2029
2030
2031
2032
2033
2034
2035

2036
2037

2038
2039
2040
2041
2042
2043


2044
2045
2046
2047
2048
2049
2050
2051

2052















2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076







-
+

-
+





-
-
+
+






-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-








+
+
+
+
+
+
+
+
+







  SET(SQLITE_TEXT);
#undef SET
  int rc = TH_OK;
  static Th_Command_Reg aCommand[] = {
    {"query",             queryTopLevelCmd,  0},
    {0, 0, 0}
  };
  rc = Th_register_commands( interp, aCommand );
  rc = Th_RegisterCommands( interp, aCommand );
  if(TH_OK==rc){
    Th_Sqlite * sq = Th_Malloc(interp, sizeof(Th_Sqlite));
    Th_Query * sq = Th_Malloc(interp, sizeof(Th_Query));
    if(!sq){
      rc = TH_ERROR;
    }else{
      assert( NULL == sq->aStmt );
      assert( 0 == sq->nStmt );
      Th_Data_Set( interp, Th_Sqlite_KEY, sq, finalizerSqlite );
      assert( sq == Th_sqlite_manager(interp) );
      Th_SetData( interp, Th_Query_KEY, sq, finalizerSqlite );
      assert( sq == Th_query_manager(interp) );
    }
  }
  return rc;
}

#endif
/* end TH_ENABLE_SQLITE */
/* end TH_ENABLE_QUERY */

int Th_register_commands( Th_Interp * interp,
                           Th_Command_Reg const * aCommand ){
  int i;
  int rc = TH_OK;
  for(i=0; (TH_OK==rc) && aCommand[i].zName; ++i){
    if ( !aCommand[i].zName ) break;
    else if( !aCommand[i].xProc ) continue;
    else{
      rc = Th_CreateCommand(interp, aCommand[i].zName, aCommand[i].xProc,
                            aCommand[i].pContext, 0);
    }
  }
  return rc;
}

/*
** Make sure the interpreter has been initialized.  Initialize it if
** it has not been already.
**
** The interpreter is stored in the g.interp global variable.
*/
void Th_FossilInit(void){
  /* The fossil-internal Th_Vtab instance. */
  static Th_Vtab vtab = { xRealloc, {/*out*/
    NULL /*write()*/,
    NULL/*dispose()*/,
    NULL/*pState*/,
    1/*enabled*/
    }
  };

  static PutsCmdData puts_Html = {0, 0, 0};
  static PutsCmdData puts_Normal = {1, 0, 0};
  static Th_Command_Reg aCommand[] = {
    {"anycap",        anycapCmd,            0},
    {"combobox",      comboboxCmd,          0},
    {"date",          dateCmd,              0},
    {"enable_output", enableOutputCmd,      0},
2005
2006
2007
2008
2009
2010
2011
2012

2013
2014

2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025

2026
2027
2028

2029
2030
2031
2032
2033
2034

2035
2036
2037
2038
2039
2040
2041
2087
2088
2089
2090
2091
2092
2093

2094
2095

2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106

2107
2108
2109

2110
2111
2112
2113
2114
2115

2116
2117
2118
2119
2120
2121
2122
2123







-
+

-
+










-
+


-
+





-
+







    {"wiki",          wikiCmd,              0},

    {0, 0, 0}
  };
  if( g.interp==0 ){
    int i;
    if(g.cgiOutput){
      vtab.out.write = Th_output_f_cgi_content;
      vtab.out.write = Th_Output_f_cgi_content;
    }else{
      vtab.out = Th_Vtab_Output_FILE;
      vtab.out = Th_Vtab_OutputMethods_FILE;
      vtab.out.pState = stdout;
    }
    vtab.out.enabled = enableOutput;
    g.interp = Th_CreateInterp(&vtab);
    th_register_language(g.interp);       /* Basic scripting commands. */
#ifdef FOSSIL_ENABLE_TCL
    if( getenv("TH1_ENABLE_TCL")!=0 || db_get_boolean("tcl", 0) ){
      th_register_tcl(g.interp, &g.tcl);  /* Tcl integration commands. */
    }
#endif
#ifdef TH_ENABLE_OUTBUF
#ifdef TH_ENABLE_OB
    th_register_ob(g.interp);
#endif
#ifdef TH_ENABLE_SQLITE
#ifdef TH_ENABLE_QUERY
    th_register_query(g.interp);
#endif
#ifdef TH_ENABLE_ARGV
    th_register_argv(g.interp);
#endif
    Th_register_commands( g.interp, aCommand );
    Th_RegisterCommands( g.interp, aCommand );
    Th_Eval( g.interp, 0, "proc incr {name {step 1}} {\n"
             "upvar $name x\n"
             "set x [expr $x+$step]\n"
             "}", -1 );
  }
}

2138
2139
2140
2141
2142
2143
2144
2145

2146
2147
2148
2149
2150
2151
2152
2220
2221
2222
2223
2224
2225
2226

2227
2228
2229
2230
2231
2232
2233
2234







-
+







**
** If flags does NOT contain the Th_Render_Flags_NO_DOLLAR_DEREF bit
** then TH1 variables are $aaa or $<aaa>.  The first form of variable
** is literal.  The second is run through htmlize before being
** inserted.
**
** This routine processes the template and writes the results
** via Th_output().
** via Th_Output().
*/
int Th_Render(const char *z, int flags){
  int i = 0;
  int n;
  int rc = TH_OK;
  char const *zResult;
  char doDollar = !(flags & Th_Render_Flags_NO_DOLLAR_DEREF);
2199
2200
2201
2202
2203
2204
2205
2206
2207






2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218

2219
2220
2221
2222
2223
2224
2281
2282
2283
2284
2285
2286
2287


2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303

2304
2305
2306
2307
2308
2309
2310







-
-
+
+
+
+
+
+










-
+






/*
** COMMAND: test-th-render
** COMMAND: th1
**
** Processes a file provided on the command line as a TH1-capable
** script/page. Output is sent to stdout or the CGI output buffer, as
** appropriate. The input file is assumed to be text/wiki/HTML content
** which may contain TH1 tag blocks. Each block is executed in the
** same TH1 interpreter instance.
** which may contain TH1 tag blocks and variables in the form $var or
** $<var>. Each block is executed in the same TH1 interpreter
** instance.
**
** ACHTUNG: not all of the $variables which are set in CGI mode
** are available via this (CLI) command.
**
*/
void test_th_render(void){
  Blob in;
  if( g.argc<3 ){
    usage("FILE");
    assert(0 && "usage() does not return");
  }
  blob_zero(&in);
  db_open_config(0); /* Needed for global "tcl" setting. */
#ifdef TH_ENABLE_SQLITE
#ifdef TH_ENABLE_QUERY
  db_find_and_open_repository(OPEN_ANY_SCHEMA,0)
    /* required for th1 query API. */;
#endif
  blob_read_from_file(&in, g.argv[2]);
  Th_Render(blob_str(&in), Th_Render_Flags_DEFAULT);
}