Files
2026-06-06 18:52:20 +03:00

81 lines
1.5 KiB
Go

package postgres
import (
"context"
"database/sql"
"errors"
"fmt"
"time"
_ "github.com/lib/pq" // postgres
"m8sh.su/d/jules/database"
)
type DB struct {
users *Users
chats *Chats
facts *Facts
contacts *Contacts
notifications *Notifications
actions *Actions
conn *sql.DB
}
func New(connString string) (*DB, error) {
conn, _ := sql.Open("postgres", connString)
conn.SetMaxOpenConns(25)
conn.SetMaxIdleConns(5)
conn.SetConnMaxLifetime(5 * time.Minute)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := conn.PingContext(ctx); err != nil {
return nil, fmt.Errorf("ping database: %w", errors.Join(err, conn.Close()))
}
if err := runMigrations(conn); err != nil {
return nil, fmt.Errorf("run migrations: %w", errors.Join(err, conn.Close()))
}
return &DB{
users: &Users{conn: conn},
chats: &Chats{conn: conn},
facts: &Facts{conn: conn},
contacts: &Contacts{conn: conn},
notifications: &Notifications{conn: conn},
actions: &Actions{conn: conn},
conn: conn,
}, nil
}
func (db *DB) Users() database.Users {
return db.users
}
func (db *DB) Chats() database.Chats {
return db.chats
}
func (db *DB) Facts() database.Facts {
return db.facts
}
func (db *DB) Contacts() database.Contacts {
return db.contacts
}
func (db *DB) Notifications() database.Notifications {
return db.notifications
}
func (db *DB) Actions() database.Actions {
return db.actions
}
func (db *DB) Close() error {
return db.conn.Close()
}