Skip to content

Commit d2837b7

Browse files
kyleconroyclaude
andcommitted
core: land xqlc catalog + analyzer on sqlc's AST
Port xqlc's core catalog (SQLite-backed sql_* catalog) and its dialect-neutral query analyzer into internal/core, repointing the analyzer from xqlc's copy of the AST onto sqlc's internal/sql/ast so there is a single AST. No converter and no second AST package. A smoke test drives the analyzer with sqlc's own PostgreSQL parser to prove the repointed analyzer resolves columns, types, star expansion, and aliases end-to-end against internal/sql/ast. This is the first step of merging xqlc back into sqlc as the future analysis core; ClickHouse will be the first engine wired onto it. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01XTGxNHW6v1S1YyC9FDSgrK
1 parent 22d878a commit d2837b7

23 files changed

Lines changed: 2283 additions & 3 deletions

go.mod

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,27 +30,36 @@ require (
3030
google.golang.org/grpc v1.81.1
3131
google.golang.org/protobuf v1.36.11
3232
gopkg.in/yaml.v3 v3.0.1
33+
modernc.org/sqlite v1.48.1
3334
)
3435

3536
require (
3637
cel.dev/expr v0.25.1 // indirect
3738
filippo.io/edwards25519 v1.2.0 // indirect
39+
github.com/dustin/go-humanize v1.0.1 // indirect
40+
github.com/google/uuid v1.6.0 // indirect
3841
github.com/inconshreveable/mousetrap v1.1.0 // indirect
3942
github.com/jackc/pgpassfile v1.0.0 // indirect
4043
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
4144
github.com/jackc/puddle/v2 v2.2.2 // indirect
4245
github.com/kr/text v0.2.0 // indirect
46+
github.com/mattn/go-isatty v0.0.20 // indirect
4347
github.com/ncruces/go-sqlite3-wasm/v2 v2.6.35302 // indirect
48+
github.com/ncruces/go-strftime v1.0.0 // indirect
4449
github.com/ncruces/julianday v1.0.0 // indirect
50+
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
4551
github.com/rogpeppe/go-internal v1.10.0 // indirect
4652
github.com/wasilibs/wazero-helpers v0.0.0-20240620070341-3dff1577cd52 // indirect
4753
github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f // indirect
4854
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect
4955
go.yaml.in/yaml/v3 v3.0.4 // indirect
50-
golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b // indirect
56+
golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546 // indirect
5157
golang.org/x/net v0.55.0 // indirect
5258
golang.org/x/sys v0.45.0 // indirect
5359
golang.org/x/text v0.37.0 // indirect
5460
google.golang.org/genproto/googleapis/api v0.0.0-20260226221140-a57be14db171 // indirect
5561
google.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171 // indirect
62+
modernc.org/libc v1.70.0 // indirect
63+
modernc.org/mathutil v1.7.1 // indirect
64+
modernc.org/memory v1.11.0 // indirect
5665
)

go.sum

Lines changed: 47 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@ github.com/cubicdaiya/gonp v1.0.4/go.mod h1:iWGuP/7+JVTn02OWhRemVbMmG1DOUnmrGTYY
1313
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
1414
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
1515
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
16+
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
17+
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
1618
github.com/fatih/structtag v1.2.0 h1:/OdNE99OxoI/PqaW/SuSK9uxxT3f/tcSZgon/ssNSx4=
1719
github.com/fatih/structtag v1.2.0/go.mod h1:mBJUNpUnHmRKrKlQQlmCrh5PuhftFbNv8Ys4/aAZl94=
1820
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
@@ -27,8 +29,12 @@ github.com/google/cel-go v0.28.1 h1:YWIwi77J4xIsYUwAF/iIuS6haffzIHS8yWI8glSbLWM=
2729
github.com/google/cel-go v0.28.1/go.mod h1:X0bD6iVNR8pkROSOoHVdgTkzmRcosof7WQqCD6wcMc8=
2830
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
2931
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
32+
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=
33+
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
3034
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
3135
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
36+
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
37+
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
3238
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
3339
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
3440
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
@@ -47,16 +53,22 @@ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
4753
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
4854
github.com/lib/pq v1.12.3 h1:tTWxr2YLKwIvK90ZXEw8GP7UFHtcbTtty8zsI+YjrfQ=
4955
github.com/lib/pq v1.12.3/go.mod h1:/p+8NSbOcwzAEI7wiMXFlgydTwcgTr3OSKMsD2BitpA=
56+
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
57+
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
5058
github.com/ncruces/go-sqlite3 v0.34.4 h1:bp8jd1o2CMvjkrrp1lOtHDu1TdzExNWACt+piQeMwzg=
5159
github.com/ncruces/go-sqlite3 v0.34.4/go.mod h1:tOyhDWnzlrzflKIGw177imjuO4ZEbfOS1NJ67B1BanQ=
5260
github.com/ncruces/go-sqlite3-wasm/v2 v2.6.35302 h1:IZCiInPIp6OhOc1skMDGOBMwMQuE1TK+QqVe35vd/ro=
5361
github.com/ncruces/go-sqlite3-wasm/v2 v2.6.35302/go.mod h1:ELHF6yqC51E0DiitfabHXl/aKKouCihugbhNT5a+yEY=
62+
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
63+
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
5464
github.com/ncruces/julianday v1.0.0 h1:fH0OKwa7NWvniGQtxdJRxAgkBMolni2BjDHaWTxqt7M=
5565
github.com/ncruces/julianday v1.0.0/go.mod h1:Dusn2KvZrrovOMJuOt0TNXL6tB7U2E8kvza5fFc9G7g=
5666
github.com/pganalyze/pg_query_go/v6 v6.2.2 h1:O0L6zMC226R82RF3X5n0Ki6HjytDsoAzuzp4ATVAHNo=
5767
github.com/pganalyze/pg_query_go/v6 v6.2.2/go.mod h1:Cn6+j4870kJz3iYNsb0VsNG04vpSWgEvBwc590J4qD0=
5868
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
5969
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
70+
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
71+
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
6072
github.com/riza-io/grpc-go v0.2.0 h1:2HxQKFVE7VuYstcJ8zqpN84VnAoJ4dCL6YFhJewNcHQ=
6173
github.com/riza-io/grpc-go v0.2.0/go.mod h1:2bDvR9KkKC3KhtlSHfR3dAXjUMT86kg4UfWFyVGWqi8=
6274
github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=
@@ -104,16 +116,21 @@ go.opentelemetry.io/otel/trace v1.43.0 h1:BkNrHpup+4k4w+ZZ86CZoHHEkohws8AY+WTX09
104116
go.opentelemetry.io/otel/trace v1.43.0/go.mod h1:/QJhyVBUUswCphDVxq+8mld+AvhXZLhe+8WVFxiFff0=
105117
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
106118
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
107-
golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b h1:M2rDM6z3Fhozi9O7NWsxAkg/yqS/lQJ6PmkyIV3YP+o=
108-
golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b/go.mod h1:3//PLf8L/X+8b4vuAfHzxeRUl04Adcb341+IGKfnqS8=
119+
golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546 h1:mgKeJMpvi0yx/sU5GsxQ7p6s2wtOnGAHZWCHUM4KGzY=
120+
golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546/go.mod h1:j/pmGrbnkbPtQfxEe5D0VQhZC6qKbfKifgD0oM7sR70=
121+
golang.org/x/mod v0.35.0 h1:Ww1D637e6Pg+Zb2KrWfHQUnH2dQRLBQyAtpr/haaJeM=
122+
golang.org/x/mod v0.35.0/go.mod h1:+GwiRhIInF8wPm+4AoT6L0FA1QWAad3OMdTRx4tFYlU=
109123
golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8=
110124
golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww=
111125
golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM=
112126
golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
127+
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
113128
golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY=
114129
golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
115130
golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc=
116131
golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38=
132+
golang.org/x/tools v0.45.0 h1:18qN3FAooORvApf5XjCXgsuayZOEtXf6JK18I3+ONa8=
133+
golang.org/x/tools v0.45.0/go.mod h1:LuUGqqaXcXMEFEruIVJVm5mgDD8vww/z/SR1gQ4uE/0=
117134
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
118135
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
119136
google.golang.org/genproto/googleapis/api v0.0.0-20260226221140-a57be14db171 h1:tu/dtnW1o3wfaxCOjSLn5IRX4YDcJrtlpzYkhHhGaC4=
@@ -130,3 +147,31 @@ gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EV
130147
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
131148
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
132149
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
150+
modernc.org/cc/v4 v4.27.1 h1:9W30zRlYrefrDV2JE2O8VDtJ1yPGownxciz5rrbQZis=
151+
modernc.org/cc/v4 v4.27.1/go.mod h1:uVtb5OGqUKpoLWhqwNQo/8LwvoiEBLvZXIQ/SmO6mL0=
152+
modernc.org/ccgo/v4 v4.32.0 h1:hjG66bI/kqIPX1b2yT6fr/jt+QedtP2fqojG2VrFuVw=
153+
modernc.org/ccgo/v4 v4.32.0/go.mod h1:6F08EBCx5uQc38kMGl+0Nm0oWczoo1c7cgpzEry7Uc0=
154+
modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM=
155+
modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU=
156+
modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
157+
modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
158+
modernc.org/gc/v3 v3.1.2 h1:ZtDCnhonXSZexk/AYsegNRV1lJGgaNZJuKjJSWKyEqo=
159+
modernc.org/gc/v3 v3.1.2/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
160+
modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
161+
modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
162+
modernc.org/libc v1.70.0 h1:U58NawXqXbgpZ/dcdS9kMshu08aiA6b7gusEusqzNkw=
163+
modernc.org/libc v1.70.0/go.mod h1:OVmxFGP1CI/Z4L3E0Q3Mf1PDE0BucwMkcXjjLntvHJo=
164+
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
165+
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
166+
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
167+
modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
168+
modernc.org/opt v0.1.4 h1:2kNGMRiUjrp4LcaPuLY2PzUfqM/w9N23quVwhKt5Qm8=
169+
modernc.org/opt v0.1.4/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
170+
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
171+
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
172+
modernc.org/sqlite v1.48.1 h1:S85iToyU6cgeojybE2XJlSbcsvcWkQ6qqNXJHtW5hWA=
173+
modernc.org/sqlite v1.48.1/go.mod h1:hWjRO6Tj/5Ik8ieqxQybiEOUXy0NJFNp2tpvVpKlvig=
174+
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
175+
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
176+
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
177+
modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=

internal/core/analysis.go

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
package core
2+
3+
// Command identifies the kind of statement that produced a PrepareResult.
4+
// Only the four DML statements that can have a prepare-able shape are
5+
// emitted; DDL and TCL produce an empty result with Command == "".
6+
type Command string
7+
8+
const (
9+
CommandSelect Command = "SELECT"
10+
CommandInsert Command = "INSERT"
11+
CommandUpdate Command = "UPDATE"
12+
CommandDelete Command = "DELETE"
13+
)
14+
15+
// PrepareResult describes the output of preparing a SQL statement.
16+
type PrepareResult struct {
17+
Command Command `json:"command,omitempty"`
18+
Columns []Column `json:"columns"`
19+
Parameters []Parameter `json:"parameters"`
20+
}
21+
22+
// ColumnSource identifies the table column a result column or bind
23+
// parameter is sourced from. All fields are optional; the struct is
24+
// emitted only when at least one is populated.
25+
//
26+
// Schema / Table / Column are the *origin* identifiers (pre-alias) —
27+
// they correspond to sqlite's `sqlite3_column_origin_name` and mysql's
28+
// `org_table` / `org_name`. TableAlias is the name the query used to
29+
// refer to the table; it lets codegen distinguish `t1` from `t2` in
30+
// `SELECT t1.x, t2.x FROM t t1 JOIN t t2 ...`.
31+
type ColumnSource struct {
32+
Schema string `json:"schema,omitempty"`
33+
Table string `json:"table,omitempty"`
34+
TableAlias string `json:"table_alias,omitempty"`
35+
Column string `json:"column,omitempty"`
36+
}
37+
38+
// Column describes a single output column from a prepared statement.
39+
//
40+
// SourceClassOID and SourceAttributeOID are populated when the column
41+
// is a direct reference to a table column (i.e. it appears in
42+
// sql_attribute); they are zero for computed/derived expressions like
43+
// aggregates or arithmetic. Source is the human-readable resolution of
44+
// those OIDs and is populated under the same conditions.
45+
//
46+
// DeclType, TypeLength, TypeScale, IsPrimaryKey, IsUnique, and
47+
// IsAutoIncrement come from the resolved source attribute and are zero
48+
// for computed expressions.
49+
type Column struct {
50+
Name string `json:"name"`
51+
DataType string `json:"data_type"`
52+
TypeOID int64 `json:"type_oid,omitempty"`
53+
NotNull bool `json:"not_null"`
54+
SourceClassOID int64 `json:"source_class_oid,omitempty"`
55+
SourceAttributeOID int64 `json:"source_attribute_oid,omitempty"`
56+
Source *ColumnSource `json:"source,omitempty"`
57+
DeclType string `json:"decl_type,omitempty"`
58+
TypeLength int `json:"type_length,omitempty"`
59+
TypeScale int `json:"type_scale,omitempty"`
60+
IsPrimaryKey bool `json:"is_primary_key,omitempty"`
61+
IsUnique bool `json:"is_unique,omitempty"`
62+
IsAutoIncrement bool `json:"is_auto_increment,omitempty"`
63+
}
64+
65+
// Parameter describes a bind parameter in a prepared statement.
66+
//
67+
// Number is the 1-based position of the parameter as it appeared in the
68+
// source ($1, $2, ...). Name is populated for named-parameter dialects
69+
// or when a sqlc-style "-- name:" annotation gave the param a name; it
70+
// is empty otherwise. DataType / TypeOID / NotNull come from the
71+
// resolved usage site (an operator overload, function argument, etc.).
72+
// Source identifies the column the parameter binds against (e.g.
73+
// `users.age` for `WHERE age > $1`), when one can be inferred.
74+
type Parameter struct {
75+
Number int `json:"number"`
76+
Name string `json:"name,omitempty"`
77+
DataType string `json:"data_type,omitempty"`
78+
TypeOID int64 `json:"type_oid,omitempty"`
79+
NotNull bool `json:"not_null"`
80+
Source *ColumnSource `json:"source,omitempty"`
81+
}

internal/core/analyzer/analyzer.go

Lines changed: 152 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
1+
// Package analyzer implements a dialect-neutral SQL query analyzer that
2+
// resolves names, types, operators, and parameters by querying the
3+
// catalog (core.Catalog). It produces a core.PrepareResult.
4+
//
5+
// Scope is intentionally narrow in this iteration: single-relation SELECT
6+
// queries, simple WHERE / GROUP BY / projection. JOINs, subqueries,
7+
// CTEs, set ops, and DML RETURNING are intended follow-ups.
8+
package analyzer
9+
10+
import (
11+
"fmt"
12+
13+
"github.com/sqlc-dev/sqlc/internal/core"
14+
"github.com/sqlc-dev/sqlc/internal/sql/ast"
15+
)
16+
17+
// Prepare walks a parsed statement and produces a PrepareResult by
18+
// querying the catalog for relations, types, operators, and casts.
19+
// stmt can be a *ast.RawStmt (typical parser output) or an unwrapped
20+
// statement node.
21+
func Prepare(cat *core.Catalog, stmt ast.Node) (core.PrepareResult, error) {
22+
if rs, ok := stmt.(*ast.RawStmt); ok {
23+
stmt = rs.Stmt
24+
}
25+
a := &analyzer{
26+
cat: cat,
27+
params: map[int]*core.Parameter{},
28+
}
29+
switch s := stmt.(type) {
30+
case *ast.SelectStmt:
31+
if err := a.analyzeSelect(s); err != nil {
32+
return core.PrepareResult{}, err
33+
}
34+
a.command = core.CommandSelect
35+
default:
36+
return core.PrepareResult{}, fmt.Errorf("analyzer: unsupported statement %T", stmt)
37+
}
38+
return a.result(), nil
39+
}
40+
41+
type analyzer struct {
42+
cat *core.Catalog
43+
scope *scope
44+
columns []core.Column
45+
params map[int]*core.Parameter
46+
command core.Command
47+
}
48+
49+
func (a *analyzer) result() core.PrepareResult {
50+
return core.PrepareResult{
51+
Command: a.command,
52+
Columns: a.columns,
53+
Parameters: orderedParams(a.params),
54+
}
55+
}
56+
57+
func orderedParams(m map[int]*core.Parameter) []core.Parameter {
58+
if len(m) == 0 {
59+
return nil
60+
}
61+
maxN := 0
62+
for n := range m {
63+
if n > maxN {
64+
maxN = n
65+
}
66+
}
67+
out := make([]core.Parameter, 0, len(m))
68+
for i := 1; i <= maxN; i++ {
69+
if p, ok := m[i]; ok {
70+
out = append(out, *p)
71+
}
72+
}
73+
return out
74+
}
75+
76+
func (a *analyzer) analyzeSelect(s *ast.SelectStmt) error {
77+
sc, err := a.buildScope(s.FromClause)
78+
if err != nil {
79+
return err
80+
}
81+
a.scope = sc
82+
83+
// Join ON conditions get typed against the (already-assembled)
84+
// scope so they can reference columns from either side.
85+
for _, item := range listItems(s.FromClause) {
86+
if err := a.typeJoinConditions(item); err != nil {
87+
return fmt.Errorf("join: %w", err)
88+
}
89+
}
90+
91+
if s.WhereClause != nil {
92+
if _, err := a.typeExpr(s.WhereClause); err != nil {
93+
return fmt.Errorf("where: %w", err)
94+
}
95+
}
96+
if items := listItems(s.GroupClause); items != nil {
97+
for _, g := range items {
98+
if _, err := a.typeExpr(g); err != nil {
99+
return fmt.Errorf("group by: %w", err)
100+
}
101+
}
102+
}
103+
if s.HavingClause != nil {
104+
if _, err := a.typeExpr(s.HavingClause); err != nil {
105+
return fmt.Errorf("having: %w", err)
106+
}
107+
}
108+
109+
targets := listItems(s.TargetList)
110+
if targets == nil {
111+
return fmt.Errorf("select: empty target list")
112+
}
113+
for _, t := range targets {
114+
rt, ok := t.(*ast.ResTarget)
115+
if !ok {
116+
continue
117+
}
118+
if err := a.projectTarget(rt); err != nil {
119+
return err
120+
}
121+
}
122+
return nil
123+
}
124+
125+
func listItems(l *ast.List) []ast.Node {
126+
if l == nil {
127+
return nil
128+
}
129+
return l.Items
130+
}
131+
132+
// typeJoinConditions walks a FROM-list item and types every join's ON
133+
// expression. USING clauses are skipped — the columns they reference
134+
// already exist in scope, no expression to type.
135+
func (a *analyzer) typeJoinConditions(item ast.Node) error {
136+
je, ok := item.(*ast.JoinExpr)
137+
if !ok {
138+
return nil
139+
}
140+
if err := a.typeJoinConditions(je.Larg); err != nil {
141+
return err
142+
}
143+
if err := a.typeJoinConditions(je.Rarg); err != nil {
144+
return err
145+
}
146+
if je.Quals != nil {
147+
if _, err := a.typeExpr(je.Quals); err != nil {
148+
return fmt.Errorf("ON: %w", err)
149+
}
150+
}
151+
return nil
152+
}

0 commit comments

Comments
 (0)