2021-01-02 02:07:43 +00:00
|
|
|
// Copyright 2020 The Gitea Authors. All rights reserved.
|
2022-11-27 13:20:29 -05:00
|
|
|
// SPDX-License-Identifier: MIT
|
2025-11-30 17:47:45 +01:00
|
|
|
// Copyright 2025 The Forgejo Authors. All rights reserved.
|
|
|
|
|
// SPDX-License-Identifier: GPL-3.0-or-later
|
2021-01-02 02:07:43 +00:00
|
|
|
|
2021-09-19 19:49:59 +08:00
|
|
|
package db
|
2021-01-02 02:07:43 +00:00
|
|
|
|
|
|
|
|
import (
|
2025-11-30 17:47:45 +01:00
|
|
|
"context"
|
2021-01-02 02:07:43 +00:00
|
|
|
"database/sql"
|
|
|
|
|
"database/sql/driver"
|
2025-11-30 17:47:45 +01:00
|
|
|
"errors"
|
2021-01-02 02:07:43 +00:00
|
|
|
|
2025-03-27 19:40:14 +00:00
|
|
|
"forgejo.org/modules/setting"
|
2021-01-02 02:07:43 +00:00
|
|
|
|
2025-11-30 17:47:45 +01:00
|
|
|
"github.com/jackc/pgx/v5/stdlib"
|
2021-01-02 02:07:43 +00:00
|
|
|
"xorm.io/xorm/dialects"
|
|
|
|
|
)
|
|
|
|
|
|
2025-11-30 17:47:45 +01:00
|
|
|
func init() {
|
|
|
|
|
// Register pgx-based driver as "postgresschema" for PostgreSQL with schema support
|
|
|
|
|
// This wraps pgx/v5/stdlib and injects search_path configuration on connection
|
|
|
|
|
// For PostgreSQL without schema, engine.go uses "pgx" directly (registered by pgx/v5/stdlib)
|
|
|
|
|
drv := &postgresSchemaDriver{innerDriver: &stdlib.Driver{}}
|
|
|
|
|
sql.Register("postgresschema", drv)
|
|
|
|
|
dialects.RegisterDriver("postgresschema", dialects.QueryDriver("postgres"))
|
2021-01-02 02:07:43 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type postgresSchemaDriver struct {
|
2025-11-30 17:47:45 +01:00
|
|
|
innerDriver *stdlib.Driver
|
2021-01-02 02:07:43 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Open opens a new connection to the database. name is a connection string.
|
|
|
|
|
// This function opens the postgres connection in the default manner but immediately
|
|
|
|
|
// runs set_config to set the search_path appropriately
|
|
|
|
|
func (d *postgresSchemaDriver) Open(name string) (driver.Conn, error) {
|
2025-11-30 17:47:45 +01:00
|
|
|
conn, err := d.innerDriver.Open(name)
|
2021-01-02 02:07:43 +00:00
|
|
|
if err != nil {
|
|
|
|
|
return conn, err
|
|
|
|
|
}
|
|
|
|
|
|
2025-11-30 17:47:45 +01:00
|
|
|
// pgx implements ExecerContext, not the deprecated Execer interface
|
|
|
|
|
execer, ok := conn.(driver.ExecerContext)
|
|
|
|
|
if !ok {
|
|
|
|
|
_ = conn.Close()
|
|
|
|
|
return nil, errors.New("pgx driver connection does not implement ExecerContext")
|
2021-01-02 02:07:43 +00:00
|
|
|
}
|
|
|
|
|
|
2025-11-30 17:47:45 +01:00
|
|
|
_, err = execer.ExecContext(context.Background(), `SELECT set_config(
|
2021-01-02 02:07:43 +00:00
|
|
|
'search_path',
|
|
|
|
|
$1 || ',' || current_setting('search_path'),
|
2025-11-30 17:47:45 +01:00
|
|
|
false)`, []driver.NamedValue{{Ordinal: 1, Value: setting.Database.Schema}})
|
2021-01-02 02:07:43 +00:00
|
|
|
if err != nil {
|
|
|
|
|
_ = conn.Close()
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return conn, nil
|
|
|
|
|
}
|