42 lines
836 B
Go
42 lines
836 B
Go
|
package database
|
||
|
|
||
|
import (
|
||
|
"database/sql"
|
||
|
"log"
|
||
|
"os"
|
||
|
"time"
|
||
|
|
||
|
"github.com/jinzhu/gorm"
|
||
|
)
|
||
|
|
||
|
// Postgres database driver
|
||
|
import _ "github.com/jinzhu/gorm/dialects/postgres"
|
||
|
|
||
|
// Db is the open Database
|
||
|
var Db *gorm.DB
|
||
|
|
||
|
// URL defines the structure of a shortened URL
|
||
|
type URL struct {
|
||
|
ID uint `gorm:"primary_key:auto_increment"`
|
||
|
CreatedAt time.Time
|
||
|
UpdatedAt time.Time
|
||
|
|
||
|
Short sql.NullString `gorm:"unique_index:short_url;not null"`
|
||
|
Long sql.NullString `gorm:"unique;not null"`
|
||
|
Hits sql.NullInt64
|
||
|
}
|
||
|
|
||
|
// InitDb opens a database connection and runs the auto migration
|
||
|
func InitDb(DBType, DBConnection string) {
|
||
|
var err error
|
||
|
Db, err = gorm.Open(DBType, DBConnection)
|
||
|
if err != nil {
|
||
|
log.Fatal("Could not open database:", err)
|
||
|
}
|
||
|
if os.Getenv("GIN_MODE") != "release" {
|
||
|
Db.LogMode(true)
|
||
|
}
|
||
|
|
||
|
Db.AutoMigrate(&URL{})
|
||
|
}
|