{"modulePath":"github.com/weiwolves/pkg","version":"v0.0.0-20200322065615-581c8d33cff6","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package dmlgen\n\nPackage dmlgen generates Go code and protocol buffer files from database tables.\n\nTODO check for [https://github.com/improbable-eng/ts-protoc-gen](https://github.com/improbable-eng/ts-protoc-gen) and [https://github.com/improbable-eng/grpc-web](https://github.com/improbable-eng/grpc-web)\n\n## Functions\n\n```go\nfunc GenerateJSON(fileNameOrDirectory, buildTags string, g *bootstrap.Generator) error\n```\nGenerateJSON creates the easysjon code for a specific file or a whole directory. argument \\`g\\` can be nil. deprecated as there are stdlib compatible packages which have the same speed without code gen.\n\n```go\nfunc GenerateProto(protoFilesPath string, po *ProtocOptions) error\n```\nGenerateProto searches all \\*.proto files in the given path and calls protoc to generate the Go source code.\n\n## Types\n\n```go\ntype FeatureToggle uint64\n```\nFeatureToggle allows certain generated code blocks to be switched off or on.\n\n```go\nconst (\n\tFeatureCollectionAppend FeatureToggle = 1 \u003c\u003c iota\n\tFeatureCollectionBinaryMarshaler\n\tFeatureCollectionCut\n\tFeatureCollectionDelete\n\tFeatureCollectionEach\n\tFeatureCollectionFilter\n\tFeatureCollectionInsert\n\tFeatureCollectionStruct // creates the struct type\n\tFeatureCollectionSwap\n\tFeatureCollectionUniqueGetters\n\tFeatureCollectionUniquifiedGetters\n\tFeatureCollectionValidate\n\tFeatureDB\n\tFeatureDBAssignLastInsertID\n\tFeatureDBDelete\n\tFeatureDBInsert\n\tFeatureDBMapColumns\n\tFeatureDBSelect\n\tFeatureDBTracing // opentelemetry tracing\n\tFeatureDBUpdate\n\tFeatureDBUpsert\n\tFeatureEntityCopy\n\tFeatureEntityEmpty\n\tFeatureEntityGetSetPrivateFields\n\tFeatureEntityIsSet\n\tFeatureEntityRelationships\n\tFeatureEntityStruct // creates the struct type\n\tFeatureEntityValidate\n\tFeatureEntityWriteTo\n)\n```\nList of available features\n\n```go\nfunc (f FeatureToggle) String() string\n```\n\n```go\ntype ForeignKeyOptions struct {\n\tIncludeRelationShips []string\n\tExcludeRelationships []string\n}\n```\nForeignKeyOptions applies to WithForeignKeyRelationships\n\n```go\ntype Generator struct {\n\tPackage                     string // Name of the package\n\tPackageImportPath           string // Name of the package\n\tPackageSerializer           string // Name of the package, if empty uses field Package\n\tPackageSerializerImportPath string // Name of the package, if empty uses field PackageImportPath\n\tBuildTags                   []string\n\tImportPaths                 []string\n\tImportPathsTesting          []string\n\t// Tables uses the table name as map key and the table description as value.\n\tTables map[string]*Table\n\t// Serializer defines the de/serializing method to use. Either\n\t// `empty`=default (none) or proto=protocol buffers or fbs=flatbuffers. JSON\n\t// marshaling is not affected with this config. Only one serializer can be\n\t// defined because some Go types depends on the types of serializer. E.g.\n\t// protobuf cannot use int16/int8 whereas in flatbuffers they are available.\n\t// Using a common denominator for every serializer like an int32 can cause\n\t// data loss when communicating with the database table which has different\n\t// (smaller) column types than an int32.\n\tSerializer string\n\t// SerializerHeaderOptions defines custom headers to use in the .proto or .fbs file.\n\t// For proto, sane defaults are available.\n\tSerializerHeaderOptions []string\n\t// TestSQLDumpGlobPath contains the path and glob pattern to load a SQL dump\n\t// containing the table schemas to run integration tests. If empty no dumps\n\t// get loaded and the test program assumes that the tables already exists.\n\tTestSQLDumpGlobPath string\n\t// contains filtered or unexported fields\n}\n```\nGenerator can generated Go source for for database tables once correctly configured.\n\n```go\nfunc NewGenerator(packageImportPath string, opts ...Option) (*Generator, error)\n```\nNewGenerator 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.\n\n```go\nfunc (g *Generator) GenerateGo(wMain, wTest io.Writer) error\n```\nGenerateGo writes the Go source code into \\`w\\` and the test code into wTest.\n\n```go\nfunc (g *Generator) GenerateSerializer(wMain, wTest io.Writer) error\n```\nGenerateSerializer writes the protocol buffer specifications into \\`w\\` and its test sources into wTest, if there are any tests.\n\n```go\ntype Option struct {\n\t// contains filtered or unexported fields\n}\n```\nOption represents a sortable option for the NewGenerator function. Each option function can be applied in a mixed order.\n\n```go\nfunc WithBuildTags(lines ...string) (opt Option)\n```\nWithBuildTags adds your build tags to the file header. Each argument represents a build tag line.\n\n```go\nfunc WithCustomCode(marker, code string) (opt Option)\n```\nWithCustomCode inserts at the marker position your custom Go code. For available markers search these .go files for the map access of field \\*Generator.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.\n\n```go\nfunc WithCustomCodeFunc(marker string, fn func(g *Generator, t *Table, w io.Writer)) (opt Option)\n```\nWithCustomCodeFunc same as WithCustomCode but allows access to meta data. The func fn takes as first argument the main Generator where access to package global configuration is possible. If the scope of the marker is within a table, then argument t gets set, otherwise it is nil. The output must be written to w.\n\n```go\nfunc WithForeignKeyRelationships(ctx context.Context, db dml.Querier, o ForeignKeyOptions) (opt Option)\n```\nWithForeignKeyRelationships analyzes 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. includeRelationShips and excludeRelationships must be a balanced slice in the notation of \"table1.column1\",\"table2.column2\". For example:\n\n\t\"customer_entity.store_id\", \"store.store_id\" which means that the\n\nstruct CustomerEntity won't have a field to the Store struct (1:1 relationship) (in case of excluding). The reverse case can also be added\n\n\t\"store.store_id\", \"customer_entity.store_id\" which means that the\n\nStore struct won't or will have a field pointing to the CustomerEntityCollection (1:M relationship). Setting includeRelationShips to nil will include all relationships.\n\n```go\nfunc WithProtobuf(sc *SerializerConfig) (opt Option)\n```\nWithProtobuf enables protocol buffers as a serialization method. Argument headerOptions is optional. Heads up: This function also sets the internal Serializer field and all types will get adjusted to the minimum protobuf types. E.g. uint32 minimum instead of uint8/uint16. So if the Generator gets created multiple times to separate the creation of code, the WithProtobuf function must get set for Generator objects. See package store.\n\n```go\nfunc WithTable(tableName string, columns ddl.Columns, options ...string) (opt Option)\n```\nWithTable sets a table and its columns. Allows to overwrite a table fetched with function WithTablesFromDB. Argument \\`options\\` can be set to \"overwrite\" and/or \"view\". Each option is its own slice entry.\n\n```go\nfunc WithTableConfig(tableName string, opt *TableConfig) (o Option)\n```\nWithTableConfig applies options to an existing table, identified by the table name used as map key. Options are custom struct or different encoders. Returns a not-found error if the table cannot be found in the \\`Generator\\` map.\n\n```go\nfunc WithTableConfigDefault(opt TableConfig) (o Option)\n```\nWithTableConfigDefault sets for all tables the same configuration but can be overwritten on a per table basis with function WithTableConfig. Current behaviour: Does not apply the default config to all tables but only to those which have set an empty \\`WithTableConfig(\"table\\_name\",\u0026dmlgen.TableConfig{})\\`.\n\n```go\nfunc WithTablesFromDB(ctx context.Context, db *dml.ConnPool, tables ...string) (opt Option)\n```\nWithTablesFromDB queries the information\\_schema table and loads the column definition of the provided \\`tables\\` slice. It adds the tables to the \\`Generator\\` map. Once added a call to WithTableConfig can add additional configurations.\n\n```go\ntype ProtocOptions struct {\n\tBuildTags          []string\n\tWorkingDirectory   string\n\tProtoGen           string // default gofast, options: gogo, gogofast, gogofaster\n\tGRPC               bool\n\tGRPCGatewayOutMap  []string // GRPC must be enabled in the above field\n\tGRPCGatewayOutPath string   // GRPC must be enabled in the above field\n\tProtoPath          []string\n\tGoGoOutPath        string\n\tGoGoOutMap         []string\n\tSwaggerOutPath     string\n\tCustomArgs         []string\n}\n```\nProtocOptions allows to modify the protoc CLI command.\n\n```go\ntype SerializerConfig struct {\n\tPackageImportPath string\n\tHeaders           []string\n}\n```\nSerializerConfig applies various optional settings to WithProtobuf and/or WithFlatbuffers and/or WithTypeScript.\n\n```go\ntype Table struct {\n\tPackage              string // Name of the package\n\tTable                *ddl.Table\n\tComment              string // Comment above the struct type declaration\n\tHasAutoIncrement     uint8  // 0=nil,1=false (has NO auto increment),2=true has auto increment\n\tHasEasyJSONMarshaler bool\n\tHasSerializer        bool // writes the .proto file if true\n\t// contains filtered or unexported fields\n}\n```\ntable writes one database table into Go source code.\n\n```go\nfunc (t *Table) CollectionName() string\n```\n\n```go\nfunc (t *Table) EntityName() string\n```\n\n```go\nfunc (t *Table) GoCamelMaybePrivate(fieldName string) string\n```\n\n```go\nfunc (t *Table) IsFieldPrivate(dbColumnName string) bool\n```\n\n```go\nfunc (t *Table) IsFieldPublic(dbColumnName string) bool\n```\n\n```go\ntype TableConfig struct {\n\t// Encoders add method receivers for, each struct, compatible with the\n\t// interface declarations in the various encoding packages. Supported\n\t// encoder names are: json resp. easyjson.\n\tEncoders []string\n\t// StructTags enables struct tags proactively for the whole struct. Allowed\n\t// values are: bson, db, env, json, protobuf, toml, yaml and xml. For bson,\n\t// json, yaml and xml the omitempty attribute has been set. If you need a\n\t// different struct tag for a specifiv column you must set the option\n\t// CustomStructTags.\n\tStructTags []string\n\t// CustomStructTags allows to specify custom struct tags for a specific\n\t// column. The slice must be balanced, means index i sets to the column name\n\t// and index i+1 to the desired struct tag.\n\t// \t\t[]string{\"column_a\",`json: \",omitempty\"`,\"column_b\",\"`xml:,omitempty`\"}\n\t// In case when foreign keys should be referenced:\n\t// \t\t[]string{\"FieldNameX\",`faker: \"-\"`,\"FieldNameY\",\"`xml:field_name_y,omitempty`\"}\n\t// TODO CustomStructTags should be appended to StructTags\n\tCustomStructTags []string // balanced slice\n\t// AppendCustomStructTags []string // balanced slice TODO maybe this additionally\n\t// Comment adds custom comments to each struct type. Useful when relying on\n\t// 3rd party JSON marshaler code generators like easyjson or ffjson. If\n\t// comment spans over multiple lines each line will be checked if it starts\n\t// with the comment identifier (//). If not, the identifier will be\n\t// prepended.\n\tComment string\n\t// ColumnAliases specifies different names used for a column. For example\n\t// customer_entity.entity_id can also be sales_order.customer_id, hence a\n\t// Foreign Key. The alias would be just: entity_id:[]string{\"customer_id\"}.\n\tColumnAliases map[string][]string // key=column name value a list of aliases\n\t// UniquifiedColumns specifies columns which are non primary/unique key one\n\t// but should have a dedicated function to extract their unique primitive\n\t// values as a slice. Not allowed are text, blob and binary.\n\tUniquifiedColumns []string\n\t// PrivateFields list struct field names which should be private to avoid\n\t// accidentally leaking through encoders. Appropriate getter/setter methods\n\t// get generated.\n\tPrivateFields []string\n\t// FeaturesInclude if set includes only those features, otherwise\n\t// everything. Some features can only be included on Default level and not\n\t// on a per table level.\n\tFeaturesInclude FeatureToggle\n\t// FeaturesExclude excludes features while field FeaturesInclude is empty.\n\t// Some features can only be excluded on Default level and not on a per\n\t// table level.\n\tFeaturesExclude FeatureToggle\n\t// FieldMapFn can map a dbIdentifier (database identifier) of the current\n\t// table to a new name. dbIdentifier is in most cases the column name and in\n\t// cases of foreign keys, it is the table name.\n\tFieldMapFn func(dbIdentifier string) (newName string)\n\t// contains filtered or unexported fields\n}\n```\nTableConfig used in conjunction with WithTableConfig and WithTableConfigDefault to apply different configurations for a generated struct and its struct collection.\n\n```go\ntype TypeDef struct {\n\tGoUNull    string // unsigned null\n\tGoUNotNull string // unsigned not null\n\tGoNull     string // A go type which can be null/nil\n\tGoNotNull  string // A usually native Go primitive type\n\n\tSerializerUNull    string\n\tSerializerUNotNull string\n\tSerializerNull     string\n\tSerializerNotNull  string\n}\n```\nTypeDef 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.\n\n","path":"github.com/weiwolves/pkg/sql/dmlgen","name":"dmlgen","synopsis":"Package dmlgen generates Go code and protocol buffer files from database tables.","isRedistributable":true}
