Documentation
¶
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func InitDefault ¶
InitDefault initializes the default singleton PostgreSQL connection pool.
Example ¶
ExampleInitDefault shows the singleton pattern for the default PostgreSQL pool. Call InitDefault once at application startup; subsequent calls are silently ignored (sync.Once). After a successful call, Default returns the initialised *pgxpool.Pool which can be passed directly to sqlc-generated Queries.
package main
import (
"fmt"
"github.com/phcp-tech/common-library-golang/dbsqlc/postgres"
)
func main() {
err := postgres.InitDefault(&postgres.Config{
Host: "127.0.0.1",
Port: "19999",
Database: "mydb",
Username: "user",
Password: "pass",
MaxOpenConns: 10,
MaxIdleConns: 2,
ConnMaxLifetime: 60,
ConnMaxIdletime: 10,
})
fmt.Println(err)
fmt.Println(postgres.Default() != nil)
}
Output: <nil> true
func NewPostgres ¶
NewPostgres opens a *pgxpool.Pool connection to PostgreSQL and configures the connection pool. It returns the pgx native pool so sqlc-generated Queries (sql_package: "pgx/v5") can use it directly.
Example ¶
ExampleNewPostgres shows that pool creation is lazy: pgxpool.NewWithConfig does not establish any connections at creation time, so no live PostgreSQL server is required. Connections are acquired on first use. Zero-value pool fields fall back to the dbsqlc package defaults (MaxOpenConns=100, MaxIdleConns=25, ConnMaxLifetime=60min, ConnMaxIdletime=10min).
package main
import (
"fmt"
"github.com/phcp-tech/common-library-golang/dbsqlc/postgres"
)
func main() {
pool, err := postgres.NewPostgres(&postgres.Config{
Host: "127.0.0.1",
Port: "19999",
Database: "mydb",
Username: "user",
Password: "pass",
})
if err != nil {
fmt.Println("error:", err)
return
}
defer pool.Close()
fmt.Println("pool created")
}
Output: pool created
Example (CustomPool) ¶
ExampleNewPostgres_customPool shows how to override the default connection pool settings.
package main
import (
"fmt"
"github.com/phcp-tech/common-library-golang/dbsqlc/postgres"
)
func main() {
pool, err := postgres.NewPostgres(&postgres.Config{
Host: "127.0.0.1",
Port: "19999",
Database: "mydb",
Username: "user",
Password: "pass",
SearchPath: "myschema",
MaxOpenConns: 50,
MaxIdleConns: 10,
ConnMaxLifetime: 30, // minutes
ConnMaxIdletime: 5, // minutes
})
if err != nil {
fmt.Println("error:", err)
return
}
defer pool.Close()
fmt.Println("pool created")
}
Output: pool created
Types ¶
type Config ¶
type Config struct {
// Database connection parameters
Host string
Port string
Database string
Username string
Password string
// Optional search_path to set for all connections in the pool
SearchPath string
// Connection pool parameters
MaxOpenConns int
MaxIdleConns int
ConnMaxLifetime int
ConnMaxIdletime int
}