Error: Duplicate foreign key constraint name - python

I exported a schema from workbench and now trying to use that script to create table in my server, But getting error
I tried to change the table and also tried to find duplicate foriegn key.
ERROR 1826: Duplicate foreign key constraint name 'bank_id'
SQL Statement:
-- Table aditya.users_has_bank
CREATE TABLE IF NOT EXISTS `aditya`.`users_has_bank` (
`users_user_id` INT NOT NULL AUTO_INCREMENT,
`bank_id` INT NOT NULL,
`user_id` INT NOT NULL,
PRIMARY KEY (`users_user_id`),
INDEX `bank_id_idx` (`bank_id` ASC) VISIBLE,
INDEX `user_id_idx` (`user_id` ASC) VISIBLE,
CONSTRAINT `bank_id`
FOREIGN KEY (`bank_id`)
REFERENCES `aditya`.`bank` (`bank_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `user_id`
FOREIGN KEY (`user_id`)
REFERENCES `aditya`.`users` (`user_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB

High possibility that FK name is used in other tables within your schema. Please do practice good FK naming convention
Source: Foreign Key naming scheme

Related

How do I create a foreign key in sqlite3 python

I can't get my program to use a foreign key for some unbeknown reason. I have read other questions related to this but cant find an answer that works. I tried the PRAGMA foreign_keys = ON, but instead i get a syntax error for "foreign_keys". I also tried removing this and running the program again and instead got an error saying the column I'm trying to create doesn't exist
import sqlite3
import os
import random
from tkinter import *
import uuid
PRAGMA foreign_keys = ON
conn = sqlite3.connect('MyComputerScience.db')
c = conn.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS users (
UserID text PRIMARY KEY,
FName text,
SName text,
username text,
password varchar,
userType text)""")
c.execute("""CREATE TABLE IF NOT EXISTS classes (
ClassID PRIMARY KEY,
FOREIGN KEY (User) REFERENCES users(UserID)))""")
FOREIGN KEY (User) REFERENCES users(UserID)))""")
sqlite3.OperationalError: unknown column "User" in foreign key definition
You need to create the fields in the table before using them as a foreign key.
As you did not add a field User to your table, you got the error:
unknown column "User" in foreign key definition
To fix the error, add User to your table definition
c.execute("""CREATE TABLE IF NOT EXISTS classes (
ClassID PRIMARY KEY,
User text,
FOREIGN KEY (User) REFERENCES users(UserID)))""")
However, I would question the design. The table classes would only be able to relate one user per class. Is that what you want to do?
c.execute("""CREATE TABLE IF NOT EXISTS classes (
ClassID PRIMARY KEY,
FOREIGN KEY (ClassID) REFERENCES users(UserID)))""")
That's the correct syntax but this way you set as foreign key your primary key. Maybe you wanted to use another field.

Error code 1215: Why Can't I Add Foreign Key

I cannot figure out why I can't add foreign key to my table... Can someone help me out? This is what I'm having trouble with:
CREATE TABLE Albums(
album_id INTEGER,
producer_id CHAR(6)NOT NULL,
release_date DATE,
album_title VARCHAR(30)NOT NULL,
price NUMERIC(5,2),
PRIMARY KEY(album_id),
FOREIGN KEY(producer_id)REFERENCES Musicians(sin));
The above code works
CREATE TABLE Orders(
order_id INTEGER NOT NULL,
album_id INTEGER,
album_title VARCHAR(30)NOT NULL,
price NUMERIC(5,2),
PRIMARY KEY(order_id, album_id),
FOREIGN KEY (album_id) REFERENCES Albums(album_id),
FOREIGN KEY (album_title) REFERENCES Albums(album_title),
FOREIGN KEY (price) REFERENCES Albums(price));
But this doesn't. I don't know why but I can't add album_title and price as Foreign Keys.
Here's what the documentation says:
A FOREIGN KEY constraint does not have to be linked only to a PRIMARY
KEY constraint in another table; it can also be defined to reference
the columns of a UNIQUE constraint in another table.
So album_title and price should be either PRIMARY KEY or should have UNIQUE Constraint in the Albums Table.

Adding primary key to existing MySQL table in alembic

I am trying to add an 'id' primary key column to an already existing MySQL table using alembic. I tried the following...
op.add_column('mytable', sa.Column('id', sa.Integer(), nullable=False))
op.alter_column('mytable', 'id', autoincrement=True, existing_type=sa.Integer(), existing_server_default=False, existing_nullable=False)
but got the following error
sqlalchemy.exc.OperationalError: (OperationalError) (1075, 'Incorrect table definition; there can be only one auto column and it must be defined as a key') 'ALTER TABLE mytable CHANGE id id INTEGER NOT NULL AUTO_INCREMENT' ()
looks like the sql statement generated by alembic did not add PRIMARY KEY at the end of the alter statement. Could I have missed some settings?
Thanks in advance!
I spent some time digging through the alembic source code, and this doesn't seem to be supported. You can specify primary keys when creating a table, but not when adding columns. In fact, it specifically checks and won't let you (link to source):
# from alembic.operations.toimpl.add_column, line 132
for constraint in t.constraints:
if not isinstance(constraint, sa_schema.PrimaryKeyConstraint):
operations.impl.add_constraint(constraint)
I looked around, and adding a primary key to an existing table may result in unspecified behavior - primary keys aren't supposed to be null, so your engine may or may not create primary keys for existing rows. See this SO discussion for more info: Insert auto increment primary key to existing table
I'd just run the alter query directly, and create primary keys if you need to.
op.execute("ALTER TABLE mytable ADD id INT PRIMARY KEY AUTO_INCREMENT;")
If you really need cross-engine compatibility, the big hammer would be to (1) create a new table identical to the old one with a primary key, (2) migrate all your data, (3)delete the old table and (4) rename the new table.
Hope that helps.
You have to remove the primary key that is in the table and then create a new one that includes all columns that you want as the primary key.
eg. In psql use \d <table name> to define the schema, then check the primary key constraint.
Indexes:
"enrollments_pkey" PRIMARY KEY, btree (se_crs_id, se_std_id)
then use this information in alembic
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('enrollments', sa.Column(
'se_semester', sa.String(length=30), nullable=False))
op.drop_constraint('enrollments_pkey', 'enrollments', type_='primary')
op.create_primary_key('enrollments_pkey', 'enrollments', [
'se_std_id', 'se_crs_id', 'se_semester'])
The results after running \d enrollments should be updated to
Indexes:
"enrollments_pkey" PRIMARY KEY, btree (se_std_id, se_crs_id, se_semester)
This solution worked fine for me.

A table with a composite Primary key, one of the fields with autoincrement

Im using a table constraint to create a composite primary key, I would like the id field to autoincrement, is this possible? or what are the alternatives?
CREATE TABLE IF NOT EXISTS atable(
id INTEGER NOT NULL, --I want to autoincrement this one
name TEXT NOT NULL,
anotherCol TEXT,
PRIMARY KEY(id, name));
No, there's only one primary key: that's the composite of id and name.
If you mean that you want id to be the primary key, and name to be an indexed alternate key, I'd say that you should give name a unique constraint and make id the primary key.
Here's the link to the SQLite FAQ page where your question of how to autoincrement an integer primary key is #1. http://www.sqlite.org/faq.html#q1
Here's your SQL reworked a little:
CREATE TABLE IF NOT EXISTS atable(
id INTEGER PRIMARY KEY, -- use NULL for this column on INSERT to autoinc
name TEXT NOT NULL,
anotherCol TEXT);
then create a unique index on NAME as suggested by duffymo and Kaleb.
It doesn't look to me that the OP want names to be unique. (But I could be wrong.) At any rate, you can
get an autoincrementing integer by using INTEGER PRIMARY KEY and inserting NULL into that column, and
declare a superkey by using a UNIQUE constraint on (id, name).
A superkey is just a candidate key (primary key in this case) plus one or more columns.
CREATE TABLE yourtable(
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
CONSTRAINT superkey UNIQUE (id, name)
);
If you turn on foreign key support using PRAGMA foreign_keys = on;, the superkey can be the target of foreign key constraints in other tables. But I'm not certain that's what you were looking for.

AUTO_INCREMENT in sqlite problem with python

I am using sqlite with python 2.5. I get a sqlite error with the syntax below. I looked around and saw AUTOINCREMENT on this page http://www.sqlite.org/syntaxdiagrams.html#column-constraint but that did not work either. Without AUTO_INCREMENT my table can be created.
An error occurred: near "AUTO_INCREMENT": syntax error
CREATE TABLE fileInfo
(
fileId int NOT NULL AUTO_INCREMENT,
name varchar(255),
status int NOT NULL,
PRIMARY KEY (fileId)
);
This is addressed in the SQLite FAQ. Question #1.
Which states:
How do I create an AUTOINCREMENT
field?
Short answer: A column declared
INTEGER PRIMARY KEY will
autoincrement.
Here is the long answer: If you
declare a column of a table to be
INTEGER PRIMARY KEY, then whenever you
insert a NULL into that column of the
table, the NULL is automatically
converted into an integer which is one
greater than the largest value of that
column over all other rows in the
table, or 1 if the table is empty. (If
the largest possible integer key,
9223372036854775807, then an unused
key value is chosen at random.) For
example, suppose you have a table like
this:
CREATE TABLE t1( a INTEGER PRIMARY
KEY, b INTEGER ); With this table,
the statement
INSERT INTO t1 VALUES(NULL,123); is
logically equivalent to saying:
INSERT INTO t1 VALUES((SELECT max(a)
FROM t1)+1,123); There is a function
named sqlite3_last_insert_rowid()
which will return the integer key for
the most recent insert operation.
Note that the integer key is one
greater than the largest key that was
in the table just prior to the insert.
The new key will be unique over all
keys currently in the table, but it
might overlap with keys that have been
previously deleted from the table. To
create keys that are unique over the
lifetime of the table, add the
AUTOINCREMENT keyword to the INTEGER
PRIMARY KEY declaration. Then the key
chosen will be one more than than the
largest key that has ever existed in
that table. If the largest possible
key has previously existed in that
table, then the INSERT will fail with
an SQLITE_FULL error code.
It looks like AUTO_INCREMENT should be AUTOINCREMENT see http://www.sqlite.org/syntaxdiagrams.html#column-constraint
You could try
CREATE TABLE fileInfo
(
fileid INTEGER PRIMARY KEY AUTOINCREMENT,
name STRING,
status INTEGER NOT NULL
);
We just changed the order from
NOT NULL, AUTO_INCREMENT
to
AUTO_INCREMENT NOT NULL,
an example :
cursor.execute("CREATE TABLE users(\
user_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\
user_name VARCHAR(100) NOT NULL)")

Categories

Resources