carray.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  1. /*
  2. ** 2016-06-29
  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 demonstrates how to create a table-valued-function that
  14. ** returns the values in a C-language array.
  15. ** Examples:
  16. **
  17. ** SELECT * FROM carray($ptr,5)
  18. **
  19. ** The query above returns 5 integers contained in a C-language array
  20. ** at the address $ptr. $ptr is a pointer to the array of integers.
  21. ** The pointer value must be assigned to $ptr using the
  22. ** sqlite3_bind_pointer() interface with a pointer type of "carray".
  23. ** For example:
  24. **
  25. ** static int aX[] = { 53, 9, 17, 2231, 4, 99 };
  26. ** int i = sqlite3_bind_parameter_index(pStmt, "$ptr");
  27. ** sqlite3_bind_pointer(pStmt, i, aX, "carray", 0);
  28. **
  29. ** There is an optional third parameter to determine the datatype of
  30. ** the C-language array. Allowed values of the third parameter are
  31. ** 'int32', 'int64', 'double', 'char*', 'struct iovec'. Example:
  32. **
  33. ** SELECT * FROM carray($ptr,10,'char*');
  34. **
  35. ** The default value of the third parameter is 'int32'.
  36. **
  37. ** HOW IT WORKS
  38. **
  39. ** The carray "function" is really a virtual table with the
  40. ** following schema:
  41. **
  42. ** CREATE TABLE carray(
  43. ** value,
  44. ** pointer HIDDEN,
  45. ** count HIDDEN,
  46. ** ctype TEXT HIDDEN
  47. ** );
  48. **
  49. ** If the hidden columns "pointer" and "count" are unconstrained, then
  50. ** the virtual table has no rows. Otherwise, the virtual table interprets
  51. ** the integer value of "pointer" as a pointer to the array and "count"
  52. ** as the number of elements in the array. The virtual table steps through
  53. ** the array, element by element.
  54. */
  55. #include "sqlite3ext.h"
  56. SQLITE_EXTENSION_INIT1
  57. #include <assert.h>
  58. #include <string.h>
  59. #ifdef _WIN32
  60. struct iovec {
  61. void *iov_base;
  62. size_t iov_len;
  63. };
  64. #else
  65. # include <sys/uio.h>
  66. #endif
  67. /* Allowed values for the mFlags parameter to sqlite3_carray_bind().
  68. ** Must exactly match the definitions in carray.h.
  69. */
  70. #ifndef CARRAY_INT32
  71. # define CARRAY_INT32 0 /* Data is 32-bit signed integers */
  72. # define CARRAY_INT64 1 /* Data is 64-bit signed integers */
  73. # define CARRAY_DOUBLE 2 /* Data is doubles */
  74. # define CARRAY_TEXT 3 /* Data is char* */
  75. # define CARRAY_BLOB 4 /* Data is struct iovec* */
  76. #endif
  77. #ifndef SQLITE_API
  78. # ifdef _WIN32
  79. # define SQLITE_API __declspec(dllexport)
  80. # else
  81. # define SQLITE_API
  82. # endif
  83. #endif
  84. #ifndef SQLITE_OMIT_VIRTUALTABLE
  85. /*
  86. ** Names of allowed datatypes
  87. */
  88. static const char *azType[] = { "int32", "int64", "double", "char*",
  89. "struct iovec" };
  90. /*
  91. ** Structure used to hold the sqlite3_carray_bind() information
  92. */
  93. typedef struct carray_bind carray_bind;
  94. struct carray_bind {
  95. void *aData; /* The data */
  96. int nData; /* Number of elements */
  97. int mFlags; /* Control flags */
  98. void (*xDel)(void*); /* Destructor for aData */
  99. };
  100. /* carray_cursor is a subclass of sqlite3_vtab_cursor which will
  101. ** serve as the underlying representation of a cursor that scans
  102. ** over rows of the result
  103. */
  104. typedef struct carray_cursor carray_cursor;
  105. struct carray_cursor {
  106. sqlite3_vtab_cursor base; /* Base class - must be first */
  107. sqlite3_int64 iRowid; /* The rowid */
  108. void *pPtr; /* Pointer to the array of values */
  109. sqlite3_int64 iCnt; /* Number of integers in the array */
  110. unsigned char eType; /* One of the CARRAY_type values */
  111. };
  112. /*
  113. ** The carrayConnect() method is invoked to create a new
  114. ** carray_vtab that describes the carray virtual table.
  115. **
  116. ** Think of this routine as the constructor for carray_vtab objects.
  117. **
  118. ** All this routine needs to do is:
  119. **
  120. ** (1) Allocate the carray_vtab object and initialize all fields.
  121. **
  122. ** (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
  123. ** result set of queries against carray will look like.
  124. */
  125. static int carrayConnect(
  126. sqlite3 *db,
  127. void *pAux,
  128. int argc, const char *const*argv,
  129. sqlite3_vtab **ppVtab,
  130. char **pzErr
  131. ){
  132. sqlite3_vtab *pNew;
  133. int rc;
  134. /* Column numbers */
  135. #define CARRAY_COLUMN_VALUE 0
  136. #define CARRAY_COLUMN_POINTER 1
  137. #define CARRAY_COLUMN_COUNT 2
  138. #define CARRAY_COLUMN_CTYPE 3
  139. rc = sqlite3_declare_vtab(db,
  140. "CREATE TABLE x(value,pointer hidden,count hidden,ctype hidden)");
  141. if( rc==SQLITE_OK ){
  142. pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
  143. if( pNew==0 ) return SQLITE_NOMEM;
  144. memset(pNew, 0, sizeof(*pNew));
  145. }
  146. return rc;
  147. }
  148. /*
  149. ** This method is the destructor for carray_cursor objects.
  150. */
  151. static int carrayDisconnect(sqlite3_vtab *pVtab){
  152. sqlite3_free(pVtab);
  153. return SQLITE_OK;
  154. }
  155. /*
  156. ** Constructor for a new carray_cursor object.
  157. */
  158. static int carrayOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
  159. carray_cursor *pCur;
  160. pCur = sqlite3_malloc( sizeof(*pCur) );
  161. if( pCur==0 ) return SQLITE_NOMEM;
  162. memset(pCur, 0, sizeof(*pCur));
  163. *ppCursor = &pCur->base;
  164. return SQLITE_OK;
  165. }
  166. /*
  167. ** Destructor for a carray_cursor.
  168. */
  169. static int carrayClose(sqlite3_vtab_cursor *cur){
  170. sqlite3_free(cur);
  171. return SQLITE_OK;
  172. }
  173. /*
  174. ** Advance a carray_cursor to its next row of output.
  175. */
  176. static int carrayNext(sqlite3_vtab_cursor *cur){
  177. carray_cursor *pCur = (carray_cursor*)cur;
  178. pCur->iRowid++;
  179. return SQLITE_OK;
  180. }
  181. /*
  182. ** Return values of columns for the row at which the carray_cursor
  183. ** is currently pointing.
  184. */
  185. static int carrayColumn(
  186. sqlite3_vtab_cursor *cur, /* The cursor */
  187. sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
  188. int i /* Which column to return */
  189. ){
  190. carray_cursor *pCur = (carray_cursor*)cur;
  191. sqlite3_int64 x = 0;
  192. switch( i ){
  193. case CARRAY_COLUMN_POINTER: return SQLITE_OK;
  194. case CARRAY_COLUMN_COUNT: x = pCur->iCnt; break;
  195. case CARRAY_COLUMN_CTYPE: {
  196. sqlite3_result_text(ctx, azType[pCur->eType], -1, SQLITE_STATIC);
  197. return SQLITE_OK;
  198. }
  199. default: {
  200. switch( pCur->eType ){
  201. case CARRAY_INT32: {
  202. int *p = (int*)pCur->pPtr;
  203. sqlite3_result_int(ctx, p[pCur->iRowid-1]);
  204. return SQLITE_OK;
  205. }
  206. case CARRAY_INT64: {
  207. sqlite3_int64 *p = (sqlite3_int64*)pCur->pPtr;
  208. sqlite3_result_int64(ctx, p[pCur->iRowid-1]);
  209. return SQLITE_OK;
  210. }
  211. case CARRAY_DOUBLE: {
  212. double *p = (double*)pCur->pPtr;
  213. sqlite3_result_double(ctx, p[pCur->iRowid-1]);
  214. return SQLITE_OK;
  215. }
  216. case CARRAY_TEXT: {
  217. const char **p = (const char**)pCur->pPtr;
  218. sqlite3_result_text(ctx, p[pCur->iRowid-1], -1, SQLITE_TRANSIENT);
  219. return SQLITE_OK;
  220. }
  221. case CARRAY_BLOB: {
  222. const struct iovec *p = (struct iovec*)pCur->pPtr;
  223. sqlite3_result_blob(ctx, p[pCur->iRowid-1].iov_base,
  224. (int)p[pCur->iRowid-1].iov_len, SQLITE_TRANSIENT);
  225. return SQLITE_OK;
  226. }
  227. }
  228. }
  229. }
  230. sqlite3_result_int64(ctx, x);
  231. return SQLITE_OK;
  232. }
  233. /*
  234. ** Return the rowid for the current row. In this implementation, the
  235. ** rowid is the same as the output value.
  236. */
  237. static int carrayRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
  238. carray_cursor *pCur = (carray_cursor*)cur;
  239. *pRowid = pCur->iRowid;
  240. return SQLITE_OK;
  241. }
  242. /*
  243. ** Return TRUE if the cursor has been moved off of the last
  244. ** row of output.
  245. */
  246. static int carrayEof(sqlite3_vtab_cursor *cur){
  247. carray_cursor *pCur = (carray_cursor*)cur;
  248. return pCur->iRowid>pCur->iCnt;
  249. }
  250. /*
  251. ** This method is called to "rewind" the carray_cursor object back
  252. ** to the first row of output.
  253. */
  254. static int carrayFilter(
  255. sqlite3_vtab_cursor *pVtabCursor,
  256. int idxNum, const char *idxStr,
  257. int argc, sqlite3_value **argv
  258. ){
  259. carray_cursor *pCur = (carray_cursor *)pVtabCursor;
  260. pCur->pPtr = 0;
  261. pCur->iCnt = 0;
  262. switch( idxNum ){
  263. case 1: {
  264. carray_bind *pBind = sqlite3_value_pointer(argv[0], "carray-bind");
  265. if( pBind==0 ) break;
  266. pCur->pPtr = pBind->aData;
  267. pCur->iCnt = pBind->nData;
  268. pCur->eType = pBind->mFlags & 0x07;
  269. break;
  270. }
  271. case 2:
  272. case 3: {
  273. pCur->pPtr = sqlite3_value_pointer(argv[0], "carray");
  274. pCur->iCnt = pCur->pPtr ? sqlite3_value_int64(argv[1]) : 0;
  275. if( idxNum<3 ){
  276. pCur->eType = CARRAY_INT32;
  277. }else{
  278. unsigned char i;
  279. const char *zType = (const char*)sqlite3_value_text(argv[2]);
  280. for(i=0; i<sizeof(azType)/sizeof(azType[0]); i++){
  281. if( sqlite3_stricmp(zType, azType[i])==0 ) break;
  282. }
  283. if( i>=sizeof(azType)/sizeof(azType[0]) ){
  284. pVtabCursor->pVtab->zErrMsg = sqlite3_mprintf(
  285. "unknown datatype: %Q", zType);
  286. return SQLITE_ERROR;
  287. }else{
  288. pCur->eType = i;
  289. }
  290. }
  291. break;
  292. }
  293. }
  294. pCur->iRowid = 1;
  295. return SQLITE_OK;
  296. }
  297. /*
  298. ** SQLite will invoke this method one or more times while planning a query
  299. ** that uses the carray virtual table. This routine needs to create
  300. ** a query plan for each invocation and compute an estimated cost for that
  301. ** plan.
  302. **
  303. ** In this implementation idxNum is used to represent the
  304. ** query plan. idxStr is unused.
  305. **
  306. ** idxNum is:
  307. **
  308. ** 1 If only the pointer= constraint exists. In this case, the
  309. ** parameter must be bound using sqlite3_carray_bind().
  310. **
  311. ** 2 if the pointer= and count= constraints exist.
  312. **
  313. ** 3 if the ctype= constraint also exists.
  314. **
  315. ** idxNum is 0 otherwise and carray becomes an empty table.
  316. */
  317. static int carrayBestIndex(
  318. sqlite3_vtab *tab,
  319. sqlite3_index_info *pIdxInfo
  320. ){
  321. int i; /* Loop over constraints */
  322. int ptrIdx = -1; /* Index of the pointer= constraint, or -1 if none */
  323. int cntIdx = -1; /* Index of the count= constraint, or -1 if none */
  324. int ctypeIdx = -1; /* Index of the ctype= constraint, or -1 if none */
  325. const struct sqlite3_index_constraint *pConstraint;
  326. pConstraint = pIdxInfo->aConstraint;
  327. for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
  328. if( pConstraint->usable==0 ) continue;
  329. if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
  330. switch( pConstraint->iColumn ){
  331. case CARRAY_COLUMN_POINTER:
  332. ptrIdx = i;
  333. break;
  334. case CARRAY_COLUMN_COUNT:
  335. cntIdx = i;
  336. break;
  337. case CARRAY_COLUMN_CTYPE:
  338. ctypeIdx = i;
  339. break;
  340. }
  341. }
  342. if( ptrIdx>=0 ){
  343. pIdxInfo->aConstraintUsage[ptrIdx].argvIndex = 1;
  344. pIdxInfo->aConstraintUsage[ptrIdx].omit = 1;
  345. pIdxInfo->estimatedCost = (double)1;
  346. pIdxInfo->estimatedRows = 100;
  347. pIdxInfo->idxNum = 1;
  348. if( cntIdx>=0 ){
  349. pIdxInfo->aConstraintUsage[cntIdx].argvIndex = 2;
  350. pIdxInfo->aConstraintUsage[cntIdx].omit = 1;
  351. pIdxInfo->idxNum = 2;
  352. if( ctypeIdx>=0 ){
  353. pIdxInfo->aConstraintUsage[ctypeIdx].argvIndex = 3;
  354. pIdxInfo->aConstraintUsage[ctypeIdx].omit = 1;
  355. pIdxInfo->idxNum = 3;
  356. }
  357. }
  358. }else{
  359. pIdxInfo->estimatedCost = (double)2147483647;
  360. pIdxInfo->estimatedRows = 2147483647;
  361. pIdxInfo->idxNum = 0;
  362. }
  363. return SQLITE_OK;
  364. }
  365. /*
  366. ** This following structure defines all the methods for the
  367. ** carray virtual table.
  368. */
  369. static sqlite3_module carrayModule = {
  370. 0, /* iVersion */
  371. 0, /* xCreate */
  372. carrayConnect, /* xConnect */
  373. carrayBestIndex, /* xBestIndex */
  374. carrayDisconnect, /* xDisconnect */
  375. 0, /* xDestroy */
  376. carrayOpen, /* xOpen - open a cursor */
  377. carrayClose, /* xClose - close a cursor */
  378. carrayFilter, /* xFilter - configure scan constraints */
  379. carrayNext, /* xNext - advance a cursor */
  380. carrayEof, /* xEof - check for end of scan */
  381. carrayColumn, /* xColumn - read data */
  382. carrayRowid, /* xRowid - read data */
  383. 0, /* xUpdate */
  384. 0, /* xBegin */
  385. 0, /* xSync */
  386. 0, /* xCommit */
  387. 0, /* xRollback */
  388. 0, /* xFindMethod */
  389. 0, /* xRename */
  390. 0, /* xSavepoint */
  391. 0, /* xRelease */
  392. 0, /* xRollbackTo */
  393. 0, /* xShadow */
  394. 0 /* xIntegrity */
  395. };
  396. /*
  397. ** Destructor for the carray_bind object
  398. */
  399. static void carrayBindDel(void *pPtr){
  400. carray_bind *p = (carray_bind*)pPtr;
  401. if( p->xDel!=SQLITE_STATIC ){
  402. p->xDel(p->aData);
  403. }
  404. sqlite3_free(p);
  405. }
  406. /*
  407. ** Invoke this interface in order to bind to the single-argument
  408. ** version of CARRAY().
  409. */
  410. SQLITE_API int sqlite3_carray_bind(
  411. sqlite3_stmt *pStmt,
  412. int idx,
  413. void *aData,
  414. int nData,
  415. int mFlags,
  416. void (*xDestroy)(void*)
  417. ){
  418. carray_bind *pNew;
  419. int i;
  420. pNew = sqlite3_malloc64(sizeof(*pNew));
  421. if( pNew==0 ){
  422. if( xDestroy!=SQLITE_STATIC && xDestroy!=SQLITE_TRANSIENT ){
  423. xDestroy(aData);
  424. }
  425. return SQLITE_NOMEM;
  426. }
  427. pNew->nData = nData;
  428. pNew->mFlags = mFlags;
  429. if( xDestroy==SQLITE_TRANSIENT ){
  430. sqlite3_int64 sz = nData;
  431. switch( mFlags & 0x07 ){
  432. case CARRAY_INT32: sz *= 4; break;
  433. case CARRAY_INT64: sz *= 8; break;
  434. case CARRAY_DOUBLE: sz *= 8; break;
  435. case CARRAY_TEXT: sz *= sizeof(char*); break;
  436. case CARRAY_BLOB: sz *= sizeof(struct iovec); break;
  437. }
  438. if( (mFlags & 0x07)==CARRAY_TEXT ){
  439. for(i=0; i<nData; i++){
  440. const char *z = ((char**)aData)[i];
  441. if( z ) sz += strlen(z) + 1;
  442. }
  443. }else if( (mFlags & 0x07)==CARRAY_BLOB ){
  444. for(i=0; i<nData; i++){
  445. sz += ((struct iovec*)aData)[i].iov_len;
  446. }
  447. }
  448. pNew->aData = sqlite3_malloc64( sz );
  449. if( pNew->aData==0 ){
  450. sqlite3_free(pNew);
  451. return SQLITE_NOMEM;
  452. }
  453. if( (mFlags & 0x07)==CARRAY_TEXT ){
  454. char **az = (char**)pNew->aData;
  455. char *z = (char*)&az[nData];
  456. for(i=0; i<nData; i++){
  457. const char *zData = ((char**)aData)[i];
  458. sqlite3_int64 n;
  459. if( zData==0 ){
  460. az[i] = 0;
  461. continue;
  462. }
  463. az[i] = z;
  464. n = strlen(zData);
  465. memcpy(z, zData, n+1);
  466. z += n+1;
  467. }
  468. }else if( (mFlags & 0x07)==CARRAY_BLOB ){
  469. struct iovec *p = (struct iovec*)pNew->aData;
  470. unsigned char *z = (unsigned char*)&p[nData];
  471. for(i=0; i<nData; i++){
  472. size_t n = ((struct iovec*)aData)[i].iov_len;
  473. p[i].iov_len = n;
  474. p[i].iov_base = z;
  475. z += n;
  476. memcpy(p[i].iov_base, ((struct iovec*)aData)[i].iov_base, n);
  477. }
  478. }else{
  479. memcpy(pNew->aData, aData, sz);
  480. }
  481. pNew->xDel = sqlite3_free;
  482. }else{
  483. pNew->aData = aData;
  484. pNew->xDel = xDestroy;
  485. }
  486. return sqlite3_bind_pointer(pStmt, idx, pNew, "carray-bind", carrayBindDel);
  487. }
  488. /*
  489. ** For testing purpose in the TCL test harness, we need a method for
  490. ** setting the pointer value. The inttoptr(X) SQL function accomplishes
  491. ** this. Tcl script will bind an integer to X and the inttoptr() SQL
  492. ** function will use sqlite3_result_pointer() to convert that integer into
  493. ** a pointer.
  494. **
  495. ** This is for testing on TCL only.
  496. */
  497. #ifdef SQLITE_TEST
  498. static void inttoptrFunc(
  499. sqlite3_context *context,
  500. int argc,
  501. sqlite3_value **argv
  502. ){
  503. void *p;
  504. sqlite3_int64 i64;
  505. i64 = sqlite3_value_int64(argv[0]);
  506. if( sizeof(i64)==sizeof(p) ){
  507. memcpy(&p, &i64, sizeof(p));
  508. }else{
  509. int i32 = i64 & 0xffffffff;
  510. memcpy(&p, &i32, sizeof(p));
  511. }
  512. sqlite3_result_pointer(context, p, "carray", 0);
  513. }
  514. #endif /* SQLITE_TEST */
  515. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  516. SQLITE_API int sqlite3_carray_init(
  517. sqlite3 *db,
  518. char **pzErrMsg,
  519. const sqlite3_api_routines *pApi
  520. ){
  521. int rc = SQLITE_OK;
  522. SQLITE_EXTENSION_INIT2(pApi);
  523. #ifndef SQLITE_OMIT_VIRTUALTABLE
  524. rc = sqlite3_create_module(db, "carray", &carrayModule, 0);
  525. #ifdef SQLITE_TEST
  526. if( rc==SQLITE_OK ){
  527. rc = sqlite3_create_function(db, "inttoptr", 1, SQLITE_UTF8, 0,
  528. inttoptrFunc, 0, 0);
  529. }
  530. #endif /* SQLITE_TEST */
  531. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  532. return rc;
  533. }