2019-07-27 10:40:30 +02:00
|
|
|
package postgres
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"database/sql"
|
|
|
|
|
"fmt"
|
2020-06-27 18:48:19 +02:00
|
|
|
"github.com/go-jet/jet/v2/generator/internal/metadata"
|
|
|
|
|
"github.com/go-jet/jet/v2/generator/internal/template"
|
|
|
|
|
"github.com/go-jet/jet/v2/internal/utils"
|
|
|
|
|
"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
|
2019-09-20 18:20:26 +02:00
|
|
|
func Generate(destDir string, dbConn DBConnection) (err error) {
|
|
|
|
|
defer utils.ErrorCatch(&err)
|
2019-07-27 10:40:30 +02:00
|
|
|
|
|
|
|
|
db, err := openConnection(dbConn)
|
2019-09-20 18:20:26 +02:00
|
|
|
utils.PanicOnError(err)
|
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...")
|
2019-09-20 18:20:26 +02:00
|
|
|
schemaInfo := metadata.GetSchemaMetaData(db, dbConn.SchemaName, &postgresQuerySet{})
|
2019-07-27 10:40:30 +02:00
|
|
|
|
|
|
|
|
genPath := path.Join(destDir, dbConn.DBName, dbConn.SchemaName)
|
2019-09-20 18:20:26 +02:00
|
|
|
template.GenerateFiles(genPath, schemaInfo, postgres.Dialect)
|
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
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func openConnection(dbConn DBConnection) (*sql.DB, error) {
|
|
|
|
|
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)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
err = db.Ping()
|
|
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return db, nil
|
|
|
|
|
}
|