derived table and row number addition

This commit is contained in:
2025-10-21 00:27:00 +05:30
parent 12d6fface6
commit 9837fb1e37
6 changed files with 112 additions and 7 deletions

11
playground/db/derived.go Normal file
View File

@@ -0,0 +1,11 @@
package db
import "code.patial.tech/go/pgm"
func DerivedTable(tblName string, fromQry pgm.Query) pgm.Table {
t := pgm.Table{
Name: tblName,
DerivedTable: fromQry,
}
return t
}

View File

@@ -60,6 +60,27 @@ func TestSelectWithHaving(t *testing.T) {
}
}
func TestSelectDerived(t *testing.T) {
expected := "SELECT t.* FROM (SELECT users.*, ROW_NUMBER() OVER (PARTITION BY users.status_id ORDER BY users.created_at DESC) AS rn" +
" FROM users WHERE users.status_id = $1) AS t WHERE t.rn <= $2" +
" ORDER BY t.status_id, t.created_at DESC"
qry := db.User.
Select(user.All, user.CreatedAt.RowNumberDescPartionBy(user.StatusID, "rn")).
Where(user.StatusID.Eq(1))
tbl := db.DerivedTable("t", qry)
got := tbl.
Select(tbl.Field("*")).
Where(tbl.Field("rn").Lte(5)).
OrderBy(tbl.Field("status_id"), tbl.Field("created_at").Desc()).
String()
if expected != got {
t.Errorf("\nexpected: %q\n\ngot: %q", expected, got)
}
}
func TestSelectWithJoin(t *testing.T) {
got := db.User.Select(user.Email, user.FirstName).
Join(db.UserSession, user.ID, usersession.UserID).