2017-10-04 19:35:59 -04:00
|
|
|
package db
|
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
|
|
|
"fmt"
|
|
|
|
"github.com/aclindsa/moneygo/internal/config"
|
|
|
|
"github.com/aclindsa/moneygo/internal/handlers"
|
|
|
|
_ "github.com/go-sql-driver/mysql"
|
|
|
|
_ "github.com/lib/pq"
|
|
|
|
_ "github.com/mattn/go-sqlite3"
|
|
|
|
"gopkg.in/gorp.v1"
|
2017-10-24 20:57:55 -04:00
|
|
|
"log"
|
|
|
|
"strings"
|
2017-10-04 19:35:59 -04:00
|
|
|
)
|
|
|
|
|
2017-11-03 20:50:19 -04:00
|
|
|
const luaMaxLengthBuffer int = 4096
|
|
|
|
|
2017-10-05 08:06:08 -04:00
|
|
|
func GetDbMap(db *sql.DB, dbtype config.DbType) (*gorp.DbMap, error) {
|
2017-10-04 19:35:59 -04:00
|
|
|
var dialect gorp.Dialect
|
2017-10-05 08:06:08 -04:00
|
|
|
if dbtype == config.SQLite {
|
2017-10-04 19:35:59 -04:00
|
|
|
dialect = gorp.SqliteDialect{}
|
2017-10-05 08:06:08 -04:00
|
|
|
} else if dbtype == config.MySQL {
|
2017-10-04 19:35:59 -04:00
|
|
|
dialect = gorp.MySQLDialect{
|
|
|
|
Engine: "InnoDB",
|
|
|
|
Encoding: "UTF8",
|
|
|
|
}
|
2017-10-05 08:06:08 -04:00
|
|
|
} else if dbtype == config.Postgres {
|
2017-10-04 19:35:59 -04:00
|
|
|
dialect = gorp.PostgresDialect{}
|
|
|
|
} else {
|
2017-10-05 08:06:08 -04:00
|
|
|
return nil, fmt.Errorf("Don't know gorp dialect to go with '%s' DB type", dbtype.String())
|
2017-10-04 19:35:59 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
dbmap := &gorp.DbMap{Db: db, Dialect: dialect}
|
|
|
|
dbmap.AddTableWithName(handlers.User{}, "users").SetKeys(true, "UserId")
|
|
|
|
dbmap.AddTableWithName(handlers.Session{}, "sessions").SetKeys(true, "SessionId")
|
|
|
|
dbmap.AddTableWithName(handlers.Account{}, "accounts").SetKeys(true, "AccountId")
|
|
|
|
dbmap.AddTableWithName(handlers.Security{}, "securities").SetKeys(true, "SecurityId")
|
|
|
|
dbmap.AddTableWithName(handlers.Transaction{}, "transactions").SetKeys(true, "TransactionId")
|
|
|
|
dbmap.AddTableWithName(handlers.Split{}, "splits").SetKeys(true, "SplitId")
|
|
|
|
dbmap.AddTableWithName(handlers.Price{}, "prices").SetKeys(true, "PriceId")
|
2017-11-03 20:50:19 -04:00
|
|
|
rtable := dbmap.AddTableWithName(handlers.Report{}, "reports").SetKeys(true, "ReportId")
|
|
|
|
rtable.ColMap("Lua").SetMaxSize(handlers.LuaMaxLength + luaMaxLengthBuffer)
|
2017-10-04 19:35:59 -04:00
|
|
|
|
|
|
|
err := dbmap.CreateTablesIfNotExists()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return dbmap, nil
|
|
|
|
}
|
2017-10-24 20:57:55 -04:00
|
|
|
|
|
|
|
func GetDSN(dbtype config.DbType, dsn string) string {
|
|
|
|
if dbtype == config.MySQL && !strings.Contains(dsn, "parseTime=true") {
|
|
|
|
log.Fatalf("The DSN for MySQL MUST contain 'parseTime=True' but does not!")
|
|
|
|
}
|
|
|
|
return dsn
|
|
|
|
}
|