Files
jules/database/postgres/postgres.go
T
2026-04-16 23:40:23 +03:00

82 lines
1.5 KiB
Go

package postgres
import (
"context"
"database/sql"
"fmt"
"time"
"github.com/d1nch8g/jules/database"
_ "github.com/lib/pq"
)
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 {
conn.Close()
return nil, fmt.Errorf("ping database: %w", err)
}
if err := runMigrations(conn); err != nil {
conn.Close()
return nil, fmt.Errorf("run migrations: %w", err)
}
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()
}