1
0
mirror of https://github.com/aclindsa/moneygo.git synced 2024-10-31 16:00:05 -04:00
moneygo/internal/db/db.go

63 lines
2.1 KiB
Go
Raw Normal View History

package db
import (
"database/sql"
"fmt"
"github.com/aclindsa/gorp"
"github.com/aclindsa/moneygo/internal/config"
"github.com/aclindsa/moneygo/internal/models"
_ "github.com/go-sql-driver/mysql"
_ "github.com/lib/pq"
_ "github.com/mattn/go-sqlite3"
"log"
"strings"
)
2017-12-04 21:05:17 -05:00
// luaMaxLengthBuffer is intended to be enough bytes such that a given string
// no longer than models.LuaMaxLength is sure to fit within a database
// implementation's string type specified by the same.
const luaMaxLengthBuffer int = 4096
func GetDbMap(db *sql.DB, dbtype config.DbType) (*gorp.DbMap, error) {
var dialect gorp.Dialect
if dbtype == config.SQLite {
dialect = gorp.SqliteDialect{}
} else if dbtype == config.MySQL {
dialect = gorp.MySQLDialect{
Engine: "InnoDB",
Encoding: "UTF8",
}
} else if dbtype == config.Postgres {
dialect = gorp.PostgresDialect{
LowercaseFields: true,
}
} else {
return nil, fmt.Errorf("Don't know gorp dialect to go with '%s' DB type", dbtype.String())
}
dbmap := &gorp.DbMap{Db: db, Dialect: dialect}
dbmap.AddTableWithName(models.User{}, "users").SetKeys(true, "UserId")
2017-12-03 06:11:38 -05:00
dbmap.AddTableWithName(models.Session{}, "sessions").SetKeys(true, "SessionId")
dbmap.AddTableWithName(models.Account{}, "accounts").SetKeys(true, "AccountId")
2017-12-03 06:38:22 -05:00
dbmap.AddTableWithName(models.Security{}, "securities").SetKeys(true, "SecurityId")
dbmap.AddTableWithName(models.Transaction{}, "transactions").SetKeys(true, "TransactionId")
dbmap.AddTableWithName(models.Split{}, "splits").SetKeys(true, "SplitId")
2017-12-04 21:05:17 -05:00
dbmap.AddTableWithName(models.Price{}, "prices").SetKeys(true, "PriceId")
2017-12-05 05:58:36 -05:00
rtable := dbmap.AddTableWithName(models.Report{}, "reports").SetKeys(true, "ReportId")
rtable.ColMap("Lua").SetMaxSize(models.LuaMaxLength + luaMaxLengthBuffer)
err := dbmap.CreateTablesIfNotExists()
if err != nil {
return nil, err
}
return dbmap, nil
}
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
}