I have a database that is about Heroku. A field is automatically filled with the date. I try to use current_timestamp, but it does not seem to work.
Here is the schema of the database.
drop table if exists users;
create table users (
id int GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
name varchar,
email varchar,
username varchar,
password varchar,
register_date CURRENT_TIMESTAMP() not null
);
Here is the query:
cur.execute("INSERT INTO users(name, email, username, password) VALUES(%s, %s, %s, %s)", (name, email, username, password))
And here is the error:
ERROR: syntax error at or near "CURRENT_TIMESTAMP"
LINE 7: register_date CURRENT_TIMESTAMP() not null
postgresql doesn't recognize CURRENT_TIMESTAMP() that's why you have to use CURRENT_TIMESTAMP (without parentheses). Next create table query must work for you:
create table users (
id int GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
name varchar,
email varchar,
username varchar,
password varchar,
register_date timestamp default CURRENT_TIMESTAMP not null
);
To check that it works just run next query from postgres REPL:
insert into users(name, email, username, password)
values('n', 'e#e.com', 'un', 'pwd');
To add a column with default current timestamp you could use TIMESTAMP type with default value as NOW()
create table users (
id int GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
name varchar,
email varchar,
username varchar,
password varchar,
register_date TIMESTAMP DEFAULT NOW()
);
Sample data
INSERT INTO users(name, email, username, password)
VALUES('Foo', 'foo#bar.com', 'bar', 'foobar')
Demo with 9.6
Demo with 10
Related
i will import data csv to postgresql via pgAdmin 4. But, there are problem
ERROR: invalid input syntax for type integer: ""
CONTEXT: COPY films, line 1, column gross: ""
i understand about the error that is line 1 column gross there is null value and in some other columns there are also null values. My questions, how to import file csv but in the that file there is null value. I've been search in google but not found similar my case.
CREATE TABLE public.films
(
id int,
title varchar,
release_year float4,
country varchar,
duration float4,
language varchar,
certification varchar,
gross int,
budget int
);
And i try in this code below, but failed
CREATE TABLE public.films
(
id int,
title varchar,
release_year float4 null,
country varchar null,
duration float4 null,
language varchar null,
certification varchar null,
gross float4 null,
budget float4 null
);
error message in image
I've searched on google and on the stackoverflow forums. I hope that someone will help solve my problem
There is no difference between the two table definitions. A column accepts NULL by default.
The issue is not a NULL value but an empty string:
select ''::integer;
ERROR: invalid input syntax for type integer: ""
LINE 1: select ''::integer;
select null::integer;
int4
------
NULL
Create a staging table that has data type of varchar for the fields that are now integer. Load the data into that table. Then modify the empty string data that will be integer using something like:
update table set gross = nullif(trim(gross), '');
Then move the data to the production table.
This is not a pgAdmin4 issue it is a data issue. Working in psql because it is easier to follow:
CREATE TABLE public.films_text
(
id varchar,
title varchar,
release_year varchar,
country varchar,
duration varchar,
language varchar,
certification varchar,
gross varchar,
budget varchar
);
\copy films_text from '~/Downloads/films.csv' with csv
COPY 4968
CREATE TABLE public.films
(
id int,
title varchar,
release_year float4,
country varchar,
duration float4,
language varchar,
certification varchar,
gross int,
budget int
);
-- Below done because of this value 12215500000 in budget column
alter table films alter COLUMN budget type int8;
INSERT INTO films
SELECT
id::int,
title,
nullif (trim(release_year), '')::real, country, nullif(trim(duration), '')::real,
LANGUAGE,
certification,
nullif (trim(gross), '')::float, nullif(trim(budget), '')::float
FROM
films_text;
INSERT 0 4968
It worked for me:
https://learnsql.com/blog/how-to-import-csv-to-postgresql/
a small workaround but it works
I created a table
I added headers to csv file
Right click on the newly created table-> Import/export data, select csv file to upload, go to tab2 - select Header and it should work
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');
I have a user table and I should remove the NOT NULL restrictions from the firstname, username and lastname fields, do I understand correctly that nothing can be changed directly, do I need to add a new sql file and with the command? How can I remove NOT NULL and break nothing? everything breaks down
CREATE TABLE "user" (
id SERIAL UNIQUE PRIMARY KEY,
username VARCHAR(255) NOT NULL,
password VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL,
first_name VARCHAR(255) NOT NULL,
last_name VARCHAR(255) NOT NULL,
last_password_reset TIMESTAMP NOT NULL DEFAULT NOW(),
roles JSONB NOT NULL,
active BOOLEAN NOT NULL DEFAULT TRUE,
date_created TIMESTAMP NOT NULL DEFAULT NOW(),
date_updated TIMESTAMP NOT NULL DEFAULT NOW()
);
ALTER TABLE user ALTER COLUMN username DROP NOT NULL;
I have wrote a stored-procedure in PostgreSQL as an API to create contract and user in a same time (by postgrest).
CREATE OR REPLACE FUNCTION
auth.create_contracts(
username text,
password text,
services json,
province text,
region text,
type user_group,
telephone text,
mobile text,
email text,
start_date text,
end_date text,
organization_name text,
contract_number text,
name text,
economy_code INTEGER,
t_name text,
t_phone text,
t_ip text,
t_email text,
t_telephone text,
t_prefer_contract text,
area_state text,
area_city text,
area_county text
) RETURNS json
LANGUAGE plpgsql
AS $$
DECLARE
_user_id INTEGER;
_res json;
_now DOUBLE PRECISION;
_app_token text;
_username text;
BEGIN
SELECT random_string(64) INTO _app_token;
INSERT INTO auth.users(
username,
password,
role,
services,
app_token,
province,
region,
type,
phone,
organization_name,
mobile,
email
)
VALUES (
username,
password,
username,
services,
_app_token,
province,
region,
type,
telephone,
organization_name,
mobile,
email
);
SELECT username INTO _username;
SELECT id FROM auth.users WHERE users.username=_username
INTO _user_id;
INSERT INTO auth.contracts(
user_id,
start_date,
end_date,
organization_name,
contract_number,
economy_code,
t_name,
t_phone,
t_ip,
t_email,
t_telephone,
t_prefer_contract,
name,
area_state,
area_city,
area_county
)
VALUES(
_user_id,
start_date::TIMESTAMP,
end_date::TIMESTAMP,
organization_name,
contract_number,
economy_code,
t_name,
t_phone,
t_ip,
t_email,
t_telephone,
t_prefer_contract,
name,
area_state,
area_city,
area_county
);
SET TIME ZONE 'UTC-3:32';
PERFORM (
SELECT auth.contract_redis_function(end_date::TIMESTAMP, now()::TIMESTAMP,
_app_token, username, 100000)
);
SELECT json_build_object(
'status', 'ok',
'app_token', _app_token
)
INTO _res;
RETURN _res;
END;
$$;
users definition:
create table auth.users
(
id serial not null
constraint users_pkey
primary key,
username text,
password text,
role text,
services json,
app_token text,
province text,
region text,
type user_group,
contract_id integer,
phone text,
picture text,
is_first_login boolean default true,
is_locked boolean default false,
is_active boolean default true,
organization_name text,
mobile text,
email text,
prefer_contact text
)
;
create unique index users_username_uindex
on users (username);
contracts definition:
create table auth.contracts
(
user_id integer
constraint unique_contract
unique
constraint contract_user_01
references auth.users,
start_date timestamp,
end_date timestamp,
organization_name text,
contract_number text,
economy_code integer,
t_name text,
t_phone text,
t_ip text,
t_email text,
t_telephone text,
t_prefer_contract text,
area_state text,
area_city text,
area_county text,
name text,
id serial not null,
is_active boolean default true
);
I have a unique constraint on a key of users relation (id that is auto incremented)
sometimes when call the end-point raise an exception that key exists, but doesn't, and create record.
I don't know why!?
I have a similar problem when creating policy in a stored-procedure.
username is not unique in auth.users, so there is no guarantee that this query gets the correct id:
SELECT id FROM auth.users WHERE users.username=_username
INTO _user_id;
You will get the id of one of the rows with that username.
If there are several such rows, you could get the wrong one, and the UNIQUE constraint on contracts will be violated when you insert the same number a second time.
The solution is to always get the correct id like this:
INSERT INTO auth.users (...) VALUES (...)
RETURNING id INTO _user_id;
Then you will always get the id of the record you just inserted.
How to insert into table 2 all field values of a row from table A, where all values in a column A in table 1 that satisfy a condition on column B of table 1 ,but do not exist in table 2.How to frame a query using not exists?
I tried this:
INSERT INTO Teachermast (
teacher_code,
teacher_name,
designation,
dept_code,
contact_no,
email,
address,
dob,
PASSWORD
)
SELECT
userId,
username,
designation,
dept,
contact_no,
email,
address,
dob,
PASSWORD
FROM
UserMast
WHERE NOT EXISTS
(SELECT
userId
FROM
UserMast
WHERE usertype = '3')
but this doesnt seem to work.
Kindly help.
You could do a MERGE
create table users
(
userId varchar(50),
username varchar(50),
usertype int,
password varchar(50),
contact_no varchar(50),
email varchar(50),
faxno varchar(50),
address varchar(50),
created_date date,
updated_date date,
status varchar(50),
gender varchar(50),
dob date,
lasttimelogin datetime,
login_time datetime,
logoutt_time datetime,
designation varchar(50),
dept varchar(50),
email_pass varchar(50)
)
insert into users values('T0003','Ankita',3,'12345','9858585245','anki#gmail.com','201','l block noid sec 25',NULL,NULL,NULL,'Female','11/09/1990',NULL,NULL,NULL,'Teacher','EC',NULL);
insert into users values('T0004','Ribha',3,'12345','9512365423','sharma#gmail.com',NULL,'221 dwarka sec 10',NULL,NULL,NULL,'Female','12/02/1989',NULL,NULL,NULL,'Teacher','EC',NULL);
create table teachers
(
teacher_code varchar(50),
teacher_name varchar(50),
designation varchar(50),
dept_code varchar(50),
contact_no varchar(50),
email varchar(50),
address varchar(50),
dob date,
password varchar(50)
)
insert into teachers values('T0002','Tanvi','Teacher','CS','9632569856','tan123#gmail.com','298 mayur vihar ph 1','29/06/1990','12345');
insert into teachers values('T0003','Ankita','Teacher','EC','9858585245','anki#gmail.com','201 l block noida sec 25','11/09/1990','12345');
merge teachers as target
using (select userid, username, designation, dept, contact_no, email, address, dob, password from users where usertype = 3)
as source(userid, username, designation, dept, contact_no, email, address, dob, password)
on target.teacher_code = source.userid
when not matched by target then
insert (teacher_code, teacher_name, designation, dept_code, contact_no, email, address, dob, password)
values (source.userid, source.username, source.designation, source.dept, source.contact_no, source.email, source.address, source.dob, source.password);
select * from teachers
However, I think there are issues with your database design. With your current model, you could have, for example, a different address (or password!) for Ankita in table1 compared to table2. And if you change any of that information you would have to change it in both places.
Could you, for example, just insert everyone into "users" and have "teachers" be a view
select {columns} from users where usertype = 3
Please try this query
SELECT
t.userId,
t.username,
t.designation,
t.dept,
t.contact_no,
t.email,
t.address,
t.dob,
t.PASSWORD
FROM Teachermast as t
LEFT join UserMast as u on t.userId = u.teacher_code
WHERE t.usertype = '3' and u.teacher_code is null