Golang如何在SqlC中使用Validator?

huangapple go评论82阅读模式
英文:

Golang how to use Validator with SqlC

问题

有没有办法在不创建两个不同的结构体的情况下,将JSON验证[github.com/go-playground/validator/v10]和JSON查询[sqlc]结合起来?

我有以下表定义

CREATE TABLE table1 (
   columnName1 VARCHAR(200) NOT NULL PRIMARY KEY,
   columnName2 VARCHAR(200) NOT NULL
)

和以下查询

-- name: GetTable1:one
SELECT * FROM table1
WHERE columnName1 = $1 LIMIT 1;

执行SQLC后,会生成以下代码

...
// 
// This struct is created automatically by sqlC
//
type CreateTable1Params struct {
	Columnname1 string                `json:"columnname1"`
	Columnname2 string                `json:"columnname2"`
}

func (q *Queries) CreateTable1(ctx context.Context, arg CreateTable1Params ) (Table1, error) {
...
}

现在,我需要验证CreateTable1的REST参数,假设columnName2是必需的,所以我有一个类似下面的控制器包

table1Controller.go

import (
    ...
    validator "github.com/go-playground/validator/v10"
)

type Table1Controller struct {
	Validate   *validator.Validate
}

//
// This struct is created manually for validation
//
type InT1Param struct {
	ColumnName1 string `validate:"required" form:"columnName1" json:"columnName1" db:"columnname1"`
	ColumnName2 string `validate:"required" form:"columnName2" json:"columnName2" db:"columnname2" binding:"required"`
}

func (c *Table1Controller) validateInput(t1 InT1Param) error {
	err := service.Validate.Struct(t1)
	if err != nil {
		errStr := ""
		for _, mapErr := range err.(validator.ValidationErrors) {
			errStr = fmt.Sprintf("%s%s\n", errStr, mapErr.Translate(service.Translator))
		}
		return errors.New(errStr)
	}

	return nil
}

func (c *Table1Controller) Insert(ctx *gin.Context, dbQueries *dbModel.Queries, t1 InT1Param) error {
    err := c.validateInput(t1)
    if err != nil {
        return err

    inParam = dbModel.CreateTable1Param {
        Columnname1: t1.columnName1,
        Columnname2: t2.ColumnName2
    }

    outParam, err := dbQueries.CreateTable1(ctx, inParam)
    if err != nil {
        return err

    return nil
}
英文:

Is there any way to combine the JSON validation [github.com/go-playground/validator/v10] and the JSON Query [sqlc] without having to create two different structs?

I have the following table definition

CREATE TABLE table1 (
   columnName1 VARCHAR(200) NOT NULL PRIMARY KEY,
   columnName2 VARCHAR(200) NOT NULL
)

And the following query

-- name: GetTable1:one
SELECT * FROM table1
WHERE columnName1 = $1 LIMIT 1;

Executing SQLC the following code is generated

...
// 
// This struct is created automatically by sqlC
//
type CreateTable1Params struct {
	Columnname1 string                `json:"columnname1"`
	Columnname2 string                `json:"columnname2"`
}

func (q *Queries) CreateTable1(ctx context.Context, arg CreateTable1Params ) (Table1, error) {
...
}

Now, I need to validate the REST parameters for CreateTable1, let's say that columnName2 is required, so I have a controller package like the following

table1Controller.go

import (
    ...
    validator "github.com/go-playground/validator/v10"
)

type Table1Controller struct {
	Validate   *validator.Validate
}

//
// This struct is created manually for validation
//
type InT1Param struct {
	ColumnName1 string `validate:"required" form:"columnName1" json:"columnName1" db:"columnname1"`
	ColumnName2 string `validate:"required" form:"columnName2" json:"columnName2" db:"columnname2" binding="required"`
}

func (c *Table1Controller) validateInput(t1 InT1Param) error {
	err := service.Validate.Struct(t1)
	if err != nil {
		errStr := ""
		for _, mapErr := range err.(validator.ValidationErrors) {
			errStr = fmt.Sprintf("%s%s\n", errStr, mapErr.Translate(service.Translator))
		}
		return errors.New(errStr)
	}

	return nil
}

func (c *Table1Controller) Insert(ctx *gin.Context, dbQueries *dbModel.Queries, t1 InT1Param) error {
    err := c.validateInput(t1)
    if err != nil {
        return err

    inParam = dbModel.CreateTable1Param {
        Columnname1: t1.columnName1,
        Columnname2: t2.ColumnName2
    }

    outParam, err := dbQueries.CreateTable1(ctx, inParam)
    if err != nil {
        return err

    return nil
}

答案1

得分: 1

使用 sqlc.yaml 配置文件中的 overrides 键,我能够为列添加以下字段。

version: 2
sql:
  - schema: "./dbModel/migration/schema_20221008.sql"
    queries: "./dbModel/query/query.sql"
    engine: "postgresql"
    gen:
      go:
        package: "dbModel"
        out: "dbModel"
        emit_json_tags: true
        emit_db_tags: true
        emit_prepared_queries: false
        emit_interface: false
        emit_exact_table_names: false
        json_tags_case_style: camel
        overrides:
          - column: table1.column_name1
            go_struct_tag: validate:"required" x:"y,z"
          - column: table1.column_name2
            go_struct_tag: validate:"required"

这个配置为表生成了以下结构体:

type table1 struct {
	ColumnName1 string `db:"column_name1" json:"columnName1" validate:"required" x:"y,z"`
	ColumnName2 string `db:"column_name2" json:"columnName2" validate:"required"`
}

我无法更改 Param 结构体,但我猜想使用主结构体可以使用验证。

英文:

Using the overrides key of the sqlc.yaml configuration I was able to add the following fields to the columns.

version: 2
sql:
  - schema: "./dbModel/migration/schema_20221008.sql"
    queries: "./dbModel/query/query.sql"
    engine: "postgresql"
    gen:
      go:
        package: "dbModel"
        out: "dbModel"
        emit_json_tags: true
        emit_db_tags: true
        emit_prepared_queries: false
        emit_interface: false
        emit_exact_table_names: false
        json_tags_case_style: camel
        overrides:
          - column: table1.column_name1
            go_struct_tag: validate:"required" x:"y,z"
          - column: table1.column_name2
            go_struct_tag: validate:"required"

This configuration generated the following struct for the table:

type table1 struct {
	ColumnName1 string `db:"column_name1" json:"columnName1" validate:"required" x:"y,z"`
	ColumnName2 string `db:"column_name2" json:"columnName2" validate:"required"`

I wasn't able to change the Param structs but I guess using the table main struct use the validation.

huangapple
  • 本文由 发表于 2022年10月13日 10:50:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/74049973.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定