1 /*-------------------------------------------------------------------------
2  *
3  * createdb
4  *
5  * Portions Copyright (c) 1996-2021, PostgreSQL Global Development Group
6  * Portions Copyright (c) 1994, Regents of the University of California
7  *
8  * src/bin/scripts/createdb.c
9  *
10  *-------------------------------------------------------------------------
11  */
12 #include "postgres_fe.h"
13 
14 #include "common.h"
15 #include "common/logging.h"
16 #include "fe_utils/option_utils.h"
17 #include "fe_utils/string_utils.h"
18 
19 
20 static void help(const char *progname);
21 
22 
23 int
main(int argc,char * argv[])24 main(int argc, char *argv[])
25 {
26 	static struct option long_options[] = {
27 		{"host", required_argument, NULL, 'h'},
28 		{"port", required_argument, NULL, 'p'},
29 		{"username", required_argument, NULL, 'U'},
30 		{"no-password", no_argument, NULL, 'w'},
31 		{"password", no_argument, NULL, 'W'},
32 		{"echo", no_argument, NULL, 'e'},
33 		{"owner", required_argument, NULL, 'O'},
34 		{"tablespace", required_argument, NULL, 'D'},
35 		{"template", required_argument, NULL, 'T'},
36 		{"encoding", required_argument, NULL, 'E'},
37 		{"lc-collate", required_argument, NULL, 1},
38 		{"lc-ctype", required_argument, NULL, 2},
39 		{"locale", required_argument, NULL, 'l'},
40 		{"maintenance-db", required_argument, NULL, 3},
41 		{NULL, 0, NULL, 0}
42 	};
43 
44 	const char *progname;
45 	int			optindex;
46 	int			c;
47 
48 	const char *dbname = NULL;
49 	const char *maintenance_db = NULL;
50 	char	   *comment = NULL;
51 	char	   *host = NULL;
52 	char	   *port = NULL;
53 	char	   *username = NULL;
54 	enum trivalue prompt_password = TRI_DEFAULT;
55 	ConnParams	cparams;
56 	bool		echo = false;
57 	char	   *owner = NULL;
58 	char	   *tablespace = NULL;
59 	char	   *template = NULL;
60 	char	   *encoding = NULL;
61 	char	   *lc_collate = NULL;
62 	char	   *lc_ctype = NULL;
63 	char	   *locale = NULL;
64 
65 	PQExpBufferData sql;
66 
67 	PGconn	   *conn;
68 	PGresult   *result;
69 
70 	pg_logging_init(argv[0]);
71 	progname = get_progname(argv[0]);
72 	set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pgscripts"));
73 
74 	handle_help_version_opts(argc, argv, "createdb", help);
75 
76 	while ((c = getopt_long(argc, argv, "h:p:U:wWeO:D:T:E:l:", long_options, &optindex)) != -1)
77 	{
78 		switch (c)
79 		{
80 			case 'h':
81 				host = pg_strdup(optarg);
82 				break;
83 			case 'p':
84 				port = pg_strdup(optarg);
85 				break;
86 			case 'U':
87 				username = pg_strdup(optarg);
88 				break;
89 			case 'w':
90 				prompt_password = TRI_NO;
91 				break;
92 			case 'W':
93 				prompt_password = TRI_YES;
94 				break;
95 			case 'e':
96 				echo = true;
97 				break;
98 			case 'O':
99 				owner = pg_strdup(optarg);
100 				break;
101 			case 'D':
102 				tablespace = pg_strdup(optarg);
103 				break;
104 			case 'T':
105 				template = pg_strdup(optarg);
106 				break;
107 			case 'E':
108 				encoding = pg_strdup(optarg);
109 				break;
110 			case 1:
111 				lc_collate = pg_strdup(optarg);
112 				break;
113 			case 2:
114 				lc_ctype = pg_strdup(optarg);
115 				break;
116 			case 'l':
117 				locale = pg_strdup(optarg);
118 				break;
119 			case 3:
120 				maintenance_db = pg_strdup(optarg);
121 				break;
122 			default:
123 				fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
124 				exit(1);
125 		}
126 	}
127 
128 	switch (argc - optind)
129 	{
130 		case 0:
131 			break;
132 		case 1:
133 			dbname = argv[optind];
134 			break;
135 		case 2:
136 			dbname = argv[optind];
137 			comment = argv[optind + 1];
138 			break;
139 		default:
140 			pg_log_error("too many command-line arguments (first is \"%s\")",
141 						 argv[optind + 2]);
142 			fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
143 			exit(1);
144 	}
145 
146 	if (locale)
147 	{
148 		if (lc_ctype)
149 		{
150 			pg_log_error("only one of --locale and --lc-ctype can be specified");
151 			exit(1);
152 		}
153 		if (lc_collate)
154 		{
155 			pg_log_error("only one of --locale and --lc-collate can be specified");
156 			exit(1);
157 		}
158 		lc_ctype = locale;
159 		lc_collate = locale;
160 	}
161 
162 	if (encoding)
163 	{
164 		if (pg_char_to_encoding(encoding) < 0)
165 		{
166 			pg_log_error("\"%s\" is not a valid encoding name", encoding);
167 			exit(1);
168 		}
169 	}
170 
171 	if (dbname == NULL)
172 	{
173 		if (getenv("PGDATABASE"))
174 			dbname = getenv("PGDATABASE");
175 		else if (getenv("PGUSER"))
176 			dbname = getenv("PGUSER");
177 		else
178 			dbname = get_user_name_or_exit(progname);
179 	}
180 
181 	/* No point in trying to use postgres db when creating postgres db. */
182 	if (maintenance_db == NULL && strcmp(dbname, "postgres") == 0)
183 		maintenance_db = "template1";
184 
185 	cparams.dbname = maintenance_db;
186 	cparams.pghost = host;
187 	cparams.pgport = port;
188 	cparams.pguser = username;
189 	cparams.prompt_password = prompt_password;
190 	cparams.override_dbname = NULL;
191 
192 	conn = connectMaintenanceDatabase(&cparams, progname, echo);
193 
194 	initPQExpBuffer(&sql);
195 
196 	appendPQExpBuffer(&sql, "CREATE DATABASE %s",
197 					  fmtId(dbname));
198 
199 	if (owner)
200 		appendPQExpBuffer(&sql, " OWNER %s", fmtId(owner));
201 	if (tablespace)
202 		appendPQExpBuffer(&sql, " TABLESPACE %s", fmtId(tablespace));
203 	if (encoding)
204 	{
205 		appendPQExpBufferStr(&sql, " ENCODING ");
206 		appendStringLiteralConn(&sql, encoding, conn);
207 	}
208 	if (template)
209 		appendPQExpBuffer(&sql, " TEMPLATE %s", fmtId(template));
210 	if (lc_collate)
211 	{
212 		appendPQExpBufferStr(&sql, " LC_COLLATE ");
213 		appendStringLiteralConn(&sql, lc_collate, conn);
214 	}
215 	if (lc_ctype)
216 	{
217 		appendPQExpBufferStr(&sql, " LC_CTYPE ");
218 		appendStringLiteralConn(&sql, lc_ctype, conn);
219 	}
220 
221 	appendPQExpBufferChar(&sql, ';');
222 
223 	if (echo)
224 		printf("%s\n", sql.data);
225 	result = PQexec(conn, sql.data);
226 
227 	if (PQresultStatus(result) != PGRES_COMMAND_OK)
228 	{
229 		pg_log_error("database creation failed: %s", PQerrorMessage(conn));
230 		PQfinish(conn);
231 		exit(1);
232 	}
233 
234 	PQclear(result);
235 
236 	if (comment)
237 	{
238 		printfPQExpBuffer(&sql, "COMMENT ON DATABASE %s IS ", fmtId(dbname));
239 		appendStringLiteralConn(&sql, comment, conn);
240 		appendPQExpBufferChar(&sql, ';');
241 
242 		if (echo)
243 			printf("%s\n", sql.data);
244 		result = PQexec(conn, sql.data);
245 
246 		if (PQresultStatus(result) != PGRES_COMMAND_OK)
247 		{
248 			pg_log_error("comment creation failed (database was created): %s",
249 						 PQerrorMessage(conn));
250 			PQfinish(conn);
251 			exit(1);
252 		}
253 
254 		PQclear(result);
255 	}
256 
257 	PQfinish(conn);
258 
259 	exit(0);
260 }
261 
262 
263 static void
help(const char * progname)264 help(const char *progname)
265 {
266 	printf(_("%s creates a PostgreSQL database.\n\n"), progname);
267 	printf(_("Usage:\n"));
268 	printf(_("  %s [OPTION]... [DBNAME] [DESCRIPTION]\n"), progname);
269 	printf(_("\nOptions:\n"));
270 	printf(_("  -D, --tablespace=TABLESPACE  default tablespace for the database\n"));
271 	printf(_("  -e, --echo                   show the commands being sent to the server\n"));
272 	printf(_("  -E, --encoding=ENCODING      encoding for the database\n"));
273 	printf(_("  -l, --locale=LOCALE          locale settings for the database\n"));
274 	printf(_("      --lc-collate=LOCALE      LC_COLLATE setting for the database\n"));
275 	printf(_("      --lc-ctype=LOCALE        LC_CTYPE setting for the database\n"));
276 	printf(_("  -O, --owner=OWNER            database user to own the new database\n"));
277 	printf(_("  -T, --template=TEMPLATE      template database to copy\n"));
278 	printf(_("  -V, --version                output version information, then exit\n"));
279 	printf(_("  -?, --help                   show this help, then exit\n"));
280 	printf(_("\nConnection options:\n"));
281 	printf(_("  -h, --host=HOSTNAME          database server host or socket directory\n"));
282 	printf(_("  -p, --port=PORT              database server port\n"));
283 	printf(_("  -U, --username=USERNAME      user name to connect as\n"));
284 	printf(_("  -w, --no-password            never prompt for password\n"));
285 	printf(_("  -W, --password               force password prompt\n"));
286 	printf(_("  --maintenance-db=DBNAME      alternate maintenance database\n"));
287 	printf(_("\nBy default, a database with the same name as the current user is created.\n"));
288 	printf(_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
289 	printf(_("%s home page: <%s>\n"), PACKAGE_NAME, PACKAGE_URL);
290 }
291