graphql 从数据库查询

This commit is contained in:
2023-11-20 22:23:48 +08:00
parent a22c4e8bf6
commit e43fde4116
5 changed files with 96 additions and 51 deletions

View File

@@ -2,50 +2,70 @@ package models
import (
"fmt"
"strings"
"github.com/graphql-go/graphql"
"github.com/graphql-go/graphql/language/ast"
)
func NewSchema() (graphql.Schema, error) {
user := graphql.NewObject(graphql.ObjectConfig{
Name: "User",
Fields: graphql.Fields{
"id": &graphql.Field{Type: graphql.Int},
"name": &graphql.Field{Type: graphql.String},
"age": &graphql.Field{Type: graphql.Int},
"info": &graphql.Field{Type: graphql.String},
"price": &graphql.Field{Type: graphql.Float},
"avatar": &graphql.Field{Type: graphql.String},
"id": &graphql.Field{Type: graphql.Int},
"user_name": &graphql.Field{Type: graphql.String},
"avatar": &graphql.Field{Type: graphql.String},
"rank": &graphql.Field{Type: graphql.String},
"price": &graphql.Field{Type: graphql.Float},
"create_time": &graphql.Field{Type: graphql.DateTime},
"update_time": &graphql.Field{Type: graphql.DateTime},
},
})
users := &graphql.Field{
Type: graphql.NewList(user),
Args: graphql.FieldConfigArgument{
"id": &graphql.ArgumentConfig{
Type: graphql.Int,
},
"id": &graphql.ArgumentConfig{Type: graphql.Int},
"user_name": &graphql.ArgumentConfig{Type: graphql.String},
"avatar": &graphql.ArgumentConfig{Type: graphql.String},
"rank": &graphql.ArgumentConfig{Type: graphql.String},
"create_time": &graphql.ArgumentConfig{Type: graphql.DateTime},
"update_time": &graphql.ArgumentConfig{Type: graphql.DateTime},
},
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
fmt.Println("p.Args:", p.Args)
return []interface{}{
map[string]interface{}{
"id": 1,
"name": "user1",
"age": 10,
"info": "info",
"price": 1.1,
"avatar": "",
},
map[string]interface{}{
"id": 2,
"name": "user2",
"age": 20,
"info": "info",
"price": 2.2,
"avatar": "",
},
}, nil
var fields []string
requestedFields := p.Info.FieldASTs[0].SelectionSet.Selections
for _, field := range requestedFields {
fieldAST, ok := field.(*ast.Field)
if ok {
fields = append(fields, fieldAST.Name.Value)
}
}
fields_str := strings.Join(fields, ",")
var where []string
if p.Args["id"] != nil {
where = append(where, fmt.Sprintf("id=%d", p.Args["id"]))
}
if p.Args["user_name"] != nil {
where = append(where, fmt.Sprintf("user_name='%s'", p.Args["user_name"]))
}
// 筛选条件
where_str := strings.Join(where, " AND ")
fmt.Println(where_str)
var query strings.Builder
query.WriteString(fmt.Sprintf("SELECT %s FROM web_member WHERE %s LIMIT %s", fields_str, where_str, "10"))
fmt.Println(query.String())
var users []User
if err := connection.Select(&users, query.String()); err != nil {
fmt.Println("获取用户列表失败", err)
return nil, err
}
fmt.Println(users)
return users, nil
},
}
@@ -76,6 +96,9 @@ func NewSchema() (graphql.Schema, error) {
},
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
fmt.Println("p.Args:", p.Args)
//connection.Query("SELECT ")
return []interface{}{
map[string]interface{}{
"id": 1,

View File

@@ -10,14 +10,29 @@ import (
"time"
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
)
var connection *sqlx.DB
var connectionx *sql.DB
func init() {
var err error
user := Viper.Get("mysql.user").(string)
password := Viper.Get("mysql.password").(string)
host := Viper.Get("mysql.host").(string)
port := Viper.Get("mysql.port").(int)
database := Viper.Get("mysql.database").(string)
connection, err = sqlx.Connect("mysql", fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", user, password, host, port, database))
if err != nil {
log.Fatalln("连接数据库失败", err)
}
}
type MysqlConnection struct {
Database *sql.DB
}
var connection *sql.DB
// 初始化数据库连接
func (m *MysqlConnection) Init() (err error) {
user := Viper.Get("mysql.user").(string)
@@ -26,12 +41,12 @@ func (m *MysqlConnection) Init() (err error) {
port := Viper.Get("mysql.port").(int)
database := Viper.Get("mysql.database").(string)
sqlconf := user + ":" + password + "@tcp(" + host + ":" + strconv.Itoa(port) + ")/" + database + "?charset=utf8mb4&parseTime=True&loc=Local"
connection, err = sql.Open("mysql", sqlconf) // 连接数据库
m.Database, err = sql.Open("mysql", sqlconf) // 连接数据库
if err != nil {
log.Println("连接数据库失败", err)
return
}
m.Database = connection
connectionx = m.Database
return
}
@@ -83,11 +98,12 @@ func (m *MysqlConnection) GetImages(page int, size int) (images []byte, err erro
}
type User struct {
Id int `json:"id"`
UserName string `json:"user_name"`
Avatar string `json:"avatar"`
CreateTime time.Time `json:"create_time"`
UpdateTime time.Time `json:"update_time"`
ID int `json:"id" db:"id"`
UserName string `json:"user_name" db:"user_name"`
Avatar string `json:"avatar" db:"avatar"`
Rank string `json:"rank" db:"rank"`
CreateTime time.Time `json:"create_time" db:"create_time"`
UpdateTime time.Time `json:"update_time" db:"update_time"`
}
// 获取一组用户信息
@@ -98,7 +114,7 @@ func QueryUserList(id_list []int) (users []User) {
return
}
idstr := strings.Trim(strings.Replace(fmt.Sprint(id_list), " ", ",", -1), "[]")
rows, err := connection.Query("SELECT id, user_name, avatar, update_time, create_time FROM web_member WHERE id IN (" + idstr + ") LIMIT " + strconv.Itoa(count))
rows, err := connectionx.Query("SELECT id, user_name, avatar, update_time, create_time FROM web_member WHERE id IN (" + idstr + ") LIMIT " + strconv.Itoa(count))
if err != nil {
log.Println("获取用户列表失败", err)
return
@@ -106,7 +122,7 @@ func QueryUserList(id_list []int) (users []User) {
defer rows.Close()
for rows.Next() {
var u User
rows.Scan(&u.Id, &u.UserName, &u.Avatar, &u.UpdateTime, &u.CreateTime)
rows.Scan(&u.ID, &u.UserName, &u.Avatar, &u.UpdateTime, &u.CreateTime)
u.UpdateTime = u.UpdateTime.UTC()
u.CreateTime = u.CreateTime.UTC()
users = append(users, u)
@@ -130,7 +146,7 @@ func QueryArticleList(id_list []int) (articles []Article) {
return
}
idstr := strings.Trim(strings.Replace(fmt.Sprint(id_list), " ", ",", -1), "[]")
rows, err := connection.Query("SELECT id, title, tags, update_time, create_time FROM web_article WHERE id IN (" + idstr + ") LIMIT " + strconv.Itoa(count))
rows, err := connectionx.Query("SELECT id, title, tags, update_time, create_time FROM web_article WHERE id IN (" + idstr + ") LIMIT " + strconv.Itoa(count))
if err != nil {
log.Println("获取文章列表失败", err)
return