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.

80 lines
1.9 KiB

  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. store.DB.Close()
  56. store.DB = nil
  57. return fmt.Errorf("can not connect to %s error:%v", dbFile, err)
  58. }
  59. if err = store.DB.Ping(); err != nil {
  60. return fmt.Errorf("connect to %s error:%v", dbFile, err)
  61. }
  62. if err = store.CreateTable(context.Background(), abstract_sql.DEFAULT_TABLE); err != nil {
  63. return fmt.Errorf("init table %s: %v", abstract_sql.DEFAULT_TABLE, err)
  64. }
  65. return nil
  66. }