162: ERROR: duplicate key value violates unique constraint "articles_pkey" when I try to run the command: psql newsdata.sql - psql

I get this when I try to connect my DB when I run the following
psql newsdata.sql
here is the whole output
vagrant#vagrant:/vagrant$ psql -d news -f newsdata.sql
SET
SET
SET
SET
SET
SET
SET
SET
SET
psql:newsdata.sql:31: ERROR: relation "articles" already exists
ALTER TABLE
psql:newsdata.sql:45: ERROR: relation "articles_id_seq" already exists
ALTER TABLE
ALTER SEQUENCE
psql:newsdata.sql:65: ERROR: relation "authors" already exists
ALTER TABLE
psql:newsdata.sql:79: ERROR: relation "authors_id_seq" already exists
ALTER TABLE
ALTER SEQUENCE
psql:newsdata.sql:102: ERROR: relation "log" already exists
ALTER TABLE
psql:newsdata.sql:116: ERROR: relation "log_id_seq" already exists
ALTER TABLE
ALTER SEQUENCE
ALTER TABLE
ALTER TABLE
ALTER TABLE
psql:newsdata.sql:162: ERROR: duplicate key value violates unique constraint "articles_pkey"
DETAIL: Key (id)=(23) already exists.
CONTEXT: COPY articles, line 1
setval
--------
30
(1 row)
psql:newsdata.sql:181: ERROR: duplicate key value violates unique constraint "authors_pkey"
DETAIL: Key (id)=(1) already exists.
CONTEXT: COPY authors, line 1
setval
--------
4
(1 row)
psql:newsdata.sql:1677931: ERROR: duplicate key value violates unique constraint "log_pkey"
DETAIL: Key (id)=(1678923) already exists.
CONTEXT: COPY log, line 1
setval
---------
3356657
(1 row)
psql:newsdata.sql:1677946: ERROR: multiple primary keys for table "articles" are not allowed
psql:newsdata.sql:1677954: ERROR: relation "articles_slug_key" already exists
psql:newsdata.sql:1677962: ERROR: multiple primary keys for table "authors" are not allowed
psql:newsdata.sql:1677970: ERROR: multiple primary keys for table "log" are not allowed
psql:newsdata.sql:1677978: ERROR: constraint "articles_author_fkey" for relation "articles" already exists
I just don't understand what's dublicated key so I can fix it, I'm begginner could you provide a detailed answer for this? even if it's just a link to check, it would help a lot.

DETAIL: Key (id)=(23) already exists.
DETAIL: Key (id)=(1) already exists.
Script attempted to insert id=23 or id=1 but theses values are already in table.
So unique constraint violated, and each tuple have not unique id.

solved.
The problem was because I ran this command before so now I tried psql -d news and it worked.
the output showed a table for relations

Related

Why Composite Primary Key is not added as a Foreign Key in psql (rails app)?

I am using activerecord-multi-tenant gem for implementing MultiTenancy in my rails project.
Followed instruction from here
I have a User model, Attendance Model which belongs to User, And Company as a tenant.
While I am updating User's primary key(id) to composite key(id, company_id) It is updating.
But when I am trying to update the Foreign key in Attendance models it is only trying to take user_id as a fk and searching for its unique constraint.
Here is the commands i used -
execute 'ALTER TABLE users DROP CONSTRAINT users_pkey;'
execute 'ALTER TABLE users ADD CONSTRAINT users_pkey PRIMARY KEY(id, company_id);'
execute 'ALTER TABLE attendances DROP CONSTRAINT attendances_pkey;'
execute 'ALTER TABLE attendances ADD CONSTRAINT attendances_pkey PRIMARY KEY (id, company_id);'
execute 'ALTER TABLE attendances ADD FOREIGN KEY(user_id, company_id) REFERENCES users(id, company_id);'
The Error i am getting while schema:load
ActiveRecord::StatementInvalid: PG::InvalidForeignKey: ERROR: there is no unique constraint matching given keys for referenced table "users"
: ALTER TABLE "attendances" ADD CONSTRAINT "attendances_user_id_company_id_fkey"
FOREIGN KEY ("user_id")
REFERENCES "users" ("id")
The solution was using structure.sql file.
In schema.rb file it cant always follow the sql command and reflect in the database. So I was getting this error InvalidForeignKey as schema couldn't load the sql command properly.
After moving to structure.sql all the migration were run properly with exact commands inside the files.

Unable to find column names in a FK constraint

I have created two tables in Snowflake.
create or replace TRANSIENT TABLE TESTPARENT (
COL1 NUMBER(38,0) NOT NULL,
COL2 VARCHAR(16777216) NOT NULL,
COL3 VARCHAR(16777216) NOT NULL,
constraint UNIQ_COL3 unique (COL3)
);
create or replace TRANSIENT TABLE TESTCHILD3 (
COL_A NUMBER(38,0) NOT NULL,
COL_B NUMBER(38,0) NOT NULL,
ABCDEF VARCHAR(16777216) NOT NULL,
constraint FKEY_1 foreign key (COL_A, COL_B) references TEST_DB.PUBLIC.TESTPARENT1(COL1,COL2),
constraint FKEY_2 foreign key (ABCDEF) references TEST_DB.PUBLIC.TESTPARENT(COL3)
);
Now I want to execute a query and see the names of columns that are involved in FKEY_2 FOREIGN KEY
in Table TESTCHILD3, but it seems like there are no DB Table/View that keeps this information. I can find out the column names for UNIQUE KEY & PRIMARY KEY but there is nothing for FOREIGN KEYS.
EDIT
I have already tried INFORMATION_SCHEMA.TABLE_CONSTRAINTS, along with INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS and all the other system tables. No luck. Only DESC TABLE is giving me some info related to CONSTRAINTS and COLUMNS but that also has FOREIGN KEY CONSTRAINTS information missing.
SHOW IMPORTED KEYS IN TABLE <fk_table_name>;
Updated answer:
I was checking on something unrelated and noticed a very efficient way to list all primary and foreign keys:
show exported keys in account; -- Foreign keys
show primary keys in account;
When you limit the call to a table, it appears you have to request the foreign keys that point to the parent table:
show exported keys in table "DB_NAME"."SCHEMA_NAME"."PARENT_TABLE";
You can check the documentation for how to limit the show command to a specific database or schema, but this returns rich information in a table very quickly.
maybe you can try to query this view: INFORMATION_SCHEMA.TABLE_CONSTRAINTS
Note: TABLE_CONSTRAINTS only displays objects for which the current role for the session has been granted access privileges.
For more see: https://docs.snowflake.net/manuals/sql-reference/info-schema/table_constraints.html

Sorting by joined table value with Rails

I'm trying to sort a list of items based on the value of field on a joined table. Here's what I've got so far:
FeaturedEvent.joins(:event).order('event.start_datetime').limit(5)
This looks right to me but when it's run it returns a Postgres error about there being a missing FROM statement:
PG::UndefinedTable: ERROR: missing FROM-clause entry for table "event" LINE 1: ...ts"."id" = "featured_events"."event_id" ORDER BY event.star... ^ : SELECT "featured_events".* FROM "featured_events" INNER JOIN "events" ON "events"."id" = "featured_events"."event_id" ORDER BY event.start_datetime LIMIT 5
I tried the suggestions in this post about putting the ordering in default scope but it came out with the same error – I'm guessing it's a Postgres thing.
How can I fix this?
Thanks!
Try
FeaturedEvent.includes(:event).order('events.start_datetime').limit(5)
In your order the table name should be the real database table name.
As I guess, the table name must be events
Your table name is events so you just have to add s in event
FeaturedEvent.joins(:event).order('events.start_datetime').limit(5)

Whats wrong with the foreign-key constraint in this table?

table creation failed because a foreign key constraint was not correctly formed
the first create table my_seeking, works fine, when I try to run the create contactstoseeking I get the following err msg
Error Code: 1005. Can't create table 'db_ferguson.contactstoseeking'
(errno: 150)
CREATE TABLE IF NOT EXISTS `my_seeking` (
`id` INT NOT NULL ,
`seeking` VARCHAR(45) NULL ,
PRIMARY KEY (`id`) )
ENGINE = InnoDB
;
CREATE TABLE IF NOT EXISTS `contactsTOseeking` (
`id` INT NOT NULL ,
`seek` VARCHAR(45) NOT NULL ,
UNIQUE INDEX `id_UNIQUE` (`id` ASC) ,
UNIQUE INDEX `seek_UNIQUE` (`seek` ASC) ,
CONSTRAINT `fk_contactsTOseeking_my_seeking1`
FOREIGN KEY (`id` )
REFERENCES `mydb`.`my_seeking` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
A search of the web shows that err 150 is tied to my fk constraint.
Cannot create table. If the error message refers to error 150, table creation failed because a foreign key constraint was not correctly formed. If the error message refers to error –1, table creation probably failed because the table includes a column name that matched the name of an internal InnoDB table."
this code was generated BY MySQL, and this is my first attempt at foreign keys. I tried coding it manually and had issues so I thought that I would let workbench do it. WHAT EVER the problem is I cant see it or it is beyond my current skill set
Did you try removing the 'mydb' text in the reference? It indicates a table in 'mydb' database.

Rails postgreSQL duplicate key

I have a Rails app that uses postgreSQL.
I recently did a backup of production and restored it to development.
When I try to add a Payment record in development, I get:
ERROR: duplicate key value violates unique constraint "payments_pkey"
DETAIL: Key (id)=(1) already exists.
Yet, there is only one record in the table with id=1 and the payments_id_seq has Current value = 1.
So, whey isn't Rails trying to add id=2 ??
Thanks for the help!
PS - is there a script or command in pgadmin to force the id_seq to be correct?
If you receive a PostgreSQL unique key violation error message ("duplicate key value violates unique constraint..."), probably your primary key index is out of sync, e.g. after populating the database.
Use
ActiveRecord::Base.connection.reset_pk_sequence!('[table_name]')
to fix the sequence for the users table.
Presumably whatever method you used to copy your database didn't update your sequences along the way, a standard dump/restore should have take care of that but if you copied things row-by-row by hand then you'll have to fix things using setval.
If you only need to fix the sequence for a table T, then you could do this from the console:
ActiveRecord::Base.connection.execute(%q{
select setval('T_id_seq', m)
from (
select max(id) from T
) as dt(m)
})
or you could feed that SQL to pgadmin. You'd repeat that for each table T.

Resources