|
|
package postgres
import ( "context" "database/sql" "fmt" "git.aiterp.net/rpdata/api/database/postgres/psqlcore" "git.aiterp.net/rpdata/api/internal/config" "git.aiterp.net/rpdata/api/repositories" "time" )
func Connect(cfg config.Database) (*DB, error) { sslMode := "disable" if cfg.SSL { sslMode = "enable" } psqlInfo := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=%s", cfg.Host, cfg.Port, cfg.Username, cfg.Password, cfg.Db, sslMode, )
timeout, cancel := context.WithTimeout(context.Background(), time.Second*15) defer cancel()
db, err := sql.Open("postgres", psqlInfo) if err != nil { return nil, err } if err := db.PingContext(timeout); err != nil { return nil, err }
q := psqlcore.New(db) if err := q.EnsureCounter(timeout, "data_character_id"); err != nil { return nil, err } if err := q.EnsureCounter(timeout, "data_change_id"); err != nil { return nil, err } if err := q.EnsureCounter(timeout, "data_log_short_id"); err != nil { return nil, err }
return &DB{ db: db, insertWithIDs: cfg.RestoreIDs, }, nil }
type DB struct { insertWithIDs bool db *sql.DB }
func (d *DB) Changes() repositories.ChangeRepository { return &changeRepository{insertWithIDs: d.insertWithIDs, db: d.db} }
func (d *DB) Channels() repositories.ChannelRepository { return &channelRepository{insertWithIDs: d.insertWithIDs, db: d.db} }
func (d *DB) Characters() repositories.CharacterRepository { return &characterRepository{insertWithIDs: d.insertWithIDs, db: d.db} }
func (d *DB) Tags() repositories.TagRepository { panic("implement me") }
func (d *DB) Logs() repositories.LogRepository { panic("implement me") }
func (d *DB) Posts() repositories.PostRepository { panic("implement me") }
func (d *DB) Stories() repositories.StoryRepository { panic("implement me") }
func (d *DB) Chapters() repositories.ChapterRepository { panic("implement me") }
func (d *DB) Comments() repositories.CommentRepository { panic("implement me") }
func (d *DB) Keys() repositories.KeyRepository { panic("implement me") }
func (d *DB) Users() repositories.UserRepository { panic("implement me") }
func (d *DB) Files() repositories.FileRepository { panic("implement me") }
func (d *DB) Close(context.Context) error { return d.db.Close() }
|