postgreSQL syntax error at or near "foreign" - postgresql

I get the following error of "syntax error at or near "foreign"" when trying to create kurinys table. Might be a silly mistake but I can't recognize it. Thank you in advance.
create table elba7430.kurinys(
id INTEGER not null check (id > 10000),
pavadinimas VARCHAR (55) not null,
metai YEAR,
meno_rusies_id INTEGER not null check (meno_rusies_id > 100),
autoriaus_id INTEGER not null check (autoriaus_id > 1000000),
kliento_id INTEGER not null check (kliento_id > 1000000),
ilgis_cm DECIMAL (100,2),
plotis_cm DECIMAL (100,2),
kaina DECIMAL (100,2),
primary key (id),
foreign key (meno_rusies_id)
REFERENCES elba7430.meno_rusis on delete cascade on update restrict,
foreign key (autoriaus_id)
REFERENCES elba7430.autorius on delete cascade on update restrict,
foreign key (kliento_id)
REFERENCES elba7430.klientas on delete cascade on update restrict
);
create table elba7430.meno_rusis(
id INTEGER not null check (id > 100),
pavadinimas VARCHAR (100) not null,
primary key(id)
);
create table elba7430.autorius(
id INTEGER not null check (id > 1000000),
vardas VARCHAR (40) not null,
pavarde VARCHAR (55) not null,
gimimo_metai DATE,
primary key(id)
);
create table elba7430.klientas(
id INTEGER not null check (id > 1000000),
vardas VARCHAR (40),
pavarde VARCHAR (55),
primary key(id)
);

Changing the order of your declarations and replacing the year data type by a valid one will solve this issue, here you can replicate this: db<>fiddle

Related

Postgres violates not null constraint, even when there isn't one

Hey I have a Postgres database that has a Schema with
CREATE TABLE Mentor (
mentor_ID serial unique,
person_ID serial not null unique,
career_history varchar(255) not null,
preferred_communication varchar(50) not null,
mentoring_preference varchar(50) not null,
linked_in varchar(100) not null,
capacity int not null,
feedback_rating int,
feeback_comment varchar(255),
PRIMARY KEY (mentor_ID),
CONSTRAINT fk_person FOREIGN KEY (person_ID) REFERENCES Person(person_ID)
);
CREATE TABLE Mentee(
mentee_ID integer not null unique,
mentor_ID serial references Mentor(mentor_ID),
person_ID serial not null unique,
study_year int,
motivation varchar(50),
interests varchar(255),
random_match boolean default false,
PRIMARY KEY (mentee_ID),
CONSTRAINT fk_person FOREIGN KEY (person_ID) REFERENCES Person(person_ID)
);
With this, i expect to be able to enter null values for mentor_ID in my database but when I enter the query
insert into mentee(mentee_ID, mentor_ID, person_ID) VALUES (12313, null, 1)
I get the violation
ERROR: null value in column "mentor_id" of relation "mentee" violates not-null constraint
I was wondering how I could make it so I can insert null values for mentor_ID? I dont have it as not null in the table but it still says violating not null constraint.
Thank you
Because serial is not null.
serial is...
CREATE SEQUENCE tablename_colname_seq AS integer;
CREATE TABLE tablename (
colname integer NOT NULL DEFAULT nextval('tablename_colname_seq')
);
ALTER SEQUENCE tablename_colname_seq OWNED BY tablename.colname;
Note the integer not null. This is because serial is to be used for primary keys, not foreign keys. Foreign keys are always assigned, they don't need to auto increment.
Use a plain integer.
mentor_ID integer references Mentor(mentor_ID)
Same for your other foreign keys.
Notes:
identity is the SQL standard way to do auto incremented primary keys.
You don't need to declare primary keys as unique, primary keys are already unique.
Unless there's a specific reason to constrain the size of a text field, use text. varchar and text only use the necessary amount of space for each row. "foo" will take the same amount of space in varchar(10) as in varchar(255). For example, there's no particular reason to limit the size of their linked in nor motivation.

Execute procedure automatically

I have this table
create table preƱadas(
hierro varchar(15) NOT NULL,
hierro_toro varchar (30) NOT NULL,
fecha_esperada_parto timestamp,
observaciones varchar(200),
primary key (hierro),
foreign key (hierro) references animales,
foreign key (hierro_toro) references animales (hierro)
);
i would like to eliminate a record automatically from it when now() is one month past fecha_esperada_parto
Any ideas how to do it?

Error Code: 1822. Failed to add the foreign key constraint. Missing index for constraint 'questions_ibfk_1' in the referenced table 'category'

cannot add foreign key constraint to table
create table users
(
user_id int auto_increment primary key not null,
username varchar(50) unique null ,
email varchar(50) unique ,
passwords varchar(50) not null,
login_status boolean not null
);
create table category (
category_id int primary key not null,
category_name varchar(50) not null
);
create table answers (
id_answer int auto_increment primary key not null,
answer boolean not null
);
create table questions (
question_id int primary key not null,
category_name varchar(50) not null,
content varchar(50) not null ,
foreign key (category_name) references category (category_name)
);
You get this error because there's no index on category_name in the category table. Change that CREATE statement as follows:
create table category (
category_id int primary key not null,
category_name varchar(50) not null,
KEY category_name_index (category_name)
);
From the docs (8.0 version, but the statement is true for older versions):
MySQL requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan. In the referencing table, there must be an index where the foreign key columns are listed as the first columns in the same order. Such an index is created on the referencing table automatically if it does not exist. This index might be silently dropped later, if you create another index that can be used to enforce the foreign key constraint. index_name, if given, is used as described previously.
Also, you're using a varchar(50) as your foreign key, which is not usually a great idea for a variety of reasons. You probably want to use a numeric value, such as category_id, instead.

NetBeans Generated REST Service works for XML requests, but not JSON

I am using NetBeans to help me build a REST web service. My steps taken have been the following:
New Project -> Web Application
New File -> Web Service -> RESTFul WebService from Database
Select the Datasource (which is a MySQL DB)
Everything generates, right click on project -> Test RESTFul
WebServices
When I want to test GET(application/XML), I can get a result returned fine, I can also get an XML response from a Jersey Client I made after the fact. But when I test the JSON functions, I always seem to get errors:
exception
javax.servlet.ServletException: org.glassfish.jersey.server.ContainerException: java.lang.NoClassDefFoundError: Could not initialize class org.eclipse.persistence.jaxb.BeanValidationHelper
root cause
org.glassfish.jersey.server.ContainerException:
java.lang.NoClassDefFoundError: Could not initialize class
org.eclipse.persistence.jaxb.BeanValidationHelper
root cause
java.lang.NoClassDefFoundError: Could not initialize class org.eclipse.persistence.jaxb.BeanValidationHelper
My Database schema, which would really be the only thing I've written myself, is the following:
-- ****************** SqlDBM: MySQL ******************;
-- ***************************************************;
DROP TABLE `roles`;
DROP TABLE `orders`;
DROP TABLE `inventory`;
DROP TABLE `users`;
DROP TABLE `warehouses`;
DROP TABLE `inventory`;
DROP TABLE `addresses`;
DROP TABLE `products`;
-- ************************************** `addresses`
CREATE TABLE `addresses`
(
`addressID` INTEGER NOT NULL AUTO_INCREMENT ,
`streetNum` INTEGER NOT NULL ,
`streetName` VARCHAR(45) NOT NULL ,
`unitNum` INTEGER ,
`city` VARCHAR(45) NOT NULL ,
`province` VARCHAR(45) NOT NULL ,
`postalCode` VARCHAR(6) NOT NULL ,
PRIMARY KEY (`addressID`)
);
-- ************************************** `products`
CREATE TABLE `products`
(
`productID` INTEGER NOT NULL AUTO_INCREMENT ,
`productNO` VARCHAR(40) NOT NULL ,
`productName` VARCHAR(80) NOT NULL ,
`productDesc` VARCHAR(160) NOT NULL ,
`cost` REAL NOT NULL ,
`price` REAL NOT NULL ,
PRIMARY KEY (`productID`)
);
-- ************************************** `users`
CREATE TABLE `users`
(
`userID` INTEGER NOT NULL AUTO_INCREMENT ,
`firstName` VARCHAR(20) NOT NULL ,
`lastName` VARCHAR(20) NOT NULL ,
`dateOfBirth` DATE NOT NULL ,
`email` VARCHAR(45) NOT NULL ,
`password` CHAR(64) NOT NULL ,
`addressID` INTEGER NOT NULL ,
PRIMARY KEY (`userID`),
KEY `fkIdx_87` (`addressID`),
CONSTRAINT `FK_87` FOREIGN KEY `fkIdx_87` (`addressID`) REFERENCES `addresses` (`addressID`)
);
-- ************************************** `warehouses`
CREATE TABLE `warehouses`
(
`warehouseID` INTEGER NOT NULL AUTO_INCREMENT ,
`addressID` INTEGER NOT NULL ,
PRIMARY KEY (`warehouseID`),
KEY `fkIdx_58` (`addressID`),
CONSTRAINT `FK_58` FOREIGN KEY `fkIdx_58` (`addressID`) REFERENCES `addresses` (`addressID`)
);
-- ************************************** `inventory`
CREATE TABLE `inventory`
(
`id` INTEGER NOT NULL AUTO_INCREMENT ,
`productID` INTEGER NOT NULL ,
`warehouseID` INTEGER NOT NULL ,
`expiry` DATE NOT NULL ,
`productID_1` INTEGER NOT NULL ,
PRIMARY KEY (`id`),
KEY `fkIdx_31` (`productID_1`),
CONSTRAINT `FK_31` FOREIGN KEY `fkIdx_31` (`productID_1`) REFERENCES `products` (`productID`)
);
-- ************************************** `roles`
CREATE TABLE `roles`
(
`roleID` INTEGER NOT NULL AUTO_INCREMENT ,
`roleName` VARCHAR(20) NOT NULL ,
`userID` INTEGER NOT NULL ,
PRIMARY KEY (`roleID`),
KEY `fkIdx_96` (`userID`),
CONSTRAINT `FK_96` FOREIGN KEY `fkIdx_96` (`userID`) REFERENCES `users` (`userID`)
);
-- ************************************** `orders`
CREATE TABLE `orders`
(
`orderID` INTEGER NOT NULL AUTO_INCREMENT ,
`orderNum` INTEGER NOT NULL ,
`productID` INTEGER NOT NULL ,
`quantity` INTEGER NOT NULL ,
`userID` INTEGER NOT NULL ,
PRIMARY KEY (`orderID`),
KEY `fkIdx_70` (`productID`),
CONSTRAINT `FK_70` FOREIGN KEY `fkIdx_70` (`productID`) REFERENCES `products` (`productID`),
KEY `fkIdx_100` (`userID`),
CONSTRAINT `FK_100` FOREIGN KEY `fkIdx_100` (`userID`) REFERENCES `users` (`userID`)
);
-- ************************************** `inventory`
CREATE TABLE `inventory`
(
`id` INTEGER NOT NULL AUTO_INCREMENT ,
`expiry` DATE ,
`productID` INTEGER NOT NULL ,
`warehouseID` INTEGER NOT NULL ,
PRIMARY KEY (`id`),
KEY `fkIdx_40` (`productID`),
CONSTRAINT `FK_40` FOREIGN KEY `fkIdx_40` (`productID`) REFERENCES `products` (`productID`),
KEY `fkIdx_62` (`warehouseID`),
CONSTRAINT `FK_62` FOREIGN KEY `fkIdx_62` (`warehouseID`) REFERENCES `warehouses` (`warehouseID`)
);

Postgres before insert trigger using sequence from another table

Using Postgres, what I would like to achieve is to be able to have many different instrument types, with corresponding [TYPE].instrument tables, which all have a unique ID in the table, but also reference a unique ID in the instrument.master table. I have the following:
create schema instrument
CREATE TABLE instrument.type (
id smallserial NOT NULL,
name text not null,
code text not null,
CONSTRAINT pk_instrument_type PRIMARY KEY (id)
);
ALTER TABLE instrument.type ADD CONSTRAINT unq_instrument_type_code UNIQUE(code);
ALTER TABLE instrument.type ADD CONSTRAINT unq_instrument_type_name UNIQUE(name);
insert into instrument.type (name, code) values ('futures', 'f');
CREATE TABLE instrument.master (
id serial NOT NULL,
type smallint not null references instrument.type (id),
timestamp timestamp with time zone not null,
CONSTRAINT pk_instrument_master PRIMARY KEY (id)
);
CREATE TABLE futures.definition (
id smallserial NOT NULL,
code text not null,
CONSTRAINT pk_futures_definition PRIMARY KEY (id)
);
ALTER TABLE futures.definition ADD CONSTRAINT unq_futures_definition_code UNIQUE(code);
insert into futures.definition (code) values ('ED');
CREATE TABLE futures.instrument (
id smallserial NOT NULL,
master serial not null references instrument.master (id),
definition smallint not null references futures.definition (id),
month smallint not null,
year smallint not null,
CONSTRAINT pk_futures_instrument PRIMARY KEY (id),
check (month >= 1),
check (month <= 12),
check (year >= 1900)
);
ALTER TABLE futures.instrument ADD CONSTRAINT unq_futures_instrument UNIQUE(definition, month, year);
CREATE OR REPLACE FUNCTION trigger_master_futures()
RETURNS trigger AS
$BODY$
BEGIN
insert into instrument.master (type, timestamp)
select id, current_timestamp from instrument.type where code = 'f';
NEW.master := currval('instrument.master_id_seq');
RETURN NEW;
END;
$BODY$
LANGUAGE 'plpgsql' VOLATILE;
create trigger trg_futures_instrument before insert on futures.instrument
for each row
execute procedure trigger_master_futures();
I then test with:
insert into futures.instrument (definition, month, year)
select id, 3, 2015 from futures.definition where code = 'ED';
Everything works almost as I would like it to. The only issue is that somehow, instrument.master.id ends up being one more than futures.instrument.master. I am not sure what I need to do to achieve the behavior I want, which is that whenever an entry is inserted into futures.instrument, an entry should be inserted into instrument.master, and the id entry of the latter should be inserted into the master entry of the former. I actually think it should have failed since the foreign key relationship is violated somehow.
As it turns out, everything was correct. The issue was that in futures.instrument, the type of the master column is serial, and it should have been int.