/ Check-in [86b30cd0]
Login

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

Overview
Comment:better handling of out-of-memory errors (CVS 207)
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1: 86b30cd0975dfea9424b9f9f0d4194aa71ce508b
User & Date: drh 2001-04-11 14:28:42
Context
2001-04-11
14:29
:-) (CVS 208) check-in: 555351dd user: drh tags: trunk
14:28
better handling of out-of-memory errors (CVS 207) check-in: 86b30cd0 user: drh tags: trunk
2001-04-07
15:24
Added new tests (CVS 206) check-in: 2507ec40 user: drh tags: trunk
Changes
Hide Diffs Side-by-Side Diffs Ignore Whitespace Patch

Changes to src/build.c.

    29     29   **     DROP TABLE
    30     30   **     CREATE INDEX
    31     31   **     DROP INDEX
    32     32   **     creating expressions and ID lists
    33     33   **     COPY
    34     34   **     VACUUM
    35     35   **
    36         -** $Id: build.c,v 1.26 2001/04/04 11:48:57 drh Exp $
           36  +** $Id: build.c,v 1.27 2001/04/11 14:28:42 drh Exp $
    37     37   */
    38     38   #include "sqliteInt.h"
    39     39   
    40     40   /*
    41     41   ** This routine is called after a single SQL statement has been
    42     42   ** parsed and we want to execute the VDBE code to implement 
    43     43   ** that statement.  Prior action routines should have already
................................................................................
    45     45   ** This routine just has to execute the VDBE code.
    46     46   **
    47     47   ** Note that if an error occurred, it might be the case that
    48     48   ** no VDBE code was generated.
    49     49   */
    50     50   void sqliteExec(Parse *pParse){
    51     51     int rc = SQLITE_OK;
           52  +  if( sqlite_malloc_failed ) return;
    52     53     if( pParse->pVdbe ){
    53     54       if( pParse->explain ){
    54     55         rc = sqliteVdbeList(pParse->pVdbe, pParse->xCallback, pParse->pArg, 
    55     56                             &pParse->zErrMsg);
    56     57       }else{
    57     58         FILE *trace = (pParse->db->flags & SQLITE_VdbeTrace)!=0 ? stderr : 0;
    58     59         sqliteVdbeTrace(pParse->pVdbe, trace);
................................................................................
    92     93   }
    93     94   
    94     95   /*
    95     96   ** Set the Expr.token field of the given expression to span all
    96     97   ** text between the two given tokens.
    97     98   */
    98     99   void sqliteExprSpan(Expr *pExpr, Token *pLeft, Token *pRight){
    99         -  pExpr->span.z = pLeft->z;
   100         -  pExpr->span.n = pRight->n + (int)pRight->z - (int)pLeft->z;
          100  +  if( pExpr ){
          101  +    pExpr->span.z = pLeft->z;
          102  +    pExpr->span.n = pRight->n + (int)pRight->z - (int)pLeft->z;
          103  +  }
   101    104   }
   102    105   
   103    106   /*
   104    107   ** Construct a new expression node for a function with multiple
   105    108   ** arguments.
   106    109   */
   107    110   Expr *sqliteExprFunction(ExprList *pList, Token *pToken){
................................................................................
   163    166     return 0;
   164    167   }
   165    168   
   166    169   /*
   167    170   ** Remove the given index from the index hash table, and free
   168    171   ** its memory structures.
   169    172   **
   170         -** The index is removed from the database hash table, but it is
   171         -** not unlinked from the Table that is being indexed.  Unlinking
   172         -** from the Table must be done by the calling function.
          173  +** The index is removed from the database hash table if db!=NULL.
          174  +** But it is not unlinked from the Table that is being indexed.  
          175  +** Unlinking from the Table must be done by the calling function.
   173    176   */
   174    177   static void sqliteDeleteIndex(sqlite *db, Index *pIndex){
   175    178     int h;
   176         -  if( pIndex->zName ){
          179  +  if( pIndex->zName && db ){
   177    180       h = sqliteHashNoCase(pIndex->zName, 0) % N_HASH;
   178    181       if( db->apIdxHash[h]==pIndex ){
   179    182         db->apIdxHash[h] = pIndex->pHash;
   180    183       }else{
   181    184         Index *p;
   182    185         for(p=db->apIdxHash[h]; p && p->pHash!=pIndex; p=p->pHash){}
   183    186         if( p && p->pHash==pIndex ){
................................................................................
   191    194   /*
   192    195   ** Remove the memory data structures associated with the given
   193    196   ** Table.  No changes are made to disk by this routine.
   194    197   **
   195    198   ** This routine just deletes the data structure.  It does not unlink
   196    199   ** the table data structure from the hash table.  But does it destroy
   197    200   ** memory structures of the indices associated with the table.
          201  +**
          202  +** Indices associated with the table are unlinked from the "db"
          203  +** data structure if db!=NULL.  If db==NULL, indices attached to
          204  +** the table are deleted, but it is assumed they have already been
          205  +** unlinked.
   198    206   */
   199    207   void sqliteDeleteTable(sqlite *db, Table *pTable){
   200    208     int i;
   201    209     Index *pIndex, *pNext;
   202    210     if( pTable==0 ) return;
   203    211     for(i=0; i<pTable->nCol; i++){
   204    212       sqliteFree(pTable->aCol[i].zName);
................................................................................
   232    240   */
   233    241   void sqliteStartTable(Parse *pParse, Token *pStart, Token *pName){
   234    242     Table *pTable;
   235    243     char *zName;
   236    244   
   237    245     pParse->sFirstToken = *pStart;
   238    246     zName = sqliteTableNameFromToken(pName);
          247  +  if( zName==0 ) return;
   239    248     pTable = sqliteFindTable(pParse->db, zName);
   240    249     if( pTable!=0 ){
   241    250       sqliteSetNString(&pParse->zErrMsg, "table ", 0, pName->z, pName->n,
   242    251           " already exists", 0, 0);
   243    252       sqliteFree(zName);
   244    253       pParse->nErr++;
   245    254       return;
................................................................................
   248    257       sqliteSetString(&pParse->zErrMsg, "there is already an index named ", 
   249    258          zName, 0);
   250    259       sqliteFree(zName);
   251    260       pParse->nErr++;
   252    261       return;
   253    262     }
   254    263     pTable = sqliteMalloc( sizeof(Table) );
   255         -  if( pTable==0 ){
   256         -    sqliteSetString(&pParse->zErrMsg, "out of memory", 0);
   257         -    pParse->nErr++;
   258         -    return;
   259         -  }
          264  +  if( pTable==0 ) return;
   260    265     pTable->zName = zName;
   261    266     pTable->pHash = 0;
   262    267     pTable->nCol = 0;
   263    268     pTable->aCol = 0;
   264    269     pTable->pIndex = 0;
   265    270     if( pParse->pNewTable ) sqliteDeleteTable(pParse->db, pParse->pNewTable);
   266    271     pParse->pNewTable = pTable;
................................................................................
   271    276   */
   272    277   void sqliteAddColumn(Parse *pParse, Token *pName){
   273    278     Table *p;
   274    279     char **pz;
   275    280     if( (p = pParse->pNewTable)==0 ) return;
   276    281     if( (p->nCol & 0x7)==0 ){
   277    282       p->aCol = sqliteRealloc( p->aCol, (p->nCol+8)*sizeof(p->aCol[0]));
   278         -  }
   279         -  if( p->aCol==0 ){
   280         -    p->nCol = 0;
   281         -    return;
          283  +    if( p->aCol==0 ){
          284  +      p->nCol = 0;
          285  +      return;
          286  +    }
   282    287     }
   283    288     memset(&p->aCol[p->nCol], 0, sizeof(p->aCol[0]));
   284    289     pz = &p->aCol[p->nCol++].zName;
   285    290     sqliteSetNString(pz, pName->z, pName->n, 0);
   286    291     sqliteDequote(*pz);
   287    292   }
   288    293   
................................................................................
   319    324   ** We do not want to create it again.
   320    325   */
   321    326   void sqliteEndTable(Parse *pParse, Token *pEnd){
   322    327     Table *p;
   323    328     int h;
   324    329     int addMeta;       /* True to insert a meta records into the file */
   325    330   
   326         -  if( pParse->nErr ) return;
          331  +  if( pEnd==0 || pParse->nErr || sqlite_malloc_failed ) return;
   327    332     p = pParse->pNewTable;
   328         -  addMeta =  p!=0 && pParse->db->nTable==1;
          333  +  if( p==0 ) return;
          334  +  addMeta =  pParse->db->nTable==1;
   329    335   
   330    336     /* Add the table to the in-memory representation of the database
   331    337     */
   332         -  if( p!=0 && pParse->explain==0 ){
          338  +  if( pParse->explain==0 ){
   333    339       h = sqliteHashNoCase(p->zName, 0) % N_HASH;
   334    340       p->pHash = pParse->db->apTblHash[h];
   335    341       pParse->db->apTblHash[h] = p;
   336    342       pParse->pNewTable = 0;
   337    343       pParse->db->nTable++;
   338    344     }
   339    345   
................................................................................
   377    383   }
   378    384   
   379    385   /*
   380    386   ** Given a token, look up a table with that name.  If not found, leave
   381    387   ** an error for the parser to find and return NULL.
   382    388   */
   383    389   Table *sqliteTableFromToken(Parse *pParse, Token *pTok){
   384         -  char *zName = sqliteTableNameFromToken(pTok);
   385         -  Table *pTab = sqliteFindTable(pParse->db, zName);
          390  +  char *zName;
          391  +  Table *pTab;
          392  +  zName = sqliteTableNameFromToken(pTok);
          393  +  if( zName==0 ) return 0;
          394  +  pTab = sqliteFindTable(pParse->db, zName);
   386    395     sqliteFree(zName);
   387    396     if( pTab==0 ){
   388    397       sqliteSetNString(&pParse->zErrMsg, "no such table: ", 0, 
   389    398           pTok->z, pTok->n, 0);
   390    399       pParse->nErr++;
   391    400     }
   392    401     return pTab;
................................................................................
   397    406   */
   398    407   void sqliteDropTable(Parse *pParse, Token *pName){
   399    408     Table *pTable;
   400    409     int h;
   401    410     Vdbe *v;
   402    411     int base;
   403    412   
          413  +  if( pParse->nErr || sqlite_malloc_failed ) return;
   404    414     pTable = sqliteTableFromToken(pParse, pName);
   405    415     if( pTable==0 ) return;
   406    416     if( pTable->readOnly ){
   407    417       sqliteSetString(&pParse->zErrMsg, "table ", pTable->zName, 
   408    418          " may not be dropped", 0);
   409    419       pParse->nErr++;
   410    420       return;
................................................................................
   482    492   ){
   483    493     Table *pTab;     /* Table to be indexed */
   484    494     Index *pIndex;   /* The index to be created */
   485    495     char *zName = 0;
   486    496     int i, j, h;
   487    497     Token nullId;    /* Fake token for an empty ID list */
   488    498   
          499  +  if( pParse->nErr || sqlite_malloc_failed ) goto exit_create_index;
          500  +
   489    501     /*
   490    502     ** Find the table that is to be indexed.  Return early if not found.
   491    503     */
   492    504     if( pTable!=0 ){
   493    505       pTab =  sqliteTableFromToken(pParse, pTable);
   494    506     }else{
   495    507       pTab =  pParse->pNewTable;
................................................................................
   508    520     */
   509    521     if( pName ){
   510    522       zName = sqliteTableNameFromToken(pName);
   511    523     }else{
   512    524       zName = 0;
   513    525       sqliteSetString(&zName, pTab->zName, "__primary_key", 0);
   514    526     }
          527  +  if( zName==0 ) goto exit_create_index;
   515    528     if( sqliteFindIndex(pParse->db, zName) ){
   516    529       sqliteSetString(&pParse->zErrMsg, "index ", zName, 
   517    530          " already exists", 0);
   518    531       pParse->nErr++;
   519    532       goto exit_create_index;
   520    533     }
   521    534     if( sqliteFindTable(pParse->db, zName) ){
................................................................................
   537    550     }
   538    551   
   539    552     /* 
   540    553     ** Allocate the index structure. 
   541    554     */
   542    555     pIndex = sqliteMalloc( sizeof(Index) + strlen(zName) + 1 +
   543    556                           sizeof(int)*pList->nId );
   544         -  if( pIndex==0 ){
   545         -    sqliteSetString(&pParse->zErrMsg, "out of memory", 0);
   546         -    pParse->nErr++;
   547         -    goto exit_create_index;
   548         -  }
          557  +  if( pIndex==0 ) goto exit_create_index;
   549    558     pIndex->aiColumn = (int*)&pIndex[1];
   550    559     pIndex->zName = (char*)&pIndex->aiColumn[pList->nId];
   551    560     strcpy(pIndex->zName, zName);
   552    561     pIndex->pTable = pTab;
   553    562     pIndex->nColumn = pList->nId;
   554    563   
   555    564     /* Scan the names of the columns of the table to be indexed and
................................................................................
   652    661   ** This routine will drop an existing named index.
   653    662   */
   654    663   void sqliteDropIndex(Parse *pParse, Token *pName){
   655    664     Index *pIndex;
   656    665     char *zName;
   657    666     Vdbe *v;
   658    667   
          668  +  if( pParse->nErr || sqlite_malloc_failed ) return;
   659    669     zName = sqliteTableNameFromToken(pName);
          670  +  if( zName==0 ) return;
   660    671     pIndex = sqliteFindIndex(pParse->db, zName);
   661    672     sqliteFree(zName);
   662    673     if( pIndex==0 ){
   663    674       sqliteSetNString(&pParse->zErrMsg, "no such index: ", 0, 
   664    675           pName->z, pName->n, 0);
   665    676       pParse->nErr++;
   666    677       return;
................................................................................
   710    721   ** Add a new element to the end of an expression list.  If pList is
   711    722   ** initially NULL, then create a new expression list.
   712    723   */
   713    724   ExprList *sqliteExprListAppend(ExprList *pList, Expr *pExpr, Token *pName){
   714    725     int i;
   715    726     if( pList==0 ){
   716    727       pList = sqliteMalloc( sizeof(ExprList) );
          728  +    if( pList==0 ) return 0;
   717    729     }
   718         -  if( pList==0 ) return 0;
   719    730     if( (pList->nExpr & 7)==0 ){
   720    731       int n = pList->nExpr + 8;
   721    732       pList->a = sqliteRealloc(pList->a, n*sizeof(pList->a[0]));
   722    733       if( pList->a==0 ){
   723    734         pList->nExpr = 0;
   724    735         return pList;
   725    736       }
................................................................................
   747    758     sqliteFree(pList->a);
   748    759     sqliteFree(pList);
   749    760   }
   750    761   
   751    762   /*
   752    763   ** Append a new element to the given IdList.  Create a new IdList if
   753    764   ** need be.
          765  +**
          766  +** A new IdList is returned, or NULL if malloc() fails.
   754    767   */
   755    768   IdList *sqliteIdListAppend(IdList *pList, Token *pToken){
   756    769     if( pList==0 ){
   757    770       pList = sqliteMalloc( sizeof(IdList) );
   758    771       if( pList==0 ) return 0;
   759    772     }
   760    773     if( (pList->nId & 7)==0 ){
   761    774       pList->a = sqliteRealloc(pList->a, (pList->nId+8)*sizeof(pList->a[0]) );
   762    775       if( pList->a==0 ){
   763    776         pList->nId = 0;
   764         -      return pList;
          777  +      sqliteIdListDelete(pList);
          778  +      return 0;
   765    779       }
   766    780     }
   767    781     memset(&pList->a[pList->nId], 0, sizeof(pList->a[0]));
   768    782     if( pToken ){
   769         -    sqliteSetNString(&pList->a[pList->nId].zName, pToken->z, pToken->n, 0);
   770         -    sqliteDequote(pList->a[pList->nId].zName);
          783  +    char **pz = &pList->a[pList->nId].zName;
          784  +    sqliteSetNString(pz, pToken->z, pToken->n, 0);
          785  +    if( *pz==0 ){
          786  +      sqliteIdListDelete(pList);
          787  +      return 0;
          788  +    }else{
          789  +      sqliteDequote(*pz);
          790  +    }
   771    791     }
   772    792     pList->nId++;
   773    793     return pList;
   774    794   }
   775    795   
   776    796   /*
   777    797   ** Add an alias to the last identifier on the given identifier list.
................................................................................
   789    809   */
   790    810   void sqliteIdListDelete(IdList *pList){
   791    811     int i;
   792    812     if( pList==0 ) return;
   793    813     for(i=0; i<pList->nId; i++){
   794    814       sqliteFree(pList->a[i].zName);
   795    815       sqliteFree(pList->a[i].zAlias);
          816  +    if( pList->a[i].pSelect ){
          817  +      sqliteFree(pList->a[i].zName);
          818  +      sqliteSelectDelete(pList->a[i].pSelect);
          819  +      sqliteDeleteTable(0, pList->a[i].pTab);
          820  +    }
   796    821     }
   797    822     sqliteFree(pList->a);
   798    823     sqliteFree(pList);
   799    824   }
   800    825   
   801    826   
   802    827   /*
................................................................................
   820    845     char *zTab;
   821    846     int i, j;
   822    847     Vdbe *v;
   823    848     int addr, end;
   824    849     Index *pIdx;
   825    850   
   826    851     zTab = sqliteTableNameFromToken(pTableName);
          852  +  if( sqlite_malloc_failed || zTab==0 ) goto copy_cleanup;
   827    853     pTab = sqliteFindTable(pParse->db, zTab);
   828    854     sqliteFree(zTab);
   829    855     if( pTab==0 ){
   830    856       sqliteSetNString(&pParse->zErrMsg, "no such table: ", 0, 
   831    857           pTableName->z, pTableName->n, 0);
   832    858       pParse->nErr++;
   833    859       goto copy_cleanup;
................................................................................
   887    913   ** collapse free space, etc.  It is modelled after the VACUUM command
   888    914   ** in PostgreSQL.
   889    915   */
   890    916   void sqliteVacuum(Parse *pParse, Token *pTableName){
   891    917     char *zName;
   892    918     Vdbe *v;
   893    919   
          920  +  if( pParse->nErr || sqlite_malloc_failed ) return;
   894    921     if( pTableName ){
   895    922       zName = sqliteTableNameFromToken(pTableName);
   896    923     }else{
   897    924       zName = 0;
   898    925     }
   899    926     if( zName && sqliteFindIndex(pParse->db, zName)==0
   900    927       && sqliteFindTable(pParse->db, zName)==0 ){
................................................................................
   929    956   ** Begin a transaction
   930    957   */
   931    958   void sqliteBeginTransaction(Parse *pParse){
   932    959     int rc;
   933    960     DbbeMethods *pM;
   934    961     sqlite *db;
   935    962     if( pParse==0 || (db=pParse->db)==0 || db->pBe==0 ) return;
          963  +  if( pParse->nErr || sqlite_malloc_failed ) return;
   936    964     if( db->flags & SQLITE_InTrans ) return;
   937    965     pM = pParse->db->pBe->x;
   938    966     if( pM && pM->BeginTransaction ){
   939    967       rc = (*pM->BeginTransaction)(pParse->db->pBe);
   940    968     }else{
   941    969       rc = SQLITE_OK;
   942    970     }
................................................................................
   949    977   ** Commit a transaction
   950    978   */
   951    979   void sqliteCommitTransaction(Parse *pParse){
   952    980     int rc;
   953    981     DbbeMethods *pM;
   954    982     sqlite *db;
   955    983     if( pParse==0 || (db=pParse->db)==0 || db->pBe==0 ) return;
          984  +  if( pParse->nErr || sqlite_malloc_failed ) return;
   956    985     if( (db->flags & SQLITE_InTrans)==0 ) return;
   957    986     pM = pParse->db->pBe->x;
   958    987     if( pM && pM->Commit ){
   959    988       rc = (*pM->Commit)(pParse->db->pBe);
   960    989     }else{
   961    990       rc = SQLITE_OK;
   962    991     }
................................................................................
   969    998   ** Rollback a transaction
   970    999   */
   971   1000   void sqliteRollbackTransaction(Parse *pParse){
   972   1001     int rc;
   973   1002     DbbeMethods *pM;
   974   1003     sqlite *db;
   975   1004     if( pParse==0 || (db=pParse->db)==0 || db->pBe==0 ) return;
         1005  +  if( pParse->nErr || sqlite_malloc_failed ) return;
   976   1006     if( (db->flags & SQLITE_InTrans)==0 ) return;
   977   1007     pM = pParse->db->pBe->x;
   978   1008     if( pM && pM->Rollback ){
   979   1009       rc = (*pM->Rollback)(pParse->db->pBe);
   980   1010     }else{
   981   1011       rc = SQLITE_OK;
   982   1012     }
   983   1013     if( rc==SQLITE_OK ){
   984   1014       db->flags &= ~SQLITE_InTrans;
   985   1015     }
   986   1016   }

Changes to src/dbbe.c.

    26     26   ** sqlite and the code that does the actually reading and writing
    27     27   ** of information to the disk.
    28     28   **
    29     29   ** This file uses GDBM as the database backend.  It should be
    30     30   ** relatively simple to convert to a different database such
    31     31   ** as NDBM, SDBM, or BerkeleyDB.
    32     32   **
    33         -** $Id: dbbe.c,v 1.26 2001/04/04 21:22:14 drh Exp $
           33  +** $Id: dbbe.c,v 1.27 2001/04/11 14:28:42 drh Exp $
    34     34   */
    35     35   #include "sqliteInt.h"
    36     36   #include <unistd.h>
    37     37   #include <ctype.h>
    38     38   
    39     39   /*
    40     40   ** This routine opens a new database.  It looks at the first
................................................................................
    61     61     if( strncmp(zName, "memory:", 7)==0 ){
    62     62       extern Dbbe *sqliteMemOpen(const char*,int,int,char**);
    63     63       return sqliteMemOpen(&zName[7], writeFlag, createFlag, pzErrMsg);
    64     64     }
    65     65     return sqliteGdbmOpen(zName, writeFlag, createFlag, pzErrMsg);
    66     66   }
    67     67   
           68  +#if 0  /* NOT USED */
    68     69   /*
    69     70   ** Translate the name of an SQL table (or index) into the name 
    70     71   ** of a file that holds the key/data pairs for that table or
    71     72   ** index.  Space to hold the filename is obtained from
    72     73   ** sqliteMalloc() and must be freed by the calling function.
    73     74   **
    74     75   ** zDir is the name of the directory in which the file should
................................................................................
   111    112     }
   112    113     for(k=0; (c = zSuffix[k])!=0; k++){
   113    114       zFile[i++] = c;
   114    115     }
   115    116     zFile[i] = 0;
   116    117     return zFile;
   117    118   }
          119  +#endif /* NOT USED */

Changes to src/dbbegdbm.c.

    26     26   ** sqlite and the code that does the actually reading and writing
    27     27   ** of information to the disk.
    28     28   **
    29     29   ** This file uses GDBM as the database backend.  It should be
    30     30   ** relatively simple to convert to a different database such
    31     31   ** as NDBM, SDBM, or BerkeleyDB.
    32     32   **
    33         -** $Id: dbbegdbm.c,v 1.6 2001/04/04 11:48:57 drh Exp $
           33  +** $Id: dbbegdbm.c,v 1.7 2001/04/11 14:28:42 drh Exp $
    34     34   */
    35     35   #include "sqliteInt.h"
    36     36   #include <gdbm.h>
    37     37   #include <sys/stat.h>
    38     38   #include <unistd.h>
    39     39   #include <ctype.h>
    40     40   #include <time.h>
................................................................................
   181    181   
   182    182     if( pBe->inTrans ) writeable = 1;
   183    183     *ppCursr = 0;
   184    184     pCursr = sqliteMalloc( sizeof(*pCursr) );
   185    185     if( pCursr==0 ) return SQLITE_NOMEM;
   186    186     if( zTable ){
   187    187       zFile = sqliteFileOfTable(pBe, zTable);
          188  +    if( zFile==0 ) return SQLITE_NOMEM;
   188    189       for(pFile=pBe->pOpen; pFile; pFile=pFile->pNext){
   189    190         if( strcmp(pFile->zName,zFile)==0 ) break;
   190    191       }
   191    192     }else{
   192    193       pFile = 0;
   193    194       zFile = 0;
   194    195     }

Changes to src/dbbemem.c.

    26     26   ** sqlite and the code that does the actually reading and writing
    27     27   ** of information to the disk.
    28     28   **
    29     29   ** This file uses an in-memory hash table as the database backend. 
    30     30   ** Nothing is ever written to disk using this backend.  All information
    31     31   ** is forgotten when the program exits.
    32     32   **
    33         -** $Id: dbbemem.c,v 1.13 2001/04/04 11:48:58 drh Exp $
           33  +** $Id: dbbemem.c,v 1.14 2001/04/11 14:28:42 drh Exp $
    34     34   */
    35     35   #include "sqliteInt.h"
    36     36   #include <sys/stat.h>
    37     37   #include <unistd.h>
    38     38   #include <ctype.h>
    39     39   #include <time.h>
    40     40   
................................................................................
   152    152   static void ArrayRehash(Array *array, int new_size){
   153    153     struct _Array_ht *new_ht;       /* The new hash table */
   154    154     ArrayElem *elem, *next_elem;    /* For looping over existing elements */
   155    155     int i;                          /* Loop counter */
   156    156     ArrayElem *x;                   /* Element being copied to new hash table */
   157    157   
   158    158     new_ht = sqliteMalloc( new_size*sizeof(struct _Array_ht) );
          159  +  if( new_ht==0 ){ ArrayClear(array); return; }
   159    160     if( array->ht ) sqliteFree(array->ht);
   160    161     array->ht = new_ht;
   161    162     array->htsize = new_size;
   162    163     for(i=new_size-1; i>=0; i--){ 
   163    164       new_ht[i].count = 0;
   164    165       new_ht[i].chain = 0;
   165    166     }
................................................................................
   301    302     new_elem = (ArrayElem*)sqliteMalloc( sizeof(ArrayElem) + key.n );
   302    303     if( new_elem==0 ) return nil;
   303    304     new_elem->key.n = key.n;
   304    305     new_elem->key.p = (void*)&new_elem[1];
   305    306     memcpy(new_elem->key.p, key.p, key.n);
   306    307     array->count++;
   307    308     if( array->htsize==0 ) ArrayRehash(array,4);
          309  +  if( array->htsize==0 ) return nil;
   308    310     if( array->count > array->htsize ){
   309    311       ArrayRehash(array,array->htsize*2);
          312  +    if( array->htsize==0 ){
          313  +      sqliteFree(new_elem);
          314  +      return nil;
          315  +    }
   310    316     }
   311    317     h = hraw & (array->htsize-1);
   312    318     elem = array->ht[h].chain;
   313    319     if( elem ){
   314    320       new_elem->next = elem;
   315    321       new_elem->prev = elem->prev;
   316    322       if( elem->prev ){ elem->prev->next = new_elem; }
................................................................................
   464    470   
   465    471     *ppCursr = 0;
   466    472     pCursr = sqliteMalloc( sizeof(*pCursr) );
   467    473     if( pCursr==0 ) return SQLITE_NOMEM;
   468    474     if( zTable ){
   469    475       Datum key;
   470    476       zName = sqliteNameOfTable(zTable);
          477  +    if( zName==0 ) return SQLITE_NOMEM;
   471    478       key.p = zName;
   472    479       key.n = strlen(zName);
   473    480       pTble = ArrayFind(&pBe->tables, key).p;
   474    481     }else{
   475    482       zName = 0;
   476    483       pTble = 0;
   477    484     }
................................................................................
   686    693     DbbeCursor *pCursr,       /* Write new entry into this database table */
   687    694     int nKey, char *pKey,     /* The key of the new entry */
   688    695     int nData, char *pData    /* The data of the new entry */
   689    696   ){
   690    697     Datum data, key;
   691    698     data.n = nData;
   692    699     data.p = sqliteMalloc( data.n );
          700  +  if( data.p==0 ) return SQLITE_NOMEM;
   693    701     memcpy(data.p, pData, data.n);
   694    702     key.n = nKey;
   695    703     key.p = pKey;
   696    704     assert( nKey==4 || pCursr->pTble->intKeyOnly==0 );
   697    705     data = ArrayInsert(&pCursr->pTble->data, key, data);
   698    706     if( data.p ){
   699    707       sqliteFree(data.p);

Changes to src/delete.c.

    20     20   **   drh@hwaci.com
    21     21   **   http://www.hwaci.com/drh/
    22     22   **
    23     23   *************************************************************************
    24     24   ** This file contains C code routines that are called by the parser
    25     25   ** to handle DELETE FROM statements.
    26     26   **
    27         -** $Id: delete.c,v 1.8 2001/03/20 22:05:00 drh Exp $
           27  +** $Id: delete.c,v 1.9 2001/04/11 14:28:42 drh Exp $
    28     28   */
    29     29   #include "sqliteInt.h"
    30     30   
    31     31   /*
    32     32   ** Process a DELETE FROM statement.
    33     33   */
    34     34   void sqliteDeleteFrom(
................................................................................
    40     40     Table *pTab;           /* The table from which records will be deleted */
    41     41     IdList *pTabList;      /* An ID list holding pTab and nothing else */
    42     42     int end, addr;         /* A couple addresses of generated code */
    43     43     int i;                 /* Loop counter */
    44     44     WhereInfo *pWInfo;     /* Information about the WHERE clause */
    45     45     Index *pIdx;           /* For looping over indices of the table */
    46     46     int base;              /* Index of the first available table cursor */
           47  +
           48  +  if( pParse->nErr || sqlite_malloc_failed ){
           49  +    pTabList = 0;
           50  +    goto delete_from_cleanup;
           51  +  }
    47     52   
    48     53     /* Locate the table which we want to delete.  This table has to be
    49     54     ** put in an IdList structure because some of the subroutines we
    50     55     ** will be calling are designed to work with multiple tables and expect
    51     56     ** an IdList* parameter instead of just a Table* parameger.
    52     57     */
    53     58     pTabList = sqliteIdListAppend(0, pTableName);
           59  +  if( pTabList==0 ) goto delete_from_cleanup;
    54     60     for(i=0; i<pTabList->nId; i++){
    55     61       pTabList->a[i].pTab = sqliteFindTable(pParse->db, pTabList->a[i].zName);
    56     62       if( pTabList->a[i].pTab==0 ){
    57     63         sqliteSetString(&pParse->zErrMsg, "no such table: ", 
    58     64            pTabList->a[i].zName, 0);
    59     65         pParse->nErr++;
    60     66         goto delete_from_cleanup;

Changes to src/expr.c.

    20     20   **   drh@hwaci.com
    21     21   **   http://www.hwaci.com/drh/
    22     22   **
    23     23   *************************************************************************
    24     24   ** This file contains routines used for analyzing expressions and
    25     25   ** for generating VDBE code that evaluates expressions.
    26     26   **
    27         -** $Id: expr.c,v 1.23 2001/04/04 21:22:14 drh Exp $
           27  +** $Id: expr.c,v 1.24 2001/04/11 14:28:42 drh Exp $
    28     28   */
    29     29   #include "sqliteInt.h"
    30     30   
    31     31   /*
    32     32   ** Walk an expression tree.  Return 1 if the expression is constant
    33     33   ** and 0 if it involves variables.
    34     34   */
................................................................................
   119    119   ** If it finds any, it generates code to write the value of that select
   120    120   ** into a memory cell.
   121    121   **
   122    122   ** Unknown columns or tables provoke an error.  The function returns
   123    123   ** the number of errors seen and leaves an error message on pParse->zErrMsg.
   124    124   */
   125    125   int sqliteExprResolveIds(Parse *pParse, IdList *pTabList, Expr *pExpr){
   126         -  if( pExpr==0 ) return 0;
          126  +  if( pExpr==0 || pTabList==0 ) return 0;
   127    127     switch( pExpr->op ){
   128    128       /* A lone identifier */
   129    129       case TK_ID: {
   130    130         int cnt = 0;      /* Number of matches */
   131    131         int i;            /* Loop counter */
   132    132         char *z = sqliteStrNDup(pExpr->token.z, pExpr->token.n);
          133  +      if( z==0 ) return 1;
   133    134         for(i=0; i<pTabList->nId; i++){
   134    135           int j;
   135    136           Table *pTab = pTabList->a[i].pTab;
   136    137           if( pTab==0 ) continue;
   137    138           for(j=0; j<pTab->nCol; j++){
   138    139             if( sqliteStrICmp(pTab->aCol[j].zName, z)==0 ){
   139    140               cnt++;
................................................................................
   173    174   
   174    175         pLeft = pExpr->pLeft;
   175    176         pRight = pExpr->pRight;
   176    177         assert( pLeft && pLeft->op==TK_ID );
   177    178         assert( pRight && pRight->op==TK_ID );
   178    179         zLeft = sqliteStrNDup(pLeft->token.z, pLeft->token.n);
   179    180         zRight = sqliteStrNDup(pRight->token.z, pRight->token.n);
          181  +      if( zLeft==0 || zRight==0 ){
          182  +        sqliteFree(zLeft);
          183  +        sqliteFree(zRight);
          184  +        return 1;
          185  +      }
   180    186         pExpr->iTable = -1;
   181    187         for(i=0; i<pTabList->nId; i++){
   182    188           int j;
   183    189           char *zTab;
   184    190           Table *pTab = pTabList->a[i].pTab;
   185    191           if( pTab==0 ) continue;
   186    192           if( pTabList->a[i].zAlias ){
................................................................................
   476    482   /*
   477    483   ** Generate code into the current Vdbe to evaluate the given
   478    484   ** expression and leave the result on the top of stack.
   479    485   */
   480    486   void sqliteExprCode(Parse *pParse, Expr *pExpr){
   481    487     Vdbe *v = pParse->pVdbe;
   482    488     int op;
          489  +  if( v==0 || pExpr==0 ) return;
   483    490     switch( pExpr->op ){
   484    491       case TK_PLUS:     op = OP_Add;      break;
   485    492       case TK_MINUS:    op = OP_Subtract; break;
   486    493       case TK_STAR:     op = OP_Multiply; break;
   487    494       case TK_SLASH:    op = OP_Divide;   break;
   488    495       case TK_AND:      op = OP_And;      break;
   489    496       case TK_OR:       op = OP_Or;       break;
................................................................................
   679    686   ** Generate code for a boolean expression such that a jump is made
   680    687   ** to the label "dest" if the expression is true but execution
   681    688   ** continues straight thru if the expression is false.
   682    689   */
   683    690   void sqliteExprIfTrue(Parse *pParse, Expr *pExpr, int dest){
   684    691     Vdbe *v = pParse->pVdbe;
   685    692     int op = 0;
          693  +  if( v==0 || pExpr==0 ) return;
   686    694     switch( pExpr->op ){
   687    695       case TK_LT:       op = OP_Lt;       break;
   688    696       case TK_LE:       op = OP_Le;       break;
   689    697       case TK_GT:       op = OP_Gt;       break;
   690    698       case TK_GE:       op = OP_Ge;       break;
   691    699       case TK_NE:       op = OP_Ne;       break;
   692    700       case TK_EQ:       op = OP_Eq;       break;
................................................................................
   765    773   ** Generate code for a boolean expression such that a jump is made
   766    774   ** to the label "dest" if the expression is false but execution
   767    775   ** continues straight thru if the expression is true.
   768    776   */
   769    777   void sqliteExprIfFalse(Parse *pParse, Expr *pExpr, int dest){
   770    778     Vdbe *v = pParse->pVdbe;
   771    779     int op = 0;
          780  +  if( v==0 || pExpr==0 ) return;
   772    781     switch( pExpr->op ){
   773    782       case TK_LT:       op = OP_Ge;       break;
   774    783       case TK_LE:       op = OP_Gt;       break;
   775    784       case TK_GT:       op = OP_Le;       break;
   776    785       case TK_GE:       op = OP_Lt;       break;
   777    786       case TK_NE:       op = OP_Eq;       break;
   778    787       case TK_EQ:       op = OP_Ne;       break;
................................................................................
   892    901   ** Add a new element to the pParse->aAgg[] array and return its index.
   893    902   */
   894    903   static int appendAggInfo(Parse *pParse){
   895    904     if( (pParse->nAgg & 0x7)==0 ){
   896    905       int amt = pParse->nAgg + 8;
   897    906       pParse->aAgg = sqliteRealloc(pParse->aAgg, amt*sizeof(pParse->aAgg[0]));
   898    907       if( pParse->aAgg==0 ){
   899         -      sqliteSetString(&pParse->zErrMsg, "out of memory", 0);
   900         -      pParse->nErr++;
          908  +      pParse->nAgg = 0;
   901    909         return -1;
   902    910       }
   903    911     }
   904    912     memset(&pParse->aAgg[pParse->nAgg], 0, sizeof(pParse->aAgg[0]));
   905    913     return pParse->nAgg++;
   906    914   }
   907    915   

Changes to src/insert.c.

    20     20   **   drh@hwaci.com
    21     21   **   http://www.hwaci.com/drh/
    22     22   **
    23     23   *************************************************************************
    24     24   ** This file contains C code routines that are called by the parser
    25     25   ** to handle INSERT statements.
    26     26   **
    27         -** $Id: insert.c,v 1.12 2001/01/15 22:51:11 drh Exp $
           27  +** $Id: insert.c,v 1.13 2001/04/11 14:28:42 drh Exp $
    28     28   */
    29     29   #include "sqliteInt.h"
    30     30   
    31     31   /*
    32     32   ** This routine is call to handle SQL of the following forms:
    33     33   **
    34     34   **    insert into TABLE (IDLIST) values(EXPRLIST)
................................................................................
    55     55     int i, j, idx;        /* Loop counters */
    56     56     Vdbe *v;              /* Generate code into this virtual machine */
    57     57     Index *pIdx;          /* For looping over indices of the table */
    58     58     int srcTab;           /* Date comes from this temporary cursor if >=0 */
    59     59     int nColumn;          /* Number of columns in the data */
    60     60     int base;             /* First available cursor */
    61     61     int iCont, iBreak;    /* Beginning and end of the loop over srcTab */
           62  +
           63  +  if( pParse->nErr || sqlite_malloc_failed ) goto insert_cleanup;
    62     64   
    63     65     /* Locate the table into which we will be inserting new information.
    64     66     */
    65     67     zTab = sqliteTableNameFromToken(pTableName);
           68  +  if( zTab==0 ) goto insert_cleanup;
    66     69     pTab = sqliteFindTable(pParse->db, zTab);
    67     70     sqliteFree(zTab);
    68     71     if( pTab==0 ){
    69     72       sqliteSetNString(&pParse->zErrMsg, "no such table: ", 0, 
    70     73           pTableName->z, pTableName->n, 0);
    71     74       pParse->nErr++;
    72     75       goto insert_cleanup;
................................................................................
    90     93     ** then we just have to count the number of expressions.
    91     94     */
    92     95     if( pSelect ){
    93     96       int rc;
    94     97       srcTab = pParse->nTab++;
    95     98       sqliteVdbeAddOp(v, OP_OpenTbl, srcTab, 1, 0, 0);
    96     99       rc = sqliteSelect(pParse, pSelect, SRT_Table, srcTab);
    97         -    if( rc ) goto insert_cleanup;
          100  +    if( rc || pParse->nErr || sqlite_malloc_failed ) goto insert_cleanup;
    98    101       assert( pSelect->pEList );
    99    102       nColumn = pSelect->pEList->nExpr;
   100    103     }else{
          104  +    assert( pList!=0 );
   101    105       srcTab = -1;
   102    106       assert( pList );
   103    107       nColumn = pList->nExpr;
   104    108     }
   105    109   
   106    110     /* Make sure the number of columns in the source data matches the number
   107    111     ** of columns to be inserted into the table.

Changes to src/main.c.

    22     22   **
    23     23   *************************************************************************
    24     24   ** Main file for the SQLite library.  The routines in this file
    25     25   ** implement the programmer interface to the library.  Routines in
    26     26   ** other files are for internal use by SQLite and should not be
    27     27   ** accessed by users of the library.
    28     28   **
    29         -** $Id: main.c,v 1.27 2001/04/06 16:13:43 drh Exp $
           29  +** $Id: main.c,v 1.28 2001/04/11 14:28:42 drh Exp $
    30     30   */
    31     31   #include "sqliteInt.h"
    32     32   #include <unistd.h>
    33     33   
    34     34   /*
    35     35   ** This is the callback routine for the code that initializes the
    36     36   ** database.  Each callback contains text of a CREATE TABLE or
................................................................................
   153    153     };
   154    154   
   155    155     /* Create a virtual machine to run the initialization program.  Run
   156    156     ** the program.  The delete the virtual machine.
   157    157     */
   158    158     vdbe = sqliteVdbeCreate(db);
   159    159     if( vdbe==0 ){
   160         -    sqliteSetString(pzErrMsg, "out of memory",0); 
   161         -    return 1;
          160  +    sqliteSetString(pzErrMsg, "out of memory");
          161  +    return SQLITE_NOMEM;
   162    162     }
   163    163     sqliteVdbeAddOpList(vdbe, sizeof(initProg)/sizeof(initProg[0]), initProg);
   164    164     rc = sqliteVdbeExec(vdbe, sqliteOpenCb, db, pzErrMsg, 
   165    165                         db->pBusyArg, db->xBusyCallback);
   166    166     sqliteVdbeDelete(vdbe);
   167    167     if( rc==SQLITE_OK && db->file_format<2 && db->nTable>0 ){
   168    168       sqliteSetString(pzErrMsg, "obsolete file format", 0);
................................................................................
   175    175       azArg[1] = 0;
   176    176       sqliteOpenCb(db, 1, azArg, 0);
   177    177       pTab = sqliteFindTable(db, MASTER_NAME);
   178    178       if( pTab ){
   179    179         pTab->readOnly = 1;
   180    180       }
   181    181       db->flags |= SQLITE_Initialized;
   182         -  }else{
   183         -    sqliteStrRealloc(pzErrMsg);
   184    182     }
   185    183     return rc;
   186    184   }
   187    185   
   188    186   /*
   189    187   ** The version of the library
   190    188   */
................................................................................
   212    210   sqlite *sqlite_open(const char *zFilename, int mode, char **pzErrMsg){
   213    211     sqlite *db;
   214    212     int rc;
   215    213   
   216    214     /* Allocate the sqlite data structure */
   217    215     db = sqliteMalloc( sizeof(sqlite) );
   218    216     if( pzErrMsg ) *pzErrMsg = 0;
   219         -  if( db==0 ){
   220         -    sqliteSetString(pzErrMsg, "out of memory", 0);
   221         -    sqliteStrRealloc(pzErrMsg);
   222         -    return 0;
   223         -  }
          217  +  if( db==0 ) goto no_mem_on_open;
   224    218     
   225    219     /* Open the backend database driver */
   226    220     db->pBe = sqliteDbbeOpen(zFilename, (mode&0222)!=0, mode!=0, pzErrMsg);
   227    221     if( db->pBe==0 ){
   228         -    sqliteStrRealloc(pzErrMsg);
   229    222       sqliteFree(db);
          223  +    sqliteStrRealloc(pzErrMsg);
   230    224       return 0;
   231    225     }
   232    226   
   233    227     /* Assume file format 1 unless the database says otherwise */
   234    228     db->file_format = 1;
   235    229   
   236    230     /* Attempt to read the schema */
   237    231     rc = sqliteInit(db, pzErrMsg);
   238         -  if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
          232  +  if( sqlite_malloc_failed ){
          233  +    goto no_mem_on_open;
          234  +  }else if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
   239    235       sqlite_close(db);
   240    236       return 0;
   241    237     }else /* if( pzErrMsg ) */{
   242         -    free(*pzErrMsg);
          238  +    sqliteFree(*pzErrMsg);
   243    239       *pzErrMsg = 0;
   244    240     }
   245    241     return db;
          242  +
          243  +no_mem_on_open:
          244  +  sqliteSetString(pzErrMsg, "out of memory", 0);
          245  +  sqliteStrRealloc(pzErrMsg);
          246  +  return 0;
   246    247   }
   247    248   
   248    249   /*
   249    250   ** Close an existing SQLite database
   250    251   */
   251    252   void sqlite_close(sqlite *db){
   252    253     int i;
................................................................................
   332    333     char **pzErrMsg             /* Write error messages here */
   333    334   ){
   334    335     Parse sParse;
   335    336   
   336    337     if( pzErrMsg ) *pzErrMsg = 0;
   337    338     if( (db->flags & SQLITE_Initialized)==0 ){
   338    339       int rc = sqliteInit(db, pzErrMsg);
   339         -    if( rc!=SQLITE_OK ) return rc;
          340  +    if( rc!=SQLITE_OK ){
          341  +      sqliteStrRealloc(pzErrMsg);
          342  +      return rc;
          343  +    }
   340    344     }
   341    345     memset(&sParse, 0, sizeof(sParse));
   342    346     sParse.db = db;
   343    347     sParse.xCallback = xCallback;
   344    348     sParse.pArg = pArg;
   345    349     sqliteRunParser(&sParse, zSql, pzErrMsg);
          350  +  if( sqlite_malloc_failed ){
          351  +    sqliteSetString(pzErrMsg, "out of memory", 0);
          352  +    sParse.rc = SQLITE_NOMEM;
          353  +  }
          354  +  sqliteStrRealloc(pzErrMsg);
   346    355     return sParse.rc;
   347    356   }
   348    357   
   349    358   /*
   350    359   ** This routine implements a busy callback that sleeps and tries
   351    360   ** again until a timeout value is reached.  The timeout value is
   352    361   ** an integer number of milliseconds passed in as the first
   353    362   ** argument.
   354    363   */
   355         -static int sqlite_default_busy_callback(
          364  +static int sqliteDefaultBusyCallback(
   356    365    void *Timeout,           /* Maximum amount of time to wait */
   357    366    const char *NotUsed,     /* The name of the table that is busy */
   358    367    int count                /* Number of times table has been busy */
   359    368   ){
   360    369   #if defined(HAVE_USLEEP) && HAVE_USLEEP
   361    370     int delay = 10000;
   362    371     int prior_delay = 0;
................................................................................
   403    412   
   404    413   /*
   405    414   ** This routine installs a default busy handler that waits for the
   406    415   ** specified number of milliseconds before returning 0.
   407    416   */
   408    417   void sqlite_busy_timeout(sqlite *db, int ms){
   409    418     if( ms>0 ){
   410         -    sqlite_busy_handler(db, sqlite_default_busy_callback, (void*)ms);
          419  +    sqlite_busy_handler(db, sqliteDefaultBusyCallback, (void*)ms);
   411    420     }else{
   412    421       sqlite_busy_handler(db, 0, 0);
   413    422     }
   414    423   }
   415    424   
   416    425   /*
   417    426   ** Cause any pending operation to stop at its earliest opportunity.
   418    427   */
   419    428   void sqlite_interrupt(sqlite *db){
   420    429     db->flags |= SQLITE_Interrupt;
   421    430   }

Changes to src/parse.y.

    22     22   **
    23     23   *************************************************************************
    24     24   ** This file contains SQLite's grammar for SQL.  Process this file
    25     25   ** using the lemon parser generator to generate C code that runs
    26     26   ** the parser.  Lemon will also generate a header file containing
    27     27   ** numeric codes for all of the tokens.
    28     28   **
    29         -** @(#) $Id: parse.y,v 1.27 2001/04/04 11:48:58 drh Exp $
           29  +** @(#) $Id: parse.y,v 1.28 2001/04/11 14:28:42 drh Exp $
    30     30   */
    31     31   %token_prefix TK_
    32     32   %token_type {Token}
    33     33   %extra_argument {Parse *pParse}
    34     34   %syntax_error {
    35     35     sqliteSetString(&pParse->zErrMsg,"syntax error",0);
    36     36     pParse->sErrToken = TOKEN;
................................................................................
   166    166   %type select {Select*}
   167    167   %destructor select {sqliteSelectDelete($$);}
   168    168   %type oneselect {Select*}
   169    169   %destructor oneselect {sqliteSelectDelete($$);}
   170    170   
   171    171   select(A) ::= oneselect(X).                      {A = X;}
   172    172   select(A) ::= select(X) joinop(Y) oneselect(Z).  {
          173  +  if( Z ){
   173    174       Z->op = Y;
   174    175       Z->pPrior = X;
   175         -    A = Z;
          176  +  }
          177  +  A = Z;
   176    178   }
   177    179   %type joinop {int}
   178    180   joinop(A) ::= UNION.      {A = TK_UNION;}
   179    181   joinop(A) ::= UNION ALL.  {A = TK_ALL;}
   180    182   joinop(A) ::= INTERSECT.  {A = TK_INTERSECT;}
   181    183   joinop(A) ::= EXCEPT.     {A = TK_EXCEPT;}
   182    184   oneselect(A) ::= SELECT distinct(D) selcollist(W) from(X) where_opt(Y)
................................................................................
   232    234   %type sortitem {Expr*}
   233    235   %destructor sortitem {sqliteExprDelete($$);}
   234    236   
   235    237   orderby_opt(A) ::= .                          {A = 0;}
   236    238   orderby_opt(A) ::= ORDER BY sortlist(X).      {A = X;}
   237    239   sortlist(A) ::= sortlist(X) COMMA sortitem(Y) sortorder(Z). {
   238    240     A = sqliteExprListAppend(X,Y,0);
   239         -  A->a[A->nExpr-1].sortOrder = Z;   /* 0 for ascending order, 1 for decending */
          241  +  if( A ) A->a[A->nExpr-1].sortOrder = Z;  /* 0=ascending, 1=decending */
   240    242   }
   241    243   sortlist(A) ::= sortitem(Y) sortorder(Z). {
   242    244     A = sqliteExprListAppend(0,Y,0);
   243         -  A->a[0].sortOrder = Z;
          245  +  if( A ) A->a[0].sortOrder = Z;
   244    246   }
   245    247   sortitem(A) ::= expr(X).   {A = X;}
   246    248   
   247    249   %type sortorder {int}
   248    250   
   249    251   sortorder(A) ::= ASC.      {A = 0;}
   250    252   sortorder(A) ::= DESC.     {A = 1;}
................................................................................
   293    295   
   294    296   itemlist(A) ::= itemlist(X) COMMA item(Y).  {A = sqliteExprListAppend(X,Y,0);}
   295    297   itemlist(A) ::= item(X).     {A = sqliteExprListAppend(0,X,0);}
   296    298   item(A) ::= INTEGER(X).      {A = sqliteExpr(TK_INTEGER, 0, 0, &X);}
   297    299   item(A) ::= PLUS INTEGER(X). {A = sqliteExpr(TK_INTEGER, 0, 0, &X);}
   298    300   item(A) ::= MINUS INTEGER(X). {
   299    301     A = sqliteExpr(TK_UMINUS, 0, 0, 0);
   300         -  A->pLeft = sqliteExpr(TK_INTEGER, 0, 0, &X);
          302  +  if( A ) A->pLeft = sqliteExpr(TK_INTEGER, 0, 0, &X);
   301    303   }
   302    304   item(A) ::= FLOAT(X).        {A = sqliteExpr(TK_FLOAT, 0, 0, &X);}
   303    305   item(A) ::= PLUS FLOAT(X).   {A = sqliteExpr(TK_FLOAT, 0, 0, &X);}
   304    306   item(A) ::= MINUS FLOAT(X).  {
   305    307     A = sqliteExpr(TK_UMINUS, 0, 0, 0);
   306         -  A->pLeft = sqliteExpr(TK_FLOAT, 0, 0, &X);
          308  +  if( A ) A->pLeft = sqliteExpr(TK_FLOAT, 0, 0, &X);
   307    309   }
   308    310   item(A) ::= STRING(X).       {A = sqliteExpr(TK_STRING, 0, 0, &X);}
   309    311   item(A) ::= NULL.            {A = sqliteExpr(TK_NULL, 0, 0, 0);}
   310    312   
   311    313   %type inscollist_opt {IdList*}
   312    314   %destructor inscollist_opt {sqliteIdListDelete($$);}
   313    315   %type inscollist {IdList*}
................................................................................
   393    395   }
   394    396   expr(A) ::= PLUS(B) expr(X). [UMINUS] {
   395    397     A = X;
   396    398     sqliteExprSpan(A,&B,&X->span);
   397    399   }
   398    400   expr(A) ::= LP(B) select(X) RP(E). {
   399    401     A = sqliteExpr(TK_SELECT, 0, 0, 0);
   400         -  A->pSelect = X;
          402  +  if( A ) A->pSelect = X;
   401    403     sqliteExprSpan(A,&B,&E);
   402    404   }
   403    405   expr(A) ::= expr(W) BETWEEN expr(X) AND expr(Y). {
   404    406     ExprList *pList = sqliteExprListAppend(0, X, 0);
   405    407     pList = sqliteExprListAppend(pList, Y, 0);
   406    408     A = sqliteExpr(TK_BETWEEN, W, 0, 0);
   407         -  A->pList = pList;
          409  +  if( A ) A->pList = pList;
   408    410     sqliteExprSpan(A,&W->span,&Y->span);
   409    411   }
   410    412   expr(A) ::= expr(W) NOT BETWEEN expr(X) AND expr(Y). {
   411    413     ExprList *pList = sqliteExprListAppend(0, X, 0);
   412    414     pList = sqliteExprListAppend(pList, Y, 0);
   413    415     A = sqliteExpr(TK_BETWEEN, W, 0, 0);
   414         -  A->pList = pList;
          416  +  if( A ) A->pList = pList;
   415    417     A = sqliteExpr(TK_NOT, A, 0, 0);
   416    418     sqliteExprSpan(A,&W->span,&Y->span);
   417    419   }
   418    420   expr(A) ::= expr(X) IN LP exprlist(Y) RP(E).  {
   419    421     A = sqliteExpr(TK_IN, X, 0, 0);
   420         -  A->pList = Y;
          422  +  if( A ) A->pList = Y;
   421    423     sqliteExprSpan(A,&X->span,&E);
   422    424   }
   423    425   expr(A) ::= expr(X) IN LP select(Y) RP(E).  {
   424    426     A = sqliteExpr(TK_IN, X, 0, 0);
   425         -  A->pSelect = Y;
          427  +  if( A ) A->pSelect = Y;
   426    428     sqliteExprSpan(A,&X->span,&E);
   427    429   }
   428    430   expr(A) ::= expr(X) NOT IN LP exprlist(Y) RP(E).  {
   429    431     A = sqliteExpr(TK_IN, X, 0, 0);
   430         -  A->pList = Y;
          432  +  if( A ) A->pList = Y;
   431    433     A = sqliteExpr(TK_NOT, A, 0, 0);
   432    434     sqliteExprSpan(A,&X->span,&E);
   433    435   }
   434    436   expr(A) ::= expr(X) NOT IN LP select(Y) RP(E).  {
   435    437     A = sqliteExpr(TK_IN, X, 0, 0);
   436         -  A->pSelect = Y;
          438  +  if( A ) A->pSelect = Y;
   437    439     A = sqliteExpr(TK_NOT, A, 0, 0);
   438    440     sqliteExprSpan(A,&X->span,&E);
   439    441   }
   440    442   
   441    443   
   442    444   
   443    445   %type exprlist {ExprList*}

Changes to src/printf.c.

   559    559             if( arg==0 ) arg = "(NULL)";
   560    560             for(i=n=0; (c=arg[i])!=0; i++){
   561    561               if( c=='\'' )  n++;
   562    562             }
   563    563             n += i + 1;
   564    564             if( n>etBUFSIZE ){
   565    565               bufpt = zExtra = sqliteMalloc( n );
          566  +            if( bufpt==0 ) return -1;
   566    567             }else{
   567    568               bufpt = buf;
   568    569             }
   569    570             for(i=j=0; (c=arg[i])!=0; i++){
   570    571               bufpt[j++] = c;
   571    572               if( c=='\'' ) bufpt[j++] = c;
   572    573             }

Changes to src/select.c.

    20     20   **   drh@hwaci.com
    21     21   **   http://www.hwaci.com/drh/
    22     22   **
    23     23   *************************************************************************
    24     24   ** This file contains C code routines that are called by the parser
    25     25   ** to handle SELECT statements.
    26     26   **
    27         -** $Id: select.c,v 1.30 2001/04/04 11:48:58 drh Exp $
           27  +** $Id: select.c,v 1.31 2001/04/11 14:28:42 drh Exp $
    28     28   */
    29     29   #include "sqliteInt.h"
    30     30   
    31     31   /*
    32     32   ** Allocate a new Select structure and return a pointer to that
    33     33   ** structure.
    34     34   */
    35     35   Select *sqliteSelectNew(
    36         -  ExprList *pEList,
    37         -  IdList *pSrc,
    38         -  Expr *pWhere,
    39         -  ExprList *pGroupBy,
    40         -  Expr *pHaving,
    41         -  ExprList *pOrderBy,
    42         -  int isDistinct
           36  +  ExprList *pEList,     /* which columns to include in the result */
           37  +  IdList *pSrc,         /* the FROM clause -- which tables to scan */
           38  +  Expr *pWhere,         /* the WHERE clause */
           39  +  ExprList *pGroupBy,   /* the GROUP BY clause */
           40  +  Expr *pHaving,        /* the HAVING clause */
           41  +  ExprList *pOrderBy,   /* the ORDER BY clause */
           42  +  int isDistinct        /* true if the DISTINCT keyword is present */
    43     43   ){
    44     44     Select *pNew;
    45     45     pNew = sqliteMalloc( sizeof(*pNew) );
    46         -  if( pNew==0 ) return 0;
    47         -  pNew->pEList = pEList;
    48         -  pNew->pSrc = pSrc;
    49         -  pNew->pWhere = pWhere;
    50         -  pNew->pGroupBy = pGroupBy;
    51         -  pNew->pHaving = pHaving;
    52         -  pNew->pOrderBy = pOrderBy;
    53         -  pNew->isDistinct = isDistinct;
    54         -  pNew->op = TK_SELECT;
           46  +  if( pNew==0 ){
           47  +    sqliteExprListDelete(pEList);
           48  +    sqliteIdListDelete(pSrc);
           49  +    sqliteExprDelete(pWhere);
           50  +    sqliteExprListDelete(pGroupBy);
           51  +    sqliteExprDelete(pHaving);
           52  +    sqliteExprListDelete(pOrderBy);
           53  +  }else{
           54  +    pNew->pEList = pEList;
           55  +    pNew->pSrc = pSrc;
           56  +    pNew->pWhere = pWhere;
           57  +    pNew->pGroupBy = pGroupBy;
           58  +    pNew->pHaving = pHaving;
           59  +    pNew->pOrderBy = pOrderBy;
           60  +    pNew->isDistinct = isDistinct;
           61  +    pNew->op = TK_SELECT;
           62  +  }
    55     63     return pNew;
    56     64   }
    57     65   
    58     66   /*
    59     67   ** Delete the given Select structure and all of its substructures.
    60     68   */
    61     69   void sqliteSelectDelete(Select *p){
................................................................................
    99    107     int eDest,              /* How to dispose of the results */
   100    108     int iParm,              /* An argument to the disposal method */
   101    109     int iContinue,          /* Jump here to continue with next row */
   102    110     int iBreak              /* Jump here to break out of the inner loop */
   103    111   ){
   104    112     Vdbe *v = pParse->pVdbe;
   105    113     int i;
          114  +  if( v==0 ) return 0;
   106    115   
   107    116     /* Pull the requested columns.
   108    117     */
   109    118     if( pEList ){
   110    119       for(i=0; i<pEList->nExpr; i++){
   111    120         sqliteExprCode(pParse, pEList->a[i].pExpr);
   112    121       }
................................................................................
   113    122       nColumn = pEList->nExpr;
   114    123     }else{
   115    124       for(i=0; i<nColumn; i++){
   116    125         sqliteVdbeAddOp(v, OP_Field, srcTab, i, 0, 0);
   117    126       }
   118    127     }
   119    128   
   120         -  /* If the current result is not distinct, skip the rest
   121         -  ** of the processing for the current row.
          129  +  /* If the DISTINCT keyword was present on the SELECT statement
          130  +  ** and this row has been seen before, then do not make this row
          131  +  ** part of the result.
   122    132     */
   123    133     if( distinct>=0 ){
   124    134       int lbl = sqliteVdbeMakeLabel(v);
   125    135       sqliteVdbeAddOp(v, OP_MakeKey, pEList->nExpr, 1, 0, 0);
   126    136       sqliteVdbeAddOp(v, OP_Distinct, distinct, lbl, 0, 0);
   127    137       sqliteVdbeAddOp(v, OP_Pop, pEList->nExpr+1, 0, 0, 0);
   128    138       sqliteVdbeAddOp(v, OP_Goto, 0, iContinue, 0, 0);
................................................................................
   225    235   ** are in the result and the name for each column.  This information
   226    236   ** is used to provide "argc" and "azCol[]" values in the callback.
   227    237   */
   228    238   static 
   229    239   void generateColumnNames(Parse *pParse, IdList *pTabList, ExprList *pEList){
   230    240     Vdbe *v = pParse->pVdbe;
   231    241     int i;
   232         -  if( pParse->colNamesSet ) return;
          242  +  if( pParse->colNamesSet || v==0 || sqlite_malloc_failed ) return;
   233    243     pParse->colNamesSet = 1;
   234    244     sqliteVdbeAddOp(v, OP_ColumnCount, pEList->nExpr, 0, 0, 0);
   235    245     for(i=0; i<pEList->nExpr; i++){
   236    246       Expr *p;
   237    247       int addr;
   238    248       if( pEList->a[i].zName ){
   239    249         char *zName = pEList->a[i].zName;
   240    250         sqliteVdbeAddOp(v, OP_ColumnName, i, 0, zName, 0);
   241    251         continue;
   242    252       }
   243    253       p = pEList->a[i].pExpr;
          254  +    if( p==0 ) continue;
   244    255       if( p->span.z && p->span.z[0] ){
   245    256         addr = sqliteVdbeAddOp(v,OP_ColumnName, i, 0, 0, 0);
   246    257         sqliteVdbeChangeP3(v, addr, p->span.z, p->span.n);
   247    258         sqliteVdbeCompressSpace(v, addr);
   248    259       }else if( p->op!=TK_COLUMN || pTabList==0 ){
   249    260         char zName[30];
   250    261         sprintf(zName, "column%d", i+1);
................................................................................
   295    306   **         of all tables.
   296    307   **
   297    308   ** Return 0 on success.  If there are problems, leave an error message
   298    309   ** in pParse and return non-zero.
   299    310   */
   300    311   static int fillInColumnList(Parse *pParse, Select *p){
   301    312     int i, j;
   302         -  IdList *pTabList = p->pSrc;
   303         -  ExprList *pEList = p->pEList;
          313  +  IdList *pTabList;
          314  +  ExprList *pEList;
          315  +
          316  +  if( p==0 || p->pSrc==0 ) return 1;
          317  +  pTabList = p->pSrc;
          318  +  pEList = p->pEList;
   304    319   
   305    320     /* Look up every table in the table list.
   306    321     */
   307    322     for(i=0; i<pTabList->nId; i++){
   308    323       if( pTabList->a[i].pTab ){
   309    324         /* This routine has run before!  No need to continue */
   310    325         return 0;
          326  +    }
          327  +    if( pTabList->a[i].zName==0 ){
          328  +      /* No table name is given.  Instead, there is a (SELECT ...) statement
          329  +      ** the results of which should be used in place of the table.  The
          330  +      ** was this is implemented is that the (SELECT ...) writes its results
          331  +      ** into a temporary table which is then scanned like any other table.
          332  +      */
          333  +      sqliteSetString(&pParse->zErrMsg, 
          334  +          "(SELECT...) in a FROM clause is not yet implemented.", 0);
          335  +      pParse->nErr++;
          336  +      return 1;
   311    337       }
   312    338       pTabList->a[i].pTab = sqliteFindTable(pParse->db, pTabList->a[i].zName);
   313    339       if( pTabList->a[i].pTab==0 ){
   314    340         sqliteSetString(&pParse->zErrMsg, "no such table: ", 
   315    341            pTabList->a[i].zName, 0);
   316    342         pParse->nErr++;
   317    343         return 1;
................................................................................
   322    348     ** a list of all columns from all tables.
   323    349     */
   324    350     if( pEList==0 ){
   325    351       for(i=0; i<pTabList->nId; i++){
   326    352         Table *pTab = pTabList->a[i].pTab;
   327    353         for(j=0; j<pTab->nCol; j++){
   328    354           Expr *pExpr = sqliteExpr(TK_DOT, 0, 0, 0);
          355  +        if( pExpr==0 ) break;
   329    356           pExpr->pLeft = sqliteExpr(TK_ID, 0, 0, 0);
          357  +        if( pExpr->pLeft==0 ) break;
   330    358           pExpr->pLeft->token.z = pTab->zName;
   331    359           pExpr->pLeft->token.n = strlen(pTab->zName);
   332    360           pExpr->pRight = sqliteExpr(TK_ID, 0, 0, 0);
          361  +        if( pExpr->pRight==0 ) break;
   333    362           pExpr->pRight->token.z = pTab->aCol[j].zName;
   334    363           pExpr->pRight->token.n = strlen(pTab->aCol[j].zName);
   335    364           pExpr->span.z = "";
   336    365           pExpr->span.n = 0;
   337    366           pEList = sqliteExprListAppend(pEList, pExpr, 0);
   338    367         }
   339    368       }
................................................................................
   362    391     int iTable,             /* Insert this this value in iTable */
   363    392     int mustComplete        /* If TRUE all ORDER BYs must match */
   364    393   ){
   365    394     int nErr = 0;
   366    395     int i, j;
   367    396     ExprList *pEList;
   368    397   
   369         -  assert( pSelect && pOrderBy );
          398  +  if( pSelect==0 || pOrderBy==0 ) return 1;
   370    399     if( mustComplete ){
   371    400       for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
   372    401     }
   373    402     if( fillInColumnList(pParse, pSelect) ){
   374    403       return 1;
   375    404     }
   376    405     if( pSelect->pPrior ){
................................................................................
   422    451   ** If an error occurs, return NULL and leave a message in pParse.
   423    452   */
   424    453   Vdbe *sqliteGetVdbe(Parse *pParse){
   425    454     Vdbe *v = pParse->pVdbe;
   426    455     if( v==0 ){
   427    456       v = pParse->pVdbe = sqliteVdbeCreate(pParse->db);
   428    457     }
   429         -  if( v==0 ){
   430         -    sqliteSetString(&pParse->zErrMsg, "out of memory", 0);
   431         -    pParse->nErr++;
   432         -  }
   433    458     return v;
   434    459   }
   435    460       
   436    461   
   437    462   /*
   438    463   ** This routine is called to process a query that is really the union
   439    464   ** or intersection of two or more separate queries.
................................................................................
   443    468     Select *pPrior;     /* Another SELECT immediately to our left */
   444    469     Vdbe *v;            /* Generate code to this VDBE */
   445    470     int base;           /* Baseline value for pParse->nTab */
   446    471   
   447    472     /* Make sure there is no ORDER BY clause on prior SELECTs.  Only the 
   448    473     ** last SELECT in the series may have an ORDER BY.
   449    474     */
   450         -  assert( p->pPrior!=0 );
          475  +  if( p==0 || p->pPrior==0 ) return 1;
   451    476     pPrior = p->pPrior;
   452    477     if( pPrior->pOrderBy ){
   453    478       sqliteSetString(&pParse->zErrMsg,"ORDER BY clause should come after ",
   454    479         selectOpName(p->op), " not before", 0);
   455    480       pParse->nErr++;
   456    481       return 1;
   457    482     }
................................................................................
   646    671     Expr *pWhere;          /* The WHERE clause.  May be NULL */
   647    672     ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
   648    673     ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
   649    674     Expr *pHaving;         /* The HAVING clause.  May be NULL */
   650    675     int isDistinct;        /* True if the DISTINCT keyword is present */
   651    676     int distinct;          /* Table to use for the distinct set */
   652    677     int base;              /* First cursor available for use */
          678  +
          679  +  if( sqlite_malloc_failed || pParse->nErr || p==0 ) return 1;
   653    680   
   654    681     /* If there is are a sequence of queries, do the earlier ones first.
   655    682     */
   656    683     if( p->pPrior ){
   657    684       return multiSelect(pParse, p, eDest, iParm);
   658    685     }
   659    686   
................................................................................
   682    709     ** columnlist in pEList if there isn't one already.  (The parser leaves
   683    710     ** a NULL in the p->pEList if the SQL said "SELECT * FROM ...")
   684    711     */
   685    712     if( fillInColumnList(pParse, p) ){
   686    713       return 1;
   687    714     }
   688    715     pEList = p->pEList;
          716  +  if( pEList==0 ) return 1;
   689    717   
   690    718     /* Allocate a temporary table to use for the DISTINCT set, if
   691    719     ** necessary.  This must be done early to allocate the cursor before
   692    720     ** any calls to sqliteExprResolveIds().
   693    721     */
   694    722     if( isDistinct ){
   695    723       distinct = pParse->nTab++;
................................................................................
   816    844           }
   817    845         }
   818    846       }
   819    847     }
   820    848   
   821    849     /* Begin generating code.
   822    850     */
   823         -  v = pParse->pVdbe;
   824         -  if( v==0 ){
   825         -    v = pParse->pVdbe = sqliteVdbeCreate(pParse->db);
   826         -  }
   827         -  if( v==0 ){
   828         -    sqliteSetString(&pParse->zErrMsg, "out of memory", 0);
   829         -    pParse->nErr++;
   830         -    return 1;
   831         -  }
          851  +  v = sqliteGetVdbe(pParse);
          852  +  if( v==0 ) return 1;
   832    853     if( pOrderBy ){
   833    854       sqliteVdbeAddOp(v, OP_SortOpen, 0, 0, 0, 0);
   834    855     }
   835    856   
   836    857     /* Identify column names if we will be using in the callback.  This
   837    858     ** step is skipped if the output is going to a table or a memory cell.
   838    859     */

Changes to src/shell.c.

    20     20   **   drh@hwaci.com
    21     21   **   http://www.hwaci.com/drh/
    22     22   **
    23     23   *************************************************************************
    24     24   ** This file contains code to implement the "sqlite" command line
    25     25   ** utility for accessing SQLite databases.
    26     26   **
    27         -** $Id: shell.c,v 1.30 2001/04/04 21:22:14 drh Exp $
           27  +** $Id: shell.c,v 1.31 2001/04/11 14:28:42 drh Exp $
    28     28   */
    29     29   #include <stdlib.h>
    30     30   #include <string.h>
    31     31   #include <stdio.h>
    32     32   #include "sqlite.h"
    33     33   #include <unistd.h>
    34     34   #include <ctype.h>
................................................................................
    56     56   ** the text in memory obtained from malloc() and returns a pointer
    57     57   ** to the text.  NULL is returned at end of file, or if malloc()
    58     58   ** fails.
    59     59   **
    60     60   ** The interface is like "readline" but no command-line editing
    61     61   ** is done.
    62     62   */
    63         -static char *getline(char *zPrompt){
           63  +static char *getline(char *zPrompt, FILE *in){
    64     64     char *zLine;
    65     65     int nLine;
    66     66     int n;
    67     67     int eol;
    68     68   
    69     69     if( zPrompt && *zPrompt ){
    70     70       printf("%s",zPrompt);
................................................................................
    77     77     eol = 0;
    78     78     while( !eol ){
    79     79       if( n+100>nLine ){
    80     80         nLine = nLine*2 + 100;
    81     81         zLine = realloc(zLine, nLine);
    82     82         if( zLine==0 ) return 0;
    83     83       }
    84         -    if( fgets(&zLine[n], nLine - n, stdin)==0 ){
           84  +    if( fgets(&zLine[n], nLine - n, in)==0 ){
    85     85         if( n==0 ){
    86     86           free(zLine);
    87     87           return 0;
    88     88         }
    89     89         zLine[n] = 0;
    90     90         eol = 1;
    91     91         break;
................................................................................
   106    106   ** is coming from a terminal.  In that case, we issue a prompt and
   107    107   ** attempt to use "readline" for command-line editing.  If "isatty"
   108    108   ** is false, use "getline" instead of "readline" and issue to prompt.
   109    109   **
   110    110   ** zPrior is a string of prior text retrieved.  If not the empty
   111    111   ** string, then issue a continuation prompt.
   112    112   */
   113         -static char *one_input_line(const char *zPrior, int isatty){
          113  +static char *one_input_line(const char *zPrior, FILE *in){
   114    114     char *zPrompt;
   115    115     char *zResult;
   116         -  if( !isatty ){
   117         -    return getline(0);
          116  +  if( in!=0 ){
          117  +    return getline(0, in);
   118    118     }
   119    119     if( zPrior && zPrior[0] ){
   120    120       zPrompt = "   ...> ";
   121    121     }else{
   122    122       zPrompt = "sqlite> ";
   123    123     }
   124    124     zResult = readline(zPrompt);
................................................................................
   129    129   /*
   130    130   ** An pointer to an instance of this structure is passed from
   131    131   ** the main program to the callback.  This is used to communicate
   132    132   ** state and mode information.
   133    133   */
   134    134   struct callback_data {
   135    135     sqlite *db;            /* The database */
          136  +  int echoOn;            /* True to echo input commands */
   136    137     int cnt;               /* Number of records displayed so far */
   137    138     FILE *out;             /* Write results here */
   138    139     int mode;              /* An output mode setting */
   139    140     int showHeader;        /* True to show column names in List or Column mode */
   140    141     int escape;            /* Escape this character when in MODE_List */
   141    142     char zDestTable[250];  /* Name of destination table when MODE_Insert */
   142    143     char separator[20];    /* Separator character for MODE_List */
................................................................................
   385    386   /*
   386    387   ** This is a different callback routine used for dumping the database.
   387    388   ** Each row received by this callback consists of a table name,
   388    389   ** the table type ("index" or "table") and SQL to create the table.
   389    390   ** This routine should print text sufficient to recreate the table.
   390    391   */
   391    392   static int dump_callback(void *pArg, int nArg, char **azArg, char **azCol){
   392         -  struct callback_data *pData = (struct callback_data *)pArg;
          393  +  struct callback_data *p = (struct callback_data *)pArg;
   393    394     if( nArg!=3 ) return 1;
   394         -  fprintf(pData->out, "%s;\n", azArg[2]);
          395  +  fprintf(p->out, "%s;\n", azArg[2]);
   395    396     if( strcmp(azArg[1],"table")==0 ){
   396    397       struct callback_data d2;
   397         -    d2 = *pData;
          398  +    d2 = *p;
   398    399       d2.mode = MODE_List;
   399    400       d2.escape = '\t';
   400    401       strcpy(d2.separator,"\t");
   401         -    fprintf(pData->out, "COPY '%s' FROM STDIN;\n", azArg[0]);
   402         -    sqlite_exec_printf(pData->db, 
          402  +    fprintf(p->out, "COPY '%s' FROM STDIN;\n", azArg[0]);
          403  +    sqlite_exec_printf(p->db, 
   403    404          "SELECT * FROM '%q'",
   404    405          callback, &d2, 0, azArg[0]
   405    406       );
   406         -    fprintf(pData->out, "\\.\n");
          407  +    fprintf(p->out, "\\.\n");
   407    408     }
   408         -  fprintf(pData->out, "VACUUM '%s';\n", azArg[0]);
          409  +  fprintf(p->out, "VACUUM '%s';\n", azArg[0]);
   409    410     return 0;
   410    411   }
   411    412   
   412    413   /*
   413    414   ** Text of a help message
   414    415   */
   415    416   static char zHelp[] = 
   416    417     ".dump ?TABLE? ...      Dump the database in an text format\n"
          418  +  ".echo ON|OFF           Turn command echo on or off\n"
   417    419     ".exit                  Exit this program\n"
   418    420     ".explain               Set output mode suitable for EXPLAIN\n"
   419    421     ".header ON|OFF         Turn display of headers on or off\n"
   420    422     ".help                  Show this message\n"
   421    423     ".indices TABLE         Show names of all indices on TABLE\n"
   422    424     ".mode MODE             Set mode to one of \"line\", \"column\", \n"
   423    425     "                       \"insert\", \"list\", or \"html\"\n"
   424    426     ".mode insert TABLE     Generate SQL insert statements for TABLE\n"
   425    427     ".output FILENAME       Send output to FILENAME\n"
   426    428     ".output stdout         Send output to the screen\n"
          429  +  ".read FILENAME         Execute SQL in FILENAME\n"
          430  +  ".reindex ?TABLE?       Rebuild indices\n"
          431  +/*  ".rename OLD NEW        Change the name of a table or index\n" */
   427    432     ".schema ?TABLE?        Show the CREATE statements\n"
   428    433     ".separator STRING      Change separator string for \"list\" mode\n"
   429    434     ".tables ?PATTERN?      List names of tables matching a pattern\n"
   430    435     ".timeout MS            Try opening locked tables for MS milliseconds\n"
   431    436     ".width NUM NUM ...     Set column widths for \"column\" mode\n"
   432    437   ;
   433    438   
          439  +/* Forward reference */
          440  +static void process_input(struct callback_data *p, FILE *in);
          441  +
   434    442   /*
   435    443   ** If an input line begins with "." then invoke this routine to
   436    444   ** process that line.
   437    445   */
   438    446   static void do_meta_command(char *zLine, sqlite *db, struct callback_data *p){
   439    447     int i = 1;
   440    448     int nArg = 0;
................................................................................
   486    494         }
   487    495       }
   488    496       if( zErrMsg ){
   489    497         fprintf(stderr,"Error: %s\n", zErrMsg);
   490    498         free(zErrMsg);
   491    499       }
   492    500     }else
          501  +
          502  +  if( c=='e' && strncmp(azArg[0], "echo", n)==0 && nArg>1 ){
          503  +    int j;
          504  +    char *z = azArg[1];
          505  +    int val = atoi(azArg[1]);
          506  +    for(j=0; z[j]; j++){
          507  +      if( isupper(z[j]) ) z[j] = tolower(z[j]);
          508  +    }
          509  +    if( strcmp(z,"on")==0 ){
          510  +      val = 1;
          511  +    }else if( strcmp(z,"yes")==0 ){
          512  +      val = 1;
          513  +    } 
          514  +    p->echoOn = val;
          515  +  }else
   493    516   
   494    517     if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
   495    518       exit(0);
   496    519     }else
   497    520   
   498    521     if( c=='e' && strncmp(azArg[0], "explain", n)==0 ){
   499    522       p->mode = MODE_Column;
................................................................................
   555    578       }else if( strncmp(azArg[1],"insert",n2)==0 ){
   556    579         p->mode = MODE_Insert;
   557    580         if( nArg>=3 ){
   558    581           sprintf(p->zDestTable,"%.*s", (int)(sizeof(p->zDestTable)-1), azArg[2]);
   559    582         }else{
   560    583           sprintf(p->zDestTable,"table");
   561    584         }
          585  +    }else {
          586  +      fprintf(stderr,"mode should be on of: column html insert line list\n");
   562    587       }
   563    588     }else
   564    589   
   565    590     if( c=='o' && strncmp(azArg[0], "output", n)==0 && nArg==2 ){
   566    591       if( p->out!=stdout ){
   567    592         fclose(p->out);
   568    593       }
................................................................................
   572    597         p->out = fopen(azArg[1], "w");
   573    598         if( p->out==0 ){
   574    599           fprintf(stderr,"can't write to \"%s\"\n", azArg[1]);
   575    600           p->out = stdout;
   576    601         }
   577    602       }
   578    603     }else
          604  +
          605  +  if( c=='r' && strncmp(azArg[0], "read", n)==0 && nArg==2 ){
          606  +    FILE *alt = fopen(azArg[1], "r");
          607  +    if( alt==0 ){
          608  +      fprintf(stderr,"can't open \"%s\"\n", azArg[1]);
          609  +    }else{
          610  +      process_input(p, alt);
          611  +      fclose(alt);
          612  +    }
          613  +  }else
          614  +
          615  +  if( c=='r' && strncmp(azArg[0], "reindex", n)==0 ){
          616  +    char **azResult;
          617  +    int nRow, rc;
          618  +    char *zErrMsg;
          619  +    int i;
          620  +    char *zSql;
          621  +    if( nArg==1 ){
          622  +      rc = sqlite_get_table(db,
          623  +        "SELECT name, sql FROM sqlite_master "
          624  +        "WHERE type='index'",
          625  +        &azResult, &nRow, 0, &zErrMsg
          626  +      );
          627  +    }else{
          628  +      rc = sqlite_get_table_printf(db,
          629  +        "SELECT name, sql FROM sqlite_master "
          630  +        "WHERE type='index' AND tbl_name LIKE '%q'",
          631  +        &azResult, &nRow, 0, &zErrMsg, azArg[1]
          632  +      );
          633  +    }
          634  +    for(i=1; rc==SQLITE_OK && i<=nRow; i++){
          635  +      extern char *sqlite_mprintf(const char *, ...);
          636  +      zSql = sqlite_mprintf(
          637  +         "DROP INDEX '%q';\n%s;\nVACUUM '%q';",
          638  +         azResult[i*2], azResult[i*2+1], azResult[i*2]);
          639  +      if( p->echoOn ) printf("%s\n", zSql);
          640  +      rc = sqlite_exec(db, zSql, 0, 0, &zErrMsg);
          641  +    }
          642  +    sqlite_free_table(azResult);
          643  +    if( zErrMsg ){
          644  +      fprintf(stderr,"Error: %s\n", zErrMsg);
          645  +      free(zErrMsg);
          646  +    }
          647  +  }else
   579    648   
   580    649     if( c=='s' && strncmp(azArg[0], "schema", n)==0 ){
   581    650       struct callback_data data;
   582    651       char *zErrMsg = 0;
   583    652       memcpy(&data, p, sizeof(data));
   584    653       data.showHeader = 0;
   585    654       data.mode = MODE_Semi;
................................................................................
   680    749     }else
   681    750   
   682    751     {
   683    752       fprintf(stderr, "unknown command: \"%s\". Enter \".help\" for help\n",
   684    753         azArg[0]);
   685    754     }
   686    755   }
          756  +
          757  +static char *Argv0;
          758  +static void process_input(struct callback_data *p, FILE *in){
          759  +  char *zLine;
          760  +  char *zSql = 0;
          761  +  int nSql = 0;
          762  +  char *zErrMsg;
          763  +  while( (zLine = one_input_line(zSql, in))!=0 ){
          764  +    if( p->echoOn ) printf("%s\n", zLine);
          765  +    if( zLine && zLine[0]=='.' ){
          766  +      do_meta_command(zLine, db, p);
          767  +      free(zLine);
          768  +      continue;
          769  +    }
          770  +    if( zSql==0 ){
          771  +      int i;
          772  +      for(i=0; zLine[i] && isspace(zLine[i]); i++){}
          773  +      if( zLine[i]!=0 ){
          774  +        nSql = strlen(zLine);
          775  +        zSql = malloc( nSql+1 );
          776  +        strcpy(zSql, zLine);
          777  +      }
          778  +    }else{
          779  +      int len = strlen(zLine);
          780  +      zSql = realloc( zSql, nSql + len + 2 );
          781  +      if( zSql==0 ){
          782  +        fprintf(stderr,"%s: out of memory!\n", Argv0);
          783  +        exit(1);
          784  +      }
          785  +      strcpy(&zSql[nSql++], "\n");
          786  +      strcpy(&zSql[nSql], zLine);
          787  +      nSql += len;
          788  +    }
          789  +    free(zLine);
          790  +    if( zSql && sqlite_complete(zSql) ){
          791  +      p->cnt = 0;
          792  +      if( sqlite_exec(db, zSql, callback, p, &zErrMsg)!=0 
          793  +           && zErrMsg!=0 ){
          794  +        if( in!=0 && !p->echoOn ) printf("%s\n",zSql);
          795  +        printf("SQL error: %s\n", zErrMsg);
          796  +        free(zErrMsg);
          797  +        zErrMsg = 0;
          798  +      }
          799  +      free(zSql);
          800  +      zSql = 0;
          801  +      nSql = 0;
          802  +    }
          803  +  }
          804  +  if( zSql ){
          805  +    printf("Incomplete SQL: %s\n", zSql);
          806  +    free(zSql);
          807  +  }
          808  +}
   687    809   
   688    810   int main(int argc, char **argv){
   689    811     char *zErrMsg = 0;
   690         -  char *argv0 = argv[0];
   691    812     struct callback_data data;
   692         -  int echo = 0;
   693    813   
          814  +  Argv0 = argv[0];
   694    815     memset(&data, 0, sizeof(data));
   695    816     data.mode = MODE_List;
   696    817     strcpy(data.separator,"|");
   697    818     data.showHeader = 0;
   698    819   #ifdef SIGINT
   699    820     signal(SIGINT, interrupt_handler);
   700    821   #endif
................................................................................
   720    841         argc--;
   721    842         argv++;
   722    843       }else if( strcmp(argv[1],"-noheader")==0 ){
   723    844         data.showHeader = 0;
   724    845         argc--;
   725    846         argv++;
   726    847       }else if( strcmp(argv[1],"-echo")==0 ){
   727         -      echo = 1;
          848  +      data.echoOn = 1;
   728    849         argc--;
   729    850         argv++;
   730    851       }else{
   731         -      fprintf(stderr,"%s: unknown option: %s\n", argv0, argv[1]);
          852  +      fprintf(stderr,"%s: unknown option: %s\n", Argv0, argv[1]);
   732    853         return 1;
   733    854       }
   734    855     }
   735    856     if( argc!=2 && argc!=3 ){
   736         -    fprintf(stderr,"Usage: %s ?OPTIONS? FILENAME ?SQL?\n", argv0);
          857  +    fprintf(stderr,"Usage: %s ?OPTIONS? FILENAME ?SQL?\n", Argv0);
   737    858       exit(1);
   738    859     }
   739    860     data.db = db = sqlite_open(argv[1], 0666, &zErrMsg);
   740    861     if( db==0 ){
   741    862       data.db = db = sqlite_open(argv[1], 0444, &zErrMsg);
   742    863       if( db==0 ){
   743    864         if( zErrMsg ){
................................................................................
   753    874     data.out = stdout;
   754    875     if( argc==3 ){
   755    876       if( sqlite_exec(db, argv[2], callback, &data, &zErrMsg)!=0 && zErrMsg!=0 ){
   756    877         fprintf(stderr,"SQL error: %s\n", zErrMsg);
   757    878         exit(1);
   758    879       }
   759    880     }else{
   760         -    char *zLine;
   761         -    char *zSql = 0;
   762         -    int nSql = 0;
   763         -    int istty = isatty(0);
   764         -    if( istty ){
          881  +    if( isatty(0) ){
   765    882         printf(
   766    883           "SQLite version %s\n"
   767    884           "Enter \".help\" for instructions\n",
   768    885           sqlite_version
   769    886         );
   770         -    }
   771         -    while( (zLine = one_input_line(zSql, istty))!=0 ){
   772         -      if( echo ) printf("%s\n", zLine);
   773         -      if( zLine && zLine[0]=='.' ){
   774         -        do_meta_command(zLine, db, &data);
   775         -        free(zLine);
   776         -        continue;
   777         -      }
   778         -      if( zSql==0 ){
   779         -        int i;
   780         -        for(i=0; zLine[i] && isspace(zLine[i]); i++){}
   781         -        if( zLine[i]!=0 ){
   782         -          nSql = strlen(zLine);
   783         -          zSql = malloc( nSql+1 );
   784         -          strcpy(zSql, zLine);
   785         -        }
   786         -      }else{
   787         -        int len = strlen(zLine);
   788         -        zSql = realloc( zSql, nSql + len + 2 );
   789         -        if( zSql==0 ){
   790         -          fprintf(stderr,"%s: out of memory!\n", argv0);
   791         -          exit(1);
   792         -        }
   793         -        strcpy(&zSql[nSql++], "\n");
   794         -        strcpy(&zSql[nSql], zLine);
   795         -        nSql += len;
   796         -      }
   797         -      free(zLine);
   798         -      if( zSql && sqlite_complete(zSql) ){
   799         -        data.cnt = 0;
   800         -        if( sqlite_exec(db, zSql, callback, &data, &zErrMsg)!=0 
   801         -             && zErrMsg!=0 ){
   802         -          if( !istty && !echo ) printf("%s\n",zSql);
   803         -          printf("SQL error: %s\n", zErrMsg);
   804         -          free(zErrMsg);
   805         -          zErrMsg = 0;
   806         -        }
   807         -        free(zSql);
   808         -        zSql = 0;
   809         -        nSql = 0;
   810         -      }
          887  +      process_input(&data, 0);
          888  +    }else{
          889  +      process_input(&data, stdin);
   811    890       }
   812    891     }
   813    892     sqlite_close(db);
   814    893     return 0;
   815    894   }

Changes to src/sqliteInt.h.

    19     19   ** Author contact information:
    20     20   **   drh@hwaci.com
    21     21   **   http://www.hwaci.com/drh/
    22     22   **
    23     23   *************************************************************************
    24     24   ** Internal interface definitions for SQLite.
    25     25   **
    26         -** @(#) $Id: sqliteInt.h,v 1.40 2001/04/07 15:24:33 drh Exp $
           26  +** @(#) $Id: sqliteInt.h,v 1.41 2001/04/11 14:28:43 drh Exp $
    27     27   */
    28     28   #include "sqlite.h"
    29     29   #include "dbbe.h"
    30     30   #include "vdbe.h"
    31     31   #include "parse.h"
    32     32   #include <gdbm.h>
    33     33   #include <stdio.h>
................................................................................
    61     61   # define sqliteStrDup(X)    sqliteStrDup_(X,__FILE__,__LINE__)
    62     62   # define sqliteStrNDup(X,Y) sqliteStrNDup_(X,Y,__FILE__,__LINE__)
    63     63     void sqliteStrRealloc(char**);
    64     64   #else
    65     65   # define sqliteStrRealloc(X)
    66     66   #endif
    67     67   
           68  +/*
           69  +** This variable gets set if malloc() ever fails.  After it gets set,
           70  +** the SQLite library shuts down permanently.
           71  +*/
           72  +extern int sqlite_malloc_failed;
           73  +
    68     74   /*
    69     75   ** The following global variables are used for testing and debugging
    70     76   ** only.  They only work if MEMORY_DEBUG is defined.
    71     77   */
    72     78   #ifdef MEMORY_DEBUG
    73     79   extern int sqlite_nMalloc;       /* Number of sqliteMalloc() calls */
    74     80   extern int sqlite_nFree;         /* Number of sqliteFree() calls */
................................................................................
   253    259   ** A list of identifiers.
   254    260   */
   255    261   struct IdList {
   256    262     int nId;         /* Number of identifiers on the list */
   257    263     struct {
   258    264       char *zName;      /* Text of the identifier. */
   259    265       char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
   260         -    Table *pTab;      /* An SQL table corresponding to zName */
   261    266       int idx;          /* Index in some Table.aCol[] of a column named zName */
          267  +    Table *pTab;      /* An SQL table corresponding to zName */
          268  +    Select *pSelect;  /* A SELECT statement used in place of a table name */
   262    269     } *a;            /* One entry for each identifier on the list */
   263    270   };
   264    271   
   265    272   /*
   266    273   ** The WHERE clause processing routine has two halves.  The
   267    274   ** first part does the start of the WHERE loop and the second
   268    275   ** half does the tail of the WHERE loop.  An instance of

Changes to src/table.c.

   136    136     *pazResult = 0;
   137    137     if( pnColumn ) *pnColumn = 0;
   138    138     if( pnRow ) *pnRow = 0;
   139    139     res.nResult = 0;
   140    140     res.nRow = 0;
   141    141     res.nColumn = 0;
   142    142     res.nData = 1;
   143         -  res.nAlloc = 200;
          143  +  res.nAlloc = 20;
   144    144     res.rc = SQLITE_OK;
   145    145     res.azResult = malloc( sizeof(char*)*res.nAlloc );
   146    146     if( res.azResult==0 ){
   147    147       return SQLITE_NOMEM;
   148    148     }
   149    149     res.azResult[0] = 0;
   150    150     rc = sqlite_exec(db, zSql, sqlite_get_table_cb, &res, pzErrMsg);

Changes to src/test1.c.

    21     21   **   http://www.hwaci.com/drh/
    22     22   **
    23     23   *************************************************************************
    24     24   ** Code for testing the printf() interface to SQLite.  This code
    25     25   ** is not included in the SQLite library.  It is used for automated
    26     26   ** testing of the SQLite library.
    27     27   **
    28         -** $Id: test1.c,v 1.1 2001/04/07 15:24:33 drh Exp $
           28  +** $Id: test1.c,v 1.2 2001/04/11 14:28:43 drh Exp $
    29     29   */
    30     30   #include "sqliteInt.h"
    31     31   #include "tcl.h"
    32     32   #include <stdlib.h>
    33     33   #include <string.h>
    34     34   
    35     35   /*
................................................................................
   263    263     if( Tcl_GetDouble(interp, argv[4], &r) ) return TCL_ERROR;
   264    264     z = sqlite_mprintf(argv[1], a[0], a[1], r);
   265    265     Tcl_AppendResult(interp, z, 0);
   266    266     sqliteFree(z);
   267    267     return TCL_OK;
   268    268   }
   269    269   
          270  +/*
          271  +** Usage: sqlite_malloc_fail N
          272  +**
          273  +** Rig sqliteMalloc() to fail on the N-th call.  Turn of this mechanism
          274  +** and reset the sqlite_malloc_failed variable is N==0.
          275  +*/
          276  +#ifdef MEMORY_DEBUG
          277  +static int sqlite_malloc_fail(
          278  +  void *NotUsed,
          279  +  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
          280  +  int argc,              /* Number of arguments */
          281  +  char **argv            /* Text of each argument */
          282  +){
          283  +  int n;
          284  +  if( argc!=2 ){
          285  +    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0], " N\"", 0);
          286  +    return TCL_ERROR;
          287  +  }
          288  +  if( Tcl_GetInt(interp, argv[1], &n) ) return TCL_ERROR;
          289  +  sqlite_iMallocFail = n;
          290  +  sqlite_malloc_failed = 0;
          291  +  return TCL_OK;
          292  +}
          293  +#endif
          294  +
          295  +/*
          296  +** Usage: sqlite_malloc_stat
          297  +**
          298  +** Return the number of prior calls to sqliteMalloc() and sqliteFree().
          299  +*/
          300  +#ifdef MEMORY_DEBUG
          301  +static int sqlite_malloc_stat(
          302  +  void *NotUsed,
          303  +  Tcl_Interp *interp,    /* The TCL interpreter that invoked this command */
          304  +  int argc,              /* Number of arguments */
          305  +  char **argv            /* Text of each argument */
          306  +){
          307  +  char zBuf[200];
          308  +  sprintf(zBuf, "%d %d %d", sqlite_nMalloc, sqlite_nFree, sqlite_iMallocFail);
          309  +  Tcl_AppendResult(interp, zBuf, 0);
          310  +  return TCL_OK;
          311  +}
          312  +#endif
          313  +
   270    314   /*
   271    315   ** Register commands with the TCL interpreter.
   272    316   */
   273    317   int Sqlitetest1_Init(Tcl_Interp *interp){
   274    318     Tcl_CreateCommand(interp, "sqlite_mprintf_int", sqlite_mprintf_int, 0, 0);
   275    319     Tcl_CreateCommand(interp, "sqlite_mprintf_str", sqlite_mprintf_str, 0, 0);
   276    320     Tcl_CreateCommand(interp, "sqlite_mprintf_double", sqlite_mprintf_double,0,0);
   277    321     Tcl_CreateCommand(interp, "sqlite_open", sqlite_test_open, 0, 0);
   278    322     Tcl_CreateCommand(interp, "sqlite_exec_printf", test_exec_printf, 0, 0);
   279    323     Tcl_CreateCommand(interp, "sqlite_get_table_printf", test_get_table_printf,
   280    324         0, 0);
   281    325     Tcl_CreateCommand(interp, "sqlite_close", sqlite_test_close, 0, 0);
          326  +#ifdef MEMORY_DEBUG
          327  +  Tcl_CreateCommand(interp, "sqlite_malloc_fail", sqlite_malloc_fail, 0, 0);
          328  +  Tcl_CreateCommand(interp, "sqlite_malloc_stat", sqlite_malloc_stat, 0, 0);
          329  +#endif
   282    330     return TCL_OK;
   283    331   }

Changes to src/tokenize.c.

    23     23   *************************************************************************
    24     24   ** An tokenizer for SQL
    25     25   **
    26     26   ** This file contains C code that splits an SQL input string up into
    27     27   ** individual tokens and sends those tokens one-by-one over to the
    28     28   ** parser for analysis.
    29     29   **
    30         -** $Id: tokenize.c,v 1.18 2001/04/04 11:48:58 drh Exp $
           30  +** $Id: tokenize.c,v 1.19 2001/04/11 14:28:43 drh Exp $
    31     31   */
    32     32   #include "sqliteInt.h"
    33     33   #include <ctype.h>
    34     34   #include <stdlib.h>
    35     35   
    36     36   /*
    37     37   ** All the keywords of the SQL language are stored as in a hash
................................................................................
   103    103     { "VALUES",            0, TK_VALUES,           0 },
   104    104     { "WHERE",             0, TK_WHERE,            0 },
   105    105   };
   106    106   
   107    107   /*
   108    108   ** This is the hash table
   109    109   */
   110         -#define KEY_HASH_SIZE 69
          110  +#define KEY_HASH_SIZE 71
   111    111   static Keyword *apHashTable[KEY_HASH_SIZE];
   112    112   
   113    113   
   114    114   /*
   115    115   ** This function looks up an identifier to determine if it is a
   116    116   ** keyword.  If it is a keyword, the token code of that keyword is 
   117    117   ** returned.  If the input is not a keyword, TK_ID is returned.
................................................................................
   324    324     if( pEngine==0 ){
   325    325       sqliteSetString(pzErrMsg, "out of memory", 0);
   326    326       return 1;
   327    327     }
   328    328   #ifndef NDEBUG
   329    329     sqliteParserTrace(trace, "parser: ");
   330    330   #endif
   331         -  while( nErr==0 && i>=0 && zSql[i]!=0 ){
          331  +  while( sqlite_malloc_failed==0 && nErr==0 && i>=0 && zSql[i]!=0 ){
   332    332       int tokenType;
   333    333       
   334    334       if( (pParse->db->flags & SQLITE_Interrupt)!=0 ){
   335    335         pParse->rc = SQLITE_INTERRUPT;
   336    336         sqliteSetString(pzErrMsg, "interrupt", 0);
   337    337         break;
   338    338       }
................................................................................
   359    359           }else if( sqliteStrNICmp(z,"--parser-trace-off--", 20)==0 ){
   360    360             trace = 0;
   361    361             sqliteParserTrace(trace, "parser: ");
   362    362           }else if( sqliteStrNICmp(z,"--vdbe-trace-on--",17)==0 ){
   363    363             pParse->db->flags |= SQLITE_VdbeTrace;
   364    364           }else if( sqliteStrNICmp(z,"--vdbe-trace-off--", 18)==0 ){
   365    365             pParse->db->flags &= ~SQLITE_VdbeTrace;
   366         -#ifdef MEMORY_DEBUG
   367         -        }else if( sqliteStrNICmp(z,"--malloc-fail=",14)==0 ){
   368         -          sqlite_iMallocFail = atoi(&z[14]);
   369         -        }else if( sqliteStrNICmp(z,"--malloc-stats--", 16)==0 ){
   370         -          if( pParse->xCallback ){
   371         -            static char *azName[4] = {"malloc", "free", "to_fail", 0 };
   372         -            char *azArg[4];
   373         -            char zVal[3][30];
   374         -            sprintf(zVal[0],"%d", sqlite_nMalloc);
   375         -            sprintf(zVal[1],"%d", sqlite_nFree);
   376         -            sprintf(zVal[2],"%d", sqlite_iMallocFail);
   377         -            azArg[0] = zVal[0];
   378         -            azArg[1] = zVal[1];
   379         -            azArg[2] = zVal[2];
   380         -            azArg[3] = 0;
   381         -            pParse->xCallback(pParse->pArg, 3, azArg, azName);
   382         -          }
   383         -#endif
   384    366           }
   385    367   #endif
   386    368           break;
   387    369         }
   388    370         case TK_ILLEGAL:
   389    371           sqliteSetNString(pzErrMsg, "unrecognized token: \"", -1, 
   390    372              pParse->sLastToken.z, pParse->sLastToken.n, "\"", 1, 0);
................................................................................
   433    415       pParse->pVdbe = 0;
   434    416     }
   435    417     if( pParse->pNewTable ){
   436    418       sqliteDeleteTable(pParse->db, pParse->pNewTable);
   437    419       pParse->pNewTable = 0;
   438    420     }
   439    421     sqliteParseInfoReset(pParse);
   440         -  sqliteStrRealloc(pzErrMsg);
   441    422     if( nErr>0 && pParse->rc==SQLITE_OK ){
   442    423       pParse->rc = SQLITE_ERROR;
   443    424     }
   444    425     return nErr;
   445    426   }

Changes to src/update.c.

    20     20   **   drh@hwaci.com
    21     21   **   http://www.hwaci.com/drh/
    22     22   **
    23     23   *************************************************************************
    24     24   ** This file contains C code routines that are called by the parser
    25     25   ** to handle UPDATE statements.
    26     26   **
    27         -** $Id: update.c,v 1.10 2001/03/14 12:35:57 drh Exp $
           27  +** $Id: update.c,v 1.11 2001/04/11 14:28:43 drh Exp $
    28     28   */
    29     29   #include "sqliteInt.h"
    30     30   
    31     31   /*
    32     32   ** Process an UPDATE statement.
    33     33   */
    34     34   void sqliteUpdate(
................................................................................
    46     46     Index *pIdx;           /* For looping over indices */
    47     47     int nIdx;              /* Number of indices that need updating */
    48     48     int base;              /* Index of first available table cursor */
    49     49     Index **apIdx = 0;     /* An array of indices that need updating too */
    50     50     int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
    51     51                            ** an expression for the i-th column of the table.
    52     52                            ** aXRef[i]==-1 if the i-th column is not changed. */
           53  +
           54  +  if( pParse->nErr || sqlite_malloc_failed ) goto update_cleanup;
    53     55   
    54     56     /* Locate the table which we want to update.  This table has to be
    55     57     ** put in an IdList structure because some of the subroutines we
    56     58     ** will be calling are designed to work with multiple tables and expect
    57     59     ** an IdList* parameter instead of just a Table* parameger.
    58     60     */
    59     61     pTabList = sqliteIdListAppend(0, pTableName);
           62  +  if( pTabList==0 ) goto update_cleanup;
    60     63     for(i=0; i<pTabList->nId; i++){
    61     64       pTabList->a[i].pTab = sqliteFindTable(pParse->db, pTabList->a[i].zName);
    62     65       if( pTabList->a[i].pTab==0 ){
    63     66         sqliteSetString(&pParse->zErrMsg, "no such table: ", 
    64     67            pTabList->a[i].zName, 0);
    65     68         pParse->nErr++;
    66     69         goto update_cleanup;

Changes to src/util.c.

    22     22   **
    23     23   *************************************************************************
    24     24   ** Utility functions used throughout sqlite.
    25     25   **
    26     26   ** This file contains functions for allocating memory, comparing
    27     27   ** strings, and stuff like that.
    28     28   **
    29         -** $Id: util.c,v 1.20 2001/04/05 15:57:13 drh Exp $
           29  +** $Id: util.c,v 1.21 2001/04/11 14:28:43 drh Exp $
    30     30   */
    31     31   #include "sqliteInt.h"
    32     32   #include <stdarg.h>
    33     33   #include <ctype.h>
    34     34   
           35  +/*
           36  +** If malloc() ever fails, this global variable gets set to 1.
           37  +** This causes the library to abort and never again function.
           38  +*/
           39  +int sqlite_malloc_failed = 0;
           40  +
    35     41   /*
    36     42   ** If MEMORY_DEBUG is defined, then use versions of malloc() and
    37     43   ** free() that track memory usage and check for buffer overruns.
    38     44   */
    39     45   #ifdef MEMORY_DEBUG
    40     46   
    41     47   /*
................................................................................
    54     60   void *sqliteMalloc_(int n, char *zFile, int line){
    55     61     void *p;
    56     62     int *pi;
    57     63     int k;
    58     64     sqlite_nMalloc++;
    59     65     if( sqlite_iMallocFail>=0 ){
    60     66       sqlite_iMallocFail--;
    61         -    if( sqlite_iMallocFail==0 ) return 0;
           67  +    if( sqlite_iMallocFail==0 ){
           68  +      sqlite_malloc_failed++;
           69  +      return 0;
           70  +    }
    62     71     }
    63     72     if( n==0 ) return 0;
    64     73     k = (n+sizeof(int)-1)/sizeof(int);
    65     74     pi = malloc( (3+k)*sizeof(int));
    66         -  if( pi==0 ) return 0;
           75  +  if( pi==0 ){
           76  +    sqlite_malloc_failed++;
           77  +    return 0;
           78  +  }
    67     79     pi[0] = 0xdead1122;
    68     80     pi[1] = n;
    69     81     pi[k+2] = 0xdead3344;
    70     82     p = &pi[2];
    71     83     memset(p, 0, n);
    72     84   #if MEMORY_DEBUG>1
    73     85     fprintf(stderr,"malloc %d bytes at 0x%x from %s:%d\n", n, (int)p, zFile,line);
................................................................................
   127    139     oldK = (oldN+sizeof(int)-1)/sizeof(int);
   128    140     if( oldPi[oldK+2]!=0xdead3344 ){
   129    141       fprintf(stderr,"High-end memory corruption in realloc at 0x%x\n", (int)p);
   130    142       return 0;
   131    143     }
   132    144     k = (n + sizeof(int) - 1)/sizeof(int);
   133    145     pi = malloc( (k+3)*sizeof(int) );
          146  +  if( pi==0 ){
          147  +    sqlite_malloc_failed++;
          148  +    return 0;
          149  +  }
   134    150     pi[0] = 0xdead1122;
   135    151     pi[1] = n;
   136    152     pi[k+2] = 0xdead3344;
   137    153     p = &pi[2];
   138    154     memcpy(p, oldP, n>oldN ? oldN : n);
   139    155     if( n>oldN ){
   140    156       memset(&((char*)p)[oldN], 0, n-oldN);
................................................................................
   147    163   #endif
   148    164     return p;
   149    165   }
   150    166   
   151    167   /*
   152    168   ** Make a duplicate of a string into memory obtained from malloc()
   153    169   ** Free the original string using sqliteFree().
          170  +**
          171  +** This routine is called on all strings that are passed outside of
          172  +** the SQLite library.  That way clients can free the string using free()
          173  +** rather than having to call sqliteFree().
   154    174   */
   155    175   void sqliteStrRealloc(char **pz){
   156    176     char *zNew;
   157    177     if( pz==0 || *pz==0 ) return;
   158    178     zNew = malloc( strlen(*pz) + 1 );
   159         -  if( zNew ) strcpy(zNew, *pz);
          179  +  if( zNew==0 ){
          180  +    sqlite_malloc_failed++;
          181  +    sqliteFree(*pz);
          182  +    *pz = 0;
          183  +  }
          184  +  strcpy(zNew, *pz);
   160    185     sqliteFree(*pz);
   161    186     *pz = zNew;
   162    187   }
   163    188   
   164    189   /*
   165    190   ** Make a copy of a string in memory obtained from sqliteMalloc()
   166    191   */
................................................................................
   187    212   
   188    213   /*
   189    214   ** Allocate new memory and set it to zero.  Return NULL if
   190    215   ** no memory is available.
   191    216   */
   192    217   void *sqliteMalloc(int n){
   193    218     void *p = malloc(n);
   194         -  if( p==0 ) return 0;
          219  +  if( p==0 ){
          220  +    sqlite_malloc_failed++;
          221  +    return 0;
          222  +  }
   195    223     memset(p, 0, n);
   196    224     return p;
   197    225   }
   198    226   
   199    227   /*
   200    228   ** Free memory previously obtained from sqliteMalloc()
   201    229   */
................................................................................
   214    242     if( p==0 ){
   215    243       return sqliteMalloc(n);
   216    244     }
   217    245     if( n==0 ){
   218    246       sqliteFree(p);
   219    247       return 0;
   220    248     }
   221         -  return realloc(p, n);
          249  +  p = realloc(p, n);
          250  +  if( p==0 ){
          251  +    sqlite_malloc_failed++;
          252  +  }
          253  +  return p;
   222    254   }
   223    255   
   224    256   /*
   225    257   ** Make a copy of a string in memory obtained from sqliteMalloc()
   226    258   */
   227    259   char *sqliteStrDup(const char *z){
   228    260     char *zNew = sqliteMalloc(strlen(z)+1);
................................................................................
   321    353   ** the quote characters.  The conversion is done in-place.  If the
   322    354   ** input does not begin with a quote character, then this routine
   323    355   ** is a no-op.
   324    356   */
   325    357   void sqliteDequote(char *z){
   326    358     int quote;
   327    359     int i, j;
          360  +  if( z==0 ) return;
   328    361     quote = z[0];
   329    362     if( quote!='\'' && quote!='"' ) return;
   330    363     for(i=1, j=0; z[i]; i++){
   331    364       if( z[i]==quote ){
   332    365         if( z[i+1]==quote ){
   333    366           z[j++] = quote;
   334    367           i++;

Changes to src/vdbe.c.

    37     37   ** inplicit conversion from one type to the other occurs as necessary.
    38     38   ** 
    39     39   ** Most of the code in this file is taken up by the sqliteVdbeExec()
    40     40   ** function which does the work of interpreting a VDBE program.
    41     41   ** But other routines are also provided to help in building up
    42     42   ** a program instruction by instruction.
    43     43   **
    44         -** $Id: vdbe.c,v 1.56 2001/04/05 15:57:13 drh Exp $
           44  +** $Id: vdbe.c,v 1.57 2001/04/11 14:28:43 drh Exp $
    45     45   */
    46     46   #include "sqliteInt.h"
    47     47   #include <unistd.h>
    48     48   #include <ctype.h>
    49     49   
    50     50   /*
    51     51   ** SQL is translated into a sequence of instructions to be
................................................................................
   219    219   };
   220    220   
   221    221   /*
   222    222   ** Create a new virtual database engine.
   223    223   */
   224    224   Vdbe *sqliteVdbeCreate(sqlite *db){
   225    225     Vdbe *p;
   226         -
   227    226     p = sqliteMalloc( sizeof(Vdbe) );
          227  +  if( p==0 ) return 0;
   228    228     p->pBe = db->pBe;
   229    229     p->db = db;
   230    230     return p;
   231    231   }
   232    232   
   233    233   /*
   234    234   ** Turn tracing on or off
................................................................................
   364    364   ** or a double quote character (ASCII 0x22).  Two quotes in a row
   365    365   ** resolve to be a single actual quote character within the string.
   366    366   */
   367    367   void sqliteVdbeDequoteP3(Vdbe *p, int addr){
   368    368     char *z;
   369    369     if( addr<0 || addr>=p->nOp ) return;
   370    370     z = p->aOp[addr].p3;
   371         -  sqliteDequote(z);
          371  +  if( z ) sqliteDequote(z);
   372    372   }
   373    373   
   374    374   /*
   375    375   ** On the P3 argument of the given instruction, change all
   376    376   ** strings of whitespace characters into a single space and
   377    377   ** delete leading and trailing whitespace.
   378    378   */
   379    379   void sqliteVdbeCompressSpace(Vdbe *p, int addr){
   380    380     char *z;
   381    381     int i, j;
   382    382     if( addr<0 || addr>=p->nOp ) return;
   383    383     z = p->aOp[addr].p3;
          384  +  if( z==0 ) return;
   384    385     i = j = 0;
   385    386     while( isspace(z[i]) ){ i++; }
   386    387     while( z[i] ){
   387    388       if( isspace(z[i]) ){
   388    389         z[j++] = ' ';
   389    390         while( isspace(z[++i]) ){}
   390    391       }else{
................................................................................
   458    459   */
   459    460   static void AggRehash(Agg *p, int nHash){
   460    461     int size;
   461    462     AggElem *pElem;
   462    463     if( p->nHash==nHash ) return;
   463    464     size = nHash * sizeof(AggElem*);
   464    465     p->apHash = sqliteRealloc(p->apHash, size );
          466  +  if( p->apHash==0 ){
          467  +    AggReset(p);
          468  +    return;
          469  +  }
   465    470     memset(p->apHash, 0, size);
   466    471     p->nHash = nHash;
   467    472     for(pElem=p->pFirst; pElem; pElem=pElem->pNext){
   468    473       AggEnhash(p, pElem);
   469    474     }
   470    475   }
   471    476   
................................................................................
   530    535   static void SetInsert(Set *p, char *zKey){
   531    536     SetElem *pElem;
   532    537     int h = sqliteHashNoCase(zKey, 0) % ArraySize(p->apHash);
   533    538     for(pElem=p->apHash[h]; pElem; pElem=pElem->pHash){
   534    539       if( strcmp(pElem->zKey, zKey)==0 ) return;
   535    540     }
   536    541     pElem = sqliteMalloc( sizeof(*pElem) + strlen(zKey) );
   537         -  if( pElem==0 ) return;
          542  +  if( pElem==0 ){
          543  +    SetClear(p);
          544  +    return;
          545  +  }
   538    546     strcpy(pElem->zKey, zKey);
   539    547     pElem->pNext = p->pAll;
   540    548     p->pAll = pElem;
   541    549     pElem->pHash = p->apHash[h];
   542    550     p->apHash[h] = pElem;
   543    551   }
   544    552   
................................................................................
  1000   1008     rc = SQLITE_OK;
  1001   1009   #ifdef MEMORY_DEBUG
  1002   1010     if( access("vdbe_trace",0)==0 ){
  1003   1011       p->trace = stderr;
  1004   1012     }
  1005   1013   #endif
  1006   1014     /* if( pzErrMsg ){ *pzErrMsg = 0; } */
         1015  +  if( sqlite_malloc_failed ) rc = SQLITE_NOMEM;
  1007   1016     for(pc=0; rc==SQLITE_OK && pc<p->nOp VERIFY(&& pc>=0); pc++){
  1008   1017       pOp = &p->aOp[pc];
  1009   1018   
  1010   1019       /* Interrupt processing if requested.
  1011   1020       */
  1012   1021       if( db->flags & SQLITE_Interrupt ){
  1013   1022         db->flags &= ~SQLITE_Interrupt;
................................................................................
  1360   1369           }else if( (ft & fn & STK_Int)==STK_Int ){
  1361   1370             copy = aStack[nos].i<aStack[tos].i;
  1362   1371           }else if( ( (ft|fn) & (STK_Int|STK_Real) ) !=0 ){
  1363   1372             Realify(p, tos);
  1364   1373             Realify(p, nos);
  1365   1374             copy = aStack[tos].r>aStack[nos].r;
  1366   1375           }else{
  1367         -          Stringify(p, tos);
  1368         -          Stringify(p, nos);
         1376  +          if( Stringify(p, tos) || Stringify(p, nos) ) goto no_mem;
  1369   1377             copy = sqliteCompare(zStack[tos],zStack[nos])>0;
  1370   1378           }
  1371   1379           if( copy ){
  1372   1380             Release(p, nos);
  1373   1381             aStack[nos] = aStack[tos];
  1374   1382             zStack[nos] = zStack[tos];
  1375   1383             zStack[tos] = 0;
................................................................................
  1401   1409           }else if( (ft & fn & STK_Int)==STK_Int ){
  1402   1410             copy = aStack[nos].i>aStack[tos].i;
  1403   1411           }else if( ( (ft|fn) & (STK_Int|STK_Real) ) !=0 ){
  1404   1412             Realify(p, tos);
  1405   1413             Realify(p, nos);
  1406   1414             copy = aStack[tos].r<aStack[nos].r;
  1407   1415           }else{
  1408         -          Stringify(p, tos);
  1409         -          Stringify(p, nos);
         1416  +          if( Stringify(p, tos) || Stringify(p, nos) ) goto no_mem;
  1410   1417             copy = sqliteCompare(zStack[tos],zStack[nos])<0;
  1411   1418           }
  1412   1419           if( copy ){
  1413   1420             Release(p, nos);
  1414   1421             aStack[nos] = aStack[tos];
  1415   1422             zStack[nos] = zStack[tos];
  1416   1423             zStack[tos] = 0;
................................................................................
  1481   1488           int ft, fn;
  1482   1489           VERIFY( if( nos<0 ) goto not_enough_stack; )
  1483   1490           ft = aStack[tos].flags;
  1484   1491           fn = aStack[nos].flags;
  1485   1492           if( (ft & fn)==STK_Int ){
  1486   1493             c = aStack[nos].i - aStack[tos].i;
  1487   1494           }else{
  1488         -          Stringify(p, tos);
  1489         -          Stringify(p, nos);
         1495  +          if( Stringify(p, tos) || Stringify(p, nos) ) goto no_mem;
  1490   1496             c = sqliteCompare(zStack[nos], zStack[tos]);
  1491   1497           }
  1492   1498           switch( pOp->opcode ){
  1493   1499             case OP_Eq:    c = c==0;     break;
  1494   1500             case OP_Ne:    c = c!=0;     break;
  1495   1501             case OP_Lt:    c = c<0;      break;
  1496   1502             case OP_Le:    c = c<=0;     break;
................................................................................
  1519   1525         ** are different.
  1520   1526         */
  1521   1527         case OP_Like: {
  1522   1528           int tos = p->tos;
  1523   1529           int nos = tos - 1;
  1524   1530           int c;
  1525   1531           VERIFY( if( nos<0 ) goto not_enough_stack; )
  1526         -        Stringify(p, tos);
  1527         -        Stringify(p, nos);
         1532  +        if( Stringify(p, tos) || Stringify(p, nos) ) goto no_mem;
  1528   1533           c = sqliteLikeCompare(zStack[tos], zStack[nos]);
  1529   1534           POPSTACK;
  1530   1535           POPSTACK;
  1531   1536           if( pOp->p1 ) c = !c;
  1532   1537           if( c ) pc = pOp->p2-1;
  1533   1538           break;
  1534   1539         }
................................................................................
  1552   1557         ** are different.
  1553   1558         */
  1554   1559         case OP_Glob: {
  1555   1560           int tos = p->tos;
  1556   1561           int nos = tos - 1;
  1557   1562           int c;
  1558   1563           VERIFY( if( nos<0 ) goto not_enough_stack; )
  1559         -        Stringify(p, tos);
  1560         -        Stringify(p, nos);
         1564  +        if( Stringify(p, tos) || Stringify(p, nos) ) goto no_mem;
  1561   1565           c = sqliteGlobCompare(zStack[tos], zStack[nos]);
  1562   1566           POPSTACK;
  1563   1567           POPSTACK;
  1564   1568           if( pOp->p1 ) c = !c;
  1565   1569           if( c ) pc = pOp->p2-1;
  1566   1570           break;
  1567   1571         }
................................................................................
  3066   3070         case OP_AggFocus: {
  3067   3071           int tos = p->tos;
  3068   3072           AggElem *pElem;
  3069   3073           char *zKey;
  3070   3074           int nKey;
  3071   3075   
  3072   3076           VERIFY( if( tos<0 ) goto not_enough_stack; )
  3073         -        Stringify(p, tos);
         3077  +        if( Stringify(p, tos) ) goto no_mem;
  3074   3078           zKey = zStack[tos]; 
  3075   3079           nKey = aStack[tos].n;
  3076   3080           if( p->agg.nHash<=0 ){
  3077   3081             pElem = 0;
  3078   3082           }else{
  3079   3083             int h = sqliteHashNoCase(zKey, nKey-1) % p->agg.nHash;
  3080   3084             for(pElem=p->agg.apHash[h]; pElem; pElem=pElem->pHash){
................................................................................
  3082   3086             }
  3083   3087           }
  3084   3088           if( pElem ){
  3085   3089             p->agg.pCurrent = pElem;
  3086   3090             pc = pOp->p2 - 1;
  3087   3091           }else{
  3088   3092             AggInsert(&p->agg, zKey);
         3093  +          if( sqlite_malloc_failed ) goto no_mem;
  3089   3094           }
  3090   3095           POPSTACK;
  3091   3096           break; 
  3092   3097         }
  3093   3098   
  3094   3099         /* Opcode: AggIncr P1 P2 *
  3095   3100         **
................................................................................
  3237   3242             p->nSet = i+1;
  3238   3243           }
  3239   3244           if( pOp->p3 ){
  3240   3245             SetInsert(&p->aSet[i], pOp->p3);
  3241   3246           }else{
  3242   3247             int tos = p->tos;
  3243   3248             if( tos<0 ) goto not_enough_stack;
  3244         -          Stringify(p, tos);
         3249  +          if( Stringify(p, tos) ) goto no_mem;
  3245   3250             SetInsert(&p->aSet[i], zStack[tos]);
  3246   3251             POPSTACK;
  3247   3252           }
         3253  +        if( sqlite_malloc_failed ) goto no_mem;
  3248   3254           break;
  3249   3255         }
  3250   3256   
  3251   3257         /* Opcode: SetFound P1 P2 *
  3252   3258         **
  3253   3259         ** Pop the stack once and compare the value popped off with the
  3254   3260         ** contents of set P1.  If the element popped exists in set P1,
  3255   3261         ** then jump to P2.  Otherwise fall through.
  3256   3262         */
  3257   3263         case OP_SetFound: {
  3258   3264           int i = pOp->p1;
  3259   3265           int tos = p->tos;
  3260   3266           VERIFY( if( tos<0 ) goto not_enough_stack; )
  3261         -        Stringify(p, tos);
         3267  +        if( Stringify(p, tos) ) goto no_mem;
  3262   3268           if( VERIFY( i>=0 && i<p->nSet &&) SetTest(&p->aSet[i], zStack[tos])){
  3263   3269             pc = pOp->p2 - 1;
  3264   3270           }
  3265   3271           POPSTACK;
  3266   3272           break;
  3267   3273         }
  3268   3274   
................................................................................
  3272   3278         ** contents of set P1.  If the element popped does not exists in 
  3273   3279         ** set P1, then jump to P2.  Otherwise fall through.
  3274   3280         */
  3275   3281         case OP_SetNotFound: {
  3276   3282           int i = pOp->p1;
  3277   3283           int tos = p->tos;
  3278   3284           VERIFY( if( tos<0 ) goto not_enough_stack; )
  3279         -        Stringify(p, tos);
         3285  +        if( Stringify(p, tos) ) goto no_mem;
  3280   3286           if(VERIFY( i>=0 && i<p->nSet &&) !SetTest(&p->aSet[i], zStack[tos])){
  3281   3287             pc = pOp->p2 - 1;
  3282   3288           }
  3283   3289           POPSTACK;
  3284   3290           break;
  3285   3291         }
  3286   3292   
................................................................................
  3289   3295         ** Interpret the top of the stack as a string.  Replace the top of
  3290   3296         ** stack with an integer which is the length of the string.
  3291   3297         */
  3292   3298         case OP_Strlen: {
  3293   3299           int tos = p->tos;
  3294   3300           int len;
  3295   3301           VERIFY( if( tos<0 ) goto not_enough_stack; )
  3296         -        Stringify(p, tos);
         3302  +        if( Stringify(p, tos) ) goto no_mem;
  3297   3303   #ifdef SQLITE_UTF8
  3298   3304           {
  3299   3305             char *z = zStack[tos];
  3300   3306             for(len=0; *z; z++){ if( (0xc0&*z)!=0x80 ) len++; }
  3301   3307           }
  3302   3308   #else
  3303   3309           len = aStack[tos].n-1;
................................................................................
  3347   3353             Integerify(p, p->tos);
  3348   3354             start = aStack[p->tos].i - 1;
  3349   3355             POPSTACK;
  3350   3356           }else{
  3351   3357             start = pOp->p1 - 1;
  3352   3358           }
  3353   3359           VERIFY( if( p->tos<0 ) goto not_enough_stack; )
  3354         -        Stringify(p, p->tos);
         3360  +        if( Stringify(p, p->tos) ) goto no_mem;
  3355   3361   
  3356   3362           /* "n" will be the number of characters in the input string.
  3357   3363           ** For iso8859, the number of characters is the number of bytes.
  3358   3364           ** Buf for UTF-8, some characters can use multiple bytes and the
  3359   3365           ** situation is more complex. 
  3360   3366           */
  3361   3367   #ifdef SQLITE_UTF8

Changes to src/where.c.

    21     21   **   http://www.hwaci.com/drh/
    22     22   **
    23     23   *************************************************************************
    24     24   ** This module contains C code that generates VDBE code used to process
    25     25   ** the WHERE clause of SQL statements.  Also found here are subroutines
    26     26   ** to generate VDBE code to evaluate expressions.
    27     27   **
    28         -** $Id: where.c,v 1.13 2001/04/04 11:48:58 drh Exp $
           28  +** $Id: where.c,v 1.14 2001/04/11 14:28:43 drh Exp $
    29     29   */
    30     30   #include "sqliteInt.h"
    31     31   
    32     32   /*
    33     33   ** The query generator uses an array of instances of this structure to
    34     34   ** help it analyze the subexpressions of the WHERE clause.  Each WHERE
    35     35   ** clause subexpression is separated from the others by an AND operator.
................................................................................
   166    166     /* Allocate space for aOrder[]. */
   167    167     aOrder = sqliteMalloc( sizeof(int) * pTabList->nId );
   168    168   
   169    169     /* Allocate and initialize the WhereInfo structure that will become the
   170    170     ** return value.
   171    171     */
   172    172     pWInfo = sqliteMalloc( sizeof(WhereInfo) );
   173         -  if( pWInfo==0 ){
          173  +  if( sqlite_malloc_failed ){
   174    174       sqliteFree(aOrder);
          175  +    sqliteFree(pWInfo);
   175    176       return 0;
   176    177     }
   177    178     pWInfo->pParse = pParse;
   178    179     pWInfo->pTabList = pTabList;
   179    180     base = pWInfo->base = pParse->nTab;
   180    181   
   181    182     /* Split the WHERE clause into as many as 32 separate subexpressions

Changes to test/all.test.

    18     18   # Author contact information:
    19     19   #   drh@hwaci.com
    20     20   #   http://www.hwaci.com/drh/
    21     21   #
    22     22   #***********************************************************************
    23     23   # This file runs all tests.
    24     24   #
    25         -# $Id: all.test,v 1.5 2000/12/10 18:23:51 drh Exp $
           25  +# $Id: all.test,v 1.6 2001/04/11 14:28:43 drh Exp $
    26     26   
    27     27   set testdir [file dirname $argv0]
    28     28   source $testdir/tester.tcl
    29     29   rename finish_test really_finish_test
    30     30   proc finish_test {} {memleak_check}
    31     31   
    32     32   if {[file exists ./sqlite_test_count]} {
................................................................................
    49     49   
    50     50   
    51     51   for {set Counter 0} {$Counter<$COUNT} {incr Counter} {
    52     52     foreach p $PREFIXES {
    53     53       set dbprefix $p
    54     54       foreach testfile [lsort -dictionary [glob $testdir/*.test]] {
    55     55         if {[file tail $testfile]=="all.test"} continue
           56  +      if {[file tail $testfile]=="malloc.test"} continue
    56     57         source $testfile
    57     58       }
    58     59     }
    59     60     if {[info exists Leak]} {
    60     61       lappend LeakList $Leak
    61     62     }
    62     63   }
................................................................................
    74     75          puts "     Got: $LeakList"
    75     76          incr ::nErr
    76     77          break
    77     78       }
    78     79     }
    79     80     puts " Ok"
    80     81   }
           82  +
           83  +if {[file readable $testdir/malloc.test]} {
           84  +  for {set Counter 0} {$Counter<$COUNT} {incr Counter} {
           85  +    foreach p $PREFIXES {
           86  +      set dbprefix $p
           87  +      source $testdir/malloc.test
           88  +    }
           89  +  }
           90  +}
    81     91   
    82     92   really_finish_test

Changes to test/printf.test.

    19     19   #   drh@hwaci.com
    20     20   #   http://www.hwaci.com/drh/
    21     21   #
    22     22   #***********************************************************************
    23     23   # This file implements regression tests for SQLite library.  The
    24     24   # focus of this file is testing the sqlite_*_printf() interface.
    25     25   #
    26         -# $Id: printf.test,v 1.1 2001/04/07 15:24:33 drh Exp $
           26  +# $Id: printf.test,v 1.2 2001/04/11 14:28:43 drh Exp $
    27     27   
    28     28   set testdir [file dirname $argv0]
    29     29   source $testdir/tester.tcl
    30     30   
    31     31   set n 1
    32     32   foreach v {1 2 5 10 99 100 1000000 999999999 0 -1 -2 -5 -10 -99 -100 -9999999} {
    33     33     do_test printf-1.$n.1 [subst {
................................................................................
    35     35     }] [format {Three integers: %d %x %o} $v $v $v]
    36     36     do_test printf-1.$n.2 [subst {
    37     37       sqlite_mprintf_int {Three integers: (%6d) (%6x) (%6o)} $v $v $v
    38     38     }] [format {Three integers: (%6d) (%6x) (%6o)} $v $v $v]
    39     39     do_test printf-1.$n.3 [subst {
    40     40       sqlite_mprintf_int {Three integers: (%-6d) (%-6x) (%-6o)} $v $v $v
    41     41     }] [format {Three integers: (%-6d) (%-6x) (%-6o)} $v $v $v]
           42  +  do_test printf-1.$n.4 [subst {
           43  +    sqlite_mprintf_int {Three integers: (%+6d) (%+6x) (%+6o)} $v $v $v
           44  +  }] [format {Three integers: (%+6d) (%+6x) (%+6o)} $v $v $v]
           45  +  do_test printf-1.$n.5 [subst {
           46  +    sqlite_mprintf_int {Three integers: (%06d) (%06x) (%06o)} $v $v $v
           47  +  }] [format {Three integers: (%06d) (%06x) (%06o)} $v $v $v]
           48  +  do_test printf-1.$n.6 [subst {
           49  +    sqlite_mprintf_int {Three integers: (% 6d) (% 6x) (% 6o)} $v $v $v
           50  +  }] [format {Three integers: (% 6d) (% 6x) (% 6o)} $v $v $v]
    42     51     incr n
    43     52   }
    44     53   
    45     54   set m 1
    46     55   foreach {a b} {1 1 5 5 10 10 10 5} {
    47     56     set n 1
    48     57     foreach x {0.001 1.0e-20 1.0 0.0 100.0 9.99999 -0.00543 -1.0 -99.99999} {
................................................................................
    85     94     sqlite_mprintf_str {%d %d A String: (%-30s)} 1 2 {This is the string}
    86     95   } [format {%d %d A String: (%-30s)} 1 2 {This is the string}]
    87     96   
    88     97   do_test printf-4.1 {
    89     98     sqlite_mprintf_str {%d %d A quoted string: '%q'} 1 2 {Hi Y'all}
    90     99   } {1 2 A quoted string: 'Hi Y''all'}
    91    100   
          101  +do_test printf-5.1 {
          102  +  set x [sqlite_mprintf_str {%d %d %100000s} 0 0 {Hello}]
          103  +  string length $x
          104  +} {994}
          105  +do_test printf-5.2 {
          106  +  sqlite_mprintf_str {%d %d (%-10.10s) %} -9 -10 {HelloHelloHello}
          107  +} {-9 -10 (HelloHello) %}
          108  +do_test printf-5.3 {
          109  +  sqlite_mprintf_str {%% %d %d (%=10s)} 5 6 Hello
          110  +} {% 5 6 (  Hello   )}
          111  +
    92    112   finish_test

Changes to test/tableapi.test.

    20     20   #   http://www.hwaci.com/drh/
    21     21   #
    22     22   #***********************************************************************
    23     23   # This file implements regression tests for SQLite library.  The
    24     24   # focus of this file is testing the sqlite_exec_printf() and
    25     25   # sqlite_get_table_printf() APIs.
    26     26   #
    27         -# $Id: tableapi.test,v 1.1 2001/04/07 15:24:34 drh Exp $
           27  +# $Id: tableapi.test,v 1.2 2001/04/11 14:28:43 drh Exp $
    28     28   
    29     29   set testdir [file dirname $argv0]
    30     30   source $testdir/tester.tcl
    31     31   
    32     32   do_test tableapi-1.0 {
    33     33     set ::dbx [sqlite_open testdb]
    34     34     catch {sqlite_exec_printf $::dbx {DROP TABLE xyz} {}}
................................................................................
    44     44   } {0 {a b 1 {Hi Y'all}}}
    45     45   
    46     46   do_test tableapi-2.1 {
    47     47     sqlite_get_table_printf $::dbx {
    48     48       SELECT * FROM xyz WHERE b='%q'
    49     49     } {Hi Y'all}
    50     50   } {0 1 2 a b 1 {Hi Y'all}}
           51  +do_test tableapi-2.2 {
           52  +  sqlite_get_table_printf $::dbx {
           53  +    SELECT * FROM xyz
           54  +  } {}
           55  +} {0 1 2 a b 1 {Hi Y'all}}
           56  +do_test tableapi-2.3 {
           57  +  for {set i 2} {$i<=50} {incr i} {
           58  +    sqlite_get_table_printf $::dbx \
           59  +       "INSERT INTO xyz VALUES($i,'(%s)')" $i
           60  +  }
           61  +  sqlite_get_table_printf $::dbx {
           62  +    SELECT * FROM xyz ORDER BY a
           63  +  } {}
           64  +} {0 50 2 a b 1 {Hi Y'all} 2 (2) 3 (3) 4 (4) 5 (5) 6 (6) 7 (7) 8 (8) 9 (9) 10 (10) 11 (11) 12 (12) 13 (13) 14 (14) 15 (15) 16 (16) 17 (17) 18 (18) 19 (19) 20 (20) 21 (21) 22 (22) 23 (23) 24 (24) 25 (25) 26 (26) 27 (27) 28 (28) 29 (29) 30 (30) 31 (31) 32 (32) 33 (33) 34 (34) 35 (35) 36 (36) 37 (37) 38 (38) 39 (39) 40 (40) 41 (41) 42 (42) 43 (43) 44 (44) 45 (45) 46 (46) 47 (47) 48 (48) 49 (49) 50 (50)}
           65  +do_test tableapi-2.3.1 {
           66  +  sqlite_get_table_printf $::dbx {
           67  +    SELECT * FROM xyz  WHERE a>49 ORDER BY a
           68  +  } {}
           69  +} {0 1 2 a b 50 (50)}
           70  +do_test tableapi-2.3.2 {
           71  +  sqlite_get_table_printf $::dbx {
           72  +    SELECT * FROM xyz WHERE a>47 ORDER BY a
           73  +  } {}
           74  +} {0 3 2 a b 48 (48) 49 (49) 50 (50)}
           75  +do_test tableapi-2.4 {
           76  +  set ::big_str [sqlite_mprintf_str {%500'* Hello %500'*} 0 0 {}]
           77  +  sqlite_get_table_printf $::dbx {
           78  +    INSERT INTO xyz VALUES(51,'%q')
           79  +  } $::big_str
           80  +} {0 0 0}
           81  +do_test tableapi-2.5 {
           82  +  sqlite_get_table_printf $::dbx {
           83  +    SELECT * FROM xyz WHERE a>49 ORDER BY a;
           84  +  } {}
           85  +} "0 2 2 a b 50 (50) 51 \173$::big_str\175"
           86  +do_test tableapi-2.6 {
           87  +  sqlite_get_table_printf $::dbx {
           88  +    INSERT INTO xyz VALUES(52,NULL)
           89  +  } {}
           90  +  sqlite_get_table_printf $::dbx {
           91  +    SELECT * FROM xyz WHERE a IN (42,50,52) ORDER BY a DESC
           92  +  } {}
           93  +} {0 3 2 a b 52 NULL 50 (50) 42 (42)}
    51     94   
    52     95   do_test tableapi-99.0 {
    53     96     sqlite_close $::dbx
    54     97   } {}
    55     98   
    56     99   finish_test

Changes to test/tester.tcl.

    19     19   #   drh@hwaci.com
    20     20   #   http://www.hwaci.com/drh/
    21     21   #
    22     22   #***********************************************************************
    23     23   # This file implements some common TCL routines used for regression
    24     24   # testing the SQLite library
    25     25   #
    26         -# $Id: tester.tcl,v 1.14 2001/04/06 16:13:43 drh Exp $
           26  +# $Id: tester.tcl,v 1.15 2001/04/11 14:28:43 drh Exp $
    27     27   
    28     28   # Make sure tclsqlite was compiled correctly.  Abort now with an
    29     29   # error message if not.
    30     30   #
    31     31   if {[sqlite -tcl-uses-utf]} {
    32     32     if {"\u1234"=="u1234"} {
    33     33       puts stderr "***** BUILD PROBLEM *****"
................................................................................
   179    179         set ::skip_test 0
   180    180         return
   181    181       }
   182    182     }
   183    183     set ::skip_test 1
   184    184   }
   185    185   
   186         -# The procedure uses the special "--malloc-stats--" macro of SQLite
          186  +# The procedure uses the special "sqlite_malloc_stat" command
   187    187   # (which is only available if SQLite is compiled with -DMEMORY_DEBUG=1)
   188    188   # to see how many malloc()s have not been free()ed.  The number
   189    189   # of surplus malloc()s is stored in the global variable $::Leak.
   190    190   # If the value in $::Leak grows, it may mean there is a memory leak
   191    191   # in the library.
   192    192   #
   193    193   proc memleak_check {} {
   194         -  set r [execsql {--malloc-stats--}]
   195         -  if {$r==""} return
   196         -  set ::Leak [expr {[lindex $r 0]-[lindex $r 1]}]
   197         -  # puts "*** $::Leak mallocs have not been freed ***"
          194  +  if {[info command sqlite_malloc_stat]!=""} {
          195  +    set r [sqlite_malloc_stat]
          196  +    set ::Leak [expr {[lindex $r 0]-[lindex $r 1]}]
          197  +  }
   198    198   }
   199    199   
   200    200   # Run this routine last
   201    201   #
   202    202   proc finish_test {} {
   203    203     global nTest nErr nProb
   204    204     memleak_check

Changes to www/changes.tcl.

    13     13   
    14     14   
    15     15   proc chng {date desc} {
    16     16     puts "<DT><B>$date</B></DT>"
    17     17     puts "<DD><P><UL>$desc</UL></P></DD>"
    18     18   }
    19     19   
    20         -chng {2001 Apr 6 (1.0.31)} {
           20  +chng {2001 Apr 11 (1.0.31)} {
           21  +<li>More robust handling of out-of-memory errors.</li>
    21     22   <li>New tests added to the test suite.</li>
    22     23   }
    23     24   
    24     25   chng {2001 Apr 6 (1.0.30)} {
    25     26   <li>Remove the <b>sqlite_encoding</b> TCL variable that was introduced
    26     27       in the previous version.</li>
    27     28   <li>Add options <b>-encoding</b> and <b>-tcl-uses-utf</b> to the