* Append a psql meta-command that connects to the given database with the * then-current connection's user, host and port. */
| 470 | * then-current connection's user, host and port. |
| 471 | */ |
| 472 | void |
| 473 | appendPsqlMetaConnect(PQExpBuffer buf, const char *dbname) |
| 474 | { |
| 475 | const char *s; |
| 476 | bool complex; |
| 477 | |
| 478 | /* |
| 479 | * If the name is plain ASCII characters, emit a trivial "\connect "foo"". |
| 480 | * For other names, even many not technically requiring it, skip to the |
| 481 | * general case. No database has a zero-length name. |
| 482 | */ |
| 483 | complex = false; |
| 484 | for (s = dbname; *s; s++) |
| 485 | { |
| 486 | if (*s == '\n' || *s == '\r') |
| 487 | { |
| 488 | fprintf(stderr, |
| 489 | _("database name contains a newline or carriage return: \"%s\"\n"), |
| 490 | dbname); |
| 491 | exit(EXIT_FAILURE); |
| 492 | } |
| 493 | |
| 494 | if (!((*s >= 'a' && *s <= 'z') || (*s >= 'A' && *s <= 'Z') || |
| 495 | (*s >= '0' && *s <= '9') || *s == '_' || *s == '.')) |
| 496 | { |
| 497 | complex = true; |
| 498 | } |
| 499 | } |
| 500 | |
| 501 | appendPQExpBufferStr(buf, "\\connect "); |
| 502 | if (complex) |
| 503 | { |
| 504 | PQExpBufferData connstr; |
| 505 | |
| 506 | initPQExpBuffer(&connstr); |
| 507 | appendPQExpBuffer(&connstr, "dbname="); |
| 508 | appendConnStrVal(&connstr, dbname); |
| 509 | |
| 510 | appendPQExpBuffer(buf, "-reuse-previous=on "); |
| 511 | |
| 512 | /* |
| 513 | * As long as the name does not contain a newline, SQL identifier |
| 514 | * quoting satisfies the psql meta-command parser. Prefer not to |
| 515 | * involve psql-interpreted single quotes, which behaved differently |
| 516 | * before PostgreSQL 9.2. |
| 517 | */ |
| 518 | appendPQExpBufferStr(buf, quote_identifier(connstr.data)); |
| 519 | |
| 520 | termPQExpBuffer(&connstr); |
| 521 | } |
| 522 | else |
| 523 | appendPQExpBufferStr(buf, quote_identifier(dbname)); |
| 524 | appendPQExpBufferChar(buf, '\n'); |
| 525 | } |
| 526 | |
| 527 | |
| 528 | /* |
no test coverage detected