sqlite.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package sqlite
  2. import (
  3. "database/sql"
  4. "github.com/pkg/errors"
  5. // Import the SQLite driver.
  6. _ "modernc.org/sqlite"
  7. "github.com/usememos/memos/server/profile"
  8. "github.com/usememos/memos/store"
  9. )
  10. type DB struct {
  11. db *sql.DB
  12. profile *profile.Profile
  13. }
  14. // NewDB opens a database specified by its database driver name and a
  15. // driver-specific data source name, usually consisting of at least a
  16. // database name and connection information.
  17. func NewDB(profile *profile.Profile) (store.Driver, error) {
  18. // Ensure a DSN is set before attempting to open the database.
  19. if profile.DSN == "" {
  20. return nil, errors.New("dsn required")
  21. }
  22. // Connect to the database with some sane settings:
  23. // - No shared-cache: it's obsolete; WAL journal mode is a better solution.
  24. // - No foreign key constraints: it's currently disabled by default, but it's a
  25. // good practice to be explicit and prevent future surprises on SQLite upgrades.
  26. // - Journal mode set to WAL: it's the recommended journal mode for most applications
  27. // as it prevents locking issues.
  28. //
  29. // Notes:
  30. // - When using the `modernc.org/sqlite` driver, each pragma must be prefixed with `_pragma=`.
  31. //
  32. // References:
  33. // - https://pkg.go.dev/modernc.org/sqlite#Driver.Open
  34. // - https://www.sqlite.org/sharedcache.html
  35. // - https://www.sqlite.org/pragma.html
  36. sqliteDB, err := sql.Open("sqlite", profile.DSN+"?_pragma=foreign_keys(0)&_pragma=busy_timeout(10000)&_pragma=journal_mode(WAL)")
  37. if err != nil {
  38. return nil, errors.Wrapf(err, "failed to open db with dsn: %s", profile.DSN)
  39. }
  40. driver := DB{db: sqliteDB, profile: profile}
  41. return &driver, nil
  42. }
  43. func (d *DB) GetDB() *sql.DB {
  44. return d.db
  45. }
  46. func (d *DB) Close() error {
  47. return d.db.Close()
  48. }