Golang pq: syntax error when executing sql
Asked Answered
B

1

16

Using revel, golang 1.1.2, gorp, postgres 9.3.2 on heroku

Following robfig's List booking example

func (c App) ViewPosts(page int) revel.Result {
    if page == 0 {
        page = 1
    }
    var posts []*models.Post
    size := 10
    posts = loadPosts(c.Txn.Select(models.Post{},
        `select * from posts offset ? limit ?`, (page-1)*size, size)) // error here
    return c.RenderJson(posts)
}

Not sure why I'm getting pq: syntax error at or near "limit". I'm assuming the combined query is wrong. Why does the query not end up being something like select * from posts offset 0 limit 10, which I've tested to run on postgres. Where am I messing up?

Blent answered 12/1, 2014 at 10:36 Comment(0)
P
26

I'm not familiar with postgres, but I found this issue. I think you should use it like in the godoc

Example in godoc

age := 21
rows, err := db.Query("SELECT name FROM users WHERE age = $1", age)

(Replace "?" with "$n")

Your code

func (c App) ViewPosts(page int) revel.Result {
if page == 0 {
    page = 1
}
var posts []*models.Post
size := 10
posts = loadPosts(c.Txn.Select(models.Post{},
    `select * from posts offset $1 limit $2`, (page-1)*size, size))
return c.RenderJson(posts)
}
Princely answered 12/1, 2014 at 10:48 Comment(1)
If anyone else stumbles across this, I seen it with Gorm in Golang when using the .Limit(). This was because I had left a ; at the end of my query, so Gorm adding a limit after the fact was problematic.Detour

© 2022 - 2024 — McMap. All rights reserved.