lovasoa / SQLpage

SQL-only webapp builder, empowering data analysts to build websites and applications quickly
https://sql.ophir.dev
MIT License
880 stars 62 forks source link

PostgreSQL: UPDATE using subselect fails "subquery must return only one column" #473

Open guspower opened 2 days ago

guspower commented 2 days ago

Introduction

A update using subselect query that succeeds when run directly against postgreSQL, and parses successfully using sqlparser, fails to run in SQLPage with error error returned from database: subquery must return only one column.

To Reproduce

DROP TABLE IF EXISTS customer_groups;
DROP TABLE IF EXISTS customers;

CREATE TEMPORARY TABLE customer_groups (
   customer_group_id bigserial NOT NULL
   , activation int
   , deposit int
);

INSERT INTO customer_groups (activation, deposit)
VALUES (100, 100);

CREATE TEMPORARY TABLE customers (
   month int NOT NULL
   , won_customers int
   , total_deposits bigint
);

INSERT INTO customers (month)
    SELECT * FROM generate_series(1,60);

UPDATE customers c SET (won_customers, total_deposits) =
    (SELECT 
        activation
        , activation * deposit        
    FROM
        customer_groups
    WHERE
        customer_group_id = 1
    AND
        c.month = 1
    )
    ; 

SELECT * FROM customers ORDER BY month ASC;

Expectation: a 3 column table output with the first row as 1, 100, 10000

Actual behavior

Failed to execute SQL statement:
UPDATE customers AS c SET won_customers.total_deposits = (SELECT activation, activation * deposit FROM customer_groups WHERE customer_group_id = 1 AND c.month = 1);
                                                          ⬆️
line 1, character 58

error returned from database: subquery must return only one column

You can see that the SET won_customers.total_deposits looks incorrect. A related example from the postgreSQL docs is:

UPDATE summary s SET (sum_x, sum_y, avg_x, avg_y) =
    (SELECT sum(x), sum(y), avg(x), avg(y) FROM data d
     WHERE d.group_id = s.group_id);

Screenshots

N/A

Expected behavior

The SQL should execute successfully

Version information

Additional context

I verified that sqlparser is ok with it by modifying the parse example on the README.md

lovasoa commented 2 days ago

Hello! Thank you for reporting the issue. I think this is a duplicate of https://github.com/lovasoa/SQLpage/issues/403. I have already submitted a patch for it upstream, and it was accepted, we are just waiting for a new release of sqlparser.

lovasoa commented 1 day ago

The new sqlparser with the fix is scheduled for release today: https://github.com/sqlparser-rs/sqlparser-rs/issues/1296

guspower commented 1 day ago

That's great news. And of course I should have picked up that while sqlparser did parse the SQL statement without error, what it produced was wrong, i.e. I should have run and inspected

println!("{}", ast[0].to_string());

not just

println!("AST: {:?}", ast);