Skip to content

Instantly share code, notes, and snippets.

@youknowcast
Last active March 26, 2021 04:26
Show Gist options
  • Save youknowcast/1feefeeab8cd03ef37108cacd5dd9206 to your computer and use it in GitHub Desktop.
Save youknowcast/1feefeeab8cd03ef37108cacd5dd9206 to your computer and use it in GitHub Desktop.
ULID と JSON 型の動作確認スクリプト
version: '3'
services:
mysql:
build: ./mysql/ #Dockerfileからビルドすることを示す
volumes:
- ./mysql/db:/docker-entrypoint-initdb.d #初期データ
environment:
- MYSQL_ROOT_PASSWORD=root #環境変数
ports:
- "3306:3306"
FROM mysql
#ポートを開ける
EXPOSE 3306
#MySQL設定ファイルをイメージ内にコピー
ADD ./my.cnf /etc/mysql/conf.d/my.cnf
#docker runに実行される
CMD ["mysqld"]
package main
import (
"encoding/json"
"fmt"
"math/rand"
"time"
"github.com/oklog/ulid/v2"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
func ExampleULID() string {
t := time.Unix(1000000, 0)
entropy := ulid.Monotonic(rand.New(rand.NewSource(t.UnixNano())), 0)
id := ulid.MustNew(ulid.Timestamp(t), entropy).String()
fmt.Println(id)
// Output: 0000XSNJG0MQJHBF4QX1EFD6Y3
return id
}
// Validation 用 JSON 定義
type SampleJson struct {
CompanyId string
UserId int
Comment string
}
// DAO
type JsonDataTest struct {
// gorm.Model
Id string
Jdoc string // DDL 上は type: JSON で定義
}
func QueryMySQL(id string, data string) {
dsn := "root:root@tcp(127.0.0.1:3306)/test_json_data?charset=utf8&parseTime=True&loc=Local"
db, _ := gorm.Open(mysql.Open(dsn), &gorm.Config{})
psmt := JsonDataTest{
Id: id,
Jdoc: data,
}
result := db.Create(&psmt)
if result.Error != nil {
return
}
// 取り出してみる
var target JsonDataTest
result2 := db.Where("id = ?", psmt.Id).Last(&target)
if result2.Error != nil {
return
}
sj := SampleJson{}
json.Unmarshal([]byte(target.Jdoc), &sj)
fmt.Printf("%v\n", sj)
}
func main() {
// ulid
id := ExampleULID()
// mysql
sampleJson, _ := json.Marshal(&SampleJson{
CompanyId: "test Inc.",
UserId: 9999,
Comment: "hogehoge",
})
QueryMySQL(id, string(sampleJson))
}
## launch docker
$ docker-compose up -d
## connect to db
$ mysql -u root -h 127.0.0.1 --port=3306 -p
## create
CREATE DATABASE test_json_data;
CREATE TABLE json_data_test (id char(26), jdoc JSON);
## run
$ go run main.go
[mysqld]
character-set-server=utf8
[mysql]
default-character-set=utf8
[client]
default-character-set=utf8
@youknowcast
Copy link
Author

正直,charset は utf8mb4 にしないのは自分でもよくわからないけど,検証用にどっかのサイトのコピペで作ったので・・

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment