jet/generator/postgres/postgres_generator.go

86 lines
2.1 KiB
Go
Raw Normal View History

2019-07-27 10:40:30 +02:00
package postgres
import (
"database/sql"
"fmt"
2021-08-30 15:09:09 +03:00
"path"
"strconv"
"github.com/go-jet/jet/v2/generator/metadata"
"github.com/go-jet/jet/v2/generator/template"
2020-06-27 18:48:19 +02:00
"github.com/go-jet/jet/v2/internal/utils"
"github.com/go-jet/jet/v2/internal/utils/throw"
2020-06-27 18:48:19 +02:00
"github.com/go-jet/jet/v2/postgres"
2021-08-30 15:09:09 +03:00
"github.com/jackc/pgconn"
2019-07-27 10:40:30 +02:00
)
// DBConnection contains postgres connection details
type DBConnection struct {
Host string
Port int
User string
Password string
SslMode string
Params string
DBName string
SchemaName string
}
// Generate generates jet files at destination dir from database connection details
func Generate(destDir string, dbConn DBConnection, genTemplate ...template.Template) (err error) {
2019-09-20 18:20:26 +02:00
defer utils.ErrorCatch(&err)
2019-07-27 10:40:30 +02:00
2021-08-30 15:09:09 +03:00
connectionString := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=%s %s",
dbConn.Host, strconv.Itoa(dbConn.Port), dbConn.User, dbConn.Password, dbConn.DBName, dbConn.SslMode, dbConn.Params)
db := openConnection(connectionString)
2019-08-08 12:02:32 +02:00
defer utils.DBClose(db)
2019-07-27 10:40:30 +02:00
2021-08-30 15:09:09 +03:00
generate(db, dbConn.DBName, dbConn.SchemaName, destDir, genTemplate...)
2019-07-27 10:40:30 +02:00
2021-08-30 15:09:09 +03:00
return
}
2021-08-30 15:09:09 +03:00
func GenerateDSN(dsn, schema, destDir string, templates ...template.Template) (err error) {
defer utils.ErrorCatch(&err)
2021-08-30 15:09:09 +03:00
cfg, err := pgconn.ParseConfig(dsn)
throw.OnError(err)
if cfg.Database == "" {
panic("database name is required")
}
db := openConnection(dsn)
defer utils.DBClose(db)
2021-08-30 15:09:09 +03:00
generate(db, cfg.Database, schema, destDir, templates...)
2019-07-27 10:40:30 +02:00
2019-09-20 18:20:26 +02:00
return
2019-07-27 10:40:30 +02:00
}
2021-08-30 15:09:09 +03:00
func openConnection(dsn string) *sql.DB {
fmt.Println("Connecting to postgres database: " + dsn)
2019-07-27 10:40:30 +02:00
2021-08-30 15:09:09 +03:00
db, err := sql.Open("postgres", dsn)
throw.OnError(err)
2019-07-27 10:40:30 +02:00
err = db.Ping()
throw.OnError(err)
2019-07-27 10:40:30 +02:00
return db
2019-07-27 10:40:30 +02:00
}
2021-08-30 15:09:09 +03:00
func generate(db *sql.DB, dbName, schema, destDir string, templates ...template.Template) {
fmt.Println("Retrieving schema information...")
generatorTemplate := template.Default(postgres.Dialect)
if len(templates) > 0 {
generatorTemplate = templates[0]
}
schemaMetadata := metadata.GetSchema(db, &postgresQuerySet{}, schema)
dirPath := path.Join(destDir, dbName)
template.ProcessSchema(dirPath, schemaMetadata, generatorTemplate)
}