2023-12-28 16:29:18 +08:00
|
|
|
package postgresql
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"database/sql"
|
|
|
|
"fmt"
|
2024-01-02 17:08:13 +08:00
|
|
|
"time"
|
|
|
|
|
2023-12-28 16:29:18 +08:00
|
|
|
"github.com/1Panel-dev/1Panel/backend/buserr"
|
|
|
|
"github.com/1Panel-dev/1Panel/backend/constant"
|
|
|
|
"github.com/1Panel-dev/1Panel/backend/utils/postgresql/client"
|
|
|
|
_ "github.com/jackc/pgx/v5/stdlib"
|
|
|
|
)
|
|
|
|
|
|
|
|
type PostgresqlClient interface {
|
|
|
|
Create(info client.CreateInfo) error
|
2024-01-08 17:40:42 +08:00
|
|
|
CreateUser(info client.CreateInfo, withDeleteDB bool) error
|
2023-12-28 16:29:18 +08:00
|
|
|
Delete(info client.DeleteInfo) error
|
2024-01-09 12:43:33 +08:00
|
|
|
ChangePrivileges(info client.Privileges) error
|
2023-12-28 16:29:18 +08:00
|
|
|
ChangePassword(info client.PasswordChangeInfo) error
|
|
|
|
|
|
|
|
Backup(info client.BackupInfo) error
|
|
|
|
Recover(info client.RecoverInfo) error
|
2024-01-02 17:08:13 +08:00
|
|
|
SyncDB() ([]client.SyncDBInfo, error)
|
2023-12-28 16:29:18 +08:00
|
|
|
Close()
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewPostgresqlClient(conn client.DBInfo) (PostgresqlClient, error) {
|
|
|
|
if conn.From == "local" {
|
2024-01-07 22:52:41 +08:00
|
|
|
connArgs := []string{"exec", conn.Address, "psql", "-t", "-U", conn.Username, "-c"}
|
2024-01-02 17:08:13 +08:00
|
|
|
return client.NewLocal(connArgs, conn.Address, conn.Username, conn.Password, conn.Database), nil
|
2023-12-28 16:29:18 +08:00
|
|
|
}
|
2024-01-02 17:08:13 +08:00
|
|
|
|
2023-12-28 16:29:18 +08:00
|
|
|
connArgs := fmt.Sprintf("postgres://%s:%s@%s:%d/?sslmode=disable", conn.Username, conn.Password, conn.Address, conn.Port)
|
|
|
|
db, err := sql.Open("pgx", connArgs)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(conn.Timeout)*time.Second)
|
|
|
|
defer cancel()
|
|
|
|
if err := db.PingContext(ctx); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
if ctx.Err() == context.DeadlineExceeded {
|
|
|
|
return nil, buserr.New(constant.ErrExecTimeOut)
|
|
|
|
}
|
|
|
|
|
|
|
|
return client.NewRemote(client.Remote{
|
|
|
|
Client: db,
|
2024-01-08 18:21:33 +08:00
|
|
|
From: "remote",
|
2023-12-28 16:29:18 +08:00
|
|
|
Database: conn.Database,
|
|
|
|
User: conn.Username,
|
|
|
|
Password: conn.Password,
|
|
|
|
Address: conn.Address,
|
|
|
|
Port: conn.Port,
|
|
|
|
}), nil
|
|
|
|
}
|