Why regenerated Postgres table raise error in Vapor? - postgresql

A table in production environment was created like this:
-- DDL generated by Postico 1.5.10
-- Not all database features are supported. Do not use for backup.
-- Table Definition ----------------------------------------------
CREATE TABLE "TempUser" (
id bigint PRIMARY KEY,
"Uuid" text NOT NULL,
"dateCreated" timestamp without time zone NOT NULL,
"lastRequestDate" timestamp without time zone NOT NULL,
"lastRequestLocation" text,
"numOfRequest" bigint NOT NULL,
comment text NOT NULL,
"lastRequestDescription" text NOT NULL,
"bookedSeats" text NOT NULL,
"bookUntil" timestamp without time zone,
"lastEventVisited" text
);
-- Indices -------------------------------------------------------
CREATE UNIQUE INDEX "pk:TempUser.id" ON "TempUser"(id int8_ops);
Why I remove table in dev environment and create like this in Postgres console, I got following error after try writing programmatically:
[ ERROR ] PostgreSQLError.server.error.ExecConstraints: POST /registerTempUser null value in column "id" violates not-null constraint (ErrorMiddleware.swift:26)
[ DEBUG ] Possible causes for PostgreSQLError.server.error.ExecConstraints: Failing row contains (null, 015574220836500, 2020-07-09 19:42:36.803846, 2020-07-09 19:42:36.803846, null, 1, , POST /registerTempUser HTTP/1.1
Host: localhost:8080
Content-Typ..., [], null, null). (ErrorMiddleware.swift:26)
Why, what is wrong?
Tried set sequence thing:
select setval(pg_get_serial_sequence('"TempUser"', 'id'), 1);
select currval(pg_get_serial_sequence('"TempUser"', 'id'));
nothing changed.

Related

How to get primary key sequence in Postgres?

I have following table:
-- DDL generated by Postico 1.5.10
-- Not all database features are supported. Do not use for backup.
-- Table Definition ----------------------------------------------
CREATE TABLE "Ticket" (
id bigint PRIMARY KEY,
"paymentId" text NOT NULL,
"transactionId" text,
"dateCreated" timestamp without time zone NOT NULL,
"dateValidated" timestamp without time zone,
"sellerPaymentId" text NOT NULL,
"sellerPaymentProvider" text NOT NULL,
"userId" bigint NOT NULL,
"userIdFb" text NOT NULL,
"userName" text NOT NULL,
"eventDescription" text NOT NULL,
"eventTimeId" text,
"eventId" text NOT NULL,
"eventName" text NOT NULL,
"startTime" timestamp without time zone,
"endTime" timestamp without time zone,
quantity bigint,
"unitPrice" text,
seats jsonb[],
location text NOT NULL,
link text,
"eventTimesSelected" jsonb,
"otherListsSelected" jsonb,
"transactionIdBarion1" text,
"transactionIdBarion2" text
);
-- Indices -------------------------------------------------------
CREATE UNIQUE INDEX "pk:Ticket.id" ON "Ticket"(id int8_ops);
When inserting a new row, got this error:
[ ERROR ] PostgreSQLError.server.error._bt_check_unique: POST /startPayment duplicate key value violates unique constraint "pk:Ticket.id" (ErrorMiddleware.swift:26)
[ DEBUG ] Possible causes for PostgreSQLError.server.error._bt_check_unique: Key (id)=(1) already exists. (ErrorMiddleware.swift:26)
How the heck I can reset the primary key sequence? There are many answers on internet, but what is the name of my sequence? :) I do not see any 'name' in my DDL.
I tried fetch sequence name like this:
select currval(pg_get_serial_sequence("Ticket", "id"));
no luck:
ERROR: column "Ticket" does not exist
LINE 1: select currval(pg_get_serial_sequence("Ticket", "id"));
pg_get_serial_sequence() expects string values, not identifiers. Your problems stem from the fact that you used those dreaded quoted identifiers when creating the table which is strongly discouraged.
You need to pass the double quotes inside single quotes:
select currval(pg_get_serial_sequence('"Ticket"', '"id"'));
You should reconsider the usage of quoted identifiers to avoid problems like that in the future.
How the heck I can reset the primary key sequence
How to reset postgres' primary key sequence when it falls out of sync?
How to bulk update sequence ID postgreSQL for all tables

null value in column violates not-null constraint PostgreSQL

I'm trying to import a csv into PostgreSQL database table.When i executing the following query:
My table name is trendmania_video
COPY public.trendmania_video FROM 'C:\Users\Shahnawaz Irfan\Desktop\0.csv' DELIMITER ',' CSV HEADER;
a following error occurred:
ERROR: null value in column "v_id" violates not-null constraint
DETAIL: Failing row contains (null, null, UgzYr_WZlR73yFBnRdx4AaABAg, yar
kindly ap urdu m b toturial bna lety wordpress k liye to hma..., null, null,
null, null, null, null, null, null, null, null).
CONTEXT: COPY trendmania_video, line 10: ",,UgzYr_WZlR73yFBnRdx4AaABAg,yar
kindly ap urdu m b toturial bna lety wordpress k liye to hmari b he..."
SQL state: 23502
I also tried manually by using import button, but same error occurs.
In your table trendmania_video, you have v_id to be not null which causes this issue. You one option is to get ride of the not null constrain:
ALTER TABLE public.trendmania_video ALTER COLUMN v_id DROP NOT NULL;
If this is a new table then it's better to recreate it with a new table with an auto-cremented id while v_id is another value.
CREATE TABLE trendmania_video(
id SERIAL PRIMARY KEY,
v_id VARCHAR
--the rest of the columns
);

PostgreSQL foreign keys multiple keys on single table

I can imagine that it is unlikely that this question has never been answered. However, I have not found it, so in any case here is my problem:
I am migrating from MySQL.
I am getting an error when I try to create a table with one single data field with 2 foreign keys referencing another table.
My goal is to simply have a phone directory for employees.
The directory table must reference the employee id as well as the phone number type.
I get this error when trying to do so:
ERROR: There is no unique constraint matching given keys, for referenced table: Employees!
Here is my current sql dump:
-- ----------------------------
-- Table structure for EmployeeGroups
-- ----------------------------
DROP TABLE IF EXISTS "public"."EmployeeGroups";
CREATE TABLE "public"."EmployeeGroups" (
"Id" int8 DEFAULT nextval('"EmployeeGroups_Id_seq"'::regclass) NOT NULL,
"EmployeeGroup" varchar(255) COLLATE "default"
)
WITH (OIDS=FALSE)
;
-- ----------------------------
-- Table structure for Employees
-- ----------------------------
DROP TABLE IF EXISTS "public"."Employees";
CREATE TABLE "public"."Employees" (
"Id" int8 DEFAULT nextval('"Employees_Id_seq"'::regclass) NOT NULL,
"EmployeeGroupId" int8 DEFAULT
nextval('"Employees_EmployeeGroupId_seq"'::regclass) NOT NULL,
"FirstName" varchar(255) COLLATE "default",
"LastName" varchar(255) COLLATE "default",
"CivicNumber" int4,
"CivicNumberAlias" int4,
"StreetName" varchar(255) COLLATE "default",
"City" varchar(255) COLLATE "default",
"PostalCode" varchar(255) COLLATE "default",
"UserAcessLevel" int8 DEFAULT
nextval('"Employees_UserAcessLevel_seq"'::regclass) NOT NULL,
"Username" varchar(255) COLLATE "default",
"Password" varchar(255) COLLATE "default",
"Timestamp" date
)
WITH (OIDS=FALSE)
;
-- ----------------------------
-- Table structure for PhoneNumberType
-- ----------------------------
DROP TABLE IF EXISTS "public"."PhoneNumberType";
CREATE TABLE "public"."PhoneNumberType" (
"Id" int8 DEFAULT nextval('"PhoneNumberType_Id_seq1"'::regclass) NOT NULL,
"PhoneNumberType" varchar(150) COLLATE "default" NOT NULL
)
WITH (OIDS=FALSE)
;
-- ----------------------------
-- Table structure for SystemAcessLevel
-- ----------------------------
DROP TABLE IF EXISTS "public"."SystemAcessLevel";
CREATE TABLE "public"."SystemAcessLevel" (
"Id" int8 DEFAULT nextval('"SystemAcessLevel_Id_seq"'::regclass) NOT NULL,
"AcessLevel" varchar(255) COLLATE "default" NOT NULL
)
WITH (OIDS=FALSE);
Here is my error generating statement:
CREATE TABLE "public"."NewTable" (
"Id" serial8 NOT NULL,
"EmployeeId" int8 NOT NULL,
"PhoneNumberTypeId" int8 NOT NULL,
"PhoneNumber" varchar(16) NOT NULL,
PRIMARY KEY ("Id"),
CONSTRAINT "phone_fk_emp_id" FOREIGN KEY ("EmployeeId")
REFERENCES "public"."Employees" ("Id") ON DELETE NO ACTION ON UPDATE
CASCADE,
CONSTRAINT "phone_fk_type_id" FOREIGN KEY ("PhoneNumberTypeId")
REFERENCES "public"."PhoneNumberType" ("Id") ON DELETE NO ACTION ON
UPDATE CASCADE
)
WITH (OIDS=FALSE)
;
As it turns out the problem was identifying the
EmployeeGroupId
field that was referenced in the Employees table as a second primary key created a conflict when adding the EmployeeDirectory table referencing the same foreing key as a second primary key of the Employees.GroupId field.
In other word seems like PostgreSQL considers second primary key as unique identifiers creating a one to one relationship therefore it considers it as an error to have an additional table referencing the same identifier as a foreing key stated as a second primary key, and please correct me if I am wrong since not an expert when it comes to PostgreSQL.
This however is accepted by Mysql; this is why I was having a hard time figuring out this error.
Every column (or set of columns) that you reference in a foreign key must have a primary key or unique constraint on it.
Otherwise, how could you identify which row the foreign key points to?

Joomla extension installation with PostgreSQL support

I would like to support PostgreSQL with my extension, however I'm running into a problem when I attempt to install it. Currently, I have the following in my XML for the install section:
<install>
<sql>
<file driver="mysql" charset="utf8">sql/install.mysql.utf8.sql</file>
<file driver="postgresql" charset="utf8">sql/install.postgresql.utf8.sql</file>
</sql>
</install>
And here is the code for install.postgresql.utf8.sql:
CREATE TABLE "#__shoutbox" (
"id" serial NOT NULL,
"name" character varying(25) DEFAULT '' NOT NULL,
"when" timestamp without time zone DEFAULT '' NOT NULL,
"ip" character varying(15) DEFAULT '' NOT NULL,
"msg" text NOT NULL,
"user_id" bigint(11) DEFAULT 0 NOT NULL,
PRIMARY KEY ("id")
);
INSERT INTO "#__shoutbox" ("name", "when", "msg", "user_id") VALUES ('JoomJunk', '2013-04-04 20:00:00', 'Welcome to the Shoutbox', '0');
I have noticed a few differences between the query for MySQL and PostgreSQL which I think I have taken into consideration, but when I attempt to install the extension, I get the following error:
Database query failed (error # %s): %s SQL=CREATE TABLE "pdo31_shoutbox" ( "id" serial NOT NULL, "name" character varying(25) DEFAULT '' NOT NULL, "when" timestamp without time zone DEFAULT '' NOT NULL, "ip" character varying(15) DEFAULT '' NOT NULL, "msg" text NOT NULL, "user_id" bigint(11) DEFAULT 0 NOT NULL, PRIMARY KEY ("id") );
There is no documentation on supporting PostgreSQL for extensions so I have done what I can by looking at the SQL file from the Joomla 3.1 installation folder.
Is the problem with my query?
The default value for when is not a valid timestamp. If you want when to be empty then remove the NOT NULL constraint so it can be NULL. Otherwise specify a valid timestamp like '2013-4-4 12:34:56'.
Bigint in postgresql does not support a size specification. It is always 64-bits (which is more then 11 decimal digits).
CREATE TABLE "pdo31_shoutbox" (
"id" serial NOT NULL,
"name" character varying(25) DEFAULT '' NOT NULL,
"when" timestamp without time zone,
"ip" character varying(15) DEFAULT '' NOT NULL,
"msg" text NOT NULL,
"user_id" bigint DEFAULT 0 NOT NULL,
PRIMARY KEY ("id")
);

pgAdmin - When trying to make a foreign key "referencing" gives no options

I have three tables: ModelingAgency.clients, ModelingAgency.models, ModelingAgency.Bookings. All three tables have a primary key column called id.
The table bookings has two columns that reference clients and models. In pgAdmin when I try to create a foreign key in bookings to either clients or models I get the following screens:
What am I overlooking here? I am new to PostgreSQL (This is my first test project with PostgreSQL -- I've always used MySQL and occasionally SQL Server) so it's probably something obvious (I just don't see it).
EDIT: Here is the DDL, as requested:
-- Table: "ModelingAgency.bookings"
-- DROP TABLE "ModelingAgency.bookings";
CREATE TABLE "ModelingAgency.bookings"
(
id integer NOT NULL DEFAULT nextval('"ModelingAgency.Bookings_id_seq"'::regclass),
"clientId" integer NOT NULL,
"modelId" integer NOT NULL,
"time" timestamp with time zone NOT NULL DEFAULT now(),
"location" character varying(100) NOT NULL DEFAULT 'No Location Selected'::character varying,
CONSTRAINT "bookingId" PRIMARY KEY (id)
)
WITH (
OIDS=FALSE
);
ALTER TABLE "ModelingAgency.bookings" OWNER TO "MyBatisTutorial";
-- Table: "ModelingAgency.clients"
-- DROP TABLE "ModelingAgency.clients";
CREATE TABLE "ModelingAgency.clients"
(
id integer NOT NULL DEFAULT nextval('"ModelAgency.clients_id_seq"'::regclass),
"name" character varying(45) NOT NULL,
CONSTRAINT "clientId" PRIMARY KEY (id)
)
WITH (
OIDS=FALSE
);
ALTER TABLE "ModelingAgency.clients" OWNER TO "MyBatisTutorial";
-- Table: "ModelingAgency.models"
-- DROP TABLE "ModelingAgency.models";
CREATE TABLE "ModelingAgency.models"
(
id serial NOT NULL,
"name" character varying(45) NOT NULL,
CONSTRAINT "modelId" PRIMARY KEY (id)
)
WITH (
OIDS=FALSE
);
ALTER TABLE "ModelingAgency.models" OWNER TO "MyBatisTutorial";
Looking into your posted DDL code I see that your table's names are written in wrong way (that causes your issue with pgAdmin):
"ModelingAgency.bookings"
It should be in format "schema"."tableName":
"ModelingAgency"."bookings"
After that Object browser looks like this (probably you need to create schema first using easily pgAdmin or with CREATE SCHEMA SQL statement):
Here is working DDL code (I omitted some things like OIDS and OWNER TO, but that doesn't matter to your case, BTW OIDS are false on default):
DROP TABLE IF EXISTS "ModelingAgency"."bookings";
CREATE TABLE "ModelingAgency"."bookings"
(
id serial,
"clientId" integer NOT NULL,
"modelId" integer NOT NULL,
"time" timestamp with time zone NOT NULL DEFAULT now(),
"location" character varying(100) NOT NULL
DEFAULT 'No Location Selected'::character varying,
CONSTRAINT "bookingId" PRIMARY KEY (id)
);
DROP TABLE IF EXISTS "ModelingAgency"."clients";
CREATE TABLE "ModelingAgency"."clients"
(
id serial,
"name" character varying(45) NOT NULL,
CONSTRAINT "clientId" PRIMARY KEY (id)
);
DROP TABLE IF EXISTS "ModelingAgency"."models";
CREATE TABLE "ModelingAgency"."models"
(
id serial NOT NULL,
"name" character varying(45) NOT NULL,
CONSTRAINT "modelId" PRIMARY KEY (id)
)