I got a files table:
CREATE TABLE files (
id SERIAL PRIMARY KEY,
path VARCHAR NOT NULL UNIQUE
);
And I wanna write an sql transaction to emulate FS behavior when you tryna create a file:
- if a file with such path doesn’t exist yet -> create it
- if it does -> create a file with name like
{filename} (1)
- if such file already exists too -> find the greatest available number
n
and paste it into{filename} ({n})
So I’m stuck in that moment:
WITH f AS (
SELECT path
FROM files
WHERE path ~ '^(kek|kek (d+))$'
ORDER BY path DESC
)
SELECT
CASE
WHEN COUNT(f) > 1 THEN (
WITH cte AS (
SELECT *
FROM (
SELECT SUBSTRING(f.path, 6, LENGTH(f.path) - 6)::numeric AS i
FROM f
WHERE f.path != 'kek'
) AS n
WHERE i > 0
ORDER BY i
)
-- SELECT LAG(arr, 1, NULL) OVER (
-- PARTITION BY arr
-- ORDER BY arr
-- ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
-- )
-- FROM a
SELECT ARRAY(
SELECT i + 1
FROM cte
)
)
WHEN COUNT(f) = 0 THEN 'kek (0)'
ELSE 'kek'
END
FROM f
that gives me a sorted array (or a query) of such numbers. But how to find the next greatest available number?
Maybe you got something better in your mind cause this query already looks too enormous for such task IMO
2
Answers
After realizing that commenters and that indian retard can't read so they wrote some sht, I spent some hours and finally solved it.
My commented attempts with using the
LAG
window function were in a right way. So the final answer is:I separated
kek
as it's gonna be an argument, not just a part of a plain query how dumbs above were assuming. And the magic number6
is also a pasted value since it's a length of thekek (
part and I'm gonna calculate it in my program and paste it to the plain queryAnd it's also available as a DB Fiddle
Do you provide a filename to generate a new file number for the specific file?
I have tried to solve it but if you could let us what input will be provided to the query and what output you expect?
This query will generate the latest file number + 1 for the patterns provided in the where clause in the CTE;
Output