Hello I'm pretty new to PostgreSQL so I trying to create a one to one relationship between the tables account and bank_account - postgresql

I tried using a foreign key, but it still shows them as being separate and not connected is there something I'm missing here, my goal was to originally link the persons name to the account_balance.
CREATE TABLE accounts (
id SERIAL,
first_name VARCHAR(50),
last_name VARCHAR (50),
username VARCHAR (50),
password VARCHAR (500),
account_Type VARCHAR (10),
bday VARCHAR (50),
PRIMARY KEY(id)
);
CREATE TABLE bank_account(
id SERIAL,
account_number INTEGER PRIMARY KEY,
account_balance INTEGER,
CONSTRAINT bank_users
FOREIGN KEY (id)
REFERENCES accounts(id)
ON DELETE CASCADE
);
INSERT INTO accounts (
first_name,
last_name,
username,
password,
account_Type,
bday)
VALUES ('bob', 'john', 'bob#gmail.com', crypt('bob1',gen_salt('bf')),'Manager', '01/01/1985'),
('Tom', 'lin', 'tom#gmail.com', 'tom1', 'Manager', '5/23/1990');
INSERT INTO bank_account(
account_number,
account_balance)
VALUES ('1234', '50000'),('4332', '100000');

Related

How do you create the table structure in PostgreSQL to make a many-to-many relationship

my example so far I would like to know how to create a many to many relationship with these.
CREATE TABLE accounts (
id SERIAL,
first_name VARCHAR(50),
last_name VARCHAR (50),
username VARCHAR (50),
password VARCHAR (500),
account_Type VARCHAR (10),
bday VARCHAR (50),
PRIMARY KEY(id)
);
CREATE TABLE bank_account(
id SERIAL,
account_number INTEGER PRIMARY KEY,
account_balance INTEGER
);
you can create a table like this one:
CREATE TABLE bank_account_accounts(
id serial primary key,
accounts_id integer,
bank_account_id integer
);

PostgreSQL ERROR: relation "XXX" does not exist and unsure why

I run my code and get the error in PostgreSQL. I have created multiple tables and the first seems to work while the others don't.
create table people (
id serial,
family_names text,
given_names text,
displayed_names text,
email_address text,
primary key (id)
);
create table users (
userid integer,
website text,
date_registered date,
gender GenderValue,
birthday date,
password text,
portrait integer,
primary key (userid),
foreign key (userid) references people(id),
foreign key (portrait) references photos(photoid)
);
create table photos (
photoid serial,
title TitleValue,
date_uploaded date,
date_taken date,
description text,
technical_details text,
safety_level safetyLevel,
visibility visibilityLevel,
owns integer,
primary key (photoid),
foreign key (owns) references users(userid)
);

postgresql: constaint to have unique values across 2 tables

I have 2 tables:
CREATE TABLE public."user"
(
id integer NOT NULL DEFAULT nextval('user_id_seq'::regclass),
username character varying(256) COLLATE pg_catalog."default",
CONSTRAINT user_pkey PRIMARY KEY (id)
)
CREATE TABLE public.user_tenant
(
user_id integer NOT NULL,
tenant_id integer NOT NULL,
CONSTRAINT user_fk FOREIGN KEY (user_id)
REFERENCES public."user" (id) MATCH SIMPLE
ON UPDATE NO ACTION
ON DELETE CASCADE
)
I need to have unique values (user.username, user_tenant.tenant_id). How can I declare such a constraint?
I would make the username unique, just like the tenant that is in another table. When that is done, you can put a primary key on the user_id and tenant_id:
CREATE TABLE public."user"
(
id integer NOT NULL DEFAULT nextval('user_id_seq'::regclass),
username character varying(256) COLLATE pg_catalog."default" unique,
CONSTRAINT user_pkey PRIMARY KEY (id)
);
CREATE TABLE public.user_tenant
(
user_id integer NOT NULL,
tenant_id integer NOT NULL,
CONSTRAINT user_fk FOREIGN KEY (user_id)
REFERENCES public."user" (id) MATCH SIMPLE
ON UPDATE NO ACTION
ON DELETE CASCADE,
CONSTRAINT user_tenant_pk PRIMARY KEY (user_id, tenant_id)
);
By the way, don't use reserved names like "user" for table names.
You can create a function which can check for uniqueness across multiple tables (example here: Postgres unique combination constraint across tables) but it looks like you may need to the structure of your tables or follow Frank Heikens' answer.
EDIT:
CREATE TABLE public."user"
(
id SERIAL,
username character varying(256) COLLATE pg_catalog."default",
PRIMARY KEY (id)
);
CREATE TABLE public.user_tenant
(
user_id integer NOT NULL,
tenant_id integer NOT NULL,
CONSTRAINT user_fk FOREIGN KEY (user_id)
REFERENCES public."user" (id) MATCH SIMPLE
ON UPDATE NO ACTION
ON DELETE CASCADE
);
CREATE OR REPLACE FUNCTION public.check_user_tenant(user_id integer, tenant_id integer)
RETURNS boolean AS
$$
DECLARE b_result boolean;
BEGIN
SELECT (COUNT(*) = 0) INTO b_result
FROM public.user u
JOIN public.user_tenant ut ON ut.user_id IN (SELECT id
FROM public.user i_u
WHERE i_u.username = u.username)
WHERE u.id = $1 AND ut.tenant_id = $2;
RETURN b_result;
END
$$ LANGUAGE 'plpgsql';
ALTER TABLE public.user_tenant
ADD CONSTRAINT check_filename CHECK
(public.check_user_tenant(user_id, tenant_id));
-- Testing:
insert into public."user" (username) VALUES ('foo');
insert into public.user_tenant (user_id, tenant_id) VALUES (1,3);
insert into public."user" (username) VALUES ('foo');
-- Violates constraint:
insert into public.user_tenant (user_id, tenant_id) VALUES (2,3);

Does postgresql require unique constraint names when defining FOREIGN KEYS

Here is my schema for database tables:
CREATE TABLE users (
user_id INTEGER NOT NULL,
device_id INTEGER,
user_points INTEGER,
cookie VARCHAR,
PRIMARY KEY (user_id)
);
CREATE TABLE admins (
admin_id INTEGER NOT NULL,
username VARCHAR,
password VARCHAR
);
CREATE TABLE admin_adventure (
adventure_id INTEGER NOT NULL,
admin_id INTEGER,
PRIMARY KEY (adventure_id)
);
CREATE TABLE adventures (
adventure_id INTEGER NOT NULL,
prize_id INTEGER,
novella_id INTEGER,
PRIMARY KEY (adventure_id)
);
Here I'm trying to define FOREIGN KEYS:
ALTER TABLE admin_adventure ADD FOREIGN KEY ( admin_id ) REFERENCES admins ( admin_id );
ALTER TABLE admin_adventure ADD FOREIGN KEY ( adventure_id ) REFERENCES adventures ( adventure_id );
And here is the error I get when trying to migrate with Flyway:
ERROR: there is no unique constraint matching given keys for
referenced table "admins"
Can someone explain what I'm doing wrong and why I get this error?
The error message is complaining that you are trying to link a foreign key to a column in another table which is not unique (e.g. a primary key). Try making the admin_id column in the admins table a primary key:
CREATE TABLE admins (
admin_id INTEGER NOT NULL,
username VARCHAR,
password VARCHAR,
PRIMARY KEY (admin_id)
);
Like the documentation says:
A foreign key must reference columns that either are a primary key or form a unique constraint.
So you must either
ALTER TABLE admins ADD PRIMARY KEY (admin_id);
or
ALTER TABLE admins ADD UNIQUE (admin_id);

Postgresql Creating a Schema with tables in it

Here's my script.
CREATE SCHEMA testSchema
create table REF_PRODUCT (
id int8 not null,
created_date timestamp,
CODE varchar(255),
DESCRIPTION varchar(255),
LOCATION varchar(255),
MANUFACTURER varchar(255),
NAME varchar(255),
COST numeric(19, 2),
DEALERS_PRICE numeric(19, 2),
SUGGESTED_RETAIL_PRICE numeric(19, 2),
STOCK int4,
PRODUCT_TYPE varchar(255),
picture_id int8,
primary key (id)
)
create table TXN_LINE_ITEM (
id int8 not null,
created_date timestamp,
cancelled boolean,
cost numeric(19, 2),
dp numeric(19, 2),
itemCode varchar(255),
itemName varchar(255),
priceType varchar(255),
qty int4,
refunded boolean,
srp numeric(19, 2),
total numeric(19, 2),
transactionRecord_id int8,
primary key (id)
)
create table TXN_PRODUCT_PICTURE (
id int8 not null,
created_date timestamp,
picture bytea,
primary key (id)
)
create table TXN_TRANSACTION_RECORD (
id int8 not null,
created_date timestamp,
total numeric(19, 2),
transaction_date timestamp,
TRANSACTION_NUMBER varchar(255),
VALID boolean,
primary key (id)
)
alter table REF_PRODUCT
add constraint FK_sjugahpelk16qj5h3w8dli42l
foreign key (picture_id)
references TXN_PRODUCT_PICTURE;
alter table TXN_LINE_ITEM
add constraint FK_o5mslaahpil9d3g9rl2s22rpm
foreign key (transactionRecord_id)
references TXN_TRANSACTION_RECORD;
create table SEQ_ENTITY_ID (
sequence_name varchar(255),
sequence_next_hi_value int4
);
The problem is the fk relationships specified in alter table statement is not being created
Because of this error.
[WARNING ] CREATE SCHEMA testSchema
create table REF_PRODUCT (
id int8 not null,
created_date timestamp,
CODE varchar(255),
DESCRIPTION varchar(255),
LOCATION varchar(255),
MANUFACTURER varchar(255),
NAME varchar(255),
COST numeric(19, 2),
DEALERS_PRICE numeric(19, 2),
SUGGESTED_RETAIL_PRICE numeric(19, 2),
STOCK int4,
PRODUCT_TYPE varchar(255),
picture_id int8,
primary key (id)
)
create table TXN_LINE_ITEM (
id int8 not null,
created_date timestamp,
cancelled boolean,
cost numeric(19, 2),
dp numeric(19, 2),
itemCode varchar(255),
itemName varchar(255),
priceType varchar(255),
qty int4,
refunded boolean,
srp numeric(19, 2),
total numeric(19, 2),
transactionRecord_id int8,
primary key (id)
)
create table TXN_PRODUCT_PICTURE (
id int8 not null,
created_date timestamp,
picture bytea,
primary key (id)
)
create table TXN_TRANSACTION_RECORD (
id int8 not null,
created_date timestamp,
total numeric(19, 2),
transaction_date timestamp,
TRANSACTION_NUMBER varchar(255),
VALID boolean,
primary key (id)
)
alter table REF_PRODUCT
add constraint FK_sjugahpelk16qj5h3w8dli42l
foreign key (picture_id)
references TXN_PRODUCT_PICTURE
ERROR: syntax error at or near "alter"
LINE 53: alter table REF_PRODUCT
^
[WARNING ] alter table TXN_LINE_ITEM
add constraint FK_o5mslaahpil9d3g9rl2s22rpm
foreign key (transactionRecord_id)
references TXN_TRANSACTION_RECORD
ERROR: relation "txn_line_item" does not exist
[WARNING ] create table SEQ_ENTITY_ID (
sequence_name varchar(255),
sequence_next_hi_value int4
)
ERROR: relation "seq_entity_id" already exists
NOTE THAT: There's no existing tables on the said Schema I have made. What have I missed?
I think you have two ways of doing this.
The first one: don't run one create schema statement, but run individual statements for each part (this is what I prefer). You can still do that as a single transaction:
begin transaction;
CREATE SCHEMA testSchema; -- only create the namespace
-- make the new schema the default schema
-- so the the tables do not need to be full qualified
set search_path = testschema;
create table REF_PRODUCT (
...
);
create table TXN_LINE_ITEM (
...
);
create table TXN_PRODUCT_PICTURE (
...
);
create table TXN_TRANSACTION_RECORD (
...
);
alter table REF_PRODUCT
add constraint fk_product_picture
foreign key (picture_id)
references TXN_PRODUCT_PICTURE;
alter table TXN_LINE_ITEM
add constraint FK_line_item_trans_record
foreign key (transactionRecord_id)
references TXN_TRANSACTION_RECORD;
create table SEQ_ENTITY_ID (
sequence_name varchar(255),
sequence_next_hi_value int4
);
commit;
The other option is to move the foreign keys into the table definition, but then you need to re-order your create table statements:
CREATE SCHEMA testSchema
create table TXN_PRODUCT_PICTURE (
...
)
create table TXN_TRANSACTION_RECORD (
...
)
create table REF_PRODUCT (
...,
constraint fk_product_picture
foreign key (picture_id)
references TXN_PRODUCT_PICTURE
)
create table TXN_LINE_ITEM (
...
constraint FK_line_item_trans_record
foreign key (transactionRecord_id)
references TXN_TRANSACTION_RECORD
)
create table SEQ_ENTITY_ID (
sequence_name varchar(255),
sequence_next_hi_value int4
)
;
Unrelated, but:
What is this SEQ_ENTITY_ID table for? Why don't you use native Postgres sequences. They will be much faster, more scalable and more robust than anything you can do in your application to generate unique numbers