012-Go ORMフレームワークのGormテスト

3542 ワード

1:参照:https://github.com/jinzhu/gorm
2:データベーススクリプト(pg)
--
create table posts(
    id            serial primary key,
    content        text,
    author        varchar(100),
    create_time    timestamptz
);

create table comments(
    id            serial primary key,
    content        text,
    author        varchar(100),
    post_id        int references posts(id),
    create_time    timestamptz
);

3:posts.go
package posts

import(
	"fmt"
	"github.com/jinzhu/gorm"
	_"github.com/lib/pq"
	"time"
)


type Comment struct{
	ID			int 		
	Content		string		`sql:"not null"`
	Author		string		`sql:"not null"`
	PostId		int 		`sql:"post_id"`
	CreateTime	time.Time	`sql:"create_time"`
}

type Post struct{
	ID			int 		
	Content		string		`sql:"not null"`
	Author		string		`sql:"not null"`
	CreateTime	time.Time	`sql:"create_time"`
	Comments	[]Comment
}


const(
    host = "192.168.72.128"
    port = 5432
    user = "test"
    password = "test"
    dbname = "testdb"
)

var Db *gorm.DB

func init(){
	var err error
	
	psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+
		"password=%s dbname=%s sslmode=disable",host, port, user, password, dbname)

	Db, err = gorm.Open("postgres", psqlInfo)
	if err != nil{
		panic(err)
	}

	Db.AutoMigrate(&Post{}, &Comment{})
}

func (post *Post) CreatePost() error{
	return Db.Create(post).Error
}

func (comment *Comment) CreateComment(post *Post) error{
	return Db.Model(post).Association("Comments").Append(comment).Error
}

func (post *Post) GetComments() (comments []Comment, err error){
	Db.Where("author=$1", " ").First(post)
	err = Db.Model(&post).Related(&comments).Error
	return
}

 4:main.go
package main

import(
	"fmt"
	"time"
	"Chapter02/posts"
)

func main(){
	post := posts.Post{
		Content:"Hello go!",
		Author:" ",
		CreateTime:	time.Now(),
	}

	fmt.Println(post)

	err := post.CreatePost()
	if err!=nil{
		panic(err)
	}
	fmt.Println(post)

	comment := posts.Comment{
		Content:" ",
		Author:" ",
		CreateTime:	time.Now(),
	}
	err = comment.CreateComment(&post)
	if err != nil{
		panic(err)
	}

	post = posts.Post{}
	comments, err := post.GetComments()
	if err != nil{
		panic(err)
	}
	for _,p :=  range comments{
		fmt.Printf("%s-%s
", p.Author,p.Content) } }