Skip to content

Commit

Permalink
check if database is alive
Browse files Browse the repository at this point in the history
  • Loading branch information
hisham waleed karam committed Oct 14, 2018
1 parent 0948cb7 commit dfe9ea4
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 1 deletion.
7 changes: 6 additions & 1 deletion datastore.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
6 changes: 6 additions & 0 deletions layer.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
17 changes: 17 additions & 0 deletions utils.go
Original file line number Diff line number Diff line change
@@ -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"
)

Expand Down Expand Up @@ -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
}
9 changes: 9 additions & 0 deletions utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

0 comments on commit dfe9ea4

Please sign in to comment.