extensions/sqlite/sqlite-source/alter.c
author Asher Baker <asherkin@gmail.com>
Thu Apr 26 16:58:18 2012 +0100 (2012-04-26)
changeset 3488 bee90c8ef6c3
parent 1952 b7aa2b626807
permissions -rw-r--r--
Fixed client serials not being unique on Windows (bug 5285, r=psychonic).
ds@1952
     1
/*
ds@1952
     2
** 2005 February 15
ds@1952
     3
**
ds@1952
     4
** The author disclaims copyright to this source code.  In place of
ds@1952
     5
** a legal notice, here is a blessing:
ds@1952
     6
**
ds@1952
     7
**    May you do good and not evil.
ds@1952
     8
**    May you find forgiveness for yourself and forgive others.
ds@1952
     9
**    May you share freely, never taking more than you give.
ds@1952
    10
**
ds@1952
    11
*************************************************************************
ds@1952
    12
** This file contains C code routines that used to generate VDBE code
ds@1952
    13
** that implements the ALTER TABLE command.
ds@1952
    14
**
ds@1952
    15
** $Id$
ds@1952
    16
*/
ds@1952
    17
#include "sqliteInt.h"
ds@1952
    18
#include <ctype.h>
ds@1952
    19
ds@1952
    20
/*
ds@1952
    21
** The code in this file only exists if we are not omitting the
ds@1952
    22
** ALTER TABLE logic from the build.
ds@1952
    23
*/
ds@1952
    24
#ifndef SQLITE_OMIT_ALTERTABLE
ds@1952
    25
ds@1952
    26
ds@1952
    27
/*
ds@1952
    28
** This function is used by SQL generated to implement the 
ds@1952
    29
** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
ds@1952
    30
** CREATE INDEX command. The second is a table name. The table name in 
ds@1952
    31
** the CREATE TABLE or CREATE INDEX statement is replaced with the third
ds@1952
    32
** argument and the result returned. Examples:
ds@1952
    33
**
ds@1952
    34
** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
ds@1952
    35
**     -> 'CREATE TABLE def(a, b, c)'
ds@1952
    36
**
ds@1952
    37
** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
ds@1952
    38
**     -> 'CREATE INDEX i ON def(a, b, c)'
ds@1952
    39
*/
ds@1952
    40
static void renameTableFunc(
ds@1952
    41
  sqlite3_context *context,
ds@1952
    42
  int argc,
ds@1952
    43
  sqlite3_value **argv
ds@1952
    44
){
ds@1952
    45
  unsigned char const *zSql = sqlite3_value_text(argv[0]);
ds@1952
    46
  unsigned char const *zTableName = sqlite3_value_text(argv[1]);
ds@1952
    47
ds@1952
    48
  int token;
ds@1952
    49
  Token tname;
ds@1952
    50
  unsigned char const *zCsr = zSql;
ds@1952
    51
  int len = 0;
ds@1952
    52
  char *zRet;
ds@1952
    53
ds@1952
    54
  sqlite3 *db = sqlite3_user_data(context);
ds@1952
    55
ds@1952
    56
  /* The principle used to locate the table name in the CREATE TABLE 
ds@1952
    57
  ** statement is that the table name is the first token that is immediatedly
ds@1952
    58
  ** followed by a left parenthesis - TK_LP - or "USING" TK_USING.
ds@1952
    59
  */
ds@1952
    60
  if( zSql ){
ds@1952
    61
    do {
ds@1952
    62
      if( !*zCsr ){
ds@1952
    63
        /* Ran out of input before finding an opening bracket. Return NULL. */
ds@1952
    64
        return;
ds@1952
    65
      }
ds@1952
    66
ds@1952
    67
      /* Store the token that zCsr points to in tname. */
ds@1952
    68
      tname.z = zCsr;
ds@1952
    69
      tname.n = len;
ds@1952
    70
ds@1952
    71
      /* Advance zCsr to the next token. Store that token type in 'token',
ds@1952
    72
      ** and it's length in 'len' (to be used next iteration of this loop).
ds@1952
    73
      */
ds@1952
    74
      do {
ds@1952
    75
        zCsr += len;
ds@1952
    76
        len = sqlite3GetToken(zCsr, &token);
ds@1952
    77
      } while( token==TK_SPACE );
ds@1952
    78
      assert( len>0 );
ds@1952
    79
    } while( token!=TK_LP && token!=TK_USING );
ds@1952
    80
ds@1952
    81
    zRet = sqlite3MPrintf(db, "%.*s%Q%s", tname.z - zSql, zSql, 
ds@1952
    82
       zTableName, tname.z+tname.n);
ds@1952
    83
    sqlite3_result_text(context, zRet, -1, sqlite3_free);
ds@1952
    84
  }
ds@1952
    85
}
ds@1952
    86
ds@1952
    87
#ifndef SQLITE_OMIT_TRIGGER
ds@1952
    88
/* This function is used by SQL generated to implement the
ds@1952
    89
** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER 
ds@1952
    90
** statement. The second is a table name. The table name in the CREATE 
ds@1952
    91
** TRIGGER statement is replaced with the third argument and the result 
ds@1952
    92
** returned. This is analagous to renameTableFunc() above, except for CREATE
ds@1952
    93
** TRIGGER, not CREATE INDEX and CREATE TABLE.
ds@1952
    94
*/
ds@1952
    95
static void renameTriggerFunc(
ds@1952
    96
  sqlite3_context *context,
ds@1952
    97
  int argc,
ds@1952
    98
  sqlite3_value **argv
ds@1952
    99
){
ds@1952
   100
  unsigned char const *zSql = sqlite3_value_text(argv[0]);
ds@1952
   101
  unsigned char const *zTableName = sqlite3_value_text(argv[1]);
ds@1952
   102
ds@1952
   103
  int token;
ds@1952
   104
  Token tname;
ds@1952
   105
  int dist = 3;
ds@1952
   106
  unsigned char const *zCsr = zSql;
ds@1952
   107
  int len = 0;
ds@1952
   108
  char *zRet;
ds@1952
   109
ds@1952
   110
  sqlite3 *db = sqlite3_user_data(context);
ds@1952
   111
ds@1952
   112
  /* The principle used to locate the table name in the CREATE TRIGGER 
ds@1952
   113
  ** statement is that the table name is the first token that is immediatedly
ds@1952
   114
  ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
ds@1952
   115
  ** of TK_WHEN, TK_BEGIN or TK_FOR.
ds@1952
   116
  */
ds@1952
   117
  if( zSql ){
ds@1952
   118
    do {
ds@1952
   119
ds@1952
   120
      if( !*zCsr ){
ds@1952
   121
        /* Ran out of input before finding the table name. Return NULL. */
ds@1952
   122
        return;
ds@1952
   123
      }
ds@1952
   124
ds@1952
   125
      /* Store the token that zCsr points to in tname. */
ds@1952
   126
      tname.z = zCsr;
ds@1952
   127
      tname.n = len;
ds@1952
   128
ds@1952
   129
      /* Advance zCsr to the next token. Store that token type in 'token',
ds@1952
   130
      ** and it's length in 'len' (to be used next iteration of this loop).
ds@1952
   131
      */
ds@1952
   132
      do {
ds@1952
   133
        zCsr += len;
ds@1952
   134
        len = sqlite3GetToken(zCsr, &token);
ds@1952
   135
      }while( token==TK_SPACE );
ds@1952
   136
      assert( len>0 );
ds@1952
   137
ds@1952
   138
      /* Variable 'dist' stores the number of tokens read since the most
ds@1952
   139
      ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN 
ds@1952
   140
      ** token is read and 'dist' equals 2, the condition stated above
ds@1952
   141
      ** to be met.
ds@1952
   142
      **
ds@1952
   143
      ** Note that ON cannot be a database, table or column name, so
ds@1952
   144
      ** there is no need to worry about syntax like 
ds@1952
   145
      ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
ds@1952
   146
      */
ds@1952
   147
      dist++;
ds@1952
   148
      if( token==TK_DOT || token==TK_ON ){
ds@1952
   149
        dist = 0;
ds@1952
   150
      }
ds@1952
   151
    } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
ds@1952
   152
ds@1952
   153
    /* Variable tname now contains the token that is the old table-name
ds@1952
   154
    ** in the CREATE TRIGGER statement.
ds@1952
   155
    */
ds@1952
   156
    zRet = sqlite3MPrintf(db, "%.*s%Q%s", tname.z - zSql, zSql, 
ds@1952
   157
       zTableName, tname.z+tname.n);
ds@1952
   158
    sqlite3_result_text(context, zRet, -1, sqlite3_free);
ds@1952
   159
  }
ds@1952
   160
}
ds@1952
   161
#endif   /* !SQLITE_OMIT_TRIGGER */
ds@1952
   162
ds@1952
   163
/*
ds@1952
   164
** Register built-in functions used to help implement ALTER TABLE
ds@1952
   165
*/
ds@1952
   166
void sqlite3AlterFunctions(sqlite3 *db){
ds@1952
   167
  static const struct {
ds@1952
   168
     char *zName;
ds@1952
   169
     signed char nArg;
ds@1952
   170
     void (*xFunc)(sqlite3_context*,int,sqlite3_value **);
ds@1952
   171
  } aFuncs[] = {
ds@1952
   172
    { "sqlite_rename_table",    2, renameTableFunc},
ds@1952
   173
#ifndef SQLITE_OMIT_TRIGGER
ds@1952
   174
    { "sqlite_rename_trigger",  2, renameTriggerFunc},
ds@1952
   175
#endif
ds@1952
   176
  };
ds@1952
   177
  int i;
ds@1952
   178
ds@1952
   179
  for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
ds@1952
   180
    sqlite3CreateFunc(db, aFuncs[i].zName, aFuncs[i].nArg,
ds@1952
   181
        SQLITE_UTF8, (void *)db, aFuncs[i].xFunc, 0, 0);
ds@1952
   182
  }
ds@1952
   183
}
ds@1952
   184
ds@1952
   185
/*
ds@1952
   186
** Generate the text of a WHERE expression which can be used to select all
ds@1952
   187
** temporary triggers on table pTab from the sqlite_temp_master table. If
ds@1952
   188
** table pTab has no temporary triggers, or is itself stored in the 
ds@1952
   189
** temporary database, NULL is returned.
ds@1952
   190
*/
ds@1952
   191
static char *whereTempTriggers(Parse *pParse, Table *pTab){
ds@1952
   192
  Trigger *pTrig;
ds@1952
   193
  char *zWhere = 0;
ds@1952
   194
  char *tmp = 0;
ds@1952
   195
  const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
ds@1952
   196
ds@1952
   197
  /* If the table is not located in the temp-db (in which case NULL is 
ds@1952
   198
  ** returned, loop through the tables list of triggers. For each trigger
ds@1952
   199
  ** that is not part of the temp-db schema, add a clause to the WHERE 
ds@1952
   200
  ** expression being built up in zWhere.
ds@1952
   201
  */
ds@1952
   202
  if( pTab->pSchema!=pTempSchema ){
ds@1952
   203
    sqlite3 *db = pParse->db;
ds@1952
   204
    for( pTrig=pTab->pTrigger; pTrig; pTrig=pTrig->pNext ){
ds@1952
   205
      if( pTrig->pSchema==pTempSchema ){
ds@1952
   206
        if( !zWhere ){
ds@1952
   207
          zWhere = sqlite3MPrintf(db, "name=%Q", pTrig->name);
ds@1952
   208
        }else{
ds@1952
   209
          tmp = zWhere;
ds@1952
   210
          zWhere = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, pTrig->name);
ds@1952
   211
          sqlite3_free(tmp);
ds@1952
   212
        }
ds@1952
   213
      }
ds@1952
   214
    }
ds@1952
   215
  }
ds@1952
   216
  return zWhere;
ds@1952
   217
}
ds@1952
   218
ds@1952
   219
/*
ds@1952
   220
** Generate code to drop and reload the internal representation of table
ds@1952
   221
** pTab from the database, including triggers and temporary triggers.
ds@1952
   222
** Argument zName is the name of the table in the database schema at
ds@1952
   223
** the time the generated code is executed. This can be different from
ds@1952
   224
** pTab->zName if this function is being called to code part of an 
ds@1952
   225
** "ALTER TABLE RENAME TO" statement.
ds@1952
   226
*/
ds@1952
   227
static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
ds@1952
   228
  Vdbe *v;
ds@1952
   229
  char *zWhere;
ds@1952
   230
  int iDb;                   /* Index of database containing pTab */
ds@1952
   231
#ifndef SQLITE_OMIT_TRIGGER
ds@1952
   232
  Trigger *pTrig;
ds@1952
   233
#endif
ds@1952
   234
ds@1952
   235
  v = sqlite3GetVdbe(pParse);
ds@1952
   236
  if( !v ) return;
ds@1952
   237
  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
ds@1952
   238
  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
ds@1952
   239
  assert( iDb>=0 );
ds@1952
   240
ds@1952
   241
#ifndef SQLITE_OMIT_TRIGGER
ds@1952
   242
  /* Drop any table triggers from the internal schema. */
ds@1952
   243
  for(pTrig=pTab->pTrigger; pTrig; pTrig=pTrig->pNext){
ds@1952
   244
    int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
ds@1952
   245
    assert( iTrigDb==iDb || iTrigDb==1 );
ds@1952
   246
    sqlite3VdbeOp3(v, OP_DropTrigger, iTrigDb, 0, pTrig->name, 0);
ds@1952
   247
  }
ds@1952
   248
#endif
ds@1952
   249
ds@1952
   250
  /* Drop the table and index from the internal schema */
ds@1952
   251
  sqlite3VdbeOp3(v, OP_DropTable, iDb, 0, pTab->zName, 0);
ds@1952
   252
ds@1952
   253
  /* Reload the table, index and permanent trigger schemas. */
ds@1952
   254
  zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
ds@1952
   255
  if( !zWhere ) return;
ds@1952
   256
  sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 0, zWhere, P3_DYNAMIC);
ds@1952
   257
ds@1952
   258
#ifndef SQLITE_OMIT_TRIGGER
ds@1952
   259
  /* Now, if the table is not stored in the temp database, reload any temp 
ds@1952
   260
  ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined. 
ds@1952
   261
  */
ds@1952
   262
  if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
ds@1952
   263
    sqlite3VdbeOp3(v, OP_ParseSchema, 1, 0, zWhere, P3_DYNAMIC);
ds@1952
   264
  }
ds@1952
   265
#endif
ds@1952
   266
}
ds@1952
   267
ds@1952
   268
/*
ds@1952
   269
** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy" 
ds@1952
   270
** command. 
ds@1952
   271
*/
ds@1952
   272
void sqlite3AlterRenameTable(
ds@1952
   273
  Parse *pParse,            /* Parser context. */
ds@1952
   274
  SrcList *pSrc,            /* The table to rename. */
ds@1952
   275
  Token *pName              /* The new table name. */
ds@1952
   276
){
ds@1952
   277
  int iDb;                  /* Database that contains the table */
ds@1952
   278
  char *zDb;                /* Name of database iDb */
ds@1952
   279
  Table *pTab;              /* Table being renamed */
ds@1952
   280
  char *zName = 0;          /* NULL-terminated version of pName */ 
ds@1952
   281
  sqlite3 *db = pParse->db; /* Database connection */
ds@1952
   282
  int nTabName;             /* Number of UTF-8 characters in zTabName */
ds@1952
   283
  const char *zTabName;     /* Original name of the table */
ds@1952
   284
  Vdbe *v;
ds@1952
   285
#ifndef SQLITE_OMIT_TRIGGER
ds@1952
   286
  char *zWhere = 0;         /* Where clause to locate temp triggers */
ds@1952
   287
#endif
ds@1952
   288
  int isVirtualRename = 0;  /* True if this is a v-table with an xRename() */
ds@1952
   289
  
ds@1952
   290
  if( db->mallocFailed ) goto exit_rename_table;
ds@1952
   291
  assert( pSrc->nSrc==1 );
ds@1952
   292
  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
ds@1952
   293
ds@1952
   294
  pTab = sqlite3LocateTable(pParse, pSrc->a[0].zName, pSrc->a[0].zDatabase);
ds@1952
   295
  if( !pTab ) goto exit_rename_table;
ds@1952
   296
  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
ds@1952
   297
  zDb = db->aDb[iDb].zName;
ds@1952
   298
ds@1952
   299
  /* Get a NULL terminated version of the new table name. */
ds@1952
   300
  zName = sqlite3NameFromToken(db, pName);
ds@1952
   301
  if( !zName ) goto exit_rename_table;
ds@1952
   302
ds@1952
   303
  /* Check that a table or index named 'zName' does not already exist
ds@1952
   304
  ** in database iDb. If so, this is an error.
ds@1952
   305
  */
ds@1952
   306
  if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
ds@1952
   307
    sqlite3ErrorMsg(pParse, 
ds@1952
   308
        "there is already another table or index with this name: %s", zName);
ds@1952
   309
    goto exit_rename_table;
ds@1952
   310
  }
ds@1952
   311
ds@1952
   312
  /* Make sure it is not a system table being altered, or a reserved name
ds@1952
   313
  ** that the table is being renamed to.
ds@1952
   314
  */
ds@1952
   315
  if( strlen(pTab->zName)>6 && 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7) ){
ds@1952
   316
    sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
ds@1952
   317
    goto exit_rename_table;
ds@1952
   318
  }
ds@1952
   319
  if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
ds@1952
   320
    goto exit_rename_table;
ds@1952
   321
  }
ds@1952
   322
ds@1952
   323
#ifndef SQLITE_OMIT_AUTHORIZATION
ds@1952
   324
  /* Invoke the authorization callback. */
ds@1952
   325
  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
ds@1952
   326
    goto exit_rename_table;
ds@1952
   327
  }
ds@1952
   328
#endif
ds@1952
   329
ds@1952
   330
#ifndef SQLITE_OMIT_VIRTUALTABLE
ds@1952
   331
  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
ds@1952
   332
    goto exit_rename_table;
ds@1952
   333
  }
ds@1952
   334
  if( IsVirtual(pTab) && pTab->pMod->pModule->xRename ){
ds@1952
   335
    isVirtualRename = 1;
ds@1952
   336
  }
ds@1952
   337
#endif
ds@1952
   338
ds@1952
   339
  /* Begin a transaction and code the VerifyCookie for database iDb. 
ds@1952
   340
  ** Then modify the schema cookie (since the ALTER TABLE modifies the
ds@1952
   341
  ** schema). Open a statement transaction if the table is a virtual
ds@1952
   342
  ** table.
ds@1952
   343
  */
ds@1952
   344
  v = sqlite3GetVdbe(pParse);
ds@1952
   345
  if( v==0 ){
ds@1952
   346
    goto exit_rename_table;
ds@1952
   347
  }
ds@1952
   348
  sqlite3BeginWriteOperation(pParse, isVirtualRename, iDb);
ds@1952
   349
  sqlite3ChangeCookie(db, v, iDb);
ds@1952
   350
ds@1952
   351
  /* If this is a virtual table, invoke the xRename() function if
ds@1952
   352
  ** one is defined. The xRename() callback will modify the names
ds@1952
   353
  ** of any resources used by the v-table implementation (including other
ds@1952
   354
  ** SQLite tables) that are identified by the name of the virtual table.
ds@1952
   355
  */
ds@1952
   356
#ifndef SQLITE_OMIT_VIRTUALTABLE
ds@1952
   357
  if( isVirtualRename ){
ds@1952
   358
    sqlite3VdbeOp3(v, OP_String8, 0, 0, zName, 0);
ds@1952
   359
    sqlite3VdbeOp3(v, OP_VRename, 0, 0, (const char*)pTab->pVtab, P3_VTAB);
ds@1952
   360
  }
ds@1952
   361
#endif
ds@1952
   362
ds@1952
   363
  /* figure out how many UTF-8 characters are in zName */
ds@1952
   364
  zTabName = pTab->zName;
ds@1952
   365
  nTabName = sqlite3Utf8CharLen(zTabName, -1);
ds@1952
   366
ds@1952
   367
  /* Modify the sqlite_master table to use the new table name. */
ds@1952
   368
  sqlite3NestedParse(pParse,
ds@1952
   369
      "UPDATE %Q.%s SET "
ds@1952
   370
#ifdef SQLITE_OMIT_TRIGGER
ds@1952
   371
          "sql = sqlite_rename_table(sql, %Q), "
ds@1952
   372
#else
ds@1952
   373
          "sql = CASE "
ds@1952
   374
            "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
ds@1952
   375
            "ELSE sqlite_rename_table(sql, %Q) END, "
ds@1952
   376
#endif
ds@1952
   377
          "tbl_name = %Q, "
ds@1952
   378
          "name = CASE "
ds@1952
   379
            "WHEN type='table' THEN %Q "
ds@1952
   380
            "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
ds@1952
   381
             "'sqlite_autoindex_' || %Q || substr(name,%d+18,10) "
ds@1952
   382
            "ELSE name END "
ds@1952
   383
      "WHERE tbl_name=%Q AND "
ds@1952
   384
          "(type='table' OR type='index' OR type='trigger');", 
ds@1952
   385
      zDb, SCHEMA_TABLE(iDb), zName, zName, zName, 
ds@1952
   386
#ifndef SQLITE_OMIT_TRIGGER
ds@1952
   387
      zName,
ds@1952
   388
#endif
ds@1952
   389
      zName, nTabName, zTabName
ds@1952
   390
  );
ds@1952
   391
ds@1952
   392
#ifndef SQLITE_OMIT_AUTOINCREMENT
ds@1952
   393
  /* If the sqlite_sequence table exists in this database, then update 
ds@1952
   394
  ** it with the new table name.
ds@1952
   395
  */
ds@1952
   396
  if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
ds@1952
   397
    sqlite3NestedParse(pParse,
ds@1952
   398
        "UPDATE %Q.sqlite_sequence set name = %Q WHERE name = %Q",
ds@1952
   399
        zDb, zName, pTab->zName);
ds@1952
   400
  }
ds@1952
   401
#endif
ds@1952
   402
ds@1952
   403
#ifndef SQLITE_OMIT_TRIGGER
ds@1952
   404
  /* If there are TEMP triggers on this table, modify the sqlite_temp_master
ds@1952
   405
  ** table. Don't do this if the table being ALTERed is itself located in
ds@1952
   406
  ** the temp database.
ds@1952
   407
  */
ds@1952
   408
  if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
ds@1952
   409
    sqlite3NestedParse(pParse, 
ds@1952
   410
        "UPDATE sqlite_temp_master SET "
ds@1952
   411
            "sql = sqlite_rename_trigger(sql, %Q), "
ds@1952
   412
            "tbl_name = %Q "
ds@1952
   413
            "WHERE %s;", zName, zName, zWhere);
ds@1952
   414
    sqlite3_free(zWhere);
ds@1952
   415
  }
ds@1952
   416
#endif
ds@1952
   417
ds@1952
   418
  /* Drop and reload the internal table schema. */
ds@1952
   419
  reloadTableSchema(pParse, pTab, zName);
ds@1952
   420
ds@1952
   421
exit_rename_table:
ds@1952
   422
  sqlite3SrcListDelete(pSrc);
ds@1952
   423
  sqlite3_free(zName);
ds@1952
   424
}
ds@1952
   425
ds@1952
   426
ds@1952
   427
/*
ds@1952
   428
** This function is called after an "ALTER TABLE ... ADD" statement
ds@1952
   429
** has been parsed. Argument pColDef contains the text of the new
ds@1952
   430
** column definition.
ds@1952
   431
**
ds@1952
   432
** The Table structure pParse->pNewTable was extended to include
ds@1952
   433
** the new column during parsing.
ds@1952
   434
*/
ds@1952
   435
void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
ds@1952
   436
  Table *pNew;              /* Copy of pParse->pNewTable */
ds@1952
   437
  Table *pTab;              /* Table being altered */
ds@1952
   438
  int iDb;                  /* Database number */
ds@1952
   439
  const char *zDb;          /* Database name */
ds@1952
   440
  const char *zTab;         /* Table name */
ds@1952
   441
  char *zCol;               /* Null-terminated column definition */
ds@1952
   442
  Column *pCol;             /* The new column */
ds@1952
   443
  Expr *pDflt;              /* Default value for the new column */
ds@1952
   444
  sqlite3 *db;              /* The database connection; */
ds@1952
   445
ds@1952
   446
  if( pParse->nErr ) return;
ds@1952
   447
  pNew = pParse->pNewTable;
ds@1952
   448
  assert( pNew );
ds@1952
   449
ds@1952
   450
  db = pParse->db;
ds@1952
   451
  assert( sqlite3BtreeHoldsAllMutexes(db) );
ds@1952
   452
  iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
ds@1952
   453
  zDb = db->aDb[iDb].zName;
ds@1952
   454
  zTab = pNew->zName;
ds@1952
   455
  pCol = &pNew->aCol[pNew->nCol-1];
ds@1952
   456
  pDflt = pCol->pDflt;
ds@1952
   457
  pTab = sqlite3FindTable(db, zTab, zDb);
ds@1952
   458
  assert( pTab );
ds@1952
   459
ds@1952
   460
#ifndef SQLITE_OMIT_AUTHORIZATION
ds@1952
   461
  /* Invoke the authorization callback. */
ds@1952
   462
  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
ds@1952
   463
    return;
ds@1952
   464
  }
ds@1952
   465
#endif
ds@1952
   466
ds@1952
   467
  /* If the default value for the new column was specified with a 
ds@1952
   468
  ** literal NULL, then set pDflt to 0. This simplifies checking
ds@1952
   469
  ** for an SQL NULL default below.
ds@1952
   470
  */
ds@1952
   471
  if( pDflt && pDflt->op==TK_NULL ){
ds@1952
   472
    pDflt = 0;
ds@1952
   473
  }
ds@1952
   474
ds@1952
   475
  /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
ds@1952
   476
  ** If there is a NOT NULL constraint, then the default value for the
ds@1952
   477
  ** column must not be NULL.
ds@1952
   478
  */
ds@1952
   479
  if( pCol->isPrimKey ){
ds@1952
   480
    sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
ds@1952
   481
    return;
ds@1952
   482
  }
ds@1952
   483
  if( pNew->pIndex ){
ds@1952
   484
    sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
ds@1952
   485
    return;
ds@1952
   486
  }
ds@1952
   487
  if( pCol->notNull && !pDflt ){
ds@1952
   488
    sqlite3ErrorMsg(pParse, 
ds@1952
   489
        "Cannot add a NOT NULL column with default value NULL");
ds@1952
   490
    return;
ds@1952
   491
  }
ds@1952
   492
ds@1952
   493
  /* Ensure the default expression is something that sqlite3ValueFromExpr()
ds@1952
   494
  ** can handle (i.e. not CURRENT_TIME etc.)
ds@1952
   495
  */
ds@1952
   496
  if( pDflt ){
ds@1952
   497
    sqlite3_value *pVal;
ds@1952
   498
    if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
ds@1952
   499
      db->mallocFailed = 1;
ds@1952
   500
      return;
ds@1952
   501
    }
ds@1952
   502
    if( !pVal ){
ds@1952
   503
      sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
ds@1952
   504
      return;
ds@1952
   505
    }
ds@1952
   506
    sqlite3ValueFree(pVal);
ds@1952
   507
  }
ds@1952
   508
ds@1952
   509
  /* Modify the CREATE TABLE statement. */
ds@1952
   510
  zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
ds@1952
   511
  if( zCol ){
ds@1952
   512
    char *zEnd = &zCol[pColDef->n-1];
ds@1952
   513
    while( (zEnd>zCol && *zEnd==';') || isspace(*(unsigned char *)zEnd) ){
ds@1952
   514
      *zEnd-- = '\0';
ds@1952
   515
    }
ds@1952
   516
    sqlite3NestedParse(pParse, 
ds@1952
   517
        "UPDATE %Q.%s SET "
ds@1952
   518
          "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d,length(sql)) "
ds@1952
   519
        "WHERE type = 'table' AND name = %Q", 
ds@1952
   520
      zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
ds@1952
   521
      zTab
ds@1952
   522
    );
ds@1952
   523
    sqlite3_free(zCol);
ds@1952
   524
  }
ds@1952
   525
ds@1952
   526
  /* If the default value of the new column is NULL, then set the file
ds@1952
   527
  ** format to 2. If the default value of the new column is not NULL,
ds@1952
   528
  ** the file format becomes 3.
ds@1952
   529
  */
ds@1952
   530
  sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
ds@1952
   531
ds@1952
   532
  /* Reload the schema of the modified table. */
ds@1952
   533
  reloadTableSchema(pParse, pTab, pTab->zName);
ds@1952
   534
}
ds@1952
   535
ds@1952
   536
/*
ds@1952
   537
** This function is called by the parser after the table-name in
ds@1952
   538
** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument 
ds@1952
   539
** pSrc is the full-name of the table being altered.
ds@1952
   540
**
ds@1952
   541
** This routine makes a (partial) copy of the Table structure
ds@1952
   542
** for the table being altered and sets Parse.pNewTable to point
ds@1952
   543
** to it. Routines called by the parser as the column definition
ds@1952
   544
** is parsed (i.e. sqlite3AddColumn()) add the new Column data to 
ds@1952
   545
** the copy. The copy of the Table structure is deleted by tokenize.c 
ds@1952
   546
** after parsing is finished.
ds@1952
   547
**
ds@1952
   548
** Routine sqlite3AlterFinishAddColumn() will be called to complete
ds@1952
   549
** coding the "ALTER TABLE ... ADD" statement.
ds@1952
   550
*/
ds@1952
   551
void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
ds@1952
   552
  Table *pNew;
ds@1952
   553
  Table *pTab;
ds@1952
   554
  Vdbe *v;
ds@1952
   555
  int iDb;
ds@1952
   556
  int i;
ds@1952
   557
  int nAlloc;
ds@1952
   558
  sqlite3 *db = pParse->db;
ds@1952
   559
ds@1952
   560
  /* Look up the table being altered. */
ds@1952
   561
  assert( pParse->pNewTable==0 );
ds@1952
   562
  assert( sqlite3BtreeHoldsAllMutexes(db) );
ds@1952
   563
  if( db->mallocFailed ) goto exit_begin_add_column;
ds@1952
   564
  pTab = sqlite3LocateTable(pParse, pSrc->a[0].zName, pSrc->a[0].zDatabase);
ds@1952
   565
  if( !pTab ) goto exit_begin_add_column;
ds@1952
   566
ds@1952
   567
#ifndef SQLITE_OMIT_VIRTUALTABLE
ds@1952
   568
  if( IsVirtual(pTab) ){
ds@1952
   569
    sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
ds@1952
   570
    goto exit_begin_add_column;
ds@1952
   571
  }
ds@1952
   572
#endif
ds@1952
   573
ds@1952
   574
  /* Make sure this is not an attempt to ALTER a view. */
ds@1952
   575
  if( pTab->pSelect ){
ds@1952
   576
    sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
ds@1952
   577
    goto exit_begin_add_column;
ds@1952
   578
  }
ds@1952
   579
ds@1952
   580
  assert( pTab->addColOffset>0 );
ds@1952
   581
  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
ds@1952
   582
ds@1952
   583
  /* Put a copy of the Table struct in Parse.pNewTable for the
ds@1952
   584
  ** sqlite3AddColumn() function and friends to modify.
ds@1952
   585
  */
ds@1952
   586
  pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
ds@1952
   587
  if( !pNew ) goto exit_begin_add_column;
ds@1952
   588
  pParse->pNewTable = pNew;
ds@1952
   589
  pNew->nRef = 1;
ds@1952
   590
  pNew->nCol = pTab->nCol;
ds@1952
   591
  assert( pNew->nCol>0 );
ds@1952
   592
  nAlloc = (((pNew->nCol-1)/8)*8)+8;
ds@1952
   593
  assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
ds@1952
   594
  pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
ds@1952
   595
  pNew->zName = sqlite3DbStrDup(db, pTab->zName);
ds@1952
   596
  if( !pNew->aCol || !pNew->zName ){
ds@1952
   597
    db->mallocFailed = 1;
ds@1952
   598
    goto exit_begin_add_column;
ds@1952
   599
  }
ds@1952
   600
  memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
ds@1952
   601
  for(i=0; i<pNew->nCol; i++){
ds@1952
   602
    Column *pCol = &pNew->aCol[i];
ds@1952
   603
    pCol->zName = sqlite3DbStrDup(db, pCol->zName);
ds@1952
   604
    pCol->zColl = 0;
ds@1952
   605
    pCol->zType = 0;
ds@1952
   606
    pCol->pDflt = 0;
ds@1952
   607
  }
ds@1952
   608
  pNew->pSchema = db->aDb[iDb].pSchema;
ds@1952
   609
  pNew->addColOffset = pTab->addColOffset;
ds@1952
   610
  pNew->nRef = 1;
ds@1952
   611
ds@1952
   612
  /* Begin a transaction and increment the schema cookie.  */
ds@1952
   613
  sqlite3BeginWriteOperation(pParse, 0, iDb);
ds@1952
   614
  v = sqlite3GetVdbe(pParse);
ds@1952
   615
  if( !v ) goto exit_begin_add_column;
ds@1952
   616
  sqlite3ChangeCookie(db, v, iDb);
ds@1952
   617
ds@1952
   618
exit_begin_add_column:
ds@1952
   619
  sqlite3SrcListDelete(pSrc);
ds@1952
   620
  return;
ds@1952
   621
}
ds@1952
   622
#endif  /* SQLITE_ALTER_TABLE */