Add WITH RECURSIVE support.

This commit is contained in:
go-jet 2021-12-14 17:14:13 +01:00
parent 02123005c1
commit 47545ce571
5 changed files with 289 additions and 5 deletions

View file

@ -1,9 +1,10 @@
package jet package jet
// WITH function creates new with statement from list of common table expressions for specified dialect // WITH function creates new with statement from list of common table expressions for specified dialect
func WITH(dialect Dialect, cte ...CommonTableExpressionDefinition) func(statement Statement) Statement { func WITH(dialect Dialect, recursive bool, cte ...CommonTableExpressionDefinition) func(statement Statement) Statement {
newWithImpl := &withImpl{ newWithImpl := &withImpl{
ctes: cte, recursive: recursive,
ctes: cte,
serializerStatementInterfaceImpl: serializerStatementInterfaceImpl{ serializerStatementInterfaceImpl: serializerStatementInterfaceImpl{
dialect: dialect, dialect: dialect,
statementType: WithStatementType, statementType: WithStatementType,
@ -23,6 +24,7 @@ func WITH(dialect Dialect, cte ...CommonTableExpressionDefinition) func(statemen
type withImpl struct { type withImpl struct {
serializerStatementInterfaceImpl serializerStatementInterfaceImpl
recursive bool
ctes []CommonTableExpressionDefinition ctes []CommonTableExpressionDefinition
primaryStatement SerializerStatement primaryStatement SerializerStatement
} }
@ -31,6 +33,10 @@ func (w withImpl) serialize(statement StatementType, out *SQLBuilder, options ..
out.NewLine() out.NewLine()
out.WriteString("WITH") out.WriteString("WITH")
if w.recursive {
out.WriteString("RECURSIVE")
}
for i, cte := range w.ctes { for i, cte := range w.ctes {
if i > 0 { if i > 0 {
out.WriteString(",") out.WriteString(",")

View file

@ -10,7 +10,12 @@ type CommonTableExpression struct {
// WITH function creates new WITH statement from list of common table expressions // WITH function creates new WITH statement from list of common table expressions
func WITH(cte ...jet.CommonTableExpressionDefinition) func(statement jet.Statement) Statement { func WITH(cte ...jet.CommonTableExpressionDefinition) func(statement jet.Statement) Statement {
return jet.WITH(Dialect, cte...) return jet.WITH(Dialect, false, cte...)
}
// WITH_RECURSIVE function creates new WITH RECURSIVE statement from list of common table expressions
func WITH_RECURSIVE(cte ...jet.CommonTableExpressionDefinition) func(statement jet.Statement) Statement {
return jet.WITH(Dialect, true, cte...)
} }
// CTE creates new named CommonTableExpression // CTE creates new named CommonTableExpression

View file

@ -10,7 +10,12 @@ type CommonTableExpression struct {
// WITH function creates new WITH statement from list of common table expressions // WITH function creates new WITH statement from list of common table expressions
func WITH(cte ...jet.CommonTableExpressionDefinition) func(statement jet.Statement) Statement { func WITH(cte ...jet.CommonTableExpressionDefinition) func(statement jet.Statement) Statement {
return jet.WITH(Dialect, cte...) return jet.WITH(Dialect, false, cte...)
}
// WITH_RECURSIVE function creates new WITH RECURSIVE statement from list of common table expressions
func WITH_RECURSIVE(cte ...jet.CommonTableExpressionDefinition) func(statement jet.Statement) Statement {
return jet.WITH(Dialect, true, cte...)
} }
// CTE creates new named CommonTableExpression // CTE creates new named CommonTableExpression

View file

@ -10,7 +10,12 @@ type CommonTableExpression struct {
// WITH function creates new WITH statement from list of common table expressions // WITH function creates new WITH statement from list of common table expressions
func WITH(cte ...jet.CommonTableExpressionDefinition) func(statement jet.Statement) Statement { func WITH(cte ...jet.CommonTableExpressionDefinition) func(statement jet.Statement) Statement {
return jet.WITH(Dialect, cte...) return jet.WITH(Dialect, false, cte...)
}
// WITH_RECURSIVE function creates new WITH RECURSIVE statement from list of common table expressions
func WITH_RECURSIVE(cte ...jet.CommonTableExpressionDefinition) func(statement jet.Statement) Statement {
return jet.WITH(Dialect, true, cte...)
} }
// CTE creates new named CommonTableExpression // CTE creates new named CommonTableExpression

View file

@ -1,6 +1,7 @@
package postgres package postgres
import ( import (
"context"
"github.com/go-jet/jet/v2/internal/testutils" "github.com/go-jet/jet/v2/internal/testutils"
. "github.com/go-jet/jet/v2/postgres" . "github.com/go-jet/jet/v2/postgres"
"github.com/go-jet/jet/v2/tests/.gentestdata/jetdb/northwind/model" "github.com/go-jet/jet/v2/tests/.gentestdata/jetdb/northwind/model"
@ -219,3 +220,265 @@ FROM log_discontinued;
require.NoError(t, err) require.NoError(t, err)
} }
type EmployeeWrap struct {
model.Employees
Subordinates []*EmployeeWrap
}
func TestWithRecursive(t *testing.T) {
subordinates := CTE("subordinates")
stmt := WITH_RECURSIVE(
subordinates.AS(
SELECT(
Employees.AllColumns,
).FROM(
Employees,
).WHERE(
Employees.EmployeeID.EQ(Int(2)),
).UNION(
SELECT(
Employees.AllColumns,
).FROM(
Employees.
INNER_JOIN(subordinates, Employees.EmployeeID.From(subordinates).EQ(Employees.ReportsTo)),
),
),
),
)(
SELECT(
subordinates.AllColumns(),
).FROM(
subordinates,
),
)
type employeeID = int16
employeeMap := make(map[employeeID]*EmployeeWrap)
rows, err := stmt.Rows(context.Background(), db)
require.NoError(t, err)
var result *EmployeeWrap
for rows.Next() {
var employeeModel model.Employees
err := rows.Scan(&employeeModel)
require.NoError(t, err)
newEmployeeWrap := &EmployeeWrap{
Employees: employeeModel,
}
employeeMap[employeeModel.EmployeeID] = newEmployeeWrap
if employeeModel.ReportsTo == nil { // top manager(always first row in the result)
result = newEmployeeWrap
continue
}
if employee, ok := employeeMap[*employeeModel.ReportsTo]; ok {
employee.Subordinates = append(employee.Subordinates, newEmployeeWrap)
}
}
require.NoError(t, rows.Err())
require.NoError(t, rows.Close())
testutils.AssertJSON(t, *result, `
{
"EmployeeID": 2,
"LastName": "Fuller",
"FirstName": "Andrew",
"Title": "Vice President, Sales",
"TitleOfCourtesy": "Dr.",
"BirthDate": "1952-02-19T00:00:00Z",
"HireDate": "1992-08-14T00:00:00Z",
"Address": "908 W. Capital Way",
"City": "Tacoma",
"Region": "WA",
"PostalCode": "98401",
"Country": "USA",
"HomePhone": "(206) 555-9482",
"Extension": "3457",
"Photo": "",
"Notes": "Andrew received his BTS commercial in 1974 and a Ph.D. in international marketing from the University of Dallas in 1981. He is fluent in French and Italian and reads German. He joined the company as a sales representative, was promoted to sales manager in January 1992 and to vice president of sales in March 1993. Andrew is a member of the Sales Management Roundtable, the Seattle Chamber of Commerce, and the Pacific Rim Importers Association.",
"ReportsTo": null,
"PhotoPath": "http://accweb/emmployees/fuller.bmp",
"Subordinates": [
{
"EmployeeID": 1,
"LastName": "Davolio",
"FirstName": "Nancy",
"Title": "Sales Representative",
"TitleOfCourtesy": "Ms.",
"BirthDate": "1948-12-08T00:00:00Z",
"HireDate": "1992-05-01T00:00:00Z",
"Address": "507 - 20th Ave. E.\\nApt. 2A",
"City": "Seattle",
"Region": "WA",
"PostalCode": "98122",
"Country": "USA",
"HomePhone": "(206) 555-9857",
"Extension": "5467",
"Photo": "",
"Notes": "Education includes a BA in psychology from Colorado State University in 1970. She also completed The Art of the Cold Call. Nancy is a member of Toastmasters International.",
"ReportsTo": 2,
"PhotoPath": "http://accweb/emmployees/davolio.bmp",
"Subordinates": null
},
{
"EmployeeID": 3,
"LastName": "Leverling",
"FirstName": "Janet",
"Title": "Sales Representative",
"TitleOfCourtesy": "Ms.",
"BirthDate": "1963-08-30T00:00:00Z",
"HireDate": "1992-04-01T00:00:00Z",
"Address": "722 Moss Bay Blvd.",
"City": "Kirkland",
"Region": "WA",
"PostalCode": "98033",
"Country": "USA",
"HomePhone": "(206) 555-3412",
"Extension": "3355",
"Photo": "",
"Notes": "Janet has a BS degree in chemistry from Boston College (1984). She has also completed a certificate program in food retailing management. Janet was hired as a sales associate in 1991 and promoted to sales representative in February 1992.",
"ReportsTo": 2,
"PhotoPath": "http://accweb/emmployees/leverling.bmp",
"Subordinates": null
},
{
"EmployeeID": 4,
"LastName": "Peacock",
"FirstName": "Margaret",
"Title": "Sales Representative",
"TitleOfCourtesy": "Mrs.",
"BirthDate": "1937-09-19T00:00:00Z",
"HireDate": "1993-05-03T00:00:00Z",
"Address": "4110 Old Redmond Rd.",
"City": "Redmond",
"Region": "WA",
"PostalCode": "98052",
"Country": "USA",
"HomePhone": "(206) 555-8122",
"Extension": "5176",
"Photo": "",
"Notes": "Margaret holds a BA in English literature from Concordia College (1958) and an MA from the American Institute of Culinary Arts (1966). She was assigned to the London office temporarily from July through November 1992.",
"ReportsTo": 2,
"PhotoPath": "http://accweb/emmployees/peacock.bmp",
"Subordinates": null
},
{
"EmployeeID": 5,
"LastName": "Buchanan",
"FirstName": "Steven",
"Title": "Sales Manager",
"TitleOfCourtesy": "Mr.",
"BirthDate": "1955-03-04T00:00:00Z",
"HireDate": "1993-10-17T00:00:00Z",
"Address": "14 Garrett Hill",
"City": "London",
"Region": null,
"PostalCode": "SW1 8JR",
"Country": "UK",
"HomePhone": "(71) 555-4848",
"Extension": "3453",
"Photo": "",
"Notes": "Steven Buchanan graduated from St. Andrews University, Scotland, with a BSC degree in 1976. Upon joining the company as a sales representative in 1992, he spent 6 months in an orientation program at the Seattle office and then returned to his permanent post in London. He was promoted to sales manager in March 1993. Mr. Buchanan has completed the courses Successful Telemarketing and International Sales Management. He is fluent in French.",
"ReportsTo": 2,
"PhotoPath": "http://accweb/emmployees/buchanan.bmp",
"Subordinates": [
{
"EmployeeID": 6,
"LastName": "Suyama",
"FirstName": "Michael",
"Title": "Sales Representative",
"TitleOfCourtesy": "Mr.",
"BirthDate": "1963-07-02T00:00:00Z",
"HireDate": "1993-10-17T00:00:00Z",
"Address": "Coventry House\\nMiner Rd.",
"City": "London",
"Region": null,
"PostalCode": "EC2 7JR",
"Country": "UK",
"HomePhone": "(71) 555-7773",
"Extension": "428",
"Photo": "",
"Notes": "Michael is a graduate of Sussex University (MA, economics, 1983) and the University of California at Los Angeles (MBA, marketing, 1986). He has also taken the courses Multi-Cultural Selling and Time Management for the Sales Professional. He is fluent in Japanese and can read and write French, Portuguese, and Spanish.",
"ReportsTo": 5,
"PhotoPath": "http://accweb/emmployees/davolio.bmp",
"Subordinates": null
},
{
"EmployeeID": 7,
"LastName": "King",
"FirstName": "Robert",
"Title": "Sales Representative",
"TitleOfCourtesy": "Mr.",
"BirthDate": "1960-05-29T00:00:00Z",
"HireDate": "1994-01-02T00:00:00Z",
"Address": "Edgeham Hollow\\nWinchester Way",
"City": "London",
"Region": null,
"PostalCode": "RG1 9SP",
"Country": "UK",
"HomePhone": "(71) 555-5598",
"Extension": "465",
"Photo": "",
"Notes": "Robert King served in the Peace Corps and traveled extensively before completing his degree in English at the University of Michigan in 1992, the year he joined the company. After completing a course entitled Selling in Europe, he was transferred to the London office in March 1993.",
"ReportsTo": 5,
"PhotoPath": "http://accweb/emmployees/davolio.bmp",
"Subordinates": null
},
{
"EmployeeID": 9,
"LastName": "Dodsworth",
"FirstName": "Anne",
"Title": "Sales Representative",
"TitleOfCourtesy": "Ms.",
"BirthDate": "1966-01-27T00:00:00Z",
"HireDate": "1994-11-15T00:00:00Z",
"Address": "7 Houndstooth Rd.",
"City": "London",
"Region": null,
"PostalCode": "WG2 7LT",
"Country": "UK",
"HomePhone": "(71) 555-4444",
"Extension": "452",
"Photo": "",
"Notes": "Anne has a BA degree in English from St. Lawrence College. She is fluent in French and German.",
"ReportsTo": 5,
"PhotoPath": "http://accweb/emmployees/davolio.bmp",
"Subordinates": null
}
]
},
{
"EmployeeID": 8,
"LastName": "Callahan",
"FirstName": "Laura",
"Title": "Inside Sales Coordinator",
"TitleOfCourtesy": "Ms.",
"BirthDate": "1958-01-09T00:00:00Z",
"HireDate": "1994-03-05T00:00:00Z",
"Address": "4726 - 11th Ave. N.E.",
"City": "Seattle",
"Region": "WA",
"PostalCode": "98105",
"Country": "USA",
"HomePhone": "(206) 555-1189",
"Extension": "2344",
"Photo": "",
"Notes": "Laura received a BA in psychology from the University of Washington. She has also completed a course in business French. She reads and writes French.",
"ReportsTo": 2,
"PhotoPath": "http://accweb/emmployees/davolio.bmp",
"Subordinates": null
}
]
}
`)
}