buggins / ddbc

DDBC is DB Connector for D language (similar to JDBC)
78 stars 45 forks source link

update query from POD type in pgsql #88

Open Rogni opened 4 years ago

Rogni commented 4 years ago

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

SingingBush commented 4 years ago

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";
Rogni commented 4 years ago

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 commented 4 years ago

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 ?