ddbc icon indicating copy to clipboard operation
ddbc copied to clipboard

update query from POD type in pgsql

Open Rogni opened this issue 4 years ago • 3 comments

https://github.com/buggins/ddbc/blob/cb72071bbe0ce089204e40d88ef71b6f605852c3/source/ddbc/pods.d#L1094 how to use update from struct in pgsql ?

struct user {
    size_t id;
    string name;
}

user u;
u.id = 1;
u.name  = "Test";

stmt.update!user(u); generate query UPDATE user SET name="Test" WHERE id=1; and i receive error ERROR: column "Test" does not exist

Rogni avatar Feb 11 '20 12:02 Rogni

The error is weird as there's no column called Test, I suspect it's simply a misleading error and that the cause of the problem is that user is a reserved word that should be surrounded with ".

I tested the SQL with https://www.db-fiddle.com/f/hroWDeZav3cgHSkwV8qUFQ/0

and found that I certainly needed to use double quotes around the tables name:

CREATE TABLE "user" (
  id INT PRIMARY KEY NOT NULL,
  name TEXT NOT NULL
);

INSERT INTO "user" (id, name) VALUES (1, 'Initial Value');

UPDATE "user" SET name='Test' WHERE id=1;

SELECT * FROM "user";

SingingBush avatar Feb 11 '20 13:02 SingingBush

okey. i create test database and run

create table custom_table ( 
    id SERIAL PRIMARY KEY, 
    firstname TEXT,
    lastname TEXT
);

INSERT INTO custom_table(firstname,lastname) VALUES ('TestFirstname','TestLastname');

in main.d

import ddbc;
static import config;
import std.conv: to;


private const string CONNECTION_URL = "postgresql://"~ config.HOST 
                            ~ ":" ~ to!string(config.PORT) ~"/"
                            ~ config.DATABASE ~ "?user="
                            ~ config.USER ~",password="
                            ~ config.PASSWORD ~ ",ssl=true";

struct custom_table
{
    size_t id;
    string firstname;
    string lastname;
}


int main(string args[]) {
    custom_table item;
    item.id = 0;
    item.firstname = "TestFirstname";
    item.lastname = "TestLastname";
    auto connection = createConnection(CONNECTION_URL);
    scope (exit) connection.close();
    auto statement = connection.createStatement();
    scope (exit) statement.close();
    update!custom_table(statement, item);

    return 0;
}

Error:

2020-02-11T17:23:28.993:pgsqlddbc.d:executeUpdate:670 UPDATE custom_table SET firstname="TestFirstname",lastname="TestLastname" WHERE id=0;
ddbc.core.SQLException@../../../.dub/packages/ddbc-0.5.1/ddbc/source/ddbc/drivers/pgsqlddbc.d(676): ERROR:  column "TestFirstname" does not exist
LINE 1: UPDATE custom_table SET firstname="TestFirstname",lastname="...

Rogni avatar Feb 11 '20 14:02 Rogni

why in update query used https://github.com/buggins/ddbc/blob/cb72071bbe0ce089204e40d88ef71b6f605852c3/source/ddbc/pods.d#L1093 ? why not use https://github.com/buggins/ddbc/blob/cb72071bbe0ce089204e40d88ef71b6f605852c3/source/ddbc/pods.d#L1040 ?

Rogni avatar Feb 12 '20 08:02 Rogni