Skip to content
This repository has been archived by the owner on May 6, 2023. It is now read-only.

Commit

Permalink
feat(database_adapter): add database adapter
Browse files Browse the repository at this point in the history
  • Loading branch information
rpplusplus committed Jun 26, 2019
1 parent 44911e2 commit 11e043c
Showing 1 changed file with 54 additions and 0 deletions.
54 changes: 54 additions & 0 deletions database_adapter.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package main

import (
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)

type DataBaseAdapter struct {
url string
}

func NewDataBaseAdapter(url string) DataBaseAdapter {
d := DataBaseAdapter{}
d.url = url
return d
}

func (database DataBaseAdapter) GetURL() string {
return fmt.Sprintf("%s?charset=utf8mb4&parseTime=True&loc=Local", database.url)
}

func (database DataBaseAdapter) GetDB() (*gorm.DB) {
db, err := gorm.Open("mysql", database.GetURL())

if err != nil {
panic("failed to connect database")
}

return db
}

func (database DataBaseAdapter) migration() {
db := database.GetDB()
defer db.Close()

db.AutoMigrate(&BlockModel{})
}

func (database DataBaseAdapter) GetLatestVersion() uint64 {
db := database.GetDB()
defer db.Close()
result := BlockModel{}
db.Order("version desc").First(&result)

return result.Version
}

func (database DataBaseAdapter) SaveBlock(model BlockModel) {
db := database.GetDB()
defer db.Close()

db.Create(&model)
}

0 comments on commit 11e043c

Please sign in to comment.