Golang Basic-Postgresql-ORM 프레임워크github.com/go-pg/pg 학습3(QueryOne,Query,Select 사용법)
10675 단어 Go 베이스gin/pg(golang)
Golang Basic-Postgresql-ORM 프레임워크github.com/go-pg/pg 학습1(데이터베이스 연결, 창설, 삭제표)
Golang Basic-Postgresql-ORM 프레임워크github.com/go-pg/pg 학습2
데이터 준비
package main
import (
"fmt"
"github.com/go-pg/pg"
"github.com/go-pg/pg/orm"
_ "github.com/lib/pq"
)
const (
host = "localhost"
port = 5432
user = "wyfzhiliao"
password = "wyfzhiliao"
dbname = "go"
)
func connet() *pg.DB{
db:=pg.Connect(&pg.Options{
User:user,
Password:password,
Database:dbname,
})
var n int
_,err:=db.QueryOne(pg.Scan(&n),"SELECT 1")
if err != nil{
panic(err)
}
return db
}
type User struct {
Id int64
Name string
Emails []string
tableName struct{} `sql:"users"`
}
type Story struct {
Id int64
Title string
AuthorId int64
Author *User
tableName struct{} `sql:"storys"`
}
func (s Story) String() string {
return fmt.Sprintf("Story", s.Id, s.Title, s.Author)
}
func (u User) String() string {
return fmt.Sprintf("User(%d %s %v)", u.Id, u.Name, u.Emails)
}
func CreateTabel(db *pg.DB) error{
for _,model:= range []interface{}{&User{}, &Story{}}{
err:=db.CreateTable(model,&orm.CreateTableOptions{
IfNotExists:true,
FKConstraints:true,
})
if err!= nil{
return err
}
}
return nil
}
// user
func CreateUser(db *pg.DB, user *User) (orm.Result,error) {
res, err := db.QueryOne(user, `
INSERT INTO users (name, emails) VALUES (?name, ?emails)
RETURNING id
`, user)
return res,err
}
// story
func CreateStory(db *pg.DB, story *Story) error {
_, err := db.QueryOne(story, `
INSERT INTO storys (title, author_id) VALUES (?title, ?author_id)
RETURNING id
`, story)
return err
}
func main() {
db:=connet()
err := CreateTabel(db)
if err != nil {
panic(err)
}
user1 := &User{
Name: "admin",
Emails: []string{"admin1@admin", "admin2@admin"},
}
res,err := CreateUser(db, user1)
if err != nil {
panic(err)
}
fmt.Println(res)
res,err = CreateUser(db, &User{
Name: "root",
Emails: []string{"root1@root", "root2@root"},
})
if err != nil {
panic(err)
}
fmt.Println(res)
story1 := &Story{
Title: "Cool story",
AuthorId: user1.Id,
}
err = CreateStory(db, story1)
}
상기 코드를 실행하면users,storys표를 생성하고 표에 관련 데이터를 삽입할 수 있습니다
go=# select * from storys;
id | title | author_id
----+------------+-----------
1 | Cool story | 1
(1 row)
go=# select * from users;
id | name | emails
----+-------+----------------------------------
1 | admin | ["admin1@admin", "admin2@admin"]
2 | root | ["root1@root", "root2@root"]
(2 rows)
go=#
주의해야 할 것은 우리가users표 데이터,storys표 데이터를 추가하는 것은 다음과 같은 방식을 통해 이루어진 것이고 두 번째 블로그에서
db.Insert
,또는db.Model(user4,user5).Insert()
방식으로 추가한 것이기 때문에users표를 추가할 때RETURNING id
가 있어storys표에 키를 생성할 수 있음을 주의해야 한다.db.QueryOne(user, `
INSERT INTO users (name, emails) VALUES (?name, ?emails)
RETURNING id
`, user)
db.QueryOne(story, `
INSERT INTO storys (title, author_id) VALUES (?title, ?author_id)
RETURNING id
`, story)
QueryOne, Query 사용 방법
QueryOne users
func GetUsers(db *pg.DB) ([]User, error) {
var users []User
_, err := db.Query(&users, `SELECT * FROM users`)
return users, err
}
users, err := GetUsers(db)
if err != nil {
panic(err)
}
fmt.Println(users)
출력 결과는 다음과 같습니다.
[User(1 admin [admin1@admin admin2@admin]) User(2 root [root1@root root2@root])]
Query ID users
user, err := GetUser(db, 1)
if err != nil {
panic(err)
}
fmt.Println(user)
func GetUser(db *pg.DB, id int64) (*User, error) {
var user User
_, err := db.QueryOne(&user, `SELECT * FROM users WHERE id = ?`, id)
return &user, err
}
출력은 다음과 같습니다.
User(1 admin [admin1@admin admin2@admin])
Query IDS users
func GetUsersByIds(db *pg.DB, ids []int64) ([]User, error) {
var users []User
_, err := db.Query(&users, `SELECT * FROM users WHERE id IN (?)`, pg.In(ids))
return users, err
}
ids:=[]int64{1,2}
usersByIds,err :=GetUsersByIds(db,ids)
if err != nil {
panic(err)
}
fmt.Println(usersByIds)
출력은 다음과 같습니다.
[User(1 admin [admin1@admin admin2@admin]) User(2 root [root1@root root2@root])]
select
Select book by primary key:
book := &Book{Id: 1}
err := db.Select(book)
// SELECT "book"."id", "book"."title", "book"."text"
// FROM "books" WHERE id = 1
Same more explicitly:
book := new(Book)
err := db.Model(book).Where("id = ?", 1).Select()
// SELECT "book"."id", "book"."title", "book"."text"
// FROM "books" WHERE id = 1
Select only book title and text:
err := db.Model(book).Column("title", "text").Where("id = ?", 1).Select()
// SELECT "title", "text"
// FROM "books" WHERE id = 1
Select only book title and text into variables:
var title, text string
err := db.Model((*Book)(nil)).
Column("title", "text").
Where("id = ?", 1).
Select(&title, &text)
// SELECT "title", "text"
// FROM "books" WHERE id = 1
Select book using WHERE … AND …:
err := db.Model(book).
Where("id > ?", 100).
Where("title LIKE ?", "my%").
Limit(1).
Select()
// SELECT "book"."id", "book"."title", "book"."text"
// FROM "books"
// WHERE (id > 100) AND (title LIKE 'my%')
// LIMIT 1
Select book using WHERE … OR …:
err := db.Model(book).
Where("id > ?", 100).
WhereOr("title LIKE ?", "my%").
Limit(1).
Select()
// SELECT "book"."id", "book"."title", "book"."text"
// FROM "books"
// WHERE (id > 100) OR (title LIKE 'my%')
// LIMIT 1
Select book user WHERE … AND (… OR …):
err := db.Model(book).
Where("title LIKE ?", "my%").
WhereGroup(func(q *orm.Query) (*orm.Query, error) {
q = q.WhereOr("id = 1").
WhereOr("id = 2")
return q, nil
}).
Limit(1).
Select()
// SELECT "book"."id", "book"."title", "book"."text"
// FROM "books"
// WHERE (title LIKE 'my%') AND (id = 1 OR id = 2)
// LIMIT 1
Select first 20 books:
var books []Book
err := db.Model(&books).Order("id ASC").Limit(20).Select()
// SELECT "book"."id", "book"."title", "book"."text"
// FROM "books"
// ORDER BY id ASC LIMIT 20
Count books:
count, err := db.Model((*Book)(nil)).Count()
// SELECT count(*) FROM "books"
Select book ids as PostgreSQL array:
var ids []int
err := db.Model((*Book)(nil)).ColumnExpr("array_agg(id)").Select(pg.Array(&ids))
// SELECT array_agg(id) FROM "books"
Select by multiple ids:
ids := []int{1, 2, 3}
err := db.Model((*Book)(nil)).
Where("id in (?)", pg.In(ids)).
Select()
// SELECT * FROM books WHERE id IN (1, 2, 3)
ID를 통한 질의
func main() {
db:=connet()
user:=User{
Id:1,
}
err:=db.Select(&user)
if err!= nil{
panic(err)
}
fmt.Println(user)
}
출력은 다음과 같습니다.
User(1 admin [admin1@admin admin2@admin])
Apply에서 Where 필터 기준 조회 추가
func main() {
db:=connet()
var name string
name = "admin"
filter := func(q *orm.Query) (*orm.Query, error) {
if name == "admin" {
q = q.Where("name = ?", "admin")
}
if name == "root" {
q = q.Where("name = ?", "root")
}
return q, nil
}
var user []User
err := db.Model(&user).
Apply(filter).
Select()
if err != nil {
panic(err)
}
fmt.Println(user)
}
출력 결과는 다음과 같습니다.
[User(1 admin [admin1@admin admin2@admin])]
name = "admin"을name = "root"출력으로 바꾸면 결과는 다음과 같습니다.
[User(2 root [root1@root root2@root])]
name = "admin"을name = "sdfsfsf"출력으로 바꾸면 다음과 같습니다.
[User(1 admin [admin1@admin admin2@admin]) User(2 root [root1@root root2@root])]
모든 레코드 조회
func main() {
db:=connet()
var user []User
db.Model(&user).Column("id","name",).
OrderExpr("id ASC").Select()
fmt.Println(user)
}
출력 결과는 다음과 같습니다.
[User(1 admin []) User(2 root [])]
질의 레코드의 모든 ID 값 가져오기
func main() {
db:=connet()
var ids []int
err:=db.Model(&User{}).ColumnExpr("array_agg(id)").Select(pg.Array(&ids))
if err!=nil{
panic(err)
}
fmt.Println(ids)
}
출력은 다음과 같습니다.
[1 2]
WhereGroup
func main() {
db:=connet()
var users []User
err:=db.Model(&users).WhereGroup(func(query *orm.Query) (*orm.Query, error) {
query = query.WhereOr("id=1").WhereOr("id=2")
return query,nil
}).Where("name is not null").Select()
if err!= nil{
panic(err)
}
fmt.Println(users)
}
출력은 다음과 같습니다.
[User(1 admin [admin1@admin admin2@admin]) User(2 root [root1@root root2@root])]
WhereIn
func main() {
db:=connet()
var users []User
err:=db.Model(&users).WhereIn("id IN (?)",1,3).Select()
if err!= nil{
panic(err)
}
fmt.Println(users)
}
출력은 다음과 같습니다.
[User(1 admin [admin1@admin admin2@admin])]