2019-07-27 10:40:30 +02:00
|
|
|
package postgres
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"database/sql"
|
|
|
|
|
"fmt"
|
2021-07-27 17:39:21 +02:00
|
|
|
"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"
|
2021-07-27 17:39:21 +02:00
|
|
|
"github.com/go-jet/jet/v2/internal/utils/throw"
|
2020-06-27 18:48:19 +02:00
|
|
|
"github.com/go-jet/jet/v2/postgres"
|
2019-07-27 10:40:30 +02:00
|
|
|
"path"
|
|
|
|
|
"strconv"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// 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
|
2021-07-27 17:39:21 +02:00
|
|
|
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-07-27 17:39:21 +02:00
|
|
|
db := openConnection(dbConn)
|
2019-08-08 12:02:32 +02:00
|
|
|
defer utils.DBClose(db)
|
2019-07-27 10:40:30 +02:00
|
|
|
|
|
|
|
|
fmt.Println("Retrieving schema information...")
|
|
|
|
|
|
2021-07-27 17:39:21 +02:00
|
|
|
generatorTemplate := template.Default(postgres.Dialect)
|
|
|
|
|
if len(genTemplate) > 0 {
|
|
|
|
|
generatorTemplate = genTemplate[0]
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
schemaMetadata := metadata.GetSchema(db, &postgresQuerySet{}, dbConn.SchemaName)
|
|
|
|
|
|
|
|
|
|
dirPath := path.Join(destDir, dbConn.DBName)
|
|
|
|
|
|
|
|
|
|
template.ProcessSchema(dirPath, schemaMetadata, generatorTemplate)
|
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-07-27 17:39:21 +02:00
|
|
|
func openConnection(dbConn DBConnection) *sql.DB {
|
2019-07-27 10:40:30 +02: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)
|
|
|
|
|
|
|
|
|
|
fmt.Println("Connecting to postgres database: " + connectionString)
|
|
|
|
|
|
|
|
|
|
db, err := sql.Open("postgres", connectionString)
|
2021-07-27 17:39:21 +02:00
|
|
|
throw.OnError(err)
|
2019-07-27 10:40:30 +02:00
|
|
|
|
|
|
|
|
err = db.Ping()
|
2021-07-27 17:39:21 +02:00
|
|
|
throw.OnError(err)
|
2019-07-27 10:40:30 +02:00
|
|
|
|
2021-07-27 17:39:21 +02:00
|
|
|
return db
|
2019-07-27 10:40:30 +02:00
|
|
|
}
|