From dfe9ea421ac0ef9c26097812929814a2f6d6d7ec Mon Sep 17 00:00:00 2001 From: hisham waleed karam Date: Sun, 14 Oct 2018 03:20:46 +0200 Subject: [PATCH] check if database is alive --- datastore.go | 7 ++++++- layer.go | 6 ++++++ utils.go | 17 +++++++++++++++++ utils_test.go | 9 +++++++++ 4 files changed, 38 insertions(+), 1 deletion(-) diff --git a/datastore.go b/datastore.go index 24feaa5..e3ba917 100644 --- a/datastore.go +++ b/datastore.go @@ -11,7 +11,12 @@ type datastore struct { Name string `yaml:"name"` } -//BuildConnectionString return postgres connection as string +//BuildConnectionString return gdal postgres connection as string func (ds *datastore) BuildConnectionString() string { return fmt.Sprintf("PG: host=%s port=%d dbname=%s user=%s password=%s", ds.Host, ds.Port, ds.DBName, ds.DBUser, ds.DBPass) } + +//PostgresConnectionString return postgres connection as string +func (ds *datastore) PostgresConnectionString() string { + return fmt.Sprintf("postgresql://%s:%s@%s:%d/%s?sslmode=disable", ds.DBUser, ds.DBPass, ds.Host, ds.Port, ds.DBName) +} diff --git a/layer.go b/layer.go index 65f4593..7bf32d6 100644 --- a/layer.go +++ b/layer.go @@ -55,6 +55,12 @@ func (manager *ManagerConfig) PublishGeoserverLayer(layer *GdalLayer) (ok bool, //LayerToPostgis add Layer to Postgis func (layer *GdalLayer) LayerToPostgis(targetSource *gdal.DataSource, manager *ManagerConfig, overwrite bool) (newLayer *GdalLayer, err error) { + connStr := manager.Datastore.PostgresConnectionString() + dbErr := DBIsAlive(connStr) + if dbErr != nil { + err = dbErr + return + } if targetSource == nil { err = errors.New("Invalid Datasource") return diff --git a/utils.go b/utils.go index b94f5d1..e9b9f81 100644 --- a/utils.go +++ b/utils.go @@ -1,12 +1,14 @@ package gismanager import ( + "database/sql" "io/ioutil" "os" "path" "path/filepath" "strings" + _ "github.com/lib/pq" yaml "gopkg.in/yaml.v2" ) @@ -69,3 +71,18 @@ func GetGISFiles(root string) ([]string, error) { return files, nil } + +//DBIsAlive check if database alive +func DBIsAlive(connectionStr string) (err error) { + db, dbErr := sql.Open("postgres", connectionStr) + if dbErr != nil { + err = dbErr + return + } + if pingErr := db.Ping(); pingErr != nil { + db.Close() + err = pingErr + return + } + return +} diff --git a/utils_test.go b/utils_test.go index 0b7f964..7900668 100644 --- a/utils_test.go +++ b/utils_test.go @@ -24,3 +24,12 @@ func TestGetGISFiles(t *testing.T) { assert.Equal(t, 0, len(dummyFiles)) assert.NotNil(t, dummyFileserr) } +func TestDBIsAlive(t *testing.T) { + manager, _ := FromConfig("./testdata/test_config.yml") + connStr := manager.Datastore.PostgresConnectionString() + dbErr := DBIsAlive(connStr) + assert.Nil(t, dbErr) + connStr = "xxxxx" + err := DBIsAlive(connStr) + assert.NotNil(t, err) +}