how to set list of valid characters in postgresql strings - postgresql

I want to make a username field in postgresql database of course usernames has name patterns
like using 0-9 a-z A-Z _ characters only how do I do such thing ?
I tried making the server check the username before it insert it into the database it works but it's like meh

You could create your table with a check constraint on the username field:
CREATE TABLE courses (
...,
username VARCHAR(50) CHECK (username ~ '^[A-Z0-9_]+$'),
...
);
The above check constraint is using a case insensitive regex to assert that the username contains only letters, numbers, or underscore.

Related

Are table names case sensitive in Heroku Postgres add-on? [duplicate]

I have a db table say, persons in Postgres handed down by another team that has a column name say, "first_Name". Now am trying to use PG commander to query this table on this column-name.
select * from persons where first_Name="xyz";
And it just returns
ERROR: column "first_Name" does not exist
Not sure if I am doing something silly or is there a workaround to this problem that I am missing?
Identifiers (including column names) that are not double-quoted are folded to lowercase in PostgreSQL. Column names that were created with double-quotes and thereby retained uppercase letters (and/or other syntax violations) have to be double-quoted for the rest of their life:
"first_Name"
Values (string literals / constants) are enclosed in single quotes:
'xyz'
So, yes, PostgreSQL column names are case-sensitive (when double-quoted):
SELECT * FROM persons WHERE "first_Name" = 'xyz';
Read the manual on identifiers here.
My standing advice is to use legal, lower-case names exclusively so double-quoting is never required.
To quote the documentation:
Key words and unquoted identifiers are case insensitive. Therefore:
UPDATE MY_TABLE SET A = 5;
can equivalently be written as:
uPDaTE my_TabLE SeT a = 5;
You could also write it using quoted identifiers:
UPDATE "my_table" SET "a" = 5;
Quoting an identifier makes it case-sensitive, whereas unquoted names are always folded to lower case (unlike the SQL standard where unquoted names are folded to upper case). For example, the identifiers FOO, foo, and "foo" are considered the same by PostgreSQL, but "Foo" and "FOO" are different from these three and each other.
If you want to write portable applications you are advised to always quote a particular name or never quote it.
The column names which are mixed case or uppercase have to be double quoted in PostgresQL. So best convention will be to follow all small case with underscore.
if use JPA I recommend change to lowercase schema, table and column names, you can use next intructions for help you:
select
psat.schemaname,
psat.relname,
pa.attname,
psat.relid
from
pg_catalog.pg_stat_all_tables psat,
pg_catalog.pg_attribute pa
where
psat.relid = pa.attrelid
change schema name:
ALTER SCHEMA "XXXXX" RENAME TO xxxxx;
change table names:
ALTER TABLE xxxxx."AAAAA" RENAME TO aaaaa;
change column names:
ALTER TABLE xxxxx.aaaaa RENAME COLUMN "CCCCC" TO ccccc;
You can try this example for table and column naming in capital letters. (postgresql)
//Sql;
create table "Test"
(
"ID" integer,
"NAME" varchar(255)
)
//C#
string sqlCommand = $#"create table ""TestTable"" (
""ID"" integer GENERATED BY DEFAULT AS IDENTITY primary key,
""ExampleProperty"" boolean,
""ColumnName"" varchar(255))";

Error at insert encode password in postgres

i've create this psql table code :
CREATE TABLE admin (id INT NOT NULL, username VARCHAR(180) NOT NULL, roles JSON NOT NULL, password VARCHAR(255) NOT NULL, PRIMARY KEY(id))');
and then
INSERT INTO admin (id, username, roles, password) VALUES (nextval('admin_id_seq'), 'admin', '["ROLE_ADMIN"]', '$argon2id$v=19$m=65536,t=4,p=1$Kcm6sv104bqBtb+FEh+dDQ$caej4aGFAYMvBqKNHgFAGw6+1rua1Iwk/g09mYbOCLMx’);
there no single error on my end at terminal but 0 rows on table, any code that i missed ?
if you look closely at your values (truncated below!), you'll see that the very last single quote is actually a "right single quotation mark" (U+2019) and not a "single quote" / "apostrophe" (U+0027), while all other quotes are apostrophe, as they should be.
(nextval('admin_id_seq'), 'admin', '["ROLE_ADMIN"]', '$argon2id$v=19$...’)
^-- this one
If you look very closely, you can see that it even looks different. You can zoom in to see the difference more easily.
The solution is to replace the last one with an apostrophe / single quote (U+0027):
INSERT INTO admin (id, username, roles, password) VALUES (nextval('admin_id_seq'), 'admin', '["ROLE_ADMIN"]', '$argon2id$v=19$m=65536,t=4,p=1$Kcm6sv104bqBtb+FEh+dDQ$caej4aGFAYMvBqKNHgFAGw6+1rua1Iwk/g09mYbOCLMx');

What should be the data type of field 'email' in Postgresql database in pgadmin 4?

You can see that I am getting 'No results found' when searching for varchar.
I need to know the data type that I should select for 'email' in postgresql database.
In the past I used text or varchar or character varying
Apart from using of VARCHAR (as suggested by #Maria), you might get some insight from this link:
https://www.dbrnd.com/2018/04/postgresql-how-to-validate-the-email-address-column/
and from this https://dba.stackexchange.com/questions/68266/what-is-the-best-way-to-store-an-email-address-in-postgresql
if you read some parts of it, they created their own functions or constraints, which would likely help you in understanding PSQL more.
TL/DR, or the links might change in the future (shamelessly taken from one of the links):
CREATE EXTENSION citext;
CREATE DOMAIN domain_email AS citext
CHECK(
VALUE ~ '^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$'
);
-- for valid samples
SELECT 'some_email#gmail.com'::domain_email;
SELECT 'accountant#dbrnd.org'::domain_email;
-- for an invalid sample
SELECT 'dba#aol.info'::domain_email;
As Neil had pointed out, yeah it's just like using custom TYPES.
CREATE DOMAIN creates a new domain. A domain is essentially a data type with optional constraints (restrictions on the allowed set of values).
source
For those of you unfamiliar with the weird characters used to check the value, it's a regex pattern.
And an example used with a table:
CREATE TABLE sample_table ( id SERIAL PRIMARY KEY, email domain_email );
-- The following is invalid, because ".info" has 4 characters
-- the regex pattern only allows 2-3 characters
INSERT INTO sample_table (email) VALUES ('sample_email#gmail.info');
ERROR: value for domain domain_email violates check constraint "domain_email_check"
-- The following query is valid
INSERT INTO sample_table (email) VALUES ('sample_email#gmail.com');
SELECT * FROM sample_table;
id | email
----+------------------------
1 | sample_email#gmail.com
(1 row)
Thanks Neil for the suggestion.
I recommend you yo use CITEXT type that ignores case in values comparison. It's important for email to prevent duplication like username#example.com and UserName#example.com.
This type is the part of the citext extension that could be activates by the following query:
CREATE EXTENSION citext;

Does tsvector works with citext

I have a citext column named email and also a tsvector column named search to do full text search. My trigger is like this:
tsvector_update_trigger(search_vector, 'pg_catalog.english', name, email)
name is just a normal text column. However, because email is citext which is text, but just case-insensitive, it appear that the trigger will not work. I have error that mention email is not of "character type". I am wondering why Postgres has difficulty treating citext as just text or cast to text and go about its business of tokenizing it?
How to have email remain as citext and still full-text searchable?
why not just typecast the field to text and life is good? name::text should do. tsvector is case insensitive anyway.

Firebird and Table,field name lowercase

I have converted a database from MySQL to Firebird, all tables name and field name are in lowercase, when I query the database, it gives me an error of table not found, because Firebird automatically converted the name of table in the query in UPPERCASE letters, but my table name in database is lowercase.
To query the database, I'm required to enclose the name of the table or the name of the field in double quotes, for example:
SELECT "field1","field2" FROM "table"
Is there a setting in Firebird to allow to query database with table/field name in lowercase letter without quoting it?
No. BTW, I suggest you to always create DB objects in uppercase (and without double quotes) in Firebird. This simplifies a lot, since you can access them writing in any case (even mixed case).