diff options
author | Mo Tarbin <mhed.t91@gmail.com> | 2024-06-30 21:41:41 -0400 |
---|---|---|
committer | Mo Tarbin <mhed.t91@gmail.com> | 2024-06-30 21:41:41 -0400 |
commit | c13dd9addbf89f716e4ef5cfdf1d673139ffcb68 (patch) | |
tree | bc09646ce1d6d3a402abb4694e19da51b57204f6 /internal/database | |
download | donetick-c13dd9addbf89f716e4ef5cfdf1d673139ffcb68.tar.gz donetick-c13dd9addbf89f716e4ef5cfdf1d673139ffcb68.tar.bz2 donetick-c13dd9addbf89f716e4ef5cfdf1d673139ffcb68.zip |
Move to Donetick Org, first commit
Diffstat (limited to 'internal/database')
-rw-r--r-- | internal/database/database.go | 44 |
1 files changed, 44 insertions, 0 deletions
diff --git a/internal/database/database.go b/internal/database/database.go new file mode 100644 index 0000000..8fc8a68 --- /dev/null +++ b/internal/database/database.go @@ -0,0 +1,44 @@ +package database + +import ( + "fmt" + "time" + + "gorm.io/driver/postgres" + "gorm.io/driver/sqlite" // Sqlite driver based on CGO + "gorm.io/gorm/logger" + + // "github.com/glebarez/sqlite" // Pure go SQLite driver, checkout https://github.com/glebarez/sqlite for details + "donetick.com/core/config" + "donetick.com/core/logging" + "gorm.io/gorm" +) + +func NewDatabase(cfg *config.Config) (*gorm.DB, error) { + var db *gorm.DB + var err error + switch cfg.Database.Type { + case "postgres": + dsn := fmt.Sprintf("host=%s port=%v user=%s password=%s dbname=%s sslmode=disable TimeZone=Asia/Shanghai", cfg.Database.Host, cfg.Database.Port, cfg.Database.User, cfg.Database.Password, cfg.Database.Name) + for i := 0; i <= 30; i++ { + db, err = gorm.Open(postgres.Open(dsn), &gorm.Config{ + Logger: logger.Default.LogMode(logger.Info), + }) + if err == nil { + break + } + logging.DefaultLogger().Warnf("failed to open database: %v", err) + time.Sleep(500 * time.Millisecond) + } + + default: + + db, err = gorm.Open(sqlite.Open("donetick.db"), &gorm.Config{}) + + } + + if err != nil { + return nil, err + } + return db, nil +} |