Skip to content

Commit fe08b00

Browse files
authored
fix: explicitly use the POSTGRES_USER (#13)
1 parent 12a4ab3 commit fe08b00

File tree

1 file changed

+11
-7
lines changed

1 file changed

+11
-7
lines changed

ensure_role_and_database_exists.c

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,31 +12,35 @@ static ClientAuthentication_hook_type original_client_auth_hook = NULL;
1212

1313
static void ensure_role_and_database_exists(Port *port, int status) {
1414
char *cmd;
15+
char *postgres_user;
1516
char *role_attributes;
1617

1718
if (original_client_auth_hook) {
1819
original_client_auth_hook(port, status);
1920
}
2021

21-
// don't infinitely recurse
22-
if (strcmp(port->database_name, "postgres") == 0 && strcmp(port->user_name, "postgres") == 0) {
22+
postgres_user = getenv("POSTGRES_USER");
23+
24+
fprintf(stderr, "handling connection for username '%s' to database '%s'\n", port->user_name, port->database_name);
25+
26+
// don't infinitely recurse when connecting as superuser
27+
if (strcmp(port->database_name, postgres_user) == 0 && strcmp(port->user_name, postgres_user) == 0) {
2328
return;
2429
}
2530

2631
role_attributes = getenv("POSTGRES_ROLE_ATTRIBUTES");
2732

2833
fprintf(stderr, "ensuring user_name '%s' exists with attributes '%s'\n", port->user_name, role_attributes);
2934
asprintf(&cmd,
30-
"echo \"SELECT 'CREATE ROLE %s WITH %s' WHERE NOT EXISTS (SELECT FROM pg_roles WHERE rolname = '%s')\\gexec\" | psql",
31-
port->user_name, role_attributes, port->user_name);
35+
"echo \"SELECT 'CREATE ROLE %s WITH %s' WHERE NOT EXISTS (SELECT FROM pg_roles WHERE rolname = '%s')\\gexec\" | psql -U %s -d %s",
36+
port->user_name, role_attributes, port->user_name, postgres_user, postgres_user);
3237
system(cmd);
3338
free(cmd);
3439

3540
fprintf(stderr, "ensuring database '%s' exists\n", port->database_name);
36-
3741
asprintf(&cmd,
38-
"echo \"SELECT 'CREATE DATABASE %s WITH OWNER = %s' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = '%s')\\gexec\" | psql",
39-
port->database_name, port->user_name, port->database_name);
42+
"echo \"SELECT 'CREATE DATABASE %s WITH OWNER = %s' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = '%s')\\gexec\" | psql -U %s -d %s",
43+
port->database_name, port->user_name, port->database_name, postgres_user, postgres_user);
4044
system(cmd);
4145
free(cmd);
4246
}

0 commit comments

Comments
 (0)