Utoljára aktív 1740724148

This can be used when you have an app that needs postgres and you want to quickly make a new db for it with a user

Revízió 270c62798166bbd4f06e24e07dc70e85ec1f5dbc

newdb.sql Eredeti
1DO $$
2DECLARE
3 username text := 'new_user'; -- Variable for the username
4 user_password text := 'new_password'; -- Variable for the user's password
5 db_name text := 'new_database'; -- Variable for the database name
6BEGIN
7 -- Step 1: Create the database
8 EXECUTE format('CREATE DATABASE %I;', db_name);
9
10 -- Step 2: Create the user with the password
11 EXECUTE format('CREATE USER %I WITH PASSWORD %L;', username, user_password);
12
13 -- Step 3: Connect to the created database
14 -- In this case, we can't connect from within the same query, but you can use this after running the block:
15 -- \c new_database;
16
17 -- Step 4: Grant the new user all privileges on the created database
18 EXECUTE format('GRANT ALL PRIVILEGES ON DATABASE %I TO %I;', db_name, username);
19
20 -- Step 5: Grant the new user full privileges on the public schema of the created database
21 EXECUTE format('GRANT ALL PRIVILEGES ON SCHEMA public TO %I;', username);
22 EXECUTE format('GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO %I;', username);
23 EXECUTE format('GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO %I;', username);
24 EXECUTE format('ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO %I;', username);
25 EXECUTE format('ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON SEQUENCES TO %I;', username);
26
27 -- Optionally, raise a notice to confirm completion
28 RAISE NOTICE 'Database % created, user % granted privileges.', db_name, username;
29END $$;
30