Skip to content

Commit

Permalink
Merge pull request #1 from k1LoW/add-driver-interface
Browse files Browse the repository at this point in the history
Add driver interface
  • Loading branch information
k1LoW authored May 20, 2018
2 parents 27ed3fb + b4416f1 commit 33c57c6
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 7 deletions.
17 changes: 13 additions & 4 deletions db/db.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
package db

import (
"database/sql"
"fmt"
"github.com/k1LoW/tbls/drivers/postgres"
"github.com/k1LoW/tbls/schema"
"github.com/xo/dburl"
"strings"
)

type Driver interface {
Analize(*sql.DB, *schema.Schema) error
}

func Analyze(urlstr string) (*schema.Schema, error) {
s := &schema.Schema{}
u, err := dburl.Parse(urlstr)
Expand All @@ -22,14 +27,18 @@ func Analyze(urlstr string) (*schema.Schema, error) {
return s, err
}
defer db.Close()

var driver Driver

switch u.Driver {
case "postgres":
err := postgres.Analize(db, s)
if err != nil {
return s, err
}
driver = new(postgres.Postgres)
default:
return s, fmt.Errorf("Error: %s", "unsupported driver")
}
err = driver.Analize(db, s)
if err != nil {
return s, err
}
return s, nil
}
9 changes: 6 additions & 3 deletions drivers/postgres/postgres.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,12 @@ import (
"strings"
)

var ReFK = regexp.MustCompile(`FOREIGN KEY \((.+)\) REFERENCES (.+)\((.+)\)`)
var reFK = regexp.MustCompile(`FOREIGN KEY \((.+)\) REFERENCES (.+)\((.+)\)`)

func Analize(db *sql.DB, s *schema.Schema) error {
type Postgres struct{}

// Analize PostgreSQL database schema
func (p *Postgres) Analize(db *sql.DB, s *schema.Schema) error {

// tables
tableRows, err := db.Query(`
Expand Down Expand Up @@ -198,7 +201,7 @@ WHERE table_name = $1`, tableName)

// Relations
for _, r := range relations {
result := ReFK.FindAllStringSubmatch(r.Def, -1)
result := reFK.FindAllStringSubmatch(r.Def, -1)
strColumns := strings.Split(result[0][1], ", ")
strParentTable := result[0][2]
strParentColumns := strings.Split(result[0][3], ", ")
Expand Down

0 comments on commit 33c57c6

Please # to comment.