sqlite
[Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI.
Brought by drakestapleton
sqlite / ext / intck / sqlite3intck.c
| 1 | /* |
| 2 | ** 2024-02-08 |
| 3 | ** |
| 4 | ** The author disclaims copyright to this source code. In place of |
| 5 | ** a legal notice, here is a blessing: |
| 6 | ** |
| 7 | ** May you do good and not evil. |
| 8 | ** May you find forgiveness for yourself and forgive others. |
| 9 | ** May you share freely, never taking more than you give. |
| 10 | ** |
| 11 | ************************************************************************* |
| 12 | */ |
| 13 | |
| 14 | #include "sqlite3intck.h" |
| 15 | #include <string.h> |
| 16 | #include <assert.h> |
| 17 | |
| 18 | #include <stdio.h> |
| 19 | #include <stdlib.h> |
| 20 | |
| 21 | /* |
| 22 | ** nKeyVal: |
| 23 | ** The number of values that make up the 'key' for the current pCheck |
| 24 | ** statement. |
| 25 | ** |
| 26 | ** rc: |
| 27 | ** Error code returned by most recent sqlite3_intck_step() or |
| 28 | ** sqlite3_intck_unlock() call. This is set to SQLITE_DONE when |
| 29 | ** the integrity-check operation is finished. |
| 30 | ** |
| 31 | ** zErr: |
| 32 | ** If the object has entered the error state, this is the error message. |
| 33 | ** Is freed using sqlite3_free() when the object is deleted. |
| 34 | ** |
| 35 | ** zTestSql: |
| 36 | ** The value returned by the most recent call to sqlite3_intck_testsql(). |
| 37 | ** Each call to testsql() frees the previous zTestSql value (using |
| 38 | ** sqlite3_free()) and replaces it with the new value it will return. |
| 39 | */ |
| 40 | struct sqlite3_intck { |
| 41 | sqlite3 *db; |
| 42 | const char *zDb; /* Copy of zDb parameter to _open() */ |
| 43 | char *zObj; /* Current object. Or NULL. */ |
| 44 | |
| 45 | sqlite3_stmt *pCheck; /* Current check statement */ |
| 46 | char *zKey; |
| 47 | int nKeyVal; |
| 48 | |
| 49 | char *zMessage; |
| 50 | int bCorruptSchema; |
| 51 | |
| 52 | int rc; /* Error code */ |
| 53 | char *zErr; /* Error message */ |
| 54 | char *zTestSql; /* Returned by sqlite3_intck_test_sql() */ |
| 55 | }; |
| 56 | |
| 57 | |
| 58 | /* |
| 59 | ** Some error has occurred while using database p->db. Save the error message |
| 60 | ** and error code currently held by the database handle in p->rc and p->zErr. |
| 61 | */ |
| 62 | static void intckSaveErrmsg(sqlite3_intck *p){ |
| 63 | p->rc = sqlite3_errcode(p->db); |
| 64 | sqlite3_free(p->zErr); |
| 65 | p->zErr = sqlite3_mprintf("%s", sqlite3_errmsg(p->db)); |
| 66 | } |
| 67 | |
| 68 | /* |
| 69 | ** If the handle passed as the first argument is already in the error state, |
| 70 | ** then this function is a no-op (returns NULL immediately). Otherwise, if an |
| 71 | ** error occurs within this function, it leaves an error in said handle. |
| 72 | ** |
| 73 | ** Otherwise, this function attempts to prepare SQL statement zSql and |
| 74 | ** return the resulting statement handle to the user. |
| 75 | */ |
| 76 | static sqlite3_stmt *intckPrepare(sqlite3_intck *p, const char *zSql){ |
| 77 | sqlite3_stmt *pRet = 0; |
| 78 | if( p->rc==SQLITE_OK ){ |
| 79 | p->rc = sqlite3_prepare_v2(p->db, zSql, -1, &pRet, 0); |
| 80 | if( p->rc!=SQLITE_OK ){ |
| 81 | intckSaveErrmsg(p); |
| 82 | assert( pRet==0 ); |
| 83 | } |
| 84 | } |
| 85 | return pRet; |
| 86 | } |
| 87 | |
| 88 | /* |
| 89 | ** If the handle passed as the first argument is already in the error state, |
| 90 | ** then this function is a no-op (returns NULL immediately). Otherwise, if an |
| 91 | ** error occurs within this function, it leaves an error in said handle. |
| 92 | ** |
| 93 | ** Otherwise, this function treats argument zFmt as a printf() style format |
| 94 | ** string. It formats it according to the trailing arguments and then |
| 95 | ** attempts to prepare the results and return the resulting prepared |
| 96 | ** statement. |
| 97 | */ |
| 98 | static sqlite3_stmt *intckPrepareFmt(sqlite3_intck *p, const char *zFmt, ...){ |
| 99 | sqlite3_stmt *pRet = 0; |
| 100 | va_list ap; |
| 101 | char *zSql = 0; |
| 102 | va_start(ap, zFmt); |
| 103 | zSql = sqlite3_vmprintf(zFmt, ap); |
| 104 | if( p->rc==SQLITE_OK && zSql==0 ){ |
| 105 | p->rc = SQLITE_NOMEM; |
| 106 | } |
| 107 | pRet = intckPrepare(p, zSql); |
| 108 | sqlite3_free(zSql); |
| 109 | va_end(ap); |
| 110 | return pRet; |
| 111 | } |
| 112 | |
| 113 | /* |
| 114 | ** Finalize SQL statement pStmt. If an error occurs and the handle passed |
| 115 | ** as the first argument does not already contain an error, store the |
| 116 | ** error in the handle. |
| 117 | */ |
| 118 | static void intckFinalize(sqlite3_intck *p, sqlite3_stmt *pStmt){ |
| 119 | int rc = sqlite3_finalize(pStmt); |
| 120 | if( p->rc==SQLITE_OK && rc!=SQLITE_OK ){ |
| 121 | intckSaveErrmsg(p); |
| 122 | } |
| 123 | } |
| 124 | |
| 125 | /* |
| 126 | ** If there is already an error in handle p, return it. Otherwise, call |
| 127 | ** sqlite3_step() on the statement handle and return that value. |
| 128 | */ |
| 129 | static int intckStep(sqlite3_intck *p, sqlite3_stmt *pStmt){ |
| 130 | if( p->rc ) return p->rc; |
| 131 | return sqlite3_step(pStmt); |
| 132 | } |
| 133 | |
| 134 | /* |
| 135 | ** Execute SQL statement zSql. There is no way to obtain any results |
| 136 | ** returned by the statement. This function uses the sqlite3_intck error |
| 137 | ** code convention. |
| 138 | */ |
| 139 | static void intckExec(sqlite3_intck *p, const char *zSql){ |
| 140 | sqlite3_stmt *pStmt = 0; |
| 141 | pStmt = intckPrepare(p, zSql); |
| 142 | intckStep(p, pStmt); |
| 143 | intckFinalize(p, pStmt); |
| 144 | } |
| 145 | |
| 146 | /* |
| 147 | ** A wrapper around sqlite3_mprintf() that uses the sqlite3_intck error |
| 148 | ** code convention. |
| 149 | */ |
| 150 | static char *intckMprintf(sqlite3_intck *p, const char *zFmt, ...){ |
| 151 | va_list ap; |
| 152 | char *zRet = 0; |
| 153 | va_start(ap, zFmt); |
| 154 | zRet = sqlite3_vmprintf(zFmt, ap); |
| 155 | if( p->rc==SQLITE_OK ){ |
| 156 | if( zRet==0 ){ |
| 157 | p->rc = SQLITE_NOMEM; |
| 158 | } |
| 159 | }else{ |
| 160 | sqlite3_free(zRet); |
| 161 | zRet = 0; |
| 162 | } |
| 163 | va_end(ap); |
| 164 | return zRet; |
| 165 | } |
| 166 | |
| 167 | /* |
| 168 | ** This is used by sqlite3_intck_unlock() to save the vector key value |
| 169 | ** required to restart the current pCheck query as a nul-terminated string |
| 170 | ** in p->zKey. |
| 171 | */ |
| 172 | static void intckSaveKey(sqlite3_intck *p){ |
| 173 | int ii; |
| 174 | char *zSql = 0; |
| 175 | sqlite3_stmt *pStmt = 0; |
| 176 | sqlite3_stmt *pXinfo = 0; |
| 177 | const char *zDir = 0; |
| 178 | |
| 179 | assert( p->pCheck ); |
| 180 | assert( p->zKey==0 ); |
| 181 | |
| 182 | pXinfo = intckPrepareFmt(p, |
| 183 | "SELECT group_concat(desc, '') FROM %Q.sqlite_schema s, " |
| 184 | "pragma_index_xinfo(%Q, %Q) " |
| 185 | "WHERE s.type='index' AND s.name=%Q", |
| 186 | p->zDb, p->zObj, p->zDb, p->zObj |
| 187 | ); |
| 188 | if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXinfo) ){ |
| 189 | zDir = (const char*)sqlite3_column_text(pXinfo, 0); |
| 190 | } |
| 191 | |
| 192 | if( zDir==0 ){ |
| 193 | /* Object is a table, not an index. This is the easy case,as there are |
| 194 | ** no DESC columns or NULL values in a primary key. */ |
| 195 | const char *zSep = "SELECT '(' || "; |
| 196 | for(ii=0; ii<p->nKeyVal; ii++){ |
| 197 | zSql = intckMprintf(p, "%z%squote(?)", zSql, zSep); |
| 198 | zSep = " || ', ' || "; |
| 199 | } |
| 200 | zSql = intckMprintf(p, "%z || ')'", zSql); |
| 201 | }else{ |
| 202 | |
| 203 | /* Object is an index. */ |
| 204 | assert( p->nKeyVal>1 ); |
| 205 | for(ii=p->nKeyVal; ii>0; ii--){ |
| 206 | int bLastIsDesc = zDir[ii-1]=='1'; |
| 207 | int bLastIsNull = sqlite3_column_type(p->pCheck, ii)==SQLITE_NULL; |
| 208 | const char *zLast = sqlite3_column_name(p->pCheck, ii); |
| 209 | char *zLhs = 0; |
| 210 | char *zRhs = 0; |
| 211 | char *zWhere = 0; |
| 212 | |
| 213 | if( bLastIsNull ){ |
| 214 | if( bLastIsDesc ) continue; |
| 215 | zWhere = intckMprintf(p, "'%s IS NOT NULL'", zLast); |
| 216 | }else{ |
| 217 | const char *zOp = bLastIsDesc ? "<" : ">"; |
| 218 | zWhere = intckMprintf(p, "'%s %s ' || quote(?%d)", zLast, zOp, ii); |
| 219 | } |
| 220 | |
| 221 | if( ii>1 ){ |
| 222 | const char *zLhsSep = ""; |
| 223 | const char *zRhsSep = ""; |
| 224 | int jj; |
| 225 | for(jj=0; jj<ii-1; jj++){ |
| 226 | const char *zAlias = (const char*)sqlite3_column_name(p->pCheck,jj+1); |
| 227 | zLhs = intckMprintf(p, "%z%s%s", zLhs, zLhsSep, zAlias); |
| 228 | zRhs = intckMprintf(p, "%z%squote(?%d)", zRhs, zRhsSep, jj+1); |
| 229 | zLhsSep = ","; |
| 230 | zRhsSep = " || ',' || "; |
| 231 | } |
| 232 | |
| 233 | zWhere = intckMprintf(p, |
| 234 | "'(%z) IS (' || %z || ') AND ' || %z", |
| 235 | zLhs, zRhs, zWhere); |
| 236 | } |
| 237 | zWhere = intckMprintf(p, "'WHERE ' || %z", zWhere); |
| 238 | |
| 239 | zSql = intckMprintf(p, "%z%s(quote( %z ) )", |
| 240 | zSql, |
| 241 | (zSql==0 ? "VALUES" : ",\n "), |
| 242 | zWhere |
| 243 | ); |
| 244 | } |
| 245 | zSql = intckMprintf(p, |
| 246 | "WITH wc(q) AS (\n%z\n)" |
| 247 | "SELECT 'VALUES' || group_concat('(' || q || ')', ',\n ') FROM wc" |
| 248 | , zSql |
| 249 | ); |
| 250 | } |
| 251 | |
| 252 | pStmt = intckPrepare(p, zSql); |
| 253 | if( p->rc==SQLITE_OK ){ |
| 254 | for(ii=0; ii<p->nKeyVal; ii++){ |
| 255 | sqlite3_bind_value(pStmt, ii+1, sqlite3_column_value(p->pCheck, ii+1)); |
| 256 | } |
| 257 | if( SQLITE_ROW==sqlite3_step(pStmt) ){ |
| 258 | p->zKey = intckMprintf(p,"%s",(const char*)sqlite3_column_text(pStmt, 0)); |
| 259 | } |
| 260 | intckFinalize(p, pStmt); |
| 261 | } |
| 262 | |
| 263 | sqlite3_free(zSql); |
| 264 | intckFinalize(p, pXinfo); |
| 265 | } |
| 266 | |
| 267 | /* |
| 268 | ** Find the next database object (table or index) to check. If successful, |
| 269 | ** set sqlite3_intck.zObj to point to a nul-terminated buffer containing |
| 270 | ** the object's name before returning. |
| 271 | */ |
| 272 | static void intckFindObject(sqlite3_intck *p){ |
| 273 | sqlite3_stmt *pStmt = 0; |
| 274 | char *zPrev = p->zObj; |
| 275 | p->zObj = 0; |
| 276 | |
| 277 | assert( p->rc==SQLITE_OK ); |
| 278 | assert( p->pCheck==0 ); |
| 279 | |
| 280 | pStmt = intckPrepareFmt(p, |
| 281 | "WITH tables(table_name) AS (" |
| 282 | " SELECT name" |
| 283 | " FROM %Q.sqlite_schema WHERE (type='table' OR type='index') AND rootpage" |
| 284 | " UNION ALL " |
| 285 | " SELECT 'sqlite_schema'" |
| 286 | ")" |
| 287 | "SELECT table_name FROM tables " |
| 288 | "WHERE ?1 IS NULL OR table_name%s?1 " |
| 289 | "ORDER BY 1" |
| 290 | , p->zDb, (p->zKey ? ">=" : ">") |
| 291 | ); |
| 292 | |
| 293 | if( p->rc==SQLITE_OK ){ |
| 294 | sqlite3_bind_text(pStmt, 1, zPrev, -1, SQLITE_TRANSIENT); |
| 295 | if( sqlite3_step(pStmt)==SQLITE_ROW ){ |
| 296 | p->zObj = intckMprintf(p,"%s",(const char*)sqlite3_column_text(pStmt, 0)); |
| 297 | } |
| 298 | } |
| 299 | intckFinalize(p, pStmt); |
| 300 | |
| 301 | /* If this is a new object, ensure the previous key value is cleared. */ |
| 302 | if( sqlite3_stricmp(p->zObj, zPrev) ){ |
| 303 | sqlite3_free(p->zKey); |
| 304 | p->zKey = 0; |
| 305 | } |
| 306 | |
| 307 | sqlite3_free(zPrev); |
| 308 | } |
| 309 | |
| 310 | /* |
| 311 | ** Return the size in bytes of the first token in nul-terminated buffer z. |
| 312 | ** For the purposes of this call, a token is either: |
| 313 | ** |
| 314 | ** * a quoted SQL string, |
| 315 | * * a contiguous series of ascii alphabet characters, or |
| 316 | * * any other single byte. |
| 317 | */ |
| 318 | static int intckGetToken(const char *z){ |
| 319 | char c = z[0]; |
| 320 | int iRet = 1; |
| 321 | if( c=='\'' || c=='"' || c=='`' ){ |
| 322 | while( z[iRet] ){ |
| 323 | if( z[iRet]==c ){ |
| 324 | iRet++; |
| 325 | if( z[iRet]!=c ) break; |
| 326 | } |
| 327 | iRet++; |
| 328 | } |
| 329 | } |
| 330 | else if( c=='[' ){ |
| 331 | while( z[iRet] && z[iRet++]!=']' ){} |
| 332 | } |
| 333 | else if( (c>='A' && c<='Z') || (c>='a' && c<='z') ){ |
| 334 | while( (z[iRet]>='A' && z[iRet]<='Z') || (z[iRet]>='a' && z[iRet]<='z') ){ |
| 335 | iRet++; |
| 336 | } |
| 337 | } |
| 338 | else if( c==0 ){ |
| 339 | iRet = 0; |
| 340 | } |
| 341 | |
| 342 | return iRet; |
| 343 | } |
| 344 | |
| 345 | /* |
| 346 | ** Return true if argument c is an ascii whitespace character. |
| 347 | */ |
| 348 | static int intckIsSpace(char c){ |
| 349 | return (c==' ' || c=='\t' || c=='\n' || c=='\r'); |
| 350 | } |
| 351 | |
| 352 | /* |
| 353 | ** Argument z points to the text of a CREATE INDEX statement. This function |
| 354 | ** identifies the part of the text that contains either the index WHERE |
| 355 | ** clause (if iCol<0) or the iCol'th column of the index. |
| 356 | ** |
| 357 | ** If (iCol<0), the identified fragment does not include the "WHERE" keyword, |
| 358 | ** only the expression that follows it. If (iCol>=0) then the identified |
| 359 | ** fragment does not include any trailing sort-order keywords - "ASC" or |
| 360 | ** "DESC". |
| 361 | ** |
| 362 | ** If the CREATE INDEX statement does not contain the requested field or |
| 363 | ** clause, NULL is returned and (*pnByte) is set to 0. Otherwise, a pointer to |
| 364 | ** the identified fragment is returned and output parameter (*pnByte) set |
| 365 | ** to its size in bytes. |
| 366 | */ |
| 367 | static const char *intckParseCreateIndex(const char *z, int iCol, int *pnByte){ |
| 368 | int iOff = 0; |
| 369 | int iThisCol = 0; |
| 370 | int iStart = 0; |
| 371 | int nOpen = 0; |
| 372 | |
| 373 | const char *zRet = 0; |
| 374 | int nRet = 0; |
| 375 | |
| 376 | int iEndOfCol = 0; |
| 377 | |
| 378 | /* Skip forward until the first "(" token */ |
| 379 | while( z[iOff]!='(' ){ |
| 380 | iOff += intckGetToken(&z[iOff]); |
| 381 | if( z[iOff]=='\0' ) return 0; |
| 382 | } |
| 383 | assert( z[iOff]=='(' ); |
| 384 | |
| 385 | nOpen = 1; |
| 386 | iOff++; |
| 387 | iStart = iOff; |
| 388 | while( z[iOff] ){ |
| 389 | const char *zToken = &z[iOff]; |
| 390 | int nToken = 0; |
| 391 | |
| 392 | /* Check if this is the end of the current column - either a "," or ")" |
| 393 | ** when nOpen==1. */ |
| 394 | if( nOpen==1 ){ |
| 395 | if( z[iOff]==',' || z[iOff]==')' ){ |
| 396 | if( iCol==iThisCol ){ |
| 397 | int iEnd = iEndOfCol ? iEndOfCol : iOff; |
| 398 | nRet = (iEnd - iStart); |
| 399 | zRet = &z[iStart]; |
| 400 | break; |
| 401 | } |
| 402 | iStart = iOff+1; |
| 403 | while( intckIsSpace(z[iStart]) ) iStart++; |
| 404 | iThisCol++; |
| 405 | } |
| 406 | if( z[iOff]==')' ) break; |
| 407 | } |
| 408 | if( z[iOff]=='(' ) nOpen++; |
| 409 | if( z[iOff]==')' ) nOpen--; |
| 410 | nToken = intckGetToken(zToken); |
| 411 | |
| 412 | if( (nToken==3 && 0==sqlite3_strnicmp(zToken, "ASC", nToken)) |
| 413 | || (nToken==4 && 0==sqlite3_strnicmp(zToken, "DESC", nToken)) |
| 414 | ){ |
| 415 | iEndOfCol = iOff; |
| 416 | }else if( 0==intckIsSpace(zToken[0]) ){ |
| 417 | iEndOfCol = 0; |
| 418 | } |
| 419 | |
| 420 | iOff += nToken; |
| 421 | } |
| 422 | |
| 423 | /* iStart is now the byte offset of 1 byte passed the final ')' in the |
| 424 | ** CREATE INDEX statement. Try to find a WHERE clause to return. */ |
| 425 | while( zRet==0 && z[iOff] ){ |
| 426 | int n = intckGetToken(&z[iOff]); |
| 427 | if( n==5 && 0==sqlite3_strnicmp(&z[iOff], "where", 5) ){ |
| 428 | zRet = &z[iOff+5]; |
| 429 | nRet = (int)strlen(zRet); |
| 430 | } |
| 431 | iOff += n; |
| 432 | } |
| 433 | |
| 434 | /* Trim any whitespace from the start and end of the returned string. */ |
| 435 | if( zRet ){ |
| 436 | while( intckIsSpace(zRet[0]) ){ |
| 437 | nRet--; |
| 438 | zRet++; |
| 439 | } |
| 440 | while( nRet>0 && intckIsSpace(zRet[nRet-1]) ) nRet--; |
| 441 | } |
| 442 | |
| 443 | *pnByte = nRet; |
| 444 | return zRet; |
| 445 | } |
| 446 | |
| 447 | /* |
| 448 | ** User-defined SQL function wrapper for intckParseCreateIndex(): |
| 449 | ** |
| 450 | ** SELECT parse_create_index(<sql>, <icol>); |
| 451 | */ |
| 452 | static void intckParseCreateIndexFunc( |
| 453 | sqlite3_context *pCtx, |
| 454 | int nVal, |
| 455 | sqlite3_value **apVal |
| 456 | ){ |
| 457 | const char *zSql = (const char*)sqlite3_value_text(apVal[0]); |
| 458 | int idx = sqlite3_value_int(apVal[1]); |
| 459 | const char *zRes = 0; |
| 460 | int nRes = 0; |
| 461 | |
| 462 | assert( nVal==2 ); |
| 463 | if( zSql ){ |
| 464 | zRes = intckParseCreateIndex(zSql, idx, &nRes); |
| 465 | } |
| 466 | sqlite3_result_text(pCtx, zRes, nRes, SQLITE_TRANSIENT); |
| 467 | } |
| 468 | |
| 469 | /* |
| 470 | ** Return true if sqlite3_intck.db has automatic indexes enabled, false |
| 471 | ** otherwise. |
| 472 | */ |
| 473 | static int intckGetAutoIndex(sqlite3_intck *p){ |
| 474 | int bRet = 0; |
| 475 | sqlite3_stmt *pStmt = 0; |
| 476 | pStmt = intckPrepare(p, "PRAGMA automatic_index"); |
| 477 | if( SQLITE_ROW==intckStep(p, pStmt) ){ |
| 478 | bRet = sqlite3_column_int(pStmt, 0); |
| 479 | } |
| 480 | intckFinalize(p, pStmt); |
| 481 | return bRet; |
| 482 | } |
| 483 | |
| 484 | /* |
| 485 | ** Return true if zObj is an index, or false otherwise. |
| 486 | */ |
| 487 | static int intckIsIndex(sqlite3_intck *p, const char *zObj){ |
| 488 | int bRet = 0; |
| 489 | sqlite3_stmt *pStmt = 0; |
| 490 | pStmt = intckPrepareFmt(p, |
| 491 | "SELECT 1 FROM %Q.sqlite_schema WHERE name=%Q AND type='index'", |
| 492 | p->zDb, zObj |
| 493 | ); |
| 494 | if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ |
| 495 | bRet = 1; |
| 496 | } |
| 497 | intckFinalize(p, pStmt); |
| 498 | return bRet; |
| 499 | } |
| 500 | |
| 501 | /* |
| 502 | ** Return a pointer to a nul-terminated buffer containing the SQL statement |
| 503 | ** used to check database object zObj (a table or index) for corruption. |
| 504 | ** If parameter zPrev is not NULL, then it must be a string containing the |
| 505 | ** vector key required to restart the check where it left off last time. |
| 506 | ** If pnKeyVal is not NULL, then (*pnKeyVal) is set to the number of |
| 507 | ** columns in the vector key value for the specified object. |
| 508 | ** |
| 509 | ** This function uses the sqlite3_intck error code convention. |
| 510 | */ |
| 511 | static char *intckCheckObjectSql( |
| 512 | sqlite3_intck *p, /* Integrity check object */ |
| 513 | const char *zObj, /* Object (table or index) to scan */ |
| 514 | const char *zPrev, /* Restart key vector, if any */ |
| 515 | int *pnKeyVal /* OUT: Number of key-values for this scan */ |
| 516 | ){ |
| 517 | char *zRet = 0; |
| 518 | sqlite3_stmt *pStmt = 0; |
| 519 | int bAutoIndex = 0; |
| 520 | int bIsIndex = 0; |
| 521 | |
| 522 | const char *zCommon = |
| 523 | /* Relation without_rowid also contains just one row. Column "b" is |
| 524 | ** set to true if the table being examined is a WITHOUT ROWID table, |
| 525 | ** or false otherwise. */ |
| 526 | ", without_rowid(b) AS (" |
| 527 | " SELECT EXISTS (" |
| 528 | " SELECT 1 FROM tabname, pragma_index_list(tab, db) AS l" |
| 529 | " WHERE origin='pk' " |
| 530 | " AND NOT EXISTS (SELECT 1 FROM sqlite_schema WHERE name=l.name)" |
| 531 | " )" |
| 532 | ")" |
| 533 | "" |
| 534 | /* Table idx_cols contains 1 row for each column in each index on the |
| 535 | ** table being checked. Columns are: |
| 536 | ** |
| 537 | ** idx_name: Name of the index. |
| 538 | ** idx_ispk: True if this index is the PK of a WITHOUT ROWID table. |
| 539 | ** col_name: Name of indexed column, or NULL for index on expression. |
| 540 | ** col_expr: Indexed expression, including COLLATE clause. |
| 541 | ** col_alias: Alias used for column in 'intck_wrapper' table. |
| 542 | */ |
| 543 | ", idx_cols(idx_name, idx_ispk, col_name, col_expr, col_alias) AS (" |
| 544 | " SELECT l.name, (l.origin=='pk' AND w.b), i.name, COALESCE((" |
| 545 | " SELECT parse_create_index(sql, i.seqno) FROM " |
| 546 | " sqlite_schema WHERE name = l.name" |
| 547 | " ), format('\"%w\"', i.name) || ' COLLATE ' || quote(i.coll))," |
| 548 | " 'c' || row_number() OVER ()" |
| 549 | " FROM " |
| 550 | " tabname t," |
| 551 | " without_rowid w," |
| 552 | " pragma_index_list(t.tab, t.db) l," |
| 553 | " pragma_index_xinfo(l.name) i" |
| 554 | " WHERE i.key" |
| 555 | " UNION ALL" |
| 556 | " SELECT '', 1, '_rowid_', '_rowid_', 'r1' FROM without_rowid WHERE b=0" |
| 557 | ")" |
| 558 | "" |
| 559 | "" |
| 560 | /* |
| 561 | ** For a PK declared as "PRIMARY KEY(a, b) ... WITHOUT ROWID", where |
| 562 | ** the intck_wrapper aliases of "a" and "b" are "c1" and "c2": |
| 563 | ** |
| 564 | ** o_pk: "o.c1, o.c2" |
| 565 | ** i_pk: "i.'a', i.'b'" |
| 566 | ** ... |
| 567 | ** n_pk: 2 |
| 568 | */ |
| 569 | ", tabpk(db, tab, idx, o_pk, i_pk, q_pk, eq_pk, ps_pk, pk_pk, n_pk) AS (" |
| 570 | " WITH pkfields(f, a) AS (" |
| 571 | " SELECT i.col_name, i.col_alias FROM idx_cols i WHERE i.idx_ispk" |
| 572 | " )" |
| 573 | " SELECT t.db, t.tab, t.idx, " |
| 574 | " group_concat(a, ', '), " |
| 575 | " group_concat('i.'||quote(f), ', '), " |
| 576 | " group_concat('quote(o.'||a||')', ' || '','' || '), " |
| 577 | " format('(%s)==(%s)'," |
| 578 | " group_concat('o.'||a, ', '), " |
| 579 | " group_concat(format('\"%w\"', f), ', ')" |
| 580 | " )," |
| 581 | " group_concat('%s', ',')," |
| 582 | " group_concat('quote('||a||')', ', '), " |
| 583 | " count(*)" |
| 584 | " FROM tabname t, pkfields" |
| 585 | ")" |
| 586 | "" |
| 587 | ", idx(name, match_expr, partial, partial_alias, idx_ps, idx_idx) AS (" |
| 588 | " SELECT idx_name," |
| 589 | " format('(%s,%s) IS (%s,%s)', " |
| 590 | " group_concat(i.col_expr, ', '), i_pk," |
| 591 | " group_concat('o.'||i.col_alias, ', '), o_pk" |
| 592 | " ), " |
| 593 | " parse_create_index(" |
| 594 | " (SELECT sql FROM sqlite_schema WHERE name=idx_name), -1" |
| 595 | " )," |
| 596 | " 'cond' || row_number() OVER ()" |
| 597 | " , group_concat('%s', ',')" |
| 598 | " , group_concat('quote('||i.col_alias||')', ', ')" |
| 599 | " FROM tabpk t, " |
| 600 | " without_rowid w," |
| 601 | " idx_cols i" |
| 602 | " WHERE i.idx_ispk==0 " |
| 603 | " GROUP BY idx_name" |
| 604 | ")" |
| 605 | "" |
| 606 | ", wrapper_with(s) AS (" |
| 607 | " SELECT 'intck_wrapper AS (\n SELECT\n ' || (" |
| 608 | " WITH f(a, b) AS (" |
| 609 | " SELECT col_expr, col_alias FROM idx_cols" |
| 610 | " UNION ALL " |
| 611 | " SELECT partial, partial_alias FROM idx WHERE partial IS NOT NULL" |
| 612 | " )" |
| 613 | " SELECT group_concat(format('%s AS %s', a, b), ',\n ') FROM f" |
| 614 | " )" |
| 615 | " || format('\n FROM %Q.%Q ', t.db, t.tab)" |
| 616 | /* If the object being checked is a table, append "NOT INDEXED". |
| 617 | ** Otherwise, append "INDEXED BY <index>", and then, if the index |
| 618 | ** is a partial index " WHERE <condition>". */ |
| 619 | " || CASE WHEN t.idx IS NULL THEN " |
| 620 | " 'NOT INDEXED'" |
| 621 | " ELSE" |
| 622 | " format('INDEXED BY %Q%s', t.idx, ' WHERE '||i.partial)" |
| 623 | " END" |
| 624 | " || '\n)'" |
| 625 | " FROM tabname t LEFT JOIN idx i ON (i.name=t.idx)" |
| 626 | ")" |
| 627 | "" |
| 628 | ; |
| 629 | |
| 630 | bAutoIndex = intckGetAutoIndex(p); |
| 631 | if( bAutoIndex ) intckExec(p, "PRAGMA automatic_index = 0"); |
| 632 | |
| 633 | bIsIndex = intckIsIndex(p, zObj); |
| 634 | if( bIsIndex ){ |
| 635 | pStmt = intckPrepareFmt(p, |
| 636 | /* Table idxname contains a single row. The first column, "db", contains |
| 637 | ** the name of the db containing the table (e.g. "main") and the second, |
| 638 | ** "tab", the name of the table itself. */ |
| 639 | "WITH tabname(db, tab, idx) AS (" |
| 640 | " SELECT %Q, (SELECT tbl_name FROM %Q.sqlite_schema WHERE name=%Q), %Q " |
| 641 | ")" |
| 642 | "" |
| 643 | ", whereclause(w_c) AS (%s)" |
| 644 | "" |
| 645 | "%s" /* zCommon */ |
| 646 | "" |
| 647 | ", case_statement(c) AS (" |
| 648 | " SELECT " |
| 649 | " 'CASE WHEN (' || group_concat(col_alias, ', ') || ', 1) IS (\n' " |
| 650 | " || ' SELECT ' || group_concat(col_expr, ', ') || ', 1 FROM '" |
| 651 | " || format('%%Q.%%Q NOT INDEXED WHERE %%s\n', t.db, t.tab, p.eq_pk)" |
| 652 | " || ' )\n THEN NULL\n '" |
| 653 | " || 'ELSE format(''surplus entry ('" |
| 654 | " || group_concat('%%s', ',') || ',' || p.ps_pk" |
| 655 | " || ') in index ' || t.idx || ''', ' " |
| 656 | " || group_concat('quote('||i.col_alias||')', ', ') || ', ' || p.pk_pk" |
| 657 | " || ')'" |
| 658 | " || '\n END AS error_message'" |
| 659 | " FROM tabname t, tabpk p, idx_cols i WHERE i.idx_name=t.idx" |
| 660 | ")" |
| 661 | "" |
| 662 | ", thiskey(k, n) AS (" |
| 663 | " SELECT group_concat(i.col_alias, ', ') || ', ' || p.o_pk, " |
| 664 | " count(*) + p.n_pk " |
| 665 | " FROM tabpk p, idx_cols i WHERE i.idx_name=p.idx" |
| 666 | ")" |
| 667 | "" |
| 668 | ", main_select(m, n) AS (" |
| 669 | " SELECT format(" |
| 670 | " 'WITH %%s\n' ||" |
| 671 | " ', idx_checker AS (\n' ||" |
| 672 | " ' SELECT %%s,\n' ||" |
| 673 | " ' %%s\n' || " |
| 674 | " ' FROM intck_wrapper AS o\n' ||" |
| 675 | " ')\n'," |
| 676 | " ww.s, c, t.k" |
| 677 | " ), t.n" |
| 678 | " FROM case_statement, wrapper_with ww, thiskey t" |
| 679 | ")" |
| 680 | |
| 681 | "SELECT m || " |
| 682 | " group_concat('SELECT * FROM idx_checker ' || w_c, ' UNION ALL '), n" |
| 683 | " FROM " |
| 684 | "main_select, whereclause " |
| 685 | , p->zDb, p->zDb, zObj, zObj |
| 686 | , zPrev ? zPrev : "VALUES('')", zCommon |
| 687 | ); |
| 688 | }else{ |
| 689 | pStmt = intckPrepareFmt(p, |
| 690 | /* Table tabname contains a single row. The first column, "db", contains |
| 691 | ** the name of the db containing the table (e.g. "main") and the second, |
| 692 | ** "tab", the name of the table itself. */ |
| 693 | "WITH tabname(db, tab, idx, prev) AS (SELECT %Q, %Q, NULL, %Q)" |
| 694 | "" |
| 695 | "%s" /* zCommon */ |
| 696 | |
| 697 | /* expr(e) contains one row for each index on table zObj. Value e |
| 698 | ** is set to an expression that evaluates to NULL if the required |
| 699 | ** entry is present in the index, or an error message otherwise. */ |
| 700 | ", expr(e, p) AS (" |
| 701 | " SELECT format('CASE WHEN EXISTS \n" |
| 702 | " (SELECT 1 FROM %%Q.%%Q AS i INDEXED BY %%Q WHERE %%s%%s)\n" |
| 703 | " THEN NULL\n" |
| 704 | " ELSE format(''entry (%%s,%%s) missing from index %%s'', %%s, %%s)\n" |
| 705 | " END\n'" |
| 706 | " , t.db, t.tab, i.name, i.match_expr, ' AND (' || partial || ')'," |
| 707 | " i.idx_ps, t.ps_pk, i.name, i.idx_idx, t.pk_pk)," |
| 708 | " CASE WHEN partial IS NULL THEN NULL ELSE i.partial_alias END" |
| 709 | " FROM tabpk t, idx i" |
| 710 | ")" |
| 711 | |
| 712 | ", numbered(ii, cond, e) AS (" |
| 713 | " SELECT 0, 'n.ii=0', 'NULL'" |
| 714 | " UNION ALL " |
| 715 | " SELECT row_number() OVER ()," |
| 716 | " '(n.ii='||row_number() OVER ()||COALESCE(' AND '||p||')', ')'), e" |
| 717 | " FROM expr" |
| 718 | ")" |
| 719 | |
| 720 | ", counter_with(w) AS (" |
| 721 | " SELECT 'WITH intck_counter(ii) AS (\n ' || " |
| 722 | " group_concat('SELECT '||ii, ' UNION ALL\n ') " |
| 723 | " || '\n)' FROM numbered" |
| 724 | ")" |
| 725 | "" |
| 726 | ", case_statement(c) AS (" |
| 727 | " SELECT 'CASE ' || " |
| 728 | " group_concat(format('\n WHEN %%s THEN (%%s)', cond, e), '') ||" |
| 729 | " '\nEND AS error_message'" |
| 730 | " FROM numbered" |
| 731 | ")" |
| 732 | "" |
| 733 | |
| 734 | /* This table contains a single row consisting of a single value - |
| 735 | ** the text of an SQL expression that may be used by the main SQL |
| 736 | ** statement to output an SQL literal that can be used to resume |
| 737 | ** the scan if it is suspended. e.g. for a rowid table, an expression |
| 738 | ** like: |
| 739 | ** |
| 740 | ** format('(%d,%d)', _rowid_, n.ii) |
| 741 | */ |
| 742 | ", thiskey(k, n) AS (" |
| 743 | " SELECT o_pk || ', ii', n_pk+1 FROM tabpk" |
| 744 | ")" |
| 745 | "" |
| 746 | ", whereclause(w_c) AS (" |
| 747 | " SELECT CASE WHEN prev!='' THEN " |
| 748 | " '\nWHERE (' || o_pk ||', n.ii) > ' || prev" |
| 749 | " ELSE ''" |
| 750 | " END" |
| 751 | " FROM tabpk, tabname" |
| 752 | ")" |
| 753 | "" |
| 754 | ", main_select(m, n) AS (" |
| 755 | " SELECT format(" |
| 756 | " '%%s, %%s\nSELECT %%s,\n%%s\nFROM intck_wrapper AS o" |
| 757 | ", intck_counter AS n%%s\nORDER BY %%s', " |
| 758 | " w, ww.s, c, thiskey.k, whereclause.w_c, t.o_pk" |
| 759 | " ), thiskey.n" |
| 760 | " FROM case_statement, tabpk t, counter_with, " |
| 761 | " wrapper_with ww, thiskey, whereclause" |
| 762 | ")" |
| 763 | |
| 764 | "SELECT m, n FROM main_select", |
| 765 | p->zDb, zObj, zPrev, zCommon |
| 766 | ); |
| 767 | } |
| 768 | |
| 769 | while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){ |
| 770 | zRet = intckMprintf(p, "%s", (const char*)sqlite3_column_text(pStmt, 0)); |
| 771 | if( pnKeyVal ){ |
| 772 | *pnKeyVal = sqlite3_column_int(pStmt, 1); |
| 773 | } |
| 774 | } |
| 775 | intckFinalize(p, pStmt); |
| 776 | |
| 777 | if( bAutoIndex ) intckExec(p, "PRAGMA automatic_index = 1"); |
| 778 | return zRet; |
| 779 | } |
| 780 | |
| 781 | /* |
| 782 | ** Register or unregister special SQL functions implemented by intck. |
| 783 | ** |
| 784 | ** Normally the custom SQL functions used by intck are only available |
| 785 | ** in between sqlite3_intck_open() and sqlite3_intck_close(). However, |
| 786 | ** for testing and debugging, it is sometimes useful to make those |
| 787 | ** functions available generally. This routine provides as a separate |
| 788 | ** interface in order to provide that capability. |
| 789 | */ |
| 790 | int sqlite3_intck_register(sqlite3 *db, int bCreate){ |
| 791 | int rc; |
| 792 | rc = sqlite3_create_function(db, "parse_create_index", |
| 793 | 2, SQLITE_UTF8, 0, bCreate ? intckParseCreateIndexFunc : 0, 0, 0 |
| 794 | ); |
| 795 | return rc; |
| 796 | } |
| 797 | |
| 798 | /* |
| 799 | ** Open a new integrity-check object. |
| 800 | */ |
| 801 | int sqlite3_intck_open( |
| 802 | sqlite3 *db, /* Database handle to operate on */ |
| 803 | const char *zDbArg, /* "main", "temp" etc. */ |
| 804 | sqlite3_intck **ppOut /* OUT: New integrity-check handle */ |
| 805 | ){ |
| 806 | sqlite3_intck *pNew = 0; |
| 807 | int rc = SQLITE_OK; |
| 808 | const char *zDb = zDbArg ? zDbArg : "main"; |
| 809 | int nDb = (int)strlen(zDb); |
| 810 | |
| 811 | pNew = (sqlite3_intck*)sqlite3_malloc(sizeof(*pNew) + nDb + 1); |
| 812 | if( pNew==0 ){ |
| 813 | rc = SQLITE_NOMEM; |
| 814 | }else{ |
| 815 | memset(pNew, 0, sizeof(*pNew)); |
| 816 | pNew->db = db; |
| 817 | pNew->zDb = (const char*)&pNew[1]; |
| 818 | memcpy(&pNew[1], zDb, nDb+1); |
| 819 | rc = sqlite3_intck_register(db, 1); |
| 820 | if( rc!=SQLITE_OK ){ |
| 821 | sqlite3_intck_close(pNew); |
| 822 | pNew = 0; |
| 823 | } |
| 824 | } |
| 825 | |
| 826 | *ppOut = pNew; |
| 827 | return rc; |
| 828 | } |
| 829 | |
| 830 | /* |
| 831 | ** Free the integrity-check object. |
| 832 | */ |
| 833 | void sqlite3_intck_close(sqlite3_intck *p){ |
| 834 | if( p ){ |
| 835 | sqlite3_finalize(p->pCheck); |
| 836 | sqlite3_intck_register(p->db, 0); |
| 837 | sqlite3_free(p->zObj); |
| 838 | sqlite3_free(p->zKey); |
| 839 | sqlite3_free(p->zTestSql); |
| 840 | sqlite3_free(p->zErr); |
| 841 | sqlite3_free(p->zMessage); |
| 842 | sqlite3_free(p); |
| 843 | } |
| 844 | } |
| 845 | |
| 846 | /* |
| 847 | ** Step the integrity-check object. |
| 848 | */ |
| 849 | int sqlite3_intck_step(sqlite3_intck *p){ |
| 850 | if( p->rc==SQLITE_OK ){ |
| 851 | |
| 852 | if( p->zMessage ){ |
| 853 | sqlite3_free(p->zMessage); |
| 854 | p->zMessage = 0; |
| 855 | } |
| 856 | |
| 857 | if( p->bCorruptSchema ){ |
| 858 | p->rc = SQLITE_DONE; |
| 859 | }else |
| 860 | if( p->pCheck==0 ){ |
| 861 | intckFindObject(p); |
| 862 | if( p->rc==SQLITE_OK ){ |
| 863 | if( p->zObj ){ |
| 864 | char *zSql = 0; |
| 865 | zSql = intckCheckObjectSql(p, p->zObj, p->zKey, &p->nKeyVal); |
| 866 | p->pCheck = intckPrepare(p, zSql); |
| 867 | sqlite3_free(zSql); |
| 868 | sqlite3_free(p->zKey); |
| 869 | p->zKey = 0; |
| 870 | }else{ |
| 871 | p->rc = SQLITE_DONE; |
| 872 | } |
| 873 | }else if( p->rc==SQLITE_CORRUPT ){ |
| 874 | p->rc = SQLITE_OK; |
| 875 | p->zMessage = intckMprintf(p, "%s", |
| 876 | "corruption found while reading database schema" |
| 877 | ); |
| 878 | p->bCorruptSchema = 1; |
| 879 | } |
| 880 | } |
| 881 | |
| 882 | if( p->pCheck ){ |
| 883 | assert( p->rc==SQLITE_OK ); |
| 884 | if( sqlite3_step(p->pCheck)==SQLITE_ROW ){ |
| 885 | /* Normal case, do nothing. */ |
| 886 | }else{ |
| 887 | intckFinalize(p, p->pCheck); |
| 888 | p->pCheck = 0; |
| 889 | p->nKeyVal = 0; |
| 890 | if( p->rc==SQLITE_CORRUPT ){ |
| 891 | p->rc = SQLITE_OK; |
| 892 | p->zMessage = intckMprintf(p, |
| 893 | "corruption found while scanning database object %s", p->zObj |
| 894 | ); |
| 895 | } |
| 896 | } |
| 897 | } |
| 898 | } |
| 899 | |
| 900 | return p->rc; |
| 901 | } |
| 902 | |
| 903 | /* |
| 904 | ** Return a message describing the corruption encountered by the most recent |
| 905 | ** call to sqlite3_intck_step(), or NULL if no corruption was encountered. |
| 906 | */ |
| 907 | const char *sqlite3_intck_message(sqlite3_intck *p){ |
| 908 | assert( p->pCheck==0 || p->zMessage==0 ); |
| 909 | if( p->zMessage ){ |
| 910 | return p->zMessage; |
| 911 | } |
| 912 | if( p->pCheck ){ |
| 913 | return (const char*)sqlite3_column_text(p->pCheck, 0); |
| 914 | } |
| 915 | return 0; |
| 916 | } |
| 917 | |
| 918 | /* |
| 919 | ** Return the error code and message. |
| 920 | */ |
| 921 | int sqlite3_intck_error(sqlite3_intck *p, const char **pzErr){ |
| 922 | if( pzErr ) *pzErr = p->zErr; |
| 923 | return (p->rc==SQLITE_DONE ? SQLITE_OK : p->rc); |
| 924 | } |
| 925 | |
| 926 | /* |
| 927 | ** Close any read transaction the integrity-check object is holding open |
| 928 | ** on the database. |
| 929 | */ |
| 930 | int sqlite3_intck_unlock(sqlite3_intck *p){ |
| 931 | if( p->rc==SQLITE_OK && p->pCheck ){ |
| 932 | assert( p->zKey==0 && p->nKeyVal>0 ); |
| 933 | intckSaveKey(p); |
| 934 | intckFinalize(p, p->pCheck); |
| 935 | p->pCheck = 0; |
| 936 | } |
| 937 | return p->rc; |
| 938 | } |
| 939 | |
| 940 | /* |
| 941 | ** Return the SQL statement used to check object zObj. Or, if zObj is |
| 942 | ** NULL, the current SQL statement. |
| 943 | */ |
| 944 | const char *sqlite3_intck_test_sql(sqlite3_intck *p, const char *zObj){ |
| 945 | sqlite3_free(p->zTestSql); |
| 946 | p->zTestSql = 0; |
| 947 | if( zObj ){ |
| 948 | p->zTestSql = intckCheckObjectSql(p, zObj, 0, 0); |
| 949 | }else if( p->zObj ){ |
| 950 | p->zTestSql = intckCheckObjectSql(p, p->zObj, p->zKey, 0); |
| 951 | } |
| 952 | return p->zTestSql; |
| 953 | } |