Skip to content

Commit e67bef2

Browse files
dialect/sql: added support for ydb create view queries (#5)
1 parent db0e2b0 commit e67bef2

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

dialect/sql/builder.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,12 @@ func (v *ViewBuilder) Query() (string, []any) {
131131
if len(v.columns) > 0 {
132132
v.Pad().Wrap(func(b *Builder) { b.JoinComma(v.columns...) })
133133
}
134+
135+
// YDB-specific: WITH (security_invoker = TRUE) is mandatory
136+
if v.ydb() {
137+
v.WriteString(" WITH (security_invoker = TRUE)")
138+
}
139+
134140
v.WriteString(" AS ")
135141
v.Join(v.as)
136142
return v.String(), v.args

dialect/sql/builder_test.go

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2336,6 +2336,34 @@ func TestSelector_VIEW_SecondaryIndex_YDB(t *testing.T) {
23362336
})
23372337
}
23382338

2339+
func TestCreateView_YDB(t *testing.T) {
2340+
t.Run("Basic view with security_invoker", func(t *testing.T) {
2341+
d := Dialect(dialect.YDB)
2342+
query, args := d.CreateView("recent_series").
2343+
As(
2344+
d.Select("*").
2345+
From(Table("db")).
2346+
Where(GT("release_date", "2020-01-01")),
2347+
).
2348+
Query()
2349+
2350+
require.Contains(t, query, "CREATE VIEW `recent_series` WITH (security_invoker = TRUE) AS SELECT * FROM `db`")
2351+
require.Contains(t, query, "WHERE `release_date` > $p0")
2352+
require.Equal(t, []any{driver.NamedValue{Name: "p0", Value: "2020-01-01"}}, args)
2353+
})
2354+
2355+
t.Run("Non-YDB dialect should not generate WITH clause", func(t *testing.T) {
2356+
query, _ := Dialect(dialect.Postgres).
2357+
CreateView("my_view").
2358+
As(Select("*").From(Table("users"))).
2359+
Query()
2360+
2361+
// Postgres should not have the WITH clause
2362+
require.NotContains(t, query, "WITH (security_invoker")
2363+
require.Contains(t, query, `CREATE VIEW "my_view" AS SELECT * FROM "users"`)
2364+
})
2365+
}
2366+
23392367
func TestSelector_SetOperatorWithRecursive(t *testing.T) {
23402368
t1, t2, t3 := Table("files"), Table("files"), Table("path")
23412369
n := Queries{

0 commit comments

Comments
 (0)