Postgresql. Create function get_ticket - postgresql

Create a function to Get Ticket (for a Reservation).Ticket a booked reservation when the passenger pays the total amount.
Create a trigger, called line disruption, that adjusts all the tickets to the immediate next line when a line is closed due to an accident or maintenance, unless the customer specified no substitutions/adjustments in which case the ticket is canceled.
I created the tables, but I have some mistakes on my function: Please show me the mistakes and explain your solutions.
CREATE OR REPLACE FUNCTION get_ticket (reservation_id int, id int, price int)
RETURNS SETOF ticket
AS $$
BEGIN
INSERT INTO Ticket (ticket_id, reservation_id, price);
END;
$$ LANGUAGE plpgsql;
CREATE TABLE Customer (
id int PRIMARY KEY,
fname varchar,
lname varchar,
street varchar,
town varchar,
postal_code varchar
);
CREATE TABLE Station (
id int PRIMARY KEY,
name varchar,
open_time varchar,
close_time varchar,
stop_delay int,
street varchar,
town varchar,
postal_code varchar
);
CREATE TABLE Train (
id int PRIMARY KEY,
name varchar,
description varchar,
seat_avail int,
top_speed int,
cost_per_km int
);
CREATE TABLE Rail_Line (
line_id int PRIMARY KEY,
speed_limit int
);
CREATE TABLE Passes_Thru_SRL (
line_id int PRIMARY KEY,
station_id int PRIMARY KEY,
distance int,
CONSTRAINT FK1_SRL FOREIGN KEY (line_id) REFERENCES Rail_Line (line_id) ON DELETE CASCADE,
CONSTRAINT FK2_SRL FOREIGN KEY (station_id) REFERENCES Station (id) ON DELETE CASCADE
);
CREATE TABLE Route (
route_id int PRIMARY KEY
);
CREATE TABLE Passes_Thru_SR (
route_id int PRIMARY KEY,
station_id int PRIMARY KEY,
stops bool,
CONSTRAINT FK1_SR FOREIGN KEY (route_id) REFERENCES Route (route_id) ON DELETE CASCADE,
CONSTRAINT FK2_SR FOREIGN KEY (station_id) REFERENCES Station (id) ON DELETE CASCADE
);
CREATE TABLE Route_Schedule (
route_id int PRIMARY KEY,
day varchar,
time varchar,
train_id int PRIMARY KEY,
CONSTRAINT FK1_RS FOREIGN KEY (route_id) REFERENCES Route (route_id) ON DELETE CASCADE,
CONSTRAINT FK2_RS FOREIGN KEY (train_id) REFERENCES Train (id) ON DELETE CASCADE
);
CREATE TABLE Reservation (
reservation_id int PRIMARY KEY,
price int PRIMARY KEY,
id int,
CONSTRAINT FK_RS FOREIGN KEY (id) REFERENCES Customer (id) ON DELETE CASCADE
);
CREATE TABLE Ticket (
ticket_id int PRIMARY KEY,
reservation_id int,
id int, price int,
CONSTRAINT FK_RS1 FOREIGN KEY (reservation_id) REFERENCES Reservation (reservation_id) ON DELETE CASCADE,
CONSTRAINT FK_RS2 FOREIGN KEY (id) REFERENCES Customer (id) ON DELETE CASCADE,
CONSTRAINT FK_RS3 FOREIGN KEY (price) REFERENCES Reservation (price) ON DELETE CASCADE
);

Related

What is wrong with this Query ? PostgreSQL

I want to create 3 tables and join them with foreign keys. Unfortunately, it doesn't work and I have no idea where is a mistake.
CREATE TABLE Students (
Student_Id SERIAL PRIMARY KEY,
Name VARCHAR (20) NOT NULL,
Surname VARCHAR (30) NOT NULL,
Date_of_Birth DATE NOT NULL,
Phone INT NOT NULL UNIQUE,
Email VARCHAR(225) NOT NULL UNIQUE,
Course_Id INT
FOREIGN KEY (Course_Id) REFERENCES Course (Course_Id)
);
CREATE TABLE Course (
Course_Id SERIAL PRIMARY KEY,
Student_Id INT NOT NULL,
Teacher_Id INT NOT NULL,
Category VARCHAR (30) NOT NULL,
FOREIGN KEY (Student_Id) REFERENCES Students (Student_Id)
);
CREATE TABLE Teachers (
Teacher_Id SERIAL PRIMARY KEY,
Name VARCHAR (20) NOT NULL,
Surname VARCHAR (30) NOT NULL,
Phone INT NOT NULL UNIQUE,
Salary INT NOT NULL,
Course_Id INT NOT NULL,
FOREIGN KEY (Teacher_Id) REFERENCES Course (Teacher_Id)
);
I should create a Foreign Key to join all three tables.
I get this error every time: relation "course" does not exist
I can't find where is the mistake. Please help.
It appears like you are attempting to crate a many-to-many (M:M) between Students and Teachers with Course as the resolution table. You are close, however, your definition sets up bi-directional relationships. This is normally not necessary. Define Students and Teachers without the FK to Course. Then define Course with a FK to each.
create table students (
student_id serial primary key
, name varchar (20) not null
, surname varchar (30) not null
, date_of_birth date not null
, phone int not null unique
, email varchar(225) not null unique
);
create table teachers (
teacher_id serial primary key
, name varchar (20) not null
, surname varchar (30) not null
, phone int not null unique
, salary int not null
);
create table course (
course_id serial primary key
, student_id int not null
, teacher_id int not null
, category varchar (30) not null
, foreign key (student_id) references students (student_id)
, foreign key (teacher_id) references teachers (teacher_id)
, unique (student_id, teacher_id)
);
If you must define bi-directional FK in Students and Teachers then create the tables without the FK then use alter table after Course is defined to add the FK and make them DEFERRABLE INITIALLY DEFERRED. Necessary for eventual Inserts.
alter table teachers add column course_id int references course(course_id) deferrable initially deferred;
alter table students add column course_id int references course(course_id) deferrable initially deferred;

sql error - no unique constraint matching keys

for some reason i am getting there is no unique constraint matching given keys for referenced table "accident_location". I am using postgresql to create the table. what is the error here? as i have set the primary key of ID and address_ID on my accident_location table
CREATE TABLE IF NOT EXISTS Accident(
ID varchar(10) NOT NULL,
Severity INT,
Start_Time varchar(100) NOT NULL,
End_Time varchar(100) NOT NULL,
Description varchar(100),
PRIMARY KEY(ID)
);
CREATE TABLE IF NOT EXISTS Accident_Location(
ID varchar(10),
Address_ID INT,
Start_lat float,
Start_Lng float,
End_Lat float,
End_Lng float,
"Distance(mi)" float,
PRIMARY KEY (ID,Address_ID),
FOREIGN KEY (ID) REFERENCES Accident(ID)
);
CREATE TABLE IF NOT EXISTS Address(
Address_ID INT,
Number INT,
Street varchar(100),
Side varchar(5) ,
City varchar(50) NOT NULL,
County varchar(50) ,
State varchar(10) NOT NULL,
Zipcode varchar(15) NOT NULL,
Country varchar(5) ,
Timezone varchar(30) ,
Airport_code varchar(10),
Location_ID INT NOT NULL,
Weather_ID INT NOT NULL,
PRIMARY KEY (Address_ID),
FOREIGN KEY (Address_ID) REFERENCES Accident_Location(Address_ID)
);
The referenced Address_ID on the Address table should be unique on table Accident_Location.
Change Accident_Location table to
CREATE TABLE IF NOT EXISTS Accident_Location(
ID varchar(10),
Address_ID INT constraint unx_addres_id_location unique,
Start_lat float,
Start_Lng float,
End_Lat float,
End_Lng float,
"Distance(mi)" float,
PRIMARY KEY (ID,Address_ID),
FOREIGN KEY (ID) REFERENCES Accident(ID)
);
Here, I've added a unique constraint on Address_ID
Address_ID INT constraint unx_addres_id_location unique
UPDATED
Since you are referring to Address_ID of Accident_Location table as a foreign key on the Address table, this will force you to make it a unique record. That means any two rows or more should not have the same value of Address_ID. Otherwise, the foreign key Address_ID on the Address table wouldn't know which row you are referring to.
The reason you are not seeing this same error for the Accident table is that by default primary keys are unique.

Find cause of error "constraint xxxx is not a foreign key constraint" in Postgresql

I have defined these tables:
CREATE TABLE "public".category (id BIGSERIAL NOT NULL, name varchar(255) NOT NULL, PRIMARY KEY (id));
CREATE UNIQUE INDEX category_name ON "public".category (name);
CREATE TABLE "public".clusters (id BIGSERIAL NOT NULL, name varchar(255) NOT NULL, PRIMARY KEY (id));
CREATE INDEX clusters_name ON "public".clusters (name);
CREATE TABLE "public".keywords (id BIGSERIAL NOT NULL, text varchar(255) NOT NULL, category_id int8 NOT NULL, top_results int4, cluster_id int8, month_requests int4, click_cost float8, PRIMARY KEY (id));
CREATE INDEX keywords_text ON "public".keywords (text);
ALTER TABLE "public".keywords ADD CONSTRAINT FKkeywords488682 FOREIGN KEY (cluster_id) REFERENCES "public".clusters (id);
ALTER TABLE "public".keywords ADD CONSTRAINT FKkeywords446526 FOREIGN KEY (category_id) REFERENCES "public".category (id) ON UPDATE CASCADE ON DELETE CASCADE;
added one record to category table:
INSERT INTO "public".category(id, name) VALUES (1, 'Test');
And now when I try to add record to keyword table
insert into "public"."keywords" ( "category_id", "text") values ( 1, 'testkey')
I got error:
ERROR: constraint 16959 is not a foreign key constraint
When I do
select * FROM pg_constraint;
I can't see constraint with this id. I can't understand what is the cause of this problem.

'there is no unique constraint matching given keys for referenced table' where i dont want something to be unique

In Postgres I have written the following code:
CREATE TABLE students (
student_id BIGINT PRIMARY KEY,
first_name VARCHAR(15),
surname VARCHAR(35),
enrollment_year INT);
CREATE TABLE teachers (
bsn BIGINT PRIMARY KEY,
first_name VARCHAR(15),
surname VARCHAR(35),
salary REAL,
scale INT,
CONSTRAINT salary CHECK(salary < (25 * scale) AND salary > (20 * scale))
);
CREATE TABLE course (
course_code VARCHAR(10) PRIMARY KEY,
course_name VARCHAR(20) UNIQUE,
study_points INT);
CREATE TABLE study_program (
course_name VARCHAR(20) PRIMARY KEY,
level VARCHAR(15),
duration VARCHAR(10),
FOREIGN KEY(course_name) REFERENCES course(course_name));
CREATE TABLE assignment (
assignment_code VARCHAR(10) UNIQUE,
course_name VARCHAR(20),
PRIMARY KEY(assignment_code, course_name),
FOREIGN KEY(course_name) REFERENCES course(course_name)
);
CREATE TABLE records (
student_id BIGINT,
course_name VARCHAR(20),
PRIMARY KEY(student_id, course_name),
FOREIGN KEY(student_id) REFERENCES students(student_id),
FOREIGN KEY(course_name) REFERENCES course(course_name));
CREATE TABLE make (
student_id BIGINT,
assignment_code VARCHAR(20),
PRIMARY KEY(student_id, assignment_code),
FOREIGN KEY(student_id) REFERENCES students(student_id),
FOREIGN KEY(assignment_code) REFERENCES assignment(assignment_code));
CREATE TABLE prerequisit (
assignment_code VARCHAR(20),
course_name VARCHAR(20),
PRIMARY KEY(assignment_code, course_name),
FOREIGN KEY(assignment_code) REFERENCES assignment(assignment_code),
FOREIGN KEY(course_name) REFERENCES course(course_name)
);
CREATE TABLE records_2 (
assignment_code VARCHAR(20),
course_name VARCHAR(20),
bsn BIGINT,
mandatory BOOLEAN,
year INT,
week INT,
PRIMARY KEY(assignment_code, course_name),
FOREIGN KEY(assignment_code) REFERENCES assignment(assignment_code),
FOREIGN KEY(course_name) REFERENCES course(course_name)
);
CREATE TABLE designes (
course_code VARCHAR(15),
bsn BIGINT,
study_points INT,
course_name VARCHAR(20),
PRIMARY KEY(course_code, bsn),
FOREIGN KEY(course_code) REFERENCES course(course_code),
FOREIGN KEY(bsn) REFERENCES teachers(bsn),
FOREIGN KEY(study_points) REFERENCES course(study_points),
FOREIGN KEY(course_name) REFERENCES course(course_name)
);
CREATE TABLE reviews (
bsn BIGINT PRIMARY KEY,
course_code VARCHAR(15),
study_points INT,
course_name VARCHAR(20),
FOREIGN KEY(bsn) REFERENCES teachers(bsn),
FOREIGN KEY(course_code) REFERENCES course(course_code),
FOREIGN KEY(study_points) REFERENCES course(study_points),
FOREIGN KEY(course_name) REFERENCES course(course_name)
);
The error I get is
ERROR: there is no unique constraint matching given keys for referenced table "course"
This error is fixed by adding the UNIQUE constraint to study points, however I do not want study points to be unique because I need different courses to have the same amount of study points.
Referencing study_points makes no sense whatsoever. In fact referencing three different columns of a single table makes no sense whatsoever.
You only need FOREIGN KEY(course_code) REFERENCES course(course_code) and you don't need the columns course_name and study_points in the reviews table as they are implicitly defined through the foreign key to the course table.
Which means the table should look something like this:
CREATE TABLE reviews
(
bsn BIGINT PRIMARY KEY,
course_code VARCHAR(15),
FOREIGN KEY(bsn) REFERENCES teachers(bsn),
FOREIGN KEY(course_code) REFERENCES course(course_code)
);
Which then begs the question: what is that table supposed to do? You can only have a single row per teacher in there because bsn is the primary key (thus can't be repeated). So that is a one-to-one (or one-to-zero/one) relationship. Which in turn means you could move the column course_code to the teachers table, e.g. as reviewed_course.
However, I guess you meant to create a many-to-many relationship between teachers and course which then should be something like this:
CREATE TABLE reviews
(
bsn BIGINT,
course_code VARCHAR(15),
primary key (bsn, course_code),
FOREIGN KEY(bsn) REFERENCES teachers(bsn),
FOREIGN KEY(course_code) REFERENCES course(course_code)
);
That makes the combination of bsn and course_code unique. Which means each teacher can review each course exactly once, but a teacher can review multiple courses and a single course can be reviewed by multiple teachers.

Many to many to many relationships with EF4 and Code First

I've got a problem I can't figure out how to express with CTP5 of Code First and EF4.
EDIT: Added my old schema at the bottom that I'd like to replicate through CF
Here's my specific scenario:
A Team is an abstract concept; it should exist with a specific set of players, in a specific division, in a specific season.
A concrete example of this in action from the NFL:
1996 (season) AFC Central (division) Houston Oilers (team)
1997 (season) AFC Central (division) Tennessee Oilers (team)
1999 (season) AFC Central (division) Tennessee Titans (team)
2002 (season) AFC South (division) Tennessee Titans (team)
These are all the same team. I want to be able to do the following:
// Titans team id = 17
var myTeam = myContext.Teams.Single(t => t.Id == 17)
// display players
foreach (var p in myTeam.Seasons[1999].Players)
{
// Do something with the p here
}
// Display current division
Response.Write(myTeam.Seasons[2002].Division.Name);
I'm not sure of the specific query syntax within an ICollection member variable of myTeam.Seasons, but the concept should be the same none the less.
Can anyone shed some light on how you'd express this concept through CF in EF4 CF CTP5?
How would you express this through Code First?
Current SQL tables
CREATE TABLE dbo.Season
(
Id INT IDENTITY(1,1) NOT NULL,
LeagueId INT NOT NULL,
[Name] NVARCHAR(50) NOT NULL,
[Year] CHAR(4) NOT NULL,
PrevSeasonId INT NULL
) ON [PRIMARY];
// Primary key
ALTER TABLE dbo.Season WITH NOCHECK ADD
CONSTRAINT PK_Season PRIMARY KEY NONCLUSTERED (Id) ON [PRIMARY];
CREATE TABLE dbo.Division
(
Id INT IDENTITY(1,1) NOT NULL,
DefaultName NVARCHAR(50) NOT NULL
) ON [PRIMARY];
// Primary key
ALTER TABLE dbo.Division WITH NOCHECK ADD
CONSTRAINT PK_Division PRIMARY KEY NONCLUSTERED (Id) ON [PRIMARY];
// Key Relation Table
CREATE TABLE dbo.DivisionsInSeason
(
DivisionId INT NOT NULL,
SeasonId INT NOT NULL,
DefaultName NVARCHAR(50) NOT NULL,
Commissioner UNIQUEIDENTIFIER NOT NULL,
ParentDivId INT NULL
) ON [PRIMARY];
// Primary Key
ALTER TABLE dbo.DivisionsInSeason WITH NOCHECK ADD
CONSTRAINT PK_DivisionsInSeason PRIMARY KEY NONCLUSTERED (DivisionId, SeasonId) ON [PRIMARY] ;
// Foreign Keys
ALTER TABLE dbo.DivisionsInSeason WITH CHECK ADD
CONSTRAINT FK_DivisionsInSeason_Division FOREIGN KEY(DivisionId) REFERENCES dbo.Division(Id),
CONSTRAINT FK_DivisionsInSeason_Season FOREIGN KEY(SeasonId) REFERENCES dbo.Season(Id),
CONSTRAINT FK_DivisionsInSeason_User FOREIGN KEY(Commissioner) REFERENCES dbo.[User](Id);
CREATE TABLE dbo.Team
(
Id INT IDENTITY(1,1) NOT NULL,
DefaultName NVARCHAR(50) NOT NULL,
DefShortName NCHAR(3) NULL
) ON [PRIMARY];
// Primary key
ALTER TABLE dbo.Team WITH NOCHECK ADD
CONSTRAINT PK_Team PRIMARY KEY NONCLUSTERED (Id) ON [PRIMARY] ;
// Key relationship table
CREATE TABLE dbo.TeamsInDivision
(
TeamId INT NOT NULL,
DivisionId INT NOT NULL,
SeasonId INT NOT NULL,
GeneralManager UNIQUEIDENTIFIER NOT NULL,
Name NVARCHAR(50) NOT NULL,
ShortName NCHAR(3) NULL
) ON [PRIMARY];
// Check Constraints
ALTER TABLE dbo.TeamsInDivision ADD
CONSTRAINT PK_TeamsInDivision PRIMARY KEY NONCLUSTERED (TeamId, DivisionId, SeasonId) ON [PRIMARY];
// Foreign Keys
ALTER TABLE dbo.TeamsInDivision WITH CHECK ADD
CONSTRAINT FK_TeamsInDivision_Team FOREIGN KEY(TeamId) REFERENCES dbo.Team(Id),
CONSTRAINT FK_TeamsInDivision_Division FOREIGN KEY(DivisionId) REFERENCES dbo.Division(Id),
CONSTRAINT FK_TeamsInDivision_Season FOREIGN KEY(SeasonId) REFERENCES dbo.Season(Id),
CONSTRAINT FK_TeamsInDivision_User FOREIGN KEY(GeneralManager) REFERENCES dbo.[User](Id);
Maybe this could be usefull
http://blogs.microsoft.co.il/blogs/gilf/archive/2011/08/01/creating-a-many-to-many-mapping-using-code-first.aspx