forked from xo/xo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
110 lines (101 loc) · 2.29 KB
/
main.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
// Command booktest is an example of using a similar schema on different
// databases.
package main
import (
"context"
"database/sql"
"flag"
"fmt"
"os"
"os/user"
// drivers
_ "github.com/denisenkom/go-mssqldb"
_ "github.com/go-sql-driver/mysql"
_ "github.com/godror/godror"
_ "github.com/lib/pq"
_ "github.com/mattn/go-sqlite3"
//_ "github.com/sijms/go-ora/v2"
// models
"github.com/xo/xo/_examples/booktest/mysql"
"github.com/xo/xo/_examples/booktest/oracle"
"github.com/xo/xo/_examples/booktest/postgres"
"github.com/xo/xo/_examples/booktest/sqlite3"
"github.com/xo/xo/_examples/booktest/sqlserver"
"github.com/xo/dburl"
"github.com/xo/dburl/passfile"
)
func init() {
old := dburl.Unregister("oracle")
dburl.RegisterAlias("godror", "oracle")
for _, alias := range old.Aliases {
dburl.RegisterAlias("godror", alias)
}
}
func main() {
verbose := flag.Bool("v", false, "verbose")
dsn := flag.String("dsn", "", "dsn")
flag.Parse()
if err := run(context.Background(), *verbose, *dsn); err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
}
func run(ctx context.Context, verbose bool, dsn string) error {
if verbose {
logger := func(s string, v ...interface{}) {
fmt.Printf("-------------------------------------\nQUERY: %s\n VAL: %v\n\n", s, v)
}
mysql.SetLogger(logger)
oracle.SetLogger(logger)
postgres.SetLogger(logger)
sqlite3.SetLogger(logger)
sqlserver.SetLogger(logger)
}
v, err := user.Current()
if err != nil {
return err
}
// parse url
u, err := parse(dsn)
if err != nil {
return err
}
// open database
db, err := passfile.OpenURL(u, v.HomeDir, "xopass")
if err != nil {
return err
}
var f func(context.Context, *sql.DB) error
switch u.Driver {
case "mysql":
f = runMysql
case "oracle", "godror":
f = runOracle
case "postgres":
f = runPostgres
case "sqlite3":
f = runSqlite3
case "sqlserver":
f = runSqlserver
}
return f(ctx, db)
}
func parse(dsn string) (*dburl.URL, error) {
v, err := dburl.Parse(dsn)
if err != nil {
return nil, err
}
switch v.Driver {
case "mysql":
q := v.Query()
q.Set("parseTime", "true")
v.RawQuery = q.Encode()
return dburl.Parse(v.String())
case "sqlite3":
q := v.Query()
q.Set("_loc", "auto")
v.RawQuery = q.Encode()
return dburl.Parse(v.String())
}
return v, nil
}