Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion .github/workflows/check.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,14 @@ jobs:
- run: go test ./...
- run: go install .
- uses: bufbuild/buf-setup-action@v1
with:
github_token: ${{ github.token }}
- name: Check generated ORM helpers
working-directory: example
run: |
buf generate --template '{"version":"v2","plugins":[{"local":"protoc-gen-orm-rust","out":"src/generated/orm"}]}'
git diff --exit-code -- src/generated/orm
buf generate --template '{"version":"v2","plugins":[{"local":"protoc-gen-orm-rust","opt":["storage_model"],"out":"../testdata/directory","strategy":"all"}]}'
git diff --exit-code -- src/generated/orm ../testdata/directory
directory:
runs-on: ubuntu-latest
defaults:
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ Install the executable with `go install github.com/protobuf-orm/protoc-gen-orm-r

For each ORM entity with a generated Get service, the plugin emits constructors for its key oneof, `pick`, optional `with_select`, and a router registration function. This first implementation handles scalar keys and composite keys containing scalars or top-level message references. Enum and nested message keys report a generation error. Database schema, CRUD implementations, and Payday policy are separate layers.

For a storage generator, run the plugin a second time with `opt: [storage_model]` and `strategy: all`. Its `model.json` records resolved key types, field presence, defaults, immutability, relation targets, version and erase markers, and ordered compound indexes. The graph is shared with the upstream ORM service generator. The versioned output is deterministic across input orders. [Directory model](testdata/directory/model.json)

## Test

`go test ./...` tests descriptor handling. The [directory example](example/README.md) exercises generated code with Diesel SQLite. The same Rust router serves a native Connect endpoint and a WASM Worker reached with the published TypeScript dRPC transport.
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@ go 1.27.0

require (
github.com/ettle/strcase v0.2.0
github.com/protobuf-orm/protobuf-orm v0.0.0-20260906212449-04c0cd58f10a
github.com/protobuf-orm/protobuf-orm v0.0.0-20261017212716-3430237a8656
google.golang.org/protobuf v1.36.11
)
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/protobuf-orm/protobuf-orm v0.0.0-20260906212449-04c0cd58f10a h1:EXbJ28yY25wzt2HbzVkw7Tk46pF1GAHV+XMcC+kir40=
github.com/protobuf-orm/protobuf-orm v0.0.0-20260906212449-04c0cd58f10a/go.mod h1:OYlbo4/9t+Hgj/XZwdgN8Z9MyViTLPHxBWLUR4+j52o=
github.com/protobuf-orm/protobuf-orm v0.0.0-20261017212716-3430237a8656 h1:dVr9HD7HgeUh1c+xhTfjKzwfpKTUDNMcVfMPOt8HPkI=
github.com/protobuf-orm/protobuf-orm v0.0.0-20261017212716-3430237a8656/go.mod h1:OYlbo4/9t+Hgj/XZwdgN8Z9MyViTLPHxBWLUR4+j52o=
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
Expand Down
5 changes: 4 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ func main() {
func fail(err error) { fmt.Fprintln(os.Stderr, err); os.Exit(1) }

func generate(req *pluginpb.CodeGeneratorRequest, resp *pluginpb.CodeGeneratorResponse) error {
if req.GetParameter() != "" {
if req.GetParameter() != "" && req.GetParameter() != "storage_model" {
return fmt.Errorf("unexpected plugin parameter %q", req.GetParameter())
}
files, err := protodesc.NewFiles(&descriptorpb.FileDescriptorSet{File: req.ProtoFile})
Expand All @@ -58,6 +58,9 @@ func generate(req *pluginpb.CodeGeneratorRequest, resp *pluginpb.CodeGeneratorRe
}
names := append([]string(nil), req.FileToGenerate...)
sort.Strings(names)
if req.GetParameter() == "storage_model" {
return storageModel(files, names, resp)
}
for _, name := range names {
f, err := files.FindFileByPath(name)
if err != nil {
Expand Down
118 changes: 118 additions & 0 deletions model.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
package main

import (
"context"
"encoding/json"
"fmt"
"slices"
"sort"
"strings"

"github.com/protobuf-orm/protobuf-orm/graph"
"github.com/protobuf-orm/protobuf-orm/ormpb"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protoregistry"
"google.golang.org/protobuf/types/pluginpb"
)

// The storage planner consumes resolved ORM properties. In particular, presence
// on a message edge means something different from presence on a scalar field.
type model struct {
Version int `json:"version"`
Entities []modelEntity `json:"entities"`
}
type modelEntity struct {
Name string `json:"name"`
Key string `json:"key"`
Fields []modelField `json:"fields"`
Indexes []modelIndex `json:"indexes"`
}
type modelField struct {
Name string `json:"name"`
JSON string `json:"json"`
Number int32 `json:"number"`
Kind string `json:"kind"`
Collection string `json:"collection,omitempty"`
Target string `json:"target,omitempty"`
Inverse string `json:"inverse,omitempty"`
Nullable bool `json:"nullable,omitempty"`
Immutable bool `json:"immutable,omitempty"`
Unique bool `json:"unique,omitempty"`
Default *string `json:"default,omitempty"`
Version bool `json:"version,omitempty"`
Erased bool `json:"erased,omitempty"`
}
type modelIndex struct {
Name string `json:"name"`
Fields []string `json:"fields"`
Unique bool `json:"unique,omitempty"`
ActiveOnly bool `json:"active_only,omitempty"`
Hidden bool `json:"hidden,omitempty"`
}

func storageModel(files *protoregistry.Files, names []string, resp *pluginpb.CodeGeneratorResponse) error {
g := graph.NewGraph()
for _, name := range names {
file, err := files.FindFileByPath(name)
if err != nil {
return err
}
if err := graph.Parse(context.Background(), g, file); err != nil {
return err
}
}
m := model{Version: 1, Entities: []modelEntity{}}
for _, ent := range g.Entities {
if ent.Key() == nil {
return fmt.Errorf("%s: missing ORM primary key", ent.FullName())
}
e := modelEntity{Name: string(ent.FullName()), Key: ent.Key().Name(), Indexes: []modelIndex{}}
for p := range ent.Props() {
d := p.Descriptor()
field := modelField{Name: p.Name(), JSON: d.JSONName(), Number: int32(p.Number()), Kind: strings.TrimPrefix(p.Type().String(), "TYPE_"), Nullable: p.IsNullable(), Immutable: p.IsImmutable(), Unique: p.IsUnique()}
if d.IsMap() {
field.Collection = "map"
} else if d.IsList() {
field.Collection = "list"
}
switch prop := p.(type) {
case graph.Edge:
field.Target = string(prop.Target().FullName())
if from := prop.Inverse(); from != nil {
field.Inverse = from.Name()
}
o := proto.GetExtension(d.Options(), ormpb.E_Edge).(*ormpb.EdgeOptions)
if o.HasDefault() {
field.Default = proto.String(o.GetDefault())
}
case graph.Field:
field.Erased, field.Version = prop.IsErased(), prop.IsVersion()
o := proto.GetExtension(d.Options(), ormpb.E_Field).(*ormpb.FieldOptions)
if o.HasDefault() {
field.Default = proto.String(o.GetDefault())
}
}
if field.Name == e.Key {
field.Nullable = false
}
e.Fields = append(e.Fields, field)
}
sort.Slice(e.Fields, func(i, j int) bool { return e.Fields[i].Number < e.Fields[j].Number })
for index := range ent.Indexes() {
idx := modelIndex{Name: index.Name(), Unique: index.IsUnique(), ActiveOnly: index.ExcludesErased(), Hidden: index.IsHidden()}
for prop := range index.Props() {
idx.Fields = append(idx.Fields, prop.Name())
}
e.Indexes = append(e.Indexes, idx)
}
slices.SortFunc(e.Indexes, func(a, b modelIndex) int { return strings.Compare(a.Name, b.Name) })
m.Entities = append(m.Entities, e)
}
slices.SortFunc(m.Entities, func(a, b modelEntity) int { return strings.Compare(a.Name, b.Name) })
bytes, err := json.MarshalIndent(m, "", " ")
if err != nil {
return err
}
resp.File = append(resp.File, &pluginpb.CodeGeneratorResponse_File{Name: proto.String("model.json"), Content: proto.String(string(bytes) + "\n")})
return nil
}
57 changes: 57 additions & 0 deletions testdata/directory/model.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
{
"version": 1,
"entities": [
{
"name": "directory.v1.Tenant",
"key": "id",
"fields": [
{
"name": "id",
"json": "id",
"number": 1,
"kind": "INT32",
"immutable": true,
"unique": true
}
],
"indexes": []
},
{
"name": "directory.v1.User",
"key": "id",
"fields": [
{
"name": "id",
"json": "id",
"number": 1,
"kind": "INT32",
"immutable": true,
"unique": true
},
{
"name": "tenant",
"json": "tenant",
"number": 2,
"kind": "MESSAGE",
"target": "directory.v1.Tenant"
},
{
"name": "alias",
"json": "alias",
"number": 3,
"kind": "STRING"
}
],
"indexes": [
{
"name": "alias",
"fields": [
"alias",
"tenant"
],
"unique": true
}
]
}
]
}
Loading