create a schema if it does not exist and use it in the connection

This commit is contained in:
Alfred Kamanda 2025-01-08 10:37:47 +03:00 committed by konstantinmds
parent 0f6c486ee0
commit 25c1cc41bb

View File

@ -14,6 +14,7 @@ import (
"git.defalsify.org/vise.git/persist"
"git.defalsify.org/vise.git/resource"
gdbmstorage "git.grassecon.net/urdt/ussd/internal/storage/db/gdbm"
"github.com/jackc/pgx/v5/pgxpool"
)
var (
@ -46,21 +47,28 @@ func (ms *MenuStorageService) getOrCreateDb(ctx context.Context, existingDb db.D
var newDb db.Db
var err error
schema, ok := ctx.Value("Schema").(string)
if !ok {
return nil, fmt.Errorf("failed to select the schema")
}
if existingDb != nil {
return existingDb, nil
}
connStr := ms.conn.String()
dbTyp := ms.conn.DbType()
if dbTyp == DBTYPE_POSTGRES {
newDb = postgres.NewPgDb()
} else if dbTyp == DBTYPE_GDBM {
err = ms.ensureDbDir()
if database == "postgres" {
connStr := buildConnStr()
// Ensure the schema exists
err = ensureSchemaExists(ctx, connStr, schema)
if err != nil {
return nil, err
return nil, fmt.Errorf("failed to ensure schema exists: %w", err)
}
connStr = path.Join(connStr, section)
newDb = postgres.NewPgDb().WithSchema(schema)
err = newDb.Connect(ctx, connStr)
} else {
newDb = gdbmstorage.NewThreadGdbmDb()
} else {
return nil, fmt.Errorf("unsupported connection string: '%s'\n", ms.conn.String())
@ -74,26 +82,21 @@ func (ms *MenuStorageService) getOrCreateDb(ctx context.Context, existingDb db.D
return newDb, nil
}
// WithGettext triggers use of gettext for translation of templates and menus.
//
// The first language in `lns` will be used as default language, to resolve node keys to
// language strings.
//
// If `lns` is an empty array, gettext will not be used.
func (ms *MenuStorageService) WithGettext(path string, lns []lang.Language) *MenuStorageService {
if len(lns) == 0 {
logg.Warnf("Gettext requested but no languages supplied")
return ms
// ensureSchemaExists creates a new schema if it does not exist
func ensureSchemaExists(ctx context.Context, connStr, schema string) error {
conn, err := pgxpool.New(ctx, connStr)
if err != nil {
return fmt.Errorf("failed to connect to the database: %w", err)
}
rs := resource.NewPoResource(lns[0], path)
defer conn.Close()
for _, ln := range(lns) {
rs = rs.WithLanguage(ln)
query := fmt.Sprintf("CREATE SCHEMA IF NOT EXISTS %s", schema)
_, err = conn.Exec(ctx, query)
if err != nil {
return fmt.Errorf("failed to create schema: %w", err)
}
ms.poResource = rs
return ms
return nil
}
func (ms *MenuStorageService) GetPersister(ctx context.Context) (*persist.Persister, error) {