gf icon indicating copy to clipboard operation
gf copied to clipboard

feat(cmd/gf): Add `NullFieldPattern` option for `gf gen dao` command (#4119)

Open wufeng5702 opened this issue 7 months ago • 0 comments

Overview

This PR introduces the NullFieldPattern configuration option for the gf gen dao command. This enhancement allows to specify database fields that should be generated as pointer types (*T) in entity structs when the fields have default NULL values in the database schema.

resolve #4119

Problem Solved

When working with database fields that allow NULL values:

  • Using base types (string, int etc.) in Go structs cannot distinguish between:
    • An explicit NULL value from the database
    • A zero-value (e.g., "" for string, 0 for int)
  • This causes ambiguity in application logic when zero-values are valid data

Solution

The NullFieldPattern option enables precise control over field type generation:

gfcli:
  gen:
    dao:
      - link: "mysql:root:12345678@tcp(127.0.0.1:3306)/test"
        nullFieldPattern:
          - "table_?"

Table Definition:

CREATE TABLE `table_user` (
    `id` int unsigned NOT NULL AUTO_INCREMENT COMMENT 'User ID',
    `password` varchar(45) NOT NULL COMMENT 'User Password',
    `score` decimal(10,2) unsigned DEFAULT NULL COMMENT 'Total score amount.',
    `create_at` datetime DEFAULT NULL COMMENT 'Created Time',
    `email` varchar(255) DEFAULT NULL COMMENT 'User Email',
    `status` int DEFAULT NULL COMMENT 'User Status',
    `height` float DEFAULT NULL COMMENT 'User Height',
    PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Result in generated entity:

// TableUser is the golang structure for table table_user.
type TableUser struct {
	Id       uint        `json:"id"       orm:"id"        ` // User ID
	Password string      `json:"password" orm:"password"  ` // User Password
	Score    float64     `json:"score"    orm:"score"     ` // Total score amount.
	CreateAt *gtime.Time `json:"createAt" orm:"create_at" ` // Created Time
	Email    *string     `json:"email"    orm:"email"     ` // User Email
	Status   *int        `json:"status"   orm:"status"    ` // User Status
	Height   *float64    `json:"height"   orm:"height"    ` // User Height
}

Key Features

  • Precise NULL Handling
  • Supports wildcard patterns: table_? (? is wildcard )
  • Fully forward compatible

wufeng5702 avatar May 28 '25 17:05 wufeng5702