by tomp · 9y ago · 0 comments
I've recently started working with PostgreSQL and stumbled upon a problem with their UPSERT implementation.
Basically, I want to store an id -> name mapping in a table, with the usual characteristics.
CREATE TABLE entities (id SERIAL PRIMARY KEY, name VARCHAR(10) UNIQUE NOT NULL);
Then, I want to issue a query (or queries) with some entity names that would return their indices, inserting them if necessary.It appears that's impossible to do with PostgreSQL. The closest I can get is this:
INSERT INTO entities (name) VALUES ('a'), ('b'), ('c')
ON CONFLICT (name) DO NOTHING
RETURNING id, name;
However, this (1) only returns the newly inserted rows, and (2) it increments the `id` counter even in case of conflicts (i.e. if the name already exists). While (2) is merely annoying, (1) means I have to issue at least one more SELECT query.We like to mock Java, C++ and Go for being stuck in the past, but that's nothing compared to the state of SQL. Sure, there are custom extensions that each database provider implements, but they're often lacking in obvious ways. I really wish there was some significant progress, e.g. TypeSQL or CoffeeSQL or something.
BEGIN;
INSERT INTO entities (name)
(VALUES ('a'), ('b'), ('c') EXCEPT SELECT name FROM entities);
SELECT id, name FROM entities WHERE name IN ('a', 'b', 'c');
COMMIT;Use WITH select id, name from entities where name in :data AS existing
Then return a UNION of existing and (INSERT into entities (name) :data except existing returning id, name)
I've actually seen the specific misunderstanding many times on forums and on IRC. I wonder if it'd be possible to change the syntax to something like "RETURNING [ ALL | NEW ] * | output_expression [ [ AS ] output_name ]" where when empty "NEW" would be used and be equivalent to the current semantics where "ALL" would include rows that were not inserted on conflict. "ALL" would have no different meaning on "ON CONFLICT DO UPDATE" or when no conflict resolution was specified.
For now, there are optimizations planned for the query planner that would optimize this to a single query in the next releases.
Some commercial databases already do that.
INSERT RETURNING only returns the value of the changed rows, but it does not return anything if you redirect writes with triggers or child tables, including partitioning
Actually, I find SQL pretty nice. It's strongly typed in non-MySQL engines. It's pretty expressive, and can be highly optimized without having to update queries. Analytical features found in non-MySQL databases such as windows are also invaluable for many types of analysis.
The biggest issue I've ever had is that nesting queries when doing some analytical work can be a pain. WITH does handle this to some extent, but it doesn't seem quite as nice as something like PIG where results an "flow" through the query.
The other issue is transformations like pivot tables where you don't know the column names ahead of time. pg has extensions for that, but they aren't quite as nice as a native SQL solution would be.
WITH
input_rows (name) AS
(VALUES ('a'), ('b'), ('c')),
insert_rows AS
(INSERT INTO entities (name)
SELECT ir.name
FROM input_rows AS ir
ON CONFLICT DO NOTHING
RETURNING id, name),
-- returned when insert was successful
SELECT 'new' AS src, i.id, i.name
FROM insert_rows AS i
UNION ALL
-- return when there's a conflict
SELECT 'existing' AS src, e.id, e.name
FROM entities AS e
JOIN input_rows USING (name);
As for the sequence incrementing, that's the nature of sequences: it's a trade-off between getting fast, unique values versus the overhead required tracking whether the id is used.