Debian Codegraph @

ext/intck/sqlite3intck.c

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