Extract code generation logic into internal/api package#4418
Draft
kyleconroy wants to merge 4 commits intomainfrom
Draft
Extract code generation logic into internal/api package#4418kyleconroy wants to merge 4 commits intomainfrom
kyleconroy wants to merge 4 commits intomainfrom
Conversation
The new package mirrors esbuild's Build API: a single api.Generate(ctx,
api.GenerateOptions{}) call returns a GenerateResult containing the
generated files and any errors. Most of cmd/generate.go's logic moves
here as unexported helpers; the only exported names are Generate,
GenerateOptions, and GenerateResult.
cmd.Generate is now a thin wrapper that translates the CLI's Options
struct into api.GenerateOptions. The endtoend tests call api.Generate
directly for TestExamples, TestReplay (generate command), and the
benchmarks.
https://claude.ai/code/session_01RCzB2JR5Y5ScFDUmwcxGVZ
The two new boolean options let api.Generate cover the writefiles loop and the diff comparison that previously lived in cmd. The compile command becomes Generate with neither flag set, generate maps to Write: true, and diff maps to Diff: true. While simplifying GenerateOptions: * Drop MutateConfig — tests now express config mutations by writing a temporary configuration file via writeMutatedConfig and pointing GenerateOptions.File at it. The mutated config is parsed (always to v2 shape), forced to version "2", and round-tripped via yaml. * Drop DisableProcessPlugins from the API surface; we will revisit how to express that constraint. * Add MarshalJSON/MarshalYAML to AnalyzerDatabase so the parsed Config round-trips through yaml.Marshal cleanly, which is what the new test helper relies on. cmd/diff.go is gone and cmd/generate.go is left with only the helpers (readConfig, parse, printFileErr) other cmd commands still use. https://claude.ai/code/session_01RCzB2JR5Y5ScFDUmwcxGVZ
Add an explicit allowlist of process-based plugin names to api.GenerateOptions. Generate fails before any parse or codegen runs if the configuration declares a process plugin whose name is not in the list. The "Insecure" prefix mirrors crypto/tls.Config.InsecureSkipVerify to flag the trust decision callers are making — process plugins execute arbitrary local commands. The CLI populates the allowlist by scanning the user's own config for declared process plugins, so `sqlc generate`, `sqlc compile`, and `sqlc diff` keep working. SQLCDEBUG=processplugins=0 still disables process plugins by leaving the allowlist nil. https://claude.ai/code/session_01RCzB2JR5Y5ScFDUmwcxGVZ
The struct collapses to five fields: Config (io.Reader), Stderr, Write, Diff, InsecureProcessPluginNames. api.Generate parses the config from the reader and treats every relative path in it as relative to the current working directory. CLI: each command opens the config file, reads its bytes, parses it once to extract declared process-plugin names, then chdirs to the config's directory before invoking api.Generate. Single-process so chdir is fine. Tests: a new mutatedConfigBytes helper parses the test's sqlc.yaml, forces version "2", rewrites every schema/queries/output path to be absolute relative to the test directory, and re-encodes as YAML — so api.Generate works without knowing the source directory. Optional mutate callback applies extra changes (managed-db servers etc.) and also drops a temp file alongside the original for cmd.Vet which still takes a config path. cmd/process.go and cmd/vet.go now skip joining their dir parameter when the config-supplied path is already absolute. KNOWN ISSUE: TestReplay parse-error tests and the diff_output tests fail because the api now emits absolute paths in error messages and unified-diff labels (no config-dir context to strip). Either add a BaseDir hint back to GenerateOptions or update the affected test expectations to match. https://claude.ai/code/session_01RCzB2JR5Y5ScFDUmwcxGVZ
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
This refactoring extracts the core code generation logic from
internal/cmdinto a newinternal/apipackage, establishing a programmatic API for sqlc that can be used independently of the CLI.Summary
The change moves code generation orchestration and related utilities into a new
internal/apipackage with a clean public interface (api.Generate), while the CLI continues to work through a thin wrapper. This enables programmatic use of sqlc without CLI dependencies.Key Changes
New
internal/apipackage with the following modules:api.go: Package documentation describing the public API designgenerate.go: CoreGenerate()function andGenerateOptions/GenerateResulttypesprocess.go: Query set processing logic andresultProcessorinterfacecodegen.go: Code generation orchestration (plugin handling, format selection)config.go: Configuration file reading and validationparse.go: SQL parsing logicshim.go: Protocol buffer message conversion helpersCLI refactoring (
internal/cmd/generate.go):Generate()now delegates toapi.Generate()with appropriate option translationapipackageTest updates (
internal/endtoend/endtoend_test.go):api.Generate()directly instead of CLI wrapperNotable Implementation Details
GenerateOptionsincludesDisableProcessPluginsflag to supportSQLCDEBUG=processplugins=0environment variable handlingGenerateResultalways returns a non-nilFilesmap (empty on error) and collects errors in anErrorssliceMutateConfig) provided for testing purposesvalidateProcessPluginsDisabled()for reuseoutputPairtype (renamed fromOutputPair) encapsulates SQL configuration with generation targetshttps://claude.ai/code/session_01RCzB2JR5Y5ScFDUmwcxGVZ