Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/sqlite/blob/master/ext/misc/closure.c # sqlite [Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `master` Branches Tags History `sqlite / ext / misc / closure.c` 997 lines ยท 31353 bytes Raw Blame History 1 /* 2 ** 2013-04-16 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 ** WARNING: Experimental and obsolete. Demonstration and testing use only. 14 ** 15 ** This virtual table was created prior to the addition of support for 16 ** common table expressions in SQLite. Common table expressions are a 17 ** better and more portable solution to any problem that this virtual 18 ** table solves. Common table expressions where added to SQLite in 19 ** version 3.8.3 (2014-02-02), less than 10 months after this extension 20 ** was created. Hence this extension was only useful for a small 21 ** 10-month window of time in 2013 and early 2014. 22 ** 23 ** The continued use of this extension in any real-world application should 24 ** be considered a bug in that application. 25 ** 26 ** Given its experimental and testing-only status, the code here is 27 ** deactivated unless compiled with -DSQLITE_TEST=1 28 ** 29 ** DEMONSTRATION AND TESTING USE ONLY. 30 ** 31 ************************************************************************* 32 ** 33 ** This file contains code for a virtual table that finds the transitive 34 ** closure of a parent/child relationship in a real table. The virtual 35 ** table is called "transitive_closure". 36 ** 37 ** A transitive_closure virtual table is created like this: 38 ** 39 ** CREATE VIRTUAL TABLE x USING transitive_closure( 40 ** tablename=, -- T 41 ** idcolumn=, -- X 42 ** parentcolumn= -- P 43 ** ); 44 ** 45 ** When it is created, the new transitive_closure table may be supplied 46 ** with default values for the name of a table T and columns T.X and T.P. 47 ** The T.X and T.P columns must contain integers. The ideal case is for 48 ** T.X to be the INTEGER PRIMARY KEY. The T.P column should reference 49 ** the T.X column. The row referenced by T.P is the parent of the current row. 50 ** 51 ** The tablename, idcolumn, and parentcolumn supplied by the CREATE VIRTUAL 52 ** TABLE statement may be overridden in individual queries by including 53 ** terms like tablename='newtable', idcolumn='id2', or 54 ** parentcolumn='parent3' in the WHERE clause of the query. 55 ** 56 ** For efficiency, it is essential that there be an index on the P column: 57 ** 58 ** CREATE Tidx1 ON T(P) 59 ** 60 ** Suppose a specific instance of the closure table is as follows: 61 ** 62 ** CREATE VIRTUAL TABLE ct1 USING transitive_closure( 63 ** tablename='group', 64 ** idcolumn='groupId', 65 ** parentcolumn='parentId' 66 ** ); 67 ** 68 ** Such an instance of the transitive_closure virtual table would be 69 ** appropriate for walking a tree defined using a table like this, for example: 70 ** 71 ** CREATE TABLE group( 72 ** groupId INTEGER PRIMARY KEY, 73 ** parentId INTEGER REFERENCES group 74 ** ); 75 ** CREATE INDEX group_idx1 ON group(parentId); 76 ** 77 ** The group table above would presumably have other application-specific 78 ** fields. The key point here is that rows of the group table form a 79 ** tree. The purpose of the ct1 virtual table is to easily extract 80 ** branches of that tree. 81 ** 82 ** Once it has been created, the ct1 virtual table can be queried 83 ** as follows: 84 ** 85 ** SELECT * FROM element 86 ** WHERE element.groupId IN (SELECT id FROM ct1 WHERE root=?1); 87 ** 88 ** The above query will return all elements that are part of group ?1 89 ** or children of group ?1 or grand-children of ?1 and so forth for all 90 ** descendents of group ?1. The same query can be formulated as a join: 91 ** 92 ** SELECT element.* FROM element, ct1 93 ** WHERE element.groupid=ct1.id 94 ** AND ct1.root=?1; 95 ** 96 ** The depth of the transitive_closure (the number of generations of 97 ** parent/child relations to follow) can be limited by setting "depth" 98 ** column in the WHERE clause. So, for example, the following query 99 ** finds only children and grandchildren but no further descendents: 100 ** 101 ** SELECT element.* FROM element, ct1 102 ** WHERE element.groupid=ct1.id 103 ** AND ct1.root=?1 104 ** AND ct1.depth<=2; 105 ** 106 ** The "ct1.depth<=2" term could be a strict equality "ct1.depth=2" in 107 ** order to find only the grandchildren of ?1, not ?1 itself or the 108 ** children of ?1. 109 ** 110 ** The root=?1 term must be supplied in WHERE clause or else the query 111 ** of the ct1 virtual table will return an empty set. The tablename, 112 ** idcolumn, and parentcolumn attributes can be overridden in the WHERE 113 ** clause if desired. So, for example, the ct1 table could be repurposed 114 ** to find ancestors rather than descendents by inverting the roles of 115 ** the idcolumn and parentcolumn: 116 ** 117 ** SELECT element.* FROM element, ct1 118 ** WHERE element.groupid=ct1.id 119 ** AND ct1.root=?1 120 ** AND ct1.idcolumn='parentId' 121 ** AND ct1.parentcolumn='groupId'; 122 ** 123 ** Multiple calls to ct1 could be combined. For example, the following 124 ** query finds all elements that "cousins" of groupId ?1. That is to say 125 ** elements where the groupId is a grandchild of the grandparent of ?1. 126 ** (This definition of "cousins" also includes siblings and self.) 127 ** 128 ** SELECT element.* FROM element, ct1 129 ** WHERE element.groupId=ct1.id 130 ** AND ct1.depth=2 131 ** AND ct1.root IN (SELECT id FROM ct1 132 ** WHERE root=?1 133 ** AND depth=2 134 ** AND idcolumn='parentId' 135 ** AND parentcolumn='groupId'); 136 ** 137 ** In our example, the group.groupId column is unique and thus the 138 ** subquery will return exactly one row. For that reason, the IN 139 ** operator could be replaced by "=" to get the same result. But 140 ** in the general case where the idcolumn is not unique, an IN operator 141 ** would be required for this kind of query. 142 ** 143 ** Note that because the tablename, idcolumn, and parentcolumn can 144 ** all be specified in the query, it is possible for an application 145 ** to define a single transitive_closure virtual table for use on lots 146 ** of different hierarchy tables. One might say: 147 ** 148 ** CREATE VIRTUAL TABLE temp.closure USING transitive_closure; 149 ** 150 ** As each database connection is being opened. Then the application 151 ** would always have a "closure" virtual table handy to use for querying. 152 ** 153 ** SELECT element.* FROM element, closure 154 ** WHERE element.groupid=ct1.id 155 ** AND closure.root=?1 156 ** AND closure.tablename='group' 157 ** AND closure.idname='groupId' 158 ** AND closure.parentname='parentId'; 159 ** 160 ** See the documentation at http://sqlite.org/loadext.html for information 161 ** on how to compile and use loadable extensions such as this one. 162 */ 163 #include "sqlite3ext.h" 164 SQLITE_EXTENSION_INIT1 165 #include 166 #include 167 #include 168 #include 169 #include 170 171 #ifndef SQLITE_OMIT_VIRTUALTABLE 172 173 /* 174 ** Forward declaration of objects used by this implementation 175 */ 176 typedef struct closure_vtab closure_vtab; 177 typedef struct closure_cursor closure_cursor; 178 typedef struct closure_queue closure_queue; 179 typedef struct closure_avl closure_avl; 180 181 /***************************************************************************** 182 ** AVL Tree implementation 183 */ 184 /* 185 ** Objects that want to be members of the AVL tree should embedded an 186 ** instance of this structure. 187 */ 188 struct closure_avl { 189 sqlite3_int64 id; /* Id of this entry in the table */ 190 sqlite3_int64 iGeneration; /* Which generation is this entry part of */ 191 closure_avl *pList; /* A linked list of nodes */ 192 closure_avl *pBefore; /* Other elements less than id */ 193 closure_avl *pAfter; /* Other elements greater than id */ 194 closure_avl *pUp; /* Parent element */ 195 short int height; /* Height of this node. Leaf==1 */ 196 short int imbalance; /* Height difference between pBefore and pAfter */ 197 }; 198 199 /* Recompute the closure_avl.height and closure_avl.imbalance fields for p. 200 ** Assume that the children of p have correct heights. 201 */ 202 static void closureAvlRecomputeHeight(closure_avl *p){ 203 short int hBefore = p->pBefore ? p->pBefore->height : 0; 204 short int hAfter = p->pAfter ? p->pAfter->height : 0; 205 p->imbalance = hBefore - hAfter; /* -: pAfter higher. +: pBefore higher */ 206 p->height = (hBefore>hAfter ? hBefore : hAfter)+1; 207 } 208 209 /* 210 ** P B 211 ** / \ / \ 212 ** B Z ==> X P 213 ** / \ / \ 214 ** X Y Y Z 215 ** 216 */ 217 static closure_avl *closureAvlRotateBefore(closure_avl *pP){ 218 closure_avl *pB = pP->pBefore; 219 closure_avl *pY = pB->pAfter; 220 pB->pUp = pP->pUp; 221 pB->pAfter = pP; 222 pP->pUp = pB; 223 pP->pBefore = pY; 224 if( pY ) pY->pUp = pP; 225 closureAvlRecomputeHeight(pP); 226 closureAvlRecomputeHeight(pB); 227 return pB; 228 } 229 230 /* 231 ** P A 232 ** / \ / \ 233 ** X A ==> P Z 234 ** / \ / \ 235 ** Y Z X Y 236 ** 237 */ 238 static closure_avl *closureAvlRotateAfter(closure_avl *pP){ 239 closure_avl *pA = pP->pAfter; 240 closure_avl *pY = pA->pBefore; 241 pA->pUp = pP->pUp; 242 pA->pBefore = pP; 243 pP->pUp = pA; 244 pP->pAfter = pY; 245 if( pY ) pY->pUp = pP; 246 closureAvlRecomputeHeight(pP); 247 closureAvlRecomputeHeight(pA); 248 return pA; 249 } 250 251 /* 252 ** Return a pointer to the pBefore or pAfter pointer in the parent 253 ** of p that points to p. Or if p is the root node, return pp. 254 */ 255 static closure_avl **closureAvlFromPtr(closure_avl *p, closure_avl **pp){ 256 closure_avl *pUp = p->pUp; 257 if( pUp==0 ) return pp; 258 if( pUp->pAfter==p ) return &pUp->pAfter; 259 return &pUp->pBefore; 260 } 261 262 /* 263 ** Rebalance all nodes starting with p and working up to the root. 264 ** Return the new root. 265 */ 266 static closure_avl *closureAvlBalance(closure_avl *p){ 267 closure_avl *pTop = p; 268 closure_avl **pp; 269 while( p ){ 270 closureAvlRecomputeHeight(p); 271 if( p->imbalance>=2 ){ 272 closure_avl *pB = p->pBefore; 273 if( pB->imbalance<0 ) p->pBefore = closureAvlRotateAfter(pB); 274 pp = closureAvlFromPtr(p,&p); 275 p = *pp = closureAvlRotateBefore(p); 276 }else if( p->imbalance<=(-2) ){ 277 closure_avl *pA = p->pAfter; 278 if( pA->imbalance>0 ) p->pAfter = closureAvlRotateBefore(pA); 279 pp = closureAvlFromPtr(p,&p); 280 p = *pp = closureAvlRotateAfter(p); 281 } 282 pTop = p; 283 p = p->pUp; 284 } 285 return pTop; 286 } 287 288 /* Search the tree rooted at p for an entry with id. Return a pointer 289 ** to the entry or return NULL. 290 */ 291 static closure_avl *closureAvlSearch(closure_avl *p, sqlite3_int64 id){ 292 while( p && id!=p->id ){ 293 p = (idid) ? p->pBefore : p->pAfter; 294 } 295 return p; 296 } 297 298 /* Find the first node (the one with the smallest key). 299 */ 300 static closure_avl *closureAvlFirst(closure_avl *p){ 301 if( p ) while( p->pBefore ) p = p->pBefore; 302 return p; 303 } 304 305 /* Return the node with the next larger key after p. 306 */ 307 closure_avl *closureAvlNext(closure_avl *p){ 308 closure_avl *pPrev = 0; 309 while( p && p->pAfter==pPrev ){ 310 pPrev = p; 311 p = p->pUp; 312 } 313 if( p && pPrev==0 ){ 314 p = closureAvlFirst(p->pAfter); 315 } 316 return p; 317 } 318 319 /* Insert a new node pNew. Return NULL on success. If the key is not 320 ** unique, then do not perform the insert but instead leave pNew unchanged 321 ** and return a pointer to an existing node with the same key. 322 */ 323 static closure_avl *closureAvlInsert( 324 closure_avl **ppHead, /* Head of the tree */ 325 closure_avl *pNew /* New node to be inserted */ 326 ){ 327 closure_avl *p = *ppHead; 328 if( p==0 ){ 329 p = pNew; 330 pNew->pUp = 0; 331 }else{ 332 while( p ){ 333 if( pNew->idid ){ 334 if( p->pBefore ){ 335 p = p->pBefore; 336 }else{ 337 p->pBefore = pNew; 338 pNew->pUp = p; 339 break; 340 } 341 }else if( pNew->id>p->id ){ 342 if( p->pAfter ){ 343 p = p->pAfter; 344 }else{ 345 p->pAfter = pNew; 346 pNew->pUp = p; 347 break; 348 } 349 }else{ 350 return p; 351 } 352 } 353 } 354 pNew->pBefore = 0; 355 pNew->pAfter = 0; 356 pNew->height = 1; 357 pNew->imbalance = 0; 358 *ppHead = closureAvlBalance(p); 359 return 0; 360 } 361 362 /* Walk the tree can call xDestroy on each node 363 */ 364 static void closureAvlDestroy(closure_avl *p, void (*xDestroy)(closure_avl*)){ 365 if( p ){ 366 closureAvlDestroy(p->pBefore, xDestroy); 367 closureAvlDestroy(p->pAfter, xDestroy); 368 xDestroy(p); 369 } 370 } 371 /* 372 ** End of the AVL Tree implementation 373 ******************************************************************************/ 374 375 /* 376 ** A closure virtual-table object 377 */ 378 struct closure_vtab { 379 sqlite3_vtab base; /* Base class - must be first */ 380 char *zDb; /* Name of database. (ex: "main") */ 381 char *zSelf; /* Name of this virtual table */ 382 char *zTableName; /* Name of table holding parent/child relation */ 383 char *zIdColumn; /* Name of ID column of zTableName */ 384 char *zParentColumn; /* Name of PARENT column in zTableName */ 385 sqlite3 *db; /* The database connection */ 386 int nCursor; /* Number of pending cursors */ 387 }; 388 389 /* A closure cursor object */ 390 struct closure_cursor { 391 sqlite3_vtab_cursor base; /* Base class - must be first */ 392 closure_vtab *pVtab; /* The virtual table this cursor belongs to */ 393 char *zTableName; /* Name of table holding parent/child relation */ 394 char *zIdColumn; /* Name of ID column of zTableName */ 395 char *zParentColumn; /* Name of PARENT column in zTableName */ 396 closure_avl *pCurrent; /* Current element of output */ 397 closure_avl *pClosure; /* The complete closure tree */ 398 }; 399 400 /* A queue of AVL nodes */ 401 struct closure_queue { 402 closure_avl *pFirst; /* Oldest node on the queue */ 403 closure_avl *pLast; /* Youngest node on the queue */ 404 }; 405 406 /* 407 ** Add a node to the end of the queue 408 */ 409 static void queuePush(closure_queue *pQueue, closure_avl *pNode){ 410 pNode->pList = 0; 411 if( pQueue->pLast ){ 412 pQueue->pLast->pList = pNode; 413 }else{ 414 pQueue->pFirst = pNode; 415 } 416 pQueue->pLast = pNode; 417 } 418 419 /* 420 ** Extract the oldest element (the front element) from the queue. 421 */ 422 static closure_avl *queuePull(closure_queue *pQueue){ 423 closure_avl *p = pQueue->pFirst; 424 if( p ){ 425 pQueue->pFirst = p->pList; 426 if( pQueue->pFirst==0 ) pQueue->pLast = 0; 427 } 428 return p; 429 } 430 431 /* 432 ** This function converts an SQL quoted string into an unquoted string 433 ** and returns a pointer to a buffer allocated using sqlite3_malloc() 434 ** containing the result. The caller should eventually free this buffer 435 ** using sqlite3_free. 436 ** 437 ** Examples: 438 ** 439 ** "abc" becomes abc 440 ** 'xyz' becomes xyz 441 ** [pqr] becomes pqr 442 ** `mno` becomes mno 443 */ 444 static char *closureDequote(const char *zIn){ 445 sqlite3_int64 nIn; /* Size of input string, in bytes */ 446 char *zOut; /* Output (dequoted) string */ 447 448 nIn = strlen(zIn); 449 zOut = sqlite3_malloc64(nIn+1); 450 if( zOut ){ 451 char q = zIn[0]; /* Quote character (if any ) */ 452 453 if( q!='[' && q!= '\'' && q!='"' && q!='`' ){ 454 memcpy(zOut, zIn, (size_t)(nIn+1)); 455 }else{ 456 int iOut = 0; /* Index of next byte to write to output */ 457 int iIn; /* Index of next byte to read from input */ 458 459 if( q=='[' ) q = ']'; 460 for(iIn=1; iInzDb); 477 sqlite3_free(p->zSelf); 478 sqlite3_free(p->zTableName); 479 sqlite3_free(p->zIdColumn); 480 sqlite3_free(p->zParentColumn); 481 memset(p, 0, sizeof(*p)); 482 sqlite3_free(p); 483 } 484 } 485 486 /* 487 ** xDisconnect/xDestroy method for the closure module. 488 */ 489 static int closureDisconnect(sqlite3_vtab *pVtab){ 490 closure_vtab *p = (closure_vtab*)pVtab; 491 assert( p->nCursor==0 ); 492 closureFree(p); 493 return SQLITE_OK; 494 } 495 496 /* 497 ** Check to see if the argument is of the form: 498 ** 499 ** KEY = VALUE 500 ** 501 ** If it is, return a pointer to the first character of VALUE. 502 ** If not, return NULL. Spaces around the = are ignored. 503 */ 504 static const char *closureValueOfKey(const char *zKey, const char *zStr){ 505 int nKey = (int)strlen(zKey); 506 int nStr = (int)strlen(zStr); 507 int i; 508 if( nStr module name ("transitive_closure") 521 ** argv[1] -> database name 522 ** argv[2] -> table name 523 ** argv[3...] -> arguments 524 */ 525 static int closureConnect( 526 sqlite3 *db, 527 void *pAux, 528 int argc, const char *const*argv, 529 sqlite3_vtab **ppVtab, 530 char **pzErr 531 ){ 532 int rc = SQLITE_OK; /* Return code */ 533 closure_vtab *pNew = 0; /* New virtual table */ 534 const char *zDb = argv[1]; 535 const char *zVal; 536 int i; 537 538 (void)pAux; 539 *ppVtab = 0; 540 pNew = sqlite3_malloc64( sizeof(*pNew) ); 541 if( pNew==0 ) return SQLITE_NOMEM; 542 rc = SQLITE_NOMEM; 543 memset(pNew, 0, sizeof(*pNew)); 544 pNew->db = db; 545 pNew->zDb = sqlite3_mprintf("%s", zDb); 546 if( pNew->zDb==0 ) goto closureConnectError; 547 pNew->zSelf = sqlite3_mprintf("%s", argv[2]); 548 if( pNew->zSelf==0 ) goto closureConnectError; 549 for(i=3; izTableName); 553 pNew->zTableName = closureDequote(zVal); 554 if( pNew->zTableName==0 ) goto closureConnectError; 555 if( sqlite3_stricmp(pNew->zTableName, argv[2])==0 ){ 556 *pzErr = sqlite3_mprintf("self-referential closure table"); 557 rc = SQLITE_ERROR; 558 goto closureConnectError; 559 } 560 continue; 561 } 562 zVal = closureValueOfKey("idcolumn", argv[i]); 563 if( zVal ){ 564 sqlite3_free(pNew->zIdColumn); 565 pNew->zIdColumn = closureDequote(zVal); 566 if( pNew->zIdColumn==0 ) goto closureConnectError; 567 continue; 568 } 569 zVal = closureValueOfKey("parentcolumn", argv[i]); 570 if( zVal ){ 571 sqlite3_free(pNew->zParentColumn); 572 pNew->zParentColumn = closureDequote(zVal); 573 if( pNew->zParentColumn==0 ) goto closureConnectError; 574 continue; 575 } 576 *pzErr = sqlite3_mprintf("unrecognized argument: [%s]\n", argv[i]); 577 closureFree(pNew); 578 *ppVtab = 0; 579 return SQLITE_ERROR; 580 } 581 rc = sqlite3_declare_vtab(db, 582 "CREATE TABLE x(id,depth,root HIDDEN,tablename HIDDEN," 583 "idcolumn HIDDEN,parentcolumn HIDDEN)" 584 ); 585 #define CLOSURE_COL_ID 0 586 #define CLOSURE_COL_DEPTH 1 587 #define CLOSURE_COL_ROOT 2 588 #define CLOSURE_COL_TABLENAME 3 589 #define CLOSURE_COL_IDCOLUMN 4 590 #define CLOSURE_COL_PARENTCOLUMN 5 591 if( rc!=SQLITE_OK ){ 592 closureFree(pNew); 593 } 594 *ppVtab = &pNew->base; 595 return rc; 596 597 closureConnectError: 598 closureFree(pNew); 599 return rc; 600 } 601 602 /* 603 ** Open a new closure cursor. 604 */ 605 static int closureOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){ 606 closure_vtab *p = (closure_vtab*)pVTab; 607 closure_cursor *pCur; 608 pCur = sqlite3_malloc64( sizeof(*pCur) ); 609 if( pCur==0 ) return SQLITE_NOMEM; 610 memset(pCur, 0, sizeof(*pCur)); 611 pCur->pVtab = p; 612 *ppCursor = &pCur->base; 613 p->nCursor++; 614 return SQLITE_OK; 615 } 616 617 /* 618 ** Wrapper around sqlite3_free 619 */ 620 static void closureMemFree(closure_avl *p){ sqlite3_free(p); } 621 622 /* 623 ** Free up all the memory allocated by a cursor. Set it rLimit to 0 624 ** to indicate that it is at EOF. 625 */ 626 static void closureClearCursor(closure_cursor *pCur){ 627 closureAvlDestroy(pCur->pClosure, closureMemFree); 628 sqlite3_free(pCur->zTableName); 629 sqlite3_free(pCur->zIdColumn); 630 sqlite3_free(pCur->zParentColumn); 631 pCur->zTableName = 0; 632 pCur->zIdColumn = 0; 633 pCur->zParentColumn = 0; 634 pCur->pCurrent = 0; 635 pCur->pClosure = 0; 636 } 637 638 /* 639 ** Close a closure cursor. 640 */ 641 static int closureClose(sqlite3_vtab_cursor *cur){ 642 closure_cursor *pCur = (closure_cursor *)cur; 643 closureClearCursor(pCur); 644 pCur->pVtab->nCursor--; 645 sqlite3_free(pCur); 646 return SQLITE_OK; 647 } 648 649 /* 650 ** Advance a cursor to its next row of output 651 */ 652 static int closureNext(sqlite3_vtab_cursor *cur){ 653 closure_cursor *pCur = (closure_cursor*)cur; 654 pCur->pCurrent = closureAvlNext(pCur->pCurrent); 655 return SQLITE_OK; 656 } 657 658 /* 659 ** Allocate and insert a node 660 */ 661 static int closureInsertNode( 662 closure_queue *pQueue, /* Add new node to this queue */ 663 closure_cursor *pCur, /* The cursor into which to add the node */ 664 sqlite3_int64 id, /* The node ID */ 665 sqlite3_int64 iGeneration /* The generation number for this node */ 666 ){ 667 closure_avl *pNew = sqlite3_malloc64( sizeof(*pNew) ); 668 if( pNew==0 ) return SQLITE_NOMEM; 669 memset(pNew, 0, sizeof(*pNew)); 670 pNew->id = id; 671 pNew->iGeneration = iGeneration; 672 closureAvlInsert(&pCur->pClosure, pNew); 673 queuePush(pQueue, pNew); 674 return SQLITE_OK; 675 } 676 677 /* 678 ** Called to "rewind" a cursor back to the beginning so that 679 ** it starts its output over again. Always called at least once 680 ** prior to any closureColumn, closureRowid, or closureEof call. 681 ** 682 ** This routine actually computes the closure. 683 ** 684 ** See the comment at the beginning of closureBestIndex() for a 685 ** description of the meaning of idxNum. The idxStr parameter is 686 ** not used. 687 */ 688 static int closureFilter( 689 sqlite3_vtab_cursor *pVtabCursor, 690 int idxNum, const char *idxStr, 691 int argc, sqlite3_value **argv 692 ){ 693 closure_cursor *pCur = (closure_cursor *)pVtabCursor; 694 closure_vtab *pVtab = pCur->pVtab; 695 sqlite3_int64 iRoot; 696 sqlite3_int64 mxGen = `999999999`; 697 char *zSql; 698 sqlite3_stmt *pStmt; 699 closure_avl *pAvl; 700 int rc = SQLITE_OK; 701 const char *zTableName = pVtab->zTableName; 702 const char *zIdColumn = pVtab->zIdColumn; 703 const char *zParentColumn = pVtab->zParentColumn; 704 closure_queue sQueue; 705 706 (void)idxStr; /* Unused parameter */ 707 (void)argc; /* Unused parameter */ 708 closureClearCursor(pCur); 709 memset(&sQueue, 0, sizeof(sQueue)); 710 if( (idxNum & 1)==0 ){ 711 /* No root=$root in the WHERE clause. Return an empty set */ 712 return SQLITE_OK; 713 } 714 iRoot = sqlite3_value_int64(argv[0]); 715 if( (idxNum & 0x000f0)!=0 ){ 716 mxGen = sqlite3_value_int64(argv[(idxNum>>4)&0x0f]); 717 if( (idxNum & 0x00002)!=0 ) mxGen--; 718 } 719 if( (idxNum & 0x00f00)!=0 ){ 720 zTableName = (const char*)sqlite3_value_text(argv[(idxNum>>8)&0x0f]); 721 pCur->zTableName = sqlite3_mprintf("%s", zTableName); 722 } 723 if( (idxNum & 0x0f000)!=0 ){ 724 zIdColumn = (const char*)sqlite3_value_text(argv[(idxNum>>12)&0x0f]); 725 pCur->zIdColumn = sqlite3_mprintf("%s", zIdColumn); 726 } 727 if( (idxNum & 0x0f0000)!=0 ){ 728 zParentColumn = (const char*)sqlite3_value_text(argv[(idxNum>>16)&0x0f]); 729 pCur->zParentColumn = sqlite3_mprintf("%s", zParentColumn); 730 } 731 732 zSql = sqlite3_mprintf( 733 "SELECT \"%w\".\"%w\" FROM \"%w\" WHERE \"%w\".\"%w\"=?1", 734 zTableName, zIdColumn, zTableName, zTableName, zParentColumn); 735 if( zSql==0 ){ 736 return SQLITE_NOMEM; 737 }else{ 738 rc = sqlite3_prepare_v2(pVtab->db, zSql, -1, &pStmt, 0); 739 sqlite3_free(zSql); 740 if( rc ){ 741 sqlite3_free(pVtab->base.zErrMsg); 742 pVtab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pVtab->db)); 743 return rc; 744 } 745 } 746 if( rc==SQLITE_OK ){ 747 rc = closureInsertNode(&sQueue, pCur, iRoot, 0); 748 } 749 while( (pAvl = queuePull(&sQueue))!=0 ){ 750 if( pAvl->iGeneration>=mxGen ) continue; 751 sqlite3_bind_int64(pStmt, 1, pAvl->id); 752 while( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){ 753 if( sqlite3_column_type(pStmt,0)==SQLITE_INTEGER ){ 754 sqlite3_int64 iNew = sqlite3_column_int64(pStmt, 0); 755 if( closureAvlSearch(pCur->pClosure, iNew)==0 ){ 756 rc = closureInsertNode(&sQueue, pCur, iNew, pAvl->iGeneration+1); 757 } 758 } 759 } 760 sqlite3_reset(pStmt); 761 } 762 sqlite3_finalize(pStmt); 763 if( rc==SQLITE_OK ){ 764 pCur->pCurrent = closureAvlFirst(pCur->pClosure); 765 } 766 767 return rc; 768 } 769 770 /* 771 ** Only the word and distance columns have values. All other columns 772 ** return NULL 773 */ 774 static int closureColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){ 775 closure_cursor *pCur = (closure_cursor*)cur; 776 switch( i ){ 777 case CLOSURE_COL_ID: { 778 sqlite3_result_int64(ctx, pCur->pCurrent->id); 779 break; 780 } 781 case CLOSURE_COL_DEPTH: { 782 sqlite3_result_int64(ctx, pCur->pCurrent->iGeneration); 783 break; 784 } 785 case CLOSURE_COL_ROOT: { 786 sqlite3_result_null(ctx); 787 break; 788 } 789 case CLOSURE_COL_TABLENAME: { 790 sqlite3_result_text(ctx, 791 pCur->zTableName ? pCur->zTableName : pCur->pVtab->zTableName, 792 -1, SQLITE_TRANSIENT); 793 break; 794 } 795 case CLOSURE_COL_IDCOLUMN: { 796 sqlite3_result_text(ctx, 797 pCur->zIdColumn ? pCur->zIdColumn : pCur->pVtab->zIdColumn, 798 -1, SQLITE_TRANSIENT); 799 break; 800 } 801 case CLOSURE_COL_PARENTCOLUMN: { 802 sqlite3_result_text(ctx, 803 pCur->zParentColumn ? pCur->zParentColumn : pCur->pVtab->zParentColumn, 804 -1, SQLITE_TRANSIENT); 805 break; 806 } 807 } 808 return SQLITE_OK; 809 } 810 811 /* 812 ** The rowid. For the closure table, this is the same as the "id" column. 813 */ 814 static int closureRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){ 815 closure_cursor *pCur = (closure_cursor*)cur; 816 *pRowid = pCur->pCurrent->id; 817 return SQLITE_OK; 818 } 819 820 /* 821 ** EOF indicator 822 */ 823 static int closureEof(sqlite3_vtab_cursor *cur){ 824 closure_cursor *pCur = (closure_cursor*)cur; 825 return pCur->pCurrent==0; 826 } 827 828 /* 829 ** Search for terms of these forms: 830 ** 831 ** (A) root = $root 832 ** (B1) depth < $depth 833 ** (B2) depth <= $depth 834 ** (B3) depth = $depth 835 ** (C) tablename = $tablename 836 ** (D) idcolumn = $idcolumn 837 ** (E) parentcolumn = $parentcolumn 838 ** 839 ** 840 ** 841 ** idxNum meaning 842 ** ---------- ------------------------------------------------------ 843 ** 0x00000001 Term of the form (A) found 844 ** 0x00000002 The term of bit-2 is like (B1) 845 ** 0x000000f0 Index in filter.argv[] of $depth. 0 if not used. 846 ** 0x00000f00 Index in filter.argv[] of $tablename. 0 if not used. 847 ** 0x0000f000 Index in filter.argv[] of $idcolumn. 0 if not used 848 ** 0x000f0000 Index in filter.argv[] of $parentcolumn. 0 if not used. 849 ** 850 ** There must be a term of type (A). If there is not, then the index type 851 ** is 0 and the query will return an empty set. 852 */ 853 static int closureBestIndex( 854 sqlite3_vtab *pTab, /* The virtual table */ 855 sqlite3_index_info *pIdxInfo /* Information about the query */ 856 ){ 857 int iPlan = 0; 858 int i; 859 int idx = 1; 860 const struct sqlite3_index_constraint *pConstraint; 861 closure_vtab *pVtab = (closure_vtab*)pTab; 862 double rCost = `10000000`.0; 863 864 pConstraint = pIdxInfo->aConstraint; 865 for(i=0; inConstraint; i++, pConstraint++){ 866 if( pConstraint->usable==0 ) continue; 867 if( (iPlan & 1)==0 868 && pConstraint->iColumn==CLOSURE_COL_ROOT 869 && pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ 870 ){ 871 iPlan |= 1; 872 pIdxInfo->aConstraintUsage[i].argvIndex = 1; 873 pIdxInfo->aConstraintUsage[i].omit = 1; 874 rCost /= 100.0; 875 } 876 if( (iPlan & 0x0000f0)==0 877 && pConstraint->iColumn==CLOSURE_COL_DEPTH 878 && (pConstraint->op==SQLITE_INDEX_CONSTRAINT_LT 879 || pConstraint->op==SQLITE_INDEX_CONSTRAINT_LE 880 || pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ) 881 ){ 882 iPlan |= idx<<4; 883 pIdxInfo->aConstraintUsage[i].argvIndex = ++idx; 884 if( pConstraint->op==SQLITE_INDEX_CONSTRAINT_LT ) iPlan |= 0x000002; 885 rCost /= 5.0; 886 } 887 if( (iPlan & 0x000f00)==0 888 && pConstraint->iColumn==CLOSURE_COL_TABLENAME 889 && pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ 890 ){ 891 iPlan |= idx<<8; 892 pIdxInfo->aConstraintUsage[i].argvIndex = ++idx; 893 pIdxInfo->aConstraintUsage[i].omit = 1; 894 rCost /= 5.0; 895 } 896 if( (iPlan & 0x00f000)==0 897 && pConstraint->iColumn==CLOSURE_COL_IDCOLUMN 898 && pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ 899 ){ 900 iPlan |= idx<<12; 901 pIdxInfo->aConstraintUsage[i].argvIndex = ++idx; 902 pIdxInfo->aConstraintUsage[i].omit = 1; 903 } 904 if( (iPlan & 0x0f0000)==0 905 && pConstraint->iColumn==CLOSURE_COL_PARENTCOLUMN 906 && pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ 907 ){ 908 iPlan |= idx<<16; 909 pIdxInfo->aConstraintUsage[i].argvIndex = ++idx; 910 pIdxInfo->aConstraintUsage[i].omit = 1; 911 } 912 } 913 if( (pVtab->zTableName==0 && (iPlan & 0x000f00)==0) 914 || (pVtab->zIdColumn==0 && (iPlan & 0x00f000)==0) 915 || (pVtab->zParentColumn==0 && (iPlan & 0x0f0000)==0) 916 ){ 917 /* All of tablename, idcolumn, and parentcolumn must be specified 918 ** in either the CREATE VIRTUAL TABLE or in the WHERE clause constraints 919 ** or else the result is an empty set. */ 920 iPlan = 0; 921 } 922 if( (iPlan&1)==0 ){ 923 /* If there is no usable "root=?" term, then set the index-type to 0. 924 ** Also clear any argvIndex variables already set. This is necessary 925 ** to prevent the core from throwing an "xBestIndex malfunction error" 926 ** error (because the argvIndex values are not contiguously assigned 927 ** starting from 1). */ 928 rCost *= 1e30; 929 for(i=0; inConstraint; i++, pConstraint++){ 930 pIdxInfo->aConstraintUsage[i].argvIndex = 0; 931 } 932 iPlan = 0; 933 } 934 pIdxInfo->idxNum = iPlan; 935 if( pIdxInfo->nOrderBy==1 936 && pIdxInfo->aOrderBy[0].iColumn==CLOSURE_COL_ID 937 && pIdxInfo->aOrderBy[0].desc==0 938 ){ 939 pIdxInfo->orderByConsumed = 1; 940 } 941 pIdxInfo->estimatedCost = rCost; 942 943 return SQLITE_OK; 944 } 945 946 /* 947 ** A virtual table module that implements the "transitive_closure". 948 */ 949 static sqlite3_module closureModule = { 950 0, /* iVersion */ 951 closureConnect, /* xCreate */ 952 closureConnect, /* xConnect */ 953 closureBestIndex, /* xBestIndex */ 954 closureDisconnect, /* xDisconnect */ 955 closureDisconnect, /* xDestroy */ 956 closureOpen, /* xOpen - open a cursor */ 957 closureClose, /* xClose - close a cursor */ 958 closureFilter, /* xFilter - configure scan constraints */ 959 closureNext, /* xNext - advance a cursor */ 960 closureEof, /* xEof - check for end of scan */ 961 closureColumn, /* xColumn - read data */ 962 closureRowid, /* xRowid - read data */ 963 0, /* xUpdate */ 964 0, /* xBegin */ 965 0, /* xSync */ 966 0, /* xCommit */ 967 0, /* xRollback */ 968 0, /* xFindMethod */ 969 0, /* xRename */ 970 0, /* xSavepoint */ 971 0, /* xRelease */ 972 0, /* xRollbackTo */ 973 0, /* xShadowName */ 974 0 /* xIntegrity */ 975 }; 976 977 #endif /* SQLITE_OMIT_VIRTUALTABLE */ 978 979 /* 980 ** Register the closure virtual table 981 */ 982 #ifdef _WIN32 983 __declspec(dllexport) 984 #endif 985 int sqlite3_closure_init( 986 sqlite3 *db, 987 char **pzErrMsg, 988 const sqlite3_api_routines *pApi 989 ){ 990 int rc = SQLITE_OK; 991 SQLITE_EXTENSION_INIT2(pApi); 992 (void)pzErrMsg; 993 #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_VIRTUALTABLE) 994 rc = sqlite3_create_module(db, "transitive_closure", &closureModule, 0); 995 #endif /* SQLITE_TEST && !SQLITE_OMIT_VIRTUALTABLE */ 996 return rc; 997 }