PackageManager just because
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.

140 lines
2.1 KiB

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
  1. package Database
  2. import (
  3. "database/sql"
  4. "os"
  5. "path/filepath"
  6. "time"
  7. _ "github.com/mattn/go-sqlite3"
  8. bolt "go.etcd.io/bbolt"
  9. "PackageManager/Variables"
  10. )
  11. var (
  12. DB *sql.DB
  13. FsDB *bolt.DB
  14. )
  15. func InitConfigDir() error {
  16. var (
  17. e error
  18. )
  19. _, e = os.Stat(Variables.ConfigDir)
  20. if os.IsNotExist(e) {
  21. return os.MkdirAll(Variables.ConfigDir, 0644)
  22. }
  23. return e
  24. }
  25. func InitDatabaseFiles() error {
  26. var e error
  27. // Initialise sqlite3 database for package versioning
  28. DB, e = sql.Open(
  29. "sqlite3",
  30. filepath.Join(Variables.ConfigDir, Variables.DatabaseName),
  31. )
  32. if e != nil {
  33. return e
  34. }
  35. // Initialise bolt db for filesystem hashing
  36. FsDB, e = bolt.Open(
  37. filepath.Join(Variables.ConfigDir, Variables.FsHashDatabaseName),
  38. 0600,
  39. &bolt.Options{
  40. Timeout: 5 * time.Second,
  41. })
  42. return e
  43. }
  44. func init() {
  45. var e error
  46. e = InitConfigDir()
  47. if e != nil {
  48. panic(e)
  49. }
  50. e = InitDatabaseFiles()
  51. if e != nil {
  52. panic(e)
  53. }
  54. }
  55. func InitBoltDB() error {
  56. var (
  57. tx *bolt.Tx
  58. e error
  59. )
  60. tx, e = FsDB.Begin(true)
  61. if e != nil {
  62. return e
  63. }
  64. defer tx.Rollback()
  65. _, e = tx.CreateBucketIfNotExists(Variables.FsHashIndexBucket)
  66. if e != nil {
  67. return e
  68. }
  69. _, e = tx.CreateBucketIfNotExists(Variables.FsHashPicksBucket)
  70. if e != nil {
  71. return e
  72. }
  73. e = tx.Commit()
  74. return e
  75. }
  76. func InitSqlite3DB() error {
  77. var (
  78. stmt *sql.Stmt
  79. e error
  80. )
  81. stmt, e = DB.Prepare(`
  82. CREATE TABLE IF NOT EXISTS installed_packages (
  83. id INTEGER PRIMARY KEY AUTOINCREMENT,
  84. name VARCHAR(64) NOT NULL,
  85. version VARCHAR(64) NOT NULL,
  86. installed_at INTEGER NOT NULL
  87. )
  88. `)
  89. if e != nil {
  90. return e
  91. }
  92. _, e = stmt.Exec()
  93. if e != nil {
  94. return e
  95. }
  96. stmt, e = DB.Prepare(`
  97. CREATE TABLE IF NOT EXISTS dependancy_linker (
  98. id INTEGER PRIMARY KEY AUTOINCREMENT,
  99. package_id INTEGER,
  100. dependancy_id INTEGER,
  101. FOREIGN KEY(package_id) REFERENCES installed_packages(id),
  102. FOREIGN KEY(dependancy_id) REFERENCES installed_packages(id)
  103. )
  104. `)
  105. if e != nil {
  106. return e
  107. }
  108. _, e = stmt.Exec()
  109. return e
  110. }
  111. func InitDB() error {
  112. var e error
  113. e = InitBoltDB()
  114. if e != nil {
  115. return e
  116. }
  117. return InitSqlite3DB()
  118. }