Skip to content

Commit

Permalink
Add protoc Param --bq-schema_opt=type-override=field_name.field_type
Browse files Browse the repository at this point in the history
  • Loading branch information
its28604 committed Dec 22, 2023
1 parent 8edab4b commit a3249e7
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
11 changes: 10 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,16 @@ go install github.com/GoogleCloudPlatform/protoc-gen-bq-schema@latest
```

## Usage
protoc --bq-schema\_out=path/to/outdir \[--bq-schema_opt=single-message\] foo.proto

providing `single-message` parameter tells protoc-gen-bq-schema to treat each proto files only contains one top-level type.
```sh
protoc --bq-schema\_out=path/to/outdir \[--bq-schema_opt=single-message\] foo.proto
```
When using `single-message` you can passing the type overrides as a command line parameter as well. The parameter should be a string where each field name and type pair is separated by a dot.
```sh
protoc --bq-schema\_out=path/to/outdir \[--bq-schema_opt=single-message\] \[--bq-schema_opt=type-override=field_name.field_type\] foo.proto
```


`protoc` and `protoc-gen-bq-schema` commands must be found in $PATH.

Expand Down
32 changes: 32 additions & 0 deletions pkg/converter/convert.go
Original file line number Diff line number Diff line change
Expand Up @@ -384,6 +384,38 @@ func handleSingleMessageOpt(file *descriptor.FileDescriptorProto, requestParam s
proto.SetExtension(message.GetOptions(), protos.E_BigqueryOpts, &protos.BigQueryMessageOptions{
TableName: fileName[strings.LastIndexByte(fileName, '/')+1 : strings.LastIndexByte(fileName, '.')],
})
overrides := parseTypeOverrides(requestParam)
for _, field := range message.GetField() {
if typeName, ok := overrides[field.GetName()]; ok {
if field.Options == nil {
field.Options = &descriptor.FieldOptions{}
}
proto.SetExtension(field.GetOptions(), protos.E_Bigquery, &protos.BigQueryFieldOptions{
TypeOverride: typeName,
})
}
}
}

func parseTypeOverrides(input string) map[string]string {
// Split the input string into segments
segments := strings.Split(input, ",")
// Create a map to hold the field name and type pairs
typeOverrides := make(map[string]string)

for _, segment := range segments {
// Check if the segment starts with "type-override="
if strings.HasPrefix(segment, "type-override=") {
// Remove the prefix "type-override=" from the segment
override := strings.TrimPrefix(segment, "type-override=")
// Split the override into field name and field type
pair := strings.Split(override, ".")
if len(pair) == 2 {
typeOverrides[pair[0]] = pair[1]
}
}
}
return typeOverrides
}

func Convert(req *plugin.CodeGeneratorRequest) (*plugin.CodeGeneratorResponse, error) {
Expand Down

0 comments on commit a3249e7

Please sign in to comment.