forked from ktat/goper
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgenerator.go
91 lines (82 loc) · 2.05 KB
/
generator.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package goper
import (
"io"
"os"
"fmt"
"strings"
"database/sql"
"log"
)
var logger *log.Logger
func init () {
logger = log.New(ColourStream{os.Stderr}, " [XXXX] ", log.LstdFlags)
}
// A SchemaWriter writes a set of tables to the writer denoted by Outfile
type SchemaWriter struct {
PackageName string
Outfile io.Writer
Tables []*Table
}
// Write the schema
func (this *SchemaWriter) WriteSchema() {
//Write the package declaration
fmt.Fprintf(this.Outfile, "package %s\n\n", this.PackageName)
for _, table := range this.Tables {
this.WriteType(table)
}
}
// Write an individual table
func (this *SchemaWriter) WriteType(table *Table) {
fmt.Fprintf(this.Outfile, "type %s struct {\n", CamelCase(table.Name))
for _, column := range table.Columns {
this.WriteField(&column)
}
fmt.Fprintf(this.Outfile, "}\n")
fmt.Fprintf(this.Outfile,
`
func (this *%s)Table() string {
return "%s"
}
`,
CamelCase(table.Name), table.Name)
}
// Write an individual field
func (this *SchemaWriter) WriteField(column *Column) {
fmt.Fprintf(this.Outfile, "\t%s %s `db:\"%s\"`\n",
CamelCase(column.Name), column.GoType(), column.Name)
}
// Load the database schema into memory using introspection, populating .Tables
func (this *SchemaWriter) LoadSchema(driver string, schema string, db *sql.DB) error {
dialect := DialectByDriver(driver)
logger.Printf("schema: %s\n", schema)
logger.Printf("db: %v\n", db)
tables, err := db.Query(dialect.ListTables(schema))
if err != nil {
return err
}
for tables.Next() {
var ignored sql.NullString
t := new(Table)
tables.Scan(&t.Name)
this.Tables = append(this.Tables, t)
cols, err := db.Query(dialect.ListColumns(schema, *t))
if err != nil {
return err
}
for cols.Next() {
c := new(Column)
if strings.EqualFold(dialect.Name(), "sqlite3") {
err = cols.Scan(&ignored, &c.Name, &c.DbType,
&ignored, &ignored, &ignored)
} else {
err = cols.Scan(&c.Name, &c.DbType)
}
if err != nil {
panic(err)
}
t.Columns = append(t.Columns, *c)
}
this.WriteType(t)
}
return nil
}