I was reading the documentation for SQLC from https://docs.sqlc.dev/en/latest/howto/query_count.html. I wanted to use this in my project. However, I'm not seeing any documentation related to joining operations on the tables. Is it really possible in SQLC. If yes where I could find the documentation or reference?
A commit like "cdf7025: Add MySQL json test" (or "456fcb1 Add MySQL test for SELECT * JOIN
") suggests joins are supported.
2021: But it is true, as mentioned in issue 643, that queries with JOINs are for now not documented yet.
2023: the same issue 643 now (Sept. 2023) includes a reference to the new documentation (thanks to Kyle Gray):
Embedding structs
Embedding allows you to reuse existing model structs in more queries, resulting in less manual serialization work. First, imagine we have the following schema with students and test scores.
CREATE TABLE students ( id bigserial PRIMARY KEY, name text NOT NULL, age integer NOT NULL ); CREATE TABLE test_scores ( student_id bigint NOT NULL, score integer NOT NULL, grade text NOT NULL );
We want to select the student record and the scores they got on a test. Here's how we'd usually do that:
-- name: ScoreAndTests :many SELECT students.*, test_scores.* FROM students JOIN test_scores ON test_scores.student_id = students.id WHERE students.id = ?;
When using Go, sqlc will produce a struct like this:
type ScoreAndTestsRow struct { ID int64 Name string Age int32 StudentID int64 Score int32 Grade string }
With embedding, the struct will contain a model for both tables instead of a flattened list of columns.
-- name: ScoreAndTests :many SELECT sqlc.embed(students), sqlc.embed(test_scores) FROM students JOIN test_scores ON test_scores.student_id = students.id WHERE students.id = ?;
type ScoreAndTestsRow struct { Student Student TestScore TestScore }
And discussion 363 points to the changelog for sqlc.embed
.