PageRenderTime 73ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/library/Library/WP7/SQLiteDriver/sqlite/build_c.cs

https://bitbucket.org/digitalizarte/coolstorage
C# | 4331 lines | 3723 code | 86 blank | 522 comment | 288 complexity | e464bb4162b4f5b8e141695420744dce MD5 | raw file
  1. using System;
  2. using System.Diagnostics;
  3. using System.IO;
  4. using System.Text;
  5. using i16 = System.Int16;
  6. using u8 = System.Byte;
  7. using u16 = System.UInt16;
  8. using u32 = System.UInt32;
  9. using Pgno = System.UInt32;
  10. namespace Community.CsharpSqlite
  11. {
  12. public partial class Sqlite3
  13. {
  14. /*
  15. ** 2001 September 15
  16. **
  17. ** The author disclaims copyright to this source code. In place of
  18. ** a legal notice, here is a blessing:
  19. **
  20. ** May you do good and not evil.
  21. ** May you find forgiveness for yourself and forgive others.
  22. ** May you share freely, never taking more than you give.
  23. **
  24. *************************************************************************
  25. ** This file contains C code routines that are called by the SQLite parser
  26. ** when syntax rules are reduced. The routines in this file handle the
  27. ** following kinds of SQL syntax:
  28. **
  29. ** CREATE TABLE
  30. ** DROP TABLE
  31. ** CREATE INDEX
  32. ** DROP INDEX
  33. ** creating ID lists
  34. ** BEGIN TRANSACTION
  35. ** COMMIT
  36. ** ROLLBACK
  37. *************************************************************************
  38. ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
  39. ** C#-SQLite is an independent reimplementation of the SQLite software library
  40. **
  41. ** SQLITE_SOURCE_ID: 2010-12-07 20:14:09 a586a4deeb25330037a49df295b36aaf624d0f45
  42. **
  43. *************************************************************************
  44. */
  45. //#include "sqliteInt.h"
  46. /*
  47. ** This routine is called when a new SQL statement is beginning to
  48. ** be parsed. Initialize the pParse structure as needed.
  49. */
  50. static void sqlite3BeginParse( Parse pParse, int explainFlag )
  51. {
  52. pParse.explain = (byte)explainFlag;
  53. pParse.nVar = 0;
  54. }
  55. #if !SQLITE_OMIT_SHARED_CACHE
  56. /*
  57. ** The TableLock structure is only used by the sqlite3TableLock() and
  58. ** codeTableLocks() functions.
  59. */
  60. //struct TableLock {
  61. // int iDb; /* The database containing the table to be locked */
  62. // int iTab; /* The root page of the table to be locked */
  63. // u8 isWriteLock; /* True for write lock. False for a read lock */
  64. // string zName; /* Name of the table */
  65. //};
  66. public class TableLock
  67. {
  68. public int iDb; /* The database containing the table to be locked */
  69. public int iTab; /* The root page of the table to be locked */
  70. public u8 isWriteLock; /* True for write lock. False for a read lock */
  71. public string zName; /* Name of the table */
  72. }
  73. /*
  74. ** Record the fact that we want to lock a table at run-time.
  75. **
  76. ** The table to be locked has root page iTab and is found in database iDb.
  77. ** A read or a write lock can be taken depending on isWritelock.
  78. **
  79. ** This routine just records the fact that the lock is desired. The
  80. ** code to make the lock occur is generated by a later call to
  81. ** codeTableLocks() which occurs during sqlite3FinishCoding().
  82. */
  83. void sqlite3TableLock(
  84. Parse *pParse, /* Parsing context */
  85. int iDb, /* Index of the database containing the table to lock */
  86. int iTab, /* Root page number of the table to be locked */
  87. u8 isWriteLock, /* True for a write lock */
  88. const char *zName /* Name of the table to be locked */
  89. ){
  90. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  91. int i;
  92. int nBytes;
  93. TableLock *p;
  94. assert( iDb>=0 );
  95. for(i=0; i<pToplevel->nTableLock; i++){
  96. p = &pToplevel->aTableLock[i];
  97. if( p->iDb==iDb && p->iTab==iTab ){
  98. p->isWriteLock = (p->isWriteLock || isWriteLock);
  99. return;
  100. }
  101. }
  102. nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
  103. pToplevel->aTableLock =
  104. sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
  105. if( pToplevel->aTableLock ){
  106. p = &pToplevel->aTableLock[pToplevel->nTableLock++];
  107. p->iDb = iDb;
  108. p->iTab = iTab;
  109. p->isWriteLock = isWriteLock;
  110. p->zName = zName;
  111. }else{
  112. pToplevel->nTableLock = 0;
  113. pToplevel->db->mallocFailed = 1;
  114. }
  115. }
  116. /*
  117. ** Code an OP_TableLock instruction for each table locked by the
  118. ** statement (configured by calls to sqlite3TableLock()).
  119. */
  120. static void codeTableLocks( Parse pParse )
  121. {
  122. int i;
  123. Vdbe pVdbe;
  124. pVdbe = sqlite3GetVdbe( pParse );
  125. Debug.Assert( pVdbe != null ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
  126. for ( i = 0 ; i < pParse.nTableLock ; i++ )
  127. {
  128. TableLock p = pParse.aTableLock[i];
  129. int p1 = p.iDb;
  130. sqlite3VdbeAddOp4( pVdbe, OP_TableLock, p1, p.iTab, p.isWriteLock,
  131. p.zName, P4_STATIC );
  132. }
  133. }
  134. #else
  135. // #define codeTableLocks(x)
  136. static void codeTableLocks( Parse pParse )
  137. {
  138. }
  139. #endif
  140. /*
  141. ** This routine is called after a single SQL statement has been
  142. ** parsed and a VDBE program to execute that statement has been
  143. ** prepared. This routine puts the finishing touches on the
  144. ** VDBE program and resets the pParse structure for the next
  145. ** parse.
  146. **
  147. ** Note that if an error occurred, it might be the case that
  148. ** no VDBE code was generated.
  149. */
  150. static void sqlite3FinishCoding( Parse pParse )
  151. {
  152. sqlite3 db;
  153. Vdbe v;
  154. db = pParse.db;
  155. // if ( db.mallocFailed != 0 ) return;
  156. if ( pParse.nested != 0 )
  157. return;
  158. if ( pParse.nErr != 0 )
  159. return;
  160. /* Begin by generating some termination code at the end of the
  161. ** vdbe program
  162. */
  163. v = sqlite3GetVdbe( pParse );
  164. Debug.Assert( 0 == pParse.isMultiWrite
  165. || sqlite3VdbeAssertMayAbort( v, pParse.mayAbort ) != 0 );
  166. if ( v != null )
  167. {
  168. sqlite3VdbeAddOp0( v, OP_Halt );
  169. /* The cookie mask contains one bit for each database file open.
  170. ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
  171. ** set for each database that is used. Generate code to start a
  172. ** transaction on each used database and to verify the schema cookie
  173. ** on each used database.
  174. */
  175. if ( pParse.cookieGoto > 0 )
  176. {
  177. u32 mask;
  178. int iDb;
  179. sqlite3VdbeJumpHere( v, pParse.cookieGoto - 1 );
  180. for ( iDb = 0, mask = 1; iDb < db.nDb; mask <<= 1, iDb++ )
  181. {
  182. if ( ( mask & pParse.cookieMask ) == 0 )
  183. continue;
  184. sqlite3VdbeUsesBtree( v, iDb );
  185. sqlite3VdbeAddOp2( v, OP_Transaction, iDb, ( mask & pParse.writeMask ) != 0 );
  186. if ( db.init.busy == 0 )
  187. {
  188. sqlite3VdbeAddOp2( v, OP_VerifyCookie, iDb, pParse.cookieValue[iDb] );
  189. }
  190. }
  191. #if !SQLITE_OMIT_VIRTUALTABLE
  192. {
  193. int i;
  194. for(i=0; i<pParse.nVtabLock; i++){
  195. char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
  196. sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
  197. }
  198. pParse.nVtabLock = 0;
  199. }
  200. #endif
  201. /* Once all the cookies have been verified and transactions opened,
  202. ** obtain the required table-locks. This is a no-op unless the
  203. ** shared-cache feature is enabled.
  204. */
  205. codeTableLocks( pParse );
  206. /* Initialize any AUTOINCREMENT data structures required.
  207. */
  208. sqlite3AutoincrementBegin( pParse );
  209. /* Finally, jump back to the beginning of the executable code. */
  210. sqlite3VdbeAddOp2( v, OP_Goto, 0, pParse.cookieGoto );
  211. }
  212. }
  213. /* Get the VDBE program ready for execution
  214. */
  215. if ( v != null && ALWAYS( pParse.nErr == 0 ) /* && 0 == db.mallocFailed */ )
  216. {
  217. #if SQLITE_DEBUG
  218. TextWriter trace = ( db.flags & SQLITE_VdbeTrace ) != 0 ? Console.Out : null;
  219. sqlite3VdbeTrace( v, trace );
  220. #endif
  221. Debug.Assert( pParse.iCacheLevel == 0 ); /* Disables and re-enables match */
  222. /* A minimum of one cursor is required if autoincrement is used
  223. * See ticket [a696379c1f08866] */
  224. if ( pParse.pAinc != null && pParse.nTab == 0 )
  225. pParse.nTab = 1;
  226. sqlite3VdbeMakeReady( v, pParse.nVar, pParse.nMem,
  227. pParse.nTab, pParse.nMaxArg, pParse.explain,
  228. ( pParse.isMultiWrite != 0 && pParse.mayAbort != 0 ) ? 1 : 0 );
  229. pParse.rc = SQLITE_DONE;
  230. pParse.colNamesSet = 0;
  231. }
  232. else
  233. {
  234. pParse.rc = SQLITE_ERROR;
  235. }
  236. pParse.nTab = 0;
  237. pParse.nMem = 0;
  238. pParse.nSet = 0;
  239. pParse.nVar = 0;
  240. pParse.cookieMask = 0;
  241. pParse.cookieGoto = 0;
  242. }
  243. /*
  244. ** Run the parser and code generator recursively in order to generate
  245. ** code for the SQL statement given onto the end of the pParse context
  246. ** currently under construction. When the parser is run recursively
  247. ** this way, the final OP_Halt is not appended and other initialization
  248. ** and finalization steps are omitted because those are handling by the
  249. ** outermost parser.
  250. **
  251. ** Not everything is nestable. This facility is designed to permit
  252. ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
  253. ** care if you decide to try to use this routine for some other purposes.
  254. */
  255. static void sqlite3NestedParse( Parse pParse, string zFormat, params object[] ap )
  256. {
  257. string zSql; // char *zSql;
  258. string zErrMsg = "";// char* zErrMsg = 0;
  259. sqlite3 db = pParse.db;
  260. //# define SAVE_SZ (Parse.Length - offsetof(Parse,nVar))
  261. // char saveBuf[SAVE_SZ];
  262. if ( pParse.nErr != 0 )
  263. return;
  264. Debug.Assert( pParse.nested < 10 ); /* Nesting should only be of limited depth */
  265. // va_list ap;
  266. lock ( lock_va_list )
  267. {
  268. va_start( ap, zFormat );
  269. zSql = sqlite3VMPrintf( db, zFormat, ap );
  270. va_end( ref ap );
  271. }
  272. //if( zSql=="" ){
  273. // return; /* A malloc must have failed */
  274. //}
  275. lock ( nestingLock )
  276. {
  277. pParse.nested++;
  278. pParse.SaveMembers(); // memcpy(saveBuf, pParse.nVar, SAVE_SZ);
  279. pParse.ResetMembers(); // memset(pParse.nVar, 0, SAVE_SZ);
  280. sqlite3RunParser( pParse, zSql, ref zErrMsg );
  281. sqlite3DbFree( db, ref zErrMsg );
  282. sqlite3DbFree( db, ref zSql );
  283. pParse.RestoreMembers(); // memcpy(pParse.nVar, saveBuf, SAVE_SZ);
  284. pParse.nested--;
  285. }
  286. }
  287. static Object nestingLock = new Object();
  288. /*
  289. ** Locate the in-memory structure that describes a particular database
  290. ** table given the name of that table and (optionally) the name of the
  291. ** database containing the table. Return NULL if not found.
  292. **
  293. ** If zDatabase is 0, all databases are searched for the table and the
  294. ** first matching table is returned. (No checking for duplicate table
  295. ** names is done.) The search order is TEMP first, then MAIN, then any
  296. ** auxiliary databases added using the ATTACH command.
  297. **
  298. ** See also sqlite3LocateTable().
  299. */
  300. static Table sqlite3FindTable( sqlite3 db, string zName, string zDatabase )
  301. {
  302. Table p = null;
  303. int i;
  304. int nName;
  305. Debug.Assert( zName != null );
  306. nName = sqlite3Strlen30( zName );
  307. for ( i = OMIT_TEMPDB; i < db.nDb; i++ )
  308. {
  309. int j = ( i < 2 ) ? i ^ 1 : i; /* Search TEMP before MAIN */
  310. if ( zDatabase != null && !zDatabase.Equals( db.aDb[j].zName, StringComparison.InvariantCultureIgnoreCase ) )
  311. continue;
  312. p = sqlite3HashFind( db.aDb[j].pSchema.tblHash, zName, nName, (Table)null );
  313. if ( p != null )
  314. break;
  315. }
  316. return p;
  317. }
  318. /*
  319. ** Locate the in-memory structure that describes a particular database
  320. ** table given the name of that table and (optionally) the name of the
  321. ** database containing the table. Return NULL if not found. Also leave an
  322. ** error message in pParse.zErrMsg.
  323. **
  324. ** The difference between this routine and sqlite3FindTable() is that this
  325. ** routine leaves an error message in pParse.zErrMsg where
  326. ** sqlite3FindTable() does not.
  327. */
  328. static Table sqlite3LocateTable(
  329. Parse pParse, /* context in which to report errors */
  330. int isView, /* True if looking for a VIEW rather than a TABLE */
  331. string zName, /* Name of the table we are looking for */
  332. string zDbase /* Name of the database. Might be NULL */
  333. )
  334. {
  335. Table p;
  336. /* Read the database schema. If an error occurs, leave an error message
  337. ** and code in pParse and return NULL. */
  338. if ( SQLITE_OK != sqlite3ReadSchema( pParse ) )
  339. {
  340. return null;
  341. }
  342. p = sqlite3FindTable( pParse.db, zName, zDbase );
  343. if ( p == null )
  344. {
  345. string zMsg = isView != 0 ? "no such view" : "no such table";
  346. if ( zDbase != null )
  347. {
  348. sqlite3ErrorMsg( pParse, "%s: %s.%s", zMsg, zDbase, zName );
  349. }
  350. else
  351. {
  352. sqlite3ErrorMsg( pParse, "%s: %s", zMsg, zName );
  353. }
  354. pParse.checkSchema = 1;
  355. }
  356. return p;
  357. }
  358. /*
  359. ** Locate the in-memory structure that describes
  360. ** a particular index given the name of that index
  361. ** and the name of the database that contains the index.
  362. ** Return NULL if not found.
  363. **
  364. ** If zDatabase is 0, all databases are searched for the
  365. ** table and the first matching index is returned. (No checking
  366. ** for duplicate index names is done.) The search order is
  367. ** TEMP first, then MAIN, then any auxiliary databases added
  368. ** using the ATTACH command.
  369. */
  370. static Index sqlite3FindIndex( sqlite3 db, string zName, string zDb )
  371. {
  372. Index p = null;
  373. int i;
  374. int nName = sqlite3Strlen30( zName );
  375. for ( i = OMIT_TEMPDB; i < db.nDb; i++ )
  376. {
  377. int j = ( i < 2 ) ? i ^ 1 : i; /* Search TEMP before MAIN */
  378. Schema pSchema = db.aDb[j].pSchema;
  379. Debug.Assert( pSchema != null );
  380. if ( zDb != null && !zDb.Equals( db.aDb[j].zName, StringComparison.InvariantCultureIgnoreCase ) )
  381. continue;
  382. p = sqlite3HashFind( pSchema.idxHash, zName, nName, (Index)null );
  383. if ( p != null )
  384. break;
  385. }
  386. return p;
  387. }
  388. /*
  389. ** Reclaim the memory used by an index
  390. */
  391. static void freeIndex( sqlite3 db, ref Index p )
  392. {
  393. #if !SQLITE_OMIT_ANALYZE
  394. sqlite3DeleteIndexSamples( db, p );
  395. #endif
  396. sqlite3DbFree( db, ref p.zColAff );
  397. sqlite3DbFree( db, ref p );
  398. }
  399. /*
  400. ** For the index called zIdxName which is found in the database iDb,
  401. ** unlike that index from its Table then remove the index from
  402. ** the index hash table and free all memory structures associated
  403. ** with the index.
  404. */
  405. static void sqlite3UnlinkAndDeleteIndex( sqlite3 db, int iDb, string zIdxName )
  406. {
  407. Index pIndex;
  408. int len;
  409. Hash pHash = db.aDb[iDb].pSchema.idxHash;
  410. len = sqlite3Strlen30( zIdxName );
  411. pIndex = sqlite3HashInsert( ref pHash, zIdxName, len, (Index)null );
  412. if ( pIndex != null )
  413. {
  414. if ( pIndex.pTable.pIndex == pIndex )
  415. {
  416. pIndex.pTable.pIndex = pIndex.pNext;
  417. }
  418. else
  419. {
  420. Index p;
  421. /* Justification of ALWAYS(); The index must be on the list of
  422. ** indices. */
  423. p = pIndex.pTable.pIndex;
  424. while ( ALWAYS( p != null ) && p.pNext != pIndex )
  425. {
  426. p = p.pNext;
  427. }
  428. if ( ALWAYS( p != null && p.pNext == pIndex ) )
  429. {
  430. p.pNext = pIndex.pNext;
  431. }
  432. }
  433. freeIndex( db, ref pIndex );
  434. }
  435. db.flags |= SQLITE_InternChanges;
  436. }
  437. /*
  438. ** Erase all schema information from the in-memory hash tables of
  439. ** a single database. This routine is called to reclaim memory
  440. ** before the database closes. It is also called during a rollback
  441. ** if there were schema changes during the transaction or if a
  442. ** schema-cookie mismatch occurs.
  443. **
  444. ** If iDb==0 then reset the internal schema tables for all database
  445. ** files. If iDb>=1 then reset the internal schema for only the
  446. ** single file indicated.
  447. */
  448. static void sqlite3ResetInternalSchema( sqlite3 db, int iDb )
  449. {
  450. int i, j;
  451. Debug.Assert( iDb >= 0 && iDb < db.nDb );
  452. if ( iDb == 0 )
  453. {
  454. sqlite3BtreeEnterAll( db );
  455. }
  456. for ( i = iDb; i < db.nDb; i++ )
  457. {
  458. Db pDb = db.aDb[i];
  459. if ( pDb.pSchema != null )
  460. {
  461. Debug.Assert( i == 1 || ( pDb.pBt != null && sqlite3BtreeHoldsMutex( pDb.pBt ) ) );
  462. Debug.Assert( i == 1 || ( pDb.pBt != null ) );
  463. sqlite3SchemaFree( pDb.pSchema );
  464. }
  465. if ( iDb > 0 )
  466. return;
  467. }
  468. Debug.Assert( iDb == 0 );
  469. db.flags &= ~SQLITE_InternChanges;
  470. sqlite3VtabUnlockList( db );
  471. sqlite3BtreeLeaveAll( db );
  472. /* If one or more of the auxiliary database files has been closed,
  473. ** then remove them from the auxiliary database list. We take the
  474. ** opportunity to do this here since we have just deleted all of the
  475. ** schema hash tables and therefore do not have to make any changes
  476. ** to any of those tables.
  477. */
  478. for ( i = j = 2; i < db.nDb; i++ )
  479. {
  480. Db pDb = db.aDb[i];
  481. if ( pDb.pBt == null )
  482. {
  483. sqlite3DbFree( db, ref pDb.zName );
  484. continue;
  485. }
  486. if ( j < i )
  487. {
  488. db.aDb[j] = db.aDb[i];
  489. }
  490. j++;
  491. }
  492. if ( db.nDb != j )
  493. db.aDb[j] = new Db();//memset(db.aDb[j], 0, (db.nDb-j)*sizeof(db.aDb[j]));
  494. db.nDb = j;
  495. if ( db.nDb <= 2 && db.aDb != db.aDbStatic )
  496. {
  497. Array.Copy( db.aDb, db.aDbStatic, 2 );// memcpy(db.aDbStatic, db.aDb, 2*sizeof(db.aDb[0]));
  498. sqlite3DbFree( db, ref db.aDb );
  499. //db.aDb = db.aDbStatic;
  500. }
  501. }
  502. /*
  503. ** This routine is called when a commit occurs.
  504. */
  505. static void sqlite3CommitInternalChanges( sqlite3 db )
  506. {
  507. db.flags &= ~SQLITE_InternChanges;
  508. }
  509. /*
  510. ** Delete memory allocated for the column names of a table or view (the
  511. ** Table.aCol[] array).
  512. */
  513. static void sqliteDeleteColumnNames( sqlite3 db, Table pTable )
  514. {
  515. int i;
  516. Column pCol;
  517. Debug.Assert( pTable != null );
  518. for ( i = 0; i < pTable.nCol; i++ )
  519. {
  520. pCol = pTable.aCol[i];
  521. if ( pCol != null )
  522. {
  523. sqlite3DbFree( db, ref pCol.zName );
  524. sqlite3ExprDelete( db, ref pCol.pDflt );
  525. sqlite3DbFree( db, ref pCol.zDflt );
  526. sqlite3DbFree( db, ref pCol.zType );
  527. sqlite3DbFree( db, ref pCol.zColl );
  528. }
  529. }
  530. }
  531. /*
  532. ** Remove the memory data structures associated with the given
  533. ** Table. No changes are made to disk by this routine.
  534. **
  535. ** This routine just deletes the data structure. It does not unlink
  536. ** the table data structure from the hash table. But it does destroy
  537. ** memory structures of the indices and foreign keys associated with
  538. ** the table.
  539. */
  540. static void sqlite3DeleteTable( sqlite3 db, ref Table pTable )
  541. {
  542. Index pIndex;
  543. Index pNext;
  544. Debug.Assert( null == pTable || pTable.nRef > 0 );
  545. /* Do not delete the table until the reference count reaches zero. */
  546. if ( null == pTable )
  547. return;
  548. if ( (// ( !db || db->pnBytesFreed == 0 ) &&
  549. ( --pTable.nRef ) > 0 ) )
  550. return;
  551. /* Delete all indices associated with this table. */
  552. for ( pIndex = pTable.pIndex; pIndex != null; pIndex = pNext )
  553. {
  554. pNext = pIndex.pNext;
  555. Debug.Assert( pIndex.pSchema == pTable.pSchema );
  556. //if( null==db || db.pnBytesFreed==0 ){
  557. string zName = pIndex.zName;
  558. //
  559. #if !NDEBUG || SQLITE_COVERAGE_TEST
  560. // TESTONLY ( Index pOld = ) sqlite3HashInsert(
  561. //ref pIndex.pSchema.idxHash, zName, sqlite3Strlen30(zName), 0
  562. // );
  563. Index pOld = sqlite3HashInsert(
  564. ref pIndex.pSchema.idxHash, zName, sqlite3Strlen30( zName ), (Index)null
  565. );
  566. Debug.Assert( pOld == pIndex || pOld == null );
  567. #else
  568. // TESTONLY ( Index pOld = ) sqlite3HashInsert(
  569. //ref pIndex.pSchema.idxHash, zName, sqlite3Strlen30(zName), 0
  570. // );
  571. sqlite3HashInsert(
  572. ref pIndex.pSchema.idxHash, zName, sqlite3Strlen30(zName),(Index)null
  573. );
  574. #endif
  575. //}
  576. freeIndex( db, ref pIndex );
  577. }
  578. /* Delete any foreign keys attached to this table. */
  579. sqlite3FkDelete( db, pTable );
  580. /* Delete the Table structure itself.
  581. */
  582. sqliteDeleteColumnNames( db, pTable );
  583. sqlite3DbFree( db, ref pTable.zName );
  584. sqlite3DbFree( db, ref pTable.zColAff );
  585. sqlite3SelectDelete( db, ref pTable.pSelect );
  586. #if !SQLITE_OMIT_CHECK
  587. sqlite3ExprDelete( db, ref pTable.pCheck );
  588. #endif
  589. #if !SQLITE_OMIT_VIRTUALTABLE
  590. sqlite3VtabClear(db, pTable);
  591. #endif
  592. pTable = null;// sqlite3DbFree( db, ref pTable );
  593. }
  594. /*
  595. ** Unlink the given table from the hash tables and the delete the
  596. ** table structure with all its indices and foreign keys.
  597. */
  598. static void sqlite3UnlinkAndDeleteTable( sqlite3 db, int iDb, string zTabName )
  599. {
  600. Table p;
  601. Db pDb;
  602. Debug.Assert( db != null );
  603. Debug.Assert( iDb >= 0 && iDb < db.nDb );
  604. Debug.Assert( zTabName != null );
  605. testcase( zTabName.Length == 0 ); /* Zero-length table names are allowed */
  606. pDb = db.aDb[iDb];
  607. p = sqlite3HashInsert( ref pDb.pSchema.tblHash, zTabName,
  608. sqlite3Strlen30( zTabName ), (Table)null );
  609. sqlite3DeleteTable( db, ref p );
  610. db.flags |= SQLITE_InternChanges;
  611. }
  612. /*
  613. ** Given a token, return a string that consists of the text of that
  614. ** token. Space to hold the returned string
  615. ** is obtained from sqliteMalloc() and must be freed by the calling
  616. ** function.
  617. **
  618. ** Any quotation marks (ex: "name", 'name', [name], or `name`) that
  619. ** surround the body of the token are removed.
  620. **
  621. ** Tokens are often just pointers into the original SQL text and so
  622. ** are not \000 terminated and are not persistent. The returned string
  623. ** is \000 terminated and is persistent.
  624. */
  625. static string sqlite3NameFromToken( sqlite3 db, Token pName )
  626. {
  627. string zName;
  628. if ( pName != null && pName.z != null )
  629. {
  630. zName = pName.z.Substring( 0, pName.n );//sqlite3DbStrNDup(db, (char*)pName.z, pName.n);
  631. sqlite3Dequote( ref zName );
  632. }
  633. else
  634. {
  635. return null;
  636. }
  637. return zName;
  638. }
  639. /*
  640. ** Open the sqlite_master table stored in database number iDb for
  641. ** writing. The table is opened using cursor 0.
  642. */
  643. static void sqlite3OpenMasterTable( Parse p, int iDb )
  644. {
  645. Vdbe v = sqlite3GetVdbe( p );
  646. sqlite3TableLock( p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE( iDb ) );
  647. sqlite3VdbeAddOp3( v, OP_OpenWrite, 0, MASTER_ROOT, iDb );
  648. sqlite3VdbeChangeP4( v, -1, (int)5, P4_INT32 ); /* 5 column table */
  649. if ( p.nTab == 0 )
  650. {
  651. p.nTab = 1;
  652. }
  653. }
  654. /*
  655. ** Parameter zName points to a nul-terminated buffer containing the name
  656. ** of a database ("main", "temp" or the name of an attached db). This
  657. ** function returns the index of the named database in db->aDb[], or
  658. ** -1 if the named db cannot be found.
  659. */
  660. static int sqlite3FindDbName( sqlite3 db, string zName )
  661. {
  662. int i = -1; /* Database number */
  663. if ( zName != null )
  664. {
  665. Db pDb;
  666. int n = sqlite3Strlen30( zName );
  667. for ( i = ( db.nDb - 1 ); i >= 0; i-- )
  668. {
  669. pDb = db.aDb[i];
  670. if ( ( OMIT_TEMPDB == 0 || i != 1 ) && n == sqlite3Strlen30( pDb.zName ) &&
  671. pDb.zName.Equals( zName, StringComparison.InvariantCultureIgnoreCase ) )
  672. {
  673. break;
  674. }
  675. }
  676. }
  677. return i;
  678. }
  679. /*
  680. ** The token *pName contains the name of a database (either "main" or
  681. ** "temp" or the name of an attached db). This routine returns the
  682. ** index of the named database in db->aDb[], or -1 if the named db
  683. ** does not exist.
  684. */
  685. static int sqlite3FindDb( sqlite3 db, Token pName )
  686. {
  687. int i; /* Database number */
  688. string zName; /* Name we are searching for */
  689. zName = sqlite3NameFromToken( db, pName );
  690. i = sqlite3FindDbName( db, zName );
  691. sqlite3DbFree( db, ref zName );
  692. return i;
  693. }
  694. /* The table or view or trigger name is passed to this routine via tokens
  695. ** pName1 and pName2. If the table name was fully qualified, for example:
  696. **
  697. ** CREATE TABLE xxx.yyy (...);
  698. **
  699. ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
  700. ** the table name is not fully qualified, i.e.:
  701. **
  702. ** CREATE TABLE yyy(...);
  703. **
  704. ** Then pName1 is set to "yyy" and pName2 is "".
  705. **
  706. ** This routine sets the ppUnqual pointer to point at the token (pName1 or
  707. ** pName2) that stores the unqualified table name. The index of the
  708. ** database "xxx" is returned.
  709. */
  710. static int sqlite3TwoPartName(
  711. Parse pParse, /* Parsing and code generating context */
  712. Token pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
  713. Token pName2, /* The "yyy" in the name "xxx.yyy" */
  714. ref Token pUnqual /* Write the unqualified object name here */
  715. )
  716. {
  717. int iDb; /* Database holding the object */
  718. sqlite3 db = pParse.db;
  719. if ( ALWAYS( pName2 != null ) && pName2.n > 0 )
  720. {
  721. if ( db.init.busy != 0 )
  722. {
  723. sqlite3ErrorMsg( pParse, "corrupt database" );
  724. pParse.nErr++;
  725. return -1;
  726. }
  727. pUnqual = pName2;
  728. iDb = sqlite3FindDb( db, pName1 );
  729. if ( iDb < 0 )
  730. {
  731. sqlite3ErrorMsg( pParse, "unknown database %T", pName1 );
  732. pParse.nErr++;
  733. return -1;
  734. }
  735. }
  736. else
  737. {
  738. Debug.Assert( db.init.iDb == 0 || db.init.busy != 0 );
  739. iDb = db.init.iDb;
  740. pUnqual = pName1;
  741. }
  742. return iDb;
  743. }
  744. /*
  745. ** This routine is used to check if the UTF-8 string zName is a legal
  746. ** unqualified name for a new schema object (table, index, view or
  747. ** trigger). All names are legal except those that begin with the string
  748. ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
  749. ** is reserved for internal use.
  750. */
  751. static int sqlite3CheckObjectName( Parse pParse, string zName )
  752. {
  753. if ( 0 == pParse.db.init.busy && pParse.nested == 0
  754. && ( pParse.db.flags & SQLITE_WriteSchema ) == 0
  755. && zName.StartsWith( "sqlite_", System.StringComparison.InvariantCultureIgnoreCase ) )
  756. {
  757. sqlite3ErrorMsg( pParse, "object name reserved for internal use: %s", zName );
  758. return SQLITE_ERROR;
  759. }
  760. return SQLITE_OK;
  761. }
  762. /*
  763. ** Begin constructing a new table representation in memory. This is
  764. ** the first of several action routines that get called in response
  765. ** to a CREATE TABLE statement. In particular, this routine is called
  766. ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
  767. ** flag is true if the table should be stored in the auxiliary database
  768. ** file instead of in the main database file. This is normally the case
  769. ** when the "TEMP" or "TEMPORARY" keyword occurs in between
  770. ** CREATE and TABLE.
  771. **
  772. ** The new table record is initialized and put in pParse.pNewTable.
  773. ** As more of the CREATE TABLE statement is parsed, additional action
  774. ** routines will be called to add more information to this record.
  775. ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
  776. ** is called to complete the construction of the new table record.
  777. */
  778. static void sqlite3StartTable(
  779. Parse pParse, /* Parser context */
  780. Token pName1, /* First part of the name of the table or view */
  781. Token pName2, /* Second part of the name of the table or view */
  782. int isTemp, /* True if this is a TEMP table */
  783. int isView, /* True if this is a VIEW */
  784. int isVirtual, /* True if this is a VIRTUAL table */
  785. int noErr /* Do nothing if table already exists */
  786. )
  787. {
  788. Table pTable;
  789. string zName = null; /* The name of the new table */
  790. sqlite3 db = pParse.db;
  791. Vdbe v;
  792. int iDb; /* Database number to create the table in */
  793. Token pName = new Token(); /* Unqualified name of the table to create */
  794. /* The table or view name to create is passed to this routine via tokens
  795. ** pName1 and pName2. If the table name was fully qualified, for example:
  796. **
  797. ** CREATE TABLE xxx.yyy (...);
  798. **
  799. ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
  800. ** the table name is not fully qualified, i.e.:
  801. **
  802. ** CREATE TABLE yyy(...);
  803. **
  804. ** Then pName1 is set to "yyy" and pName2 is "".
  805. **
  806. ** The call below sets the pName pointer to point at the token (pName1 or
  807. ** pName2) that stores the unqualified table name. The variable iDb is
  808. ** set to the index of the database that the table or view is to be
  809. ** created in.
  810. */
  811. iDb = sqlite3TwoPartName( pParse, pName1, pName2, ref pName );
  812. if ( iDb < 0 )
  813. return;
  814. if ( 0 == OMIT_TEMPDB && isTemp != 0 && pName2.n > 0 && iDb != 1 )
  815. {
  816. /* If creating a temp table, the name may not be qualified. Unless
  817. ** the database name is "temp" anyway. */
  818. sqlite3ErrorMsg( pParse, "temporary table name must be unqualified" );
  819. return;
  820. }
  821. if ( OMIT_TEMPDB == 0 && isTemp != 0 )
  822. iDb = 1;
  823. pParse.sNameToken = pName;
  824. zName = sqlite3NameFromToken( db, pName );
  825. if ( zName == null )
  826. return;
  827. if ( SQLITE_OK != sqlite3CheckObjectName( pParse, zName ) )
  828. {
  829. goto begin_table_error;
  830. }
  831. if ( db.init.iDb == 1 )
  832. isTemp = 1;
  833. #if !SQLITE_OMIT_AUTHORIZATION
  834. Debug.Assert( (isTemp & 1)==isTemp );
  835. {
  836. int code;
  837. char *zDb = db.aDb[iDb].zName;
  838. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
  839. goto begin_table_error;
  840. }
  841. if( isView ){
  842. if( OMIT_TEMPDB ==0&& isTemp ){
  843. code = SQLITE_CREATE_TEMP_VIEW;
  844. }else{
  845. code = SQLITE_CREATE_VIEW;
  846. }
  847. }else{
  848. if( OMIT_TEMPDB ==0&& isTemp ){
  849. code = SQLITE_CREATE_TEMP_TABLE;
  850. }else{
  851. code = SQLITE_CREATE_TABLE;
  852. }
  853. }
  854. if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
  855. goto begin_table_error;
  856. }
  857. }
  858. #endif
  859. /* Make sure the new table name does not collide with an existing
  860. ** index or table name in the same database. Issue an error message if
  861. ** it does. The exception is if the statement being parsed was passed
  862. ** to an sqlite3_declare_vtab() call. In that case only the column names
  863. ** and types will be used, so there is no need to test for namespace
  864. ** collisions.
  865. */
  866. if ( !IN_DECLARE_VTAB )
  867. {
  868. String zDb = db.aDb[iDb].zName;
  869. if ( SQLITE_OK != sqlite3ReadSchema( pParse ) )
  870. {
  871. goto begin_table_error;
  872. }
  873. pTable = sqlite3FindTable( db, zName, zDb );
  874. if ( pTable != null )
  875. {
  876. if ( noErr == 0 )
  877. {
  878. sqlite3ErrorMsg( pParse, "table %T already exists", pName );
  879. }
  880. goto begin_table_error;
  881. }
  882. if ( sqlite3FindIndex( db, zName, zDb ) != null )
  883. {
  884. sqlite3ErrorMsg( pParse, "there is already an index named %s", zName );
  885. goto begin_table_error;
  886. }
  887. }
  888. pTable = new Table();// sqlite3DbMallocZero(db, Table).Length;
  889. if ( pTable == null )
  890. {
  891. // db.mallocFailed = 1;
  892. pParse.rc = SQLITE_NOMEM;
  893. pParse.nErr++;
  894. goto begin_table_error;
  895. }
  896. pTable.zName = zName;
  897. pTable.iPKey = -1;
  898. pTable.pSchema = db.aDb[iDb].pSchema;
  899. pTable.nRef = 1;
  900. pTable.nRowEst = 1000000;
  901. Debug.Assert( pParse.pNewTable == null );
  902. pParse.pNewTable = pTable;
  903. /* If this is the magic sqlite_sequence table used by autoincrement,
  904. ** then record a pointer to this table in the main database structure
  905. ** so that INSERT can find the table easily.
  906. */
  907. #if !SQLITE_OMIT_AUTOINCREMENT
  908. if ( pParse.nested == 0 && zName == "sqlite_sequence" )
  909. {
  910. pTable.pSchema.pSeqTab = pTable;
  911. }
  912. #endif
  913. /* Begin generating the code that will insert the table record into
  914. ** the SQLITE_MASTER table. Note in particular that we must go ahead
  915. ** and allocate the record number for the table entry now. Before any
  916. ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
  917. ** indices to be created and the table record must come before the
  918. ** indices. Hence, the record number for the table must be allocated
  919. ** now.
  920. */
  921. if ( 0 == db.init.busy && ( v = sqlite3GetVdbe( pParse ) ) != null )
  922. {
  923. int j1;
  924. int fileFormat;
  925. int reg1, reg2, reg3;
  926. sqlite3BeginWriteOperation( pParse, 0, iDb );
  927. if ( isVirtual != 0 )
  928. {
  929. sqlite3VdbeAddOp0( v, OP_VBegin );
  930. }
  931. /* If the file format and encoding in the database have not been set,
  932. ** set them now.
  933. */
  934. reg1 = pParse.regRowid = ++pParse.nMem;
  935. reg2 = pParse.regRoot = ++pParse.nMem;
  936. reg3 = ++pParse.nMem;
  937. sqlite3VdbeAddOp3( v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT );
  938. sqlite3VdbeUsesBtree( v, iDb );
  939. j1 = sqlite3VdbeAddOp1( v, OP_If, reg3 );
  940. fileFormat = ( db.flags & SQLITE_LegacyFileFmt ) != 0 ?
  941. 1 : SQLITE_MAX_FILE_FORMAT;
  942. sqlite3VdbeAddOp2( v, OP_Integer, fileFormat, reg3 );
  943. sqlite3VdbeAddOp3( v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3 );
  944. sqlite3VdbeAddOp2( v, OP_Integer, ENC( db ), reg3 );
  945. sqlite3VdbeAddOp3( v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3 );
  946. sqlite3VdbeJumpHere( v, j1 );
  947. /* This just creates a place-holder record in the sqlite_master table.
  948. ** The record created does not contain anything yet. It will be replaced
  949. ** by the real entry in code generated at sqlite3EndTable().
  950. **
  951. ** The rowid for the new entry is left in register pParse->regRowid.
  952. ** The root page number of the new table is left in reg pParse->regRoot.
  953. ** The rowid and root page number values are needed by the code that
  954. ** sqlite3EndTable will generate.
  955. */
  956. if ( isView != 0 || isVirtual != 0 )
  957. {
  958. sqlite3VdbeAddOp2( v, OP_Integer, 0, reg2 );
  959. }
  960. else
  961. {
  962. sqlite3VdbeAddOp2( v, OP_CreateTable, iDb, reg2 );
  963. }
  964. sqlite3OpenMasterTable( pParse, iDb );
  965. sqlite3VdbeAddOp2( v, OP_NewRowid, 0, reg1 );
  966. sqlite3VdbeAddOp2( v, OP_Null, 0, reg3 );
  967. sqlite3VdbeAddOp3( v, OP_Insert, 0, reg3, reg1 );
  968. sqlite3VdbeChangeP5( v, OPFLAG_APPEND );
  969. sqlite3VdbeAddOp0( v, OP_Close );
  970. }
  971. /* Normal (non-error) return. */
  972. return;
  973. /* If an error occurs, we jump here */
  974. begin_table_error:
  975. sqlite3DbFree( db, ref zName );
  976. return;
  977. }
  978. /*
  979. ** This macro is used to compare two strings in a case-insensitive manner.
  980. ** It is slightly faster than calling sqlite3StrICmp() directly, but
  981. ** produces larger code.
  982. **
  983. ** WARNING: This macro is not compatible with the strcmp() family. It
  984. ** returns true if the two strings are equal, otherwise false.
  985. */
  986. //#define STRICMP(x, y) (\
  987. //sqlite3UpperToLower[*(unsigned char *)(x)]== \
  988. //sqlite3UpperToLower[*(unsigned char *)(y)] \
  989. //&& sqlite3StrICmp((x)+1,(y)+1)==0 )
  990. /*
  991. ** Add a new column to the table currently being constructed.
  992. **
  993. ** The parser calls this routine once for each column declaration
  994. ** in a CREATE TABLE statement. sqlite3StartTable() gets called
  995. ** first to get things going. Then this routine is called for each
  996. ** column.
  997. */
  998. static void sqlite3AddColumn( Parse pParse, Token pName )
  999. {
  1000. Table p;
  1001. int i;
  1002. string z;
  1003. Column pCol;
  1004. sqlite3 db = pParse.db;
  1005. if ( ( p = pParse.pNewTable ) == null )
  1006. return;
  1007. #if SQLITE_MAX_COLUMN || !SQLITE_MAX_COLUMN
  1008. if ( p.nCol + 1 > db.aLimit[SQLITE_LIMIT_COLUMN] )
  1009. {
  1010. sqlite3ErrorMsg( pParse, "too many columns on %s", p.zName );
  1011. return;
  1012. }
  1013. #endif
  1014. z = sqlite3NameFromToken( db, pName );
  1015. if ( z == null )
  1016. return;
  1017. for ( i = 0; i < p.nCol; i++ )
  1018. {
  1019. if ( z.Equals( p.aCol[i].zName, StringComparison.InvariantCultureIgnoreCase ) )
  1020. {//STRICMP(z, p.aCol[i].zName) ){
  1021. sqlite3ErrorMsg( pParse, "duplicate column name: %s", z );
  1022. sqlite3DbFree( db, ref z );
  1023. return;
  1024. }
  1025. }
  1026. if ( ( p.nCol & 0x7 ) == 0 )
  1027. {
  1028. //aNew = sqlite3DbRealloc(db,p.aCol,(p.nCol+8)*sizeof(p.aCol[0]));
  1029. //if( aNew==0 ){
  1030. // sqlite3DbFree(db,ref z);
  1031. // return;
  1032. //}
  1033. Array.Resize( ref p.aCol, p.nCol + 8 );
  1034. }
  1035. p.aCol[p.nCol] = new Column();
  1036. pCol = p.aCol[p.nCol];
  1037. //memset(pCol, 0, sizeof(p.aCol[0]));
  1038. pCol.zName = z;
  1039. /* If there is no type specified, columns have the default affinity
  1040. ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
  1041. ** be called next to set pCol.affinity correctly.
  1042. */
  1043. pCol.affinity = SQLITE_AFF_NONE;
  1044. p.nCol++;
  1045. }
  1046. /*
  1047. ** This routine is called by the parser while in the middle of
  1048. ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
  1049. ** been seen on a column. This routine sets the notNull flag on
  1050. ** the column currently under construction.
  1051. */
  1052. static void sqlite3AddNotNull( Parse pParse, int onError )
  1053. {
  1054. Table p;
  1055. p = pParse.pNewTable;
  1056. if ( p == null || NEVER( p.nCol < 1 ) )
  1057. return;
  1058. p.aCol[p.nCol - 1].notNull = (u8)onError;
  1059. }
  1060. /*
  1061. ** Scan the column type name zType (length nType) and return the
  1062. ** associated affinity type.
  1063. **
  1064. ** This routine does a case-independent search of zType for the
  1065. ** substrings in the following table. If one of the substrings is
  1066. ** found, the corresponding affinity is returned. If zType contains
  1067. ** more than one of the substrings, entries toward the top of
  1068. ** the table take priority. For example, if zType is 'BLOBINT',
  1069. ** SQLITE_AFF_INTEGER is returned.
  1070. **
  1071. ** Substring | Affinity
  1072. ** --------------------------------
  1073. ** 'INT' | SQLITE_AFF_INTEGER
  1074. ** 'CHAR' | SQLITE_AFF_TEXT
  1075. ** 'CLOB' | SQLITE_AFF_TEXT
  1076. ** 'TEXT' | SQLITE_AFF_TEXT
  1077. ** 'BLOB' | SQLITE_AFF_NONE
  1078. ** 'REAL' | SQLITE_AFF_REAL
  1079. ** 'FLOA' | SQLITE_AFF_REAL
  1080. ** 'DOUB' | SQLITE_AFF_REAL
  1081. **
  1082. ** If none of the substrings in the above table are found,
  1083. ** SQLITE_AFF_NUMERIC is returned.
  1084. */
  1085. static char sqlite3AffinityType( string zIn )
  1086. {
  1087. //u32 h = 0;
  1088. //char aff = SQLITE_AFF_NUMERIC;
  1089. zIn = zIn.ToLower();
  1090. if ( zIn.Contains( "char" ) || zIn.Contains( "clob" ) || zIn.Contains( "text" ) )
  1091. return SQLITE_AFF_TEXT;
  1092. if ( zIn.Contains( "blob" ) )
  1093. return SQLITE_AFF_NONE;
  1094. if ( zIn.Contains( "doub" ) || zIn.Contains( "floa" ) || zIn.Contains( "real" ) )
  1095. return SQLITE_AFF_REAL;
  1096. if ( zIn.Contains( "int" ) )
  1097. return SQLITE_AFF_INTEGER;
  1098. return SQLITE_AFF_NUMERIC;
  1099. // string zEnd = pType.z.Substring(pType.n);
  1100. // while( zIn!=zEnd ){
  1101. // h = (h<<8) + sqlite3UpperToLower[*zIn];
  1102. // zIn++;
  1103. // if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
  1104. // aff = SQLITE_AFF_TEXT;
  1105. // }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
  1106. // aff = SQLITE_AFF_TEXT;
  1107. // }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
  1108. // aff = SQLITE_AFF_TEXT;
  1109. // }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
  1110. // && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
  1111. // aff = SQLITE_AFF_NONE;
  1112. //#if !SQLITE_OMIT_FLOATING_POINT
  1113. // }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
  1114. // && aff==SQLITE_AFF_NUMERIC ){
  1115. // aff = SQLITE_AFF_REAL;
  1116. // }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
  1117. // && aff==SQLITE_AFF_NUMERIC ){
  1118. // aff = SQLITE_AFF_REAL;
  1119. // }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
  1120. // && aff==SQLITE_AFF_NUMERIC ){
  1121. // aff = SQLITE_AFF_REAL;
  1122. //#endif
  1123. // }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
  1124. // aff = SQLITE_AFF_INTEGER;
  1125. // break;
  1126. // }
  1127. // }
  1128. // return aff;
  1129. }
  1130. /*
  1131. ** This routine is called by the parser while in the middle of
  1132. ** parsing a CREATE TABLE statement. The pFirst token is the first
  1133. ** token in the sequence of tokens that describe the type of the
  1134. ** column currently under construction. pLast is the last token
  1135. ** in the sequence. Use this information to construct a string
  1136. ** that contains the typename of the column and store that string
  1137. ** in zType.
  1138. */
  1139. static void sqlite3AddColumnType( Parse pParse, Token pType )
  1140. {
  1141. Table p;
  1142. Column pCol;
  1143. p = pParse.pNewTable;
  1144. if ( p == null || NEVER( p.nCol < 1 ) )
  1145. return;
  1146. pCol = p.aCol[p.nCol - 1];
  1147. Debug.Assert( pCol.zType == null );
  1148. pCol.zType = sqlite3NameFromToken( pParse.db, pType );
  1149. pCol.affinity = sqlite3AffinityType( pCol.zType );
  1150. }
  1151. /*
  1152. ** The expression is the default value for the most recently added column
  1153. ** of the table currently under construction.
  1154. **
  1155. ** Default value expressions must be constant. Raise an exception if this
  1156. ** is not the case.
  1157. **
  1158. ** This routine is called by the parser while in the middle of
  1159. ** parsing a CREATE TABLE statement.
  1160. */
  1161. static void sqlite3AddDefaultValue( Parse pParse, ExprSpan pSpan )
  1162. {
  1163. Table p;
  1164. Column pCol;
  1165. sqlite3 db = pParse.db;
  1166. p = pParse.pNewTable;
  1167. if ( p != null )
  1168. {
  1169. pCol = ( p.aCol[p.nCol - 1] );
  1170. if ( sqlite3ExprIsConstantOrFunction( pSpan.pExpr ) == 0 )
  1171. {
  1172. sqlite3ErrorMsg( pParse, "default value of column [%s] is not constant",
  1173. pCol.zName );
  1174. }
  1175. else
  1176. {
  1177. /* A copy of pExpr is used instead of the original, as pExpr contains
  1178. ** tokens that point to volatile memory. The 'span' of the expression
  1179. ** is required by pragma table_info.
  1180. */
  1181. sqlite3ExprDelete( db, ref pCol.pDflt );
  1182. pCol.pDflt = sqlite3ExprDup( db, pSpan.pExpr, EXPRDUP_REDUCE );
  1183. sqlite3DbFree( db, ref pCol.zDflt );
  1184. pCol.zDflt = pSpan.zStart.Substring( 0, pSpan.zStart.Length - pSpan.zEnd.Length );
  1185. //sqlite3DbStrNDup( db, pSpan.zStart,
  1186. // (int)( pSpan.zEnd.Length - pSpan.zStart.Length ) );
  1187. }
  1188. }
  1189. sqlite3ExprDelete( db, ref pSpan.pExpr );
  1190. }
  1191. /*
  1192. ** Designate the PRIMARY KEY for the table. pList is a list of names
  1193. ** of columns that form the primary key. If pList is NULL, then the
  1194. ** most recently added column of the table is the primary key.
  1195. **
  1196. ** A table can have at most one primary key. If the table already has
  1197. ** a primary key (and this is the second primary key) then create an
  1198. ** error.
  1199. **
  1200. ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
  1201. ** then we will try to use that column as the rowid. Set the Table.iPKey
  1202. ** field of the table under construction to be the index of the
  1203. ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
  1204. ** no INTEGER PRIMARY KEY.
  1205. **
  1206. ** If the key is not an INTEGER PRIMARY KEY, then create a unique
  1207. ** index for the key. No index is created for INTEGER PRIMARY KEYs.
  1208. */
  1209. // OVERLOADS, so I don't need to rewrite parse.c
  1210. static void sqlite3AddPrimaryKey( Parse pParse, int null_2, int onError, int autoInc, int sortOrder )
  1211. {
  1212. sqlite3AddPrimaryKey( pParse, null, onError, autoInc, sortOrder );
  1213. }
  1214. static void sqlite3AddPrimaryKey(
  1215. Parse pParse, /* Parsing context */
  1216. ExprList pList, /* List of field names to be indexed */
  1217. int onError, /* What to do with a uniqueness conflict */
  1218. int autoInc, /* True if the AUTOINCREMENT keyword is present */
  1219. int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
  1220. )
  1221. {
  1222. Table pTab = pParse.pNewTable;
  1223. string zType = null;
  1224. int iCol = -1, i;
  1225. if ( pTab == null || IN_DECLARE_VTAB )
  1226. goto primary_key_exit;
  1227. if ( ( pTab.tabFlags & TF_HasPrimaryKey ) != 0 )
  1228. {
  1229. sqlite3ErrorMsg( pParse,
  1230. "table \"%s\" has more than one primary key", pTab.zName );
  1231. goto primary_key_exit;
  1232. }
  1233. pTab.tabFlags |= TF_HasPrimaryKey;
  1234. if ( pList == null )
  1235. {
  1236. iCol = pTab.nCol - 1;
  1237. pTab.aCol[iCol].isPrimKey = 1;
  1238. }
  1239. else
  1240. {
  1241. for ( i = 0; i < pList.nExpr; i++ )
  1242. {
  1243. for ( iCol = 0; iCol < pTab.nCol; iCol++ )
  1244. {
  1245. if ( pList.a[i].zName.Equals( pTab.aCol[iCol].zName, StringComparison.InvariantCultureIgnoreCase ) )
  1246. {
  1247. break;
  1248. }
  1249. }
  1250. if ( iCol < pTab.nCol )
  1251. {
  1252. pTab.aCol[iCol].isPrimKey = 1;
  1253. }
  1254. }
  1255. if ( pList.nExpr > 1 )
  1256. iCol = -1;
  1257. }
  1258. if ( iCol >= 0 && iCol < pTab.nCol )
  1259. {
  1260. zType = pTab.aCol[iCol].zType;
  1261. }
  1262. if ( zType != null && zType.Equals( "INTEGER", StringComparison.InvariantCultureIgnoreCase )
  1263. && sortOrder == SQLITE_SO_ASC )
  1264. {
  1265. pTab.iPKey = iCol;
  1266. pTab.keyConf = (byte)onError;
  1267. Debug.Assert( autoInc == 0 || autoInc == 1 );
  1268. pTab.tabFlags |= (u8)( autoInc * TF_Autoincrement );
  1269. }
  1270. else if ( autoInc != 0 )
  1271. {
  1272. #if !SQLITE_OMIT_AUTOINCREMENT
  1273. sqlite3ErrorMsg( pParse, "AUTOINCREMENT is only allowed on an " +
  1274. "INTEGER PRIMARY KEY" );
  1275. #endif
  1276. }
  1277. else
  1278. {
  1279. Index p;
  1280. p = sqlite3CreateIndex( pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0 );
  1281. if ( p != null )
  1282. {
  1283. p.autoIndex = 2;
  1284. }
  1285. pList = null;
  1286. }
  1287. primary_key_exit:
  1288. sqlite3ExprListDelete( pParse.db, ref pList );
  1289. return;
  1290. }
  1291. /*
  1292. ** Add a new CHECK constraint to the table currently under construction.
  1293. */
  1294. static void sqlite3AddCheckConstraint(
  1295. Parse pParse, /* Parsing context */
  1296. Expr pCheckExpr /* The check expression */
  1297. )
  1298. {
  1299. sqlite3 db = pParse.db;
  1300. #if !SQLITE_OMIT_CHECK
  1301. Table pTab = pParse.pNewTable;
  1302. if ( pTab != null && !IN_DECLARE_VTAB )
  1303. {
  1304. pTab.pCheck = sqlite3ExprAnd( db, pTab.pCheck, pCheckExpr );
  1305. }
  1306. else
  1307. #endif
  1308. {
  1309. sqlite3ExprDelete( db, ref pCheckExpr );
  1310. }
  1311. }
  1312. /*
  1313. ** Set the collation function of the most recently parsed table column
  1314. ** to the CollSeq given.
  1315. */
  1316. static void sqlite3AddCollateType( Parse pParse, Token pToken )
  1317. {
  1318. Table p;
  1319. int i;
  1320. string zColl; /* Dequoted name of collation sequence */
  1321. sqlite3 db;
  1322. if ( ( p = pParse.pNewTable ) == null )
  1323. return;
  1324. i = p.nCol - 1;
  1325. db = pParse.db;
  1326. zColl = sqlite3NameFromToken( db, pToken );
  1327. if ( zColl == null )
  1328. return;
  1329. if ( sqlite3LocateCollSeq( pParse, zColl ) != null )
  1330. {
  1331. Index pIdx;
  1332. p.aCol[i].zColl = zColl;
  1333. /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
  1334. ** then an index may have been created on this column before the
  1335. ** collation type was added. Correct this if it is the case.
  1336. */
  1337. for ( pIdx = p.pIndex; pIdx != null; pIdx = pIdx.pNext )
  1338. {
  1339. Debug.Assert( pIdx.nColumn == 1 );
  1340. if ( pIdx.aiColumn[0] == i )
  1341. {
  1342. pIdx.azColl[0] = p.aCol[i].zColl;
  1343. }
  1344. }
  1345. }
  1346. else
  1347. {
  1348. sqlite3DbFree( db, ref zColl );
  1349. }
  1350. }
  1351. /*
  1352. ** This function returns the collation sequence for database native text
  1353. ** encoding identified by the string zName, length nName.
  1354. **
  1355. ** If the requested collation sequence is not available, or not available
  1356. ** in the database native encoding, the collation factory is invoked to
  1357. ** request it. If the collation factory does not supply such a sequence,
  1358. ** and the sequence is available in another text encoding, then that is
  1359. ** returned instead.
  1360. **
  1361. ** If no versions of the requested collations sequence are available, or
  1362. ** another error occurs, NULL is returned and an error message written into
  1363. ** pParse.
  1364. **
  1365. ** This routine is a wrapper around sqlite3FindCollSeq(). This routine
  1366. ** invokes the collation factory if the named collation cannot be found
  1367. ** and generates an error message.
  1368. **
  1369. ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
  1370. */
  1371. static CollSeq sqlite3LocateCollSeq( Parse pParse, string zName )
  1372. {
  1373. sqlite3 db = pParse.db;
  1374. u8 enc = db.aDb[0].pSchema.enc;// ENC(db);
  1375. u8 initbusy = db.init.busy;
  1376. CollSeq pColl;
  1377. pColl = sqlite3FindCollSeq( db, enc, zName, initbusy );
  1378. if ( 0 == initbusy && ( pColl == null || pColl.xCmp == null ) )
  1379. {
  1380. pColl = sqlite3GetCollSeq( db, enc, pColl, zName );
  1381. if ( pColl == null )
  1382. {
  1383. sqlite3ErrorMsg( pParse, "no such collation sequence: %s", zName );
  1384. }
  1385. }
  1386. return pColl;
  1387. }
  1388. /*
  1389. ** Generate code that will increment the schema cookie.
  1390. **
  1391. ** The schema cookie is used to determine when the schema for the
  1392. ** database changes. After each schema change, the cookie value
  1393. ** changes. When a process first reads the schema it records the
  1394. ** cookie. Thereafter, whenever it goes to access the database,
  1395. ** it checks the cookie to make sure the schema has not changed
  1396. ** since it was last read.
  1397. **
  1398. ** This plan is not completely bullet-proof. It is possible for
  1399. ** the schema to change multiple times and for the cookie to be
  1400. ** set back to prior value. But schema changes are infrequent
  1401. ** and the probability of hitting the same cookie value is only
  1402. ** 1 chance in 2^32. So we're safe enough.
  1403. */
  1404. static void sqlite3ChangeCookie( Parse pParse, int iDb )
  1405. {
  1406. int r1 = sqlite3GetTempReg( pParse );
  1407. sqlite3 db = pParse.db;
  1408. Vdbe v = pParse.pVdbe;
  1409. sqlite3VdbeAddOp2( v, OP_Integer, db.aDb[iDb].pSchema.schema_cookie + 1, r1 );
  1410. sqlite3VdbeAddOp3( v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1 );
  1411. sqlite3ReleaseTempReg( pParse, r1 );
  1412. }
  1413. /*
  1414. ** Measure the number of characters needed to output the given
  1415. ** identifier. The number returned includes any quotes used
  1416. ** but does not include the null terminator.
  1417. **
  1418. ** The estimate is conservative. It might be larger that what is
  1419. ** really needed.
  1420. */
  1421. static int identLength( string z )
  1422. {
  1423. int n;
  1424. for ( n = 0; n < z.Length; n++ )
  1425. {
  1426. if ( z[n] == (byte)'"' )
  1427. {
  1428. n++;
  1429. }
  1430. }
  1431. return n + 2;
  1432. }
  1433. /*
  1434. ** The first parameter is a pointer to an output buffer. The second
  1435. ** parameter is a pointer to an integer that contains the offset at
  1436. ** which to write into the output buffer. This function copies the
  1437. ** nul-terminated string pointed to by the third parameter, zSignedIdent,
  1438. ** to the specified offset in the buffer and updates *pIdx to refer
  1439. ** to the first byte after the last byte written before returning.
  1440. **
  1441. ** If the string zSignedIdent consists entirely of alpha-numeric
  1442. ** characters, does not begin with a digit and is not an SQL keyword,
  1443. ** then it is copied to the output buffer exactly as it is. Otherwise,
  1444. ** it is quoted using double-quotes.
  1445. */
  1446. static void identPut( StringBuilder z, ref int pIdx, string zSignedIdent )
  1447. {
  1448. string zIdent = zSignedIdent;
  1449. int i;
  1450. int j;
  1451. bool needQuote;
  1452. i = pIdx;
  1453. for ( j = 0; j < zIdent.Length; j++ )
  1454. {
  1455. if ( !sqlite3Isalnum( zIdent[j] ) && zIdent[j] != '_' )
  1456. break;
  1457. }
  1458. needQuote = sqlite3Isdigit( zIdent[0] ) || sqlite3KeywordCode( zIdent, j ) != TK_ID;
  1459. if ( !needQuote )
  1460. {
  1461. needQuote = ( j < zIdent.Length && zIdent[j] != 0 );
  1462. }
  1463. if ( needQuote )
  1464. {
  1465. if ( i == z.Length )
  1466. z.Append( '\0' );
  1467. z[i++] = '"';
  1468. }
  1469. for ( j = 0; j < zIdent.Length; j++ )
  1470. {
  1471. if ( i == z.Length )
  1472. z.Append( '\0' );
  1473. z[i++] = zIdent[j];
  1474. if ( zIdent[j] == '"' )
  1475. {
  1476. if ( i == z.Length )
  1477. z.Append( '\0' );
  1478. z[i++] = '"';
  1479. }
  1480. }
  1481. if ( needQuote )
  1482. {
  1483. if ( i == z.Length )
  1484. z.Append( '\0' );
  1485. z[i++] = '"';
  1486. }
  1487. //z[i] = 0;
  1488. pIdx = i;
  1489. }
  1490. /*
  1491. ** Generate a CREATE TABLE statement appropriate for the given
  1492. ** table. Memory to hold the text of the statement is obtained
  1493. ** from sqliteMalloc() and must be freed by the calling function.
  1494. */
  1495. static string createTableStmt( sqlite3 db, Table p )
  1496. {
  1497. int i, k, n;
  1498. StringBuilder zStmt;
  1499. string zSep;
  1500. string zSep2;
  1501. string zEnd;
  1502. Column pCol;
  1503. n = 0;
  1504. for ( i = 0; i < p.nCol; i++ )
  1505. {//, pCol++){
  1506. pCol = p.aCol[i];
  1507. n += identLength( pCol.zName ) + 5;
  1508. }
  1509. n += identLength( p.zName );
  1510. if ( n < 50 )
  1511. {
  1512. zSep = "";
  1513. zSep2 = ",";
  1514. zEnd = ")";
  1515. }
  1516. else
  1517. {
  1518. zSep = "\n ";
  1519. zSep2 = ",\n ";
  1520. zEnd = "\n)";
  1521. }
  1522. n += 35 + 6 * p.nCol;
  1523. zStmt = new StringBuilder( n );
  1524. //zStmt = sqlite3DbMallocRaw(0, n);
  1525. //if( zStmt==0 ){
  1526. // db.mallocFailed = 1;
  1527. // return 0;
  1528. //}
  1529. //sqlite3_snprintf(n, zStmt,"CREATE TABLE ");
  1530. zStmt.Append( "CREATE TABLE " );
  1531. k = sqlite3Strlen30( zStmt );
  1532. identPut( zStmt, ref k, p.zName );
  1533. zStmt.Append( '(' );//zStmt[k++] = '(';
  1534. for ( i = 0; i < p.nCol; i++ )
  1535. {//, pCol++){
  1536. pCol = p.aCol[i];
  1537. string[] azType = new string[] {
  1538. /* SQLITE_AFF_TEXT */ " TEXT",
  1539. /* SQLITE_AFF_NONE */ "",
  1540. /* SQLITE_AFF_NUMERIC */ " NUM",
  1541. /* SQLITE_AFF_INTEGER */ " INT",
  1542. /* SQLITE_AFF_REAL */ " REAL"
  1543. };
  1544. int len;
  1545. string zType;
  1546. zStmt.Append( zSep );// sqlite3_snprintf(n-k, zStmt[k], zSep);
  1547. k = sqlite3Strlen30( zStmt );// k += strlen(zStmt[k]);
  1548. zSep = zSep2;
  1549. identPut( zStmt, ref k, pCol.zName );
  1550. Debug.Assert( pCol.affinity - SQLITE_AFF_TEXT >= 0 );
  1551. Debug.Assert( pCol.affinity - SQLITE_AFF_TEXT < azType.Length );//sizeof(azType)/sizeof(azType[0]) );
  1552. testcase( pCol.affinity == SQLITE_AFF_TEXT );
  1553. testcase( pCol.affinity == SQLITE_AFF_NONE );
  1554. testcase( pCol.affinity == SQLITE_AFF_NUMERIC );
  1555. testcase( pCol.affinity == SQLITE_AFF_INTEGER );
  1556. testcase( pCol.affinity == SQLITE_AFF_REAL );
  1557. zType = azType[pCol.affinity - SQLITE_AFF_TEXT];
  1558. len = sqlite3Strlen30( zType );
  1559. Debug.Assert( pCol.affinity == SQLITE_AFF_NONE
  1560. || pCol.affinity == sqlite3AffinityType( zType ) );
  1561. zStmt.Append( zType );// memcpy( &zStmt[k], zType, len );
  1562. k += len;
  1563. Debug.Assert( k <= n );
  1564. }
  1565. zStmt.Append( zEnd );//sqlite3_snprintf(n-k, zStmt[k], "%s", zEnd);
  1566. return zStmt.ToString();
  1567. }
  1568. /*
  1569. ** This routine is called to report the final ")" that terminates
  1570. ** a CREATE TABLE statement.
  1571. **
  1572. ** The table structure that other action routines have been building
  1573. ** is added to the internal hash tables, assuming no errors have
  1574. ** occurred.
  1575. **
  1576. ** An entry for the table is made in the master table on disk, unless
  1577. ** this is a temporary table or db.init.busy==1. When db.init.busy==1
  1578. ** it means we are reading the sqlite_master table because we just
  1579. ** connected to the database or because the sqlite_master table has
  1580. ** recently changed, so the entry for this table already exists in
  1581. ** the sqlite_master table. We do not want to create it again.
  1582. **
  1583. ** If the pSelect argument is not NULL, it means that this routine
  1584. ** was called to create a table generated from a
  1585. ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
  1586. ** the new table will match the result set of the SELECT.
  1587. */
  1588. // OVERLOADS, so I don't need to rewrite parse.c
  1589. static void sqlite3EndTable( Parse pParse, Token pCons, Token pEnd, int null_4 )
  1590. {
  1591. sqlite3EndTable( pParse, pCons, pEnd, null );
  1592. }
  1593. static void sqlite3EndTable( Parse pParse, int null_2, int null_3, Select pSelect )
  1594. {
  1595. sqlite3EndTable( pParse, null, null, pSelect );
  1596. }
  1597. static void sqlite3EndTable(
  1598. Parse pParse, /* Parse context */
  1599. Token pCons, /* The ',' token after the last column defn. */
  1600. Token pEnd, /* The final ')' token in the CREATE TABLE */
  1601. Select pSelect /* Select from a "CREATE ... AS SELECT" */
  1602. )
  1603. {
  1604. Table p;
  1605. sqlite3 db = pParse.db;
  1606. int iDb;
  1607. if ( ( pEnd == null && pSelect == null ) /*|| db.mallocFailed != 0 */ )
  1608. {
  1609. return;
  1610. }
  1611. p = pParse.pNewTable;
  1612. if ( p == null )
  1613. return;
  1614. Debug.Assert( 0 == db.init.busy || pSelect == null );
  1615. iDb = sqlite3SchemaToIndex( db, p.pSchema );
  1616. #if !SQLITE_OMIT_CHECK
  1617. /* Resolve names in all CHECK constraint expressions.
  1618. */
  1619. if ( p.pCheck != null )
  1620. {
  1621. SrcList sSrc; /* Fake SrcList for pParse.pNewTable */
  1622. NameContext sNC; /* Name context for pParse.pNewTable */
  1623. sNC = new NameContext();// memset(sNC, 0, sizeof(sNC));
  1624. sSrc = new SrcList();// memset(sSrc, 0, sizeof(sSrc));
  1625. sSrc.nSrc = 1;
  1626. sSrc.a = new SrcList_item[1];
  1627. sSrc.a[0] = new SrcList_item();
  1628. sSrc.a[0].zName = p.zName;
  1629. sSrc.a[0].pTab = p;
  1630. sSrc.a[0].iCursor = -1;
  1631. sNC.pParse = pParse;
  1632. sNC.pSrcList = sSrc;
  1633. sNC.isCheck = 1;
  1634. if ( sqlite3ResolveExprNames( sNC, ref p.pCheck ) != 0 )
  1635. {
  1636. return;
  1637. }
  1638. }
  1639. #endif // * !SQLITE_OMIT_CHECK) */
  1640. /* If the db.init.busy is 1 it means we are reading the SQL off the
  1641. ** "sqlite_master" or "sqlite_temp_master" table on the disk.
  1642. ** So do not write to the disk again. Extract the root page number
  1643. ** for the table from the db.init.newTnum field. (The page number
  1644. ** should have been put there by the sqliteOpenCb routine.)
  1645. */
  1646. if ( db.init.busy != 0 )
  1647. {
  1648. p.tnum = db.init.newTnum;
  1649. }
  1650. /* If not initializing, then create a record for the new table
  1651. ** in the SQLITE_MASTER table of the database.
  1652. **
  1653. ** If this is a TEMPORARY table, write the entry into the auxiliary
  1654. ** file instead of into the main database file.
  1655. */
  1656. if ( 0 == db.init.busy )
  1657. {
  1658. int n;
  1659. Vdbe v;
  1660. String zType = ""; /* "view" or "table" */
  1661. String zType2 = ""; /* "VIEW" or "TABLE" */
  1662. String zStmt = ""; /* Text of the CREATE TABLE or CREATE VIEW statement */
  1663. v = sqlite3GetVdbe( pParse );
  1664. if ( NEVER( v == null ) )
  1665. return;
  1666. sqlite3VdbeAddOp1( v, OP_Close, 0 );
  1667. /*
  1668. ** Initialize zType for the new view or table.
  1669. */
  1670. if ( p.pSelect == null )
  1671. {
  1672. /* A regular table */
  1673. zType = "table";
  1674. zType2 = "TABLE";
  1675. #if !SQLITE_OMIT_VIEW
  1676. }
  1677. else
  1678. {
  1679. /* A view */
  1680. zType = "view";
  1681. zType2 = "VIEW";
  1682. #endif
  1683. }
  1684. /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
  1685. ** statement to populate the new table. The root-page number for the
  1686. ** new table is in register pParse->regRoot.
  1687. **
  1688. ** Once the SELECT has been coded by sqlite3Select(), it is in a
  1689. ** suitable state to query for the column names and types to be used
  1690. ** by the new table.
  1691. **
  1692. ** A shared-cache write-lock is not required to write to the new table,
  1693. ** as a schema-lock must have already been obtained to create it. Since
  1694. ** a schema-lock excludes all other database users, the write-lock would
  1695. ** be redundant.
  1696. */
  1697. if ( pSelect != null )
  1698. {
  1699. SelectDest dest = new SelectDest();
  1700. Table pSelTab;
  1701. Debug.Assert( pParse.nTab == 1 );
  1702. sqlite3VdbeAddOp3( v, OP_OpenWrite, 1, pParse.regRoot, iDb );
  1703. sqlite3VdbeChangeP5( v, 1 );
  1704. pParse.nTab = 2;
  1705. sqlite3SelectDestInit( dest, SRT_Table, 1 );
  1706. sqlite3Select( pParse, pSelect, ref dest );
  1707. sqlite3VdbeAddOp1( v, OP_Close, 1 );
  1708. if ( pParse.nErr == 0 )
  1709. {
  1710. pSelTab = sqlite3ResultSetOfSelect( pParse, pSelect );
  1711. if ( pSelTab == null )
  1712. return;
  1713. Debug.Assert( p.aCol == null );
  1714. p.nCol = pSelTab.nCol;
  1715. p.aCol = pSelTab.aCol;
  1716. pSelTab.nCol = 0;
  1717. pSelTab.aCol = null;
  1718. sqlite3DeleteTable( db, ref pSelTab );
  1719. }
  1720. }
  1721. /* Compute the complete text of the CREATE statement */
  1722. if ( pSelect != null )
  1723. {
  1724. zStmt = createTableStmt( db, p );
  1725. }
  1726. else
  1727. {
  1728. n = (int)( pParse.sNameToken.z.Length - pEnd.z.Length ) + 1;
  1729. zStmt = sqlite3MPrintf( db,
  1730. "CREATE %s %.*s", zType2, n, pParse.sNameToken.z
  1731. );
  1732. }
  1733. /* A slot for the record has already been allocated in the
  1734. ** SQLITE_MASTER table. We just need to update that slot with all
  1735. ** the information we've collected.
  1736. */
  1737. sqlite3NestedParse( pParse,
  1738. "UPDATE %Q.%s " +
  1739. "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q " +
  1740. "WHERE rowid=#%d",
  1741. db.aDb[iDb].zName, SCHEMA_TABLE( iDb ),
  1742. zType,
  1743. p.zName,
  1744. p.zName,
  1745. pParse.regRoot,
  1746. zStmt,
  1747. pParse.regRowid
  1748. );
  1749. sqlite3DbFree( db, ref zStmt );
  1750. sqlite3ChangeCookie( pParse, iDb );
  1751. #if !SQLITE_OMIT_AUTOINCREMENT
  1752. /* Check to see if we need to create an sqlite_sequence table for
  1753. ** keeping track of autoincrement keys.
  1754. */
  1755. if ( ( p.tabFlags & TF_Autoincrement ) != 0 )
  1756. {
  1757. Db pDb = db.aDb[iDb];
  1758. if ( pDb.pSchema.pSeqTab == null )
  1759. {
  1760. sqlite3NestedParse( pParse,
  1761. "CREATE TABLE %Q.sqlite_sequence(name,seq)",
  1762. pDb.zName
  1763. );
  1764. }
  1765. }
  1766. #endif
  1767. /* Reparse everything to update our internal data structures */
  1768. sqlite3VdbeAddOp4( v, OP_ParseSchema, iDb, 0, 0,
  1769. sqlite3MPrintf( db, "tbl_name='%q'", p.zName ), P4_DYNAMIC );
  1770. }
  1771. /* Add the table to the in-memory representation of the database.
  1772. */
  1773. if ( db.init.busy != 0 )
  1774. {
  1775. Table pOld;
  1776. Schema pSchema = p.pSchema;
  1777. pOld = sqlite3HashInsert( ref pSchema.tblHash, p.zName,
  1778. sqlite3Strlen30( p.zName ), p );
  1779. if ( pOld != null )
  1780. {
  1781. Debug.Assert( p == pOld ); /* Malloc must have failed inside HashInsert() */
  1782. // db.mallocFailed = 1;
  1783. return;
  1784. }
  1785. pParse.pNewTable = null;
  1786. db.nTable++;
  1787. db.flags |= SQLITE_InternChanges;
  1788. #if !SQLITE_OMIT_ALTERTABLE
  1789. if ( p.pSelect == null )
  1790. {
  1791. string zName = pParse.sNameToken.z;
  1792. int nName;
  1793. Debug.Assert( pSelect == null && pCons != null && pEnd != null );
  1794. if ( pCons.z == null )
  1795. {
  1796. pCons = pEnd;
  1797. }
  1798. nName = zName.Length - pCons.z.Length;
  1799. p.addColOffset = 13 + nName; // sqlite3Utf8CharLen(zName, nName);
  1800. }
  1801. #endif
  1802. }
  1803. }
  1804. #if !SQLITE_OMIT_VIEW
  1805. /*
  1806. ** The parser calls this routine in order to create a new VIEW
  1807. */
  1808. static void sqlite3CreateView(
  1809. Parse pParse, /* The parsing context */
  1810. Token pBegin, /* The CREATE token that begins the statement */
  1811. Token pName1, /* The token that holds the name of the view */
  1812. Token pName2, /* The token that holds the name of the view */
  1813. Select pSelect, /* A SELECT statement that will become the new view */
  1814. int isTemp, /* TRUE for a TEMPORARY view */
  1815. int noErr /* Suppress error messages if VIEW already exists */
  1816. )
  1817. {
  1818. Table p;
  1819. int n;
  1820. string z;//const char *z;
  1821. Token sEnd;
  1822. DbFixer sFix = new DbFixer();
  1823. Token pName = null;
  1824. int iDb;
  1825. sqlite3 db = pParse.db;
  1826. if ( pParse.nVar > 0 )
  1827. {
  1828. sqlite3ErrorMsg( pParse, "parameters are not allowed in views" );
  1829. sqlite3SelectDelete( db, ref pSelect );
  1830. return;
  1831. }
  1832. sqlite3StartTable( pParse, pName1, pName2, isTemp, 1, 0, noErr );
  1833. p = pParse.pNewTable;
  1834. if ( p == null || pParse.nErr != 0 )
  1835. {
  1836. sqlite3SelectDelete( db, ref pSelect );
  1837. return;
  1838. }
  1839. sqlite3TwoPartName( pParse, pName1, pName2, ref pName );
  1840. iDb = sqlite3SchemaToIndex( db, p.pSchema );
  1841. if ( sqlite3FixInit( sFix, pParse, iDb, "view", pName ) != 0
  1842. && sqlite3FixSelect( sFix, pSelect ) != 0
  1843. )
  1844. {
  1845. sqlite3SelectDelete( db, ref pSelect );
  1846. return;
  1847. }
  1848. /* Make a copy of the entire SELECT statement that defines the view.
  1849. ** This will force all the Expr.token.z values to be dynamically
  1850. ** allocated rather than point to the input string - which means that
  1851. ** they will persist after the current sqlite3_exec() call returns.
  1852. */
  1853. p.pSelect = sqlite3SelectDup( db, pSelect, EXPRDUP_REDUCE );
  1854. sqlite3SelectDelete( db, ref pSelect );
  1855. //if ( db.mallocFailed != 0 )
  1856. //{
  1857. // return;
  1858. //}
  1859. if ( 0 == db.init.busy )
  1860. {
  1861. sqlite3ViewGetColumnNames( pParse, p );
  1862. }
  1863. /* Locate the end of the CREATE VIEW statement. Make sEnd point to
  1864. ** the end.
  1865. */
  1866. sEnd = pParse.sLastToken;
  1867. if ( ALWAYS( sEnd.z[0] != 0 ) && sEnd.z[0] != ';' )
  1868. {
  1869. sEnd.z = sEnd.z.Substring( sEnd.n );
  1870. }
  1871. sEnd.n = 0;
  1872. n = (int)( pBegin.z.Length - sEnd.z.Length );//sEnd.z - pBegin.z;
  1873. z = pBegin.z;
  1874. while ( ALWAYS( n > 0 ) && sqlite3Isspace( z[n - 1] ) )
  1875. {
  1876. n--;
  1877. }
  1878. sEnd.z = z.Substring( n - 1 );
  1879. sEnd.n = 1;
  1880. /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
  1881. sqlite3EndTable( pParse, null, sEnd, null );
  1882. return;
  1883. }
  1884. #else
  1885. static void sqlite3CreateView(
  1886. Parse pParse, /* The parsing context */
  1887. Token pBegin, /* The CREATE token that begins the statement */
  1888. Token pName1, /* The token that holds the name of the view */
  1889. Token pName2, /* The token that holds the name of the view */
  1890. Select pSelect, /* A SELECT statement that will become the new view */
  1891. int isTemp, /* TRUE for a TEMPORARY view */
  1892. int noErr /* Suppress error messages if VIEW already exists */
  1893. )
  1894. {
  1895. }
  1896. #endif // * SQLITE_OMIT_VIEW */
  1897. #if !SQLITE_OMIT_VIEW || !SQLITE_OMIT_VIRTUALTABLE
  1898. /*
  1899. ** The Table structure pTable is really a VIEW. Fill in the names of
  1900. ** the columns of the view in the pTable structure. Return the number
  1901. ** of errors. If an error is seen leave an error message in pParse.zErrMsg.
  1902. */
  1903. static int sqlite3ViewGetColumnNames( Parse pParse, Table pTable )
  1904. {
  1905. Table pSelTab; /* A fake table from which we get the result set */
  1906. Select pSel; /* Copy of the SELECT that implements the view */
  1907. int nErr = 0; /* Number of errors encountered */
  1908. int n; /* Temporarily holds the number of cursors assigned */
  1909. sqlite3 db = pParse.db; /* Database connection for malloc errors */
  1910. dxAuth xAuth; //)(void*,int,const char*,const char*,const char*,const char*);
  1911. Debug.Assert( pTable != null );
  1912. #if !SQLITE_OMIT_VIRTUALTABLE
  1913. if ( sqlite3VtabCallConnect( pParse, pTable ) )
  1914. {
  1915. return SQLITE_ERROR;
  1916. }
  1917. #endif
  1918. if ( IsVirtual( pTable ) )
  1919. return 0;
  1920. #if !SQLITE_OMIT_VIEW
  1921. /* A positive nCol means the columns names for this view are
  1922. ** already known.
  1923. */
  1924. if ( pTable.nCol > 0 )
  1925. return 0;
  1926. /* A negative nCol is a special marker meaning that we are currently
  1927. ** trying to compute the column names. If we enter this routine with
  1928. ** a negative nCol, it means two or more views form a loop, like this:
  1929. **
  1930. ** CREATE VIEW one AS SELECT * FROM two;
  1931. ** CREATE VIEW two AS SELECT * FROM one;
  1932. **
  1933. ** Actually, the error above is now caught prior to reaching this point.
  1934. ** But the following test is still important as it does come up
  1935. ** in the following:
  1936. **
  1937. ** CREATE TABLE main.ex1(a);
  1938. ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
  1939. ** SELECT * FROM temp.ex1;
  1940. */
  1941. if ( pTable.nCol < 0 )
  1942. {
  1943. sqlite3ErrorMsg( pParse, "view %s is circularly defined", pTable.zName );
  1944. return 1;
  1945. }
  1946. Debug.Assert( pTable.nCol >= 0 );
  1947. /* If we get this far, it means we need to compute the table names.
  1948. ** Note that the call to sqlite3ResultSetOfSelect() will expand any
  1949. ** "*" elements in the results set of the view and will assign cursors
  1950. ** to the elements of the FROM clause. But we do not want these changes
  1951. ** to be permanent. So the computation is done on a copy of the SELECT
  1952. ** statement that defines the view.
  1953. */
  1954. Debug.Assert( pTable.pSelect != null );
  1955. pSel = sqlite3SelectDup( db, pTable.pSelect, 0 );
  1956. if ( pSel != null )
  1957. {
  1958. u8 enableLookaside = db.lookaside.bEnabled;
  1959. n = pParse.nTab;
  1960. sqlite3SrcListAssignCursors( pParse, pSel.pSrc );
  1961. pTable.nCol = -1;
  1962. db.lookaside.bEnabled = 0;
  1963. #if !SQLITE_OMIT_AUTHORIZATION
  1964. xAuth = db.xAuth;
  1965. db.xAuth = 0;
  1966. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  1967. db.xAuth = xAuth;
  1968. #else
  1969. pSelTab = sqlite3ResultSetOfSelect( pParse, pSel );
  1970. #endif
  1971. db.lookaside.bEnabled = enableLookaside;
  1972. pParse.nTab = n;
  1973. if ( pSelTab != null )
  1974. {
  1975. Debug.Assert( pTable.aCol == null );
  1976. pTable.nCol = pSelTab.nCol;
  1977. pTable.aCol = pSelTab.aCol;
  1978. pSelTab.nCol = 0;
  1979. pSelTab.aCol = null;
  1980. sqlite3DeleteTable( db, ref pSelTab );
  1981. pTable.pSchema.flags |= DB_UnresetViews;
  1982. }
  1983. else
  1984. {
  1985. pTable.nCol = 0;
  1986. nErr++;
  1987. }
  1988. sqlite3SelectDelete( db, ref pSel );
  1989. }
  1990. else
  1991. {
  1992. nErr++;
  1993. }
  1994. #endif // * SQLITE_OMIT_VIEW */
  1995. return nErr;
  1996. }
  1997. #endif // * !SQLITE_OMIT_VIEW) || !SQLITE_OMIT_VIRTUALTABLE) */
  1998. #if !SQLITE_OMIT_VIEW
  1999. /*
  2000. ** Clear the column names from every VIEW in database idx.
  2001. */
  2002. static void sqliteViewResetAll( sqlite3 db, int idx )
  2003. {
  2004. HashElem i;
  2005. if ( !DbHasProperty( db, idx, DB_UnresetViews ) )
  2006. return;
  2007. //for(i=sqliteHashFirst(&db.aDb[idx].pSchema.tblHash); i;i=sqliteHashNext(i)){
  2008. for ( i = db.aDb[idx].pSchema.tblHash.first; i != null; i = i.next )
  2009. {
  2010. Table pTab = (Table)i.data;// sqliteHashData( i );
  2011. if ( pTab.pSelect != null )
  2012. {
  2013. sqliteDeleteColumnNames( db, pTab );
  2014. pTab.aCol = null;
  2015. pTab.nCol = 0;
  2016. }
  2017. }
  2018. DbClearProperty( db, idx, DB_UnresetViews );
  2019. }
  2020. #else
  2021. //# define sqliteViewResetAll(A,B)
  2022. static void sqliteViewResetAll( sqlite3 A, int B )
  2023. {
  2024. }
  2025. #endif // * SQLITE_OMIT_VIEW */
  2026. /*
  2027. ** This function is called by the VDBE to adjust the internal schema
  2028. ** used by SQLite when the btree layer moves a table root page. The
  2029. ** root-page of a table or index in database iDb has changed from iFrom
  2030. ** to iTo.
  2031. **
  2032. ** Ticket #1728: The symbol table might still contain information
  2033. ** on tables and/or indices that are the process of being deleted.
  2034. ** If you are unlucky, one of those deleted indices or tables might
  2035. ** have the same rootpage number as the real table or index that is
  2036. ** being moved. So we cannot stop searching after the first match
  2037. ** because the first match might be for one of the deleted indices
  2038. ** or tables and not the table/index that is actually being moved.
  2039. ** We must continue looping until all tables and indices with
  2040. ** rootpage==iFrom have been converted to have a rootpage of iTo
  2041. ** in order to be certain that we got the right one.
  2042. */
  2043. #if !SQLITE_OMIT_AUTOVACUUM
  2044. static void sqlite3RootPageMoved( Db pDb, int iFrom, int iTo )
  2045. {
  2046. HashElem pElem;
  2047. Hash pHash;
  2048. pHash = pDb.pSchema.tblHash;
  2049. for ( pElem = pHash.first; pElem != null; pElem = pElem.next )// ( pElem = sqliteHashFirst( pHash ) ; pElem ; pElem = sqliteHashNext( pElem ) )
  2050. {
  2051. Table pTab = (Table)pElem.data;// sqliteHashData( pElem );
  2052. if ( pTab.tnum == iFrom )
  2053. {
  2054. pTab.tnum = iTo;
  2055. }
  2056. }
  2057. pHash = pDb.pSchema.idxHash;
  2058. for ( pElem = pHash.first; pElem != null; pElem = pElem.next )// ( pElem = sqliteHashFirst( pHash ) ; pElem ; pElem = sqliteHashNext( pElem ) )
  2059. {
  2060. Index pIdx = (Index)pElem.data;// sqliteHashData( pElem );
  2061. if ( pIdx.tnum == iFrom )
  2062. {
  2063. pIdx.tnum = iTo;
  2064. }
  2065. }
  2066. }
  2067. #endif
  2068. /*
  2069. ** Write code to erase the table with root-page iTable from database iDb.
  2070. ** Also write code to modify the sqlite_master table and internal schema
  2071. ** if a root-page of another table is moved by the btree-layer whilst
  2072. ** erasing iTable (this can happen with an auto-vacuum database).
  2073. */
  2074. static void destroyRootPage( Parse pParse, int iTable, int iDb )
  2075. {
  2076. Vdbe v = sqlite3GetVdbe( pParse );
  2077. int r1 = sqlite3GetTempReg( pParse );
  2078. sqlite3VdbeAddOp3( v, OP_Destroy, iTable, r1, iDb );
  2079. sqlite3MayAbort( pParse );
  2080. #if !SQLITE_OMIT_AUTOVACUUM
  2081. /* OP_Destroy stores an in integer r1. If this integer
  2082. ** is non-zero, then it is the root page number of a table moved to
  2083. ** location iTable. The following code modifies the sqlite_master table to
  2084. ** reflect this.
  2085. **
  2086. ** The "#NNN" in the SQL is a special constant that means whatever value
  2087. ** is in register NNN. See grammar rules associated with the TK_REGISTER
  2088. ** token for additional information.
  2089. */
  2090. sqlite3NestedParse( pParse,
  2091. "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
  2092. pParse.db.aDb[iDb].zName, SCHEMA_TABLE( iDb ), iTable, r1, r1 );
  2093. #endif
  2094. sqlite3ReleaseTempReg( pParse, r1 );
  2095. }
  2096. /*
  2097. ** Write VDBE code to erase table pTab and all associated indices on disk.
  2098. ** Code to update the sqlite_master tables and internal schema definitions
  2099. ** in case a root-page belonging to another table is moved by the btree layer
  2100. ** is also added (this can happen with an auto-vacuum database).
  2101. */
  2102. static void destroyTable( Parse pParse, Table pTab )
  2103. {
  2104. #if SQLITE_OMIT_AUTOVACUUM
  2105. Index pIdx;
  2106. int iDb = sqlite3SchemaToIndex( pParse.db, pTab.pSchema );
  2107. destroyRootPage( pParse, pTab.tnum, iDb );
  2108. for ( pIdx = pTab.pIndex ; pIdx != null ; pIdx = pIdx.pNext )
  2109. {
  2110. destroyRootPage( pParse, pIdx.tnum, iDb );
  2111. }
  2112. #else
  2113. /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
  2114. ** is not defined), then it is important to call OP_Destroy on the
  2115. ** table and index root-pages in order, starting with the numerically
  2116. ** largest root-page number. This guarantees that none of the root-pages
  2117. ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
  2118. ** following were coded:
  2119. **
  2120. ** OP_Destroy 4 0
  2121. ** ...
  2122. ** OP_Destroy 5 0
  2123. **
  2124. ** and root page 5 happened to be the largest root-page number in the
  2125. ** database, then root page 5 would be moved to page 4 by the
  2126. ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
  2127. ** a free-list page.
  2128. */
  2129. int iTab = pTab.tnum;
  2130. int iDestroyed = 0;
  2131. while ( true )
  2132. {
  2133. Index pIdx;
  2134. int iLargest = 0;
  2135. if ( iDestroyed == 0 || iTab < iDestroyed )
  2136. {
  2137. iLargest = iTab;
  2138. }
  2139. for ( pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext )
  2140. {
  2141. int iIdx = pIdx.tnum;
  2142. Debug.Assert( pIdx.pSchema == pTab.pSchema );
  2143. if ( ( iDestroyed == 0 || ( iIdx < iDestroyed ) ) && iIdx > iLargest )
  2144. {
  2145. iLargest = iIdx;
  2146. }
  2147. }
  2148. if ( iLargest == 0 )
  2149. {
  2150. return;
  2151. }
  2152. else
  2153. {
  2154. int iDb = sqlite3SchemaToIndex( pParse.db, pTab.pSchema );
  2155. destroyRootPage( pParse, iLargest, iDb );
  2156. iDestroyed = iLargest;
  2157. }
  2158. }
  2159. #endif
  2160. }
  2161. /*
  2162. ** This routine is called to do the work of a DROP TABLE statement.
  2163. ** pName is the name of the table to be dropped.
  2164. */
  2165. static void sqlite3DropTable( Parse pParse, SrcList pName, int isView, int noErr )
  2166. {
  2167. Table pTab;
  2168. Vdbe v;
  2169. sqlite3 db = pParse.db;
  2170. int iDb;
  2171. //if ( db.mallocFailed != 0 )
  2172. //{
  2173. // goto exit_drop_table;
  2174. //}
  2175. Debug.Assert( pParse.nErr == 0 );
  2176. Debug.Assert( pName.nSrc == 1 );
  2177. if ( noErr != 0 )
  2178. db.suppressErr++;
  2179. pTab = sqlite3LocateTable( pParse, isView,
  2180. pName.a[0].zName, pName.a[0].zDatabase );
  2181. if ( noErr != 0 )
  2182. db.suppressErr--;
  2183. if ( pTab == null )
  2184. {
  2185. goto exit_drop_table;
  2186. }
  2187. iDb = sqlite3SchemaToIndex( db, pTab.pSchema );
  2188. Debug.Assert( iDb >= 0 && iDb < db.nDb );
  2189. /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
  2190. ** it is initialized.
  2191. */
  2192. if ( IsVirtual( pTab ) && sqlite3ViewGetColumnNames( pParse, pTab ) != 0 )
  2193. {
  2194. goto exit_drop_table;
  2195. }
  2196. #if !SQLITE_OMIT_AUTHORIZATION
  2197. {
  2198. int code;
  2199. string zTab = SCHEMA_TABLE(iDb);
  2200. string zDb = db.aDb[iDb].zName;
  2201. string zArg2 = 0;
  2202. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
  2203. goto exit_drop_table;
  2204. }
  2205. if( isView ){
  2206. if( OMIT_TEMPDB ==0&& iDb==1 ){
  2207. code = SQLITE_DROP_TEMP_VIEW;
  2208. }else{
  2209. code = SQLITE_DROP_VIEW;
  2210. }
  2211. }else if( IsVirtual(pTab) ){
  2212. code = SQLITE_DROP_VTABLE;
  2213. zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
  2214. }else{
  2215. if( OMIT_TEMPDB ==0&& iDb==1 ){
  2216. code = SQLITE_DROP_TEMP_TABLE;
  2217. }else{
  2218. code = SQLITE_DROP_TABLE;
  2219. }
  2220. }
  2221. if( sqlite3AuthCheck(pParse, code, pTab.zName, zArg2, zDb) ){
  2222. goto exit_drop_table;
  2223. }
  2224. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab.zName, 0, zDb) ){
  2225. goto exit_drop_table;
  2226. }
  2227. }
  2228. #endif
  2229. if ( pTab.zName.StartsWith( "sqlite_", System.StringComparison.InvariantCultureIgnoreCase ) )
  2230. {
  2231. sqlite3ErrorMsg( pParse, "table %s may not be dropped", pTab.zName );
  2232. goto exit_drop_table;
  2233. }
  2234. #if !SQLITE_OMIT_VIEW
  2235. /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
  2236. ** on a table.
  2237. */
  2238. if ( isView != 0 && pTab.pSelect == null )
  2239. {
  2240. sqlite3ErrorMsg( pParse, "use DROP TABLE to delete table %s", pTab.zName );
  2241. goto exit_drop_table;
  2242. }
  2243. if ( 0 == isView && pTab.pSelect != null )
  2244. {
  2245. sqlite3ErrorMsg( pParse, "use DROP VIEW to delete view %s", pTab.zName );
  2246. goto exit_drop_table;
  2247. }
  2248. #endif
  2249. /* Generate code to remove the table from the master table
  2250. ** on disk.
  2251. */
  2252. v = sqlite3GetVdbe( pParse );
  2253. if ( v != null )
  2254. {
  2255. Trigger pTrigger;
  2256. Db pDb = db.aDb[iDb];
  2257. sqlite3BeginWriteOperation( pParse, 1, iDb );
  2258. #if !SQLITE_OMIT_VIRTUALTABLE
  2259. if ( IsVirtual( pTab ) )
  2260. {
  2261. sqlite3VdbeAddOp0( v, OP_VBegin );
  2262. }
  2263. #endif
  2264. sqlite3FkDropTable( pParse, pName, pTab );
  2265. /* Drop all triggers associated with the table being dropped. Code
  2266. ** is generated to remove entries from sqlite_master and/or
  2267. ** sqlite_temp_master if required.
  2268. */
  2269. pTrigger = sqlite3TriggerList( pParse, pTab );
  2270. while ( pTrigger != null )
  2271. {
  2272. Debug.Assert( pTrigger.pSchema == pTab.pSchema ||
  2273. pTrigger.pSchema == db.aDb[1].pSchema );
  2274. sqlite3DropTriggerPtr( pParse, pTrigger );
  2275. pTrigger = pTrigger.pNext;
  2276. }
  2277. #if !SQLITE_OMIT_AUTOINCREMENT
  2278. /* Remove any entries of the sqlite_sequence table associated with
  2279. ** the table being dropped. This is done before the table is dropped
  2280. ** at the btree level, in case the sqlite_sequence table needs to
  2281. ** move as a result of the drop (can happen in auto-vacuum mode).
  2282. */
  2283. if ( ( pTab.tabFlags & TF_Autoincrement ) != 0 )
  2284. {
  2285. sqlite3NestedParse( pParse,
  2286. "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
  2287. pDb.zName, pTab.zName
  2288. );
  2289. }
  2290. #endif
  2291. /* Drop all SQLITE_MASTER table and index entries that refer to the
  2292. ** table. The program name loops through the master table and deletes
  2293. ** every row that refers to a table of the same name as the one being
  2294. ** dropped. Triggers are handled seperately because a trigger can be
  2295. ** created in the temp database that refers to a table in another
  2296. ** database.
  2297. */
  2298. sqlite3NestedParse( pParse,
  2299. "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
  2300. pDb.zName, SCHEMA_TABLE( iDb ), pTab.zName );
  2301. /* Drop any statistics from the sqlite_stat1 table, if it exists */
  2302. if ( sqlite3FindTable( db, "sqlite_stat1", db.aDb[iDb].zName ) != null )
  2303. {
  2304. sqlite3NestedParse( pParse,
  2305. "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb.zName, pTab.zName
  2306. );
  2307. }
  2308. if ( 0 == isView && !IsVirtual( pTab ) )
  2309. {
  2310. destroyTable( pParse, pTab );
  2311. }
  2312. /* Remove the table entry from SQLite's internal schema and modify
  2313. ** the schema cookie.
  2314. */
  2315. if ( IsVirtual( pTab ) )
  2316. {
  2317. sqlite3VdbeAddOp4( v, OP_VDestroy, iDb, 0, 0, pTab.zName, 0 );
  2318. }
  2319. sqlite3VdbeAddOp4( v, OP_DropTable, iDb, 0, 0, pTab.zName, 0 );
  2320. sqlite3ChangeCookie( pParse, iDb );
  2321. }
  2322. sqliteViewResetAll( db, iDb );
  2323. exit_drop_table:
  2324. sqlite3SrcListDelete( db, ref pName );
  2325. }
  2326. /*
  2327. ** This routine is called to create a new foreign key on the table
  2328. ** currently under construction. pFromCol determines which columns
  2329. ** in the current table point to the foreign key. If pFromCol==0 then
  2330. ** connect the key to the last column inserted. pTo is the name of
  2331. ** the table referred to. pToCol is a list of tables in the other
  2332. ** pTo table that the foreign key points to. flags contains all
  2333. ** information about the conflict resolution algorithms specified
  2334. ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
  2335. **
  2336. ** An FKey structure is created and added to the table currently
  2337. ** under construction in the pParse.pNewTable field.
  2338. **
  2339. ** The foreign key is set for IMMEDIATE processing. A subsequent call
  2340. ** to sqlite3DeferForeignKey() might change this to DEFERRED.
  2341. */
  2342. // OVERLOADS, so I don't need to rewrite parse.c
  2343. static void sqlite3CreateForeignKey( Parse pParse, int null_2, Token pTo, ExprList pToCol, int flags )
  2344. {
  2345. sqlite3CreateForeignKey( pParse, null, pTo, pToCol, flags );
  2346. }
  2347. static void sqlite3CreateForeignKey(
  2348. Parse pParse, /* Parsing context */
  2349. ExprList pFromCol, /* Columns in this table that point to other table */
  2350. Token pTo, /* Name of the other table */
  2351. ExprList pToCol, /* Columns in the other table */
  2352. int flags /* Conflict resolution algorithms. */
  2353. )
  2354. {
  2355. sqlite3 db = pParse.db;
  2356. #if !SQLITE_OMIT_FOREIGN_KEY
  2357. FKey pFKey = null;
  2358. FKey pNextTo;
  2359. Table p = pParse.pNewTable;
  2360. int nByte;
  2361. int i;
  2362. int nCol;
  2363. //string z;
  2364. Debug.Assert( pTo != null );
  2365. if ( p == null || IN_DECLARE_VTAB )
  2366. goto fk_end;
  2367. if ( pFromCol == null )
  2368. {
  2369. int iCol = p.nCol - 1;
  2370. if ( NEVER( iCol < 0 ) )
  2371. goto fk_end;
  2372. if ( pToCol != null && pToCol.nExpr != 1 )
  2373. {
  2374. sqlite3ErrorMsg( pParse, "foreign key on %s" +
  2375. " should reference only one column of table %T",
  2376. p.aCol[iCol].zName, pTo );
  2377. goto fk_end;
  2378. }
  2379. nCol = 1;
  2380. }
  2381. else if ( pToCol != null && pToCol.nExpr != pFromCol.nExpr )
  2382. {
  2383. sqlite3ErrorMsg( pParse,
  2384. "number of columns in foreign key does not match the number of " +
  2385. "columns in the referenced table" );
  2386. goto fk_end;
  2387. }
  2388. else
  2389. {
  2390. nCol = pFromCol.nExpr;
  2391. }
  2392. //nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey.aCol[0]) + pTo.n + 1;
  2393. //if( pToCol ){
  2394. // for(i=0; i<pToCol.nExpr; i++){
  2395. // nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
  2396. // }
  2397. //}
  2398. pFKey = new FKey();//sqlite3DbMallocZero(db, nByte );
  2399. if ( pFKey == null )
  2400. {
  2401. goto fk_end;
  2402. }
  2403. pFKey.pFrom = p;
  2404. pFKey.pNextFrom = p.pFKey;
  2405. //z = pFKey.aCol[nCol].zCol;
  2406. pFKey.aCol = new FKey.sColMap[nCol];// z;
  2407. pFKey.aCol[0] = new FKey.sColMap();
  2408. pFKey.zTo = pTo.z.Substring( 0, pTo.n ); //memcpy( z, pTo.z, pTo.n );
  2409. //z[pTo.n] = 0;
  2410. sqlite3Dequote( ref pFKey.zTo );
  2411. //z += pTo.n + 1;
  2412. pFKey.nCol = nCol;
  2413. if ( pFromCol == null )
  2414. {
  2415. pFKey.aCol[0].iFrom = p.nCol - 1;
  2416. }
  2417. else
  2418. {
  2419. for ( i = 0; i < nCol; i++ )
  2420. {
  2421. if ( pFKey.aCol[i] == null )
  2422. pFKey.aCol[i] = new FKey.sColMap();
  2423. int j;
  2424. for ( j = 0; j < p.nCol; j++ )
  2425. {
  2426. if ( p.aCol[j].zName.Equals( pFromCol.a[i].zName, StringComparison.InvariantCultureIgnoreCase ) )
  2427. {
  2428. pFKey.aCol[i].iFrom = j;
  2429. break;
  2430. }
  2431. }
  2432. if ( j >= p.nCol )
  2433. {
  2434. sqlite3ErrorMsg( pParse,
  2435. "unknown column \"%s\" in foreign key definition",
  2436. pFromCol.a[i].zName );
  2437. goto fk_end;
  2438. }
  2439. }
  2440. }
  2441. if ( pToCol != null )
  2442. {
  2443. for ( i = 0; i < nCol; i++ )
  2444. {
  2445. int n = sqlite3Strlen30( pToCol.a[i].zName );
  2446. if ( pFKey.aCol[i] == null )
  2447. pFKey.aCol[i] = new FKey.sColMap();
  2448. pFKey.aCol[i].zCol = pToCol.a[i].zName;
  2449. //memcpy( z, pToCol.a[i].zName, n );
  2450. //z[n] = 0;
  2451. //z += n + 1;
  2452. }
  2453. }
  2454. pFKey.isDeferred = 0;
  2455. pFKey.aAction[0] = (u8)( flags & 0xff ); /* ON DELETE action */
  2456. pFKey.aAction[1] = (u8)( ( flags >> 8 ) & 0xff ); /* ON UPDATE action */
  2457. pNextTo = sqlite3HashInsert( ref p.pSchema.fkeyHash,
  2458. pFKey.zTo, sqlite3Strlen30( pFKey.zTo ), pFKey
  2459. );
  2460. //if( pNextTo==pFKey ){
  2461. // db.mallocFailed = 1;
  2462. // goto fk_end;
  2463. //}
  2464. if ( pNextTo != null )
  2465. {
  2466. Debug.Assert( pNextTo.pPrevTo == null );
  2467. pFKey.pNextTo = pNextTo;
  2468. pNextTo.pPrevTo = pFKey;
  2469. }
  2470. /* Link the foreign key to the table as the last step.
  2471. */
  2472. p.pFKey = pFKey;
  2473. pFKey = null;
  2474. fk_end:
  2475. sqlite3DbFree( db, ref pFKey );
  2476. #endif // * !SQLITE_OMIT_FOREIGN_KEY) */
  2477. sqlite3ExprListDelete( db, ref pFromCol );
  2478. sqlite3ExprListDelete( db, ref pToCol );
  2479. }
  2480. /*
  2481. ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
  2482. ** clause is seen as part of a foreign key definition. The isDeferred
  2483. ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
  2484. ** The behavior of the most recently created foreign key is adjusted
  2485. ** accordingly.
  2486. */
  2487. static void sqlite3DeferForeignKey( Parse pParse, int isDeferred )
  2488. {
  2489. #if !SQLITE_OMIT_FOREIGN_KEY
  2490. Table pTab;
  2491. FKey pFKey;
  2492. if ( ( pTab = pParse.pNewTable ) == null || ( pFKey = pTab.pFKey ) == null )
  2493. return;
  2494. Debug.Assert( isDeferred == 0 || isDeferred == 1 ); /* EV: R-30323-21917 */
  2495. pFKey.isDeferred = (u8)isDeferred;
  2496. #endif
  2497. }
  2498. /*
  2499. ** Generate code that will erase and refill index pIdx. This is
  2500. ** used to initialize a newly created index or to recompute the
  2501. ** content of an index in response to a REINDEX command.
  2502. **
  2503. ** if memRootPage is not negative, it means that the index is newly
  2504. ** created. The register specified by memRootPage contains the
  2505. ** root page number of the index. If memRootPage is negative, then
  2506. ** the index already exists and must be cleared before being refilled and
  2507. ** the root page number of the index is taken from pIndex.tnum.
  2508. */
  2509. static void sqlite3RefillIndex( Parse pParse, Index pIndex, int memRootPage )
  2510. {
  2511. Table pTab = pIndex.pTable; /* The table that is indexed */
  2512. int iTab = pParse.nTab++; /* Btree cursor used for pTab */
  2513. int iIdx = pParse.nTab++; /* Btree cursor used for pIndex */
  2514. int addr1; /* Address of top of loop */
  2515. int tnum; /* Root page of index */
  2516. Vdbe v; /* Generate code into this virtual machine */
  2517. KeyInfo pKey; /* KeyInfo for index */
  2518. int regIdxKey; /* Registers containing the index key */
  2519. int regRecord; /* Register holding assemblied index record */
  2520. sqlite3 db = pParse.db; /* The database connection */
  2521. int iDb = sqlite3SchemaToIndex( db, pIndex.pSchema );
  2522. #if !SQLITE_OMIT_AUTHORIZATION
  2523. if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex.zName, 0,
  2524. db.aDb[iDb].zName ) ){
  2525. return;
  2526. }
  2527. #endif
  2528. /* Require a write-lock on the table to perform this operation */
  2529. sqlite3TableLock( pParse, iDb, pTab.tnum, 1, pTab.zName );
  2530. v = sqlite3GetVdbe( pParse );
  2531. if ( v == null )
  2532. return;
  2533. if ( memRootPage >= 0 )
  2534. {
  2535. tnum = memRootPage;
  2536. }
  2537. else
  2538. {
  2539. tnum = pIndex.tnum;
  2540. sqlite3VdbeAddOp2( v, OP_Clear, tnum, iDb );
  2541. }
  2542. pKey = sqlite3IndexKeyinfo( pParse, pIndex );
  2543. sqlite3VdbeAddOp4( v, OP_OpenWrite, iIdx, tnum, iDb,
  2544. pKey, P4_KEYINFO_HANDOFF );
  2545. if ( memRootPage >= 0 )
  2546. {
  2547. sqlite3VdbeChangeP5( v, 1 );
  2548. }
  2549. sqlite3OpenTable( pParse, iTab, iDb, pTab, OP_OpenRead );
  2550. addr1 = sqlite3VdbeAddOp2( v, OP_Rewind, iTab, 0 );
  2551. regRecord = sqlite3GetTempReg( pParse );
  2552. regIdxKey = sqlite3GenerateIndexKey( pParse, pIndex, iTab, regRecord, true );
  2553. if ( pIndex.onError != OE_None )
  2554. {
  2555. int regRowid = regIdxKey + pIndex.nColumn;
  2556. int j2 = sqlite3VdbeCurrentAddr( v ) + 2;
  2557. int pRegKey = regIdxKey;// SQLITE_INT_TO_PTR( regIdxKey );
  2558. /* The registers accessed by the OP_IsUnique opcode were allocated
  2559. ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey()
  2560. ** call above. Just before that function was freed they were released
  2561. ** (made available to the compiler for reuse) using
  2562. ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique
  2563. ** opcode use the values stored within seems dangerous. However, since
  2564. ** we can be sure that no other temp registers have been allocated
  2565. ** since sqlite3ReleaseTempRange() was called, it is safe to do so.
  2566. */
  2567. sqlite3VdbeAddOp4( v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32 );
  2568. sqlite3HaltConstraint(
  2569. pParse, OE_Abort, "indexed columns are not unique", P4_STATIC );
  2570. }
  2571. sqlite3VdbeAddOp2( v, OP_IdxInsert, iIdx, regRecord );
  2572. sqlite3VdbeChangeP5( v, OPFLAG_USESEEKRESULT );
  2573. sqlite3ReleaseTempReg( pParse, regRecord );
  2574. sqlite3VdbeAddOp2( v, OP_Next, iTab, addr1 + 1 );
  2575. sqlite3VdbeJumpHere( v, addr1 );
  2576. sqlite3VdbeAddOp1( v, OP_Close, iTab );
  2577. sqlite3VdbeAddOp1( v, OP_Close, iIdx );
  2578. }
  2579. /*
  2580. ** Create a new index for an SQL table. pName1.pName2 is the name of the index
  2581. ** and pTblList is the name of the table that is to be indexed. Both will
  2582. ** be NULL for a primary key or an index that is created to satisfy a
  2583. ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse.pNewTable
  2584. ** as the table to be indexed. pParse.pNewTable is a table that is
  2585. ** currently being constructed by a CREATE TABLE statement.
  2586. **
  2587. ** pList is a list of columns to be indexed. pList will be NULL if this
  2588. ** is a primary key or unique-constraint on the most recent column added
  2589. ** to the table currently under construction.
  2590. **
  2591. ** If the index is created successfully, return a pointer to the new Index
  2592. ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
  2593. ** as the tables primary key (Index.autoIndex==2).
  2594. */
  2595. // OVERLOADS, so I don't need to rewrite parse.c
  2596. static Index sqlite3CreateIndex( Parse pParse, int null_2, int null_3, int null_4, int null_5, int onError, int null_7, int null_8, int sortOrder, int ifNotExist )
  2597. {
  2598. return sqlite3CreateIndex( pParse, null, null, null, null, onError, null, null, sortOrder, ifNotExist );
  2599. }
  2600. static Index sqlite3CreateIndex( Parse pParse, int null_2, int null_3, int null_4, ExprList pList, int onError, int null_7, int null_8, int sortOrder, int ifNotExist )
  2601. {
  2602. return sqlite3CreateIndex( pParse, null, null, null, pList, onError, null, null, sortOrder, ifNotExist );
  2603. }
  2604. static Index sqlite3CreateIndex(
  2605. Parse pParse, /* All information about this Parse */
  2606. Token pName1, /* First part of index name. May be NULL */
  2607. Token pName2, /* Second part of index name. May be NULL */
  2608. SrcList pTblName, /* Table to index. Use pParse.pNewTable if 0 */
  2609. ExprList pList, /* A list of columns to be indexed */
  2610. int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  2611. Token pStart, /* The CREATE token that begins this statement */
  2612. Token pEnd, /* The ")" that closes the CREATE INDEX statement */
  2613. int sortOrder, /* Sort order of primary key when pList==NULL */
  2614. int ifNotExist /* Omit error if index already exists */
  2615. )
  2616. {
  2617. Index pRet = null; /* Pointer to return */
  2618. Table pTab = null; /* Table to be indexed */
  2619. Index pIndex = null; /* The index to be created */
  2620. string zName = null; /* Name of the index */
  2621. int nName; /* Number of characters in zName */
  2622. int i, j;
  2623. Token nullId = new Token(); /* Fake token for an empty ID list */
  2624. DbFixer sFix = new DbFixer(); /* For assigning database names to pTable */
  2625. int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
  2626. sqlite3 db = pParse.db;
  2627. Db pDb; /* The specific table containing the indexed database */
  2628. int iDb; /* Index of the database that is being written */
  2629. Token pName = null; /* Unqualified name of the index to create */
  2630. ExprList_item pListItem; /* For looping over pList */
  2631. int nCol;
  2632. int nExtra = 0;
  2633. StringBuilder zExtra = new StringBuilder();
  2634. Debug.Assert( pStart == null || pEnd != null ); /* pEnd must be non-NULL if pStart is */
  2635. Debug.Assert( pParse.nErr == 0 ); /* Never called with prior errors */
  2636. if ( /* db.mallocFailed != 0 || */ IN_DECLARE_VTAB )
  2637. {
  2638. goto exit_create_index;
  2639. }
  2640. if ( SQLITE_OK != sqlite3ReadSchema( pParse ) )
  2641. {
  2642. goto exit_create_index;
  2643. }
  2644. /*
  2645. ** Find the table that is to be indexed. Return early if not found.
  2646. */
  2647. if ( pTblName != null )
  2648. {
  2649. /* Use the two-part index name to determine the database
  2650. ** to search for the table. 'Fix' the table name to this db
  2651. ** before looking up the table.
  2652. */
  2653. Debug.Assert( pName1 != null && pName2 != null );
  2654. iDb = sqlite3TwoPartName( pParse, pName1, pName2, ref pName );
  2655. if ( iDb < 0 )
  2656. goto exit_create_index;
  2657. #if !SQLITE_OMIT_TEMPDB
  2658. /* If the index name was unqualified, check if the the table
  2659. ** is a temp table. If so, set the database to 1. Do not do this
  2660. ** if initialising a database schema.
  2661. */
  2662. if ( 0 == db.init.busy )
  2663. {
  2664. pTab = sqlite3SrcListLookup( pParse, pTblName );
  2665. if ( pName2.n == 0 && pTab != null && pTab.pSchema == db.aDb[1].pSchema )
  2666. {
  2667. iDb = 1;
  2668. }
  2669. }
  2670. #endif
  2671. if ( sqlite3FixInit( sFix, pParse, iDb, "index", pName ) != 0 &&
  2672. sqlite3FixSrcList( sFix, pTblName ) != 0
  2673. )
  2674. {
  2675. /* Because the parser constructs pTblName from a single identifier,
  2676. ** sqlite3FixSrcList can never fail. */
  2677. Debugger.Break();
  2678. }
  2679. pTab = sqlite3LocateTable( pParse, 0, pTblName.a[0].zName,
  2680. pTblName.a[0].zDatabase );
  2681. if ( pTab == null /*|| db.mallocFailed != 0 */ )
  2682. goto exit_create_index;
  2683. Debug.Assert( db.aDb[iDb].pSchema == pTab.pSchema );
  2684. }
  2685. else
  2686. {
  2687. Debug.Assert( pName == null );
  2688. pTab = pParse.pNewTable;
  2689. if ( pTab == null )
  2690. goto exit_create_index;
  2691. iDb = sqlite3SchemaToIndex( db, pTab.pSchema );
  2692. }
  2693. pDb = db.aDb[iDb];
  2694. Debug.Assert( pTab != null );
  2695. Debug.Assert( pParse.nErr == 0 );
  2696. if ( pTab.zName.StartsWith( "sqlite_", System.StringComparison.InvariantCultureIgnoreCase )
  2697. && !pTab.zName.StartsWith( "sqlite_altertab_", System.StringComparison.InvariantCultureIgnoreCase ) )
  2698. {
  2699. sqlite3ErrorMsg( pParse, "table %s may not be indexed", pTab.zName );
  2700. goto exit_create_index;
  2701. }
  2702. #if !SQLITE_OMIT_VIEW
  2703. if ( pTab.pSelect != null )
  2704. {
  2705. sqlite3ErrorMsg( pParse, "views may not be indexed" );
  2706. goto exit_create_index;
  2707. }
  2708. #endif
  2709. if ( IsVirtual( pTab ) )
  2710. {
  2711. sqlite3ErrorMsg( pParse, "virtual tables may not be indexed" );
  2712. goto exit_create_index;
  2713. }
  2714. /*
  2715. ** Find the name of the index. Make sure there is not already another
  2716. ** index or table with the same name.
  2717. **
  2718. ** Exception: If we are reading the names of permanent indices from the
  2719. ** sqlite_master table (because some other process changed the schema) and
  2720. ** one of the index names collides with the name of a temporary table or
  2721. ** index, then we will continue to process this index.
  2722. **
  2723. ** If pName==0 it means that we are
  2724. ** dealing with a primary key or UNIQUE constraint. We have to invent our
  2725. ** own name.
  2726. */
  2727. if ( pName != null )
  2728. {
  2729. zName = sqlite3NameFromToken( db, pName );
  2730. if ( zName == null )
  2731. goto exit_create_index;
  2732. if ( SQLITE_OK != sqlite3CheckObjectName( pParse, zName ) )
  2733. {
  2734. goto exit_create_index;
  2735. }
  2736. if ( 0 == db.init.busy )
  2737. {
  2738. if ( sqlite3FindTable( db, zName, null ) != null )
  2739. {
  2740. sqlite3ErrorMsg( pParse, "there is already a table named %s", zName );
  2741. goto exit_create_index;
  2742. }
  2743. }
  2744. if ( sqlite3FindIndex( db, zName, pDb.zName ) != null )
  2745. {
  2746. if ( ifNotExist == 0 )
  2747. {
  2748. sqlite3ErrorMsg( pParse, "index %s already exists", zName );
  2749. }
  2750. goto exit_create_index;
  2751. }
  2752. }
  2753. else
  2754. {
  2755. int n = 0;
  2756. Index pLoop;
  2757. for ( pLoop = pTab.pIndex, n = 1; pLoop != null; pLoop = pLoop.pNext, n++ )
  2758. {
  2759. }
  2760. zName = sqlite3MPrintf( db, "sqlite_autoindex_%s_%d", pTab.zName, n );
  2761. if ( zName == null )
  2762. {
  2763. goto exit_create_index;
  2764. }
  2765. }
  2766. /* Check for authorization to create an index.
  2767. */
  2768. #if !SQLITE_OMIT_AUTHORIZATION
  2769. {
  2770. string zDb = pDb.zName;
  2771. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
  2772. goto exit_create_index;
  2773. }
  2774. i = SQLITE_CREATE_INDEX;
  2775. if( OMIT_TEMPDB ==0&& iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
  2776. if( sqlite3AuthCheck(pParse, i, zName, pTab.zName, zDb) ){
  2777. goto exit_create_index;
  2778. }
  2779. }
  2780. #endif
  2781. /* If pList==0, it means this routine was called to make a primary
  2782. ** key out of the last column added to the table under construction.
  2783. ** So create a fake list to simulate this.
  2784. */
  2785. if ( pList == null )
  2786. {
  2787. nullId.z = pTab.aCol[pTab.nCol - 1].zName;
  2788. nullId.n = sqlite3Strlen30( nullId.z );
  2789. pList = sqlite3ExprListAppend( pParse, null, null );
  2790. if ( pList == null )
  2791. goto exit_create_index;
  2792. sqlite3ExprListSetName( pParse, pList, nullId, 0 );
  2793. pList.a[0].sortOrder = (u8)sortOrder;
  2794. }
  2795. /* Figure out how many bytes of space are required to store explicitly
  2796. ** specified collation sequence names.
  2797. */
  2798. for ( i = 0; i < pList.nExpr; i++ )
  2799. {
  2800. Expr pExpr = pList.a[i].pExpr;
  2801. if ( pExpr != null )
  2802. {
  2803. CollSeq pColl = pExpr.pColl;
  2804. /* Either pColl!=0 or there was an OOM failure. But if an OOM
  2805. ** failure we have quit before reaching this point. */
  2806. if ( ALWAYS( pColl != null ) )
  2807. {
  2808. nExtra += ( 1 + sqlite3Strlen30( pColl.zName ) );
  2809. }
  2810. }
  2811. }
  2812. /*
  2813. ** Allocate the index structure.
  2814. */
  2815. nName = sqlite3Strlen30( zName );
  2816. nCol = pList.nExpr;
  2817. pIndex = new Index();
  2818. // sqlite3DbMallocZero( db,
  2819. // Index.Length + /* Index structure */
  2820. // sizeof( int ) * nCol + /* Index.aiColumn */
  2821. // sizeof( int ) * ( nCol + 1 ) + /* Index.aiRowEst */
  2822. // sizeof( char* ) * nCol + /* Index.azColl */
  2823. // u8.Length * nCol + /* Index.aSortOrder */
  2824. // nName + 1 + /* Index.zName */
  2825. // nExtra /* Collation sequence names */
  2826. //);
  2827. //if ( db.mallocFailed != 0 )
  2828. //{
  2829. // goto exit_create_index;
  2830. //}
  2831. pIndex.azColl = new string[nCol + 1];//(char**)(pIndex[1]);
  2832. pIndex.aiColumn = new int[nCol + 1];//(int *)(pIndex->azColl[nCol]);
  2833. pIndex.aiRowEst = new int[nCol + 1];//(unsigned *)(pIndex->aiColumn[nCol]);
  2834. pIndex.aSortOrder = new byte[nCol + 1];//(u8 *)(pIndex->aiRowEst[nCol+1]);
  2835. //pIndex.zName = null;// (char*)( &pIndex->aSortOrder[nCol] );
  2836. zExtra = new StringBuilder( nName + 1 );// (char*)( &pIndex.zName[nName + 1] );
  2837. if ( zName.Length == nName )
  2838. pIndex.zName = zName;
  2839. else
  2840. {
  2841. pIndex.zName = zName.Substring( 0, nName );
  2842. }// memcpy( pIndex.zName, zName, nName + 1 );
  2843. pIndex.pTable = pTab;
  2844. pIndex.nColumn = pList.nExpr;
  2845. pIndex.onError = (u8)onError;
  2846. pIndex.autoIndex = (u8)( pName == null ? 1 : 0 );
  2847. pIndex.pSchema = db.aDb[iDb].pSchema;
  2848. /* Check to see if we should honor DESC requests on index columns
  2849. */
  2850. if ( pDb.pSchema.file_format >= 4 )
  2851. {
  2852. sortOrderMask = 1; /* Honor DESC */
  2853. }
  2854. else
  2855. {
  2856. sortOrderMask = 0; /* Ignore DESC */
  2857. }
  2858. /* Scan the names of the columns of the table to be indexed and
  2859. ** load the column indices into the Index structure. Report an error
  2860. ** if any column is not found.
  2861. **
  2862. ** TODO: Add a test to make sure that the same column is not named
  2863. ** more than once within the same index. Only the first instance of
  2864. ** the column will ever be used by the optimizer. Note that using the
  2865. ** same column more than once cannot be an error because that would
  2866. ** break backwards compatibility - it needs to be a warning.
  2867. */
  2868. for ( i = 0; i < pList.nExpr; i++ )
  2869. {//, pListItem++){
  2870. pListItem = pList.a[i];
  2871. string zColName = pListItem.zName;
  2872. Column pTabCol;
  2873. byte requestedSortOrder;
  2874. string zColl; /* Collation sequence name */
  2875. for ( j = 0; j < pTab.nCol; j++ )
  2876. {//, pTabCol++){
  2877. pTabCol = pTab.aCol[j];
  2878. if ( zColName.Equals( pTabCol.zName, StringComparison.InvariantCultureIgnoreCase ) )
  2879. break;
  2880. }
  2881. if ( j >= pTab.nCol )
  2882. {
  2883. sqlite3ErrorMsg( pParse, "table %s has no column named %s",
  2884. pTab.zName, zColName );
  2885. pParse.checkSchema = 1;
  2886. goto exit_create_index;
  2887. }
  2888. pIndex.aiColumn[i] = j;
  2889. /* Justification of the ALWAYS(pListItem->pExpr->pColl): Because of
  2890. ** the way the "idxlist" non-terminal is constructed by the parser,
  2891. ** if pListItem->pExpr is not null then either pListItem->pExpr->pColl
  2892. ** must exist or else there must have been an OOM error. But if there
  2893. ** was an OOM error, we would never reach this point. */
  2894. if ( pListItem.pExpr != null && ALWAYS( pListItem.pExpr.pColl ) )
  2895. {
  2896. int nColl;
  2897. zColl = pListItem.pExpr.pColl.zName;
  2898. nColl = sqlite3Strlen30( zColl );
  2899. Debug.Assert( nExtra >= nColl );
  2900. zExtra = new StringBuilder( zColl.Substring( 0, nColl ) );// memcpy( zExtra, zColl, nColl );
  2901. zColl = zExtra.ToString();
  2902. //zExtra += nColl;
  2903. nExtra -= nColl;
  2904. }
  2905. else
  2906. {
  2907. zColl = pTab.aCol[j].zColl;
  2908. if ( zColl == null )
  2909. {
  2910. zColl = db.pDfltColl.zName;
  2911. }
  2912. }
  2913. if ( 0 == db.init.busy && sqlite3LocateCollSeq( pParse, zColl ) == null )
  2914. {
  2915. goto exit_create_index;
  2916. }
  2917. pIndex.azColl[i] = zColl;
  2918. requestedSortOrder = (u8)( ( pListItem.sortOrder & sortOrderMask ) != 0 ? 1 : 0 );
  2919. pIndex.aSortOrder[i] = (u8)requestedSortOrder;
  2920. }
  2921. sqlite3DefaultRowEst( pIndex );
  2922. if ( pTab == pParse.pNewTable )
  2923. {
  2924. /* This routine has been called to create an automatic index as a
  2925. ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
  2926. ** a PRIMARY KEY or UNIQUE clause following the column definitions.
  2927. ** i.e. one of:
  2928. **
  2929. ** CREATE TABLE t(x PRIMARY KEY, y);
  2930. ** CREATE TABLE t(x, y, UNIQUE(x, y));
  2931. **
  2932. ** Either way, check to see if the table already has such an index. If
  2933. ** so, don't bother creating this one. This only applies to
  2934. ** automatically created indices. Users can do as they wish with
  2935. ** explicit indices.
  2936. **
  2937. ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
  2938. ** (and thus suppressing the second one) even if they have different
  2939. ** sort orders.
  2940. **
  2941. ** If there are different collating sequences or if the columns of
  2942. ** the constraint occur in different orders, then the constraints are
  2943. ** considered distinct and both result in separate indices.
  2944. */
  2945. Index pIdx;
  2946. for ( pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext )
  2947. {
  2948. int k;
  2949. Debug.Assert( pIdx.onError != OE_None );
  2950. Debug.Assert( pIdx.autoIndex != 0 );
  2951. Debug.Assert( pIndex.onError != OE_None );
  2952. if ( pIdx.nColumn != pIndex.nColumn )
  2953. continue;
  2954. for ( k = 0; k < pIdx.nColumn; k++ )
  2955. {
  2956. string z1;
  2957. string z2;
  2958. if ( pIdx.aiColumn[k] != pIndex.aiColumn[k] )
  2959. break;
  2960. z1 = pIdx.azColl[k];
  2961. z2 = pIndex.azColl[k];
  2962. if ( z1 != z2 && !z1.Equals( z2, StringComparison.InvariantCultureIgnoreCase ) )
  2963. break;
  2964. }
  2965. if ( k == pIdx.nColumn )
  2966. {
  2967. if ( pIdx.onError != pIndex.onError )
  2968. {
  2969. /* This constraint creates the same index as a previous
  2970. ** constraint specified somewhere in the CREATE TABLE statement.
  2971. ** However the ON CONFLICT clauses are different. If both this
  2972. ** constraint and the previous equivalent constraint have explicit
  2973. ** ON CONFLICT clauses this is an error. Otherwise, use the
  2974. ** explicitly specified behavior for the index.
  2975. */
  2976. if ( !( pIdx.onError == OE_Default || pIndex.onError == OE_Default ) )
  2977. {
  2978. sqlite3ErrorMsg( pParse,
  2979. "conflicting ON CONFLICT clauses specified", 0 );
  2980. }
  2981. if ( pIdx.onError == OE_Default )
  2982. {
  2983. pIdx.onError = pIndex.onError;
  2984. }
  2985. }
  2986. goto exit_create_index;
  2987. }
  2988. }
  2989. }
  2990. /* Link the new Index structure to its table and to the other
  2991. ** in-memory database structures.
  2992. */
  2993. if ( db.init.busy != 0 )
  2994. {
  2995. Index p;
  2996. p = sqlite3HashInsert( ref pIndex.pSchema.idxHash,
  2997. pIndex.zName, sqlite3Strlen30( pIndex.zName ),
  2998. pIndex );
  2999. if ( p != null )
  3000. {
  3001. Debug.Assert( p == pIndex ); /* Malloc must have failed */
  3002. // db.mallocFailed = 1;
  3003. goto exit_create_index;
  3004. }
  3005. db.flags |= SQLITE_InternChanges;
  3006. if ( pTblName != null )
  3007. {
  3008. pIndex.tnum = db.init.newTnum;
  3009. }
  3010. }
  3011. /* If the db.init.busy is 0 then create the index on disk. This
  3012. ** involves writing the index into the master table and filling in the
  3013. ** index with the current table contents.
  3014. **
  3015. ** The db.init.busy is 0 when the user first enters a CREATE INDEX
  3016. ** command. db.init.busy is 1 when a database is opened and
  3017. ** CREATE INDEX statements are read out of the master table. In
  3018. ** the latter case the index already exists on disk, which is why
  3019. ** we don't want to recreate it.
  3020. **
  3021. ** If pTblName==0 it means this index is generated as a primary key
  3022. ** or UNIQUE constraint of a CREATE TABLE statement. Since the table
  3023. ** has just been created, it contains no data and the index initialization
  3024. ** step can be skipped.
  3025. */
  3026. else //if ( 0 == db.init.busy )
  3027. {
  3028. Vdbe v;
  3029. string zStmt;
  3030. int iMem = ++pParse.nMem;
  3031. v = sqlite3GetVdbe( pParse );
  3032. if ( v == null )
  3033. goto exit_create_index;
  3034. /* Create the rootpage for the index
  3035. */
  3036. sqlite3BeginWriteOperation( pParse, 1, iDb );
  3037. sqlite3VdbeAddOp2( v, OP_CreateIndex, iDb, iMem );
  3038. /* Gather the complete text of the CREATE INDEX statement into
  3039. ** the zStmt variable
  3040. */
  3041. if ( pStart != null )
  3042. {
  3043. Debug.Assert( pEnd != null );
  3044. /* A named index with an explicit CREATE INDEX statement */
  3045. zStmt = sqlite3MPrintf( db, "CREATE%s INDEX %.*s",
  3046. onError == OE_None ? "" : " UNIQUE",
  3047. pName.z.Length - pEnd.z.Length + 1,
  3048. pName.z );
  3049. }
  3050. else
  3051. {
  3052. /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
  3053. /* zStmt = sqlite3MPrintf(""); */
  3054. zStmt = null;
  3055. }
  3056. /* Add an entry in sqlite_master for this index
  3057. */
  3058. sqlite3NestedParse( pParse,
  3059. "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
  3060. db.aDb[iDb].zName, SCHEMA_TABLE( iDb ),
  3061. pIndex.zName,
  3062. pTab.zName,
  3063. iMem,
  3064. zStmt
  3065. );
  3066. sqlite3DbFree( db, ref zStmt );
  3067. /* Fill the index with data and reparse the schema. Code an OP_Expire
  3068. ** to invalidate all pre-compiled statements.
  3069. */
  3070. if ( pTblName != null )
  3071. {
  3072. sqlite3RefillIndex( pParse, pIndex, iMem );
  3073. sqlite3ChangeCookie( pParse, iDb );
  3074. sqlite3VdbeAddOp4( v, OP_ParseSchema, iDb, 0, 0,
  3075. sqlite3MPrintf( db, "name='%q' AND type='index'", pIndex.zName ), P4_DYNAMIC );
  3076. sqlite3VdbeAddOp1( v, OP_Expire, 0 );
  3077. }
  3078. }
  3079. /* When adding an index to the list of indices for a table, make
  3080. ** sure all indices labeled OE_Replace come after all those labeled
  3081. ** OE_Ignore. This is necessary for the correct constraint check
  3082. ** processing (in sqlite3GenerateConstraintChecks()) as part of
  3083. ** UPDATE and INSERT statements.
  3084. */
  3085. if ( db.init.busy != 0 || pTblName == null )
  3086. {
  3087. if ( onError != OE_Replace || pTab.pIndex == null
  3088. || pTab.pIndex.onError == OE_Replace )
  3089. {
  3090. pIndex.pNext = pTab.pIndex;
  3091. pTab.pIndex = pIndex;
  3092. }
  3093. else
  3094. {
  3095. Index pOther = pTab.pIndex;
  3096. while ( pOther.pNext != null && pOther.pNext.onError != OE_Replace )
  3097. {
  3098. pOther = pOther.pNext;
  3099. }
  3100. pIndex.pNext = pOther.pNext;
  3101. pOther.pNext = pIndex;
  3102. }
  3103. pRet = pIndex;
  3104. pIndex = null;
  3105. }
  3106. /* Clean up before exiting */
  3107. exit_create_index:
  3108. if ( pIndex != null )
  3109. {
  3110. //sqlite3DbFree(db, ref pIndex.zColAff );
  3111. sqlite3DbFree( db, ref pIndex );
  3112. }
  3113. sqlite3ExprListDelete( db, ref pList );
  3114. sqlite3SrcListDelete( db, ref pTblName );
  3115. sqlite3DbFree( db, ref zName );
  3116. return pRet;
  3117. }
  3118. /*
  3119. ** Fill the Index.aiRowEst[] array with default information - information
  3120. ** to be used when we have not run the ANALYZE command.
  3121. **
  3122. ** aiRowEst[0] is suppose to contain the number of elements in the index.
  3123. ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
  3124. ** number of rows in the table that match any particular value of the
  3125. ** first column of the index. aiRowEst[2] is an estimate of the number
  3126. ** of rows that match any particular combiniation of the first 2 columns
  3127. ** of the index. And so forth. It must always be the case that
  3128. *
  3129. ** aiRowEst[N]<=aiRowEst[N-1]
  3130. ** aiRowEst[N]>=1
  3131. **
  3132. ** Apart from that, we have little to go on besides intuition as to
  3133. ** how aiRowEst[] should be initialized. The numbers generated here
  3134. ** are based on typical values found in actual indices.
  3135. */
  3136. static void sqlite3DefaultRowEst( Index pIdx )
  3137. {
  3138. int[] a = pIdx.aiRowEst;
  3139. int i;
  3140. int n;
  3141. Debug.Assert( a != null );
  3142. a[0] = (int)pIdx.pTable.nRowEst;
  3143. if ( a[0] < 10 )
  3144. a[0] = 10;
  3145. n = 10;
  3146. for ( i = 1; i <= pIdx.nColumn; i++ )
  3147. {
  3148. a[i] = n;
  3149. if ( n > 5 )
  3150. n--;
  3151. }
  3152. if ( pIdx.onError != OE_None )
  3153. {
  3154. a[pIdx.nColumn] = 1;
  3155. }
  3156. }
  3157. /*
  3158. ** This routine will drop an existing named index. This routine
  3159. ** implements the DROP INDEX statement.
  3160. */
  3161. static void sqlite3DropIndex( Parse pParse, SrcList pName, int ifExists )
  3162. {
  3163. Index pIndex;
  3164. Vdbe v;
  3165. sqlite3 db = pParse.db;
  3166. int iDb;
  3167. Debug.Assert( pParse.nErr == 0 ); /* Never called with prior errors */
  3168. //if ( db.mallocFailed != 0 )
  3169. //{
  3170. // goto exit_drop_index;
  3171. //}
  3172. Debug.Assert( pName.nSrc == 1 );
  3173. if ( SQLITE_OK != sqlite3ReadSchema( pParse ) )
  3174. {
  3175. goto exit_drop_index;
  3176. }
  3177. pIndex = sqlite3FindIndex( db, pName.a[0].zName, pName.a[0].zDatabase );
  3178. if ( pIndex == null )
  3179. {
  3180. if ( ifExists == 0 )
  3181. {
  3182. sqlite3ErrorMsg( pParse, "no such index: %S", pName, 0 );
  3183. }
  3184. pParse.checkSchema = 1;
  3185. goto exit_drop_index;
  3186. }
  3187. if ( pIndex.autoIndex != 0 )
  3188. {
  3189. sqlite3ErrorMsg( pParse, "index associated with UNIQUE " +
  3190. "or PRIMARY KEY constraint cannot be dropped", 0 );
  3191. goto exit_drop_index;
  3192. }
  3193. iDb = sqlite3SchemaToIndex( db, pIndex.pSchema );
  3194. #if !SQLITE_OMIT_AUTHORIZATION
  3195. {
  3196. int code = SQLITE_DROP_INDEX;
  3197. Table pTab = pIndex.pTable;
  3198. string zDb = db.aDb[iDb].zName;
  3199. string zTab = SCHEMA_TABLE(iDb);
  3200. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  3201. goto exit_drop_index;
  3202. }
  3203. if( OMIT_TEMPDB ==0&& iDb ) code = SQLITE_DROP_TEMP_INDEX;
  3204. if( sqlite3AuthCheck(pParse, code, pIndex.zName, pTab.zName, zDb) ){
  3205. goto exit_drop_index;
  3206. }
  3207. }
  3208. #endif
  3209. /* Generate code to remove the index and from the master table */
  3210. v = sqlite3GetVdbe( pParse );
  3211. if ( v != null )
  3212. {
  3213. sqlite3BeginWriteOperation( pParse, 1, iDb );
  3214. sqlite3NestedParse( pParse,
  3215. "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
  3216. db.aDb[iDb].zName, SCHEMA_TABLE( iDb ),
  3217. pIndex.zName
  3218. );
  3219. if ( sqlite3FindTable( db, "sqlite_stat1", db.aDb[iDb].zName ) != null )
  3220. {
  3221. sqlite3NestedParse( pParse,
  3222. "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q",
  3223. db.aDb[iDb].zName, pIndex.zName
  3224. );
  3225. }
  3226. sqlite3ChangeCookie( pParse, iDb );
  3227. destroyRootPage( pParse, pIndex.tnum, iDb );
  3228. sqlite3VdbeAddOp4( v, OP_DropIndex, iDb, 0, 0, pIndex.zName, 0 );
  3229. }
  3230. exit_drop_index:
  3231. sqlite3SrcListDelete( db, ref pName );
  3232. }
  3233. /*
  3234. ** pArray is a pointer to an array of objects. Each object in the
  3235. ** array is szEntry bytes in size. This routine allocates a new
  3236. ** object on the end of the array.
  3237. **
  3238. ** pnEntry is the number of entries already in use. pnAlloc is
  3239. ** the previously allocated size of the array. initSize is the
  3240. ** suggested initial array size allocation.
  3241. **
  3242. ** The index of the new entry is returned in pIdx.
  3243. **
  3244. ** This routine returns a pointer to the array of objects. This
  3245. ** might be the same as the pArray parameter or it might be a different
  3246. ** pointer if the array was resized.
  3247. */
  3248. static T[] sqlite3ArrayAllocate<T>(
  3249. sqlite3 db, /* Connection to notify of malloc failures */
  3250. T[] pArray, /* Array of objects. Might be reallocated */
  3251. int szEntry, /* Size of each object in the array */
  3252. int initSize, /* Suggested initial allocation, in elements */
  3253. ref int pnEntry, /* Number of objects currently in use */
  3254. ref int pnAlloc, /* Current size of the allocation, in elements */
  3255. ref int pIdx /* Write the index of a new slot here */
  3256. ) where T : new()
  3257. {
  3258. //char* z;
  3259. if ( pnEntry >= pnAlloc )
  3260. {
  3261. //void* pNew;
  3262. int newSize;
  3263. newSize = ( pnAlloc ) * 2 + initSize;
  3264. //pNew = sqlite3DbRealloc(db, pArray, newSize * szEntry);
  3265. //if (pNew == 0)
  3266. //{
  3267. // pIdx = -1;
  3268. // return pArray;
  3269. //}
  3270. pnAlloc = newSize; //sqlite3DbMallocSize(db, pNew)/szEntry;
  3271. //pArray = pNew;
  3272. Array.Resize( ref pArray, newSize );
  3273. }
  3274. pArray[pnEntry] = new T();
  3275. //z = (char*)pArray;
  3276. //memset(z[*pnEntry * szEntry], 0, szEntry);
  3277. pIdx = pnEntry;
  3278. ++pnEntry;
  3279. return pArray;
  3280. }
  3281. /*
  3282. ** Append a new element to the given IdList. Create a new IdList if
  3283. ** need be.
  3284. **
  3285. ** A new IdList is returned, or NULL if malloc() fails.
  3286. */
  3287. // OVERLOADS, so I don't need to rewrite parse.c
  3288. static IdList sqlite3IdListAppend( sqlite3 db, int null_2, Token pToken )
  3289. {
  3290. return sqlite3IdListAppend( db, null, pToken );
  3291. }
  3292. static IdList sqlite3IdListAppend( sqlite3 db, IdList pList, Token pToken )
  3293. {
  3294. int i = 0;
  3295. if ( pList == null )
  3296. {
  3297. pList = new IdList();//sqlite3DbMallocZero(db, sizeof(IdList));
  3298. if ( pList == null )
  3299. return null;
  3300. pList.nAlloc = 0;
  3301. }
  3302. pList.a = (IdList_item[])sqlite3ArrayAllocate(
  3303. db,
  3304. pList.a,
  3305. -1,//sizeof(pList.a[0]),
  3306. 5,
  3307. ref pList.nId,
  3308. ref pList.nAlloc,
  3309. ref i
  3310. );
  3311. if ( i < 0 )
  3312. {
  3313. sqlite3IdListDelete( db, ref pList );
  3314. return null;
  3315. }
  3316. pList.a[i].zName = sqlite3NameFromToken( db, pToken );
  3317. return pList;
  3318. }
  3319. /*
  3320. ** Delete an IdList.
  3321. */
  3322. static void sqlite3IdListDelete( sqlite3 db, ref IdList pList )
  3323. {
  3324. int i;
  3325. if ( pList == null )
  3326. return;
  3327. for ( i = 0; i < pList.nId; i++ )
  3328. {
  3329. sqlite3DbFree( db, ref pList.a[i].zName );
  3330. }
  3331. sqlite3DbFree( db, ref pList.a );
  3332. sqlite3DbFree( db, ref pList );
  3333. }
  3334. /*
  3335. ** Return the index in pList of the identifier named zId. Return -1
  3336. ** if not found.
  3337. */
  3338. static int sqlite3IdListIndex( IdList pList, string zName )
  3339. {
  3340. int i;
  3341. if ( pList == null )
  3342. return -1;
  3343. for ( i = 0; i < pList.nId; i++ )
  3344. {
  3345. if ( pList.a[i].zName.Equals( zName, StringComparison.InvariantCultureIgnoreCase ) )
  3346. return i;
  3347. }
  3348. return -1;
  3349. }
  3350. /*
  3351. ** Expand the space allocated for the given SrcList object by
  3352. ** creating nExtra new slots beginning at iStart. iStart is zero based.
  3353. ** New slots are zeroed.
  3354. **
  3355. ** For example, suppose a SrcList initially contains two entries: A,B.
  3356. ** To append 3 new entries onto the end, do this:
  3357. **
  3358. ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
  3359. **
  3360. ** After the call above it would contain: A, B, nil, nil, nil.
  3361. ** If the iStart argument had been 1 instead of 2, then the result
  3362. ** would have been: A, nil, nil, nil, B. To prepend the new slots,
  3363. ** the iStart value would be 0. The result then would
  3364. ** be: nil, nil, nil, A, B.
  3365. **
  3366. ** If a memory allocation fails the SrcList is unchanged. The
  3367. ** db.mallocFailed flag will be set to true.
  3368. */
  3369. static SrcList sqlite3SrcListEnlarge(
  3370. sqlite3 db, /* Database connection to notify of OOM errors */
  3371. SrcList pSrc, /* The SrcList to be enlarged */
  3372. int nExtra, /* Number of new slots to add to pSrc.a[] */
  3373. int iStart /* Index in pSrc.a[] of first new slot */
  3374. )
  3375. {
  3376. int i;
  3377. /* Sanity checking on calling parameters */
  3378. Debug.Assert( iStart >= 0 );
  3379. Debug.Assert( nExtra >= 1 );
  3380. Debug.Assert( pSrc != null );
  3381. Debug.Assert( iStart <= pSrc.nSrc );
  3382. /* Allocate additional space if needed */
  3383. if ( pSrc.nSrc + nExtra > pSrc.nAlloc )
  3384. {
  3385. int nAlloc = pSrc.nSrc + nExtra;
  3386. int nGot;
  3387. // sqlite3DbRealloc(db, pSrc,
  3388. // sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc.a[0]) );
  3389. pSrc.nAlloc = (i16)nAlloc;
  3390. Array.Resize( ref pSrc.a, nAlloc );
  3391. // nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
  3392. //pSrc->nAlloc = (u16)nGot;
  3393. }
  3394. /* Move existing slots that come after the newly inserted slots
  3395. ** out of the way */
  3396. for ( i = pSrc.nSrc - 1; i >= iStart; i-- )
  3397. {
  3398. pSrc.a[i + nExtra] = pSrc.a[i];
  3399. }
  3400. pSrc.nSrc += (i16)nExtra;
  3401. /* Zero the newly allocated slots */
  3402. //memset(&pSrc.a[iStart], 0, sizeof(pSrc.a[0])*nExtra);
  3403. for ( i = iStart; i < iStart + nExtra; i++ )
  3404. {
  3405. pSrc.a[i] = new SrcList_item();
  3406. pSrc.a[i].iCursor = -1;
  3407. }
  3408. /* Return a pointer to the enlarged SrcList */
  3409. return pSrc;
  3410. }
  3411. /*
  3412. ** Append a new table name to the given SrcList. Create a new SrcList if
  3413. ** need be. A new entry is created in the SrcList even if pTable is NULL.
  3414. **
  3415. ** A SrcList is returned, or NULL if there is an OOM error. The returned
  3416. ** SrcList might be the same as the SrcList that was input or it might be
  3417. ** a new one. If an OOM error does occurs, then the prior value of pList
  3418. ** that is input to this routine is automatically freed.
  3419. **
  3420. ** If pDatabase is not null, it means that the table has an optional
  3421. ** database name prefix. Like this: "database.table". The pDatabase
  3422. ** points to the table name and the pTable points to the database name.
  3423. ** The SrcList.a[].zName field is filled with the table name which might
  3424. ** come from pTable (if pDatabase is NULL) or from pDatabase.
  3425. ** SrcList.a[].zDatabase is filled with the database name from pTable,
  3426. ** or with NULL if no database is specified.
  3427. **
  3428. ** In other words, if call like this:
  3429. **
  3430. ** sqlite3SrcListAppend(D,A,B,0);
  3431. **
  3432. ** Then B is a table name and the database name is unspecified. If called
  3433. ** like this:
  3434. **
  3435. ** sqlite3SrcListAppend(D,A,B,C);
  3436. **
  3437. ** Then C is the table name and B is the database name. If C is defined
  3438. ** then so is B. In other words, we never have a case where:
  3439. **
  3440. ** sqlite3SrcListAppend(D,A,0,C);
  3441. **
  3442. ** Both pTable and pDatabase are assumed to be quoted. They are dequoted
  3443. ** before being added to the SrcList.
  3444. */
  3445. // OVERLOADS, so I don't need to rewrite parse.c
  3446. static SrcList sqlite3SrcListAppend( sqlite3 db, int null_2, Token pTable, int null_4 )
  3447. {
  3448. return sqlite3SrcListAppend( db, null, pTable, null );
  3449. }
  3450. static SrcList sqlite3SrcListAppend( sqlite3 db, int null_2, Token pTable, Token pDatabase )
  3451. {
  3452. return sqlite3SrcListAppend( db, null, pTable, pDatabase );
  3453. }
  3454. static SrcList sqlite3SrcListAppend(
  3455. sqlite3 db, /* Connection to notify of malloc failures */
  3456. SrcList pList, /* Append to this SrcList. NULL creates a new SrcList */
  3457. Token pTable, /* Table to append */
  3458. Token pDatabase /* Database of the table */
  3459. )
  3460. {
  3461. SrcList_item pItem;
  3462. Debug.Assert( pDatabase == null || pTable != null ); /* Cannot have C without B */
  3463. if ( pList == null )
  3464. {
  3465. pList = new SrcList();//sqlite3DbMallocZero(db, SrcList.Length );
  3466. //if ( pList == null ) return null;
  3467. pList.nAlloc = 1;
  3468. pList.a = new SrcList_item[1];
  3469. }
  3470. pList = sqlite3SrcListEnlarge( db, pList, 1, pList.nSrc );
  3471. //if ( db.mallocFailed != 0 )
  3472. //{
  3473. // sqlite3SrcListDelete( db, ref pList );
  3474. // return null;
  3475. //}
  3476. pItem = pList.a[pList.nSrc - 1];
  3477. if ( pDatabase != null && String.IsNullOrEmpty( pDatabase.z ) )
  3478. {
  3479. pDatabase = null;
  3480. }
  3481. if ( pDatabase != null )
  3482. {
  3483. Token pTemp = pDatabase;
  3484. pDatabase = pTable;
  3485. pTable = pTemp;
  3486. }
  3487. pItem.zName = sqlite3NameFromToken( db, pTable );
  3488. pItem.zDatabase = sqlite3NameFromToken( db, pDatabase );
  3489. return pList;
  3490. }
  3491. /*
  3492. ** Assign VdbeCursor index numbers to all tables in a SrcList
  3493. */
  3494. static void sqlite3SrcListAssignCursors( Parse pParse, SrcList pList )
  3495. {
  3496. int i;
  3497. SrcList_item pItem;
  3498. Debug.Assert( pList != null /* || pParse.db.mallocFailed != 0 */ );
  3499. if ( pList != null )
  3500. {
  3501. for ( i = 0; i < pList.nSrc; i++ )
  3502. {
  3503. pItem = pList.a[i];
  3504. if ( pItem.iCursor >= 0 )
  3505. break;
  3506. pItem.iCursor = pParse.nTab++;
  3507. if ( pItem.pSelect != null )
  3508. {
  3509. sqlite3SrcListAssignCursors( pParse, pItem.pSelect.pSrc );
  3510. }
  3511. }
  3512. }
  3513. }
  3514. /*
  3515. ** Delete an entire SrcList including all its substructure.
  3516. */
  3517. static void sqlite3SrcListDelete( sqlite3 db, ref SrcList pList )
  3518. {
  3519. int i;
  3520. SrcList_item pItem;
  3521. if ( pList == null )
  3522. return;
  3523. for ( i = 0; i < pList.nSrc; i++ )
  3524. {//, pItem++){
  3525. pItem = pList.a[i];
  3526. sqlite3DbFree( db, ref pItem.zDatabase );
  3527. sqlite3DbFree( db, ref pItem.zName );
  3528. sqlite3DbFree( db, ref pItem.zAlias );
  3529. sqlite3DbFree( db, ref pItem.zIndex );
  3530. sqlite3DeleteTable( db, ref pItem.pTab );
  3531. sqlite3SelectDelete( db, ref pItem.pSelect );
  3532. sqlite3ExprDelete( db, ref pItem.pOn );
  3533. sqlite3IdListDelete( db, ref pItem.pUsing );
  3534. }
  3535. sqlite3DbFree( db, ref pList );
  3536. }
  3537. /*
  3538. ** This routine is called by the parser to add a new term to the
  3539. ** end of a growing FROM clause. The "p" parameter is the part of
  3540. ** the FROM clause that has already been constructed. "p" is NULL
  3541. ** if this is the first term of the FROM clause. pTable and pDatabase
  3542. ** are the name of the table and database named in the FROM clause term.
  3543. ** pDatabase is NULL if the database name qualifier is missing - the
  3544. ** usual case. If the term has a alias, then pAlias points to the
  3545. ** alias token. If the term is a subquery, then pSubquery is the
  3546. ** SELECT statement that the subquery encodes. The pTable and
  3547. ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
  3548. ** parameters are the content of the ON and USING clauses.
  3549. **
  3550. ** Return a new SrcList which encodes is the FROM with the new
  3551. ** term added.
  3552. */
  3553. // OVERLOADS, so I don't need to rewrite parse.c
  3554. static SrcList sqlite3SrcListAppendFromTerm( Parse pParse, SrcList p, int null_3, int null_4, Token pAlias, Select pSubquery, Expr pOn, IdList pUsing )
  3555. {
  3556. return sqlite3SrcListAppendFromTerm( pParse, p, null, null, pAlias, pSubquery, pOn, pUsing );
  3557. }
  3558. static SrcList sqlite3SrcListAppendFromTerm( Parse pParse, SrcList p, Token pTable, Token pDatabase, Token pAlias, int null_6, Expr pOn, IdList pUsing )
  3559. {
  3560. return sqlite3SrcListAppendFromTerm( pParse, p, pTable, pDatabase, pAlias, null, pOn, pUsing );
  3561. }
  3562. static SrcList sqlite3SrcListAppendFromTerm(
  3563. Parse pParse, /* Parsing context */
  3564. SrcList p, /* The left part of the FROM clause already seen */
  3565. Token pTable, /* Name of the table to add to the FROM clause */
  3566. Token pDatabase, /* Name of the database containing pTable */
  3567. Token pAlias, /* The right-hand side of the AS subexpression */
  3568. Select pSubquery, /* A subquery used in place of a table name */
  3569. Expr pOn, /* The ON clause of a join */
  3570. IdList pUsing /* The USING clause of a join */
  3571. )
  3572. {
  3573. SrcList_item pItem;
  3574. sqlite3 db = pParse.db;
  3575. if ( null == p && ( pOn != null || pUsing != null ) )
  3576. {
  3577. sqlite3ErrorMsg( pParse, "a JOIN clause is required before %s",
  3578. ( pOn != null ? "ON" : "USING" )
  3579. );
  3580. goto append_from_error;
  3581. }
  3582. p = sqlite3SrcListAppend( db, p, pTable, pDatabase );
  3583. //if ( p == null || NEVER( p.nSrc == 0 ) )
  3584. //{
  3585. // goto append_from_error;
  3586. //}
  3587. pItem = p.a[p.nSrc - 1];
  3588. Debug.Assert( pAlias != null );
  3589. if ( pAlias.n != 0 )
  3590. {
  3591. pItem.zAlias = sqlite3NameFromToken( db, pAlias );
  3592. }
  3593. pItem.pSelect = pSubquery;
  3594. pItem.pOn = pOn;
  3595. pItem.pUsing = pUsing;
  3596. return p;
  3597. append_from_error:
  3598. Debug.Assert( p == null );
  3599. sqlite3ExprDelete( db, ref pOn );
  3600. sqlite3IdListDelete( db, ref pUsing );
  3601. sqlite3SelectDelete( db, ref pSubquery );
  3602. return null;
  3603. }
  3604. /*
  3605. ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
  3606. ** element of the source-list passed as the second argument.
  3607. */
  3608. static void sqlite3SrcListIndexedBy( Parse pParse, SrcList p, Token pIndexedBy )
  3609. {
  3610. Debug.Assert( pIndexedBy != null );
  3611. if ( p != null && ALWAYS( p.nSrc > 0 ) )
  3612. {
  3613. SrcList_item pItem = p.a[p.nSrc - 1];
  3614. Debug.Assert( 0 == pItem.notIndexed && pItem.zIndex == null );
  3615. if ( pIndexedBy.n == 1 && null == pIndexedBy.z )
  3616. {
  3617. /* A "NOT INDEXED" clause was supplied. See parse.y
  3618. ** construct "indexed_opt" for details. */
  3619. pItem.notIndexed = 1;
  3620. }
  3621. else
  3622. {
  3623. pItem.zIndex = sqlite3NameFromToken( pParse.db, pIndexedBy );
  3624. }
  3625. }
  3626. }
  3627. /*
  3628. ** When building up a FROM clause in the parser, the join operator
  3629. ** is initially attached to the left operand. But the code generator
  3630. ** expects the join operator to be on the right operand. This routine
  3631. ** Shifts all join operators from left to right for an entire FROM
  3632. ** clause.
  3633. **
  3634. ** Example: Suppose the join is like this:
  3635. **
  3636. ** A natural cross join B
  3637. **
  3638. ** The operator is "natural cross join". The A and B operands are stored
  3639. ** in p.a[0] and p.a[1], respectively. The parser initially stores the
  3640. ** operator with A. This routine shifts that operator over to B.
  3641. */
  3642. static void sqlite3SrcListShiftJoinType( SrcList p )
  3643. {
  3644. if ( p != null && p.a != null )
  3645. {
  3646. int i;
  3647. for ( i = p.nSrc - 1; i > 0; i-- )
  3648. {
  3649. p.a[i].jointype = p.a[i - 1].jointype;
  3650. }
  3651. p.a[0].jointype = 0;
  3652. }
  3653. }
  3654. /*
  3655. ** Begin a transaction
  3656. */
  3657. static void sqlite3BeginTransaction( Parse pParse, int type )
  3658. {
  3659. sqlite3 db;
  3660. Vdbe v;
  3661. int i;
  3662. Debug.Assert( pParse != null );
  3663. db = pParse.db;
  3664. Debug.Assert( db != null );
  3665. /* if( db.aDb[0].pBt==0 ) return; */
  3666. if ( sqlite3AuthCheck( pParse, SQLITE_TRANSACTION, "BEGIN", null, null ) != 0 )
  3667. {
  3668. return;
  3669. }
  3670. v = sqlite3GetVdbe( pParse );
  3671. if ( v == null )
  3672. return;
  3673. if ( type != TK_DEFERRED )
  3674. {
  3675. for ( i = 0; i < db.nDb; i++ )
  3676. {
  3677. sqlite3VdbeAddOp2( v, OP_Transaction, i, ( type == TK_EXCLUSIVE ) ? 2 : 1 );
  3678. sqlite3VdbeUsesBtree( v, i );
  3679. }
  3680. }
  3681. sqlite3VdbeAddOp2( v, OP_AutoCommit, 0, 0 );
  3682. }
  3683. /*
  3684. ** Commit a transaction
  3685. */
  3686. static void sqlite3CommitTransaction( Parse pParse )
  3687. {
  3688. sqlite3 db;
  3689. Vdbe v;
  3690. Debug.Assert( pParse != null );
  3691. db = pParse.db;
  3692. Debug.Assert( db != null );
  3693. /* if( db.aDb[0].pBt==0 ) return; */
  3694. if ( sqlite3AuthCheck( pParse, SQLITE_TRANSACTION, "COMMIT", null, null ) != 0 )
  3695. {
  3696. return;
  3697. }
  3698. v = sqlite3GetVdbe( pParse );
  3699. if ( v != null )
  3700. {
  3701. sqlite3VdbeAddOp2( v, OP_AutoCommit, 1, 0 );
  3702. }
  3703. }
  3704. /*
  3705. ** Rollback a transaction
  3706. */
  3707. static void sqlite3RollbackTransaction( Parse pParse )
  3708. {
  3709. sqlite3 db;
  3710. Vdbe v;
  3711. Debug.Assert( pParse != null );
  3712. db = pParse.db;
  3713. Debug.Assert( db != null );
  3714. /* if( db.aDb[0].pBt==0 ) return; */
  3715. if ( sqlite3AuthCheck( pParse, SQLITE_TRANSACTION, "ROLLBACK", null, null ) != 0 )
  3716. {
  3717. return;
  3718. }
  3719. v = sqlite3GetVdbe( pParse );
  3720. if ( v != null )
  3721. {
  3722. sqlite3VdbeAddOp2( v, OP_AutoCommit, 1, 1 );
  3723. }
  3724. }
  3725. /*
  3726. ** This function is called by the parser when it parses a command to create,
  3727. ** release or rollback an SQL savepoint.
  3728. */
  3729. #if !SQLITE_OMIT_AUTHORIZATION
  3730. const string[] az = { "BEGIN", "RELEASE", "ROLLBACK" };
  3731. #endif
  3732. static void sqlite3Savepoint( Parse pParse, int op, Token pName )
  3733. {
  3734. string zName = sqlite3NameFromToken( pParse.db, pName );
  3735. if ( zName != null )
  3736. {
  3737. Vdbe v = sqlite3GetVdbe( pParse );
  3738. #if !SQLITE_OMIT_AUTHORIZATION
  3739. Debug.Assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
  3740. #endif
  3741. if ( null == v
  3742. #if !SQLITE_OMIT_AUTHORIZATION
  3743. || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0)
  3744. #endif
  3745. )
  3746. {
  3747. sqlite3DbFree( pParse.db, ref zName );
  3748. return;
  3749. }
  3750. sqlite3VdbeAddOp4( v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC );
  3751. }
  3752. }
  3753. /*
  3754. ** Make sure the TEMP database is open and available for use. Return
  3755. ** the number of errors. Leave any error messages in the pParse structure.
  3756. */
  3757. static int sqlite3OpenTempDatabase( Parse pParse )
  3758. {
  3759. sqlite3 db = pParse.db;
  3760. if ( db.aDb[1].pBt == null && pParse.explain == 0 )
  3761. {
  3762. int rc;
  3763. Btree pBt = null;
  3764. const int flags =
  3765. SQLITE_OPEN_READWRITE |
  3766. SQLITE_OPEN_CREATE |
  3767. SQLITE_OPEN_EXCLUSIVE |
  3768. SQLITE_OPEN_DELETEONCLOSE |
  3769. SQLITE_OPEN_TEMP_DB;
  3770. rc = sqlite3BtreeOpen( null, db, ref pBt, 0, flags );
  3771. if ( rc != SQLITE_OK )
  3772. {
  3773. sqlite3ErrorMsg( pParse, "unable to open a temporary database " +
  3774. "file for storing temporary tables" );
  3775. pParse.rc = rc;
  3776. return 1;
  3777. }
  3778. db.aDb[1].pBt = pBt;
  3779. Debug.Assert( db.aDb[1].pSchema != null );
  3780. if ( SQLITE_NOMEM == sqlite3BtreeSetPageSize( pBt, db.nextPagesize, -1, 0 ) )
  3781. {
  3782. // db.mallocFailed = 1;
  3783. }
  3784. }
  3785. return 0;
  3786. }
  3787. /*
  3788. ** Generate VDBE code that will verify the schema cookie and start
  3789. ** a read-transaction for all named database files.
  3790. **
  3791. ** It is important that all schema cookies be verified and all
  3792. ** read transactions be started before anything else happens in
  3793. ** the VDBE program. But this routine can be called after much other
  3794. ** code has been generated. So here is what we do:
  3795. **
  3796. ** The first time this routine is called, we code an OP_Goto that
  3797. ** will jump to a subroutine at the end of the program. Then we
  3798. ** record every database that needs its schema verified in the
  3799. ** pParse.cookieMask field. Later, after all other code has been
  3800. ** generated, the subroutine that does the cookie verifications and
  3801. ** starts the transactions will be coded and the OP_Goto P2 value
  3802. ** will be made to point to that subroutine. The generation of the
  3803. ** cookie verification subroutine code happens in sqlite3FinishCoding().
  3804. **
  3805. ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
  3806. ** schema on any databases. This can be used to position the OP_Goto
  3807. ** early in the code, before we know if any database tables will be used.
  3808. */
  3809. static void sqlite3CodeVerifySchema( Parse pParse, int iDb )
  3810. {
  3811. Parse pToplevel = sqlite3ParseToplevel( pParse );
  3812. if ( pToplevel.cookieGoto == 0 )
  3813. {
  3814. Vdbe v = sqlite3GetVdbe( pToplevel );
  3815. if ( v == null )
  3816. return; /* This only happens if there was a prior error */
  3817. pToplevel.cookieGoto = sqlite3VdbeAddOp2( v, OP_Goto, 0, 0 ) + 1;
  3818. }
  3819. if ( iDb >= 0 )
  3820. {
  3821. sqlite3 db = pToplevel.db;
  3822. int mask;
  3823. Debug.Assert( iDb < db.nDb );
  3824. Debug.Assert( db.aDb[iDb].pBt != null || iDb == 1 );
  3825. Debug.Assert( iDb < SQLITE_MAX_ATTACHED + 2 );
  3826. mask = (int)( 1 << iDb );
  3827. if ( ( pToplevel.cookieMask & mask ) == 0 )
  3828. {
  3829. pToplevel.cookieMask |= (u32)mask;
  3830. pToplevel.cookieValue[iDb] = db.aDb[iDb].pSchema.schema_cookie;
  3831. if ( 0 == OMIT_TEMPDB && iDb == 1 )
  3832. {
  3833. sqlite3OpenTempDatabase( pToplevel );
  3834. }
  3835. }
  3836. }
  3837. }
  3838. /*
  3839. ** Generate VDBE code that prepares for doing an operation that
  3840. ** might change the database.
  3841. **
  3842. ** This routine starts a new transaction if we are not already within
  3843. ** a transaction. If we are already within a transaction, then a checkpoint
  3844. ** is set if the setStatement parameter is true. A checkpoint should
  3845. ** be set for operations that might fail (due to a constraint) part of
  3846. ** the way through and which will need to undo some writes without having to
  3847. ** rollback the whole transaction. For operations where all constraints
  3848. ** can be checked before any changes are made to the database, it is never
  3849. ** necessary to undo a write and the checkpoint should not be set.
  3850. */
  3851. static void sqlite3BeginWriteOperation( Parse pParse, int setStatement, int iDb )
  3852. {
  3853. Parse pToplevel = sqlite3ParseToplevel( pParse );
  3854. sqlite3CodeVerifySchema( pParse, iDb );
  3855. pToplevel.writeMask |= (u32)( 1 << iDb );
  3856. pToplevel.isMultiWrite |= (u8)setStatement;
  3857. }
  3858. /*
  3859. ** Indicate that the statement currently under construction might write
  3860. ** more than one entry (example: deleting one row then inserting another,
  3861. ** inserting multiple rows in a table, or inserting a row and index entries.)
  3862. ** If an abort occurs after some of these writes have completed, then it will
  3863. ** be necessary to undo the completed writes.
  3864. */
  3865. static void sqlite3MultiWrite( Parse pParse )
  3866. {
  3867. Parse pToplevel = sqlite3ParseToplevel( pParse );
  3868. pToplevel.isMultiWrite = 1;
  3869. }
  3870. /*
  3871. ** The code generator calls this routine if is discovers that it is
  3872. ** possible to abort a statement prior to completion. In order to
  3873. ** perform this abort without corrupting the database, we need to make
  3874. ** sure that the statement is protected by a statement transaction.
  3875. **
  3876. ** Technically, we only need to set the mayAbort flag if the
  3877. ** isMultiWrite flag was previously set. There is a time dependency
  3878. ** such that the abort must occur after the multiwrite. This makes
  3879. ** some statements involving the REPLACE conflict resolution algorithm
  3880. ** go a little faster. But taking advantage of this time dependency
  3881. ** makes it more difficult to prove that the code is correct (in
  3882. ** particular, it prevents us from writing an effective
  3883. ** implementation of sqlite3AssertMayAbort()) and so we have chosen
  3884. ** to take the safe route and skip the optimization.
  3885. */
  3886. static void sqlite3MayAbort( Parse pParse )
  3887. {
  3888. Parse pToplevel = sqlite3ParseToplevel( pParse );
  3889. pToplevel.mayAbort = 1;
  3890. }
  3891. /*
  3892. ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
  3893. ** error. The onError parameter determines which (if any) of the statement
  3894. ** and/or current transaction is rolled back.
  3895. */
  3896. static void sqlite3HaltConstraint( Parse pParse, int onError, string p4, int p4type )
  3897. {
  3898. Vdbe v = sqlite3GetVdbe( pParse );
  3899. if ( onError == OE_Abort )
  3900. {
  3901. sqlite3MayAbort( pParse );
  3902. }
  3903. sqlite3VdbeAddOp4( v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, p4, p4type );
  3904. }
  3905. static void sqlite3HaltConstraint( Parse pParse, int onError, byte[] p4, int p4type )
  3906. {
  3907. Vdbe v = sqlite3GetVdbe( pParse );
  3908. if ( onError == OE_Abort )
  3909. {
  3910. sqlite3MayAbort( pParse );
  3911. }
  3912. sqlite3VdbeAddOp4( v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, p4, p4type );
  3913. }
  3914. /*
  3915. ** Check to see if pIndex uses the collating sequence pColl. Return
  3916. ** true if it does and false if it does not.
  3917. */
  3918. #if !SQLITE_OMIT_REINDEX
  3919. static bool collationMatch( string zColl, Index pIndex )
  3920. {
  3921. int i;
  3922. Debug.Assert( zColl != null );
  3923. for ( i = 0; i < pIndex.nColumn; i++ )
  3924. {
  3925. string z = pIndex.azColl[i];
  3926. Debug.Assert( z != null );
  3927. if ( z.Equals( zColl, StringComparison.InvariantCultureIgnoreCase ) )
  3928. {
  3929. return true;
  3930. }
  3931. }
  3932. return false;
  3933. }
  3934. #endif
  3935. /*
  3936. ** Recompute all indices of pTab that use the collating sequence pColl.
  3937. ** If pColl == null then recompute all indices of pTab.
  3938. */
  3939. #if !SQLITE_OMIT_REINDEX
  3940. static void reindexTable( Parse pParse, Table pTab, string zColl )
  3941. {
  3942. Index pIndex; /* An index associated with pTab */
  3943. for ( pIndex = pTab.pIndex; pIndex != null; pIndex = pIndex.pNext )
  3944. {
  3945. if ( zColl == null || collationMatch( zColl, pIndex ) )
  3946. {
  3947. int iDb = sqlite3SchemaToIndex( pParse.db, pTab.pSchema );
  3948. sqlite3BeginWriteOperation( pParse, 0, iDb );
  3949. sqlite3RefillIndex( pParse, pIndex, -1 );
  3950. }
  3951. }
  3952. }
  3953. #endif
  3954. /*
  3955. ** Recompute all indices of all tables in all databases where the
  3956. ** indices use the collating sequence pColl. If pColl == null then recompute
  3957. ** all indices everywhere.
  3958. */
  3959. #if !SQLITE_OMIT_REINDEX
  3960. static void reindexDatabases( Parse pParse, string zColl )
  3961. {
  3962. Db pDb; /* A single database */
  3963. int iDb; /* The database index number */
  3964. sqlite3 db = pParse.db; /* The database connection */
  3965. HashElem k; /* For looping over tables in pDb */
  3966. Table pTab; /* A table in the database */
  3967. for ( iDb = 0; iDb < db.nDb; iDb++ )//, pDb++ )
  3968. {
  3969. pDb = db.aDb[iDb];
  3970. Debug.Assert( pDb != null );
  3971. for ( k = pDb.pSchema.tblHash.first; k != null; k = k.next ) //for ( k = sqliteHashFirst( pDb.pSchema.tblHash ) ; k != null ; k = sqliteHashNext( k ) )
  3972. {
  3973. pTab = (Table)k.data;// sqliteHashData( k );
  3974. reindexTable( pParse, pTab, zColl );
  3975. }
  3976. }
  3977. }
  3978. #endif
  3979. /*
  3980. ** Generate code for the REINDEX command.
  3981. **
  3982. ** REINDEX -- 1
  3983. ** REINDEX <collation> -- 2
  3984. ** REINDEX ?<database>.?<tablename> -- 3
  3985. ** REINDEX ?<database>.?<indexname> -- 4
  3986. **
  3987. ** Form 1 causes all indices in all attached databases to be rebuilt.
  3988. ** Form 2 rebuilds all indices in all databases that use the named
  3989. ** collating function. Forms 3 and 4 rebuild the named index or all
  3990. ** indices associated with the named table.
  3991. */
  3992. #if !SQLITE_OMIT_REINDEX
  3993. // OVERLOADS, so I don't need to rewrite parse.c
  3994. static void sqlite3Reindex( Parse pParse, int null_2, int null_3 )
  3995. {
  3996. sqlite3Reindex( pParse, null, null );
  3997. }
  3998. static void sqlite3Reindex( Parse pParse, Token pName1, Token pName2 )
  3999. {
  4000. CollSeq pColl; /* Collating sequence to be reindexed, or NULL */
  4001. string z; /* Name of a table or index */
  4002. string zDb; /* Name of the database */
  4003. Table pTab; /* A table in the database */
  4004. Index pIndex; /* An index associated with pTab */
  4005. int iDb; /* The database index number */
  4006. sqlite3 db = pParse.db; /* The database connection */
  4007. Token pObjName = new Token(); /* Name of the table or index to be reindexed */
  4008. /* Read the database schema. If an error occurs, leave an error message
  4009. ** and code in pParse and return NULL. */
  4010. if ( SQLITE_OK != sqlite3ReadSchema( pParse ) )
  4011. {
  4012. return;
  4013. }
  4014. if ( pName1 == null )
  4015. {
  4016. reindexDatabases( pParse, null );
  4017. return;
  4018. }
  4019. else if ( NEVER( pName2 == null ) || pName2.z == null || pName2.z.Length == 0 )
  4020. {
  4021. string zColl;
  4022. Debug.Assert( pName1.z != null );
  4023. zColl = sqlite3NameFromToken( pParse.db, pName1 );
  4024. if ( zColl == null )
  4025. return;
  4026. pColl = sqlite3FindCollSeq( db, ENC( db ), zColl, 0 );
  4027. if ( pColl != null )
  4028. {
  4029. reindexDatabases( pParse, zColl );
  4030. sqlite3DbFree( db, ref zColl );
  4031. return;
  4032. }
  4033. sqlite3DbFree( db, ref zColl );
  4034. }
  4035. iDb = sqlite3TwoPartName( pParse, pName1, pName2, ref pObjName );
  4036. if ( iDb < 0 )
  4037. return;
  4038. z = sqlite3NameFromToken( db, pObjName );
  4039. if ( z == null )
  4040. return;
  4041. zDb = db.aDb[iDb].zName;
  4042. pTab = sqlite3FindTable( db, z, zDb );
  4043. if ( pTab != null )
  4044. {
  4045. reindexTable( pParse, pTab, null );
  4046. sqlite3DbFree( db, ref z );
  4047. return;
  4048. }
  4049. pIndex = sqlite3FindIndex( db, z, zDb );
  4050. sqlite3DbFree( db, ref z );
  4051. if ( pIndex != null )
  4052. {
  4053. sqlite3BeginWriteOperation( pParse, 0, iDb );
  4054. sqlite3RefillIndex( pParse, pIndex, -1 );
  4055. return;
  4056. }
  4057. sqlite3ErrorMsg( pParse, "unable to identify the object to be reindexed" );
  4058. }
  4059. #endif
  4060. /*
  4061. ** Return a dynamicly allocated KeyInfo structure that can be used
  4062. ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
  4063. **
  4064. ** If successful, a pointer to the new structure is returned. In this case
  4065. ** the caller is responsible for calling sqlite3DbFree(db, ) on the returned
  4066. ** pointer. If an error occurs (out of memory or missing collation
  4067. ** sequence), NULL is returned and the state of pParse updated to reflect
  4068. ** the error.
  4069. */
  4070. static KeyInfo sqlite3IndexKeyinfo( Parse pParse, Index pIdx )
  4071. {
  4072. int i;
  4073. int nCol = pIdx.nColumn;
  4074. //int nBytes = KeyInfo.Length + (nCol - 1) * CollSeq*.Length + nCol;
  4075. sqlite3 db = pParse.db;
  4076. KeyInfo pKey = new KeyInfo();// (KeyInfo*)sqlite3DbMallocZero(db, nBytes);
  4077. if ( pKey != null )
  4078. {
  4079. pKey.db = pParse.db;
  4080. pKey.aSortOrder = new byte[nCol];
  4081. pKey.aColl = new CollSeq[nCol];// (u8*)&(pKey.aColl[nCol]);
  4082. // Debug.Assert(pKey.aSortOrder[nCol] == &(((u8*)pKey)[nBytes]));
  4083. for ( i = 0; i < nCol; i++ )
  4084. {
  4085. string zColl = pIdx.azColl[i];
  4086. Debug.Assert( zColl != null );
  4087. pKey.aColl[i] = sqlite3LocateCollSeq( pParse, zColl );
  4088. pKey.aSortOrder[i] = pIdx.aSortOrder[i];
  4089. }
  4090. pKey.nField = (u16)nCol;
  4091. }
  4092. if ( pParse.nErr != 0 )
  4093. {
  4094. pKey = null;
  4095. sqlite3DbFree( db, ref pKey );
  4096. }
  4097. return pKey;
  4098. }
  4099. }
  4100. }