package main
import (
"fmt"
"strings"
"gocms/utils"
"/driver/mysql"
"/gen"
"/gen/field"
"/gorm"
)
var MysqlConfig = + ":" + + "@(" + + ":" + + ")/" + + "?charset=utf8mb4&parseTime=True&loc=Local"
func main() {
generate(MysqlConfig, "article", "category", "comment", "profile", "user") // No table_name is passed to generate all data tables by default
}
func generate(sqlConf string, tables ...string) {
// Connect to the database
db, err := ((sqlConf))
if err != nil {
panic(("cannot establish db connection: %w", err))
}
// Generate an instance
g := ({
// Relative to the path when executing `go run`, the directory will be automatically created
OutPath: "./query",
// WithDefaultQuery generates the default query structure (used as a global variable), that is, the `Q` structure and its fields (each table model)
// WithoutContext generates code without context call restrictions for query
// WithQueryInterface generates query code in the form of interface (exportable), such as the `Where()` method returns an exportable interface type
Mode: | ,
// When the table field can be null value, the corresponding skeleton field uses a pointer type
FieldNullable: true, // generate pointer when field is nullable
// For fields whose default value of the table field is inconsistent with the zero value of the model structure field, if the field value is zero value when inserting data, the structure field must be of a pointer type to succeed, that is, the structure field generated under the `FieldCoverable:true` configuration.
// Because when inserting, if the field has zero value, it will be assigned a default value by GORM. If the default value of the field `age` table is 10, even if you explicitly set it to 0, it will be submitted by GORM to 10.
// If this field does not have the special need to assign a zero value during insertion mentioned above, it will be more convenient to use the field as a non-pointer type.
FieldCoverable: false, // generate pointer when field has default value, to fix problem zero value cannot be assign: /docs/#Default-Values
// The symbols of the numeric type of the model structure field are consistent with the table field. The `false` indicates that both use signed types
FieldSignable: false, // detect integer field's unsigned type, adjust generated data type
// Generate field index attributes of gorm tags
FieldWithIndexTag: false, // generate with gorm index tag
// Generate field type attributes of gorm tags
FieldWithTypeTag: true, // generate with gorm column type tag
})
// Set target db
(db)
// Custom field data type
// Unified number type is int64, compatible with protobuf
dataMap := map[string]func(detailType ) (dataType string){
"tinyint": func(detailType ) (dataType string) { return "int64" },
"smallint": func(detailType ) (dataType string) { return "int64" },
"mediumint": func(detailType ) (dataType string) { return "int64" },
"bigint": func(detailType ) (dataType string) { return "int64" },
"int": func(detailType ) (dataType string) { return "int64" },
}
// Execute before `ApplyBasic`
(dataMap)
// Customize the label of the model structure field
// Add the `string` attribute of the json tag of a specific field name, that is, when MarshalJSON, the field is converted from a numeric type to a string type
jsonField := (func(columnName string) (tagContent string) {
toStringField := `balance, `
if (toStringField, columnName) {
return columnName + ",string"
}
return columnName
})
// Define fields with non-default field names as automatic timestamps and soft delete fields;
// The default field name of automatic timestamp is: `updated_at`, `created_at, and the table field data type is: INT or DATETIME
// The default field name of soft delete is: `deleted_at`, and the table field data type is: DATETIME
autoUpdateTimeField := ("update_time", func(tag ) {
("column", "update_time")
("type", "int", "unsigned")
("autoUpdateTime")
return tag
})
autoCreateTimeField := ("create_time", func(tag ) {
("column", "create_time")
("type", "int", "unsigned")
("autoCreateTime")
return tag
})
softDeleteField := ("delete_time", "soft_delete.DeletedAt")
// Model customization option group
fieldOpts := []{jsonField, autoCreateTimeField, autoUpdateTimeField, softDeleteField}
// Method to create a model, generate the file in the query directory; the result created first will not be overwritten by the later creation
if tables != nil {
// Create the structure of the model and generate the file in the model directory; the result created first will be overwritten by the later created
// Create individual models here just to get the `*` type object for later model association operations
for _, table := range tables {
model := (table)
(model)
}
} else {
// Create all model files and overwrite the model of the same name created earlier
allModel := (fieldOpts...)
(allModel...)
}
// About how to create a model file with an association
// Can be used to specify foreign keys
//Score := ("score",
// append(
// fieldOpts,
// // user one-to-many address association, foreign key `uid` is in the address table
// (, "user", User, &{GORMTag: "foreignKey:UID"}),
// )...,
//)
()
}