|
| 1 | +\prompt "Username?" postgres_dba_username |
| 2 | +\prompt "Superuser? (1 if yes, 0 if no)" postgres_dba_is_superuser |
| 3 | +\prompt "Login? (1 if yes, 0 if no)" postgres_dba_login |
| 4 | + |
| 5 | +\set q_postgres_dba_username '\'' :postgres_dba_username '\'' |
| 6 | +\set q_postgres_dba_is_superuser '\'' :postgres_dba_is_superuser '\'' |
| 7 | +\set q_postgres_dba_login '\'' :postgres_dba_login '\'' |
| 8 | + |
| 9 | +begin; |
| 10 | + |
| 11 | +\o /dev/null |
| 12 | +select set_config('postgres_dba.username', :q_postgres_dba_username, true); |
| 13 | +select set_config('postgres_dba.is_superuser', :q_postgres_dba_is_superuser, true); |
| 14 | +select set_config('postgres_dba.login', :q_postgres_dba_login, true); |
| 15 | +\o |
| 16 | + |
| 17 | +do $$ |
| 18 | +declare |
| 19 | + pwd text; |
| 20 | + j int4; |
| 21 | + allowed text; |
| 22 | + allowed_len int4; |
| 23 | + sql text; |
| 24 | +begin |
| 25 | + if current_setting('postgres_dba.username')::text = '' then |
| 26 | + raise exception 'Username is not specified.'; |
| 27 | + end if; |
| 28 | + allowed := '23456789abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ&#%@'; |
| 29 | + allowed_len := length(allowed); |
| 30 | + pwd := ''; |
| 31 | + while length(pwd) < 16 loop |
| 32 | + j := int4(random() * allowed_len); |
| 33 | + pwd := pwd || substr(allowed, j+1, 1); |
| 34 | + end loop; |
| 35 | + sql := 'create role ' || current_setting('postgres_dba.username')::text |
| 36 | + || (case when lower(current_setting('postgres_dba.is_superuser')::text) not in ('0', '', 'no', 'false', 'n', 'f') then ' superuser' else '' end) |
| 37 | + || (case when lower(current_setting('postgres_dba.login')::text) not in ('0', '', 'no', 'false', 'n', 'f') then ' login' else '' end) |
| 38 | + || ' password ''' || pwd || ''';'; |
| 39 | + raise notice 'SQL: %', sql; |
| 40 | + execute sql; |
| 41 | + raise notice 'User % created, password: %', current_setting('postgres_dba.username')::text, pwd; |
| 42 | +end; |
| 43 | +$$ language plpgsql; |
| 44 | + |
| 45 | +commit; |
| 46 | + |
| 47 | +\unset postgres_dba_username |
| 48 | +\unset postgres_dba_username |
| 49 | +\unset postgres_dba_login |
| 50 | +\unset q_postgres_dba_username |
| 51 | +\unset q_postgres_dba_username |
| 52 | +\unset q_postgres_dba_login |
| 53 | + |
0 commit comments