Documentation
¶
Overview ¶
Package dmlgen provides code generation templates and library code for sql/dml.
To generated the protocol buffer file $ protoc --gogo_out=Mgoogle/protobuf/timestamp.proto=github.com/gogo/protobuf/types:. --proto_path=/Users/kiri/GoPro/src/:/Users/kiri/GoPro/src/github.com/gogo/protobuf/protobuf/:. *.proto
TODO: Generate also protobuf code for https://github.com/twitchtv/twirp/wiki
Index ¶
- func Asset(name string) ([]byte, error)
- func AssetDir(name string) ([]string, error)
- func AssetInfo(name string) (os.FileInfo, error)
- func AssetNames() []string
- func GenerateJSON(fname string, g *bootstrap.Generator) (err error)
- func GenerateProto(path string) error
- func MustAsset(name string) []byte
- func RestoreAsset(dir, name string) error
- func RestoreAssets(dir, name string) error
- type Option
- func WithColumnAliasesFromForeignKeys(ctx context.Context, db dml.Querier) (opt Option)
- func WithCustomCode(marker, code string) (opt Option)
- func WithFlatbuffers(headerOptions ...string) (opt Option)
- func WithLoadColumns(ctx context.Context, db dml.Querier, tables ...string) (opt Option)
- func WithProtobuf(headerOptions ...string) (opt Option)
- func WithReferenceEntitiesByForeignKeys(ctx context.Context, db dml.Querier, ...) (opt Option)
- func WithTable(tableName string, columns ddl.Columns, actions ...string) (opt Option)
- func WithTableConfig(tableName string, opt *TableConfig) (o Option)
- type TableConfig
- type Tables
- type TypeDef
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Asset ¶
Asset loads and returns the asset for the given name. It returns an error if the asset could not be found or could not be loaded.
func AssetDir ¶
AssetDir returns the file names below a certain directory embedded in the file by go-bindata. For example if you run go-bindata on data/... and data contains the following hierarchy:
data/
foo.txt
img/
a.png
b.png
then AssetDir("data") would return []string{"foo.txt", "img"} AssetDir("data/img") would return []string{"a.png", "b.png"} AssetDir("foo.txt") and AssetDir("notexist") would return an error AssetDir("") will return []string{"data"}.
func AssetInfo ¶
AssetInfo loads and returns the asset info for the given name. It returns an error if the asset could not be found or could not be loaded.
func AssetNames ¶
func AssetNames() []string
AssetNames returns the names of the assets. nolint: deadcode
func GenerateJSON ¶
GenerateJSON creates the easysjon code for a specific file or a whole directory. argument `g` can be nil.
func GenerateProto ¶
GenerateProto searches all *.proto files in the given path and calls protoc to generate the Go source code.
func MustAsset ¶
MustAsset is like Asset but panics when Asset would return an error. It simplifies safe initialization of global variables. nolint: deadcode
func RestoreAsset ¶
RestoreAsset restores an asset under the given directory
func RestoreAssets ¶
RestoreAssets restores an asset under the given directory recursively
Types ¶
type Option ¶
type Option struct {
// contains filtered or unexported fields
}
Option represents a sortable option for the NewTables function. Each option function can be applied in a mixed order.
func WithColumnAliasesFromForeignKeys ¶
WithColumnAliasesFromForeignKeys extracts similar column names from foreign key definitions. For the list of tables and their primary/unique keys, this function searches the foreign keys to other tables and uses the column name as the alias. For example the table `customer_entity` and its PK column `entity_id` has a foreign key in table `sales_order` whose name is `customer_id`. When generation code for customer_entity, the column entity_id can be used additionally with the name customer_id, hence customer_id is the alias.
func WithCustomCode ¶
WithCustomCode inserts at the marker position your custom Go code. For available markers search the .go.tpl files for the function call `CustomCode`. An example got written in TestGenerate_Tables_Protobuf_Json. If the marker does not exists or has a typo, no error gets reported and no code gets written.
func WithFlatbuffers ¶
WithFlatbuffers enables flatbuffers (FBS) as a serialization method. Argument headerOptions is optional.
func WithLoadColumns ¶
WithLoadColumns queries the information_schema table and loads the column definition of the provided `tables` slice.
func WithProtobuf ¶
WithProtobuf enables protocol buffers as a serialization method. Argument headerOptions is optional.
func WithReferenceEntitiesByForeignKeys ¶
func WithReferenceEntitiesByForeignKeys(ctx context.Context, db dml.Querier, structFieldNameMapperFn func(string) string) (opt Option)
WithReferenceEntitiesByForeignKeys analyses the foreign keys which points to a table and adds them as a struct field name. For example: customer_address_entity.parent_id is a foreign key to customer_entity.entity_id hence the generated struct CustomerEntity has a new field which gets named CustomerAddressEntityCollection, pointing to type CustomerAddressEntityCollection. structFieldNameMapperFn can be nil, if so the name of the Go collection type gets used as field name.
func WithTable ¶
WithTable sets a table and its columns. Allows to overwrite a table fetched with function WithLoadColumns. Argument `actions` can only be set to "overwrite".
func WithTableConfig ¶
func WithTableConfig(tableName string, opt *TableConfig) (o Option)
WithTableConfig applies options to a table, identified by the table name used as map key. Options are custom struct or different encoders.
type TableConfig ¶
type TableConfig struct {
// Encoders add method receivers for, each struct, compatible with the
// interface declarations in the various encoding packages. Supported
// encoder names are: json, binary, and protobuf. Text includes JSON. Binary
// includes Gob.
Encoders []string
// StructTags enables struct tags proactively for the whole struct. Allowed
// values are: bson, db, env, json, protobuf, toml, yaml and xml. For bson,
// json, yaml and xml the omitempty attribute has been set. If you need a
// different struct tag for a specifiv column you must set the option
// CustomStructTags.
StructTags []string
// CustomStructTags allows to specify custom struct tags for a specific
// column. The slice must be balanced, means index i sets to the column name
// and index i+1 to the desired struct tag.
// []string{"column_a",`json: ",omitempty"`,"column_b","`xml:,omitempty`"}
CustomStructTags []string // balanced slice
// Comment adds custom comments to each struct type. Useful when relying on
// 3rd party JSON marshaler code generators like easyjson or ffjson. If
// comment spans over multiple lines each line will be checked if it starts
// with the comment identifier (//). If not, the identifier will be
// prepended.
Comment string
// ColumnAliases specifies different names used for a column. For example
// customer_entity.entity_id can also be sales_order.customer_id, hence a
// Foreign Key. The alias would be just: entity_id:[]string{"customer_id"}.
ColumnAliases map[string][]string // key=column name value a list of aliases
// UniquifiedColumns specifies columns which are non primary/unique key one
// but should have a dedicated function to extract their unique primitive
// values as a slice. Not allowed are text, blob and binary.
UniquifiedColumns []string
// PrivateFields list struct field names which should be private to avoid
// accidentally leaking through encoders. Appropriate getter/setter methods
// get generated.
PrivateFields []string
// contains filtered or unexported fields
}
TableConfig used in conjunction with WithTableConfig to apply different configurations for a generated struct and its struct collection.
type Tables ¶
type Tables struct {
Package string // Name of the package
PackageImportPath string // Name of the package
ImportPaths []string
ImportPathsTesting []string
// Tables uses the table name as map key and the table description as value.
Tables map[string]*table
template.FuncMap
DisableFileHeader bool
DisableTableSchemas bool
// Serializer defines the de/serializing method to use. Either
// `empty`=default (none) or proto=protocol buffers or fbs=flatbuffers. JSON
// marshaling is not affected with this config. Only one serializer can be
// defined because some Go types depends on the types of serializer. E.g.
// protobuf cannot use int16/int8 whereas in flatbuffers they are available.
// Using a common denominator for every serializer like an int32 can cause
// data loss when communicating with the database table which has different
// (smaller) column types than an int32.
Serializer string
// SerializerHeaderOptions defines custom headers to use in the .proto or .fbs file.
// For proto, sane defaults are available.
SerializerHeaderOptions []string
// TestSQLDumpGlobPath contains the path and glob pattern to load a SQL dump
// containing the table schemas to run integration tests. If empty no dumps
// get loaded and the test program assumes that the tables already exists.
TestSQLDumpGlobPath string
// contains filtered or unexported fields
}
Tables can generated Go source for for database tables once correctly configured.
func NewTables ¶
NewTables creates a new instance of the SQL table code generator. The order of the applied options does not matter as they are getting sorted internally.
func (*Tables) GenerateGo ¶
GenerateGo writes the Go source code into `w` and the test code into wTest.
type TypeDef ¶
type TypeDef struct {
GoUNull string // unsigned null
GoUNotNull string // unsigned not null
GoNull string // A go type which can be null/nil
GoNotNull string // A usually native Go primitive type
SerializerUNull string
SerializerUNotNull string
SerializerNull string
SerializerNotNull string
}
TypeDef used in variable `mysqlTypeToGo` to map a MySQL/MariaDB type to its appropriate Go and serializer type. Those types are getting printed in the generated files.