Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgresql Parameter Issue $1

I am working on setting up a database, building a custom Upsert as Postgresql apparently doesn't have that yet. Anyway my parameters aren't playing nicely.

I am using Martini.

This code:

func CreateBook(ren render.Render, r *http.Request, db *sql.DB) {
    _, err := db.Query("INSERT INTO books (title, first, last, class) SELECT $1, $2, $3, $4 WHERE NOT EXISTS (SELECT * FROM books WHERE title = $1)",
    r.FormValue("title"),
    r.FormValue("first"),
    r.FormValue("last"),
    r.FormValue("class"))

    PanicIf(err)

Throws this error:

pq: inconsistent types deduced for parameter $1

I am fairly certain it's some kind of typecasting issue with the second $1 but none of the rational solutions seem to make sense.

Its a stupid question with hopefully an easy answer but I haven't been able to find any answers anywhere else.

like image 544
Sam Avatar asked Jul 30 '15 20:07

Sam


People also ask

What does $1 mean in Postgres?

Arguments to the SQL function are referenced in the function body using the syntax $n: $1 refers to the first argument, $2 to the second, and so on. If an argument is of a composite type, then the dot notation, e.g., $1.name, can be used to access attributes of the argument.

What does <> mean in PostgreSQL?

<> is the standard SQL operator meaning "not equal". Many databases, including postgresql, supports != as a synonym for <> . They're exactly the same in postgresql.

How do you change parameters in PostgreSQL?

Starting wiht PostgreSQL 9.4 you can change parameters in postgresql. conf with the “alter system” command in psql. In principle every parameter can be changed that way but not every parameter is applied immediately. Some of the parameters require a reload others require a complete restart of the instance.

What is the limit for in clause in PostgreSQL?

At least I can tell there is a technical limit of 32767 values (=Short. MAX_VALUE) passable to the PostgreSQL backend, using Posgresql's JDBC driver 9.1. Show activity on this post.


1 Answers

It is hard to tell exactly what is going on as the database structure is not known. But trying this query in the sqlfiddle shows the following:

create table books (
  id serial,
  title varchar
);

PREPARE booksplan AS
  INSERT INTO books (title)
  SELECT $1 WHERE NOT EXISTS (SELECT * FROM books WHERE title = $1);

>> ERROR:  inconsistent types deduced for parameter $1
>> Detail: text versus character varying Position: 59

So I suspect that when the $1 is used for the first time, the text is deduced but the varchar is deduced for the second $1 (as it compared with title, which is varchar).

As workaround you can probably try

_, err := db.Query(`INSERT INTO books (title, first, last, class)
    SELECT CAST($1 AS VARCHAR), $2, $3, $4
    WHERE NOT EXISTS (SELECT 1 FROM books WHERE title = $1)`,
like image 70
Alex Netkachov Avatar answered Oct 05 '22 14:10

Alex Netkachov