Skip to content

Commit

Permalink
Add support for WITH query (ContentSquare#108)
Browse files Browse the repository at this point in the history
* allow caching for queries starting with `WITH` statement
  • Loading branch information
gontarzpawel authored Feb 23, 2021
1 parent 2e8c798 commit 7cabf6e
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 5 deletions.
18 changes: 13 additions & 5 deletions utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -140,16 +140,24 @@ func getFullQueryFromBody(req *http.Request) ([]byte, error) {
return b, nil
}

var cachableStatements = []string{"SELECT", "WITH"}

// canCacheQuery returns true if q can be cached.
func canCacheQuery(q []byte) bool {
q = skipLeadingComments(q)

// Currently only SELECT queries may be cached.
if len(q) < len("SELECT") {
return false
for _, statement := range cachableStatements {
if len(q) < len(statement) {
continue
}

l := bytes.ToUpper(q[:len(statement)])
if bytes.HasPrefix(l, []byte(statement)) {
return true
}
}
q = bytes.ToUpper(q[:len("SELECT")])
return bytes.HasPrefix(q, []byte("SELECT"))

return false
}

func skipLeadingComments(q []byte) []byte {
Expand Down
1 change: 1 addition & 0 deletions utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ func TestCanCacheQuery(t *testing.T) {
testCanCacheQuery(t, "\t\t sElECt 123 ", true)
testCanCacheQuery(t, " --- sd s\n /* dfsf */\n seleCT ", true)
testCanCacheQuery(t, " --- sd s\n /* dfsf */\n insert ", false)
testCanCacheQuery(t, "WITH 1 as alias SELECT alias FROM nothing ", true)
}

func testCanCacheQuery(t *testing.T, q string, expected bool) {
Expand Down

0 comments on commit 7cabf6e

Please sign in to comment.