OLD | NEW |
(Empty) | |
| 1 /* |
| 2 ** 2016-08-09 |
| 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 an SQL function that is a pass-through |
| 14 ** for integer values (it returns a copy of its argument) but also saves the |
| 15 ** value that is passed through into a C-language variable. The address of |
| 16 ** the C-language variable is supplied as the second argument. |
| 17 ** |
| 18 ** This allows, for example, a counter to incremented and the original |
| 19 ** value retrieved, atomically, using a single statement: |
| 20 ** |
| 21 ** UPDATE counterTab SET cnt=remember(cnt,$PTR)+1 WHERE id=$ID |
| 22 ** |
| 23 ** Prepare the above statement once. Then to use it, bind the address |
| 24 ** of the output variable to $PTR and the id of the counter to $ID and |
| 25 ** run the prepared statement. |
| 26 ** |
| 27 ** One can imagine doing similar things with floating-point values and |
| 28 ** strings, but this demonstration extension will stick to using just |
| 29 ** integers. |
| 30 */ |
| 31 #include "sqlite3ext.h" |
| 32 SQLITE_EXTENSION_INIT1 |
| 33 #include <assert.h> |
| 34 |
| 35 /* |
| 36 ** remember(V,PTR) |
| 37 ** |
| 38 ** Return the integer value V. Also save the value of V in a |
| 39 ** C-language variable whose address is PTR. |
| 40 */ |
| 41 static void rememberFunc( |
| 42 sqlite3_context *pCtx, |
| 43 int argc, |
| 44 sqlite3_value **argv |
| 45 ){ |
| 46 sqlite3_int64 v; |
| 47 sqlite3_int64 ptr; |
| 48 assert( argc==2 ); |
| 49 v = sqlite3_value_int64(argv[0]); |
| 50 ptr = sqlite3_value_int64(argv[1]); |
| 51 *((sqlite3_int64*)ptr) = v; |
| 52 sqlite3_result_int64(pCtx, v); |
| 53 } |
| 54 |
| 55 #ifdef _WIN32 |
| 56 __declspec(dllexport) |
| 57 #endif |
| 58 int sqlite3_remember_init( |
| 59 sqlite3 *db, |
| 60 char **pzErrMsg, |
| 61 const sqlite3_api_routines *pApi |
| 62 ){ |
| 63 int rc = SQLITE_OK; |
| 64 SQLITE_EXTENSION_INIT2(pApi); |
| 65 rc = sqlite3_create_function(db, "remember", 2, SQLITE_UTF8, 0, |
| 66 rememberFunc, 0, 0); |
| 67 return rc; |
| 68 } |
OLD | NEW |