Search code examples
cpostgresqlerror-handlinglibpq

"Relation does not exist" error, only with libpq


I'm trying to run this query to insert new row to Users table from my C code using PQexec() (libpq)

INSERT INTO Users 
VALUES (( 
SELECT MIN(s.id) 
FROM generate_series(1,( 
SELECT GREATEST(MAX(Id) + 1,1) FROM Users 
 )) AS s(id) 
WHERE NOT EXISTS (SELECT 1 FROM Users WHERE Id = s.id)) 
 , 'Tester', 27) 
RETURNING Id;

It performs what i need when i run it in psql terminal, but from C it returns

Error executing query: ERROR:  relation "users" does not exist

I checked connection status and it succeeded, using the same user i connect to from terminal. How come it can't find the users table?

EDIT: adding C-code Connection:

sprintf(connect_param,"host=address dbname=%s user=%s password=%s",
                                                    USERNAME, USERNAME, PASSWORD);
conn = PQconnectdb(connect_param);

Query:

sprintf(cmd, "INSERT INTO Users "
             "VALUES (( "
            "SELECT MIN(s.id) "
            "FROM generate_series(1,( "
            "SELECT GREATEST(MAX(Id) + 1,1) FROM Users "
            " )) AS s(id) "
            "WHERE NOT EXISTS (SELECT 1 FROM Users WHERE Id = s.id)) "
            " , \'%s\', %d) "
            "RETURNING Id;", Name, Age);
res = PQexec(conn,cmd);

Solution

  • I am going for deduction:

     Error executing query: ERROR:  relation "users" does not exist
    

    This kind of error is throw when the databases doesn't find the table(view, or wathelse can pass through a SELECT, he gives the name of "relation") .So your code looks fine, but a sub-set of reasons can be:

    • the table users doesn't exists. Some spelling mistake
    • you perform the query in the wrong database (where this table is not defined)
    • you perform the query in the wrong server (as above)
    • you perform the query in the wrong schema (as above)
    • The string get truncate from the sprintf.

    and similar. The connection works very well since you get an answer from the database