The runtime query builder: MySQL and ClickHouse
Every file of the MySQL and ClickHouse versions side by side, with the lines that differ marked. 4 parameter or column types differ in Go.
Configuration
sgl.yamldiffers
MySQL
ClickHouse
1
version: 11
version: 12
2
3
databases:3
databases:4
- name: pier4
- name: pier5
dialect: mysql5
dialect: clickhouse6
migrations: db/migrations6
migrations: db/migrations7
queries: db/queries7
queries: db/queries8
go:8
go:9
package: store9
package: store10
out: internal/store10
out: internal/storeMigrations
db/migrations/0001_lost_property.up.sqldiffers
MySQL
ClickHouse
1
CREATE TABLE lost_property (1
CREATE TABLE lost_property (2
id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,2
id UInt64,3
item VARCHAR(50) NOT NULL,3
item String,4
colour VARCHAR(20) NOT NULL,4
colour String,5
found_at VARCHAR(50) NOT NULL,5
found_at String,6
days_held INT NOT NULL,6
days_held UInt32,7
claimed BOOLEAN NOT NULL DEFAULT FALSE,7
claimed Bool DEFAULT false,8
owner_phone VARCHAR(20)8
owner_phone Nullable(String)9
);9
) ENGINE = MergeTree() ORDER BY id;db/migrations/0001_lost_property.down.sqlidentical
MySQL
ClickHouse
1
DROP TABLE lost_property;1
DROP TABLE lost_property;Queries
HandIndiffers
MySQL · db/queries/lost_property.sql
ClickHouse · db/queries/lost_property.sql
1
-- sgl.query(HandIn, exec)1
-- sgl.query(HandIn, exec)2
INSERT INTO lost_property (item, colour, found_at, days_held) VALUES (?, ?, ?, ?);2
INSERT INTO lost_property (id, item, colour, found_at, days_held)3
VALUES ({id:UInt64}, {item:String}, {colour:String}, {found_at:String}, {days_held:UInt32});Claimdiffers
MySQL · db/queries/lost_property.sql
ClickHouse · db/queries/lost_property.sql
1
-- sgl.query(Claim, execrows)1
-- sgl.query(Claim, asyncexec)2
UPDATE lost_property SET claimed = TRUE, owner_phone = ? WHERE id = ?;2
ALTER TABLE lost_property3
UPDATE claimed = true, owner_phone = {owner_phone:Nullable(String)}4
WHERE id = {id:UInt64};SearchUnclaimeddiffers
MySQL · db/queries/lost_property.sql
ClickHouse · db/queries/lost_property.sql
1
-- sgl.query(SearchUnclaimed, many, dynamic: runtime)1
-- sgl.query(SearchUnclaimed, many, dynamic: runtime)2
SELECT id, item, colour, found_at, days_held2
SELECT id, item, colour, found_at, days_held3
FROM lost_property3
FROM lost_property4
WHERE claimed = FALSE4
WHERE claimed = falseWhat sgl generates
HandIndiffers
MySQL
ClickHouse
1
func (queries *Queries) HandIn(ctx context.Context, params HandInParams) error1
func (queries *Queries) HandIn(ctx context.Context, params HandInParams) error2
2
3
type HandInParams struct {3
type HandInParams struct {4
ID uint644
Item string5
Item string5
Colour string6
Colour string6
FoundAt string7
FoundAt string7
DaysHeld int328
DaysHeld uint328
}9
}Claimdiffers
MySQL
ClickHouse
1
func (queries *Queries) Claim(ctx context.Context, params ClaimParams) (int64, error)1
func (queries *Queries) Claim(ctx context.Context, params ClaimParams) error2
2
3
type ClaimParams struct {3
type ClaimParams struct {4
OwnerPhone *string4
OwnerPhone *string5
ID int645
ID uint646
}6
}SearchUnclaimeddiffers
MySQL
ClickHouse
1
func (queries *Queries) SearchUnclaimed() *SearchUnclaimedBuilder1
func (queries *Queries) SearchUnclaimed() *SearchUnclaimedBuilder2
2
3
type SearchUnclaimedRow struct {3
type SearchUnclaimedRow struct {4
ID int64 `json:"id"`4
ID uint64 `json:"id"`5
Item string `json:"item"`5
Item string `json:"item"`6
Colour string `json:"colour"`6
Colour string `json:"colour"`7
FoundAt string `json:"found_at"`7
FoundAt string `json:"found_at"`8
DaysHeld int32 `json:"days_held"`8
DaysHeld uint32 `json:"days_held"`9
}9
}The program
example.godiffers
MySQL
ClickHouse
1
package main1
package main2
2
3
import (3
import (4
"context"4
"context"5
"database/sql"5
"database/sql"6
"errors"6
"errors"7
"fmt"7
"fmt"8
"io"8
"io"9
9
10
"seagull.sh/seagull/examples/mysql/014_runtime_builder/internal/store"10
"seagull.sh/seagull/examples/clickhouse/014_runtime_builder/internal/store"11
)11
)12
12
13
// run searches the pier's unclaimed lost property. dynamic: runtime turns SearchUnclaimed13
// run searches the pier's unclaimed lost property. dynamic: runtime turns SearchUnclaimed14
// into a builder: Where, OrderBy, Limit and Offset add to the SQL, and All, One or Count14
// into a builder: Where, OrderBy, Limit and Offset add to the SQL, and All, One or Count15
// run it. The base query already has WHERE claimed = FALSE, so each Where is joined with15
// run it. The base query already has WHERE claimed = false, so each Where is joined with16
// AND, which sgl vet points out as hint Q022. The builder inserts its filters, order and16
// AND, which sgl vet points out as hint Q022. The builder inserts its filters, order and17
// limit at the places the query leaves for them, before any LIMIT or trailing semicolon,17
// limit at the places the query leaves for them, before any LIMIT or trailing semicolon,18
// and Count replaces the SELECT list with COUNT(*), wrapping the whole query instead when18
// and Count replaces the SELECT list with COUNT(*), wrapping the whole query instead when19
// it groups or is DISTINCT (Q023).19
// it groups or is DISTINCT (Q023).20
//20
//21
// The builder is safe with untrusted input. Where and OrderBy accept only the columns the21
// The builder is safe with untrusted input. Where and OrderBy accept only the columns the22
// query selects, so owner_phone, which the table has but the query leaves out, cannot be22
// query selects, so owner_phone, which the table has but the query leaves out, cannot be23
// searched. Operators and directions come from fixed allow-lists, and every value is23
// searched. Operators and directions come from fixed allow-lists, and every value is24
// bound as a parameter, never written into the SQL. A refused input does not panic: the24
// bound as a parameter, never written into the SQL. A refused input does not panic: the25
// terminal returns ErrSglUnknownColumn, ErrSglUnknownOperator or ErrSglUnknownDirection.25
// terminal returns ErrSglUnknownColumn, ErrSglUnknownOperator or ErrSglUnknownDirection.26
//26
//27
// Claim is an ALTER TABLE ... UPDATE mutation, so it is asyncexec; the connection sets28
// mutations_sync=2, so the claimed phone is gone from the searches that follow.29
//27
// Takes database (*sql.DB) which is a migrated database.30
// Takes database (*sql.DB) which is a migrated database.28
// Takes output (io.Writer) which receives the searches and the refusals.31
// Takes output (io.Writer) which receives the searches and the refusals.29
//32
//30
// Returns error when a query fails or an unsafe input is not refused.33
// Returns error when a query fails or an unsafe input is not refused.31
func run(ctx context.Context, database *sql.DB, output io.Writer) error {34
func run(ctx context.Context, database *sql.DB, output io.Writer) error {32
queries := store.New(database)35
queries := store.New(database)33
36
34
items := []store.HandInParams{37
items := []store.HandInParams{35
{Item: "umbrella", Colour: "red", FoundAt: "the pier", DaysHeld: 40},38
{ID: 1, Item: "umbrella", Colour: "red", FoundAt: "the pier", DaysHeld: 40},36
{Item: "sunglasses", Colour: "black", FoundAt: "the beach", DaysHeld: 12},39
{ID: 2, Item: "sunglasses", Colour: "black", FoundAt: "the beach", DaysHeld: 12},37
{Item: "bucket and spade", Colour: "red", FoundAt: "the beach", DaysHeld: 3},40
{ID: 3, Item: "bucket and spade", Colour: "red", FoundAt: "the beach", DaysHeld: 3},38
{Item: "umbrella", Colour: "blue", FoundAt: "the cafe", DaysHeld: 33},41
{ID: 4, Item: "umbrella", Colour: "blue", FoundAt: "the cafe", DaysHeld: 33},39
{Item: "phone", Colour: "black", FoundAt: "the pier", DaysHeld: 1},42
{ID: 5, Item: "phone", Colour: "black", FoundAt: "the pier", DaysHeld: 1},40
}43
}41
for _, item := range items {44
for _, item := range items {42
if err := queries.HandIn(ctx, item); err != nil {45
if err := queries.HandIn(ctx, item); err != nil {43
return fmt.Errorf("handing in a %s: %w", item.Item, err)46
return fmt.Errorf("handing in a %s: %w", item.Item, err)44
}47
}45
}48
}46
if _, err := queries.Claim(ctx, store.ClaimParams{OwnerPhone: new("07700 900123"), ID: 5}); err != nil {49
if err := queries.Claim(ctx, store.ClaimParams{OwnerPhone: new("07700 900123"), ID: 5}); err != nil {47
return fmt.Errorf("claiming the phone: %w", err)50
return fmt.Errorf("claiming the phone: %w", err)48
}51
}49
52
50
red, err := queries.SearchUnclaimed().Where("colour", "=", "red").All(ctx)53
red, err := queries.SearchUnclaimed().Where("colour", "=", "red").OrderBy("id", "ASC").All(ctx)51
if err != nil {54
if err != nil {52
return fmt.Errorf("finding red items: %w", err)55
return fmt.Errorf("finding red items: %w", err)53
}56
}54
fmt.Fprintln(output, "red:")57
fmt.Fprintln(output, "red:")55
printItems(output, red)58
printItems(output, red)56
59
57
longest, err := queries.SearchUnclaimed().60
longest, err := queries.SearchUnclaimed().58
Where("days_held", ">=", 30).61
Where("days_held", ">=", 30).59
OrderBy("days_held", "DESC").62
OrderBy("days_held", "DESC").60
Limit(2).63
Limit(2).61
All(ctx)64
All(ctx)62
if err != nil {65
if err != nil {63
return fmt.Errorf("finding long-held items: %w", err)66
return fmt.Errorf("finding long-held items: %w", err)64
}67
}65
fmt.Fprintln(output, "held 30 days or more, longest first:")68
fmt.Fprintln(output, "held 30 days or more, longest first:")66
printItems(output, longest)69
printItems(output, longest)67
70
68
umbrellas, err := queries.SearchUnclaimed().Where("item", "=", "umbrella").Count(ctx)71
umbrellas, err := queries.SearchUnclaimed().Where("item", "=", "umbrella").Count(ctx)69
if err != nil {72
if err != nil {70
return fmt.Errorf("counting umbrellas: %w", err)73
return fmt.Errorf("counting umbrellas: %w", err)71
}74
}72
fmt.Fprintf(output, "unclaimed umbrellas: %d\n", umbrellas)75
fmt.Fprintf(output, "unclaimed umbrellas: %d\n", umbrellas)73
76
74
tautology, err := queries.SearchUnclaimed().Where("item", "=", "' OR '1'='1").All(ctx)77
tautology, err := queries.SearchUnclaimed().Where("item", "=", "' OR '1'='1").All(ctx)75
if err != nil {78
if err != nil {76
return fmt.Errorf("searching for a quoted value: %w", err)79
return fmt.Errorf("searching for a quoted value: %w", err)77
}80
}78
fmt.Fprintf(output, "items named ' OR '1'='1: %d, as the value is bound, not run\n", len(tautology))81
fmt.Fprintf(output, "items named ' OR '1'='1: %d, as the value is bound, not run\n", len(tautology))79
82
80
attempts := []struct {83
attempts := []struct {81
label string84
label string82
search *store.SearchUnclaimedBuilder85
search *store.SearchUnclaimedBuilder83
}{86
}{84
{label: "a column the query does not select", search: queries.SearchUnclaimed().Where("owner_phone", "IS NOT NULL", nil)},87
{label: "a column the query does not select", search: queries.SearchUnclaimed().Where("owner_phone", "IS NOT NULL", nil)},85
{label: "SQL in a column name", search: queries.SearchUnclaimed().OrderBy("id; DROP TABLE lost_property", "ASC")},88
{label: "SQL in a column name", search: queries.SearchUnclaimed().OrderBy("id; DROP TABLE lost_property", "ASC")},86
{label: "an operator outside the allow-list", search: queries.SearchUnclaimed().Where("colour", "= 'red' OR 1=1 --", "red")},89
{label: "an operator outside the allow-list", search: queries.SearchUnclaimed().Where("colour", "= 'red' OR 1=1 --", "red")},87
{label: "a direction outside the allow-list", search: queries.SearchUnclaimed().OrderBy("days_held", "DESC; DROP TABLE lost_property")},90
{label: "a direction outside the allow-list", search: queries.SearchUnclaimed().OrderBy("days_held", "DESC; DROP TABLE lost_property")},88
}91
}89
for _, attempt := range attempts {92
for _, attempt := range attempts {90
_, err := attempt.search.All(ctx)93
_, err := attempt.search.All(ctx)91
switch {94
switch {92
case errors.Is(err, store.ErrSglUnknownColumn), errors.Is(err, store.ErrSglUnknownOperator), errors.Is(err, store.ErrSglUnknownDirection):95
case errors.Is(err, store.ErrSglUnknownColumn), errors.Is(err, store.ErrSglUnknownOperator), errors.Is(err, store.ErrSglUnknownDirection):93
fmt.Fprintf(output, "refused %s: %v\n", attempt.label, err)96
fmt.Fprintf(output, "refused %s: %v\n", attempt.label, err)94
case err == nil:97
case err == nil:95
return fmt.Errorf("%s: got no error, want a refusal", attempt.label)98
return fmt.Errorf("%s: got no error, want a refusal", attempt.label)96
default:99
default:97
return fmt.Errorf("%s: got %w, want a refusal", attempt.label, err)100
return fmt.Errorf("%s: got %w, want a refusal", attempt.label, err)98
}101
}99
}102
}100
return nil103
return nil101
}104
}102
105
103
// printItems writes one line per item.106
// printItems writes one line per item.104
//107
//105
// Takes output (io.Writer) which receives the lines.108
// Takes output (io.Writer) which receives the lines.106
// Takes items ([]store.SearchUnclaimedRow) which are the items to print.109
// Takes items ([]store.SearchUnclaimedRow) which are the items to print.107
func printItems(output io.Writer, items []store.SearchUnclaimedRow) {110
func printItems(output io.Writer, items []store.SearchUnclaimedRow) {108
for _, item := range items {111
for _, item := range items {109
fmt.Fprintf(output, " #%d %s %s, found at %s, held %d days\n", item.ID, item.Colour, item.Item, item.FoundAt, item.DaysHeld)112
fmt.Fprintf(output, " #%d %s %s, found at %s, held %d days\n", item.ID, item.Colour, item.Item, item.FoundAt, item.DaysHeld)110
}113
}111
}114
}Go type differences
The same SQL types map to different Go types, because each database reports them differently.
| Query | Field | MySQL | ClickHouse |
|---|---|---|---|
| HandIn | parameter days_held | int32 | uint32 |
| Claim | parameter id | int64 | uint64 |
| SearchUnclaimed | column id | int64 | uint64 |
| SearchUnclaimed | column days_held | int32 | uint32 |