1 /* 2 ** 2016-05-28 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 ** This file contains the implementation of an SQLite virtual table for 14 ** reading CSV files. 15 ** 16 ** Usage: 17 ** 18 ** .load ./csv 19 ** CREATE VIRTUAL TABLE temp.csv USING csv(filename=FILENAME); 20 ** SELECT * FROM csv; 21 ** 22 ** The columns are named "c1", "c2", "c3", ... by default. But the 23 ** application can define its own CREATE TABLE statement as an additional 24 ** parameter. For example: 25 ** 26 ** CREATE VIRTUAL TABLE temp.csv2 USING csv( 27 ** filename = "../http.log", 28 ** schema = "CREATE TABLE x(date,ipaddr,url,referrer,userAgent)" 29 ** ); 30 ** 31 ** Instead of specifying a file, the text of the CSV can be loaded using 32 ** the data= parameter. 33 ** 34 ** If the columns=N parameter is supplied, then the CSV file is assumed to have 35 ** N columns. If the columns parameter is omitted, the CSV file is opened 36 ** as soon as the virtual table is constructed and the first row of the CSV 37 ** is read in order to count the tables. 38 ** 39 ** Some extra debugging features (used for testing virtual tables) are available 40 ** if this module is compiled with -DSQLITE_TEST. 41 */ 42 #include <sqlite3ext.h> 43 SQLITE_EXTENSION_INIT1 44 #include <string.h> 45 #include <stdlib.h> 46 #include <assert.h> 47 #include <stdarg.h> 48 #include <ctype.h> 49 #include <stdio.h> 50 51 #ifndef SQLITE_OMIT_VIRTUALTABLE 52 53 /* 54 ** A macro to hint to the compiler that a function should not be 55 ** inlined. 56 */ 57 #if defined(__GNUC__) 58 # define CSV_NOINLINE __attribute__((noinline)) 59 #elif defined(_MSC_VER) && _MSC_VER>=1310 60 # define CSV_NOINLINE __declspec(noinline) 61 #else 62 # define CSV_NOINLINE 63 #endif 64 65 66 /* Max size of the error message in a CsvReader */ 67 #define CSV_MXERR 200 68 69 /* Size of the CsvReader input buffer */ 70 #define CSV_INBUFSZ 1024 71 72 /* A context object used when read a CSV file. */ 73 typedef struct CsvReader CsvReader; 74 struct CsvReader { 75 FILE *in; /* Read the CSV text from this input stream */ 76 char *z; /* Accumulated text for a field */ 77 int n; /* Number of bytes in z */ 78 int nAlloc; /* Space allocated for z[] */ 79 int nLine; /* Current line number */ 80 int bNotFirst; /* True if prior text has been seen */ 81 int cTerm; /* Character that terminated the most recent field */ 82 size_t iIn; /* Next unread character in the input buffer */ 83 size_t nIn; /* Number of characters in the input buffer */ 84 char *zIn; /* The input buffer */ 85 char zErr[CSV_MXERR]; /* Error message */ 86 }; 87 88 /* Initialize a CsvReader object */ 89 static void csv_reader_init(CsvReader *p){ 90 p->in = 0; 91 p->z = 0; 92 p->n = 0; 93 p->nAlloc = 0; 94 p->nLine = 0; 95 p->bNotFirst = 0; 96 p->nIn = 0; 97 p->zIn = 0; 98 p->zErr[0] = 0; 99 } 100 101 /* Close and reset a CsvReader object */ 102 static void csv_reader_reset(CsvReader *p){ 103 if( p->in ){ 104 fclose(p->in); 105 sqlite3_free(p->zIn); 106 } 107 sqlite3_free(p->z); 108 csv_reader_init(p); 109 } 110 111 /* Report an error on a CsvReader */ 112 static void csv_errmsg(CsvReader *p, const char *zFormat, ...){ 113 va_list ap; 114 va_start(ap, zFormat); 115 sqlite3_vsnprintf(CSV_MXERR, p->zErr, zFormat, ap); 116 va_end(ap); 117 } 118 119 /* Open the file associated with a CsvReader 120 ** Return the number of errors. 121 */ 122 static int csv_reader_open( 123 CsvReader *p, /* The reader to open */ 124 const char *zFilename, /* Read from this filename */ 125 const char *zData /* ... or use this data */ 126 ){ 127 if( zFilename ){ 128 p->zIn = sqlite3_malloc( CSV_INBUFSZ ); 129 if( p->zIn==0 ){ 130 csv_errmsg(p, "out of memory"); 131 return 1; 132 } 133 p->in = fopen(zFilename, "rb"); 134 if( p->in==0 ){ 135 sqlite3_free(p->zIn); 136 csv_reader_reset(p); 137 csv_errmsg(p, "cannot open '%s' for reading", zFilename); 138 return 1; 139 } 140 }else{ 141 assert( p->in==0 ); 142 p->zIn = (char*)zData; 143 p->nIn = strlen(zData); 144 } 145 return 0; 146 } 147 148 /* The input buffer has overflowed. Refill the input buffer, then 149 ** return the next character 150 */ 151 static CSV_NOINLINE int csv_getc_refill(CsvReader *p){ 152 size_t got; 153 154 assert( p->iIn>=p->nIn ); /* Only called on an empty input buffer */ 155 assert( p->in!=0 ); /* Only called if reading froma file */ 156 157 got = fread(p->zIn, 1, CSV_INBUFSZ, p->in); 158 if( got==0 ) return EOF; 159 p->nIn = got; 160 p->iIn = 1; 161 return p->zIn[0]; 162 } 163 164 /* Return the next character of input. Return EOF at end of input. */ 165 static int csv_getc(CsvReader *p){ 166 if( p->iIn >= p->nIn ){ 167 if( p->in!=0 ) return csv_getc_refill(p); 168 return EOF; 169 } 170 return ((unsigned char*)p->zIn)[p->iIn++]; 171 } 172 173 /* Increase the size of p->z and append character c to the end. 174 ** Return 0 on success and non-zero if there is an OOM error */ 175 static CSV_NOINLINE int csv_resize_and_append(CsvReader *p, char c){ 176 char *zNew; 177 int nNew = p->nAlloc*2 + 100; 178 zNew = sqlite3_realloc64(p->z, nNew); 179 if( zNew ){ 180 p->z = zNew; 181 p->nAlloc = nNew; 182 p->z[p->n++] = c; 183 return 0; 184 }else{ 185 csv_errmsg(p, "out of memory"); 186 return 1; 187 } 188 } 189 190 /* Append a single character to the CsvReader.z[] array. 191 ** Return 0 on success and non-zero if there is an OOM error */ 192 static int csv_append(CsvReader *p, char c){ 193 if( p->n>=p->nAlloc-1 ) return csv_resize_and_append(p, c); 194 p->z[p->n++] = c; 195 return 0; 196 } 197 198 /* Read a single field of CSV text. Compatible with rfc4180 and extended 199 ** with the option of having a separator other than ",". 200 ** 201 ** + Input comes from p->in. 202 ** + Store results in p->z of length p->n. Space to hold p->z comes 203 ** from sqlite3_malloc64(). 204 ** + Keep track of the line number in p->nLine. 205 ** + Store the character that terminates the field in p->cTerm. Store 206 ** EOF on end-of-file. 207 ** 208 ** Return "" at EOF. Return 0 on an OOM error. 209 */ 210 static char *csv_read_one_field(CsvReader *p){ 211 int c; 212 p->n = 0; 213 c = csv_getc(p); 214 if( c==EOF ){ 215 p->cTerm = EOF; 216 return ""; 217 } 218 if( c=='"' ){ 219 int pc, ppc; 220 int startLine = p->nLine; 221 pc = ppc = 0; 222 while( 1 ){ 223 c = csv_getc(p); 224 if( c<='"' || pc=='"' ){ 225 if( c=='\n' ) p->nLine++; 226 if( c=='"' ){ 227 if( pc=='"' ){ 228 pc = 0; 229 continue; 230 } 231 } 232 if( (c==',' && pc=='"') 233 || (c=='\n' && pc=='"') 234 || (c=='\n' && pc=='\r' && ppc=='"') 235 || (c==EOF && pc=='"') 236 ){ 237 do{ p->n--; }while( p->z[p->n]!='"' ); 238 p->cTerm = (char)c; 239 break; 240 } 241 if( pc=='"' && c!='\r' ){ 242 csv_errmsg(p, "line %d: unescaped %c character", p->nLine, '"'); 243 break; 244 } 245 if( c==EOF ){ 246 csv_errmsg(p, "line %d: unterminated %c-quoted field\n", 247 startLine, '"'); 248 p->cTerm = (char)c; 249 break; 250 } 251 } 252 if( csv_append(p, (char)c) ) return 0; 253 ppc = pc; 254 pc = c; 255 } 256 }else{ 257 /* If this is the first field being parsed and it begins with the 258 ** UTF-8 BOM (0xEF BB BF) then skip the BOM */ 259 if( (c&0xff)==0xef && p->bNotFirst==0 ){ 260 csv_append(p, (char)c); 261 c = csv_getc(p); 262 if( (c&0xff)==0xbb ){ 263 csv_append(p, (char)c); 264 c = csv_getc(p); 265 if( (c&0xff)==0xbf ){ 266 p->bNotFirst = 1; 267 p->n = 0; 268 return csv_read_one_field(p); 269 } 270 } 271 } 272 while( c>',' || (c!=EOF && c!=',' && c!='\n') ){ 273 if( csv_append(p, (char)c) ) return 0; 274 c = csv_getc(p); 275 } 276 if( c=='\n' ){ 277 p->nLine++; 278 if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--; 279 } 280 p->cTerm = (char)c; 281 } 282 if( p->z ) p->z[p->n] = 0; 283 p->bNotFirst = 1; 284 return p->z; 285 } 286 287 288 /* Forward references to the various virtual table methods implemented 289 ** in this file. */ 290 static int csvtabCreate(sqlite3*, void*, int, const char*const*, 291 sqlite3_vtab**,char**); 292 static int csvtabConnect(sqlite3*, void*, int, const char*const*, 293 sqlite3_vtab**,char**); 294 static int csvtabBestIndex(sqlite3_vtab*,sqlite3_index_info*); 295 static int csvtabDisconnect(sqlite3_vtab*); 296 static int csvtabOpen(sqlite3_vtab*, sqlite3_vtab_cursor**); 297 static int csvtabClose(sqlite3_vtab_cursor*); 298 static int csvtabFilter(sqlite3_vtab_cursor*, int idxNum, const char *idxStr, 299 int argc, sqlite3_value **argv); 300 static int csvtabNext(sqlite3_vtab_cursor*); 301 static int csvtabEof(sqlite3_vtab_cursor*); 302 static int csvtabColumn(sqlite3_vtab_cursor*,sqlite3_context*,int); 303 static int csvtabRowid(sqlite3_vtab_cursor*,sqlite3_int64*); 304 305 /* An instance of the CSV virtual table */ 306 typedef struct CsvTable { 307 sqlite3_vtab base; /* Base class. Must be first */ 308 char *zFilename; /* Name of the CSV file */ 309 char *zData; /* Raw CSV data in lieu of zFilename */ 310 long iStart; /* Offset to start of data in zFilename */ 311 int nCol; /* Number of columns in the CSV file */ 312 unsigned int tstFlags; /* Bit values used for testing */ 313 } CsvTable; 314 315 /* Allowed values for tstFlags */ 316 #define CSVTEST_FIDX 0x0001 /* Pretend that constrained searchs cost less*/ 317 318 /* A cursor for the CSV virtual table */ 319 typedef struct CsvCursor { 320 sqlite3_vtab_cursor base; /* Base class. Must be first */ 321 CsvReader rdr; /* The CsvReader object */ 322 char **azVal; /* Value of the current row */ 323 int *aLen; /* Length of each entry */ 324 sqlite3_int64 iRowid; /* The current rowid. Negative for EOF */ 325 } CsvCursor; 326 327 /* Transfer error message text from a reader into a CsvTable */ 328 static void csv_xfer_error(CsvTable *pTab, CsvReader *pRdr){ 329 sqlite3_free(pTab->base.zErrMsg); 330 pTab->base.zErrMsg = sqlite3_mprintf("%s", pRdr->zErr); 331 } 332 333 /* 334 ** This method is the destructor fo a CsvTable object. 335 */ 336 static int csvtabDisconnect(sqlite3_vtab *pVtab){ 337 CsvTable *p = (CsvTable*)pVtab; 338 sqlite3_free(p->zFilename); 339 sqlite3_free(p->zData); 340 sqlite3_free(p); 341 return SQLITE_OK; 342 } 343 344 /* Skip leading whitespace. Return a pointer to the first non-whitespace 345 ** character, or to the zero terminator if the string has only whitespace */ 346 static const char *csv_skip_whitespace(const char *z){ 347 while( isspace((unsigned char)z[0]) ) z++; 348 return z; 349 } 350 351 /* Remove trailing whitespace from the end of string z[] */ 352 static void csv_trim_whitespace(char *z){ 353 size_t n = strlen(z); 354 while( n>0 && isspace((unsigned char)z[n]) ) n--; 355 z[n] = 0; 356 } 357 358 /* Dequote the string */ 359 static void csv_dequote(char *z){ 360 int j; 361 char cQuote = z[0]; 362 size_t i, n; 363 364 if( cQuote!='\'' && cQuote!='"' ) return; 365 n = strlen(z); 366 if( n<2 || z[n-1]!=z[0] ) return; 367 for(i=1, j=0; i<n-1; i++){ 368 if( z[i]==cQuote && z[i+1]==cQuote ) i++; 369 z[j++] = z[i]; 370 } 371 z[j] = 0; 372 } 373 374 /* Check to see if the string is of the form: "TAG = VALUE" with optional 375 ** whitespace before and around tokens. If it is, return a pointer to the 376 ** first character of VALUE. If it is not, return NULL. 377 */ 378 static const char *csv_parameter(const char *zTag, int nTag, const char *z){ 379 z = csv_skip_whitespace(z); 380 if( strncmp(zTag, z, nTag)!=0 ) return 0; 381 z = csv_skip_whitespace(z+nTag); 382 if( z[0]!='=' ) return 0; 383 return csv_skip_whitespace(z+1); 384 } 385 386 /* Decode a parameter that requires a dequoted string. 387 ** 388 ** Return 1 if the parameter is seen, or 0 if not. 1 is returned 389 ** even if there is an error. If an error occurs, then an error message 390 ** is left in p->zErr. If there are no errors, p->zErr[0]==0. 391 */ 392 static int csv_string_parameter( 393 CsvReader *p, /* Leave the error message here, if there is one */ 394 const char *zParam, /* Parameter we are checking for */ 395 const char *zArg, /* Raw text of the virtual table argment */ 396 char **pzVal /* Write the dequoted string value here */ 397 ){ 398 const char *zValue; 399 zValue = csv_parameter(zParam,(int)strlen(zParam),zArg); 400 if( zValue==0 ) return 0; 401 p->zErr[0] = 0; 402 if( *pzVal ){ 403 csv_errmsg(p, "more than one '%s' parameter", zParam); 404 return 1; 405 } 406 *pzVal = sqlite3_mprintf("%s", zValue); 407 if( *pzVal==0 ){ 408 csv_errmsg(p, "out of memory"); 409 return 1; 410 } 411 csv_trim_whitespace(*pzVal); 412 csv_dequote(*pzVal); 413 return 1; 414 } 415 416 417 /* Return 0 if the argument is false and 1 if it is true. Return -1 if 418 ** we cannot really tell. 419 */ 420 static int csv_boolean(const char *z){ 421 if( sqlite3_stricmp("yes",z)==0 422 || sqlite3_stricmp("on",z)==0 423 || sqlite3_stricmp("true",z)==0 424 || (z[0]=='1' && z[1]==0) 425 ){ 426 return 1; 427 } 428 if( sqlite3_stricmp("no",z)==0 429 || sqlite3_stricmp("off",z)==0 430 || sqlite3_stricmp("false",z)==0 431 || (z[0]=='0' && z[1]==0) 432 ){ 433 return 0; 434 } 435 return -1; 436 } 437 438 439 /* 440 ** Parameters: 441 ** filename=FILENAME Name of file containing CSV content 442 ** data=TEXT Direct CSV content. 443 ** schema=SCHEMA Alternative CSV schema. 444 ** header=YES|NO First row of CSV defines the names of 445 ** columns if "yes". Default "no". 446 ** columns=N Assume the CSV file contains N columns. 447 ** 448 ** Only available if compiled with SQLITE_TEST: 449 ** 450 ** testflags=N Bitmask of test flags. Optional 451 ** 452 ** If schema= is omitted, then the columns are named "c0", "c1", "c2", 453 ** and so forth. If columns=N is omitted, then the file is opened and 454 ** the number of columns in the first row is counted to determine the 455 ** column count. If header=YES, then the first row is skipped. 456 */ 457 static int csvtabConnect( 458 sqlite3 *db, 459 void *pAux, 460 int argc, const char *const*argv, 461 sqlite3_vtab **ppVtab, 462 char **pzErr 463 ){ 464 CsvTable *pNew = 0; /* The CsvTable object to construct */ 465 int bHeader = -1; /* header= flags. -1 means not seen yet */ 466 int rc = SQLITE_OK; /* Result code from this routine */ 467 int i, j; /* Loop counters */ 468 #ifdef SQLITE_TEST 469 int tstFlags = 0; /* Value for testflags=N parameter */ 470 #endif 471 int nCol = -99; /* Value of the columns= parameter */ 472 CsvReader sRdr; /* A CSV file reader used to store an error 473 ** message and/or to count the number of columns */ 474 static const char *azParam[] = { 475 "filename", "data", "schema", 476 }; 477 char *azPValue[3]; /* Parameter values */ 478 # define CSV_FILENAME (azPValue[0]) 479 # define CSV_DATA (azPValue[1]) 480 # define CSV_SCHEMA (azPValue[2]) 481 482 483 assert( sizeof(azPValue)==sizeof(azParam) ); 484 memset(&sRdr, 0, sizeof(sRdr)); 485 memset(azPValue, 0, sizeof(azPValue)); 486 for(i=3; i<argc; i++){ 487 const char *z = argv[i]; 488 const char *zValue; 489 for(j=0; j<sizeof(azParam)/sizeof(azParam[0]); j++){ 490 if( csv_string_parameter(&sRdr, azParam[j], z, &azPValue[j]) ) break; 491 } 492 if( j<sizeof(azParam)/sizeof(azParam[0]) ){ 493 if( sRdr.zErr[0] ) goto csvtab_connect_error; 494 }else 495 if( (zValue = csv_parameter("header",6,z))!=0 ){ 496 int x; 497 if( bHeader>=0 ){ 498 csv_errmsg(&sRdr, "more than one 'header' parameter"); 499 goto csvtab_connect_error; 500 } 501 x = csv_boolean(zValue); 502 if( x==1 ){ 503 bHeader = 1; 504 }else if( x==0 ){ 505 bHeader = 0; 506 }else{ 507 csv_errmsg(&sRdr, "unrecognized argument to 'header': %s", zValue); 508 goto csvtab_connect_error; 509 } 510 }else 511 #ifdef SQLITE_TEST 512 if( (zValue = csv_parameter("testflags",9,z))!=0 ){ 513 tstFlags = (unsigned int)atoi(zValue); 514 }else 515 #endif 516 if( (zValue = csv_parameter("columns",7,z))!=0 ){ 517 if( nCol>0 ){ 518 csv_errmsg(&sRdr, "more than one 'columns' parameter"); 519 goto csvtab_connect_error; 520 } 521 nCol = atoi(zValue); 522 if( nCol<=0 ){ 523 csv_errmsg(&sRdr, "must have at least one column"); 524 goto csvtab_connect_error; 525 } 526 }else 527 { 528 csv_errmsg(&sRdr, "unrecognized parameter '%s'", z); 529 goto csvtab_connect_error; 530 } 531 } 532 if( (CSV_FILENAME==0)==(CSV_DATA==0) ){ 533 csv_errmsg(&sRdr, "must either filename= or data= but not both"); 534 goto csvtab_connect_error; 535 } 536 if( nCol<=0 && csv_reader_open(&sRdr, CSV_FILENAME, CSV_DATA) ){ 537 goto csvtab_connect_error; 538 } 539 pNew = sqlite3_malloc( sizeof(*pNew) ); 540 *ppVtab = (sqlite3_vtab*)pNew; 541 if( pNew==0 ) goto csvtab_connect_oom; 542 memset(pNew, 0, sizeof(*pNew)); 543 if( nCol>0 ){ 544 pNew->nCol = nCol; 545 }else{ 546 do{ 547 const char *z = csv_read_one_field(&sRdr); 548 if( z==0 ) goto csvtab_connect_oom; 549 pNew->nCol++; 550 }while( sRdr.cTerm==',' ); 551 } 552 pNew->zFilename = CSV_FILENAME; CSV_FILENAME = 0; 553 pNew->zData = CSV_DATA; CSV_DATA = 0; 554 #ifdef SQLITE_TEST 555 pNew->tstFlags = tstFlags; 556 #endif 557 pNew->iStart = bHeader==1 ? ftell(sRdr.in) : 0; 558 csv_reader_reset(&sRdr); 559 if( CSV_SCHEMA==0 ){ 560 char *zSep = ""; 561 CSV_SCHEMA = sqlite3_mprintf("CREATE TABLE x("); 562 if( CSV_SCHEMA==0 ) goto csvtab_connect_oom; 563 for(i=0; i<pNew->nCol; i++){ 564 CSV_SCHEMA = sqlite3_mprintf("%z%sc%d TEXT",CSV_SCHEMA, zSep, i); 565 zSep = ","; 566 } 567 CSV_SCHEMA = sqlite3_mprintf("%z);", CSV_SCHEMA); 568 } 569 rc = sqlite3_declare_vtab(db, CSV_SCHEMA); 570 if( rc ) goto csvtab_connect_error; 571 for(i=0; i<sizeof(azPValue)/sizeof(azPValue[0]); i++){ 572 sqlite3_free(azPValue[i]); 573 } 574 return SQLITE_OK; 575 576 csvtab_connect_oom: 577 rc = SQLITE_NOMEM; 578 csv_errmsg(&sRdr, "out of memory"); 579 580 csvtab_connect_error: 581 if( pNew ) csvtabDisconnect(&pNew->base); 582 for(i=0; i<sizeof(azPValue)/sizeof(azPValue[0]); i++){ 583 sqlite3_free(azPValue[i]); 584 } 585 if( sRdr.zErr[0] ){ 586 sqlite3_free(*pzErr); 587 *pzErr = sqlite3_mprintf("%s", sRdr.zErr); 588 } 589 csv_reader_reset(&sRdr); 590 if( rc==SQLITE_OK ) rc = SQLITE_ERROR; 591 return rc; 592 } 593 594 /* 595 ** Reset the current row content held by a CsvCursor. 596 */ 597 static void csvtabCursorRowReset(CsvCursor *pCur){ 598 CsvTable *pTab = (CsvTable*)pCur->base.pVtab; 599 int i; 600 for(i=0; i<pTab->nCol; i++){ 601 sqlite3_free(pCur->azVal[i]); 602 pCur->azVal[i] = 0; 603 pCur->aLen[i] = 0; 604 } 605 } 606 607 /* 608 ** The xConnect and xCreate methods do the same thing, but they must be 609 ** different so that the virtual table is not an eponymous virtual table. 610 */ 611 static int csvtabCreate( 612 sqlite3 *db, 613 void *pAux, 614 int argc, const char *const*argv, 615 sqlite3_vtab **ppVtab, 616 char **pzErr 617 ){ 618 return csvtabConnect(db, pAux, argc, argv, ppVtab, pzErr); 619 } 620 621 /* 622 ** Destructor for a CsvCursor. 623 */ 624 static int csvtabClose(sqlite3_vtab_cursor *cur){ 625 CsvCursor *pCur = (CsvCursor*)cur; 626 csvtabCursorRowReset(pCur); 627 csv_reader_reset(&pCur->rdr); 628 sqlite3_free(cur); 629 return SQLITE_OK; 630 } 631 632 /* 633 ** Constructor for a new CsvTable cursor object. 634 */ 635 static int csvtabOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){ 636 CsvTable *pTab = (CsvTable*)p; 637 CsvCursor *pCur; 638 size_t nByte; 639 nByte = sizeof(*pCur) + (sizeof(char*)+sizeof(int))*pTab->nCol; 640 pCur = sqlite3_malloc64( nByte ); 641 if( pCur==0 ) return SQLITE_NOMEM; 642 memset(pCur, 0, nByte); 643 pCur->azVal = (char**)&pCur[1]; 644 pCur->aLen = (int*)&pCur->azVal[pTab->nCol]; 645 *ppCursor = &pCur->base; 646 if( csv_reader_open(&pCur->rdr, pTab->zFilename, pTab->zData) ){ 647 csv_xfer_error(pTab, &pCur->rdr); 648 return SQLITE_ERROR; 649 } 650 return SQLITE_OK; 651 } 652 653 654 /* 655 ** Advance a CsvCursor to its next row of input. 656 ** Set the EOF marker if we reach the end of input. 657 */ 658 static int csvtabNext(sqlite3_vtab_cursor *cur){ 659 CsvCursor *pCur = (CsvCursor*)cur; 660 CsvTable *pTab = (CsvTable*)cur->pVtab; 661 int i = 0; 662 char *z; 663 do{ 664 z = csv_read_one_field(&pCur->rdr); 665 if( z==0 ){ 666 csv_xfer_error(pTab, &pCur->rdr); 667 break; 668 } 669 if( i<pTab->nCol ){ 670 if( pCur->aLen[i] < pCur->rdr.n+1 ){ 671 char *zNew = sqlite3_realloc64(pCur->azVal[i], pCur->rdr.n+1); 672 if( zNew==0 ){ 673 csv_errmsg(&pCur->rdr, "out of memory"); 674 csv_xfer_error(pTab, &pCur->rdr); 675 break; 676 } 677 pCur->azVal[i] = zNew; 678 pCur->aLen[i] = pCur->rdr.n+1; 679 } 680 memcpy(pCur->azVal[i], z, pCur->rdr.n+1); 681 i++; 682 } 683 }while( pCur->rdr.cTerm==',' ); 684 if( z==0 || (pCur->rdr.cTerm==EOF && i<pTab->nCol) ){ 685 pCur->iRowid = -1; 686 }else{ 687 pCur->iRowid++; 688 while( i<pTab->nCol ){ 689 sqlite3_free(pCur->azVal[i]); 690 pCur->azVal[i] = 0; 691 pCur->aLen[i] = 0; 692 i++; 693 } 694 } 695 return SQLITE_OK; 696 } 697 698 /* 699 ** Return values of columns for the row at which the CsvCursor 700 ** is currently pointing. 701 */ 702 static int csvtabColumn( 703 sqlite3_vtab_cursor *cur, /* The cursor */ 704 sqlite3_context *ctx, /* First argument to sqlite3_result_...() */ 705 int i /* Which column to return */ 706 ){ 707 CsvCursor *pCur = (CsvCursor*)cur; 708 CsvTable *pTab = (CsvTable*)cur->pVtab; 709 if( i>=0 && i<pTab->nCol && pCur->azVal[i]!=0 ){ 710 sqlite3_result_text(ctx, pCur->azVal[i], -1, SQLITE_STATIC); 711 } 712 return SQLITE_OK; 713 } 714 715 /* 716 ** Return the rowid for the current row. 717 */ 718 static int csvtabRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){ 719 CsvCursor *pCur = (CsvCursor*)cur; 720 *pRowid = pCur->iRowid; 721 return SQLITE_OK; 722 } 723 724 /* 725 ** Return TRUE if the cursor has been moved off of the last 726 ** row of output. 727 */ 728 static int csvtabEof(sqlite3_vtab_cursor *cur){ 729 CsvCursor *pCur = (CsvCursor*)cur; 730 return pCur->iRowid<0; 731 } 732 733 /* 734 ** Only a full table scan is supported. So xFilter simply rewinds to 735 ** the beginning. 736 */ 737 static int csvtabFilter( 738 sqlite3_vtab_cursor *pVtabCursor, 739 int idxNum, const char *idxStr, 740 int argc, sqlite3_value **argv 741 ){ 742 CsvCursor *pCur = (CsvCursor*)pVtabCursor; 743 CsvTable *pTab = (CsvTable*)pVtabCursor->pVtab; 744 pCur->iRowid = 0; 745 if( pCur->rdr.in==0 ){ 746 assert( pCur->rdr.zIn==pTab->zData ); 747 assert( pTab->iStart>=0 ); 748 assert( (size_t)pTab->iStart<=pCur->rdr.nIn ); 749 pCur->rdr.iIn = pTab->iStart; 750 }else{ 751 fseek(pCur->rdr.in, pTab->iStart, SEEK_SET); 752 pCur->rdr.iIn = 0; 753 pCur->rdr.nIn = 0; 754 } 755 return csvtabNext(pVtabCursor); 756 } 757 758 /* 759 ** Only a forward full table scan is supported. xBestIndex is mostly 760 ** a no-op. If CSVTEST_FIDX is set, then the presence of equality 761 ** constraints lowers the estimated cost, which is fiction, but is useful 762 ** for testing certain kinds of virtual table behavior. 763 */ 764 static int csvtabBestIndex( 765 sqlite3_vtab *tab, 766 sqlite3_index_info *pIdxInfo 767 ){ 768 pIdxInfo->estimatedCost = 1000000; 769 #ifdef SQLITE_TEST 770 if( (((CsvTable*)tab)->tstFlags & CSVTEST_FIDX)!=0 ){ 771 /* The usual (and sensible) case is to always do a full table scan. 772 ** The code in this branch only runs when testflags=1. This code 773 ** generates an artifical and unrealistic plan which is useful 774 ** for testing virtual table logic but is not helpful to real applications. 775 ** 776 ** Any ==, LIKE, or GLOB constraint is marked as usable by the virtual 777 ** table (even though it is not) and the cost of running the virtual table 778 ** is reduced from 1 million to just 10. The constraints are *not* marked 779 ** as omittable, however, so the query planner should still generate a 780 ** plan that gives a correct answer, even if they plan is not optimal. 781 */ 782 int i; 783 int nConst = 0; 784 for(i=0; i<pIdxInfo->nConstraint; i++){ 785 unsigned char op; 786 if( pIdxInfo->aConstraint[i].usable==0 ) continue; 787 op = pIdxInfo->aConstraint[i].op; 788 if( op==SQLITE_INDEX_CONSTRAINT_EQ 789 || op==SQLITE_INDEX_CONSTRAINT_LIKE 790 || op==SQLITE_INDEX_CONSTRAINT_GLOB 791 ){ 792 pIdxInfo->estimatedCost = 10; 793 pIdxInfo->aConstraintUsage[nConst].argvIndex = nConst+1; 794 nConst++; 795 } 796 } 797 } 798 #endif 799 return SQLITE_OK; 800 } 801 802 803 static sqlite3_module CsvModule = { 804 0, /* iVersion */ 805 csvtabCreate, /* xCreate */ 806 csvtabConnect, /* xConnect */ 807 csvtabBestIndex, /* xBestIndex */ 808 csvtabDisconnect, /* xDisconnect */ 809 csvtabDisconnect, /* xDestroy */ 810 csvtabOpen, /* xOpen - open a cursor */ 811 csvtabClose, /* xClose - close a cursor */ 812 csvtabFilter, /* xFilter - configure scan constraints */ 813 csvtabNext, /* xNext - advance a cursor */ 814 csvtabEof, /* xEof - check for end of scan */ 815 csvtabColumn, /* xColumn - read data */ 816 csvtabRowid, /* xRowid - read data */ 817 0, /* xUpdate */ 818 0, /* xBegin */ 819 0, /* xSync */ 820 0, /* xCommit */ 821 0, /* xRollback */ 822 0, /* xFindMethod */ 823 0, /* xRename */ 824 }; 825 826 #ifdef SQLITE_TEST 827 /* 828 ** For virtual table testing, make a version of the CSV virtual table 829 ** available that has an xUpdate function. But the xUpdate always returns 830 ** SQLITE_READONLY since the CSV file is not really writable. 831 */ 832 static int csvtabUpdate(sqlite3_vtab *p,int n,sqlite3_value**v,sqlite3_int64*x){ 833 return SQLITE_READONLY; 834 } 835 static sqlite3_module CsvModuleFauxWrite = { 836 0, /* iVersion */ 837 csvtabCreate, /* xCreate */ 838 csvtabConnect, /* xConnect */ 839 csvtabBestIndex, /* xBestIndex */ 840 csvtabDisconnect, /* xDisconnect */ 841 csvtabDisconnect, /* xDestroy */ 842 csvtabOpen, /* xOpen - open a cursor */ 843 csvtabClose, /* xClose - close a cursor */ 844 csvtabFilter, /* xFilter - configure scan constraints */ 845 csvtabNext, /* xNext - advance a cursor */ 846 csvtabEof, /* xEof - check for end of scan */ 847 csvtabColumn, /* xColumn - read data */ 848 csvtabRowid, /* xRowid - read data */ 849 csvtabUpdate, /* xUpdate */ 850 0, /* xBegin */ 851 0, /* xSync */ 852 0, /* xCommit */ 853 0, /* xRollback */ 854 0, /* xFindMethod */ 855 0, /* xRename */ 856 }; 857 #endif /* SQLITE_TEST */ 858 859 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */ 860 861 862 #ifdef _WIN32 863 __declspec(dllexport) 864 #endif 865 /* 866 ** This routine is called when the extension is loaded. The new 867 ** CSV virtual table module is registered with the calling database 868 ** connection. 869 */ 870 int sqlite3_csv_init( 871 sqlite3 *db, 872 char **pzErrMsg, 873 const sqlite3_api_routines *pApi 874 ){ 875 #ifndef SQLITE_OMIT_VIRTUALTABLE 876 int rc; 877 SQLITE_EXTENSION_INIT2(pApi); 878 rc = sqlite3_create_module(db, "csv", &CsvModule, 0); 879 #ifdef SQLITE_TEST 880 if( rc==SQLITE_OK ){ 881 rc = sqlite3_create_module(db, "csv_wr", &CsvModuleFauxWrite, 0); 882 } 883 #endif 884 return rc; 885 #else 886 return SQLITE_OK; 887 #endif 888 } 889