PostgreSQL syntax error related to INSERT and/or WITH. Occurs in 8.4 but not 9.1. Ideas? - postgresql

Here is some SQL for PostgreSQL (I know it's a silly query; I've boiled the original query down to the simplest broken code):
CREATE TABLE entity (
id SERIAL PRIMARY KEY
);
WITH new_entity
AS (INSERT INTO entity DEFAULT VALUES
RETURNING id
)
SELECT id FROM new_entity;
Here it is running on PostgreSQL 9.1:
psql:../sandbox/test.sql:3: NOTICE: CREATE TABLE will create implicit sequence "entity_id_seq" for serial column "entity.id"
psql:../sandbox/test.sql:3: NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "entity_pkey" for table "entity"
CREATE TABLE
id
----
1
(1 row)
Here it is not running on PostgreSQL 8.4:
psql:../sandbox/test.sql:3: NOTICE: CREATE TABLE will create implicit sequence "entity_id_seq" for serial column "entity.id"
psql:../sandbox/test.sql:3: NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "entity_pkey" for table "entity"
CREATE TABLE
psql:../sandbox/test.sql:9: ERROR: syntax error at or near "INSERT"
LINE 2: AS (INSERT INTO entity DEFAULT VALUES
Obviously, the table creation goes fine in both cases, but it wipes out on the second query in PostgreSQL 8.4. From this error message I am unable to gather exactly what the problem is. I don't know what it is that 9.1 has and 8.4 doesn't have that could result in this syntax error. It's hilariously hard to google it. I am approaching the level of desperation required to trawl through the pages of PostgreSQL release notes between 8.4 and 9.1 and finding out if anything related to WITH … AS or INSERT … RETURNING was changed or added, but before I go there I am hoping one of you has the experience and/or godly google-fu to help me out here.

Data-modifying statements in WITH were introduced in Postgres 9.1

Related

PostgreSQL create table fails on identity column

I'm trying to set up a Postgres table using DBeaver as my management tool to run queries. Everything seems to work OK until I try to generate a table with an identity column. I am getting this error:
ERROR: syntax error at or near "GENERATED"
This is the query that is failing:
create table public.test (
id INT GENERATED BY DEFAULT AS IDENTITY
)
This query works just fine:
create table public.test (
id INT
)
I referenced data here and here to make sure the syntax was correct. What's going on?
EDIT: My problem was that my version is too old: 9.5.18 - needs to be 10 for this command to work.

SET*5 set_config ------------ (1 row) SET*4 CREATE TABLE ERROR: syntax error at or near "AS" LINE 2: AS integer ^ Import error: exit status 3 [duplicate]

Postgresql lost the autoincrement feature after a restore. My database was created on Windows 10 (v 10.1) and I restored it to Postgresql on Ubuntu (v 9.6). Now that I posted the question I saw that the versions are different. I didn't use any obscure feature, only tables, functions, and columns with serials. Also, the restore process didn't complain about anything. I checked the dump options but I couldn't find anything that caused the problem.
With Pgadmin right-clicking the table > scripts > create a script on my original table gives this:
CREATE TABLE public.produto
(
produto_id integer NOT NULL DEFAULT nextval('produto_produto_id_seq'::regclass),
...
);
In my server, the restored database. It seems it lost the feature.
CREATE TABLE public.produto
(
produto_id integer NOT NULL,
...
);
You didn't check for errors during restore of the database; there should have been a few.
A dump of a table like yours will look like this in PostgreSQL v10 (this is 10.3 and it looks slightly different in 10.1, but that's irrelevant to this case):
CREATE TABLE public.produto (
produto_id integer NOT NULL
);
ALTER TABLE public.produto OWNER TO laurenz;
CREATE SEQUENCE public.produto_produto_id_seq
AS integer
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE public.produto_produto_id_seq OWNER TO laurenz;
ALTER SEQUENCE public.produto_produto_id_seq
OWNED BY public.produto.produto_id;
ALTER TABLE ONLY public.produto
ALTER COLUMN produto_id
SET DEFAULT nextval('public.produto_produto_id_seq'::regclass);
Now the problem is that AS integer was introduced to CREATE SEQUENCE in PostgreSQL v10, so that statement will fail with a syntax error in 9.6.
What is the consequence?
The table is created like in the first statement.
The third statement creating the sequence fails.
All the following statements that require the sequence will also fail.
Note: It is not supported to downgrade PostgeSQL with dump and restore.
The solution is to manually edit the dump until it works, in particular you'll have to remove the AS integer or AS bigint clause in CREATE SEQUENCE.

Why doesn't knex create serial column in postgres?

I use knex to create a postgres table as following:
knex.schema.createTable('users', table => {
table.bigIncrements('user_id');
....
})
But after the table was created, the column user_id is a integer not the serial as expected.
The sql get by the pgAdmin is as following:
CREATE TABLE public.users
(
user_id bigint NOT NULL DEFAULT nextval('users_user_id_seq'::regclass),
....
)
And the consequence is that when I do insert statement, the user_id won't auto increment as expected.
Any gives?
====================
Currently I just changed to mysql connection, and the inserting works well. But if I changed the database back to postgresql, then inserting would fail due to the duplication of user_id. The code can be found here: https://github.com/buzz-buzz/buzz-service
serial and bigserial are not real types they are just shorthand for what pgAdmin is showing.
You will also find that a sequence has been created with the name users_user_id_seq when you look under sequences in pgAdmin.

Does Go-Gorm support insert with auto incremented ID for partitioned tables in PostgreSQL?

I have a table in PostgreSQL represented as the following Go struct:
type AppLog struct {
ID int // set to auto increment in DB, also a primary key
event string
createTime time.Time
}
I configured monthly table partitioning with the above as the base table and a insert trigger to route the data into the child table for the current month using the dateTime values as the partition key.
[the trigger function etc are omitted for brevity]
When I try to insert into AppLog table, Postgres routes the operation to the appropriate child table, say AppLog_2017-05 (current month table), but the insert fails with the following error:
INSERT INTO "app_logs" ("event", "create_time")
VALUES ('device /dev/sdc is now ready','2017-05-26T15:04:30+05:30')
RETURNING "app_logs"."id"
ERROR: sql: no rows in result set
When the same query is run in the Postgres Shell, it runs fine.
Can someone help me understand how to do inserts using GORM in PostgreSQL where table partitioning is configured behind the scene? I am not sure if this is a problem with GORM or the Go PostgreSQL driver or Go Database/SQL package. Or, if I am missing anything.
Any help will be highly appreciated.
I got the answer. It was not an issue with GORM or Go-PQ. I was doing some goof up in my trigger function while returning the inserted values from the child table.

DB2 -- unique constraint on multiple columns

I'm trying to add a unique constraint on 2 columns on DB2-- docType column and title column. The values of each column can repeat in themselves. however, the values of (docType, title) pairs should not repeat.
I tried so far
ALTER TABLE externalfiles
ADD CONSTRAINT logicalKey UNIQUE (doctype, title)
and
alter table externalfiles add unique (doctype, title)
, and got the following error to both:
Operation not allowed for reason code "7" on table "PIT.EXTERNALFILES".. SQLCODE=-668, SQLSTATE=57016, DRIVER=4.21.29
Isn't this any allowed??
DB2 Unique Constraint over multiple Columns suggests creating indexes as alternative to this. Haven't tried indexing them yet-- however, i'm wondering why the unique constraint isn't working.
TIA.
This web search on db2 luw sqlstate 57016 returns a number of links that suggest a prior ALTER may require that a REORG be performed before the ADD CONSTRAINT can be effected.
Perhaps most notable was the following doc link and snippet of text describing the RC7 [apparently SQLERRMC=7]:
DB2 for Linux UNIX and Windows 9.7.0
->Database fundamentals
->Messages
->SQL Messages
->SQL0500 - SQL0999
->SQL0668N
…
7 • The table is in the reorg pending state. This can occur after an
ALTER TABLE statement containing a REORG-recommended operation.
…
First try to reorganize table by
call sysproc.admin_cmd ('reorg table <TABLE_NAME>');
Than try again to create unique index. It should work.