mirror of
https://github.com/bitechdev/ResolveSpec.git
synced 2026-08-29 20:42:35 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
798bb47e71 | ||
|
|
105a5e1b87 | ||
|
|
a68cf83be6 | ||
|
|
dab4940ace | ||
|
|
c7178e0a2b | ||
|
|
0261f121e8 | ||
|
|
93dc1008ee | ||
|
|
c60565e4e0 | ||
|
|
16cc7d350e |
@@ -1,5 +1,7 @@
|
|||||||
.PHONY: test test-unit test-integration docker-up docker-down clean
|
.PHONY: test test-unit test-integration docker-up docker-down clean
|
||||||
|
|
||||||
|
GOLANGCI_LINT := $(shell go env GOPATH)/bin/golangci-lint
|
||||||
|
|
||||||
# Run all unit tests
|
# Run all unit tests
|
||||||
test-unit:
|
test-unit:
|
||||||
@echo "Running unit tests..."
|
@echo "Running unit tests..."
|
||||||
@@ -49,7 +51,9 @@ release-version: ## Create and push a release with specific version (use: make r
|
|||||||
|
|
||||||
lint: ## Run linter
|
lint: ## Run linter
|
||||||
@echo "Running linter..."
|
@echo "Running linter..."
|
||||||
@if command -v golangci-lint > /dev/null; then \
|
@if [ -x "$(GOLANGCI_LINT)" ]; then \
|
||||||
|
"$(GOLANGCI_LINT)" run --config=.golangci.json; \
|
||||||
|
elif command -v golangci-lint > /dev/null; then \
|
||||||
golangci-lint run --config=.golangci.json; \
|
golangci-lint run --config=.golangci.json; \
|
||||||
else \
|
else \
|
||||||
echo "golangci-lint not installed. Install with: go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest"; \
|
echo "golangci-lint not installed. Install with: go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest"; \
|
||||||
@@ -58,7 +62,9 @@ lint: ## Run linter
|
|||||||
|
|
||||||
lintfix: ## Run linter
|
lintfix: ## Run linter
|
||||||
@echo "Running linter..."
|
@echo "Running linter..."
|
||||||
@if command -v golangci-lint > /dev/null; then \
|
@if [ -x "$(GOLANGCI_LINT)" ]; then \
|
||||||
|
"$(GOLANGCI_LINT)" run --config=.golangci.json --fix; \
|
||||||
|
elif command -v golangci-lint > /dev/null; then \
|
||||||
golangci-lint run --config=.golangci.json --fix; \
|
golangci-lint run --config=.golangci.json --fix; \
|
||||||
else \
|
else \
|
||||||
echo "golangci-lint not installed. Install with: go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest"; \
|
echo "golangci-lint not installed. Install with: go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest"; \
|
||||||
|
|||||||
@@ -33,13 +33,13 @@ require (
|
|||||||
github.com/uptrace/bun/driver/sqliteshim v1.2.16
|
github.com/uptrace/bun/driver/sqliteshim v1.2.16
|
||||||
github.com/uptrace/bunrouter v1.0.23
|
github.com/uptrace/bunrouter v1.0.23
|
||||||
go.mongodb.org/mongo-driver v1.17.9
|
go.mongodb.org/mongo-driver v1.17.9
|
||||||
go.opentelemetry.io/otel v1.43.0
|
go.opentelemetry.io/otel v1.44.0
|
||||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.43.0
|
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.43.0
|
||||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.43.0
|
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.43.0
|
||||||
go.opentelemetry.io/otel/sdk v1.43.0
|
go.opentelemetry.io/otel/sdk v1.44.0
|
||||||
go.opentelemetry.io/otel/trace v1.43.0
|
go.opentelemetry.io/otel/trace v1.44.0
|
||||||
go.uber.org/zap v1.28.0
|
go.uber.org/zap v1.28.0
|
||||||
golang.org/x/crypto v0.51.0
|
golang.org/x/crypto v0.55.0
|
||||||
golang.org/x/oauth2 v0.36.0
|
golang.org/x/oauth2 v0.36.0
|
||||||
golang.org/x/time v0.15.0
|
golang.org/x/time v0.15.0
|
||||||
gorm.io/driver/postgres v1.6.0
|
gorm.io/driver/postgres v1.6.0
|
||||||
@@ -137,22 +137,21 @@ require (
|
|||||||
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect
|
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect
|
||||||
github.com/yusufpapurcu/wmi v1.2.4 // indirect
|
github.com/yusufpapurcu/wmi v1.2.4 // indirect
|
||||||
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
|
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
|
||||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.49.0 // indirect
|
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0 // indirect
|
||||||
go.opentelemetry.io/otel/metric v1.43.0 // indirect
|
go.opentelemetry.io/otel/metric v1.44.0 // indirect
|
||||||
go.opentelemetry.io/proto/otlp v1.10.0 // indirect
|
go.opentelemetry.io/proto/otlp v1.10.0 // indirect
|
||||||
go.uber.org/atomic v1.11.0 // indirect
|
go.uber.org/atomic v1.11.0 // indirect
|
||||||
go.uber.org/multierr v1.11.0 // indirect
|
go.uber.org/multierr v1.11.0 // indirect
|
||||||
go.yaml.in/yaml/v2 v2.4.4 // indirect
|
go.yaml.in/yaml/v2 v2.4.4 // indirect
|
||||||
go.yaml.in/yaml/v3 v3.0.4 // indirect
|
go.yaml.in/yaml/v3 v3.0.4 // indirect
|
||||||
golang.org/x/mod v0.36.0 // indirect
|
golang.org/x/mod v0.38.0 // indirect
|
||||||
golang.org/x/net v0.54.0 // indirect
|
golang.org/x/net v0.58.0 // indirect
|
||||||
golang.org/x/sync v0.20.0 // indirect
|
golang.org/x/sync v0.22.0 // indirect
|
||||||
golang.org/x/sys v0.44.0 // indirect
|
golang.org/x/sys v0.47.0 // indirect
|
||||||
golang.org/x/text v0.37.0 // indirect
|
golang.org/x/text v0.41.0 // indirect
|
||||||
golang.org/x/tools v0.45.0 // indirect
|
google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa // indirect
|
||||||
google.golang.org/genproto/googleapis/api v0.0.0-20260519071638-aa98bba5eb94 // indirect
|
google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa // indirect
|
||||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260519071638-aa98bba5eb94 // indirect
|
google.golang.org/grpc v1.83.2 // indirect
|
||||||
google.golang.org/grpc v1.81.1 // indirect
|
|
||||||
google.golang.org/protobuf v1.36.11 // indirect
|
google.golang.org/protobuf v1.36.11 // indirect
|
||||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||||
modernc.org/libc v1.72.3 // indirect
|
modernc.org/libc v1.72.3 // indirect
|
||||||
|
|||||||
@@ -348,24 +348,24 @@ go.mongodb.org/mongo-driver v1.17.9 h1:IexDdCuuNJ3BHrELgBlyaH9p60JXAvdzWR128q+U5
|
|||||||
go.mongodb.org/mongo-driver v1.17.9/go.mod h1:LlOhpH5NUEfhxcAwG0UEkMqwYcc4JU18gtCdGudk/tQ=
|
go.mongodb.org/mongo-driver v1.17.9/go.mod h1:LlOhpH5NUEfhxcAwG0UEkMqwYcc4JU18gtCdGudk/tQ=
|
||||||
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
|
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
|
||||||
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
|
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
|
||||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.49.0 h1:jq9TW8u3so/bN+JPT166wjOI6/vQPF6Xe7nMNIltagk=
|
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0 h1:F7Jx+6hwnZ41NSFTO5q4LYDtJRXBf2PD0rNBkeB/lus=
|
||||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.49.0/go.mod h1:p8pYQP+m5XfbZm9fxtSKAbM6oIllS7s2AfxrChvc7iw=
|
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0/go.mod h1:UHB22Z8QsdRDrnAtX4PntOl36ajSxcdUMt1sF7Y6E7Q=
|
||||||
go.opentelemetry.io/otel v1.43.0 h1:mYIM03dnh5zfN7HautFE4ieIig9amkNANT+xcVxAj9I=
|
go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU=
|
||||||
go.opentelemetry.io/otel v1.43.0/go.mod h1:JuG+u74mvjvcm8vj8pI5XiHy1zDeoCS2LB1spIq7Ay0=
|
go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc=
|
||||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.43.0 h1:88Y4s2C8oTui1LGM6bTWkw0ICGcOLCAI5l6zsD1j20k=
|
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.43.0 h1:88Y4s2C8oTui1LGM6bTWkw0ICGcOLCAI5l6zsD1j20k=
|
||||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.43.0/go.mod h1:Vl1/iaggsuRlrHf/hfPJPvVag77kKyvrLeD10kpMl+A=
|
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.43.0/go.mod h1:Vl1/iaggsuRlrHf/hfPJPvVag77kKyvrLeD10kpMl+A=
|
||||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.43.0 h1:RAE+JPfvEmvy+0LzyUA25/SGawPwIUbZ6u0Wug54sLc=
|
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.43.0 h1:RAE+JPfvEmvy+0LzyUA25/SGawPwIUbZ6u0Wug54sLc=
|
||||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.43.0/go.mod h1:AGmbycVGEsRx9mXMZ75CsOyhSP6MFIcj/6dnG+vhVjk=
|
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.43.0/go.mod h1:AGmbycVGEsRx9mXMZ75CsOyhSP6MFIcj/6dnG+vhVjk=
|
||||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.19.0 h1:IeMeyr1aBvBiPVYihXIaeIZba6b8E1bYp7lbdxK8CQg=
|
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.19.0 h1:IeMeyr1aBvBiPVYihXIaeIZba6b8E1bYp7lbdxK8CQg=
|
||||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.19.0/go.mod h1:oVdCUtjq9MK9BlS7TtucsQwUcXcymNiEDjgDD2jMtZU=
|
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.19.0/go.mod h1:oVdCUtjq9MK9BlS7TtucsQwUcXcymNiEDjgDD2jMtZU=
|
||||||
go.opentelemetry.io/otel/metric v1.43.0 h1:d7638QeInOnuwOONPp4JAOGfbCEpYb+K6DVWvdxGzgM=
|
go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc=
|
||||||
go.opentelemetry.io/otel/metric v1.43.0/go.mod h1:RDnPtIxvqlgO8GRW18W6Z/4P462ldprJtfxHxyKd2PY=
|
go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo=
|
||||||
go.opentelemetry.io/otel/sdk v1.43.0 h1:pi5mE86i5rTeLXqoF/hhiBtUNcrAGHLKQdhg4h4V9Dg=
|
go.opentelemetry.io/otel/sdk v1.44.0 h1:nHYwb9lK+fJPU/dnT6s7W7Z8itMWyqrnVfbheVYrZ58=
|
||||||
go.opentelemetry.io/otel/sdk v1.43.0/go.mod h1:P+IkVU3iWukmiit/Yf9AWvpyRDlUeBaRg6Y+C58QHzg=
|
go.opentelemetry.io/otel/sdk v1.44.0/go.mod h1:Osuydd3Se74nqjAKxid74N5eC+jfEqfTegHRnq58oK0=
|
||||||
go.opentelemetry.io/otel/sdk/metric v1.43.0 h1:S88dyqXjJkuBNLeMcVPRFXpRw2fuwdvfCGLEo89fDkw=
|
go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRks6si09iEfI=
|
||||||
go.opentelemetry.io/otel/sdk/metric v1.43.0/go.mod h1:C/RJtwSEJ5hzTiUz5pXF1kILHStzb9zFlIEe85bhj6A=
|
go.opentelemetry.io/otel/sdk/metric v1.44.0/go.mod h1:5B5pMARnXxKhltooO4xUuCBorl65a4EpnTalObqOigA=
|
||||||
go.opentelemetry.io/otel/trace v1.43.0 h1:BkNrHpup+4k4w+ZZ86CZoHHEkohws8AY+WTX09nk+3A=
|
go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk=
|
||||||
go.opentelemetry.io/otel/trace v1.43.0/go.mod h1:/QJhyVBUUswCphDVxq+8mld+AvhXZLhe+8WVFxiFff0=
|
go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE=
|
||||||
go.opentelemetry.io/proto/otlp v1.10.0 h1:IQRWgT5srOCYfiWnpqUYz9CVmbO8bFmKcwYxpuCSL2g=
|
go.opentelemetry.io/proto/otlp v1.10.0 h1:IQRWgT5srOCYfiWnpqUYz9CVmbO8bFmKcwYxpuCSL2g=
|
||||||
go.opentelemetry.io/proto/otlp v1.10.0/go.mod h1:/CV4QoCR/S9yaPj8utp3lvQPoqMtxXdzn7ozvvozVqk=
|
go.opentelemetry.io/proto/otlp v1.10.0/go.mod h1:/CV4QoCR/S9yaPj8utp3lvQPoqMtxXdzn7ozvvozVqk=
|
||||||
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
|
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
|
||||||
@@ -392,16 +392,16 @@ golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOM
|
|||||||
golang.org/x/crypto v0.22.0/go.mod h1:vr6Su+7cTlO45qkww3VDJlzDn0ctJvRgYbC2NvXHt+M=
|
golang.org/x/crypto v0.22.0/go.mod h1:vr6Su+7cTlO45qkww3VDJlzDn0ctJvRgYbC2NvXHt+M=
|
||||||
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
|
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
|
||||||
golang.org/x/crypto v0.24.0/go.mod h1:Z1PMYSOR5nyMcyAVAIQSKCDwalqy85Aqn1x3Ws4L5DM=
|
golang.org/x/crypto v0.24.0/go.mod h1:Z1PMYSOR5nyMcyAVAIQSKCDwalqy85Aqn1x3Ws4L5DM=
|
||||||
golang.org/x/crypto v0.51.0 h1:IBPXwPfKxY7cWQZ38ZCIRPI50YLeevDLlLnyC5wRGTI=
|
golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M=
|
||||||
golang.org/x/crypto v0.51.0/go.mod h1:8AdwkbraGNABw2kOX6YFPs3WM22XqI4EXEd8g+x7Oc8=
|
golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis=
|
||||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||||
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||||
golang.org/x/mod v0.9.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
golang.org/x/mod v0.9.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||||
golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||||
golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||||
golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||||
golang.org/x/mod v0.36.0 h1:JJjpVx6myfUsUdAzZuOSTTmRE0PfZeNWzzvKrP7amb4=
|
golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk=
|
||||||
golang.org/x/mod v0.36.0/go.mod h1:moc6ELqsWcOw5Ef3xVprK5ul/MvtVvkIXLziUOICjUQ=
|
golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40=
|
||||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||||
golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||||
@@ -419,8 +419,8 @@ golang.org/x/net v0.22.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg=
|
|||||||
golang.org/x/net v0.24.0/go.mod h1:2Q7sJY5mzlzWjKtYUEXSlBWCdyaioyXzRB2RtU8KVE8=
|
golang.org/x/net v0.24.0/go.mod h1:2Q7sJY5mzlzWjKtYUEXSlBWCdyaioyXzRB2RtU8KVE8=
|
||||||
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
|
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
|
||||||
golang.org/x/net v0.26.0/go.mod h1:5YKkiSynbBIh3p6iOc/vibscux0x38BZDkn8sCUPxHE=
|
golang.org/x/net v0.26.0/go.mod h1:5YKkiSynbBIh3p6iOc/vibscux0x38BZDkn8sCUPxHE=
|
||||||
golang.org/x/net v0.54.0 h1:2zJIZAxAHV/OHCDTCOHAYehQzLfSXuf/5SoL/Dv6w/w=
|
golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=
|
||||||
golang.org/x/net v0.54.0/go.mod h1:Sj4oj8jK6XmHpBZU/zWHw3BV3abl4Kvi+Ut7cQcY+cQ=
|
golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU=
|
||||||
golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs=
|
golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs=
|
||||||
golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q=
|
golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q=
|
||||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
@@ -430,8 +430,8 @@ golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=
|
|||||||
golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||||
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||||
golang.org/x/sync v0.9.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
golang.org/x/sync v0.9.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||||
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
|
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
|
||||||
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||||
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
@@ -455,8 +455,8 @@ golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
|||||||
golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||||
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||||
golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||||
golang.org/x/sys v0.44.0 h1:ildZl3J4uzeKP07r2F++Op7E9B29JRUy+a27EibtBTQ=
|
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
|
||||||
golang.org/x/sys v0.44.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||||
golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE=
|
golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE=
|
||||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||||
@@ -472,8 +472,8 @@ golang.org/x/term v0.18.0/go.mod h1:ILwASektA3OnRv7amZ1xhE/KTR+u50pbXfZ03+6Nx58=
|
|||||||
golang.org/x/term v0.19.0/go.mod h1:2CuTdWZ7KHSQwUzKva0cbMg6q2DMI3Mmxp+gKJbskEk=
|
golang.org/x/term v0.19.0/go.mod h1:2CuTdWZ7KHSQwUzKva0cbMg6q2DMI3Mmxp+gKJbskEk=
|
||||||
golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY=
|
golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY=
|
||||||
golang.org/x/term v0.21.0/go.mod h1:ooXLefLobQVslOqselCNF4SxFAaoS6KujMbsGzSDmX0=
|
golang.org/x/term v0.21.0/go.mod h1:ooXLefLobQVslOqselCNF4SxFAaoS6KujMbsGzSDmX0=
|
||||||
golang.org/x/term v0.43.0 h1:S4RLU2sB31O/NCl+zFN9Aru9A/Cq2aqKpTZJ6B+DwT4=
|
golang.org/x/term v0.45.0 h1:NwWyBmoJCbfTHpxrWoZ9C6/VxOf7ic219I8xZZFdrf0=
|
||||||
golang.org/x/term v0.43.0/go.mod h1:lrhlHNdQJHO+1qVYiHfFKVuVioJIheAc3fBSMFYEIsk=
|
golang.org/x/term v0.45.0/go.mod h1:9aqxs0blBcrm/n0L9QW0aRVD+ktan8ssZromtqJC43w=
|
||||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||||
@@ -488,8 +488,8 @@ golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
|||||||
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||||
golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI=
|
golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI=
|
||||||
golang.org/x/text v0.20.0/go.mod h1:D4IsuqiFMhST5bX19pQ9ikHC2GsaKyk/oF+pn3ducp4=
|
golang.org/x/text v0.20.0/go.mod h1:D4IsuqiFMhST5bX19pQ9ikHC2GsaKyk/oF+pn3ducp4=
|
||||||
golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc=
|
golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=
|
||||||
golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38=
|
golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=
|
||||||
golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
|
golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
|
||||||
golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
|
golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
|
||||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||||
@@ -498,18 +498,18 @@ golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc
|
|||||||
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
|
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
|
||||||
golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58=
|
golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58=
|
||||||
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
|
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
|
||||||
golang.org/x/tools v0.45.0 h1:18qN3FAooORvApf5XjCXgsuayZOEtXf6JK18I3+ONa8=
|
golang.org/x/tools v0.48.0 h1:3+hClM1aLL5mjMKm5ovokw9epgRXPuu2tILgismM6RE=
|
||||||
golang.org/x/tools v0.45.0/go.mod h1:LuUGqqaXcXMEFEruIVJVm5mgDD8vww/z/SR1gQ4uE/0=
|
golang.org/x/tools v0.48.0/go.mod h1:08xX0orndb/F7jJxGDicx061tyd5pcMto75YMAXr6lk=
|
||||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
|
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
|
||||||
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
|
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
|
||||||
google.golang.org/genproto/googleapis/api v0.0.0-20260519071638-aa98bba5eb94 h1:DddG61lE5LkX6144z22i0gma9BMBs5aZ9B8lZLobxyw=
|
google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa h1:Kjn0N0tCrDgiAFW+lGO4JZ3ck44CehvJQMAwj9QF0G8=
|
||||||
google.golang.org/genproto/googleapis/api v0.0.0-20260519071638-aa98bba5eb94/go.mod h1:1dCETSCY2YKZNXQE3h4fun3TYwF5p8jejRKZgfWAgAY=
|
google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa/go.mod h1:q4lMZS6kskjT5HvCPrnnypcDPVJqT/f4nfxmkE7gryY=
|
||||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260519071638-aa98bba5eb94 h1:eZCjr/aAF8c5ccm5pb6T4EXgIei5MlAAPWPJk+5ArfY=
|
google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa h1:mZHHdPZl0dbGHCflZgAq/Q468DWVFcU2whhB2KAo8fk=
|
||||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260519071638-aa98bba5eb94/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
|
google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
|
||||||
google.golang.org/grpc v1.81.1 h1:VnnIIZ88UzOOKLukQi+ImGz8O1Wdp8nAGGnvOfEIWQQ=
|
google.golang.org/grpc v1.83.2 h1:EManeRomTObA0BU7I8vXgg/78uE5MJ9M8B39EX2WscU=
|
||||||
google.golang.org/grpc v1.81.1/go.mod h1:xGH9GfzOyMTGIOXBJmXt+BX/V0kcdQbdcuwQ/zNw42I=
|
google.golang.org/grpc v1.83.2/go.mod h1:YPI1hK3kDked6iHvgX3tR0y+nX/qpMFKhPgFsokw1S8=
|
||||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
|||||||
@@ -669,10 +669,7 @@ func (b *BunSelectQuery) PreloadRelation(relation string, apply ...func(common.S
|
|||||||
b.query = b.query.Relation(relation, func(sq *bun.SelectQuery) *bun.SelectQuery {
|
b.query = b.query.Relation(relation, func(sq *bun.SelectQuery) *bun.SelectQuery {
|
||||||
defer func() {
|
defer func() {
|
||||||
if r := recover(); r != nil {
|
if r := recover(); r != nil {
|
||||||
err := logger.HandlePanic("BunSelectQuery.PreloadRelation", r)
|
_ = logger.HandlePanic("BunSelectQuery.PreloadRelation", r)
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
if len(apply) == 0 {
|
if len(apply) == 0 {
|
||||||
|
|||||||
@@ -82,6 +82,20 @@ type queryMetricsBunUser struct {
|
|||||||
Name string `bun:"name"`
|
Name string `bun:"name"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type queryMetricsBunParent struct {
|
||||||
|
bun.BaseModel `bun:"table:metrics_bun_parents"`
|
||||||
|
ID int64 `bun:"id,pk,autoincrement"`
|
||||||
|
Name string `bun:"name"`
|
||||||
|
Children []queryMetricsBunChild `bun:"rel:has-many,join:id=parent_id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type queryMetricsBunChild struct {
|
||||||
|
bun.BaseModel `bun:"table:metrics_bun_children"`
|
||||||
|
ID int64 `bun:"id,pk,autoincrement"`
|
||||||
|
ParentID int64 `bun:"parent_id"`
|
||||||
|
Name string `bun:"name"`
|
||||||
|
}
|
||||||
|
|
||||||
func TestPgSQLAdapterRecordsSchemaEntityTableMetrics(t *testing.T) {
|
func TestPgSQLAdapterRecordsSchemaEntityTableMetrics(t *testing.T) {
|
||||||
db, mock, err := sqlmock.New()
|
db, mock, err := sqlmock.New()
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
@@ -346,3 +360,35 @@ func TestBunAdapterRecordsEntityAndTableMetrics(t *testing.T) {
|
|||||||
assert.Equal(t, "query_metrics_bun_user", calls[0].entity)
|
assert.Equal(t, "query_metrics_bun_user", calls[0].entity)
|
||||||
assert.Equal(t, "metrics_bun_users", calls[0].table)
|
assert.Equal(t, "metrics_bun_users", calls[0].table)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestBunSelectQueryScanModelSupportsHasManyPreload(t *testing.T) {
|
||||||
|
sqldb, err := sql.Open(sqliteshim.ShimName, "file::memory:?cache=shared")
|
||||||
|
require.NoError(t, err)
|
||||||
|
defer sqldb.Close()
|
||||||
|
|
||||||
|
db := bun.NewDB(sqldb, sqlitedialect.New())
|
||||||
|
defer db.Close()
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
_, err = db.NewCreateTable().Model((*queryMetricsBunParent)(nil)).IfNotExists().Exec(ctx)
|
||||||
|
require.NoError(t, err)
|
||||||
|
_, err = db.NewCreateTable().Model((*queryMetricsBunChild)(nil)).IfNotExists().Exec(ctx)
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
parent := &queryMetricsBunParent{Name: "parent"}
|
||||||
|
_, err = db.NewInsert().Model(parent).Exec(ctx)
|
||||||
|
require.NoError(t, err)
|
||||||
|
_, err = db.NewInsert().Model(&queryMetricsBunChild{ParentID: parent.ID, Name: "child"}).Exec(ctx)
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
adapter := NewBunAdapter(db)
|
||||||
|
var parents []queryMetricsBunParent
|
||||||
|
err = adapter.NewSelect().Model(&parents).PreloadRelation("Children").Scan(ctx, &parents)
|
||||||
|
require.ErrorContains(t, err, "use Model instead of the dest parameter in Scan")
|
||||||
|
|
||||||
|
parents = nil
|
||||||
|
err = adapter.NewSelect().Model(&parents).PreloadRelation("Children").ScanModel(ctx)
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.Len(t, parents, 1)
|
||||||
|
require.Len(t, parents[0].Children, 1)
|
||||||
|
}
|
||||||
|
|||||||
@@ -1040,3 +1040,21 @@ func BuildInCondition(column string, v interface{}) (query string, args []interf
|
|||||||
}
|
}
|
||||||
return fmt.Sprintf("%s IN (%s)", column, strings.Join(placeholders, ",")), values
|
return fmt.Sprintf("%s IN (%s)", column, strings.Join(placeholders, ",")), values
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// BuildArrayOverlapCondition builds a parameterized condition testing whether an
|
||||||
|
// array column has at least one element in common with the given value(s), using
|
||||||
|
// PostgreSQL's array overlap operator (&&). Unlike a text-cast ILIKE, this performs
|
||||||
|
// real element-wise containment (no substring false positives) and can use a GIN
|
||||||
|
// index on the column. A single value is treated as a one-element array.
|
||||||
|
// Returns ("", nil) if the value is empty.
|
||||||
|
func BuildArrayOverlapCondition(column string, v interface{}) (query string, args []interface{}) {
|
||||||
|
values := FilterValueToSlice(v)
|
||||||
|
if len(values) == 0 {
|
||||||
|
return "", nil
|
||||||
|
}
|
||||||
|
placeholders := make([]string, len(values))
|
||||||
|
for i := range values {
|
||||||
|
placeholders[i] = "?"
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("%s && ARRAY[%s]", column, strings.Join(placeholders, ",")), values
|
||||||
|
}
|
||||||
|
|||||||
+147
-89
@@ -542,8 +542,8 @@ func TestSplitByAND(t *testing.T) {
|
|||||||
expected: []string{"col1 between 1 and 5", "col2 between 10 and 20"},
|
expected: []string{"col1 between 1 and 5", "col2 between 10 and 20"},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "complex OR block with multiple BETWEENs (real-world case)",
|
name: "complex OR block with multiple BETWEENs (real-world case)",
|
||||||
input: "tbl.applicationdate between '2025-08-31' and '1970-01-01'\n or tbl.capturedate between '2025-08-31' and '1970-01-01'\n or tbl.startdate between '2025-08-31' AND '1970-01-01'",
|
input: "tbl.applicationdate between '2025-08-31' and '1970-01-01'\n or tbl.capturedate between '2025-08-31' and '1970-01-01'\n or tbl.startdate between '2025-08-31' AND '1970-01-01'",
|
||||||
expected: []string{"tbl.applicationdate between '2025-08-31' and '1970-01-01'\n or tbl.capturedate between '2025-08-31' and '1970-01-01'\n or tbl.startdate between '2025-08-31' AND '1970-01-01'"},
|
expected: []string{"tbl.applicationdate between '2025-08-31' and '1970-01-01'\n or tbl.capturedate between '2025-08-31' and '1970-01-01'\n or tbl.startdate between '2025-08-31' AND '1970-01-01'"},
|
||||||
},
|
},
|
||||||
// Quote-aware cases: AND inside a string literal must not split.
|
// Quote-aware cases: AND inside a string literal must not split.
|
||||||
@@ -889,93 +889,151 @@ func TestSanitizeWhereClause_PreservesParenthesesWithOR(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestAddTablePrefixToColumns_ComplexConditions(t *testing.T) {
|
func TestAddTablePrefixToColumns_ComplexConditions(t *testing.T) {
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
name string
|
name string
|
||||||
where string
|
where string
|
||||||
tableName string
|
tableName string
|
||||||
expected string
|
expected string
|
||||||
}{
|
}{
|
||||||
{
|
{
|
||||||
name: "Parentheses with true AND condition - should not prefix true",
|
name: "Parentheses with true AND condition - should not prefix true",
|
||||||
where: "(true AND status = 'active')",
|
where: "(true AND status = 'active')",
|
||||||
tableName: "mastertask",
|
tableName: "mastertask",
|
||||||
expected: "(true AND mastertask.status = 'active')",
|
expected: "(true AND mastertask.status = 'active')",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "Parentheses with multiple conditions including true",
|
name: "Parentheses with multiple conditions including true",
|
||||||
where: "(true AND status = 'active' AND id > 5)",
|
where: "(true AND status = 'active' AND id > 5)",
|
||||||
tableName: "mastertask",
|
tableName: "mastertask",
|
||||||
expected: "(true AND mastertask.status = 'active' AND mastertask.id > 5)",
|
expected: "(true AND mastertask.status = 'active' AND mastertask.id > 5)",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "Nested parentheses with true",
|
name: "Nested parentheses with true",
|
||||||
where: "((true AND status = 'active'))",
|
where: "((true AND status = 'active'))",
|
||||||
tableName: "mastertask",
|
tableName: "mastertask",
|
||||||
expected: "((true AND mastertask.status = 'active'))",
|
expected: "((true AND mastertask.status = 'active'))",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "Mixed: false AND valid conditions",
|
name: "Mixed: false AND valid conditions",
|
||||||
where: "(false AND name = 'test')",
|
where: "(false AND name = 'test')",
|
||||||
tableName: "mastertask",
|
tableName: "mastertask",
|
||||||
expected: "(false AND mastertask.name = 'test')",
|
expected: "(false AND mastertask.name = 'test')",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "Mixed: null AND valid conditions",
|
name: "Mixed: null AND valid conditions",
|
||||||
where: "(null AND status = 'active')",
|
where: "(null AND status = 'active')",
|
||||||
tableName: "mastertask",
|
tableName: "mastertask",
|
||||||
expected: "(null AND mastertask.status = 'active')",
|
expected: "(null AND mastertask.status = 'active')",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "Multiple true conditions in parentheses",
|
name: "Multiple true conditions in parentheses",
|
||||||
where: "(true AND true AND status = 'active')",
|
where: "(true AND true AND status = 'active')",
|
||||||
tableName: "mastertask",
|
tableName: "mastertask",
|
||||||
expected: "(true AND true AND mastertask.status = 'active')",
|
expected: "(true AND true AND mastertask.status = 'active')",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "Simple true without parens - should not prefix",
|
name: "Simple true without parens - should not prefix",
|
||||||
where: "true",
|
where: "true",
|
||||||
tableName: "mastertask",
|
tableName: "mastertask",
|
||||||
expected: "true",
|
expected: "true",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "Simple condition without parens - should prefix",
|
name: "Simple condition without parens - should prefix",
|
||||||
where: "status = 'active'",
|
where: "status = 'active'",
|
||||||
tableName: "mastertask",
|
tableName: "mastertask",
|
||||||
expected: "mastertask.status = 'active'",
|
expected: "mastertask.status = 'active'",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "Unregistered table with true - should not prefix true",
|
name: "Unregistered table with true - should not prefix true",
|
||||||
where: "(true AND status = 'active')",
|
where: "(true AND status = 'active')",
|
||||||
tableName: "unregistered_table",
|
tableName: "unregistered_table",
|
||||||
expected: "(true AND unregistered_table.status = 'active')",
|
expected: "(true AND unregistered_table.status = 'active')",
|
||||||
},
|
},
|
||||||
// BETWEEN regression: date literals inside BETWEEN must not be prefixed as columns.
|
// BETWEEN regression: date literals inside BETWEEN must not be prefixed as columns.
|
||||||
{
|
{
|
||||||
name: "BETWEEN date range - second date must not be prefixed",
|
name: "BETWEEN date range - second date must not be prefixed",
|
||||||
where: "applicationdate between '2025-08-31' and '1970-01-01'",
|
where: "applicationdate between '2025-08-31' and '1970-01-01'",
|
||||||
tableName: "unregistered_table",
|
tableName: "unregistered_table",
|
||||||
expected: "unregistered_table.applicationdate between '2025-08-31' and '1970-01-01'",
|
expected: "unregistered_table.applicationdate between '2025-08-31' and '1970-01-01'",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "Already-prefixed BETWEEN column - unchanged",
|
name: "Already-prefixed BETWEEN column - unchanged",
|
||||||
where: `"v_webui_clients".applicationdate between '2025-08-31' and '1970-01-01'`,
|
where: `"v_webui_clients".applicationdate between '2025-08-31' and '1970-01-01'`,
|
||||||
tableName: "v_webui_clients",
|
tableName: "v_webui_clients",
|
||||||
expected: `"v_webui_clients".applicationdate between '2025-08-31' and '1970-01-01'`,
|
expected: `"v_webui_clients".applicationdate between '2025-08-31' and '1970-01-01'`,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "Complex OR block with multiple BETWEENs - date values must not be prefixed",
|
name: "Complex OR block with multiple BETWEENs - date values must not be prefixed",
|
||||||
where: `("v_webui_clients".applicationdate between '2025-08-31' and '1970-01-01' or "v_webui_clients".clientcapturedate between '2025-08-31' and '1970-01-01' or "v_webui_clients".startdate between '2025-08-31' AND '1970-01-01')`,
|
where: `("v_webui_clients".applicationdate between '2025-08-31' and '1970-01-01' or "v_webui_clients".clientcapturedate between '2025-08-31' and '1970-01-01' or "v_webui_clients".startdate between '2025-08-31' AND '1970-01-01')`,
|
||||||
tableName: "v_webui_clients",
|
tableName: "v_webui_clients",
|
||||||
expected: `("v_webui_clients".applicationdate between '2025-08-31' and '1970-01-01' or "v_webui_clients".clientcapturedate between '2025-08-31' and '1970-01-01' or "v_webui_clients".startdate between '2025-08-31' AND '1970-01-01')`,
|
expected: `("v_webui_clients".applicationdate between '2025-08-31' and '1970-01-01' or "v_webui_clients".clientcapturedate between '2025-08-31' and '1970-01-01' or "v_webui_clients".startdate between '2025-08-31' AND '1970-01-01')`,
|
||||||
},
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
result := AddTablePrefixToColumns(tt.where, tt.tableName)
|
||||||
|
if result != tt.expected {
|
||||||
|
t.Errorf("AddTablePrefixToColumns(%q, %q) = %q; want %q", tt.where, tt.tableName, result, tt.expected)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, tt := range tests {
|
func TestBuildArrayOverlapCondition(t *testing.T) {
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
tests := []struct {
|
||||||
result := AddTablePrefixToColumns(tt.where, tt.tableName)
|
name string
|
||||||
if result != tt.expected {
|
column string
|
||||||
t.Errorf("AddTablePrefixToColumns(%q, %q) = %q; want %q", tt.where, tt.tableName, result, tt.expected)
|
value interface{}
|
||||||
}
|
expectedCond string
|
||||||
})
|
expectedArgs int
|
||||||
}
|
}{
|
||||||
|
{
|
||||||
|
name: "single scalar value",
|
||||||
|
column: "tags",
|
||||||
|
value: "urgent",
|
||||||
|
expectedCond: "tags && ARRAY[?]",
|
||||||
|
expectedArgs: 1,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "multiple values",
|
||||||
|
column: "tags",
|
||||||
|
value: []string{"urgent", "billing", "vip"},
|
||||||
|
expectedCond: "tags && ARRAY[?,?,?]",
|
||||||
|
expectedArgs: 3,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "JSON-decoded []interface{} value",
|
||||||
|
column: "tags",
|
||||||
|
value: []interface{}{"urgent", "billing"},
|
||||||
|
expectedCond: "tags && ARRAY[?,?]",
|
||||||
|
expectedArgs: 2,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "nil value",
|
||||||
|
column: "tags",
|
||||||
|
value: nil,
|
||||||
|
expectedCond: "",
|
||||||
|
expectedArgs: 0,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "empty slice value",
|
||||||
|
column: "tags",
|
||||||
|
value: []string{},
|
||||||
|
expectedCond: "",
|
||||||
|
expectedArgs: 0,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
cond, args := BuildArrayOverlapCondition(tt.column, tt.value)
|
||||||
|
if cond != tt.expectedCond {
|
||||||
|
t.Errorf("BuildArrayOverlapCondition(%q, %v) condition = %q; want %q", tt.column, tt.value, cond, tt.expectedCond)
|
||||||
|
}
|
||||||
|
if len(args) != tt.expectedArgs {
|
||||||
|
t.Errorf("BuildArrayOverlapCondition(%q, %v) args = %d; want %d", tt.column, tt.value, len(args), tt.expectedArgs)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -51,7 +51,7 @@ func (h *Handler) ParseParameters(r *http.Request) *RequestParameters {
|
|||||||
FieldFilters: make(map[string]string),
|
FieldFilters: make(map[string]string),
|
||||||
SearchFilters: make(map[string]string),
|
SearchFilters: make(map[string]string),
|
||||||
SearchOps: make(map[string]FilterOperator),
|
SearchOps: make(map[string]FilterOperator),
|
||||||
Limit: 20, // Default limit
|
Limit: 100000, // Default limit
|
||||||
Offset: 0, // Default offset
|
Offset: 0, // Default offset
|
||||||
ResponseFormat: "simple", // Default format
|
ResponseFormat: "simple", // Default format
|
||||||
ComplexAPI: false, // Default to simple API
|
ComplexAPI: false, // Default to simple API
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"reflect"
|
"reflect"
|
||||||
"sync"
|
"sync"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ModelRules defines the permissions and security settings for a model
|
// ModelRules defines the permissions and security settings for a model
|
||||||
@@ -59,12 +60,44 @@ func NewModelRegistry() *DefaultModelRegistry {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// lockRetryAttempts/lockRetryDelay bound how long the try-lock helpers below
|
||||||
|
// will spin before giving up, so a contended registriesMutex can never hang
|
||||||
|
// a caller of GetDefaultRegistry/SetDefaultRegistry.
|
||||||
|
const (
|
||||||
|
lockRetryAttempts = 20
|
||||||
|
lockRetryDelay = 1 * time.Millisecond
|
||||||
|
)
|
||||||
|
|
||||||
|
// GetDefaultRegistry returns the current default registry. It uses a
|
||||||
|
// bounded TryRLock instead of a blocking RLock so it can never hang;
|
||||||
|
// if the lock can't be acquired in time it falls back to the last known
|
||||||
|
// value without synchronization.
|
||||||
func GetDefaultRegistry() *DefaultModelRegistry {
|
func GetDefaultRegistry() *DefaultModelRegistry {
|
||||||
|
for i := 0; i < lockRetryAttempts; i++ {
|
||||||
|
if registriesMutex.TryRLock() {
|
||||||
|
defer registriesMutex.RUnlock()
|
||||||
|
return defaultRegistry
|
||||||
|
}
|
||||||
|
time.Sleep(lockRetryDelay)
|
||||||
|
}
|
||||||
return defaultRegistry
|
return defaultRegistry
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SetDefaultRegistry replaces the default registry. It uses a bounded
|
||||||
|
// TryLock instead of a blocking Lock so it can never hang; if the lock
|
||||||
|
// can't be acquired in time the call is a no-op.
|
||||||
func SetDefaultRegistry(registry *DefaultModelRegistry) {
|
func SetDefaultRegistry(registry *DefaultModelRegistry) {
|
||||||
registriesMutex.Lock()
|
acquired := false
|
||||||
|
for i := 0; i < lockRetryAttempts; i++ {
|
||||||
|
if registriesMutex.TryLock() {
|
||||||
|
acquired = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
time.Sleep(lockRetryDelay)
|
||||||
|
}
|
||||||
|
if !acquired {
|
||||||
|
return
|
||||||
|
}
|
||||||
defer registriesMutex.Unlock()
|
defer registriesMutex.Unlock()
|
||||||
|
|
||||||
foundAt := -1
|
foundAt := -1
|
||||||
@@ -90,8 +123,34 @@ func AddRegistry(registry *DefaultModelRegistry) {
|
|||||||
registries = append(registries, registry)
|
registries = append(registries, registry)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// tryLock attempts to acquire the registry's write lock, retrying briefly.
|
||||||
|
// Returns false if it could not be acquired within the bound.
|
||||||
|
func (r *DefaultModelRegistry) tryLock() bool {
|
||||||
|
for i := 0; i < lockRetryAttempts; i++ {
|
||||||
|
if r.mutex.TryLock() {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
time.Sleep(lockRetryDelay)
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// tryRLock attempts to acquire the registry's read lock, retrying briefly.
|
||||||
|
// Returns false if it could not be acquired within the bound.
|
||||||
|
func (r *DefaultModelRegistry) tryRLock() bool {
|
||||||
|
for i := 0; i < lockRetryAttempts; i++ {
|
||||||
|
if r.mutex.TryRLock() {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
time.Sleep(lockRetryDelay)
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
func (r *DefaultModelRegistry) RegisterModel(name string, model interface{}) error {
|
func (r *DefaultModelRegistry) RegisterModel(name string, model interface{}) error {
|
||||||
r.mutex.Lock()
|
if !r.tryLock() {
|
||||||
|
return fmt.Errorf("failed to register model %s: registry locked", name)
|
||||||
|
}
|
||||||
defer r.mutex.Unlock()
|
defer r.mutex.Unlock()
|
||||||
|
|
||||||
if _, exists := r.models[name]; exists {
|
if _, exists := r.models[name]; exists {
|
||||||
@@ -137,7 +196,9 @@ func (r *DefaultModelRegistry) RegisterModel(name string, model interface{}) err
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (r *DefaultModelRegistry) GetModel(name string) (interface{}, error) {
|
func (r *DefaultModelRegistry) GetModel(name string) (interface{}, error) {
|
||||||
r.mutex.RLock()
|
if !r.tryRLock() {
|
||||||
|
return nil, fmt.Errorf("failed to get model %s: registry locked", name)
|
||||||
|
}
|
||||||
defer r.mutex.RUnlock()
|
defer r.mutex.RUnlock()
|
||||||
|
|
||||||
model, exists := r.models[name]
|
model, exists := r.models[name]
|
||||||
@@ -149,7 +210,9 @@ func (r *DefaultModelRegistry) GetModel(name string) (interface{}, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (r *DefaultModelRegistry) GetAllModels() map[string]interface{} {
|
func (r *DefaultModelRegistry) GetAllModels() map[string]interface{} {
|
||||||
r.mutex.RLock()
|
if !r.tryRLock() {
|
||||||
|
return make(map[string]interface{})
|
||||||
|
}
|
||||||
defer r.mutex.RUnlock()
|
defer r.mutex.RUnlock()
|
||||||
|
|
||||||
result := make(map[string]interface{})
|
result := make(map[string]interface{})
|
||||||
@@ -253,14 +316,26 @@ func IterateModels(fn func(name string, model interface{})) {
|
|||||||
// GetModels returns a list of all models from all registries
|
// GetModels returns a list of all models from all registries
|
||||||
// Models are collected in registry order, with duplicates included
|
// Models are collected in registry order, with duplicates included
|
||||||
func GetModels() []interface{} {
|
func GetModels() []interface{} {
|
||||||
registriesMutex.RLock()
|
acquired := false
|
||||||
|
for i := 0; i < lockRetryAttempts; i++ {
|
||||||
|
if registriesMutex.TryRLock() {
|
||||||
|
acquired = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
time.Sleep(lockRetryDelay)
|
||||||
|
}
|
||||||
|
if !acquired {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
defer registriesMutex.RUnlock()
|
defer registriesMutex.RUnlock()
|
||||||
|
|
||||||
var models []interface{}
|
var models []interface{}
|
||||||
seen := make(map[string]bool)
|
seen := make(map[string]bool)
|
||||||
|
|
||||||
for _, registry := range registries {
|
for _, registry := range registries {
|
||||||
registry.mutex.RLock()
|
if !registry.tryRLock() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
for name, model := range registry.models {
|
for name, model := range registry.models {
|
||||||
// Only add the first occurrence of each model name
|
// Only add the first occurrence of each model name
|
||||||
if !seen[name] {
|
if !seen[name] {
|
||||||
|
|||||||
@@ -340,18 +340,28 @@ func (h *Handler) executeRead(ctx context.Context, schema, entity, id string, op
|
|||||||
|
|
||||||
var data interface{}
|
var data interface{}
|
||||||
if id != "" {
|
if id != "" {
|
||||||
singleResult := reflect.New(modelType).Interface()
|
pkName := reflection.GetPrimaryKeyName(model)
|
||||||
pkName := reflection.GetPrimaryKeyName(singleResult)
|
|
||||||
query = query.Where(fmt.Sprintf("%s = ?", common.QuoteIdent(pkName)), id)
|
query = query.Where(fmt.Sprintf("%s = ?", common.QuoteIdent(pkName)), id)
|
||||||
if err := query.Scan(ctx, singleResult); err != nil {
|
// Scan through the model configured on the query. Bun rejects Scan with
|
||||||
|
// a destination when the query preloads a has-many relation.
|
||||||
|
if err := query.ScanModel(ctx); err != nil {
|
||||||
if err == sql.ErrNoRows {
|
if err == sql.ErrNoRows {
|
||||||
return nil, nil, fmt.Errorf("record not found")
|
return nil, nil, fmt.Errorf("record not found")
|
||||||
}
|
}
|
||||||
return nil, nil, fmt.Errorf("query error: %w", err)
|
return nil, nil, fmt.Errorf("query error: %w", err)
|
||||||
}
|
}
|
||||||
data = singleResult
|
|
||||||
|
// The configured model is a slice so the same query construction works
|
||||||
|
// for both collection and single-record reads. Extract its one result.
|
||||||
|
scannedResults := reflect.ValueOf(modelPtr).Elem()
|
||||||
|
if scannedResults.Len() == 0 {
|
||||||
|
return nil, nil, fmt.Errorf("record not found")
|
||||||
|
}
|
||||||
|
data = scannedResults.Index(0).Interface()
|
||||||
} else {
|
} else {
|
||||||
if err := query.Scan(ctx, modelPtr); err != nil {
|
// Use the model already configured on the query. This is required by
|
||||||
|
// Bun whenever the query includes a has-many preload.
|
||||||
|
if err := query.ScanModel(ctx); err != nil {
|
||||||
return nil, nil, fmt.Errorf("query error: %w", err)
|
return nil, nil, fmt.Errorf("query error: %w", err)
|
||||||
}
|
}
|
||||||
data = reflect.ValueOf(modelPtr).Elem().Interface()
|
data = reflect.ValueOf(modelPtr).Elem().Interface()
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ package resolvemcp
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"runtime/debug"
|
||||||
|
|
||||||
"github.com/gorilla/mux"
|
"github.com/gorilla/mux"
|
||||||
"github.com/uptrace/bun"
|
"github.com/uptrace/bun"
|
||||||
@@ -25,6 +26,7 @@ import (
|
|||||||
|
|
||||||
"github.com/bitechdev/ResolveSpec/pkg/common"
|
"github.com/bitechdev/ResolveSpec/pkg/common"
|
||||||
"github.com/bitechdev/ResolveSpec/pkg/common/adapters/database"
|
"github.com/bitechdev/ResolveSpec/pkg/common/adapters/database"
|
||||||
|
"github.com/bitechdev/ResolveSpec/pkg/logger"
|
||||||
"github.com/bitechdev/ResolveSpec/pkg/modelregistry"
|
"github.com/bitechdev/ResolveSpec/pkg/modelregistry"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -82,11 +84,20 @@ func SetupMuxRoutes(muxRouter *mux.Router, handler *Handler) {
|
|||||||
// - GET {basePath}/sse — SSE connection endpoint
|
// - GET {basePath}/sse — SSE connection endpoint
|
||||||
// - POST {basePath}/message — JSON-RPC message endpoint
|
// - POST {basePath}/message — JSON-RPC message endpoint
|
||||||
func SetupBunRouterRoutes(router *bunrouter.Router, handler *Handler) {
|
func SetupBunRouterRoutes(router *bunrouter.Router, handler *Handler) {
|
||||||
|
defer func() {
|
||||||
|
if rec := recover(); rec != nil {
|
||||||
|
logger.Error("panic in resolvemcp.SetupBunRouterRoutes: %v\n%s", rec, debug.Stack())
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
basePath := handler.config.BasePath
|
basePath := handler.config.BasePath
|
||||||
h := handler.SSEServer()
|
h := handler.SSEServer()
|
||||||
|
|
||||||
router.GET(basePath+"/sse", bunrouter.HTTPHandler(h))
|
router.GET(basePath+"/sse", bunrouter.HTTPHandler(h))
|
||||||
|
logger.Info("Registered resolvemcp bunrouter route GET %s/sse", basePath)
|
||||||
|
|
||||||
router.POST(basePath+"/message", bunrouter.HTTPHandler(h))
|
router.POST(basePath+"/message", bunrouter.HTTPHandler(h))
|
||||||
|
logger.Info("Registered resolvemcp bunrouter route POST %s/message", basePath)
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewSSEServer returns an http.Handler that serves MCP over SSE.
|
// NewSSEServer returns an http.Handler that serves MCP over SSE.
|
||||||
|
|||||||
+31
-3
@@ -85,13 +85,19 @@ func buildModelInfo(schema, entity string, model interface{}) modelInfo {
|
|||||||
|
|
||||||
// Skip relation fields (slice or user-defined struct that isn't time.Time).
|
// Skip relation fields (slice or user-defined struct that isn't time.Time).
|
||||||
fieldType, found := modelType.FieldByName(d.Name)
|
fieldType, found := modelType.FieldByName(d.Name)
|
||||||
|
var unwrappedType reflect.Type
|
||||||
|
isSQLType := false
|
||||||
if found {
|
if found {
|
||||||
ft := fieldType.Type
|
ft := fieldType.Type
|
||||||
if ft.Kind() == reflect.Pointer {
|
if sqlType, ok := unwrapSQLType(ft); ok {
|
||||||
|
unwrappedType = sqlType
|
||||||
|
ft = sqlType
|
||||||
|
isSQLType = true
|
||||||
|
} else if ft.Kind() == reflect.Pointer {
|
||||||
ft = ft.Elem()
|
ft = ft.Elem()
|
||||||
}
|
}
|
||||||
isUserStruct := ft.Kind() == reflect.Struct && ft.Name() != "Time" && ft.PkgPath() != ""
|
isUserStruct := ft.Kind() == reflect.Struct && ft.Name() != "Time" && ft.PkgPath() != ""
|
||||||
if ft.Kind() == reflect.Slice || isUserStruct {
|
if !isSQLType && (ft.Kind() == reflect.Slice || isUserStruct) {
|
||||||
info.relationNames = append(info.relationNames, jsonName)
|
info.relationNames = append(info.relationNames, jsonName)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -104,6 +110,9 @@ func buildModelInfo(schema, entity string, model interface{}) modelInfo {
|
|||||||
|
|
||||||
// Derive Go type name, unwrapping pointer if needed.
|
// Derive Go type name, unwrapping pointer if needed.
|
||||||
goType := d.DataType
|
goType := d.DataType
|
||||||
|
if isSQLType {
|
||||||
|
goType = unwrappedType.Name()
|
||||||
|
}
|
||||||
if goType == "" && found {
|
if goType == "" && found {
|
||||||
ft := fieldType.Type
|
ft := fieldType.Type
|
||||||
for ft.Kind() == reflect.Pointer {
|
for ft.Kind() == reflect.Pointer {
|
||||||
@@ -125,7 +134,7 @@ func buildModelInfo(schema, entity string, model interface{}) modelInfo {
|
|||||||
isPrimary: isPrimary,
|
isPrimary: isPrimary,
|
||||||
isUnique: d.SQLKey == "unique" || d.SQLKey == "uniqueindex",
|
isUnique: d.SQLKey == "unique" || d.SQLKey == "uniqueindex",
|
||||||
isFK: d.SQLKey == "foreign_key",
|
isFK: d.SQLKey == "foreign_key",
|
||||||
nullable: d.Nullable,
|
nullable: isSQLType || d.Nullable,
|
||||||
}
|
}
|
||||||
info.columns = append(info.columns, ci)
|
info.columns = append(info.columns, ci)
|
||||||
}
|
}
|
||||||
@@ -134,6 +143,25 @@ func buildModelInfo(schema, entity string, model interface{}) modelInfo {
|
|||||||
return info
|
return info
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// unwrapSQLType returns the value type wrapped by a spectypes SQL value. These
|
||||||
|
// types are scalar columns even when their Go representation is a struct or a
|
||||||
|
// slice (for example, SqlNull[string] and SqlJSONB).
|
||||||
|
func unwrapSQLType(t reflect.Type) (reflect.Type, bool) {
|
||||||
|
for t.Kind() == reflect.Pointer {
|
||||||
|
t = t.Elem()
|
||||||
|
}
|
||||||
|
|
||||||
|
if t.PkgPath() != "github.com/bitechdev/ResolveSpec/pkg/spectypes" {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
if t.Kind() == reflect.Struct {
|
||||||
|
if value, ok := t.FieldByName("Val"); ok {
|
||||||
|
return value.Type, true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return t, true
|
||||||
|
}
|
||||||
|
|
||||||
// fieldJSONName returns the JSON tag name for a struct field, falling back to the field name.
|
// fieldJSONName returns the JSON tag name for a struct field, falling back to the field name.
|
||||||
func fieldJSONName(modelType reflect.Type, fieldName string) string {
|
func fieldJSONName(modelType reflect.Type, fieldName string) string {
|
||||||
field, ok := modelType.FieldByName(fieldName)
|
field, ok := modelType.FieldByName(fieldName)
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
package resolvemcp
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/bitechdev/ResolveSpec/pkg/spectypes"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestBuildModelInfo_UnwrapsSQLTypes(t *testing.T) {
|
||||||
|
type related struct {
|
||||||
|
ID int64 `json:"id"`
|
||||||
|
}
|
||||||
|
type model struct {
|
||||||
|
Name spectypes.SqlString `gorm:"column:name" json:"name"`
|
||||||
|
Metadata spectypes.SqlJSONB `gorm:"column:metadata;type:jsonb" json:"metadata"`
|
||||||
|
Related related `json:"related"`
|
||||||
|
}
|
||||||
|
|
||||||
|
info := buildModelInfo("public", "models", model{})
|
||||||
|
columns := make(map[string]columnInfo, len(info.columns))
|
||||||
|
for _, column := range info.columns {
|
||||||
|
columns[column.jsonName] = column
|
||||||
|
}
|
||||||
|
|
||||||
|
if column, ok := columns["name"]; !ok || column.goType != "string" || !column.nullable {
|
||||||
|
t.Errorf("expected name SQL wrapper column, got %+v", column)
|
||||||
|
}
|
||||||
|
if column, ok := columns["metadata"]; !ok || !column.nullable {
|
||||||
|
t.Errorf("expected metadata SQL wrapper column, got %+v", column)
|
||||||
|
}
|
||||||
|
if len(info.relationNames) != 1 || info.relationNames[0] != "related" {
|
||||||
|
t.Errorf("expected only related to be a relation, got %v", info.relationNames)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -57,6 +57,36 @@ func TestBuildFilterCondition(t *testing.T) {
|
|||||||
expectedCondition: "CAST(email AS TEXT) LIKE ?",
|
expectedCondition: "CAST(email AS TEXT) LIKE ?",
|
||||||
expectedArgsCount: 1,
|
expectedArgsCount: 1,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: "CONTAINS operator with single value",
|
||||||
|
filter: common.FilterOption{
|
||||||
|
Column: "tags",
|
||||||
|
Operator: "contains",
|
||||||
|
Value: "urgent",
|
||||||
|
},
|
||||||
|
expectedCondition: "tags && ARRAY[?]",
|
||||||
|
expectedArgsCount: 1,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "CONTAINS operator with multiple values",
|
||||||
|
filter: common.FilterOption{
|
||||||
|
Column: "tags",
|
||||||
|
Operator: "contains",
|
||||||
|
Value: []string{"urgent", "billing"},
|
||||||
|
},
|
||||||
|
expectedCondition: "tags && ARRAY[?,?]",
|
||||||
|
expectedArgsCount: 2,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "CONTAINS operator with empty value",
|
||||||
|
filter: common.FilterOption{
|
||||||
|
Column: "tags",
|
||||||
|
Operator: "contains",
|
||||||
|
Value: nil,
|
||||||
|
},
|
||||||
|
expectedCondition: "",
|
||||||
|
expectedArgsCount: 0,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, tt := range tests {
|
for _, tt := range tests {
|
||||||
|
|||||||
+61
-11
@@ -565,9 +565,7 @@ func (h *Handler) handleRead(ctx context.Context, w common.ResponseWriter, id st
|
|||||||
logger.Debug("Querying single record with FetchRowNumber ID: %s", targetID)
|
logger.Debug("Querying single record with FetchRowNumber ID: %s", targetID)
|
||||||
}
|
}
|
||||||
|
|
||||||
// For single record, create a new pointer to the struct type
|
pkName := reflection.GetPrimaryKeyName(model)
|
||||||
singleResult := reflect.New(modelType).Interface()
|
|
||||||
pkName := reflection.GetPrimaryKeyName(singleResult)
|
|
||||||
|
|
||||||
query = query.Where(fmt.Sprintf("%s = ?", common.QuoteIdent(pkName)), targetID)
|
query = query.Where(fmt.Sprintf("%s = ?", common.QuoteIdent(pkName)), targetID)
|
||||||
|
|
||||||
@@ -580,12 +578,21 @@ func (h *Handler) handleRead(ctx context.Context, w common.ResponseWriter, id st
|
|||||||
}
|
}
|
||||||
query = hookCtx.Query
|
query = hookCtx.Query
|
||||||
|
|
||||||
if err := query.Scan(ctx, singleResult); err != nil {
|
// Scan through the model configured on the query. Bun rejects Scan with
|
||||||
|
// a destination when the query preloads a has-many relation.
|
||||||
|
if err := query.ScanModel(ctx); err != nil {
|
||||||
logger.Error("Error querying record: %v", err)
|
logger.Error("Error querying record: %v", err)
|
||||||
statusCode, errCode, errMsg = http.StatusInternalServerError, "query_error", "Error executing query"
|
statusCode, errCode, errMsg = http.StatusInternalServerError, "query_error", "Error executing query"
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
result = singleResult
|
|
||||||
|
// The configured model is a slice so the same query construction works
|
||||||
|
// for both collection and single-record reads. Extract its one result.
|
||||||
|
scannedResults := reflect.ValueOf(modelPtr).Elem()
|
||||||
|
if scannedResults.Len() == 0 {
|
||||||
|
return sql.ErrNoRows
|
||||||
|
}
|
||||||
|
result = scannedResults.Index(0).Interface()
|
||||||
} else {
|
} else {
|
||||||
logger.Debug("Querying multiple records")
|
logger.Debug("Querying multiple records")
|
||||||
|
|
||||||
@@ -598,8 +605,9 @@ func (h *Handler) handleRead(ctx context.Context, w common.ResponseWriter, id st
|
|||||||
}
|
}
|
||||||
query = hookCtx.Query
|
query = hookCtx.Query
|
||||||
|
|
||||||
// Use the modelPtr already created and set on the query
|
// Use the model already configured on the query. This is required by
|
||||||
if err := query.Scan(ctx, modelPtr); err != nil {
|
// Bun whenever the query includes a has-many preload.
|
||||||
|
if err := query.ScanModel(ctx); err != nil {
|
||||||
logger.Error("Error querying records: %v", err)
|
logger.Error("Error querying records: %v", err)
|
||||||
statusCode, errCode, errMsg = http.StatusInternalServerError, "query_error", "Error executing query"
|
statusCode, errCode, errMsg = http.StatusInternalServerError, "query_error", "Error executing query"
|
||||||
return err
|
return err
|
||||||
@@ -1895,6 +1903,11 @@ func (h *Handler) buildFilterCondition(filter common.FilterOption) (conditionStr
|
|||||||
if condition == "" {
|
if condition == "" {
|
||||||
return "", nil
|
return "", nil
|
||||||
}
|
}
|
||||||
|
case "contains":
|
||||||
|
condition, args = common.BuildArrayOverlapCondition(filter.Column, filter.Value)
|
||||||
|
if condition == "" {
|
||||||
|
return "", nil
|
||||||
|
}
|
||||||
default:
|
default:
|
||||||
return "", nil
|
return "", nil
|
||||||
}
|
}
|
||||||
@@ -1939,6 +1952,11 @@ func (h *Handler) applyFilter(query common.SelectQuery, filter common.FilterOpti
|
|||||||
if condition == "" {
|
if condition == "" {
|
||||||
return query
|
return query
|
||||||
}
|
}
|
||||||
|
case "contains":
|
||||||
|
condition, args = common.BuildArrayOverlapCondition(filter.Column, filter.Value)
|
||||||
|
if condition == "" {
|
||||||
|
return query
|
||||||
|
}
|
||||||
default:
|
default:
|
||||||
return query
|
return query
|
||||||
}
|
}
|
||||||
@@ -2063,16 +2081,23 @@ func (h *Handler) generateMetadata(schema, entity string, model interface{}) *co
|
|||||||
jsonName = field.Name
|
jsonName = field.Name
|
||||||
}
|
}
|
||||||
|
|
||||||
if field.Type.Kind() == reflect.Slice ||
|
columnField := field
|
||||||
(field.Type.Kind() == reflect.Struct && field.Type.Name() != "Time") {
|
isSQLType := false
|
||||||
|
if unwrappedType, ok := unwrapSQLType(field.Type); ok {
|
||||||
|
columnField.Type = unwrappedType
|
||||||
|
isSQLType = true
|
||||||
|
}
|
||||||
|
|
||||||
|
if !isSQLType && (columnField.Type.Kind() == reflect.Slice ||
|
||||||
|
(columnField.Type.Kind() == reflect.Struct && columnField.Type.Name() != "Time")) {
|
||||||
metadata.Relations = append(metadata.Relations, jsonName)
|
metadata.Relations = append(metadata.Relations, jsonName)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
column := common.Column{
|
column := common.Column{
|
||||||
Name: jsonName,
|
Name: jsonName,
|
||||||
Type: getColumnType(field),
|
Type: getColumnType(columnField),
|
||||||
IsNullable: isNullable(field),
|
IsNullable: isSQLType || isNullable(field),
|
||||||
IsPrimary: strings.Contains(gormTag, "primaryKey"),
|
IsPrimary: strings.Contains(gormTag, "primaryKey"),
|
||||||
IsUnique: strings.Contains(gormTag, "unique") || strings.Contains(gormTag, "uniqueIndex"),
|
IsUnique: strings.Contains(gormTag, "unique") || strings.Contains(gormTag, "uniqueIndex"),
|
||||||
HasIndex: strings.Contains(gormTag, "index") || strings.Contains(gormTag, "uniqueIndex"),
|
HasIndex: strings.Contains(gormTag, "index") || strings.Contains(gormTag, "uniqueIndex"),
|
||||||
@@ -2163,6 +2188,31 @@ func getColumnType(field reflect.StructField) string {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// unwrapSQLType returns the value type wrapped by a spectypes SQL value. These
|
||||||
|
// types represent columns, even when their Go representation is a struct or a
|
||||||
|
// slice (for example, SqlNull[string] and SqlJSONB).
|
||||||
|
func unwrapSQLType(t reflect.Type) (reflect.Type, bool) {
|
||||||
|
for t.Kind() == reflect.Pointer {
|
||||||
|
t = t.Elem()
|
||||||
|
}
|
||||||
|
|
||||||
|
if t.PkgPath() != "github.com/bitechdev/ResolveSpec/pkg/spectypes" {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
|
||||||
|
// SqlNull aliases and the date/time wrappers expose their actual value via
|
||||||
|
// Val. FieldByName also resolves Val through the embedded SqlNull field.
|
||||||
|
if t.Kind() == reflect.Struct {
|
||||||
|
if value, ok := t.FieldByName("Val"); ok {
|
||||||
|
return value.Type, true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// SqlJSONB has no wrapper field, but remains a scalar SQL value rather than
|
||||||
|
// a relation.
|
||||||
|
return t, true
|
||||||
|
}
|
||||||
|
|
||||||
func isNullable(field reflect.StructField) bool {
|
func isNullable(field reflect.StructField) bool {
|
||||||
// Check if it's a pointer type
|
// Check if it's a pointer type
|
||||||
if field.Type.Kind() == reflect.Pointer {
|
if field.Type.Kind() == reflect.Pointer {
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/bitechdev/ResolveSpec/pkg/common"
|
"github.com/bitechdev/ResolveSpec/pkg/common"
|
||||||
|
"github.com/bitechdev/ResolveSpec/pkg/spectypes"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestNewHandler(t *testing.T) {
|
func TestNewHandler(t *testing.T) {
|
||||||
@@ -202,6 +203,48 @@ func TestGetColumnType(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestGenerateMetadata_UnwrapsSQLTypes(t *testing.T) {
|
||||||
|
type related struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
}
|
||||||
|
type model struct {
|
||||||
|
Name spectypes.SqlString `json:"name"`
|
||||||
|
Count spectypes.SqlInt64 `json:"count"`
|
||||||
|
CreatedAt spectypes.SqlTimeStamp `json:"created_at"`
|
||||||
|
Metadata spectypes.SqlJSONB `json:"metadata" gorm:"type:jsonb"`
|
||||||
|
Related related `json:"related"`
|
||||||
|
}
|
||||||
|
|
||||||
|
metadata := NewHandler(nil, nil).generateMetadata("public", "models", model{})
|
||||||
|
columns := make(map[string]common.Column, len(metadata.Columns))
|
||||||
|
for _, column := range metadata.Columns {
|
||||||
|
columns[column.Name] = column
|
||||||
|
}
|
||||||
|
|
||||||
|
for name, wantType := range map[string]string{
|
||||||
|
"name": "string",
|
||||||
|
"count": "bigint",
|
||||||
|
"created_at": "timestamp",
|
||||||
|
"metadata": "jsonb",
|
||||||
|
} {
|
||||||
|
column, ok := columns[name]
|
||||||
|
if !ok {
|
||||||
|
t.Errorf("expected %q to be a metadata column", name)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if column.Type != wantType {
|
||||||
|
t.Errorf("%q: expected type %q, got %q", name, wantType, column.Type)
|
||||||
|
}
|
||||||
|
if !column.IsNullable {
|
||||||
|
t.Errorf("%q: expected SQL wrapper to be nullable", name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(metadata.Relations) != 1 || metadata.Relations[0] != "related" {
|
||||||
|
t.Errorf("expected only related to be a relation, got %v", metadata.Relations)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestIsNullable(t *testing.T) {
|
func TestIsNullable(t *testing.T) {
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
name string
|
name string
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ package resolvespec
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/bitechdev/ResolveSpec/pkg/common"
|
"github.com/bitechdev/ResolveSpec/pkg/common"
|
||||||
"github.com/bitechdev/ResolveSpec/pkg/logger"
|
"github.com/bitechdev/ResolveSpec/pkg/logger"
|
||||||
@@ -82,6 +84,7 @@ type HookFunc func(*HookContext) error
|
|||||||
// HookRegistry manages all registered hooks
|
// HookRegistry manages all registered hooks
|
||||||
type HookRegistry struct {
|
type HookRegistry struct {
|
||||||
hooks map[HookType][]HookFunc
|
hooks map[HookType][]HookFunc
|
||||||
|
mutex sync.RWMutex
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewHookRegistry creates a new hook registry
|
// NewHookRegistry creates a new hook registry
|
||||||
@@ -91,8 +94,46 @@ func NewHookRegistry() *HookRegistry {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// hookLockRetryAttempts/hookLockRetryDelay bound how long the try-lock
|
||||||
|
// helpers below will spin before giving up, so a contended mutex can
|
||||||
|
// never hang a caller.
|
||||||
|
const (
|
||||||
|
hookLockRetryAttempts = 20
|
||||||
|
hookLockRetryDelay = 1 * time.Millisecond
|
||||||
|
)
|
||||||
|
|
||||||
|
// tryLock attempts to acquire the write lock, retrying briefly. Returns
|
||||||
|
// false if it could not be acquired within the bound.
|
||||||
|
func (r *HookRegistry) tryLock() bool {
|
||||||
|
for i := 0; i < hookLockRetryAttempts; i++ {
|
||||||
|
if r.mutex.TryLock() {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
time.Sleep(hookLockRetryDelay)
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// tryRLock attempts to acquire the read lock, retrying briefly. Returns
|
||||||
|
// false if it could not be acquired within the bound.
|
||||||
|
func (r *HookRegistry) tryRLock() bool {
|
||||||
|
for i := 0; i < hookLockRetryAttempts; i++ {
|
||||||
|
if r.mutex.TryRLock() {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
time.Sleep(hookLockRetryDelay)
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
// Register adds a new hook for the specified hook type
|
// Register adds a new hook for the specified hook type
|
||||||
func (r *HookRegistry) Register(hookType HookType, hook HookFunc) {
|
func (r *HookRegistry) Register(hookType HookType, hook HookFunc) {
|
||||||
|
if !r.tryLock() {
|
||||||
|
logger.Error("Failed to register resolvespec hook for %s: registry locked", hookType)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer r.mutex.Unlock()
|
||||||
|
|
||||||
if r.hooks == nil {
|
if r.hooks == nil {
|
||||||
r.hooks = make(map[HookType][]HookFunc)
|
r.hooks = make(map[HookType][]HookFunc)
|
||||||
}
|
}
|
||||||
@@ -110,8 +151,13 @@ func (r *HookRegistry) RegisterMultiple(hookTypes []HookType, hook HookFunc) {
|
|||||||
// Execute runs all hooks for the specified type in order
|
// Execute runs all hooks for the specified type in order
|
||||||
// If any hook returns an error, execution stops and the error is returned
|
// If any hook returns an error, execution stops and the error is returned
|
||||||
func (r *HookRegistry) Execute(hookType HookType, ctx *HookContext) error {
|
func (r *HookRegistry) Execute(hookType HookType, ctx *HookContext) error {
|
||||||
hooks, exists := r.hooks[hookType]
|
if !r.tryRLock() {
|
||||||
if !exists || len(hooks) == 0 {
|
return fmt.Errorf("hook execution failed: registry locked")
|
||||||
|
}
|
||||||
|
hooks := append([]HookFunc(nil), r.hooks[hookType]...)
|
||||||
|
r.mutex.RUnlock()
|
||||||
|
|
||||||
|
if len(hooks) == 0 {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -145,18 +191,35 @@ func (r *HookRegistry) ExecuteBeforeOp(hookType HookType, ctx *HookContext) erro
|
|||||||
|
|
||||||
// Clear removes all hooks for the specified type
|
// Clear removes all hooks for the specified type
|
||||||
func (r *HookRegistry) Clear(hookType HookType) {
|
func (r *HookRegistry) Clear(hookType HookType) {
|
||||||
|
if !r.tryLock() {
|
||||||
|
logger.Error("Failed to clear resolvespec hooks for %s: registry locked", hookType)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer r.mutex.Unlock()
|
||||||
|
|
||||||
delete(r.hooks, hookType)
|
delete(r.hooks, hookType)
|
||||||
logger.Info("Cleared all resolvespec hooks for %s", hookType)
|
logger.Info("Cleared all resolvespec hooks for %s", hookType)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ClearAll removes all registered hooks
|
// ClearAll removes all registered hooks
|
||||||
func (r *HookRegistry) ClearAll() {
|
func (r *HookRegistry) ClearAll() {
|
||||||
|
if !r.tryLock() {
|
||||||
|
logger.Error("Failed to clear all resolvespec hooks: registry locked")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer r.mutex.Unlock()
|
||||||
|
|
||||||
r.hooks = make(map[HookType][]HookFunc)
|
r.hooks = make(map[HookType][]HookFunc)
|
||||||
logger.Info("Cleared all resolvespec hooks")
|
logger.Info("Cleared all resolvespec hooks")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Count returns the number of hooks registered for a specific type
|
// Count returns the number of hooks registered for a specific type
|
||||||
func (r *HookRegistry) Count(hookType HookType) int {
|
func (r *HookRegistry) Count(hookType HookType) int {
|
||||||
|
if !r.tryRLock() {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
defer r.mutex.RUnlock()
|
||||||
|
|
||||||
if hooks, exists := r.hooks[hookType]; exists {
|
if hooks, exists := r.hooks[hookType]; exists {
|
||||||
return len(hooks)
|
return len(hooks)
|
||||||
}
|
}
|
||||||
@@ -170,6 +233,11 @@ func (r *HookRegistry) HasHooks(hookType HookType) bool {
|
|||||||
|
|
||||||
// GetAllHookTypes returns all hook types that have registered hooks
|
// GetAllHookTypes returns all hook types that have registered hooks
|
||||||
func (r *HookRegistry) GetAllHookTypes() []HookType {
|
func (r *HookRegistry) GetAllHookTypes() []HookType {
|
||||||
|
if !r.tryRLock() {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
defer r.mutex.RUnlock()
|
||||||
|
|
||||||
types := make([]HookType, 0, len(r.hooks))
|
types := make([]HookType, 0, len(r.hooks))
|
||||||
for hookType := range r.hooks {
|
for hookType := range r.hooks {
|
||||||
types = append(types, hookType)
|
types = append(types, hookType)
|
||||||
|
|||||||
+105
-88
@@ -2,6 +2,7 @@ package resolvespec
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"runtime/debug"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/gorilla/mux"
|
"github.com/gorilla/mux"
|
||||||
@@ -12,6 +13,7 @@ import (
|
|||||||
"github.com/bitechdev/ResolveSpec/pkg/common"
|
"github.com/bitechdev/ResolveSpec/pkg/common"
|
||||||
"github.com/bitechdev/ResolveSpec/pkg/common/adapters/database"
|
"github.com/bitechdev/ResolveSpec/pkg/common/adapters/database"
|
||||||
"github.com/bitechdev/ResolveSpec/pkg/common/adapters/router"
|
"github.com/bitechdev/ResolveSpec/pkg/common/adapters/router"
|
||||||
|
"github.com/bitechdev/ResolveSpec/pkg/logger"
|
||||||
"github.com/bitechdev/ResolveSpec/pkg/modelregistry"
|
"github.com/bitechdev/ResolveSpec/pkg/modelregistry"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -244,6 +246,11 @@ func wrapBunRouterHandler(handler bunrouter.HandlerFunc, authMiddleware Middlewa
|
|||||||
// Accepts bunrouter.Router or bunrouter.Group
|
// Accepts bunrouter.Router or bunrouter.Group
|
||||||
// authMiddleware is optional - if provided, routes will be protected with the middleware
|
// authMiddleware is optional - if provided, routes will be protected with the middleware
|
||||||
func SetupBunRouterRoutes(r BunRouterHandler, handler *Handler, authMiddleware MiddlewareFunc) {
|
func SetupBunRouterRoutes(r BunRouterHandler, handler *Handler, authMiddleware MiddlewareFunc) {
|
||||||
|
defer func() {
|
||||||
|
if rec := recover(); rec != nil {
|
||||||
|
logger.Error("panic in resolvespec.SetupBunRouterRoutes: %v\n%s", rec, debug.Stack())
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
// CORS config
|
// CORS config
|
||||||
corsConfig := common.DefaultCORSConfig()
|
corsConfig := common.DefaultCORSConfig()
|
||||||
@@ -269,112 +276,122 @@ func SetupBunRouterRoutes(r BunRouterHandler, handler *Handler, authMiddleware M
|
|||||||
|
|
||||||
// Loop through each registered model and create explicit routes
|
// Loop through each registered model and create explicit routes
|
||||||
for fullName := range allModels {
|
for fullName := range allModels {
|
||||||
// Parse the full name (e.g., "public.users" or just "users")
|
func() {
|
||||||
schema, entity := parseModelName(fullName)
|
defer func() {
|
||||||
|
if rec := recover(); rec != nil {
|
||||||
|
logger.Error("panic registering resolvespec routes for model %s: %v\n%s", fullName, rec, debug.Stack())
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
// Build the route paths
|
// Parse the full name (e.g., "public.users" or just "users")
|
||||||
entityPath := buildRoutePath(schema, entity)
|
schema, entity := parseModelName(fullName)
|
||||||
entityWithIDPath := entityPath + "/:id"
|
|
||||||
|
|
||||||
// Create closure variables to capture current schema and entity
|
// Build the route paths
|
||||||
currentSchema := schema
|
entityPath := buildRoutePath(schema, entity)
|
||||||
currentEntity := entity
|
entityWithIDPath := entityPath + "/:id"
|
||||||
|
|
||||||
// POST route without ID
|
// Create closure variables to capture current schema and entity
|
||||||
postEntityHandler := func(w http.ResponseWriter, req bunrouter.Request) error {
|
currentSchema := schema
|
||||||
respAdapter := router.NewHTTPResponseWriter(w)
|
currentEntity := entity
|
||||||
reqAdapter := router.NewHTTPRequest(req.Request)
|
|
||||||
common.SetCORSHeaders(respAdapter, reqAdapter, corsConfig)
|
// POST route without ID
|
||||||
params := map[string]string{
|
postEntityHandler := func(w http.ResponseWriter, req bunrouter.Request) error {
|
||||||
"schema": currentSchema,
|
respAdapter := router.NewHTTPResponseWriter(w)
|
||||||
"entity": currentEntity,
|
reqAdapter := router.NewHTTPRequest(req.Request)
|
||||||
|
common.SetCORSHeaders(respAdapter, reqAdapter, corsConfig)
|
||||||
|
params := map[string]string{
|
||||||
|
"schema": currentSchema,
|
||||||
|
"entity": currentEntity,
|
||||||
|
}
|
||||||
|
|
||||||
|
handler.Handle(respAdapter, reqAdapter, params)
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
r.Handle("POST", entityPath, wrapBunRouterHandler(postEntityHandler, authMiddleware))
|
||||||
|
|
||||||
handler.Handle(respAdapter, reqAdapter, params)
|
// POST route with ID
|
||||||
return nil
|
postEntityWithIDHandler := func(w http.ResponseWriter, req bunrouter.Request) error {
|
||||||
}
|
respAdapter := router.NewHTTPResponseWriter(w)
|
||||||
r.Handle("POST", entityPath, wrapBunRouterHandler(postEntityHandler, authMiddleware))
|
reqAdapter := router.NewHTTPRequest(req.Request)
|
||||||
|
common.SetCORSHeaders(respAdapter, reqAdapter, corsConfig)
|
||||||
|
params := map[string]string{
|
||||||
|
"schema": currentSchema,
|
||||||
|
"entity": currentEntity,
|
||||||
|
"id": req.Param("id"),
|
||||||
|
}
|
||||||
|
|
||||||
// POST route with ID
|
handler.Handle(respAdapter, reqAdapter, params)
|
||||||
postEntityWithIDHandler := func(w http.ResponseWriter, req bunrouter.Request) error {
|
return nil
|
||||||
respAdapter := router.NewHTTPResponseWriter(w)
|
|
||||||
reqAdapter := router.NewHTTPRequest(req.Request)
|
|
||||||
common.SetCORSHeaders(respAdapter, reqAdapter, corsConfig)
|
|
||||||
params := map[string]string{
|
|
||||||
"schema": currentSchema,
|
|
||||||
"entity": currentEntity,
|
|
||||||
"id": req.Param("id"),
|
|
||||||
}
|
}
|
||||||
|
r.Handle("POST", entityWithIDPath, wrapBunRouterHandler(postEntityWithIDHandler, authMiddleware))
|
||||||
|
|
||||||
handler.Handle(respAdapter, reqAdapter, params)
|
// GET route without ID
|
||||||
return nil
|
getEntityHandler := func(w http.ResponseWriter, req bunrouter.Request) error {
|
||||||
}
|
respAdapter := router.NewHTTPResponseWriter(w)
|
||||||
r.Handle("POST", entityWithIDPath, wrapBunRouterHandler(postEntityWithIDHandler, authMiddleware))
|
reqAdapter := router.NewHTTPRequest(req.Request)
|
||||||
|
common.SetCORSHeaders(respAdapter, reqAdapter, corsConfig)
|
||||||
|
params := map[string]string{
|
||||||
|
"schema": currentSchema,
|
||||||
|
"entity": currentEntity,
|
||||||
|
}
|
||||||
|
|
||||||
// GET route without ID
|
handler.HandleGet(respAdapter, reqAdapter, params)
|
||||||
getEntityHandler := func(w http.ResponseWriter, req bunrouter.Request) error {
|
return nil
|
||||||
respAdapter := router.NewHTTPResponseWriter(w)
|
|
||||||
reqAdapter := router.NewHTTPRequest(req.Request)
|
|
||||||
common.SetCORSHeaders(respAdapter, reqAdapter, corsConfig)
|
|
||||||
params := map[string]string{
|
|
||||||
"schema": currentSchema,
|
|
||||||
"entity": currentEntity,
|
|
||||||
}
|
}
|
||||||
|
r.Handle("GET", entityPath, wrapBunRouterHandler(getEntityHandler, authMiddleware))
|
||||||
|
|
||||||
handler.HandleGet(respAdapter, reqAdapter, params)
|
// GET route with ID
|
||||||
return nil
|
getEntityWithIDHandler := func(w http.ResponseWriter, req bunrouter.Request) error {
|
||||||
}
|
respAdapter := router.NewHTTPResponseWriter(w)
|
||||||
r.Handle("GET", entityPath, wrapBunRouterHandler(getEntityHandler, authMiddleware))
|
reqAdapter := router.NewHTTPRequest(req.Request)
|
||||||
|
common.SetCORSHeaders(respAdapter, reqAdapter, corsConfig)
|
||||||
|
params := map[string]string{
|
||||||
|
"schema": currentSchema,
|
||||||
|
"entity": currentEntity,
|
||||||
|
"id": req.Param("id"),
|
||||||
|
}
|
||||||
|
|
||||||
// GET route with ID
|
handler.HandleGet(respAdapter, reqAdapter, params)
|
||||||
getEntityWithIDHandler := func(w http.ResponseWriter, req bunrouter.Request) error {
|
return nil
|
||||||
respAdapter := router.NewHTTPResponseWriter(w)
|
|
||||||
reqAdapter := router.NewHTTPRequest(req.Request)
|
|
||||||
common.SetCORSHeaders(respAdapter, reqAdapter, corsConfig)
|
|
||||||
params := map[string]string{
|
|
||||||
"schema": currentSchema,
|
|
||||||
"entity": currentEntity,
|
|
||||||
"id": req.Param("id"),
|
|
||||||
}
|
}
|
||||||
|
r.Handle("GET", entityWithIDPath, wrapBunRouterHandler(getEntityWithIDHandler, authMiddleware))
|
||||||
|
|
||||||
handler.HandleGet(respAdapter, reqAdapter, params)
|
// OPTIONS route without ID (returns metadata)
|
||||||
return nil
|
// Don't apply auth middleware to OPTIONS - CORS preflight must not require auth
|
||||||
}
|
r.Handle("OPTIONS", entityPath, func(w http.ResponseWriter, req bunrouter.Request) error {
|
||||||
r.Handle("GET", entityWithIDPath, wrapBunRouterHandler(getEntityWithIDHandler, authMiddleware))
|
respAdapter := router.NewHTTPResponseWriter(w)
|
||||||
|
reqAdapter := router.NewHTTPRequest(req.Request)
|
||||||
|
optionsCorsConfig := corsConfig
|
||||||
|
optionsCorsConfig.AllowedMethods = []string{"GET", "POST", "OPTIONS"}
|
||||||
|
common.SetCORSHeaders(respAdapter, reqAdapter, optionsCorsConfig)
|
||||||
|
params := map[string]string{
|
||||||
|
"schema": currentSchema,
|
||||||
|
"entity": currentEntity,
|
||||||
|
}
|
||||||
|
|
||||||
// OPTIONS route without ID (returns metadata)
|
handler.HandleGet(respAdapter, reqAdapter, params)
|
||||||
// Don't apply auth middleware to OPTIONS - CORS preflight must not require auth
|
return nil
|
||||||
r.Handle("OPTIONS", entityPath, func(w http.ResponseWriter, req bunrouter.Request) error {
|
})
|
||||||
respAdapter := router.NewHTTPResponseWriter(w)
|
|
||||||
reqAdapter := router.NewHTTPRequest(req.Request)
|
|
||||||
optionsCorsConfig := corsConfig
|
|
||||||
optionsCorsConfig.AllowedMethods = []string{"GET", "POST", "OPTIONS"}
|
|
||||||
common.SetCORSHeaders(respAdapter, reqAdapter, optionsCorsConfig)
|
|
||||||
params := map[string]string{
|
|
||||||
"schema": currentSchema,
|
|
||||||
"entity": currentEntity,
|
|
||||||
}
|
|
||||||
|
|
||||||
handler.HandleGet(respAdapter, reqAdapter, params)
|
// OPTIONS route with ID (returns metadata)
|
||||||
return nil
|
// Don't apply auth middleware to OPTIONS - CORS preflight must not require auth
|
||||||
})
|
r.Handle("OPTIONS", entityWithIDPath, func(w http.ResponseWriter, req bunrouter.Request) error {
|
||||||
|
respAdapter := router.NewHTTPResponseWriter(w)
|
||||||
|
reqAdapter := router.NewHTTPRequest(req.Request)
|
||||||
|
optionsCorsConfig := corsConfig
|
||||||
|
optionsCorsConfig.AllowedMethods = []string{"POST", "OPTIONS"}
|
||||||
|
common.SetCORSHeaders(respAdapter, reqAdapter, optionsCorsConfig)
|
||||||
|
params := map[string]string{
|
||||||
|
"schema": currentSchema,
|
||||||
|
"entity": currentEntity,
|
||||||
|
}
|
||||||
|
|
||||||
// OPTIONS route with ID (returns metadata)
|
handler.HandleGet(respAdapter, reqAdapter, params)
|
||||||
// Don't apply auth middleware to OPTIONS - CORS preflight must not require auth
|
return nil
|
||||||
r.Handle("OPTIONS", entityWithIDPath, func(w http.ResponseWriter, req bunrouter.Request) error {
|
})
|
||||||
respAdapter := router.NewHTTPResponseWriter(w)
|
|
||||||
reqAdapter := router.NewHTTPRequest(req.Request)
|
|
||||||
optionsCorsConfig := corsConfig
|
|
||||||
optionsCorsConfig.AllowedMethods = []string{"POST", "OPTIONS"}
|
|
||||||
common.SetCORSHeaders(respAdapter, reqAdapter, optionsCorsConfig)
|
|
||||||
params := map[string]string{
|
|
||||||
"schema": currentSchema,
|
|
||||||
"entity": currentEntity,
|
|
||||||
}
|
|
||||||
|
|
||||||
handler.HandleGet(respAdapter, reqAdapter, params)
|
logger.Info("Registered resolvespec bunrouter routes for model %s at %s", fullName, entityPath)
|
||||||
return nil
|
}()
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -88,7 +88,7 @@ This will match any records where the column contains the search term (case-inse
|
|||||||
Search with specific operators (AND logic).
|
Search with specific operators (AND logic).
|
||||||
|
|
||||||
**Supported Operators:**
|
**Supported Operators:**
|
||||||
- `contains` - Contains substring (case-insensitive)
|
- `contains` - Contains substring (case-insensitive). Implemented as `CAST(col AS TEXT) ILIKE '%value%'` for every column type, including arrays (stringifies the array, then substring-matches). **Not** array containment — no GIN index use, and can false-positive on partial matches within array elements. resolvespec (a different spec package in this repo) defines `contains` differently: real PostgreSQL array-overlap (`&&`). Don't assume the two behave the same.
|
||||||
- `beginswith` / `startswith` - Starts with (case-insensitive)
|
- `beginswith` / `startswith` - Starts with (case-insensitive)
|
||||||
- `endswith` - Ends with (case-insensitive)
|
- `endswith` - Ends with (case-insensitive)
|
||||||
- `equals` / `eq` - Exact match
|
- `equals` / `eq` - Exact match
|
||||||
|
|||||||
@@ -96,6 +96,8 @@ X-Limit: 50
|
|||||||
|
|
||||||
**Available Operators**: `eq`, `neq`, `gt`, `gte`, `lt`, `lte`, `contains`, `startswith`, `endswith`, `between`, `betweeninclusive`, `in`, `empty`, `notempty`
|
**Available Operators**: `eq`, `neq`, `gt`, `gte`, `lt`, `lte`, `contains`, `startswith`, `endswith`, `between`, `betweeninclusive`, `in`, `empty`, `notempty`
|
||||||
|
|
||||||
|
> Note: `contains` here is a text-cast ILIKE substring match (works on any column type, including arrays, by stringifying first) — not array containment. resolvespec's `contains` operator has different semantics (real array overlap). See [HEADERS.md](HEADERS.md) for details.
|
||||||
|
|
||||||
For complete header documentation, see [HEADERS.md](HEADERS.md).
|
For complete header documentation, see [HEADERS.md](HEADERS.md).
|
||||||
|
|
||||||
## Lifecycle Hooks
|
## Lifecycle Hooks
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/bitechdev/ResolveSpec/pkg/common"
|
"github.com/bitechdev/ResolveSpec/pkg/common"
|
||||||
|
"github.com/bitechdev/ResolveSpec/pkg/spectypes"
|
||||||
)
|
)
|
||||||
|
|
||||||
// detailTestModel is a simple model with gorm column/type tags for detail format tests.
|
// detailTestModel is a simple model with gorm column/type tags for detail format tests.
|
||||||
@@ -207,3 +208,30 @@ func TestBuildDetailFields_SkipsRelations(t *testing.T) {
|
|||||||
t.Errorf("expected 2 scalar fields (id, name), got %d", len(fields))
|
t.Errorf("expected 2 scalar fields (id, name), got %d", len(fields))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestBuildDetailFields_UnwrapsSQLTypes(t *testing.T) {
|
||||||
|
type model struct {
|
||||||
|
Name spectypes.SqlString `gorm:"column:name" json:"name"`
|
||||||
|
CreatedAt spectypes.SqlTimeStamp `gorm:"column:created_at" json:"created_at"`
|
||||||
|
Metadata spectypes.SqlJSONB `gorm:"column:metadata;type:jsonb" json:"metadata"`
|
||||||
|
}
|
||||||
|
|
||||||
|
fields := (&Handler{}).buildDetailFields(model{})
|
||||||
|
byName := make(map[string]string, len(fields))
|
||||||
|
for _, field := range fields {
|
||||||
|
byName[field.Name] = field.DataType
|
||||||
|
if !field.Nullable {
|
||||||
|
t.Errorf("%q: expected SQL wrapper to be nullable", field.Name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for name, want := range map[string]string{
|
||||||
|
"name": "string",
|
||||||
|
"created_at": "unknown",
|
||||||
|
"metadata": "unknown",
|
||||||
|
} {
|
||||||
|
if got := byName[name]; got != want {
|
||||||
|
t.Errorf("%q: expected type %q, got %q", name, want, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
+46
-12
@@ -2551,10 +2551,18 @@ func (h *Handler) generateMetadata(schema, entity string, model interface{}) *co
|
|||||||
jsonName = field.Name
|
jsonName = field.Name
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if this is a relation field (slice or struct, but not time.Time)
|
columnType := field.Type
|
||||||
if field.Type.Kind() == reflect.Slice ||
|
isSQLType := false
|
||||||
(field.Type.Kind() == reflect.Struct && field.Type.Name() != "Time") ||
|
if unwrappedType, ok := unwrapSQLType(field.Type); ok {
|
||||||
(field.Type.Kind() == reflect.Pointer && field.Type.Elem().Kind() == reflect.Struct && field.Type.Elem().Name() != "Time") {
|
columnType = unwrappedType
|
||||||
|
isSQLType = true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if this is a relation field (slice or struct, but not time.Time).
|
||||||
|
// spectypes SQL values are columns even when their Go representation is a
|
||||||
|
// struct or a slice.
|
||||||
|
if !isSQLType && (columnType.Kind() == reflect.Slice ||
|
||||||
|
(columnType.Kind() == reflect.Struct && columnType.Name() != "Time")) {
|
||||||
metadata.Relations = append(metadata.Relations, jsonName)
|
metadata.Relations = append(metadata.Relations, jsonName)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -2575,8 +2583,8 @@ func (h *Handler) generateMetadata(schema, entity string, model interface{}) *co
|
|||||||
|
|
||||||
column := common.Column{
|
column := common.Column{
|
||||||
Name: columnName,
|
Name: columnName,
|
||||||
Type: h.getColumnType(field.Type),
|
Type: h.getColumnType(columnType),
|
||||||
IsNullable: h.isNullable(field),
|
IsNullable: isSQLType || h.isNullable(field),
|
||||||
IsPrimary: strings.Contains(gormTag, "primaryKey") || strings.Contains(gormTag, "primary_key"),
|
IsPrimary: strings.Contains(gormTag, "primaryKey") || strings.Contains(gormTag, "primary_key"),
|
||||||
IsUnique: strings.Contains(gormTag, "unique"),
|
IsUnique: strings.Contains(gormTag, "unique"),
|
||||||
HasIndex: strings.Contains(gormTag, "index"),
|
HasIndex: strings.Contains(gormTag, "index"),
|
||||||
@@ -2607,6 +2615,27 @@ func (h *Handler) getColumnType(t reflect.Type) string {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// unwrapSQLType returns the value type wrapped by a spectypes SQL value. These
|
||||||
|
// types represent columns, even when their Go representation is a struct or a
|
||||||
|
// slice (for example, SqlNull[string] and SqlJSONB).
|
||||||
|
func unwrapSQLType(t reflect.Type) (reflect.Type, bool) {
|
||||||
|
for t.Kind() == reflect.Pointer {
|
||||||
|
t = t.Elem()
|
||||||
|
}
|
||||||
|
|
||||||
|
if t.PkgPath() != "github.com/bitechdev/ResolveSpec/pkg/spectypes" {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
|
||||||
|
if t.Kind() == reflect.Struct {
|
||||||
|
if value, ok := t.FieldByName("Val"); ok {
|
||||||
|
return value.Type, true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return t, true
|
||||||
|
}
|
||||||
|
|
||||||
func (h *Handler) isNullable(field reflect.StructField) bool {
|
func (h *Handler) isNullable(field reflect.StructField) bool {
|
||||||
return field.Type.Kind() == reflect.Pointer
|
return field.Type.Kind() == reflect.Pointer
|
||||||
}
|
}
|
||||||
@@ -2705,13 +2734,18 @@ func (h *Handler) buildDetailFields(model interface{}) []reflection.ModelFieldDe
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
// Skip relation fields (slices, structs that aren't time.Time, ptrs to struct)
|
// Skip relation fields (slices and structs that aren't time.Time). spectypes
|
||||||
|
// SQL values are columns, not relations.
|
||||||
ft := field.Type
|
ft := field.Type
|
||||||
if ft.Kind() == reflect.Pointer {
|
isSQLType := false
|
||||||
|
if unwrappedType, ok := unwrapSQLType(ft); ok {
|
||||||
|
ft = unwrappedType
|
||||||
|
isSQLType = true
|
||||||
|
} else if ft.Kind() == reflect.Pointer {
|
||||||
ft = ft.Elem()
|
ft = ft.Elem()
|
||||||
}
|
}
|
||||||
if ft.Kind() == reflect.Slice ||
|
if !isSQLType && (ft.Kind() == reflect.Slice ||
|
||||||
(ft.Kind() == reflect.Struct && ft.Name() != "Time") {
|
(ft.Kind() == reflect.Struct && ft.Name() != "Time")) {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2739,7 +2773,7 @@ func (h *Handler) buildDetailFields(model interface{}) []reflection.ModelFieldDe
|
|||||||
sqlKey = "unique"
|
sqlKey = "unique"
|
||||||
}
|
}
|
||||||
|
|
||||||
nullable := field.Type.Kind() == reflect.Pointer
|
nullable := isSQLType || field.Type.Kind() == reflect.Pointer
|
||||||
if strings.Contains(gormLower, "not null") {
|
if strings.Contains(gormLower, "not null") {
|
||||||
nullable = false
|
nullable = false
|
||||||
} else if strings.Contains(gormLower, "nullable") || strings.Contains(gormLower, ",null") {
|
} else if strings.Contains(gormLower, "nullable") || strings.Contains(gormLower, ",null") {
|
||||||
@@ -2748,7 +2782,7 @@ func (h *Handler) buildDetailFields(model interface{}) []reflection.ModelFieldDe
|
|||||||
|
|
||||||
fields = append(fields, reflection.ModelFieldDetail{
|
fields = append(fields, reflection.ModelFieldDetail{
|
||||||
Name: jsonName,
|
Name: jsonName,
|
||||||
DataType: h.getColumnType(field.Type),
|
DataType: h.getColumnType(ft),
|
||||||
SQLName: sqlName,
|
SQLName: sqlName,
|
||||||
SQLDataType: sqlDataType,
|
SQLDataType: sqlDataType,
|
||||||
SQLKey: sqlKey,
|
SQLKey: sqlKey,
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ package restheadspec
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/bitechdev/ResolveSpec/pkg/common"
|
"github.com/bitechdev/ResolveSpec/pkg/common"
|
||||||
"github.com/bitechdev/ResolveSpec/pkg/logger"
|
"github.com/bitechdev/ResolveSpec/pkg/logger"
|
||||||
@@ -89,6 +91,7 @@ type HookFunc func(*HookContext) error
|
|||||||
// HookRegistry manages all registered hooks
|
// HookRegistry manages all registered hooks
|
||||||
type HookRegistry struct {
|
type HookRegistry struct {
|
||||||
hooks map[HookType][]HookFunc
|
hooks map[HookType][]HookFunc
|
||||||
|
mutex sync.RWMutex
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewHookRegistry creates a new hook registry
|
// NewHookRegistry creates a new hook registry
|
||||||
@@ -98,8 +101,46 @@ func NewHookRegistry() *HookRegistry {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// hookLockRetryAttempts/hookLockRetryDelay bound how long the try-lock
|
||||||
|
// helpers below will spin before giving up, so a contended mutex can
|
||||||
|
// never hang a caller.
|
||||||
|
const (
|
||||||
|
hookLockRetryAttempts = 20
|
||||||
|
hookLockRetryDelay = 1 * time.Millisecond
|
||||||
|
)
|
||||||
|
|
||||||
|
// tryLock attempts to acquire the write lock, retrying briefly. Returns
|
||||||
|
// false if it could not be acquired within the bound.
|
||||||
|
func (r *HookRegistry) tryLock() bool {
|
||||||
|
for i := 0; i < hookLockRetryAttempts; i++ {
|
||||||
|
if r.mutex.TryLock() {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
time.Sleep(hookLockRetryDelay)
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// tryRLock attempts to acquire the read lock, retrying briefly. Returns
|
||||||
|
// false if it could not be acquired within the bound.
|
||||||
|
func (r *HookRegistry) tryRLock() bool {
|
||||||
|
for i := 0; i < hookLockRetryAttempts; i++ {
|
||||||
|
if r.mutex.TryRLock() {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
time.Sleep(hookLockRetryDelay)
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
// Register adds a new hook for the specified hook type
|
// Register adds a new hook for the specified hook type
|
||||||
func (r *HookRegistry) Register(hookType HookType, hook HookFunc) {
|
func (r *HookRegistry) Register(hookType HookType, hook HookFunc) {
|
||||||
|
if !r.tryLock() {
|
||||||
|
logger.Error("Failed to register hook for %s: registry locked", hookType)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer r.mutex.Unlock()
|
||||||
|
|
||||||
if r.hooks == nil {
|
if r.hooks == nil {
|
||||||
r.hooks = make(map[HookType][]HookFunc)
|
r.hooks = make(map[HookType][]HookFunc)
|
||||||
}
|
}
|
||||||
@@ -117,8 +158,13 @@ func (r *HookRegistry) RegisterMultiple(hookTypes []HookType, hook HookFunc) {
|
|||||||
// Execute runs all hooks for the specified type in order
|
// Execute runs all hooks for the specified type in order
|
||||||
// If any hook returns an error, execution stops and the error is returned
|
// If any hook returns an error, execution stops and the error is returned
|
||||||
func (r *HookRegistry) Execute(hookType HookType, ctx *HookContext) error {
|
func (r *HookRegistry) Execute(hookType HookType, ctx *HookContext) error {
|
||||||
hooks, exists := r.hooks[hookType]
|
if !r.tryRLock() {
|
||||||
if !exists || len(hooks) == 0 {
|
return fmt.Errorf("hook execution failed: registry locked")
|
||||||
|
}
|
||||||
|
hooks := append([]HookFunc(nil), r.hooks[hookType]...)
|
||||||
|
r.mutex.RUnlock()
|
||||||
|
|
||||||
|
if len(hooks) == 0 {
|
||||||
// logger.Debug("No hooks registered for %s", hookType)
|
// logger.Debug("No hooks registered for %s", hookType)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -154,18 +200,35 @@ func (r *HookRegistry) ExecuteBeforeOp(hookType HookType, ctx *HookContext) erro
|
|||||||
|
|
||||||
// Clear removes all hooks for the specified type
|
// Clear removes all hooks for the specified type
|
||||||
func (r *HookRegistry) Clear(hookType HookType) {
|
func (r *HookRegistry) Clear(hookType HookType) {
|
||||||
|
if !r.tryLock() {
|
||||||
|
logger.Error("Failed to clear hooks for %s: registry locked", hookType)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer r.mutex.Unlock()
|
||||||
|
|
||||||
delete(r.hooks, hookType)
|
delete(r.hooks, hookType)
|
||||||
logger.Info("Cleared all hooks for %s", hookType)
|
logger.Info("Cleared all hooks for %s", hookType)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ClearAll removes all registered hooks
|
// ClearAll removes all registered hooks
|
||||||
func (r *HookRegistry) ClearAll() {
|
func (r *HookRegistry) ClearAll() {
|
||||||
|
if !r.tryLock() {
|
||||||
|
logger.Error("Failed to clear all hooks: registry locked")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer r.mutex.Unlock()
|
||||||
|
|
||||||
r.hooks = make(map[HookType][]HookFunc)
|
r.hooks = make(map[HookType][]HookFunc)
|
||||||
logger.Info("Cleared all hooks")
|
logger.Info("Cleared all hooks")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Count returns the number of hooks registered for a specific type
|
// Count returns the number of hooks registered for a specific type
|
||||||
func (r *HookRegistry) Count(hookType HookType) int {
|
func (r *HookRegistry) Count(hookType HookType) int {
|
||||||
|
if !r.tryRLock() {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
defer r.mutex.RUnlock()
|
||||||
|
|
||||||
if hooks, exists := r.hooks[hookType]; exists {
|
if hooks, exists := r.hooks[hookType]; exists {
|
||||||
return len(hooks)
|
return len(hooks)
|
||||||
}
|
}
|
||||||
@@ -179,6 +242,11 @@ func (r *HookRegistry) HasHooks(hookType HookType) bool {
|
|||||||
|
|
||||||
// GetAllHookTypes returns all hook types that have registered hooks
|
// GetAllHookTypes returns all hook types that have registered hooks
|
||||||
func (r *HookRegistry) GetAllHookTypes() []HookType {
|
func (r *HookRegistry) GetAllHookTypes() []HookType {
|
||||||
|
if !r.tryRLock() {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
defer r.mutex.RUnlock()
|
||||||
|
|
||||||
types := make([]HookType, 0, len(r.hooks))
|
types := make([]HookType, 0, len(r.hooks))
|
||||||
for hookType := range r.hooks {
|
for hookType := range r.hooks {
|
||||||
types = append(types, hookType)
|
types = append(types, hookType)
|
||||||
|
|||||||
+151
-135
@@ -55,6 +55,7 @@ package restheadspec
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"runtime/debug"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/gorilla/mux"
|
"github.com/gorilla/mux"
|
||||||
@@ -308,6 +309,11 @@ func wrapBunRouterHandler(handler bunrouter.HandlerFunc, authMiddleware Middlewa
|
|||||||
// Accepts bunrouter.Router or bunrouter.Group
|
// Accepts bunrouter.Router or bunrouter.Group
|
||||||
// authMiddleware is optional - if provided, routes will be protected with the middleware
|
// authMiddleware is optional - if provided, routes will be protected with the middleware
|
||||||
func SetupBunRouterRoutes(r BunRouterHandler, handler *Handler, authMiddleware MiddlewareFunc) {
|
func SetupBunRouterRoutes(r BunRouterHandler, handler *Handler, authMiddleware MiddlewareFunc) {
|
||||||
|
defer func() {
|
||||||
|
if rec := recover(); rec != nil {
|
||||||
|
logger.Error("panic in restheadspec.SetupBunRouterRoutes: %v\n%s", rec, debug.Stack())
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
// CORS config
|
// CORS config
|
||||||
corsConfig := common.DefaultCORSConfig()
|
corsConfig := common.DefaultCORSConfig()
|
||||||
@@ -333,171 +339,181 @@ func SetupBunRouterRoutes(r BunRouterHandler, handler *Handler, authMiddleware M
|
|||||||
|
|
||||||
// Loop through each registered model and create explicit routes
|
// Loop through each registered model and create explicit routes
|
||||||
for fullName := range allModels {
|
for fullName := range allModels {
|
||||||
// Parse the full name (e.g., "public.users" or just "users")
|
func() {
|
||||||
schema, entity := parseModelName(fullName)
|
defer func() {
|
||||||
|
if rec := recover(); rec != nil {
|
||||||
|
logger.Error("panic registering restheadspec routes for model %s: %v\n%s", fullName, rec, debug.Stack())
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
// Build the route paths
|
// Parse the full name (e.g., "public.users" or just "users")
|
||||||
entityPath := buildRoutePath(schema, entity)
|
schema, entity := parseModelName(fullName)
|
||||||
entityWithIDPath := entityPath + "/:id"
|
|
||||||
metadataPath := entityPath + "/metadata"
|
|
||||||
|
|
||||||
// Create closure variables to capture current schema and entity
|
// Build the route paths
|
||||||
currentSchema := schema
|
entityPath := buildRoutePath(schema, entity)
|
||||||
currentEntity := entity
|
entityWithIDPath := entityPath + "/:id"
|
||||||
|
metadataPath := entityPath + "/metadata"
|
||||||
|
|
||||||
// GET and POST for /{schema}/{entity}
|
// Create closure variables to capture current schema and entity
|
||||||
getEntityHandler := func(w http.ResponseWriter, req bunrouter.Request) error {
|
currentSchema := schema
|
||||||
respAdapter := router.NewHTTPResponseWriter(w)
|
currentEntity := entity
|
||||||
reqAdapter := router.NewBunRouterRequest(req)
|
|
||||||
common.SetCORSHeaders(respAdapter, reqAdapter, corsConfig)
|
// GET and POST for /{schema}/{entity}
|
||||||
params := map[string]string{
|
getEntityHandler := func(w http.ResponseWriter, req bunrouter.Request) error {
|
||||||
"schema": currentSchema,
|
respAdapter := router.NewHTTPResponseWriter(w)
|
||||||
"entity": currentEntity,
|
reqAdapter := router.NewBunRouterRequest(req)
|
||||||
|
common.SetCORSHeaders(respAdapter, reqAdapter, corsConfig)
|
||||||
|
params := map[string]string{
|
||||||
|
"schema": currentSchema,
|
||||||
|
"entity": currentEntity,
|
||||||
|
}
|
||||||
|
|
||||||
|
handler.Handle(respAdapter, reqAdapter, params)
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
r.Handle("GET", entityPath, wrapBunRouterHandler(getEntityHandler, authMiddleware))
|
||||||
|
|
||||||
handler.Handle(respAdapter, reqAdapter, params)
|
postEntityHandler := func(w http.ResponseWriter, req bunrouter.Request) error {
|
||||||
return nil
|
respAdapter := router.NewHTTPResponseWriter(w)
|
||||||
}
|
reqAdapter := router.NewBunRouterRequest(req)
|
||||||
r.Handle("GET", entityPath, wrapBunRouterHandler(getEntityHandler, authMiddleware))
|
common.SetCORSHeaders(respAdapter, reqAdapter, corsConfig)
|
||||||
|
params := map[string]string{
|
||||||
|
"schema": currentSchema,
|
||||||
|
"entity": currentEntity,
|
||||||
|
}
|
||||||
|
|
||||||
postEntityHandler := func(w http.ResponseWriter, req bunrouter.Request) error {
|
handler.Handle(respAdapter, reqAdapter, params)
|
||||||
respAdapter := router.NewHTTPResponseWriter(w)
|
return nil
|
||||||
reqAdapter := router.NewBunRouterRequest(req)
|
|
||||||
common.SetCORSHeaders(respAdapter, reqAdapter, corsConfig)
|
|
||||||
params := map[string]string{
|
|
||||||
"schema": currentSchema,
|
|
||||||
"entity": currentEntity,
|
|
||||||
}
|
}
|
||||||
|
r.Handle("POST", entityPath, wrapBunRouterHandler(postEntityHandler, authMiddleware))
|
||||||
|
|
||||||
handler.Handle(respAdapter, reqAdapter, params)
|
// GET, POST, PUT, PATCH, DELETE for /{schema}/{entity}/:id
|
||||||
return nil
|
getEntityWithIDHandler := func(w http.ResponseWriter, req bunrouter.Request) error {
|
||||||
}
|
respAdapter := router.NewHTTPResponseWriter(w)
|
||||||
r.Handle("POST", entityPath, wrapBunRouterHandler(postEntityHandler, authMiddleware))
|
reqAdapter := router.NewBunRouterRequest(req)
|
||||||
|
common.SetCORSHeaders(respAdapter, reqAdapter, corsConfig)
|
||||||
|
params := map[string]string{
|
||||||
|
"schema": currentSchema,
|
||||||
|
"entity": currentEntity,
|
||||||
|
"id": req.Param("id"),
|
||||||
|
}
|
||||||
|
|
||||||
// GET, POST, PUT, PATCH, DELETE for /{schema}/{entity}/:id
|
handler.Handle(respAdapter, reqAdapter, params)
|
||||||
getEntityWithIDHandler := func(w http.ResponseWriter, req bunrouter.Request) error {
|
return nil
|
||||||
respAdapter := router.NewHTTPResponseWriter(w)
|
|
||||||
reqAdapter := router.NewBunRouterRequest(req)
|
|
||||||
common.SetCORSHeaders(respAdapter, reqAdapter, corsConfig)
|
|
||||||
params := map[string]string{
|
|
||||||
"schema": currentSchema,
|
|
||||||
"entity": currentEntity,
|
|
||||||
"id": req.Param("id"),
|
|
||||||
}
|
}
|
||||||
|
r.Handle("GET", entityWithIDPath, wrapBunRouterHandler(getEntityWithIDHandler, authMiddleware))
|
||||||
|
|
||||||
handler.Handle(respAdapter, reqAdapter, params)
|
postEntityWithIDHandler := func(w http.ResponseWriter, req bunrouter.Request) error {
|
||||||
return nil
|
respAdapter := router.NewHTTPResponseWriter(w)
|
||||||
}
|
reqAdapter := router.NewBunRouterRequest(req)
|
||||||
r.Handle("GET", entityWithIDPath, wrapBunRouterHandler(getEntityWithIDHandler, authMiddleware))
|
common.SetCORSHeaders(respAdapter, reqAdapter, corsConfig)
|
||||||
|
params := map[string]string{
|
||||||
|
"schema": currentSchema,
|
||||||
|
"entity": currentEntity,
|
||||||
|
"id": req.Param("id"),
|
||||||
|
}
|
||||||
|
|
||||||
postEntityWithIDHandler := func(w http.ResponseWriter, req bunrouter.Request) error {
|
handler.Handle(respAdapter, reqAdapter, params)
|
||||||
respAdapter := router.NewHTTPResponseWriter(w)
|
return nil
|
||||||
reqAdapter := router.NewBunRouterRequest(req)
|
|
||||||
common.SetCORSHeaders(respAdapter, reqAdapter, corsConfig)
|
|
||||||
params := map[string]string{
|
|
||||||
"schema": currentSchema,
|
|
||||||
"entity": currentEntity,
|
|
||||||
"id": req.Param("id"),
|
|
||||||
}
|
}
|
||||||
|
r.Handle("POST", entityWithIDPath, wrapBunRouterHandler(postEntityWithIDHandler, authMiddleware))
|
||||||
|
|
||||||
handler.Handle(respAdapter, reqAdapter, params)
|
putEntityWithIDHandler := func(w http.ResponseWriter, req bunrouter.Request) error {
|
||||||
return nil
|
respAdapter := router.NewHTTPResponseWriter(w)
|
||||||
}
|
reqAdapter := router.NewBunRouterRequest(req)
|
||||||
r.Handle("POST", entityWithIDPath, wrapBunRouterHandler(postEntityWithIDHandler, authMiddleware))
|
common.SetCORSHeaders(respAdapter, reqAdapter, corsConfig)
|
||||||
|
params := map[string]string{
|
||||||
|
"schema": currentSchema,
|
||||||
|
"entity": currentEntity,
|
||||||
|
"id": req.Param("id"),
|
||||||
|
}
|
||||||
|
|
||||||
putEntityWithIDHandler := func(w http.ResponseWriter, req bunrouter.Request) error {
|
handler.Handle(respAdapter, reqAdapter, params)
|
||||||
respAdapter := router.NewHTTPResponseWriter(w)
|
return nil
|
||||||
reqAdapter := router.NewBunRouterRequest(req)
|
|
||||||
common.SetCORSHeaders(respAdapter, reqAdapter, corsConfig)
|
|
||||||
params := map[string]string{
|
|
||||||
"schema": currentSchema,
|
|
||||||
"entity": currentEntity,
|
|
||||||
"id": req.Param("id"),
|
|
||||||
}
|
}
|
||||||
|
r.Handle("PUT", entityWithIDPath, wrapBunRouterHandler(putEntityWithIDHandler, authMiddleware))
|
||||||
|
|
||||||
handler.Handle(respAdapter, reqAdapter, params)
|
patchEntityWithIDHandler := func(w http.ResponseWriter, req bunrouter.Request) error {
|
||||||
return nil
|
respAdapter := router.NewHTTPResponseWriter(w)
|
||||||
}
|
reqAdapter := router.NewBunRouterRequest(req)
|
||||||
r.Handle("PUT", entityWithIDPath, wrapBunRouterHandler(putEntityWithIDHandler, authMiddleware))
|
common.SetCORSHeaders(respAdapter, reqAdapter, corsConfig)
|
||||||
|
params := map[string]string{
|
||||||
|
"schema": currentSchema,
|
||||||
|
"entity": currentEntity,
|
||||||
|
"id": req.Param("id"),
|
||||||
|
}
|
||||||
|
|
||||||
patchEntityWithIDHandler := func(w http.ResponseWriter, req bunrouter.Request) error {
|
handler.Handle(respAdapter, reqAdapter, params)
|
||||||
respAdapter := router.NewHTTPResponseWriter(w)
|
return nil
|
||||||
reqAdapter := router.NewBunRouterRequest(req)
|
|
||||||
common.SetCORSHeaders(respAdapter, reqAdapter, corsConfig)
|
|
||||||
params := map[string]string{
|
|
||||||
"schema": currentSchema,
|
|
||||||
"entity": currentEntity,
|
|
||||||
"id": req.Param("id"),
|
|
||||||
}
|
}
|
||||||
|
r.Handle("PATCH", entityWithIDPath, wrapBunRouterHandler(patchEntityWithIDHandler, authMiddleware))
|
||||||
|
|
||||||
handler.Handle(respAdapter, reqAdapter, params)
|
deleteEntityWithIDHandler := func(w http.ResponseWriter, req bunrouter.Request) error {
|
||||||
return nil
|
respAdapter := router.NewHTTPResponseWriter(w)
|
||||||
}
|
reqAdapter := router.NewBunRouterRequest(req)
|
||||||
r.Handle("PATCH", entityWithIDPath, wrapBunRouterHandler(patchEntityWithIDHandler, authMiddleware))
|
common.SetCORSHeaders(respAdapter, reqAdapter, corsConfig)
|
||||||
|
params := map[string]string{
|
||||||
|
"schema": currentSchema,
|
||||||
|
"entity": currentEntity,
|
||||||
|
"id": req.Param("id"),
|
||||||
|
}
|
||||||
|
|
||||||
deleteEntityWithIDHandler := func(w http.ResponseWriter, req bunrouter.Request) error {
|
handler.Handle(respAdapter, reqAdapter, params)
|
||||||
respAdapter := router.NewHTTPResponseWriter(w)
|
return nil
|
||||||
reqAdapter := router.NewBunRouterRequest(req)
|
|
||||||
common.SetCORSHeaders(respAdapter, reqAdapter, corsConfig)
|
|
||||||
params := map[string]string{
|
|
||||||
"schema": currentSchema,
|
|
||||||
"entity": currentEntity,
|
|
||||||
"id": req.Param("id"),
|
|
||||||
}
|
}
|
||||||
|
r.Handle("DELETE", entityWithIDPath, wrapBunRouterHandler(deleteEntityWithIDHandler, authMiddleware))
|
||||||
|
|
||||||
handler.Handle(respAdapter, reqAdapter, params)
|
// Metadata endpoint
|
||||||
return nil
|
metadataHandler := func(w http.ResponseWriter, req bunrouter.Request) error {
|
||||||
}
|
respAdapter := router.NewHTTPResponseWriter(w)
|
||||||
r.Handle("DELETE", entityWithIDPath, wrapBunRouterHandler(deleteEntityWithIDHandler, authMiddleware))
|
reqAdapter := router.NewBunRouterRequest(req)
|
||||||
|
common.SetCORSHeaders(respAdapter, reqAdapter, corsConfig)
|
||||||
|
params := map[string]string{
|
||||||
|
"schema": currentSchema,
|
||||||
|
"entity": currentEntity,
|
||||||
|
}
|
||||||
|
|
||||||
// Metadata endpoint
|
handler.HandleGet(respAdapter, reqAdapter, params)
|
||||||
metadataHandler := func(w http.ResponseWriter, req bunrouter.Request) error {
|
return nil
|
||||||
respAdapter := router.NewHTTPResponseWriter(w)
|
|
||||||
reqAdapter := router.NewBunRouterRequest(req)
|
|
||||||
common.SetCORSHeaders(respAdapter, reqAdapter, corsConfig)
|
|
||||||
params := map[string]string{
|
|
||||||
"schema": currentSchema,
|
|
||||||
"entity": currentEntity,
|
|
||||||
}
|
}
|
||||||
|
r.Handle("GET", metadataPath, wrapBunRouterHandler(metadataHandler, authMiddleware))
|
||||||
|
|
||||||
handler.HandleGet(respAdapter, reqAdapter, params)
|
// OPTIONS route without ID (returns metadata)
|
||||||
return nil
|
// Don't apply auth middleware to OPTIONS - CORS preflight must not require auth
|
||||||
}
|
r.Handle("OPTIONS", entityPath, func(w http.ResponseWriter, req bunrouter.Request) error {
|
||||||
r.Handle("GET", metadataPath, wrapBunRouterHandler(metadataHandler, authMiddleware))
|
respAdapter := router.NewHTTPResponseWriter(w)
|
||||||
|
reqAdapter := router.NewBunRouterRequest(req)
|
||||||
|
optionsCorsConfig := corsConfig
|
||||||
|
optionsCorsConfig.AllowedMethods = []string{"GET", "POST", "OPTIONS"}
|
||||||
|
common.SetCORSHeaders(respAdapter, reqAdapter, optionsCorsConfig)
|
||||||
|
params := map[string]string{
|
||||||
|
"schema": currentSchema,
|
||||||
|
"entity": currentEntity,
|
||||||
|
}
|
||||||
|
|
||||||
// OPTIONS route without ID (returns metadata)
|
handler.HandleGet(respAdapter, reqAdapter, params)
|
||||||
// Don't apply auth middleware to OPTIONS - CORS preflight must not require auth
|
return nil
|
||||||
r.Handle("OPTIONS", entityPath, func(w http.ResponseWriter, req bunrouter.Request) error {
|
})
|
||||||
respAdapter := router.NewHTTPResponseWriter(w)
|
|
||||||
reqAdapter := router.NewBunRouterRequest(req)
|
|
||||||
optionsCorsConfig := corsConfig
|
|
||||||
optionsCorsConfig.AllowedMethods = []string{"GET", "POST", "OPTIONS"}
|
|
||||||
common.SetCORSHeaders(respAdapter, reqAdapter, optionsCorsConfig)
|
|
||||||
params := map[string]string{
|
|
||||||
"schema": currentSchema,
|
|
||||||
"entity": currentEntity,
|
|
||||||
}
|
|
||||||
|
|
||||||
handler.HandleGet(respAdapter, reqAdapter, params)
|
// OPTIONS route with ID (returns metadata)
|
||||||
return nil
|
// Don't apply auth middleware to OPTIONS - CORS preflight must not require auth
|
||||||
})
|
r.Handle("OPTIONS", entityWithIDPath, func(w http.ResponseWriter, req bunrouter.Request) error {
|
||||||
|
respAdapter := router.NewHTTPResponseWriter(w)
|
||||||
|
reqAdapter := router.NewBunRouterRequest(req)
|
||||||
|
optionsCorsConfig := corsConfig
|
||||||
|
optionsCorsConfig.AllowedMethods = []string{"GET", "PUT", "PATCH", "DELETE", "POST", "OPTIONS"}
|
||||||
|
common.SetCORSHeaders(respAdapter, reqAdapter, optionsCorsConfig)
|
||||||
|
params := map[string]string{
|
||||||
|
"schema": currentSchema,
|
||||||
|
"entity": currentEntity,
|
||||||
|
}
|
||||||
|
|
||||||
// OPTIONS route with ID (returns metadata)
|
handler.HandleGet(respAdapter, reqAdapter, params)
|
||||||
// Don't apply auth middleware to OPTIONS - CORS preflight must not require auth
|
return nil
|
||||||
r.Handle("OPTIONS", entityWithIDPath, func(w http.ResponseWriter, req bunrouter.Request) error {
|
})
|
||||||
respAdapter := router.NewHTTPResponseWriter(w)
|
|
||||||
reqAdapter := router.NewBunRouterRequest(req)
|
|
||||||
optionsCorsConfig := corsConfig
|
|
||||||
optionsCorsConfig.AllowedMethods = []string{"GET", "PUT", "PATCH", "DELETE", "POST", "OPTIONS"}
|
|
||||||
common.SetCORSHeaders(respAdapter, reqAdapter, optionsCorsConfig)
|
|
||||||
params := map[string]string{
|
|
||||||
"schema": currentSchema,
|
|
||||||
"entity": currentEntity,
|
|
||||||
}
|
|
||||||
|
|
||||||
handler.HandleGet(respAdapter, reqAdapter, params)
|
logger.Info("Registered restheadspec bunrouter routes for model %s at %s", fullName, entityPath)
|
||||||
return nil
|
}()
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -551,11 +551,27 @@ func (a *DatabaseAuthenticator) RefreshToken(ctx context.Context, refreshToken s
|
|||||||
return nil, fmt.Errorf("failed to parse user context: %w", err)
|
return nil, fmt.Errorf("failed to parse user context: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
return &LoginResponse{
|
// A resolvespec_refresh_token implementation that issues its own rotating
|
||||||
|
// refresh token (independent of the access/session token) returns it
|
||||||
|
// under claims.refresh_token, since UserContext has no dedicated field
|
||||||
|
// for it. Surface that into LoginResponse.RefreshToken so callers don't
|
||||||
|
// need to reach into User.Claims themselves. claims.expires_in
|
||||||
|
// (seconds) similarly overrides the default access-token ExpiresIn when
|
||||||
|
// the procedure provides a real value. Implementations that don't set
|
||||||
|
// these claims keep today's behavior unchanged (empty RefreshToken,
|
||||||
|
// 24h ExpiresIn default).
|
||||||
|
resp := &LoginResponse{
|
||||||
Token: userCtx.SessionID, // New session token from stored procedure
|
Token: userCtx.SessionID, // New session token from stored procedure
|
||||||
User: &userCtx,
|
User: &userCtx,
|
||||||
ExpiresIn: int64(24 * time.Hour.Seconds()),
|
ExpiresIn: int64(24 * time.Hour.Seconds()),
|
||||||
}, nil
|
}
|
||||||
|
if refreshToken, ok := userCtx.Claims["refresh_token"].(string); ok && refreshToken != "" {
|
||||||
|
resp.RefreshToken = refreshToken
|
||||||
|
}
|
||||||
|
if expiresIn, ok := userCtx.Claims["expires_in"].(float64); ok && expiresIn > 0 {
|
||||||
|
resp.ExpiresIn = int64(expiresIn)
|
||||||
|
}
|
||||||
|
return resp, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// JWTAuthenticator provides JWT token-based authentication
|
// JWTAuthenticator provides JWT token-based authentication
|
||||||
@@ -912,8 +928,20 @@ func (p *DatabaseRowSecurityProvider) GetRowSecurity(ctx context.Context, userRe
|
|||||||
return RowSecurity{}, ErrDirectModeUnsupported
|
return RowSecurity{}, ErrDirectModeUnsupported
|
||||||
}
|
}
|
||||||
|
|
||||||
var template string
|
// resolvespec_row_security's p_user_id is a scalar integer. GetUserRef() may
|
||||||
var hasBlock bool
|
// hand back the full *UserContext so non-DB providers can inspect claims;
|
||||||
|
// unwrap it here before it reaches the SQL args.
|
||||||
|
switch v := userRef.(type) {
|
||||||
|
case *UserContext:
|
||||||
|
if v != nil {
|
||||||
|
userRef = v.UserID
|
||||||
|
}
|
||||||
|
case UserContext:
|
||||||
|
userRef = v.UserID
|
||||||
|
}
|
||||||
|
|
||||||
|
var template sql.NullString
|
||||||
|
var hasBlock sql.NullBool
|
||||||
|
|
||||||
runQuery := func() error {
|
runQuery := func() error {
|
||||||
query := fmt.Sprintf(`SELECT p_template, p_block FROM %s($1, $2, $3)`, p.sqlNames.RowSecurity)
|
query := fmt.Sprintf(`SELECT p_template, p_block FROM %s($1, $2, $3)`, p.sqlNames.RowSecurity)
|
||||||
@@ -933,8 +961,8 @@ func (p *DatabaseRowSecurityProvider) GetRowSecurity(ctx context.Context, userRe
|
|||||||
Schema: schema,
|
Schema: schema,
|
||||||
Tablename: table,
|
Tablename: table,
|
||||||
UserID: userRef,
|
UserID: userRef,
|
||||||
Template: template,
|
Template: template.String,
|
||||||
HasBlock: hasBlock,
|
HasBlock: hasBlock.Bool,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -793,6 +793,49 @@ func TestDatabaseAuthenticatorRefreshToken(t *testing.T) {
|
|||||||
t.Errorf("unfulfilled expectations: %v", err)
|
t.Errorf("unfulfilled expectations: %v", err)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// A resolvespec_refresh_token implementation that rotates its own
|
||||||
|
// independent refresh token (not just reusing the session/access token)
|
||||||
|
// has nowhere else to put the new refresh token and real access-token
|
||||||
|
// expiry than under UserContext.Claims, since UserContext has no
|
||||||
|
// dedicated fields for either. RefreshToken must surface those claims
|
||||||
|
// keys into LoginResponse.RefreshToken/ExpiresIn rather than silently
|
||||||
|
// dropping them (see the "successful token refresh" case above, which
|
||||||
|
// covers an implementation that has no independent refresh token at all
|
||||||
|
// and gets the 24h default instead).
|
||||||
|
t.Run("surfaces rotated refresh token and expiry from claims", func(t *testing.T) {
|
||||||
|
refreshToken := "refresh-token-abc"
|
||||||
|
|
||||||
|
sessionRows := sqlmock.NewRows([]string{"p_success", "p_error", "p_user"}).
|
||||||
|
AddRow(true, nil, `{"user_id":1,"user_name":"testuser"}`)
|
||||||
|
mock.ExpectQuery(`SELECT p_success, p_error, p_user::text FROM resolvespec_session`).
|
||||||
|
WithArgs(refreshToken, "refresh").
|
||||||
|
WillReturnRows(sessionRows)
|
||||||
|
|
||||||
|
refreshRows := sqlmock.NewRows([]string{"p_success", "p_error", "p_user"}).
|
||||||
|
AddRow(true, nil, `{"user_id":1,"user_name":"testuser","session_id":"new-access-789","claims":{"refresh_token":"new-refresh-def","expires_in":900}}`)
|
||||||
|
mock.ExpectQuery(`SELECT p_success, p_error, p_user::text FROM resolvespec_refresh_token`).
|
||||||
|
WithArgs(refreshToken, sqlmock.AnyArg()).
|
||||||
|
WillReturnRows(refreshRows)
|
||||||
|
|
||||||
|
resp, err := auth.RefreshToken(ctx, refreshToken)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("expected no error, got %v", err)
|
||||||
|
}
|
||||||
|
if resp.Token != "new-access-789" {
|
||||||
|
t.Errorf("expected token new-access-789, got %s", resp.Token)
|
||||||
|
}
|
||||||
|
if resp.RefreshToken != "new-refresh-def" {
|
||||||
|
t.Errorf("expected rotated refresh token new-refresh-def, got %q", resp.RefreshToken)
|
||||||
|
}
|
||||||
|
if resp.ExpiresIn != 900 {
|
||||||
|
t.Errorf("expected ExpiresIn 900 from claims, got %d", resp.ExpiresIn)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := mock.ExpectationsWereMet(); err != nil {
|
||||||
|
t.Errorf("unfulfilled expectations: %v", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestDatabaseAuthenticatorReconnectsClosedDBPaths(t *testing.T) {
|
func TestDatabaseAuthenticatorReconnectsClosedDBPaths(t *testing.T) {
|
||||||
|
|||||||
Reference in New Issue
Block a user