3
0
mirror of https://github.com/ergochat/ergo.git synced 2024-11-25 13:29:27 +01:00
Automatically create the datastore on `oragono run` if it doesn't exist.
See also #302.
This commit is contained in:
Shivaram Lingamneni 2018-12-31 01:17:44 -05:00
parent 847922e53d
commit d6d3a10817
2 changed files with 27 additions and 12 deletions

View File

@ -52,14 +52,26 @@ func (err *incompatibleSchemaError) Error() string {
return fmt.Sprintf("Database requires update. Expected schema v%s, got v%s", err.requiredVersion, err.currentVersion)
}
// InitDB creates the database.
// InitDB creates the database, implementing the `oragono initdb` command.
func InitDB(path string) {
// prepare kvstore db
//TODO(dan): fail if already exists instead? don't want to overwrite good data
os.Remove(path)
_, err := os.Stat(path)
if err == nil {
log.Fatal("Datastore already exists (delete it manually to continue): ", path)
} else if !os.IsNotExist(err) {
log.Fatal("Datastore path is inaccessible: ", err.Error())
}
err = initializeDB(path)
if err != nil {
log.Fatal("Could not save datastore: ", err.Error())
}
}
// internal database initialization code
func initializeDB(path string) error {
store, err := buntdb.Open(path)
if err != nil {
log.Fatal(fmt.Sprintf("Failed to open datastore: %s", err.Error()))
return err
}
defer store.Close()
@ -69,9 +81,7 @@ func InitDB(path string) {
return nil
})
if err != nil {
log.Fatal("Could not save datastore:", err.Error())
}
return err
}
// OpenDatabase returns an existing database, performing a schema version check.
@ -81,10 +91,6 @@ func OpenDatabase(config *Config) (*buntdb.DB, error) {
// open the database, giving it at most one chance to auto-upgrade the schema
func openDatabaseInternal(config *Config, allowAutoupgrade bool) (db *buntdb.DB, err error) {
_, err = os.Stat(config.Datastore.Path)
if os.IsNotExist(err) {
return
}
db, err = buntdb.Open(config.Datastore.Path)
if err != nil {
return

View File

@ -885,6 +885,15 @@ func (server *Server) loadDatastore(config *Config) error {
// open the datastore and load server state for which it (rather than config)
// is the source of truth
_, err := os.Stat(config.Datastore.Path)
if os.IsNotExist(err) {
server.logger.Warning("startup", "database does not exist, creating it", config.Datastore.Path)
err = initializeDB(config.Datastore.Path)
if err != nil {
return err
}
}
db, err := OpenDatabase(config)
if err == nil {
server.store = db