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

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.

Related

How to One to One relation sqlite3 python

This is the relation I want to create for my quiz app and im using python
Module:
c.execute("""CREATE TABLE Questions (
mod_id INTEGER PRIMARY KEY,
mod_name TEXT NOT NULL
)""")
Question:
c.execute("""CREATE TABLE Questions (
quest_id INTEGER PRIMARY KEY,
quest_name TEXT NOT NULL,
mod_id INTEGER NOT NULL,
FOREIGN KEY (mod_id)
REFERENCES Modules (mod_id)
)""")
Now Since the each feedback correspont to 1 question, how do i sort of create one to one relationship? should I do the same as I did for the question table? would this be handle automatically by sqlite3??
Appreciate all sort of help Thanks!!!
EDIT: Does my feedback table need to have a primary key?? I think no because when accesing the feeback table to delete or add data we just pass the question ID as the parameter to look that row up.

Error: Duplicate foreign key constraint name

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

Django datetime primary key doesn't constrain unique

So, here's my model:
class MyModel(models.Model):
timestamp = models.DateTimeField(primary_key=True)
fielda = models.TextField()
When I call syncdb, django doesn't add a constraint to postgresql for timestamp to be unique, even though it gives it the primary key constraint.
If I change timestamp to just unique=True, django creates the unique constraint. However, if I combine unique=True and primary_key=True, django doesn't create the unique constraint.
My info:
django-south v1.8
django 1.4
python 2.7
postgresql 9.1
Edit:
If I save a model with the same exact timestamp twice in two different runs (not the same process), it doesn't raise and IntegrityError like it should. But when it creates the unique constraint and no primary key, it does with the same code.
Edit 2:
This is the code that runs when I have CONSTRAINT "MyModel_pkey" PRIMARY KEY ("timestamp") in postgresql from just having timestamp = models.DateTimeField(primary_key=True)
timestamp = datetime.datetime(2013, 7, 31, 0, 0, 0).replace(tzinfo=utc)
print timestamp # prints 2013-07-31 00:00:00+00:00
row = MyModel(timestamp=timestamp, fielda='test')
row.save()
When run twice in a row, it doesn't raise an IntegrityError. However, with the unique=True and not primary_key=True, it does raise an IntegrityError.
Maybe the example from the docs can bring some light into your question
Technically, a primary key constraint is simply a combination of a
unique constraint and a not-null constraint. So, the following two
table definitions accept the same data:
CREATE TABLE products (
product_no integer UNIQUE NOT NULL,
name text,
price numeric );
CREATE TABLE products (
product_no integer PRIMARY KEY,
name text,
price numeric );
[...] A primary key indicates that a column or group of columns can be
used as a unique identifier for rows in the table [...] Adding a
primary key will automatically create a unique btree index on the
column or group of columns used in the primary key. [...]
Ricola3D linked me to the same question (that's answered) that explains my problem.
Answered Question

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