Skip to content

Commit

Permalink
Merge pull request #22 from k1LoW/add-table-def
Browse files Browse the repository at this point in the history
Add schema.Table.Def for show table/view definition
  • Loading branch information
k1LoW authored Jun 5, 2018
2 parents 9104359 + 3fc4e63 commit dae46a8
Show file tree
Hide file tree
Showing 24 changed files with 437 additions and 18 deletions.
1 change: 1 addition & 0 deletions db/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ func Analyze(urlstr string) (*schema.Schema, error) {
s.Name = splitted[1]

db, err := dburl.Open(urlstr)
defer db.Close()
if err != nil {
return s, err
}
Expand Down
41 changes: 41 additions & 0 deletions drivers/mysql/mysql.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,47 @@ SELECT table_name, table_type, table_comment FROM information_schema.tables WHER
Comment: tableComment,
}

// table definition
if tableType == "BASE TABLE" {
tableDefRows, err := db.Query(fmt.Sprintf("SHOW CREATE TABLE %s", tableName))
defer tableDefRows.Close()
if err != nil {
return err
}
for tableDefRows.Next() {
var (
tableName string
tableDef string
)
err := tableDefRows.Scan(&tableName, &tableDef)
if err != nil {
return err
}
table.Def = tableDef
}
}

// view definition
if tableType == "VIEW" {
viewDefRows, err := db.Query(`
SELECT view_definition FROM information_schema.views
WHERE table_schema = ?
AND table_name = ?;
`, s.Name, tableName)
defer viewDefRows.Close()
if err != nil {
return err
}
for viewDefRows.Next() {
var tableDef string
err := viewDefRows.Scan(&tableDef)
if err != nil {
return err
}
table.Def = fmt.Sprintf("CREATE VIEW %s AS (%s)", tableName, tableDef)
}
}

// indexes
indexRows, err := db.Query(`
SELECT
Expand Down
38 changes: 38 additions & 0 deletions drivers/mysql/mysql_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package mysql

import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
"github.com/k1LoW/tbls/schema"
"github.com/xo/dburl"
"os"
"testing"
)

var s *schema.Schema
var db *sql.DB

func TestMain(m *testing.M) {
s = &schema.Schema{
Name: "testdb",
}
db, _ = dburl.Open("my://root:mypass@localhost:33306/testdb")
defer db.Close()
exit := m.Run()
if exit != 0 {
os.Exit(exit)
}
}

func TestAnalyzeView(t *testing.T) {
driver := new(Mysql)
err := driver.Analyze(db, s)
if err != nil {
t.Errorf("%v", err)
}
view, _ := s.FindTableByName("post_comments")
expected := view.Def
if expected == "" {
t.Errorf("actual not empty string.")
}
}
21 changes: 21 additions & 0 deletions drivers/postgres/postgres.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,27 @@ AND ps.relname = $1`, tableName)
table.Comment = tableComment
}

// view definition
if tableType == "VIEW" {
viewDefRows, err := db.Query(`
SELECT view_definition FROM information_schema.views
WHERE table_catalog = $1
AND table_name = $2;
`, s.Name, tableName)
defer viewDefRows.Close()
if err != nil {
return err
}
for viewDefRows.Next() {
var tableDef string
err := viewDefRows.Scan(&tableDef)
if err != nil {
return err
}
table.Def = fmt.Sprintf("CREATE VIEW %s AS (\n%s\n)", tableName, strings.TrimRight(tableDef, ";"))
}
}

// indexes
indexRows, err := db.Query(`
SELECT
Expand Down
38 changes: 38 additions & 0 deletions drivers/postgres/postgres_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package postgres

import (
"database/sql"
"github.com/k1LoW/tbls/schema"
_ "github.com/lib/pq"
"github.com/xo/dburl"
"os"
"testing"
)

var s *schema.Schema
var db *sql.DB

func TestMain(m *testing.M) {
s = &schema.Schema{
Name: "testdb",
}
db, _ = dburl.Open("pg://postgres:pgpass@localhost:55432/testdb?sslmode=disable")
defer db.Close()
exit := m.Run()
if exit != 0 {
os.Exit(exit)
}
}

func TestAnalyzeView(t *testing.T) {
driver := new(Postgres)
err := driver.Analyze(db, s)
if err != nil {
t.Errorf("%v", err)
}
view, _ := s.FindTableByName("post_comments")
expected := view.Def
if expected == "" {
t.Errorf("actual not empty string.")
}
}
18 changes: 9 additions & 9 deletions output/dot/templates.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,20 @@ var _Assets5bd148e6149bb9adcdddfcf8cc46d6e3047dbe26 = "digraph {{ .Table.Name }}
var _Assets21532ae17ad95976ac467eeaeab81f2bb1d537e4 = "digraph \"{{ .Schema.Name }}\" {\n // Config\n graph [rankdir=TB, layout=dot, fontname=\"Arial\"];\n node [shape=record, fontsize=14, margin=0.6, fontname=\"Arial\"];\n edge [fontsize=10, labelfloat=false, splines=none, fontname=\"Arial\"];\n\n // Tables\n {{- range $i, $t := .Schema.Tables }}\n {{ $t.Name }} [shape=none, label=<<table border=\"0\" cellborder=\"1\" cellspacing=\"0\" cellpadding=\"6\">\n <tr><td bgcolor=\"#EFEFEF\"><font face=\"Arial Bold\" point-size=\"18\">{{ $t.Name | html }}</font> <font color=\"#666666\">[{{ $t.Type | html }}]</font></td></tr>\n {{- range $ii, $c := $t.Columns }}\n <tr><td port=\"{{ $c.Name | html }}\" align=\"left\">{{ $c.Name | html }} <font color=\"#666666\">[{{ $c.Type | html }}]</font></td></tr>\n {{- end }}\n </table>>];\n {{- end }}\n\n // Relations\n {{- range $j, $r := .Schema.Relations }}\n {{ $r.Table.Name }}:{{ $c := index $r.Columns 0 }}{{ $c.Name }} -> {{ $r.ParentTable.Name }}:{{ $pc := index $r.ParentColumns 0 }}{{ $pc.Name }} [dir=back, arrowtail=crow, {{ if $r.IsAdditional }}style=\"dashed\",{{ end }} taillabel=<<table cellpadding=\"5\" border=\"0\" cellborder=\"0\"><tr><td>{{ $r.Def | html }}</td></tr></table>>];\n {{- end }}\n}\n"

// Assets returns go-assets FileSystem
var Assets = assets.NewFileSystem(map[string][]string{"/": []string{"table.dot.tmpl", "schema.dot.tmpl"}}, map[string]*assets.File{
"/schema.dot.tmpl": &assets.File{
Path: "/schema.dot.tmpl",
FileMode: 0x1a4,
Mtime: time.Unix(1528193744, 1528193744646815118),
Data: []byte(_Assets21532ae17ad95976ac467eeaeab81f2bb1d537e4),
}, "/": &assets.File{
var Assets = assets.NewFileSystem(map[string][]string{"/": []string{"schema.dot.tmpl", "table.dot.tmpl"}}, map[string]*assets.File{
"/": &assets.File{
Path: "/",
FileMode: 0x800001ed,
Mtime: time.Unix(1528193744, 1528193744647833498),
Mtime: time.Unix(1528197635, 1528197635000000000),
Data: nil,
}, "/schema.dot.tmpl": &assets.File{
Path: "/schema.dot.tmpl",
FileMode: 0x1a4,
Mtime: time.Unix(1528197635, 1528197635000000000),
Data: []byte(_Assets21532ae17ad95976ac467eeaeab81f2bb1d537e4),
}, "/table.dot.tmpl": &assets.File{
Path: "/table.dot.tmpl",
FileMode: 0x1a4,
Mtime: time.Unix(1527750838, 1527750838424881150),
Mtime: time.Unix(1527689928, 1527689928000000000),
Data: []byte(_Assets5bd148e6149bb9adcdddfcf8cc46d6e3047dbe26),
}}, "")
16 changes: 8 additions & 8 deletions output/md/templates.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,23 @@ import (
)

var _Assets43889384df1c6f74d764c29d91b9d5637eb46061 = "# {{ .Schema.Name }}\n\n## Tables\n\n| Name | Columns | Comment | Type |\n| ---- | ------- | ------- | ---- |\n{{- range $i, $t := .Schema.Tables }}\n| [{{ $t.Name }}]({{ $t.Name }}.md) | {{ len $t.Columns }} | {{ $t.Comment }} | {{ $t.Type }} |\n{{- end }}\n\n{{ if .er -}}\n## Relations\n\n![er](schema.png)\n{{- end }}\n\n---\n\n> Generated by [tbls](https://github.com/k1LoW/tbls)"
var _Assetsac44302fb6150a621aa9d04a0350aac972bf7e18 = "# {{ .Table.Name }}\n\n## Description\n\n{{ .Table.Comment }}\n\n## Columns\n\n| Name | Type | Default | Nullable | Children | Parents | Comment |\n| ---- | ---- | ------- | -------- | -------- | ------- | ------- |\n{{- range $i, $c := .Table.Columns }}\n| {{ $c.Name }} | {{ $c.Type }} | {{ $c.Default.String }} | {{ $c.Nullable }} | {{ range $ii, $r := $c.ChildRelations -}}[{{ $r.Table.Name }}]({{ $r.Table.Name }}.md) {{ end }} | {{ range $ii, $r := $c.ParentRelations -}}[{{ $r.ParentTable.Name }}]({{ $r.ParentTable.Name }}.md) {{ end }} | {{ $c.Comment }} |\n{{- end }}\n\n## Constraints\n\n| Name | Type | Def |\n| ---- | ---- | --- |\n{{- range $i, $c := .Table.Constraints }}\n| {{ $c.Name }} | {{ $c.Type }} | {{ $c.Def }} |\n{{- end }}\n\n## Indexes\n\n| Name | Def |\n| ---- | --- |\n{{- range $i, $idx := .Table.Indexes }}\n| {{ $idx.Name }} | {{ $idx.Def }} |\n{{- end }}\n\n{{ if .er -}}\n## Relations\n\n![er]({{ .Table.Name }}.png)\n{{- end }}\n\n---\n\n> Generated by [tbls](https://github.com/k1LoW/tbls)"
var _Assetsac44302fb6150a621aa9d04a0350aac972bf7e18 = "# {{ .Table.Name }}\n\n## Description\n\n{{ .Table.Comment -}}\n{{ if .Table.Def }}\n<details>\n<summary><strong>Table Definition</strong></summary>\n\n```sql\n{{ .Table.Def }}\n```\n\n</details>\n{{ end }}\n\n## Columns\n\n| Name | Type | Default | Nullable | Children | Parents | Comment |\n| ---- | ---- | ------- | -------- | -------- | ------- | ------- |\n{{- range $i, $c := .Table.Columns }}\n| {{ $c.Name }} | {{ $c.Type }} | {{ $c.Default.String }} | {{ $c.Nullable }} | {{ range $ii, $r := $c.ChildRelations -}}[{{ $r.Table.Name }}]({{ $r.Table.Name }}.md) {{ end }} | {{ range $ii, $r := $c.ParentRelations -}}[{{ $r.ParentTable.Name }}]({{ $r.ParentTable.Name }}.md) {{ end }} | {{ $c.Comment }} |\n{{- end }}\n\n## Constraints\n\n| Name | Type | Def |\n| ---- | ---- | --- |\n{{- range $i, $c := .Table.Constraints }}\n| {{ $c.Name }} | {{ $c.Type }} | {{ $c.Def }} |\n{{- end }}\n\n## Indexes\n\n| Name | Def |\n| ---- | --- |\n{{- range $i, $idx := .Table.Indexes }}\n| {{ $idx.Name }} | {{ $idx.Def }} |\n{{- end }}\n\n{{ if .er -}}\n## Relations\n\n![er]({{ .Table.Name }}.png)\n{{- end }}\n\n---\n\n> Generated by [tbls](https://github.com/k1LoW/tbls)"

// Assets returns go-assets FileSystem
var Assets = assets.NewFileSystem(map[string][]string{"/": []string{"index.md.tmpl", "table.md.tmpl"}}, map[string]*assets.File{
"/": &assets.File{
"/table.md.tmpl": &assets.File{
Path: "/table.md.tmpl",
FileMode: 0x1a4,
Mtime: time.Unix(1528198538, 1528198538000000000),
Data: []byte(_Assetsac44302fb6150a621aa9d04a0350aac972bf7e18),
}, "/": &assets.File{
Path: "/",
FileMode: 0x800001ed,
Mtime: time.Unix(1527684406, 1527684406000000000),
Mtime: time.Unix(1528198538, 1528198538000000000),
Data: nil,
}, "/index.md.tmpl": &assets.File{
Path: "/index.md.tmpl",
FileMode: 0x1a4,
Mtime: time.Unix(1527684406, 1527684406000000000),
Data: []byte(_Assets43889384df1c6f74d764c29d91b9d5637eb46061),
}, "/table.md.tmpl": &assets.File{
Path: "/table.md.tmpl",
FileMode: 0x1a4,
Mtime: time.Unix(1527684406, 1527684406000000000),
Data: []byte(_Assetsac44302fb6150a621aa9d04a0350aac972bf7e18),
}}, "")
12 changes: 11 additions & 1 deletion output/md/templates/table.md.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,17 @@

## Description

{{ .Table.Comment }}
{{ .Table.Comment -}}
{{ if .Table.Def }}
<details>
<summary><strong>Table Definition</strong></summary>

```sql
{{ .Table.Def }}
```

</details>
{{ end }}

## Columns

Expand Down
13 changes: 13 additions & 0 deletions sample/mysql/CamelizeTable.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,19 @@
## Description


<details>
<summary><strong>Table Definition</strong></summary>

```sql
CREATE TABLE `CamelizeTable` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`created` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
```

</details>


## Columns

Expand Down
22 changes: 22 additions & 0 deletions sample/mysql/comment_stars.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,28 @@
## Description


<details>
<summary><strong>Table Definition</strong></summary>

```sql
CREATE TABLE `comment_stars` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`comment_post_id` bigint(20) NOT NULL,
`comment_user_id` int(11) NOT NULL,
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`updated` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`id`),
UNIQUE KEY `user_id` (`user_id`,`comment_post_id`,`comment_user_id`),
KEY `comment_stars_user_id_post_id_fk` (`comment_post_id`,`comment_user_id`),
KEY `comment_stars_user_id_fk` (`comment_user_id`),
CONSTRAINT `comment_stars_user_id_fk` FOREIGN KEY (`comment_user_id`) REFERENCES `users` (`id`),
CONSTRAINT `comment_stars_user_id_post_id_fk` FOREIGN KEY (`comment_post_id`, `comment_user_id`) REFERENCES `comments` (`post_id`, `user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
```

</details>


## Columns

Expand Down
22 changes: 22 additions & 0 deletions sample/mysql/comments.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,28 @@
## Description


<details>
<summary><strong>Table Definition</strong></summary>

```sql
CREATE TABLE `comments` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`post_id` bigint(20) NOT NULL,
`user_id` int(11) NOT NULL,
`comment` text NOT NULL,
`created` datetime NOT NULL,
`updated` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `post_id` (`post_id`,`user_id`),
KEY `comments_user_id_fk` (`user_id`),
KEY `comments_post_id_user_id_idx` (`post_id`,`user_id`) USING HASH,
CONSTRAINT `comments_post_id_fk` FOREIGN KEY (`post_id`) REFERENCES `posts` (`id`),
CONSTRAINT `comments_user_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
```

</details>


## Columns

Expand Down
18 changes: 18 additions & 0 deletions sample/mysql/logs.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,24 @@
## Description

audit log table
<details>
<summary><strong>Table Definition</strong></summary>

```sql
CREATE TABLE `logs` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`post_id` bigint(20) DEFAULT NULL,
`comment_id` bigint(20) DEFAULT NULL,
`comment_star_id` bigint(20) DEFAULT NULL,
`payload` text,
`created` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
```

</details>


## Columns

Expand Down
9 changes: 9 additions & 0 deletions sample/mysql/post_comments.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,15 @@
## Description

post and comments View table
<details>
<summary><strong>Table Definition</strong></summary>

```sql
CREATE VIEW post_comments AS ((select `c`.`id` AS `id`,`p`.`title` AS `title`,`u2`.`username` AS `post_user`,`c`.`comment` AS `comment`,`u2`.`username` AS `comment_user`,`c`.`created` AS `created`,`c`.`updated` AS `updated` from (((`testdb`.`posts` `p` left join `testdb`.`comments` `c` on((`p`.`id` = `c`.`post_id`))) left join `testdb`.`users` `u` on((`u`.`id` = `p`.`user_id`))) left join `testdb`.`users` `u2` on((`u2`.`id` = `c`.`user_id`)))))
```

</details>


## Columns

Expand Down
21 changes: 21 additions & 0 deletions sample/mysql/posts.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,27 @@
## Description

Posts table
<details>
<summary><strong>Table Definition</strong></summary>

```sql
CREATE TABLE `posts` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`title` varchar(255) NOT NULL,
`body` text NOT NULL,
`post_type` enum('public','private','draft') NOT NULL COMMENT 'public/private/draft',
`created` datetime NOT NULL,
`updated` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `user_id` (`user_id`,`title`),
KEY `posts_user_id_idx` (`id`) USING BTREE,
CONSTRAINT `posts_user_id_fk` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='Posts table'
```

</details>


## Columns

Expand Down
Loading

0 comments on commit dae46a8

Please sign in to comment.