Skip to content

sqlx.compileNamedQuery() malforms queries with Postgres-style typecasts #650

Open

Description

@zrhoffman

Suppose you have a table named my_table created using

CREATE TABLE my_table (
    id bigint,
    name text NOT NULL
);

Typecasting to a record type using a Postgres typecast yields a syntax error:

package main

import "github.com/jmoiron/sqlx"
import _ "github.com/lib/pq"

func main() {
	db, err := sqlx.Open("postgres", "postgres://username:password@localhost/dbname")
	if err != nil {
		panic(err)
	}
	rows, err := db.NamedQuery(`SELECT (1, 'John')::my_table`, make(map[string]interface{}))
	if err != nil {
		panic(err)
	}
	defer rows.Close()
}

Error received:

err = {error | *github.com/lib/pq.Error} 
 Severity = {string} "ERROR"
 Code = {github.com/lib/pq.ErrorCode} "42601"
 Message = {string} "syntax error at or near ":""
 Detail = {string} ""
 Hint = {string} ""
 Position = {string} "19"
 InternalPosition = {string} ""
 InternalQuery = {string} ""
 Where = {string} ""
 Schema = {string} ""
 Table = {string} ""
 Column = {string} ""
 DataTypeName = {string} ""
 Constraint = {string} ""
 File = {string} "scan.l"
 Line = {string} "1123"
 Routine = {string} "scanner_yyerror"

The query returned by sqlx.compileNamedQuery() is missing a colon:

SELECT (1, 'John'):my_table

The same query using CAST() instead of :: succeeds:

SELECT CAST((1, 'John') AS my_table)

Activity

  1. ptman commented on Sep 22, 2020

    @ptman

    I just ran into the exact same problem with something like WHERE foo=:foo AND NOW() < (bar - '5 minutes'::interval)

  2. nikk-gr commented on Sep 12, 2024

    @nikk-gr

    same problem

  3. nicolabovolato commented on Oct 4, 2024

    @nicolabovolato

    Same issue here!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions