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