-
Notifications
You must be signed in to change notification settings - Fork 123
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #157 from huandu/feature/cte
Support CTE (Common Table Expression)
- Loading branch information
Showing
8 changed files
with
330 additions
and
10 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,99 @@ | ||
// Copyright 2024 Huan Du. All rights reserved. | ||
// Licensed under the MIT license that can be found in the LICENSE file. | ||
|
||
package sqlbuilder | ||
|
||
const ( | ||
cteMarkerInit injectionMarker = iota | ||
cteMarkerAfterWith | ||
) | ||
|
||
// With creates a new CTE builder with default flavor. | ||
func With(tables ...*CTETableBuilder) *CTEBuilder { | ||
return DefaultFlavor.NewCTEBuilder().With(tables...) | ||
} | ||
|
||
func newCTEBuilder() *CTEBuilder { | ||
return &CTEBuilder{ | ||
args: &Args{}, | ||
injection: newInjection(), | ||
} | ||
} | ||
|
||
// CTEBuilder is a CTE (Common Table Expression) builder. | ||
type CTEBuilder struct { | ||
tableNames []string | ||
tableBuilderVars []string | ||
|
||
args *Args | ||
|
||
injection *injection | ||
marker injectionMarker | ||
} | ||
|
||
var _ Builder = new(CTEBuilder) | ||
|
||
// With sets the CTE name and columns. | ||
func (cteb *CTEBuilder) With(tables ...*CTETableBuilder) *CTEBuilder { | ||
tableNames := make([]string, 0, len(tables)) | ||
tableBuilderVars := make([]string, 0, len(tables)) | ||
|
||
for _, table := range tables { | ||
tableNames = append(tableNames, table.TableName()) | ||
tableBuilderVars = append(tableBuilderVars, cteb.args.Add(table)) | ||
} | ||
|
||
cteb.tableNames = tableNames | ||
cteb.tableBuilderVars = tableBuilderVars | ||
cteb.marker = cteMarkerAfterWith | ||
return cteb | ||
} | ||
|
||
// Select creates a new SelectBuilder to build a SELECT statement using this CTE. | ||
func (cteb *CTEBuilder) Select(col ...string) *SelectBuilder { | ||
sb := cteb.args.Flavor.NewSelectBuilder() | ||
return sb.With(cteb).Select(col...) | ||
} | ||
|
||
// String returns the compiled CTE string. | ||
func (cteb *CTEBuilder) String() string { | ||
sql, _ := cteb.Build() | ||
return sql | ||
} | ||
|
||
// Build returns compiled CTE string and args. | ||
func (cteb *CTEBuilder) Build() (sql string, args []interface{}) { | ||
return cteb.BuildWithFlavor(cteb.args.Flavor) | ||
} | ||
|
||
// BuildWithFlavor builds a CTE with the specified flavor and initial arguments. | ||
func (cteb *CTEBuilder) BuildWithFlavor(flavor Flavor, initialArg ...interface{}) (sql string, args []interface{}) { | ||
buf := newStringBuilder() | ||
cteb.injection.WriteTo(buf, cteMarkerInit) | ||
|
||
if len(cteb.tableBuilderVars) > 0 { | ||
buf.WriteLeadingString("WITH ") | ||
buf.WriteStrings(cteb.tableBuilderVars, ", ") | ||
} | ||
|
||
cteb.injection.WriteTo(buf, cteMarkerAfterWith) | ||
return cteb.args.CompileWithFlavor(buf.String(), flavor, initialArg...) | ||
} | ||
|
||
// SetFlavor sets the flavor of compiled sql. | ||
func (cteb *CTEBuilder) SetFlavor(flavor Flavor) (old Flavor) { | ||
old = cteb.args.Flavor | ||
cteb.args.Flavor = flavor | ||
return | ||
} | ||
|
||
// SQL adds an arbitrary sql to current position. | ||
func (cteb *CTEBuilder) SQL(sql string) *CTEBuilder { | ||
cteb.injection.SQL(cteb.marker, sql) | ||
return cteb | ||
} | ||
|
||
// TableNames returns all table names in a CTE. | ||
func (cteb *CTEBuilder) TableNames() []string { | ||
return cteb.tableNames | ||
} |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,81 @@ | ||
// Copyright 2024 Huan Du. All rights reserved. | ||
// Licensed under the MIT license that can be found in the LICENSE file. | ||
|
||
package sqlbuilder | ||
|
||
import ( | ||
"fmt" | ||
"testing" | ||
|
||
"github.com/huandu/go-assert" | ||
) | ||
|
||
func ExampleWith() { | ||
sb := With( | ||
CTETable("users", "id", "name").As( | ||
Select("id", "name").From("users").Where("name IS NOT NULL"), | ||
), | ||
CTETable("devices").As( | ||
Select("device_id").From("devices"), | ||
), | ||
).Select("users.id", "orders.id", "devices.device_id").Join( | ||
"orders", | ||
"users.id = orders.user_id", | ||
"devices.device_id = orders.device_id", | ||
) | ||
|
||
fmt.Println(sb) | ||
|
||
// Output: | ||
// WITH users (id, name) AS (SELECT id, name FROM users WHERE name IS NOT NULL), devices AS (SELECT device_id FROM devices) SELECT users.id, orders.id, devices.device_id FROM users, devices JOIN orders ON users.id = orders.user_id AND devices.device_id = orders.device_id | ||
} | ||
|
||
func ExampleCTEBuilder() { | ||
usersBuilder := Select("id", "name", "level").From("users") | ||
usersBuilder.Where( | ||
usersBuilder.GreaterEqualThan("level", 10), | ||
) | ||
cteb := With( | ||
CTETable("valid_users").As(usersBuilder), | ||
) | ||
fmt.Println(cteb) | ||
|
||
sb := Select("valid_users.id", "valid_users.name", "orders.id").With(cteb) | ||
sb.Join("orders", "valid_users.id = orders.user_id") | ||
sb.Where( | ||
sb.LessEqualThan("orders.price", 200), | ||
"valid_users.level < orders.min_level", | ||
).OrderBy("orders.price").Desc() | ||
|
||
sql, args := sb.Build() | ||
fmt.Println(sql) | ||
fmt.Println(args) | ||
|
||
// Output: | ||
// WITH valid_users AS (SELECT id, name, level FROM users WHERE level >= ?) | ||
// WITH valid_users AS (SELECT id, name, level FROM users WHERE level >= ?) SELECT valid_users.id, valid_users.name, orders.id FROM valid_users JOIN orders ON valid_users.id = orders.user_id WHERE orders.price <= ? AND valid_users.level < orders.min_level ORDER BY orders.price DESC | ||
// [10 200] | ||
} | ||
|
||
func TestCTEBuilder(t *testing.T) { | ||
a := assert.New(t) | ||
cteb := newCTEBuilder() | ||
ctetb := newCTETableBuilder() | ||
cteb.SQL("/* init */") | ||
cteb.With(ctetb) | ||
cteb.SQL("/* after with */") | ||
|
||
ctetb.SQL("/* table init */") | ||
ctetb.Table("t", "a", "b") | ||
ctetb.SQL("/* after table */") | ||
|
||
ctetb.As(Select("a", "b").From("t")) | ||
ctetb.SQL("/* after table as */") | ||
|
||
sql, args := cteb.Build() | ||
a.Equal(sql, "/* init */ WITH /* table init */ t (a, b) /* after table */ AS (SELECT a, b FROM t) /* after table as */ /* after with */") | ||
a.Assert(args == nil) | ||
|
||
sql = ctetb.String() | ||
a.Equal(sql, "/* table init */ t (a, b) /* after table */ AS (SELECT a, b FROM t) /* after table as */") | ||
} |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,106 @@ | ||
// Copyright 2024 Huan Du. All rights reserved. | ||
// Licensed under the MIT license that can be found in the LICENSE file. | ||
|
||
package sqlbuilder | ||
|
||
const ( | ||
cteTableMarkerInit injectionMarker = iota | ||
cteTableMarkerAfterTable | ||
cteTableMarkerAfterAs | ||
) | ||
|
||
// CTETable creates a new CTE table builder with default flavor. | ||
func CTETable(name string, cols ...string) *CTETableBuilder { | ||
return DefaultFlavor.NewCTETableBuilder().Table(name, cols...) | ||
} | ||
|
||
func newCTETableBuilder() *CTETableBuilder { | ||
return &CTETableBuilder{ | ||
args: &Args{}, | ||
injection: newInjection(), | ||
} | ||
} | ||
|
||
// CTETableBuilder is a builder to build one table in CTE (Common Table Expression). | ||
type CTETableBuilder struct { | ||
name string | ||
cols []string | ||
builderVar string | ||
|
||
args *Args | ||
|
||
injection *injection | ||
marker injectionMarker | ||
} | ||
|
||
// Table sets the table name and columns in a CTE table. | ||
func (ctetb *CTETableBuilder) Table(name string, cols ...string) *CTETableBuilder { | ||
ctetb.name = name | ||
ctetb.cols = cols | ||
ctetb.marker = cteTableMarkerAfterTable | ||
return ctetb | ||
} | ||
|
||
// As sets the builder to select data. | ||
func (ctetb *CTETableBuilder) As(builder Builder) *CTETableBuilder { | ||
ctetb.builderVar = ctetb.args.Add(builder) | ||
ctetb.marker = cteTableMarkerAfterAs | ||
return ctetb | ||
} | ||
|
||
// String returns the compiled CTE string. | ||
func (ctetb *CTETableBuilder) String() string { | ||
sql, _ := ctetb.Build() | ||
return sql | ||
} | ||
|
||
// Build returns compiled CTE string and args. | ||
func (ctetb *CTETableBuilder) Build() (sql string, args []interface{}) { | ||
return ctetb.BuildWithFlavor(ctetb.args.Flavor) | ||
} | ||
|
||
// BuildWithFlavor builds a CTE with the specified flavor and initial arguments. | ||
func (ctetb *CTETableBuilder) BuildWithFlavor(flavor Flavor, initialArg ...interface{}) (sql string, args []interface{}) { | ||
buf := newStringBuilder() | ||
ctetb.injection.WriteTo(buf, cteTableMarkerInit) | ||
|
||
if ctetb.name != "" { | ||
buf.WriteLeadingString(ctetb.name) | ||
|
||
if len(ctetb.cols) > 0 { | ||
buf.WriteLeadingString("(") | ||
buf.WriteStrings(ctetb.cols, ", ") | ||
buf.WriteString(")") | ||
} | ||
|
||
ctetb.injection.WriteTo(buf, cteTableMarkerAfterTable) | ||
} | ||
|
||
if ctetb.builderVar != "" { | ||
buf.WriteLeadingString("AS (") | ||
buf.WriteString(ctetb.builderVar) | ||
buf.WriteRune(')') | ||
|
||
ctetb.injection.WriteTo(buf, cteTableMarkerAfterAs) | ||
} | ||
|
||
return ctetb.args.CompileWithFlavor(buf.String(), flavor, initialArg...) | ||
} | ||
|
||
// SetFlavor sets the flavor of compiled sql. | ||
func (ctetb *CTETableBuilder) SetFlavor(flavor Flavor) (old Flavor) { | ||
old = ctetb.args.Flavor | ||
ctetb.args.Flavor = flavor | ||
return | ||
} | ||
|
||
// SQL adds an arbitrary sql to current position. | ||
func (ctetb *CTETableBuilder) SQL(sql string) *CTETableBuilder { | ||
ctetb.injection.SQL(ctetb.marker, sql) | ||
return ctetb | ||
} | ||
|
||
// TableName returns the CTE table name. | ||
func (ctetb *CTETableBuilder) TableName() string { | ||
return ctetb.name | ||
} |
This file contains 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
This file contains 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
This file contains 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
Oops, something went wrong.