Skip to content

Commit

Permalink
xinliangnote#17 add init.sh
Browse files Browse the repository at this point in the history
  • Loading branch information
xinliangnote committed Mar 13, 2021
1 parent 49ccaf9 commit 36ef904
Show file tree
Hide file tree
Showing 7 changed files with 159 additions and 15 deletions.
11 changes: 11 additions & 0 deletions cmd/init/db/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
## 执行命令
在根目录下执行脚本:`./scripts/init.sh addr user pass name`
- addr:数据库地址,例如:127.0.0.1:3306
- user:账号,例如:root
- pass:密码,例如:root
- name:数据库名称,例如:go_gin_api

例如:
```
./scripts/init.sh 127.0.0.1:3306 root root go_gin_api
```
53 changes: 53 additions & 0 deletions cmd/init/db/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package main

import (
"flag"
"log"
"strings"

"github.com/xinliangnote/go-gin-api/cmd/init/db/mysql"
)

var (
dbAddr string
dbUser string
dbPass string
dbName string
)

func init() {
addr := flag.String("addr", "", "请输入 db 地址,例如:127.0.0.1:3306\n")
user := flag.String("user", "", "请输入 db 用户名\n")
pass := flag.String("pass", "", "请输入 db 密码\n")
name := flag.String("name", "", "请输入 db 名称\n")

flag.Parse()

dbAddr = *addr
dbUser = *user
dbPass = *pass
dbName = strings.ToLower(*name)
}

func main() {
// 初始化 DB
db, err := mysql.New(dbAddr, dbUser, dbPass, dbName)
if err != nil {
log.Fatal("new db err", err)
}

defer func() {
if err := db.DbClose(); err != nil {
log.Println("db close err", err)
}
}()

// 创建 user_demo 表
err = db.GetDb().Exec(mysql.CreateUserDemoTableSql()).Error
if err != nil {
log.Println("create user_demo table err", err)
return
}

log.Println("create user_demo table success")
}
64 changes: 64 additions & 0 deletions cmd/init/db/mysql/mysql.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package mysql

import (
"fmt"

"github.com/pkg/errors"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"gorm.io/gorm/schema"
)

var _ Repo = (*dbRepo)(nil)

type Repo interface {
i()
GetDb() *gorm.DB
DbClose() error
}

type dbRepo struct {
DbConn *gorm.DB
}

func New(dbAddr, dbUser, dbPass, dbName string) (Repo, error) {
dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=%t&loc=%s",
dbUser,
dbPass,
dbAddr,
dbName,
true,
"Local")

db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
NamingStrategy: schema.NamingStrategy{
SingularTable: true,
},
Logger: logger.Default.LogMode(logger.Info), // 日志配置
})

if err != nil {
return nil, errors.Wrap(err, fmt.Sprintf("[db connection failed] Database name: %s", dbName))
}

db.Set("gorm:table_options", "CHARSET=utf8mb4")

return &dbRepo{
DbConn: db,
}, nil
}

func (d *dbRepo) i() {}

func (d *dbRepo) GetDb() *gorm.DB {
return d.DbConn
}

func (d *dbRepo) DbClose() error {
sqlDB, err := d.DbConn.DB()
if err != nil {
return err
}
return sqlDB.Close()
}
27 changes: 27 additions & 0 deletions cmd/init/db/mysql/table_user_demo.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package mysql

//CREATE TABLE `user_demo` (
//`id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键',
//`user_name` varchar(32) NOT NULL DEFAULT '' COMMENT '用户名',
//`nick_name` varchar(100) NOT NULL DEFAULT '' COMMENT '昵称',
//`mobile` varchar(20) NOT NULL DEFAULT '' COMMENT '手机号',
//`is_deleted` tinyint(1) NOT NULL DEFAULT '-1' COMMENT '是否删除 1:是 -1:否',
//`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
//`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
//PRIMARY KEY (`id`)
//) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户Demo表';

func CreateUserDemoTableSql() (sql string) {
sql = "CREATE TABLE `user_demo` ("
sql += "`id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键',"
sql += "`user_name` varchar(32) NOT NULL DEFAULT '' COMMENT '用户名',"
sql += "`nick_name` varchar(100) NOT NULL DEFAULT '' COMMENT '昵称',"
sql += "`mobile` varchar(20) NOT NULL DEFAULT '' COMMENT '手机号',"
sql += "`is_deleted` tinyint(1) NOT NULL DEFAULT '-1' COMMENT '是否删除 1:是 -1:否',"
sql += "`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',"
sql += "`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',"
sql += "PRIMARY KEY (`id`)"
sql += ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户Demo表';"

return
}
5 changes: 0 additions & 5 deletions init/README.md

This file was deleted.

10 changes: 0 additions & 10 deletions init/db/tables.sql

This file was deleted.

4 changes: 4 additions & 0 deletions scripts/init.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
#!/bin/bash
printf "\nInit db\n\n"
time go run -v ./cmd/init/db/main.go -addr $1 -user $2 -pass $3 -name $4
printf "\nDone.\n\n"

0 comments on commit 36ef904

Please sign in to comment.