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.

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