-
Notifications
You must be signed in to change notification settings - Fork 111
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #124 from noapinsler/master
adding db auto discovery support to postgres
- Loading branch information
Showing
2 changed files
with
123 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,80 @@ | ||
package main | ||
|
||
import ( | ||
"database/sql" | ||
"fmt" | ||
"regexp" | ||
"strings" | ||
|
||
_ "github.com/lib/pq" | ||
) | ||
|
||
const ( | ||
INCLUDE_DBS = "/include:" | ||
EXCLUDE_DBS = "/exclude:" | ||
) | ||
|
||
func listDatabases(connStr string) ([]string, error) { | ||
|
||
db, err := sql.Open("postgres", connStr) | ||
if err != nil { | ||
return nil, err | ||
} | ||
defer db.Close() | ||
|
||
rows, err := db.Query("SELECT datname FROM pg_database WHERE datistemplate = false;") | ||
if err != nil { | ||
return nil, err | ||
} | ||
defer rows.Close() | ||
|
||
var databases []string | ||
for rows.Next() { | ||
var dbname string | ||
if err := rows.Scan(&dbname); err != nil { | ||
return nil, err | ||
} | ||
databases = append(databases, dbname) | ||
} | ||
|
||
return databases, nil | ||
} | ||
|
||
func filterDatabases(databases []string, pattern string) ([]string, error) { | ||
var filtered []string | ||
mode, dbs := parsePattern(pattern) | ||
|
||
// Split the dbs string into individual patterns | ||
dbPatterns := strings.Split(dbs, ",") | ||
|
||
// Process each database name against the patterns | ||
for _, dbname := range databases { | ||
include := false | ||
|
||
for _, dbPattern := range dbPatterns { | ||
matched, err := regexp.MatchString(dbPattern, dbname) | ||
if err != nil { | ||
return nil, fmt.Errorf("invalid pattern: %s", dbPattern) | ||
} | ||
if matched { | ||
include = true | ||
break | ||
} | ||
} | ||
|
||
if (mode == INCLUDE_DBS && include) || (mode == EXCLUDE_DBS && !include) { | ||
filtered = append(filtered, dbname) | ||
} | ||
} | ||
|
||
return filtered, nil | ||
} | ||
|
||
func parsePattern(pattern string) (mode string, dbs string) { | ||
if strings.HasPrefix(pattern, INCLUDE_DBS) { | ||
return INCLUDE_DBS, pattern[len(INCLUDE_DBS):] | ||
} else if strings.HasPrefix(pattern, EXCLUDE_DBS) { | ||
return EXCLUDE_DBS, pattern[len(EXCLUDE_DBS):] | ||
} | ||
return "", "" | ||
} |