Files
2025-10-31 14:36:41 +01:00

68 lines
1.3 KiB
Go

package database
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
)
// Client represents a database connection
type Client struct {
db *sql.DB
schema string
}
// Config holds database connection parameters
type Config struct {
Host string
Port int
Database string
Schema string
User string
Password string
}
// NewClient creates a new database client
func NewClient(cfg Config) (*Client, error) {
connStr := fmt.Sprintf(
"host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
cfg.Host, cfg.Port, cfg.User, cfg.Password, cfg.Database,
)
db, err := sql.Open("postgres", connStr)
if err != nil {
return nil, fmt.Errorf("failed to open database: %w", err)
}
if err := db.Ping(); err != nil {
db.Close()
return nil, fmt.Errorf("failed to connect to database: %w", err)
}
return &Client{
db: db,
schema: cfg.Schema,
}, nil
}
// Close closes the database connection
func (c *Client) Close() error {
return c.db.Close()
}
// TableExists checks if a table exists in the schema
func (c *Client) TableExists(tableName string) (bool, error) {
query := `
SELECT EXISTS (
SELECT 1
FROM information_schema.tables
WHERE table_schema = $1 AND table_name = $2
)
`
var exists bool
err := c.db.QueryRow(query, c.schema, tableName).Scan(&exists)
return exists, err
}