remember.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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 using sqlite3_bind_pointer() with a
  25. ** pointer type of "carray" and bind the id of the counter to $ID and
  26. ** run the prepared statement.
  27. **
  28. ** This implementation of the remember() function uses a "carray"
  29. ** pointer so that it can share pointers with the carray() extension.
  30. **
  31. ** One can imagine doing similar things with floating-point values and
  32. ** strings, but this demonstration extension will stick to using just
  33. ** integers.
  34. */
  35. #include "sqlite3ext.h"
  36. SQLITE_EXTENSION_INIT1
  37. #include <assert.h>
  38. /*
  39. ** remember(V,PTR)
  40. **
  41. ** Return the integer value V. Also save the value of V in a
  42. ** C-language variable whose address is PTR.
  43. */
  44. static void rememberFunc(
  45. sqlite3_context *pCtx,
  46. int argc,
  47. sqlite3_value **argv
  48. ){
  49. sqlite3_int64 v;
  50. sqlite3_int64 *ptr;
  51. assert( argc==2 );
  52. v = sqlite3_value_int64(argv[0]);
  53. ptr = sqlite3_value_pointer(argv[1], "carray");
  54. if( ptr ) *ptr = v;
  55. sqlite3_result_int64(pCtx, v);
  56. }
  57. #ifdef _WIN32
  58. __declspec(dllexport)
  59. #endif
  60. int sqlite3_remember_init(
  61. sqlite3 *db,
  62. char **pzErrMsg,
  63. const sqlite3_api_routines *pApi
  64. ){
  65. int rc = SQLITE_OK;
  66. SQLITE_EXTENSION_INIT2(pApi);
  67. rc = sqlite3_create_function(db, "remember", 2, SQLITE_UTF8, 0,
  68. rememberFunc, 0, 0);
  69. return rc;
  70. }