/db/api_sqlite.go

https://github.com/vadv/gopher-lua-libs · Go · 79 lines · 62 code · 15 blank · 2 comment · 11 complexity · 7c1fe9412ff107d5da9f4e4ec8c76463 MD5 · raw file

  1. // +build !windows
  2. // +build sqlite
  3. package db
  4. import (
  5. "database/sql"
  6. "sync"
  7. _ "github.com/mattn/go-sqlite3"
  8. )
  9. type luaSQLite struct {
  10. config *dbConfig
  11. sync.Mutex
  12. db *sql.DB
  13. }
  14. func init() {
  15. RegisterDriver(`sqlite3`, &luaSQLite{})
  16. }
  17. var (
  18. sharedSqlite = make(map[string]*luaSQLite, 0)
  19. sharedSqliteLock = &sync.Mutex{}
  20. )
  21. func (sqlite *luaSQLite) constructor(config *dbConfig) (luaDB, error) {
  22. sharedSqliteLock.Lock()
  23. defer sharedSqliteLock.Unlock()
  24. if config.sharedMode {
  25. result, ok := sharedSqlite[config.connString]
  26. if ok {
  27. return result, nil
  28. }
  29. }
  30. db, err := sql.Open(`sqlite3`, config.connString)
  31. if err != nil {
  32. return nil, err
  33. }
  34. db.SetMaxIdleConns(config.maxOpenConns)
  35. db.SetMaxOpenConns(config.maxOpenConns)
  36. result := &luaSQLite{config: config}
  37. result.db = db
  38. if config.sharedMode {
  39. sharedSqlite[config.connString] = result
  40. }
  41. return result, nil
  42. }
  43. func (sqlite *luaSQLite) getDB() *sql.DB {
  44. sqlite.Lock()
  45. defer sqlite.Unlock()
  46. return sqlite.db
  47. }
  48. func (sqlite *luaSQLite) getTXOptions() *sql.TxOptions {
  49. return &sql.TxOptions{ReadOnly: sqlite.config.readOnly}
  50. }
  51. func (sqlite *luaSQLite) closeDB() error {
  52. sqlite.Lock()
  53. defer sqlite.Unlock()
  54. err := sqlite.db.Close()
  55. if err != nil {
  56. return err
  57. }
  58. if sqlite.config.sharedMode {
  59. sharedSqliteLock.Lock()
  60. delete(sharedSqlite, sqlite.config.connString)
  61. sharedSqliteLock.Unlock()
  62. }
  63. return nil
  64. }