You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: README.md
+20Lines changed: 20 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -203,6 +203,26 @@ fmt.Println(ub)
203
203
// UPDATE users SET level = level + ? WHERE id = ?
204
204
```
205
205
206
+
### Build `UPDATE ... FROM`
207
+
208
+
`UpdateBuilder.From` emits a `FROM` clause for PostgreSQL, SQLite, and SQLServer flavors (it is ignored by other flavors). When a CTE includes tables created with `CTETable`, those table names are emitted before any explicit `From(...)` tables.
209
+
210
+
```go
211
+
ub:=PostgreSQL.NewUpdateBuilder()
212
+
ub.Update("users")
213
+
ub.Set(ub.Assign("name", "Huan Du"))
214
+
ub.From("people")
215
+
ub.Where("users.person_id = people.id")
216
+
217
+
sql, args:= ub.Build()
218
+
fmt.Println(sql)
219
+
fmt.Println(args)
220
+
221
+
// Output:
222
+
// UPDATE users SET name = $1 FROM people WHERE users.person_id = people.id
223
+
// [Huan Du]
224
+
```
225
+
206
226
Refer to the [WhereClause](https://pkg.go.dev/github.com/huandu/go-sqlbuilder#WhereClause) examples to learn its usage.
ub7.Where("user.id IN (SELECT id FROM temp_user)")
358
+
359
+
sql, _=ub7.BuildWithFlavor(PostgreSQL)
360
+
a.Equal("WITH temp_user AS (SELECT id FROM active_users) UPDATE user SET status = $1 FROM temp_user, person WHERE user.id IN (SELECT id FROM temp_user)", sql)
361
+
362
+
// Test with SQLServer Returning
363
+
ub8:=ub.Clone().Returning("id", "name")
364
+
sql, _=ub8.BuildWithFlavor(SQLServer)
365
+
a.Equal("UPDATE user SET name = @p1 OUTPUT INSERTED.id, INSERTED.name FROM person WHERE id = @p2", sql)
366
+
367
+
// Test with SQL injection after WHERE
368
+
ub9:=NewUpdateBuilder()
369
+
ub9.Update("user")
370
+
ub9.Set(ub9.Assign("name", "Test"))
371
+
ub9.From("person")
372
+
ub9.Where("user.id = person.id")
373
+
ub9.SQL("/* comment after where */")
374
+
375
+
sql, _=ub9.BuildWithFlavor(PostgreSQL)
376
+
a.Equal("UPDATE user SET name = $1 FROM person WHERE user.id = person.id /* comment after where */", sql)
0 commit comments