sqlite_store.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. //go:build (linux || darwin || windows) && sqlite
  2. // +build linux darwin windows
  3. // +build sqlite
  4. // limited GOOS due to modernc.org/libc/unistd
  5. package sqlite
  6. import (
  7. "context"
  8. "database/sql"
  9. "fmt"
  10. "github.com/seaweedfs/seaweedfs/weed/filer"
  11. "github.com/seaweedfs/seaweedfs/weed/filer/abstract_sql"
  12. "github.com/seaweedfs/seaweedfs/weed/filer/mysql"
  13. "github.com/seaweedfs/seaweedfs/weed/util"
  14. _ "modernc.org/sqlite"
  15. )
  16. func init() {
  17. filer.Stores = append(filer.Stores, &SqliteStore{})
  18. }
  19. type SqliteStore struct {
  20. abstract_sql.AbstractSqlStore
  21. }
  22. func (store *SqliteStore) GetName() string {
  23. return "sqlite"
  24. }
  25. func (store *SqliteStore) Initialize(configuration util.Configuration, prefix string) (err error) {
  26. dbFile := configuration.GetString(prefix + "dbFile")
  27. createTable := `CREATE TABLE IF NOT EXISTS "%s" (
  28. dirhash BIGINT,
  29. name VARCHAR(1000),
  30. directory TEXT,
  31. meta BLOB,
  32. PRIMARY KEY (dirhash, name)
  33. ) WITHOUT ROWID;`
  34. upsertQuery := `INSERT INTO "%s"(dirhash,name,directory,meta)VALUES(?,?,?,?)
  35. ON CONFLICT(dirhash,name) DO UPDATE SET
  36. directory=excluded.directory,
  37. meta=excluded.meta;
  38. `
  39. return store.initialize(
  40. dbFile,
  41. createTable,
  42. upsertQuery,
  43. )
  44. }
  45. func (store *SqliteStore) initialize(dbFile, createTable, upsertQuery string) (err error) {
  46. store.SupportBucketTable = true
  47. store.SqlGenerator = &mysql.SqlGenMysql{
  48. CreateTableSqlTemplate: createTable,
  49. DropTableSqlTemplate: "drop table `%s`",
  50. UpsertQueryTemplate: upsertQuery,
  51. }
  52. var dbErr error
  53. store.DB, dbErr = sql.Open("sqlite", dbFile)
  54. if dbErr != nil {
  55. if store.DB != nil {
  56. store.DB.Close()
  57. store.DB = nil
  58. }
  59. return fmt.Errorf("can not connect to %s error:%v", dbFile, dbErr)
  60. }
  61. if err = store.DB.Ping(); err != nil {
  62. return fmt.Errorf("connect to %s error:%v", dbFile, err)
  63. }
  64. store.DB.SetMaxOpenConns(1)
  65. if err = store.CreateTable(context.Background(), abstract_sql.DEFAULT_TABLE); err != nil {
  66. return fmt.Errorf("init table %s: %v", abstract_sql.DEFAULT_TABLE, err)
  67. }
  68. return nil
  69. }