You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

79 lines
1.9 KiB

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