doc.go 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /*
  2. Package sqlite3 provides interface to SQLite3 databases.
  3. This works as driver for database/sql.
  4. Installation
  5. go get github.com/mattn/go-sqlite3
  6. Supported Types
  7. Currently, go-sqlite3 support following data types.
  8. +------------------------------+
  9. |go | sqlite3 |
  10. |----------|-------------------|
  11. |nil | null |
  12. |int | integer |
  13. |int64 | integer |
  14. |float64 | float |
  15. |bool | integer |
  16. |[]byte | blob |
  17. |string | text |
  18. |time.Time | timestamp/datetime|
  19. +------------------------------+
  20. SQLite3 Extension
  21. You can write your own extension module for sqlite3. For example, below is a
  22. extension for Regexp matcher operation.
  23. #include <pcre.h>
  24. #include <string.h>
  25. #include <stdio.h>
  26. #include <sqlite3ext.h>
  27. SQLITE_EXTENSION_INIT1
  28. static void regexp_func(sqlite3_context *context, int argc, sqlite3_value **argv) {
  29. if (argc >= 2) {
  30. const char *target = (const char *)sqlite3_value_text(argv[1]);
  31. const char *pattern = (const char *)sqlite3_value_text(argv[0]);
  32. const char* errstr = NULL;
  33. int erroff = 0;
  34. int vec[500];
  35. int n, rc;
  36. pcre* re = pcre_compile(pattern, 0, &errstr, &erroff, NULL);
  37. rc = pcre_exec(re, NULL, target, strlen(target), 0, 0, vec, 500);
  38. if (rc <= 0) {
  39. sqlite3_result_error(context, errstr, 0);
  40. return;
  41. }
  42. sqlite3_result_int(context, 1);
  43. }
  44. }
  45. #ifdef _WIN32
  46. __declspec(dllexport)
  47. #endif
  48. int sqlite3_extension_init(sqlite3 *db, char **errmsg,
  49. const sqlite3_api_routines *api) {
  50. SQLITE_EXTENSION_INIT2(api);
  51. return sqlite3_create_function(db, "regexp", 2, SQLITE_UTF8,
  52. (void*)db, regexp_func, NULL, NULL);
  53. }
  54. It need to build as so/dll shared library. And you need to register
  55. extension module like below.
  56. sql.Register("sqlite3_with_extensions",
  57. &sqlite3.SQLiteDriver{
  58. Extensions: []string{
  59. "sqlite3_mod_regexp",
  60. },
  61. })
  62. Then, you can use this extension.
  63. rows, err := db.Query("select text from mytable where name regexp '^golang'")
  64. Connection Hook
  65. You can hook and inject your codes when connection established. database/sql
  66. doesn't provide the way to get native go-sqlite3 interfaces. So if you want,
  67. you need to hook ConnectHook and get the SQLiteConn.
  68. sql.Register("sqlite3_with_hook_example",
  69. &sqlite3.SQLiteDriver{
  70. ConnectHook: func(conn *sqlite3.SQLiteConn) error {
  71. sqlite3conn = append(sqlite3conn, conn)
  72. return nil
  73. },
  74. })
  75. */
  76. package sqlite3