/* * Return the session user of the current connection. * * Note: this will correctly detect the session user only with a * protocol-3.0 or newer backend; otherwise it will return the * connection user. */ const char * session_username(void) { const char *val; if (!pset.db) return NULL; val = PQparameterStatus(pset.db, "session_authorization"); if (val) return val; else return PQuser(pset.db); }
/* * SyncVariables * * Make psql's internal variables agree with connection state upon * establishing a new connection. */ void SyncVariables(void) { /* get stuff from connection */ pset.encoding = PQclientEncoding(pset.db); pset.popt.topt.encoding = pset.encoding; pset.sversion = PQserverVersion(pset.db); SetVariable(pset.vars, "DBNAME", PQdb(pset.db)); SetVariable(pset.vars, "USER", PQuser(pset.db)); SetVariable(pset.vars, "HOST", PQhost(pset.db)); SetVariable(pset.vars, "PORT", PQport(pset.db)); SetVariable(pset.vars, "ENCODING", pg_encoding_to_char(pset.encoding)); /* send stuff to it, too */ PQsetErrorVerbosity(pset.db, pset.verbosity); }
EtatConnexion::EtatConnexion() { map <string, string> paramsDic; SIPgSql& instance = SIPgSql::Instance(paramsDic); conn = instance.getConn(); if (PQstatus(conn) == CONNECTION_OK) { // -------- PGresult *res; // -------- res = PQexec(conn, "select version() as version"); // -------- wxString textValue; textValue.Append("host : '"); textValue.Append(PQhost(conn)); textValue.Append("' ; port : '"); textValue.Append(PQport(conn)); textValue.Append("' ; dbname : '"); textValue.Append(PQdb(conn)); textValue.Append("' ; user : '******' ;\n\n"); textValue.Append(PQgetvalue(res, 0, 0)); wxMessageBox(textValue, wxT("Statut de la connexion : OK")); } else { // devrait pas arriver !!! wxMessageBox(wxT("Choisir : Connexion->Nouvelle connexion"), wxT("Statut de la connexion : pas de connexion")); } }
/* * check_table - check account tables * IN db_conn: database connection * IN table: table name * IN fields: fields of the table * IN constraint: additional constraint of the table * RET: error code */ extern int check_table(PGconn *db_conn, char *schema, char *table, storage_field_t *fields, char *constraint) { DEF_VARS; char **tables = NULL; int i, num, rc = SLURM_SUCCESS; query = xstrdup_printf( "SELECT tablename FROM pg_tables WHERE schemaname='%s' AND " "tableowner='%s' AND tablename !~ '^pg_+' " "AND tablename !~ '^sql_+'", schema, PQuser(db_conn)); result = pgsql_db_query_ret(db_conn, query); xfree(query); if (!result) return SLURM_ERROR; num = PQntuples(result); tables = xmalloc(sizeof(char *) * (num + 1)); for (i = 0; i < num; i ++) tables[i] = xstrdup(PQgetvalue(result, i, 0)); tables[num] = NULL; PQclear(result); i = 0; while (tables[i] && strcmp(tables[i], table)) i ++; if (!tables[i]) { debug("as/pg: table %s.%s not found, create it", schema, table); rc = pgsql_db_create_table(db_conn, schema, table, fields, constraint); } else { rc = pgsql_db_make_table_current( db_conn, schema, table, fields); } for (i = 0; i < num; i ++) xfree(tables[i]); xfree(tables); return rc; }
LispObj * Lisp_PQuser(LispBuiltin *builtin) /* pq-user connection */ { char *string; PGconn *conn; LispObj *connection; connection = ARGUMENT(0); if (!CHECKO(connection, PGconn_t)) LispDestroy("%s: cannot convert %s to PGconn*", STRFUN(builtin), STROBJ(connection)); conn = (PGconn*)(connection->data.opaque.data); string = PQuser(conn); return (string ? STRING(string) : NIL); }
int main() { // próba po³±czenia PGconn *myconnection = PQconnectdb(""); // sprawdzamy status po³±czenia if(PQstatus(myconnection) == CONNECTION_OK) { printf("connection made\n"); // informacje o po³±czeniu printf("PGDBNAME = %s\n",PQdb(myconnection)); printf("PGUSER = %s\n",PQuser(myconnection)); printf("PGPASSWORD = %s\n",PQpass(myconnection)); printf("PGHOST = %s\n",PQhost(myconnection)); printf("PGPORT = %s\n",PQport(myconnection)); printf("OPTIONS = %s\n",PQoptions(myconnection)); } else printf("connection failed: %s\n", PQerrorMessage(myconnection)); // w razie utraty po³±czenia wywo³anie // PQreset(myconnection); // zamyka op³±czenie i nawi±zuje je raz jeszcze // z dotychczasowymi parametrami PQfinish(myconnection); return EXIT_SUCCESS; }
/* * do_connect -- handler for \connect * * Connects to a database with given parameters. If there exists an * established connection, NULL values will be replaced with the ones * in the current connection. Otherwise NULL will be passed for that * parameter to PQconnectdbParams(), so the libpq defaults will be used. * * In interactive mode, if connection fails with the given parameters, * the old connection will be kept. */ static bool do_connect(char *dbname, char *user, char *host, char *port) { PGconn *o_conn = pset.db, *n_conn; char *password = NULL; if (!dbname) dbname = PQdb(o_conn); if (!user) user = PQuser(o_conn); if (!host) host = PQhost(o_conn); if (!port) port = PQport(o_conn); /* * If the user asked to be prompted for a password, ask for one now. If * not, use the password from the old connection, provided the username * has not changed. Otherwise, try to connect without a password first, * and then ask for a password if needed. * * XXX: this behavior leads to spurious connection attempts recorded in * the postmaster's log. But libpq offers no API that would let us obtain * a password and then continue with the first connection attempt. */ if (pset.getPassword == TRI_YES) { password = prompt_for_password(user); } else if (o_conn && user && strcmp(PQuser(o_conn), user) == 0) { password = strdup(PQpass(o_conn)); } while (true) { #define PARAMS_ARRAY_SIZE 7 const char **keywords = pg_malloc(PARAMS_ARRAY_SIZE * sizeof(*keywords)); const char **values = pg_malloc(PARAMS_ARRAY_SIZE * sizeof(*values)); keywords[0] = "host"; values[0] = host; keywords[1] = "port"; values[1] = port; keywords[2] = "user"; values[2] = user; keywords[3] = "password"; values[3] = password; keywords[4] = "dbname"; values[4] = dbname; keywords[5] = "fallback_application_name"; values[5] = pset.progname; keywords[6] = NULL; values[6] = NULL; n_conn = PQconnectdbParams(keywords, values, true); free(keywords); free(values); /* We can immediately discard the password -- no longer needed */ if (password) free(password); if (PQstatus(n_conn) == CONNECTION_OK) break; /* * Connection attempt failed; either retry the connection attempt with * a new password, or give up. */ if (!password && PQconnectionNeedsPassword(n_conn) && pset.getPassword != TRI_NO) { PQfinish(n_conn); password = prompt_for_password(user); continue; } /* * Failed to connect to the database. In interactive mode, keep the * previous connection to the DB; in scripting mode, close our * previous connection as well. */ if (pset.cur_cmd_interactive) { psql_error("%s", PQerrorMessage(n_conn)); /* pset.db is left unmodified */ if (o_conn) fputs(_("Previous connection kept\n"), stderr); } else { psql_error("\\connect: %s", PQerrorMessage(n_conn)); if (o_conn) { PQfinish(o_conn); pset.db = NULL; } } PQfinish(n_conn); return false; } /* * Replace the old connection with the new one, and update * connection-dependent variables. */ PQsetNoticeProcessor(n_conn, NoticeProcessor, NULL); pset.db = n_conn; SyncVariables(); connection_warnings(false); /* Must be after SyncVariables */ /* Tell the user about the new connection */ if (!pset.quiet) { if (param_is_newly_set(PQhost(o_conn), PQhost(pset.db)) || param_is_newly_set(PQport(o_conn), PQport(pset.db))) { char *host = PQhost(pset.db); if (host == NULL) host = DEFAULT_PGSOCKET_DIR; /* If the host is an absolute path, the connection is via socket */ if (is_absolute_path(host)) printf(_("You are now connected to database \"%s\" as user \"%s\" via socket in \"%s\" at port \"%s\".\n"), PQdb(pset.db), PQuser(pset.db), host, PQport(pset.db)); else printf(_("You are now connected to database \"%s\" as user \"%s\" on host \"%s\" at port \"%s\".\n"), PQdb(pset.db), PQuser(pset.db), host, PQport(pset.db)); } else printf(_("You are now connected to database \"%s\" as user \"%s\".\n"), PQdb(pset.db), PQuser(pset.db)); } if (o_conn) PQfinish(o_conn); return true; }
void pgsql_session_switch_database(GSQLSession *session, gchar *database) { GSQL_TRACE_FUNC; GSQLEPGSQLSession *spec_session; GValue gpass={0, }, ghost={0, }; PGconn *conn, *newconn; const gchar *username = NULL, *password = NULL, *hostname = NULL, *currentdb = NULL, *port = NULL; g_return_if_fail(GSQL_IS_SESSION(session)); spec_session = session->spec; conn = spec_session->pgconn; // Retrieving current database from connection. Session holds the // initial database, not the current one. currentdb = PQdb(conn); if ( ! g_strcmp0(currentdb, database) ) { GSQL_DEBUG("Database: Already connected to requested db."); return; } // Retrieving hostname from session g_value_init (&ghost, G_TYPE_STRING); g_object_get_property (G_OBJECT (session), "session-hostname", &ghost); hostname = g_value_get_string(&ghost); // Retrieving password from session g_value_init (&gpass, G_TYPE_STRING); g_object_get_property (G_OBJECT (session), "session-password", &gpass); password = g_value_get_string(&gpass); // Retrieving username from connection (retrieving it from session // returns NULL) username = PQuser(conn); port = PQport(conn); if ( ! ( newconn = g_hash_table_lookup(spec_session->hash_conns, database) ) ) { newconn = PQsetdbLogin(hostname, port, NULL, NULL, database, username, password); if ( newconn && PQstatus(newconn) == CONNECTION_OK) { GSQL_DEBUG("Database: Successfully switched to [%s]", database); g_hash_table_insert (spec_session->hash_conns, database, newconn); } else { GSQL_DEBUG("Database: Switching to [%s] fail. "\ "Keep with [%s].", database, currentdb); newconn = conn; } } else { GSQL_DEBUG("Database: using previously opened connection."); } spec_session->pgconn = newconn; }
/* * Connect to the db again. * * Note: it's not really all that sensible to use a single-entry password * cache if the username keeps changing. In current usage, however, the * username never does change, so one savedPassword is sufficient. We do * update the cache on the off chance that the password has changed since the * start of the run. */ static PGconn * _connectDB(ArchiveHandle *AH, const char *reqdb, const char *requser) { PGconn *newConn; const char *newdb; const char *newuser; char *password; bool new_pass; if (!reqdb) newdb = PQdb(AH->connection); else newdb = reqdb; if (!requser || strlen(requser) == 0) newuser = PQuser(AH->connection); else newuser = requser; ahlog(AH, 1, "connecting to database \"%s\" as user \"%s\"\n", newdb, newuser); password = AH->savedPassword ? pg_strdup(AH->savedPassword) : NULL; if (AH->promptPassword == TRI_YES && password == NULL) { password = simple_prompt("Password: "******"out of memory\n"); } do { const char *keywords[7]; const char *values[7]; keywords[0] = "host"; values[0] = PQhost(AH->connection); keywords[1] = "port"; values[1] = PQport(AH->connection); keywords[2] = "user"; values[2] = newuser; keywords[3] = "password"; values[3] = password; keywords[4] = "dbname"; values[4] = newdb; keywords[5] = "fallback_application_name"; values[5] = progname; keywords[6] = NULL; values[6] = NULL; new_pass = false; newConn = PQconnectdbParams(keywords, values, true); if (!newConn) exit_horribly(modulename, "failed to reconnect to database\n"); if (PQstatus(newConn) == CONNECTION_BAD) { if (!PQconnectionNeedsPassword(newConn)) exit_horribly(modulename, "could not reconnect to database: %s", PQerrorMessage(newConn)); PQfinish(newConn); if (password) fprintf(stderr, "Password incorrect\n"); fprintf(stderr, "Connecting to %s as %s\n", newdb, newuser); if (password) free(password); if (AH->promptPassword != TRI_NO) password = simple_prompt("Password: "******"connection needs password\n"); if (password == NULL) exit_horribly(modulename, "out of memory\n"); new_pass = true; } } while (new_pass); /* * We want to remember connection's actual password, whether or not we got * it by prompting. So we don't just store the password variable. */ if (PQconnectionUsedPassword(newConn)) { if (AH->savedPassword) free(AH->savedPassword); AH->savedPassword = pg_strdup(PQpass(newConn)); } if (password) free(password); /* check for version mismatch */ _check_database_version(AH); PQsetNoticeProcessor(newConn, notice_processor, NULL); return newConn; }
void dbgPgThread::noticeHandler( void *arg, const char *message ) { // Remove the last char from the message as it'll be a \n wxString msg = wxString(message, wxConvUTF8); if (msg.EndsWith(wxT("\n"))) msg.RemoveLast(); wxLogInfo(wxT("%s"), msg.c_str()); dbgPgThread *thread = (dbgPgThread *)arg; wxEvtHandler *caller = thread->m_currentCommand->getCaller(); if( strstr( message, "PLDBGBREAK" )) { wxStringTokenizer tokens( wxString( message, wxConvUTF8 ), wxT( ":\n" )); wxString NOTICE = tokens.GetNextToken(); // NOTICE: wxString PLDBGBREAK = tokens.GetNextToken(); // PLDBGBREAK: wxString PORT = tokens.GetNextToken(); // port PGconn *conn = thread->m_owner.getConnection(); // Create a dbgConnProp object that contains the same information in a // more convenient format dbgConnProp *debugProps = new dbgConnProp; debugProps->m_host = wxString( PQhost( conn ), wxConvUTF8 ); debugProps->m_database = wxString( PQdb( conn ), wxConvUTF8 ); debugProps->m_userName = wxString( PQuser( conn ), wxConvUTF8 ); debugProps->m_debugPort = PORT; debugProps->m_port = wxString( PQport( conn ), wxConvUTF8 ); debugProps->m_password = wxString( PQpass( conn ), wxConvUTF8 ); wxCommandEvent buttonEvent( wxEVT_COMMAND_BUTTON_CLICKED, MENU_ID_SPAWN_DEBUGGER ); buttonEvent.SetClientData((wxClientData *)debugProps ); caller->AddPendingEvent( buttonEvent ); } else if( strstr( message, "INFO" )) { if( strstr( message, "CONTEXT:" ) == NULL ) { wxCommandEvent buttonEvent( wxEVT_COMMAND_BUTTON_CLICKED, MENU_ID_NOTICE_RECEIVED ); wxString strippedMessage( wxString( message, wxConvUTF8 )); strippedMessage.Replace( wxT( "INFO: " ), wxT( "" ), false ); buttonEvent.SetString( strippedMessage ); caller->AddPendingEvent( buttonEvent ); } } else { wxCommandEvent buttonEvent( wxEVT_COMMAND_BUTTON_CLICKED, MENU_ID_NOTICE_RECEIVED ); buttonEvent.SetString( wxString( message, wxConvUTF8 ) ); caller->AddPendingEvent( buttonEvent ); } }
int main (int argc, char *argv[]) { volatile int errcode = 0; int c; char *procname = argv[0]; int forceprompt = false; int needpass = false; char *filename = NULL; char *username = NULL; char *database = NULL; char *hostname = NULL; char *port = NULL; mapred_olist_t *documents; mapred_olist_t *doc_item; FILE *file; /* The long_options structure */ static struct option long_options[] = { {"help", no_argument, 0, '?'}, {"version", no_argument, 0, 'V'}, {"verbose", no_argument, 0, 'v'}, {"password", no_argument, 0, 'W'}, {"explain", no_argument, 0, 'x'}, {"explain-analyze", no_argument, 0, 'X'}, {"username", required_argument, 0, 'U'}, {"host", required_argument, 0, 'h'}, {"port", required_argument, 0, 'p'}, {"file", required_argument, 0, 'f'}, {"key", required_argument, 0, 'k'}, #ifdef INTERNAL_BUILD {"print", no_argument, 0, 'P'}, {"debug", no_argument, 0, 'D'}, #endif {0, 0, 0, 0} }; #ifdef INTERNAL_BUILD static char* short_options = "VvWxXU:h:p:f:k:?PD"; #else static char* short_options = "VvWxXU:h:p:f:k:?"; #endif while (1) { int option_index = 0; c = getopt_long(argc, argv, short_options, long_options, &option_index); if (c == -1) break; /* done processing options */ switch (c) { case '?': /* --help */ /* Actual help option given */ if (strcmp(argv[optind - 1], "-?") == 0 || strcmp(argv[optind - 1], "--help") == 0) { usage(procname, true); exit(0); } /* unknown option reported by getopt */ fprintf(stderr, "Try \"%s --help\" for usage information.\n", procname); exit(1); case 'V': /* --version */ showVersion(procname); exit(0); case 'v': /* --verbose */ global_verbose_flag = true; break; case 'x': /* --explain */ global_explain_flag |= global_explain; break; case 'X': /* --explain-analyze */ global_explain_flag |= global_explain | global_analyze; break; #ifdef INTERNAL_BUILD case 'P': /* --print (INTERNAL_BUILD only) */ global_print_flag = 1; break; case 'D': /* --debug (INTERNAL_BUILD only) */ global_debug_flag = 1; break; #endif case 'W': /* --password */ forceprompt = true; break; case 'U': /* --username */ username = optarg; break; case 'h': /* --host */ hostname = optarg; break; case 'p': /* --port */ port = optarg; break; case 'f': /* --file */ filename = optarg; break; case 'k': /* --key */ { mapred_plist_t *newitem; char *name = optarg; char *value = NULL; char *eq = strchr(name, '='); /* * either --key value : sets parameter named "key" * or --key name=value : sets parameter named "name" */ if (eq) { eq[0] = '\0'; value = eq+1; /* make sure parameter is a valid name */ if (strspn(name, wordchars) != strlen(name)) { fprintf(stderr, "bad parameter --key %s\n", name); exit(1); } } else { value = name; name = "key"; } /* Add the parameter to the global parameter list */ newitem = malloc(sizeof(mapred_plist_t)); newitem->name = name; newitem->type = value; newitem->next = global_plist; global_plist = newitem; } break; default: /* not feasible */ fprintf(stderr, "Error processing options\n"); exit(1); } } /* open the file */ if (!filename) { usage(procname, false); exit(1); } file = fopen(filename, "rb"); if (!file) { fprintf(stderr, "Error: Could not open file '%s'\n", filename); exit(1); } /* * Handle additional arguments as would psql: * - First argument is database * - Second argument is username, if not specified via -U * - All other arguments generate warnings */ if (optind < argc && !database) database = argv[optind++]; if (optind < argc && !username) username = argv[optind++]; while (optind < argc) { fprintf(stderr, "%s: warning: extra command-line argument \"%s\" ignored\n", procname, argv[optind++]); } if (global_verbose_flag) { mapred_plist_t *param = global_plist; while (param) { fprintf(stderr, "- Parameter: %s=%s\n", param->name, param->type); param = param->next; } fprintf(stderr, "- Parsing '%s':\n", filename); } documents = NULL; XTRY { documents = mapred_parse_file(file); } XCATCH(ASSERTION_FAILURE) { fprintf(stderr, "Assertion failure at %s:%d\n", xframe.file, xframe.lineno); exit(1); } XCATCH_ANY { if (global_verbose_flag) fprintf(stderr, " - "); if (xframe.exception) fprintf(stderr, "Error: %s\n", (char *) xframe.exception); else fprintf(stderr, "Unknown Error (%d) at %s:%d\n", xframe.errcode, xframe.file, xframe.lineno); exit(1); } XTRY_END; /* Do something interesting with documents */ for (doc_item = documents; doc_item; doc_item = doc_item->next) { PGconn *conn = NULL; char pwdbuf[100]; char portbuf[11]; /* max int size should be 10 digits */ char *user, *db, *host, *pwd, *pqport, *options, *tty; XTRY { mapred_document_t *doc = &doc_item->object->u.document; if (global_verbose_flag) { fprintf(stderr, "- Executing Document %d:\n", doc->id); } if (port) { pqport = port; } else if (doc->port > 0) { snprintf(portbuf, sizeof(portbuf), "%d", doc->port); pqport = portbuf; } else { pqport = NULL; } if (database) db = database; else db = doc->database; if (username) user = username; else user = doc->user; if (hostname) host = hostname; else host = doc->host; options = NULL; tty = NULL; pwd = NULL; if (forceprompt) { read_password(pwdbuf, sizeof(pwdbuf)); pwd = pwdbuf; } do { conn = PQsetdbLogin(host, pqport, options, tty, db, user, pwd); needpass = false; if (PQstatus(conn) == CONNECTION_BAD && !strcmp(PQerrorMessage(conn), PQnoPasswordSupplied)) { PQfinish(conn); read_password(pwdbuf, sizeof(pwdbuf)); pwd = pwdbuf; needpass = true; } } while (needpass); if (PQstatus(conn) == CONNECTION_BAD) { XRAISE(CONNECTION_ERROR, PQerrorMessage(conn)); } else { if (global_verbose_flag) { fprintf(stderr, " - Connected Established:\n"); fprintf(stderr, " HOST: %s\n", PQhost(conn) ? PQhost(conn) : "localhost"); fprintf(stderr, " PORT: %s\n", PQport(conn)); fprintf(stderr, " USER: %s/%s\n", PQuser(conn), PQdb(conn)); } check_version(conn); /* Prepare to receive interupts */ cancelConn = PQgetCancel(conn); if (signal(SIGINT, sigint_handler) == SIG_IGN) signal(SIGINT, SIG_IGN); if (signal(SIGHUP, sigint_handler) == SIG_IGN) signal(SIGHUP, SIG_IGN); if (signal(SIGTERM, sigint_handler) == SIG_IGN) signal(SIGTERM, SIG_IGN); mapred_run_document(conn, doc); } } XCATCH(ASSERTION_FAILURE) { fprintf(stderr, "Assertion failure at %s:%d\n", xframe.file, xframe.lineno); errcode = 1; } XCATCH(USER_INTERUPT) { if (global_verbose_flag) fprintf(stderr, " - "); fprintf(stderr, "Job Cancelled: User Interrupt"); exit(2); /* exit immediately */ } XCATCH_ANY { if (global_verbose_flag) fprintf(stderr, " - "); if (xframe.exception) fprintf(stderr, "Error: %s\n", (char *) xframe.exception); else fprintf(stderr, "Unknown Error (%d) at %s:%d\n", xframe.errcode, xframe.file, xframe.lineno); errcode = 1; } XFINALLY { /* Ignore signals until we exit */ signal(SIGINT, SIG_IGN); signal(SIGHUP, SIG_IGN); signal(SIGTERM, SIG_IGN); PQfreeCancel(cancelConn); cancelConn = NULL; PQfinish(conn); } XTRY_END; } /* Cleanup */ mapred_destroy_olist(&documents); fclose(file); return errcode; }
/*----- * The mother of all C functions *----- */ int main(int argc, char **argv) { LODumpMaster _pgLO, *pgLO = &_pgLO; char *pwd = NULL; pgLO->argv = argv; pgLO->argc = argc; pgLO->action = 0; pgLO->lolist = NULL; pgLO->user = NULL; pgLO->db = NULL; pgLO->host = NULL; pgLO->port = NULL; pgLO->space = NULL; pgLO->index = NULL; pgLO->remove = FALSE; pgLO->quiet = FALSE; pgLO->counter = 0; pgLO->lolist_start = 0; progname = argv[0]; /* * Parse ARGV */ if (argc > 1) { int arg; extern int optind; int l_index = 0; static struct option l_opt[] = { {"help", no_argument, 0, 'h'}, {"user", required_argument, 0, 'u'}, {"pwd", required_argument, 0, 'p'}, {"db", required_argument, 0, 'd'}, {"host", required_argument, 0, 'h'}, {"port", required_argument, 0, 'o'}, {"space", required_argument, 0, 's'}, {"import", no_argument, 0, 'i'}, {"export", no_argument, 0, 'e'}, {"remove", no_argument, 0, 'r'}, {"quiet", no_argument, 0, 'q'}, {"all", no_argument, 0, 'a'}, {"show", no_argument, 0, 'w'}, {NULL, 0, 0, 0} }; while ((arg = getopt_long(argc, argv, "?aeho:u:p:qd:l:t:irs:w", l_opt, &l_index)) != -1) { switch (arg) { case '?': case 'h': usage(); exit(RE_OK); case 'u': pgLO->user = strdup(optarg); break; case 't': pgLO->host = strdup(optarg); break; case 'o': pgLO->port = strdup(optarg); break; case 'p': pwd = strdup(optarg); break; case 'd': pgLO->db = strdup(optarg); break; case 's': pgLO->space = strdup(optarg); break; case 'i': pgLO->action = ACTION_IMPORT; break; case 'l': pgLO->action = ACTION_EXPORT_ATTR; pgLO->lolist_start = optind - 1; parse_lolist(pgLO); break; case 'e': case 'a': pgLO->action = ACTION_EXPORT_ALL; break; case 'w': pgLO->action = ACTION_SHOW; break; case 'r': pgLO->remove = TRUE; break; case 'q': pgLO->quiet = TRUE; break; default: fprintf(stderr, "%s: bad arg -%c\n", progname, arg); usage(); exit(RE_ERROR); } } } else { usage(); exit(RE_ERROR); } /* * Check space */ if (pgLO->space==NULL && pgLO->action != ACTION_SHOW) { if (!(pgLO->space = getenv("PWD"))) pgLO->space = "."; } if (!pgLO->action) { fprintf(stderr, "%s: What do you want - export or import?\n", progname); exit(RE_ERROR); } /* * Make connection */ pgLO->conn = PQsetdbLogin(pgLO->host, pgLO->port, NULL, NULL, pgLO->db, pgLO->user, pwd); if (PQstatus(pgLO->conn) == CONNECTION_BAD) { fprintf(stderr, "%s (connection): %s\n", progname, PQerrorMessage(pgLO->conn)); exit(RE_ERROR); } pgLO->host = PQhost(pgLO->conn) ? PQhost(pgLO->conn) : "localhost"; pgLO->db = PQdb(pgLO->conn); pgLO->user = PQuser(pgLO->conn); /* * Init index file */ if (pgLO->action != ACTION_SHOW) index_file(pgLO); PQexec(pgLO->conn, "SET search_path = public"); PQexec(pgLO->conn, "BEGIN"); switch (pgLO->action) { case ACTION_SHOW: case ACTION_EXPORT_ALL: load_lolist(pgLO); /* FALL THROUGH */ case ACTION_EXPORT_ATTR: pglo_export(pgLO); if (!pgLO->quiet) { if (pgLO->action == ACTION_SHOW) printf("\nDatabase '%s' contains %d large objects.\n\n", pgLO->db, pgLO->counter); else printf("\nExported %d large objects.\n\n", pgLO->counter); } break; case ACTION_IMPORT: pglo_import(pgLO); if (!pgLO->quiet) printf("\nImported %d large objects.\n\n", pgLO->counter); break; } PQexec(pgLO->conn, "COMMIT"); PQfinish(pgLO->conn); if (pgLO->action != ACTION_SHOW) fclose(pgLO->index); exit(RE_OK); }
int main(int argc, char *argv[]) { /* First, we need to take in input from the items file. */ if (argc != 6) { printf("Usage: workload total alpha beta gamma delta\n"); printf("The values for alpha, beta, gamma and delta need to be integers that sum to 100.\n"); exit(0); } int i, j, k, numrecs; // These are the parameters that come from the user. int total, nalpha, nbeta, ngamma, ndelta; // These represent thresholds. int talpha, tbeta, tgamma, tdelta; // These are derived parameters from the database. int alphacells, betacells, gammacells, deltacells; char **recs; PGconn *psql; AttributeInfo *head_alpha, *head_beta, *head_gamma, *head_delta; AttributeInfo *tail_alpha, *tail_beta, *tail_gamma, *tail_delta; AttributeInfo **alpha, **beta, **gamma, **delta; head_alpha = NULL; head_beta = NULL; head_gamma = NULL; head_delta = NULL; tail_alpha = NULL; tail_beta = NULL; tail_gamma = NULL; tail_delta = NULL; // Storing our parameters. total = atoi(argv[1]); nalpha = atoi(argv[2]); nbeta = atoi(argv[3]); ngamma = atoi(argv[4]); ndelta = atoi(argv[5]); // Establish thresholds for our RNG. tdelta = 100 - ndelta; tgamma = tdelta - ngamma; tbeta = tgamma - nbeta; talpha = 0; if (nalpha+nbeta+ngamma+ndelta != 100) { printf("The values for alpha, beta, gamma and delta need to be integers that sum to 100.\n"); exit(0); } // Seeding our RNG. srand(time(NULL)); // We start off by getting a recommender list. recs = recommenderList(&numrecs); printf("Numrecs: %d\n",numrecs); /* Connect to the database. */ psql = PQconnectdb("host = 'localhost' port = '5432' dbname = 'recathon'"); if (PQstatus(psql) != CONNECTION_OK) printf("bad conn\n"); printf("%s, %s, %s, %s, %s\n",PQdb(psql), PQuser(psql), PQpass(psql), PQhost(psql), PQport(psql)); if (psql == NULL) printf("connection failed\n"); // Next, we need to query the index of each recommender, to get the attribute information and // cell types. for (i = 0; i < numrecs; i++) { char *querystring, *celltype; PGresult *query; int rows, cols; AttributeInfo *newatt; querystring = (char*) malloc(1024*sizeof(char)); // Since we don't know all of the attributes, we need to request everything. sprintf(querystring,"select * from %sindex;",recs[i]); query = PQexec(psql,querystring); rows = PQntuples(query); cols = PQnfields(query); // A new AttributeInfo for each row. for (j = 0; j < rows; j++) { // Get query information. Cell type is attribute #8. Recommender-specific // attributes begin at #13. newatt = (AttributeInfo*) malloc(sizeof(AttributeInfo)); newatt->next = NULL; newatt->recname = (char*) malloc(128*sizeof(char)); sprintf(newatt->recname,"%s",recs[i]); newatt->numatts = cols - 12; newatt->attnames = (char**) malloc(newatt->numatts*sizeof(char*)); for (k = 0; k < newatt->numatts; k++) newatt->attnames[k] = (char*) malloc(64*sizeof(char)); newatt->attvalues = (char**) malloc(newatt->numatts*sizeof(char*)); for (k = 0; k < newatt->numatts; k++) newatt->attvalues[k] = (char*) malloc(64*sizeof(char)); celltype = PQgetvalue(query,j,7); if (strcmp(celltype,"Alpha") == 0) newatt->celltype = CELL_ALPHA; else if (strcmp(celltype,"Beta") == 0) newatt->celltype = CELL_BETA; else if (strcmp(celltype,"Gamma") == 0) newatt->celltype = CELL_GAMMA; else newatt->celltype = CELL_DELTA; // Get column information. for (k = 0; k < cols-12; k++) { sprintf(newatt->attnames[k],"%s",PQfname(query,k+12)); sprintf(newatt->attvalues[k],"%s",PQgetvalue(query,j,k+12)); } // With the item complete, we put it into the appropriate bucket. switch (newatt->celltype) { case CELL_ALPHA: if (!head_alpha) { head_alpha = newatt; tail_alpha = newatt; } else { tail_alpha->next = newatt; tail_alpha = newatt; } break; case CELL_BETA: if (!head_beta) { head_beta = newatt; tail_beta = newatt; } else { tail_beta->next = newatt; tail_beta = newatt; } break; case CELL_GAMMA: if (!head_gamma) { head_gamma = newatt; tail_gamma = newatt; } else { tail_gamma->next = newatt; tail_gamma = newatt; } break; default: if (!head_delta) { head_delta = newatt; tail_delta = newatt; } else { tail_delta->next = newatt; tail_delta = newatt; } break; } } PQclear(query); free(querystring); } // For easy randomization, we should flatten our AttributeInfo lists. alpha = flatten(head_alpha, &alphacells); beta = flatten(head_beta, &betacells); gamma = flatten(head_gamma, &gammacells); delta = flatten(head_delta, &deltacells); // DEBUG: loop through the lists of alpha/beta/gamma/delta cells and print info. if (DEBUG) { printf("--- ALPHA CELLS ---\n"); printCellList(alpha, alphacells); printf("--- BETA CELLS ---\n"); printCellList(beta, betacells); printf("--- GAMMA CELLS ---\n"); printCellList(gamma, gammacells); printf("--- DELTA CELLS ---\n"); printCellList(delta, deltacells); } // One more thing we need to do is obtain a list of users that will work for // each AttributeInfo. We can semi-randomize by sorting based on zip code. addUsers(alpha, alphacells, psql); addUsers(beta, betacells, psql); addUsers(gamma, gammacells, psql); addUsers(delta, deltacells, psql); // Now to issue the given number of queries, with the frequencies established // probabilistically. for (i = 0; i < total; i++) { int randnum, randatt, randuser, userid; recathon_cell celltype; bool valid = false; PGresult *workquery; char *qstring; AttributeInfo *queryatt; // It's possible one of our buckets will have nothing in it, so // we need to continue choosing until we get something valid. while (!valid) { // A RNG chooses which kind of cell we work with. randnum = rand() % 100; if (randnum < tbeta) { if (alphacells > 0) { valid = true; celltype = CELL_ALPHA; } } else if (randnum < tgamma) { if (betacells > 0) { valid = true; celltype = CELL_BETA; } } else if (randnum < tdelta) { if (gammacells > 0) { valid = true; celltype = CELL_GAMMA; } } else { if (deltacells > 0) { valid = true; celltype = CELL_DELTA; } } } // Depending on our cell type, we'll have a different set of possible // queries to issue; we can choose from the alpha, beta, gamma or delta // buckets. Which item we get is also random. switch (celltype) { case CELL_ALPHA: randatt = rand() % alphacells; queryatt = alpha[randatt]; break; case CELL_BETA: randatt = rand() % betacells; queryatt = beta[randatt]; break; case CELL_GAMMA: randatt = rand() % gammacells; queryatt = gamma[randatt]; break; default: randatt = rand() % deltacells; queryatt = delta[randatt]; break; } randuser = rand() % 10; userid = queryatt->valid_users[randuser]; qstring = (char*) malloc(1024*sizeof(char)); sprintf(qstring,"select itemid from %s recommend(10) userid=%d",queryatt->recname,userid); if (queryatt->numatts > 0) { strncat(qstring," and ",5); for (j = 0; j < queryatt->numatts; j++) { char addition[128]; sprintf(addition,"%s = '%s' ", queryatt->attnames[j],queryatt->attvalues[j]); strncat(qstring,addition,strlen(addition)); if (j+1 < queryatt->numatts) strncat(qstring,"and ",5); } } strncat(qstring,";",1); workquery = PQexec(psql,qstring); PQclear(workquery); free(qstring); } PQfinish(psql); }
bool GetRestoreSegmentDatabaseArray(PGconn *pConn, RestorePairArray * restorePairAr, BackupLoc backupLocation, char *restore_set_str, bool dataOnly) { bool bRtn = true; PQExpBuffer pQry = NULL; PGresult *pRes = NULL; int ntups; int count; int i_dbid; int i_content; int i_host; int i_port; int i; int j; int x; int dbidset_count = 0; int *dbidset = NULL; SegmentDatabase *sourceSegDB; SegmentDatabase *targetSegDB; pQry = createPQExpBuffer(); appendPQExpBuffer(pQry, "SELECT" " dbid," " content," " hostname," " port " "FROM " " gp_segment_configuration " "WHERE role='p' " "ORDER BY content DESC"); pRes = PQexec(pConn, pQry->data); if (!pRes || PQresultStatus(pRes) != PGRES_TUPLES_OK) { mpp_err_msg("ERROR", "gp_restore", "query to obtain list of Greenplum segment databases failed: %s", PQerrorMessage(pConn)); bRtn = false; goto cleanup; } ntups = PQntuples(pRes); if (ntups <= 0) { mpp_err_msg("ERROR", "gp_restore", "no Greenplum segment databases found on master segment schema"); bRtn = false; goto cleanup; } count = ntups + 1; /* * Allocate enough memory for all of them, even though some may be * filtered out. */ restorePairAr->count = 0; restorePairAr->pData = (RestorePair *) calloc(count, sizeof(RestorePair)); if (restorePairAr->pData == NULL) { mpp_err_msg("ERROR", "gp_restore", "Unable to allocate memory for Greenplum segment database information\n"); bRtn = false; goto cleanup; } /* get the column numbers */ i_dbid = PQfnumber(pRes, "dbid"); i_content = PQfnumber(pRes, "content"); i_host = PQfnumber(pRes, "hostname"); i_port = PQfnumber(pRes, "port"); /* * if the dump file is on individual databases, parse the list of dbid's * where those files exist. */ if (backupLocation == FILE_ON_INDIVIDUAL) { /* allocate dbidset. len is more than we need but it's a safe bet */ dbidset = (int *) calloc(strlen(restore_set_str), sizeof(int)); MemSet(dbidset, 0, strlen(restore_set_str) * sizeof(int)); if (dbidset == NULL) { mpp_err_msg("ERROR", "gp_restore", "Unable to allocate memory for Greenplum dbidset information\n"); bRtn = false; goto cleanup; } /* parse the user specified dbid list, return dbid count */ dbidset_count = parseDbidSet(dbidset, restore_set_str); if (dbidset_count < 1) { bRtn = false; goto cleanup; } for (i = 0; i < dbidset_count; i++) { bool match = false; for (j = 0; j < ntups; j++) { int dbid = atoi(PQgetvalue(pRes, j, i_dbid)); if (dbid == dbidset[i]) { match = true; break; } } if (!match) { mpp_err_msg("ERROR", "gp_restore", "dbid %d is not a primary Greenplum segment databases entry\n", dbidset[i]); bRtn = false; goto cleanup; } } } mpp_err_msg("INFO", "gp_restore", "Preparing to restore the following segments:\n"); /* Read through the results set. */ x = 0; for (i = 0; i < ntups; i++) { int dbid = atoi(PQgetvalue(pRes, i, i_dbid)); int contentid = atoi(PQgetvalue(pRes, i, i_content)); bool should_restore = false; /* if dataOnly don't restore the master (table definitions) */ if (dataOnly && contentid == -1) continue; if (backupLocation == FILE_ON_INDIVIDUAL) { should_restore = false; for (j = 0; j < dbidset_count; j++) { if (dbid == dbidset[j]) should_restore = true; } if (!should_restore) continue; } targetSegDB = &restorePairAr->pData[x].segdb_target; targetSegDB->dbid = dbid; targetSegDB->role = (contentid == -1 ? ROLE_MASTER : ROLE_SEGDB); targetSegDB->port = atoi(PQgetvalue(pRes, i, i_port)); targetSegDB->pszHost = strdup(PQgetvalue(pRes, i, i_host)); targetSegDB->pszDBName = PQdb(pConn); targetSegDB->pszDBUser = PQuser(pConn); targetSegDB->pszDBPswd = PQpass(pConn); targetSegDB->content = contentid; sourceSegDB = &restorePairAr->pData[x].segdb_source; sourceSegDB->dbid = targetSegDB->dbid; sourceSegDB->role = targetSegDB->role; sourceSegDB->port = targetSegDB->port; sourceSegDB->pszHost = targetSegDB->pszHost; sourceSegDB->pszDBName = targetSegDB->pszDBName; sourceSegDB->pszDBUser = targetSegDB->pszDBUser; if (targetSegDB->pszDBPswd) sourceSegDB->pszDBPswd = targetSegDB->pszDBPswd; if (targetSegDB->role == ROLE_MASTER) mpp_err_msg("INFO", "gp_restore", "Master (dbid 1)\n"); else mpp_err_msg("INFO", "gp_restore", "Segment %d (dbid %d)\n", contentid, targetSegDB->dbid); x++; } /* set the count to be the number that passed the set inclusion test */ restorePairAr->count = x; cleanup: if (pQry != NULL) destroyPQExpBuffer(pQry); if (pRes != NULL) PQclear(pRes); return bRtn; }
int main (int argc, char **argv) { PGconn *conn; char *conninfo = NULL; struct timeval start_timeval; struct timeval end_timeval; double elapsed_time; int status = STATE_UNKNOWN; int query_status = STATE_UNKNOWN; /* begin, by setting the parameters for a backend connection if the * parameters are null, then the system will try to use reasonable * defaults by looking up environment variables or, failing that, * using hardwired constants */ pgoptions = NULL; /* special options to start up the backend server */ pgtty = NULL; /* debugging tty for the backend server */ setlocale (LC_ALL, ""); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); /* Parse extra opts if any */ argv=np_extra_opts (&argc, argv, progname); if (process_arguments (argc, argv) == ERROR) usage4 (_("Could not parse arguments")); if (verbose > 2) printf("Arguments initialized\n"); /* Set signal handling and alarm */ if (signal (SIGALRM, timeout_alarm_handler) == SIG_ERR) { usage4 (_("Cannot catch SIGALRM")); } alarm (timeout_interval); if (pgparams) asprintf (&conninfo, "%s ", pgparams); asprintf (&conninfo, "%sdbname = '%s'", conninfo ? conninfo : "", dbName); if (pghost) asprintf (&conninfo, "%s host = '%s'", conninfo, pghost); if (pgport) asprintf (&conninfo, "%s port = '%s'", conninfo, pgport); if (pgoptions) asprintf (&conninfo, "%s options = '%s'", conninfo, pgoptions); /* if (pgtty) -- ignored by PQconnectdb */ if (pguser) asprintf (&conninfo, "%s user = '******'", conninfo, pguser); if (verbose) /* do not include password (see right below) in output */ printf ("Connecting to PostgreSQL using conninfo: %s%s\n", conninfo, pgpasswd ? " password = <hidden>" : ""); if (pgpasswd) asprintf (&conninfo, "%s password = '******'", conninfo, pgpasswd); /* make a connection to the database */ gettimeofday (&start_timeval, NULL); conn = PQconnectdb (conninfo); gettimeofday (&end_timeval, NULL); while (start_timeval.tv_usec > end_timeval.tv_usec) { --end_timeval.tv_sec; end_timeval.tv_usec += 1000000; } elapsed_time = (double)(end_timeval.tv_sec - start_timeval.tv_sec) + (double)(end_timeval.tv_usec - start_timeval.tv_usec) / 1000000.0; if (verbose) printf("Time elapsed: %f\n", elapsed_time); /* check to see that the backend connection was successfully made */ if (verbose) printf("Verifying connection\n"); if (PQstatus (conn) == CONNECTION_BAD) { printf (_("CRITICAL - no connection to '%s' (%s).\n"), dbName, PQerrorMessage (conn)); PQfinish (conn); return STATE_CRITICAL; } else if (elapsed_time > tcrit) { status = STATE_CRITICAL; } else if (elapsed_time > twarn) { status = STATE_WARNING; } else { status = STATE_OK; } if (verbose) { char *server_host = PQhost (conn); int server_version = PQserverVersion (conn); printf ("Successfully connected to database %s (user %s) " "at server %s%s%s (server version: %d.%d.%d, " "protocol version: %d, pid: %d)\n", PQdb (conn), PQuser (conn), PSQL_SOCKET3 (server_host, PQport (conn)), PSQL_SERVER_VERSION3 (server_version), PQprotocolVersion (conn), PQbackendPID (conn)); } printf (_(" %s - database %s (%f sec.)|%s\n"), state_text(status), dbName, elapsed_time, fperfdata("time", elapsed_time, "s", !!(twarn > 0.0), twarn, !!(tcrit > 0.0), tcrit, TRUE, 0, FALSE,0)); if (pgquery) query_status = do_query (conn, pgquery); if (verbose) printf("Closing connection\n"); PQfinish (conn); return (pgquery && query_status > status) ? query_status : status; }
int main() { // próba po³±czenia PGconn *myconnection = PQconnectdb("host=localhost port=5432 dbname=myDb user=mateuszek password=mateuszek"); //PGconn *myconnection = PQconnectdb(""); // sprawdzamy status po³±czenia if(PQstatus(myconnection) == CONNECTION_OK) { printf("connection made\n"); // informacje o po³±czeniu printf("PGDBNAME = %s\n",PQdb(myconnection)); printf("PGUSER = %s\n",PQuser(myconnection)); //printf("PGPASSWORD = %s\n",PQpass(myconnection)); printf("PGPASSWORD = ********\n"); printf("PGHOST = %s\n",PQhost(myconnection)); printf("PGPORT = %s\n",PQport(myconnection)); printf("OPTIONS = %s\n",PQoptions(myconnection)); } else{ printf("connection failed: %s\n", PQerrorMessage(myconnection)); // w razie utraty po³±czenia wywo³anie // PQreset(myconnection); // zamyka op³±czenie i nawi±zuje je raz jeszcze // z dotychczasowymi parametrami PQfinish(myconnection); return EXIT_SUCCESS; } int k=1; int choice; while (k==1){ printf("wpisz: \n"); printf("\t '0': aby zakonczyc\n"); printf("\t '1' : aby utworzyc tabele\n"); printf("\t '2' : aby usunac tabele\n"); printf("\t '3' : aby dodac rekord\n"); printf("\t '4' : aby edytowac rekord\n"); printf("\t '6' : aby wyswietlic wszystkie rekordy\n"); printf("\t '7' : wyszukaj pracownika po dacie urodzenia\n"); printf("\t '8' : wyszukaj pracownika po stanowisku i nazwisku\n"); scanf("\t%d",&choice); switch (choice){ case 1 : system("clear"); createTable(myconnection); break; case 2 : system("clear"); dropTable(myconnection); break; case 3 : system("clear"); addRecord(myconnection); break; case 4 : system("clear"); editRecord(myconnection); break; case 5 : system("clear"); deleteRecord(myconnection); break; case 6 : system("clear"); showAllRecords(myconnection); break; case 7 : system("clear"); searchByBirthDate(myconnection); break; case 8 : system("clear"); searchByPosAndSalary(myconnection); break; default: system("clear"); printf("Nieodpowiedni wybor ('%d').\n\n",choice); } } }
static int c_psql_init (void) { int i; if ((NULL == databases) || (0 == databases_num)) return 0; for (i = 0; i < databases_num; ++i) { c_psql_database_t *db = databases + i; char conninfo[4096]; char *buf = conninfo; int buf_len = sizeof (conninfo); int status; char *server_host; int server_version; /* this will happen during reinitialization */ if (NULL != db->conn) { c_psql_check_connection (db); continue; } status = ssnprintf (buf, buf_len, "dbname = '%s'", db->database); if (0 < status) { buf += status; buf_len -= status; } C_PSQL_PAR_APPEND (buf, buf_len, "host", db->host); C_PSQL_PAR_APPEND (buf, buf_len, "port", db->port); C_PSQL_PAR_APPEND (buf, buf_len, "user", db->user); C_PSQL_PAR_APPEND (buf, buf_len, "password", db->password); C_PSQL_PAR_APPEND (buf, buf_len, "sslmode", db->sslmode); C_PSQL_PAR_APPEND (buf, buf_len, "krbsrvname", db->krbsrvname); C_PSQL_PAR_APPEND (buf, buf_len, "service", db->service); db->conn = PQconnectdb (conninfo); if (0 != c_psql_check_connection (db)) continue; db->proto_version = PQprotocolVersion (db->conn); server_host = PQhost (db->conn); server_version = PQserverVersion (db->conn); log_info ("Sucessfully connected to database %s (user %s) " "at server %s%s%s (server version: %d.%d.%d, " "protocol version: %d, pid: %d)", PQdb (db->conn), PQuser (db->conn), C_PSQL_SOCKET3 (server_host, PQport (db->conn)), C_PSQL_SERVER_VERSION3 (server_version), db->proto_version, PQbackendPID (db->conn)); if (3 > db->proto_version) log_warn ("Protocol version %d does not support parameters.", db->proto_version); } plugin_register_read ("postgresql", c_psql_read); plugin_register_shutdown ("postgresql", c_psql_shutdown); return 0; } /* c_psql_init */
/* * Subroutine to actually try to execute a backslash command. */ static backslashResult exec_command(const char *cmd, PsqlScanState scan_state, PQExpBuffer query_buf) { bool success = true; /* indicate here if the command ran ok or * failed */ backslashResult status = PSQL_CMD_SKIP_LINE; /* * \a -- toggle field alignment This makes little sense but we keep it * around. */ if (strcmp(cmd, "a") == 0) { if (pset.popt.topt.format != PRINT_ALIGNED) success = do_pset("format", "aligned", &pset.popt, pset.quiet); else success = do_pset("format", "unaligned", &pset.popt, pset.quiet); } /* \C -- override table title (formerly change HTML caption) */ else if (strcmp(cmd, "C") == 0) { char *opt = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, true); success = do_pset("title", opt, &pset.popt, pset.quiet); free(opt); } /* * \c or \connect -- connect to database using the specified parameters. * * \c dbname user host port * * If any of these parameters are omitted or specified as '-', the current * value of the parameter will be used instead. If the parameter has no * current value, the default value for that parameter will be used. Some * examples: * * \c - - hst Connect to current database on current port of host * "hst" as current user. \c - usr - prt Connect to current database on * "prt" port of current host as user "usr". \c dbs Connect to * "dbs" database on current port of current host as current user. */ else if (strcmp(cmd, "c") == 0 || strcmp(cmd, "connect") == 0) { char *opt1, *opt2, *opt3, *opt4; opt1 = read_connect_arg(scan_state); opt2 = read_connect_arg(scan_state); opt3 = read_connect_arg(scan_state); opt4 = read_connect_arg(scan_state); success = do_connect(opt1, opt2, opt3, opt4); free(opt1); free(opt2); free(opt3); free(opt4); } /* \cd */ else if (strcmp(cmd, "cd") == 0) { char *opt = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, true); char *dir; if (opt) dir = opt; else { #ifndef WIN32 struct passwd *pw; pw = getpwuid(geteuid()); if (!pw) { psql_error("could not get home directory: %s\n", strerror(errno)); exit(EXIT_FAILURE); } dir = pw->pw_dir; #else /* WIN32 */ /* * On Windows, 'cd' without arguments prints the current * directory, so if someone wants to code this here instead... */ dir = "/"; #endif /* WIN32 */ } if (chdir(dir) == -1) { psql_error("\\%s: could not change directory to \"%s\": %s\n", cmd, dir, strerror(errno)); success = false; } if (pset.dirname) free(pset.dirname); pset.dirname = pg_strdup(dir); canonicalize_path(pset.dirname); if (opt) free(opt); } /* \conninfo -- display information about the current connection */ else if (strcmp(cmd, "conninfo") == 0) { char *db = PQdb(pset.db); char *host = PQhost(pset.db); if (db == NULL) printf(_("You are not connected.\n")); else { if (host == NULL) host = DEFAULT_PGSOCKET_DIR; /* If the host is an absolute path, the connection is via socket */ if (is_absolute_path(host)) printf(_("You are connected to database \"%s\" as user \"%s\" via socket in \"%s\" at port \"%s\".\n"), db, PQuser(pset.db), host, PQport(pset.db)); else printf(_("You are connected to database \"%s\" as user \"%s\" on host \"%s\" at port \"%s\".\n"), db, PQuser(pset.db), host, PQport(pset.db)); } } /* \copy */ else if (pg_strcasecmp(cmd, "copy") == 0) { /* Default fetch-it-all-and-print mode */ instr_time before, after; char *opt = psql_scan_slash_option(scan_state, OT_WHOLE_LINE, NULL, false); if (pset.timing) INSTR_TIME_SET_CURRENT(before); success = do_copy(opt); if (pset.timing && success) { INSTR_TIME_SET_CURRENT(after); INSTR_TIME_SUBTRACT(after, before); printf(_("Time: %.3f ms\n"), INSTR_TIME_GET_MILLISEC(after)); } free(opt); } /* \copyright */ else if (strcmp(cmd, "copyright") == 0) print_copyright(); /* \d* commands */ else if (cmd[0] == 'd') { char *pattern; bool show_verbose, show_system; /* We don't do SQLID reduction on the pattern yet */ pattern = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, true); show_verbose = strchr(cmd, '+') ? true : false; show_system = strchr(cmd, 'S') ? true : false; switch (cmd[1]) { case '\0': case '+': case 'S': /* GPDB: This is a change from old behavior: We used to show just system tables */ if (pattern) success = describeTableDetails(pattern, show_verbose, show_system); else /* standard listing of interesting things */ success = listTables("tvsxr", NULL, show_verbose, show_system); break; case 'a': success = describeAggregates(pattern, show_verbose, show_system); break; case 'b': success = describeTablespaces(pattern, show_verbose); break; case 'c': success = listConversions(pattern, show_system); break; case 'C': success = listCasts(pattern); break; case 'd': if (strncmp(cmd, "ddp", 3) == 0) success = listDefaultACLs(pattern); else success = objectDescription(pattern, show_system); break; case 'D': success = listDomains(pattern, show_system); break; case 'f': /* function subsystem */ switch (cmd[2]) { case '\0': case '+': case 'S': case 'a': case 'n': case 't': case 'w': success = describeFunctions(&cmd[2], pattern, show_verbose, show_system); break; default: status = PSQL_CMD_UNKNOWN; break; } break; case 'g': /* no longer distinct from \du */ success = describeRoles(pattern, show_verbose); break; case 'l': success = do_lo_list(); break; case 'n': success = listSchemas(pattern, show_verbose); break; case 'o': success = describeOperators(pattern, show_system); break; case 'p': success = permissionsList(pattern); break; case 'T': success = describeTypes(pattern, show_verbose, show_system); break; case 't': case 'v': case 'i': case 's': case 'E': /* PostgreSQL use dx for extension, change to dE for foreign table */ /* case 'S': // GPDB: We used to show just system tables for this */ case 'P': /* GPDB: Parent-only tables, no children */ success = listTables(&cmd[1], pattern, show_verbose, show_system); break; case 'r': if (cmd[2] == 'd' && cmd[3] == 's') { char *pattern2 = NULL; if (pattern) pattern2 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, true); success = listDbRoleSettings(pattern, pattern2); } else //success = PSQL_CMD_UNKNOWN; /* GPDB uses \dr for foreign tables ? */ success = listTables(&cmd[1], pattern, show_verbose, show_system); break; case 'u': success = describeRoles(pattern, show_verbose); break; case 'F': /* text search subsystem */ switch (cmd[2]) { case '\0': case '+': success = listTSConfigs(pattern, show_verbose); break; case 'p': success = listTSParsers(pattern, show_verbose); break; case 'd': success = listTSDictionaries(pattern, show_verbose); break; case 't': success = listTSTemplates(pattern, show_verbose); break; default: status = PSQL_CMD_UNKNOWN; break; } break; case 'x': /* Extensions */ if (show_verbose) success = listExtensionContents(pattern); else success = listExtensions(pattern); break; default: status = PSQL_CMD_UNKNOWN; } if (pattern) free(pattern); } /* * \e or \edit -- edit the current query buffer, or edit a file and make * it the query buffer */ else if (strcmp(cmd, "e") == 0 || strcmp(cmd, "edit") == 0) { if (!query_buf) { psql_error("no query buffer\n"); status = PSQL_CMD_ERROR; } else { char *fname; fname = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, true); expand_tilde(&fname); if (fname) canonicalize_path(fname); if (do_edit(fname, query_buf, NULL)) status = PSQL_CMD_NEWEDIT; else status = PSQL_CMD_ERROR; free(fname); } } /* * \ef -- edit the named function, or present a blank CREATE FUNCTION * template if no argument is given */ else if (strcmp(cmd, "ef") == 0) { if (!query_buf) { psql_error("no query buffer\n"); status = PSQL_CMD_ERROR; } else { char *func; Oid foid = InvalidOid; func = psql_scan_slash_option(scan_state, OT_WHOLE_LINE, NULL, true); if (!func) { /* set up an empty command to fill in */ printfPQExpBuffer(query_buf, "CREATE FUNCTION ( )\n" " RETURNS \n" " LANGUAGE \n" " -- common options: IMMUTABLE STABLE STRICT SECURITY DEFINER\n" "AS $function$\n" "\n$function$\n"); } else if (!lookup_function_oid(pset.db, func, &foid)) { /* error already reported */ status = PSQL_CMD_ERROR; } else if (!get_create_function_cmd(pset.db, foid, query_buf)) { /* error already reported */ status = PSQL_CMD_ERROR; } if (func) free(func); } if (status != PSQL_CMD_ERROR) { bool edited = false; if (!do_edit(0, query_buf, &edited)) status = PSQL_CMD_ERROR; else if (!edited) puts(_("No changes")); else status = PSQL_CMD_NEWEDIT; } } /* \echo and \qecho */ else if (strcmp(cmd, "echo") == 0 || strcmp(cmd, "qecho") == 0) { char *value; char quoted; bool no_newline = false; bool first = true; FILE *fout; if (strcmp(cmd, "qecho") == 0) fout = pset.queryFout; else fout = stdout; while ((value = psql_scan_slash_option(scan_state, OT_NORMAL, "ed, false))) { if (!quoted && strcmp(value, "-n") == 0) no_newline = true; else { if (first) first = false; else fputc(' ', fout); fputs(value, fout); } free(value); } if (!no_newline) fputs("\n", fout); } /* \encoding -- set/show client side encoding */ else if (strcmp(cmd, "encoding") == 0) { char *encoding = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false); if (!encoding) { /* show encoding */ puts(pg_encoding_to_char(pset.encoding)); } else { /* set encoding */ if (PQsetClientEncoding(pset.db, encoding) == -1) psql_error("%s: invalid encoding name or conversion procedure not found\n", encoding); else { /* save encoding info into psql internal data */ pset.encoding = PQclientEncoding(pset.db); pset.popt.topt.encoding = pset.encoding; SetVariable(pset.vars, "ENCODING", pg_encoding_to_char(pset.encoding)); } free(encoding); } } /* \f -- change field separator */ else if (strcmp(cmd, "f") == 0) { char *fname = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false); success = do_pset("fieldsep", fname, &pset.popt, pset.quiet); free(fname); } /* \g means send query */ else if (strcmp(cmd, "g") == 0) { char *fname = psql_scan_slash_option(scan_state, OT_FILEPIPE, NULL, false); if (!fname) pset.gfname = NULL; else { expand_tilde(&fname); pset.gfname = pg_strdup(fname); } free(fname); status = PSQL_CMD_SEND; } /* help */ else if (strcmp(cmd, "h") == 0 || strcmp(cmd, "help") == 0) { char *opt = psql_scan_slash_option(scan_state, OT_WHOLE_LINE, NULL, false); size_t len; /* strip any trailing spaces and semicolons */ if (opt) { len = strlen(opt); while (len > 0 && (isspace((unsigned char) opt[len - 1]) || opt[len - 1] == ';')) opt[--len] = '\0'; } helpSQL(opt, pset.popt.topt.pager); free(opt); } /* HTML mode */ else if (strcmp(cmd, "H") == 0 || strcmp(cmd, "html") == 0) { if (pset.popt.topt.format != PRINT_HTML) success = do_pset("format", "html", &pset.popt, pset.quiet); else success = do_pset("format", "aligned", &pset.popt, pset.quiet); } /* \i is include file */ else if (strcmp(cmd, "i") == 0 || strcmp(cmd, "include") == 0) { char *fname = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, true); if (!fname) { psql_error("\\%s: missing required argument\n", cmd); success = false; } else { expand_tilde(&fname); success = (process_file(fname, false) == EXIT_SUCCESS); free(fname); } } /* \l is list databases */ else if (strcmp(cmd, "l") == 0 || strcmp(cmd, "list") == 0) success = listAllDbs(false); else if (strcmp(cmd, "l+") == 0 || strcmp(cmd, "list+") == 0) success = listAllDbs(true); /* * large object things */ else if (strncmp(cmd, "lo_", 3) == 0) { char *opt1, *opt2; opt1 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, true); opt2 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, true); if (strcmp(cmd + 3, "export") == 0) { if (!opt2) { psql_error("\\%s: missing required argument\n", cmd); success = false; } else { expand_tilde(&opt2); success = do_lo_export(opt1, opt2); } } else if (strcmp(cmd + 3, "import") == 0) { if (!opt1) { psql_error("\\%s: missing required argument\n", cmd); success = false; } else { expand_tilde(&opt1); success = do_lo_import(opt1, opt2); } } else if (strcmp(cmd + 3, "list") == 0) success = do_lo_list(); else if (strcmp(cmd + 3, "unlink") == 0) { if (!opt1) { psql_error("\\%s: missing required argument\n", cmd); success = false; } else success = do_lo_unlink(opt1); } else status = PSQL_CMD_UNKNOWN; free(opt1); free(opt2); } /* \o -- set query output */ else if (strcmp(cmd, "o") == 0 || strcmp(cmd, "out") == 0) { char *fname = psql_scan_slash_option(scan_state, OT_FILEPIPE, NULL, true); expand_tilde(&fname); success = setQFout(fname); free(fname); } /* \p prints the current query buffer */ else if (strcmp(cmd, "p") == 0 || strcmp(cmd, "print") == 0) { if (query_buf && query_buf->len > 0) puts(query_buf->data); else if (!pset.quiet) puts(_("Query buffer is empty.")); fflush(stdout); } /* \password -- set user password */ else if (strcmp(cmd, "password") == 0) { char *pw1; char *pw2; pw1 = simple_prompt("Enter new password: "******"Enter it again: ", 100, false); if (strcmp(pw1, pw2) != 0) { fprintf(stderr, _("Passwords didn't match.\n")); success = false; } else { char *opt0 = psql_scan_slash_option(scan_state, OT_SQLID, NULL, true); char *user; char *encrypted_password; if (opt0) user = opt0; else user = PQuser(pset.db); encrypted_password = PQencryptPassword(pw1, user); if (!encrypted_password) { fprintf(stderr, _("Password encryption failed.\n")); success = false; } else { PQExpBufferData buf; PGresult *res; initPQExpBuffer(&buf); printfPQExpBuffer(&buf, "ALTER USER %s PASSWORD ", fmtId(user)); appendStringLiteralConn(&buf, encrypted_password, pset.db); res = PSQLexec(buf.data, false); termPQExpBuffer(&buf); if (!res) success = false; else PQclear(res); PQfreemem(encrypted_password); } } free(pw1); free(pw2); } /* \prompt -- prompt and set variable */ else if (strcmp(cmd, "prompt") == 0) { char *opt, *prompt_text = NULL; char *arg1, *arg2; arg1 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false); arg2 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false); if (!arg1) { psql_error("\\%s: missing required argument\n", cmd); success = false; } else { char *result; if (arg2) { prompt_text = arg1; opt = arg2; } else opt = arg1; if (!pset.inputfile) result = simple_prompt(prompt_text, 4096, true); else { if (prompt_text) { fputs(prompt_text, stdout); fflush(stdout); } result = gets_fromFile(stdin); } if (!SetVariable(pset.vars, opt, result)) { psql_error("\\%s: error\n", cmd); success = false; } free(result); if (prompt_text) free(prompt_text); free(opt); } } /* \pset -- set printing parameters */ else if (strcmp(cmd, "pset") == 0) { char *opt0 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false); char *opt1 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false); if (!opt0) { psql_error("\\%s: missing required argument\n", cmd); success = false; } else success = do_pset(opt0, opt1, &pset.popt, pset.quiet); free(opt0); free(opt1); } /* \q or \quit */ else if (strcmp(cmd, "q") == 0 || strcmp(cmd, "quit") == 0) status = PSQL_CMD_TERMINATE; /* reset(clear) the buffer */ else if (strcmp(cmd, "r") == 0 || strcmp(cmd, "reset") == 0) { resetPQExpBuffer(query_buf); psql_scan_reset(scan_state); if (!pset.quiet) puts(_("Query buffer reset (cleared).")); } /* \s save history in a file or show it on the screen */ else if (strcmp(cmd, "s") == 0) { char *fname = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, true); #if defined(WIN32) && !defined(__CYGWIN__) /* * XXX This does not work for all terminal environments or for output * containing non-ASCII characters; see comments in simple_prompt(). */ #define DEVTTY "con" #else #define DEVTTY "/dev/tty" #endif expand_tilde(&fname); /* This scrolls off the screen when using /dev/tty */ success = saveHistory(fname ? fname : DEVTTY, -1, false, false); if (success && !pset.quiet && fname) printf(gettext("Wrote history to file \"%s/%s\".\n"), pset.dirname ? pset.dirname : ".", fname); if (!fname) putchar('\n'); free(fname); } /* \set -- generalized set variable/option command */ else if (strcmp(cmd, "set") == 0) { char *opt0 = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false); if (!opt0) { /* list all variables */ PrintVariables(pset.vars); success = true; } else { /* * Set variable to the concatenation of the arguments. */ char *newval; char *opt; opt = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false); newval = pg_strdup(opt ? opt : ""); free(opt); while ((opt = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false))) { newval = realloc(newval, strlen(newval) + strlen(opt) + 1); if (!newval) { psql_error("out of memory\n"); exit(EXIT_FAILURE); } strcat(newval, opt); free(opt); } if (!SetVariable(pset.vars, opt0, newval)) { psql_error("\\%s: error\n", cmd); success = false; } free(newval); } free(opt0); } /* \t -- turn off headers and row count */ else if (strcmp(cmd, "t") == 0) { char *opt = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, true); success = do_pset("tuples_only", opt, &pset.popt, pset.quiet); free(opt); } /* \T -- define html <table ...> attributes */ else if (strcmp(cmd, "T") == 0) { char *value = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false); success = do_pset("tableattr", value, &pset.popt, pset.quiet); free(value); } /* \timing -- toggle timing of queries */ else if (strcmp(cmd, "timing") == 0) { char *opt = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false); if (opt) pset.timing = ParseVariableBool(opt); else pset.timing = !pset.timing; if (!pset.quiet) { if (pset.timing) puts(_("Timing is on.")); else puts(_("Timing is off.")); } free(opt); } /* \unset */ else if (strcmp(cmd, "unset") == 0) { char *opt = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, false); if (!opt) { psql_error("\\%s: missing required argument\n", cmd); success = false; } else if (!SetVariable(pset.vars, opt, NULL)) { psql_error("\\%s: error\n", cmd); success = false; } free(opt); } /* \w -- write query buffer to file */ else if (strcmp(cmd, "w") == 0 || strcmp(cmd, "write") == 0) { FILE *fd = NULL; bool is_pipe = false; char *fname = NULL; if (!query_buf) { psql_error("no query buffer\n"); status = PSQL_CMD_ERROR; } else { fname = psql_scan_slash_option(scan_state, OT_FILEPIPE, NULL, true); expand_tilde(&fname); if (!fname) { psql_error("\\%s: missing required argument\n", cmd); success = false; } else { if (fname[0] == '|') { is_pipe = true; fd = popen(&fname[1], "w"); } else { canonicalize_path(fname); fd = fopen(fname, "w"); } if (!fd) { psql_error("%s: %s\n", fname, strerror(errno)); success = false; } } } if (fd) { int result; if (query_buf && query_buf->len > 0) fprintf(fd, "%s\n", query_buf->data); if (is_pipe) result = pclose(fd); else result = fclose(fd); if (result == EOF) { psql_error("%s: %s\n", fname, strerror(errno)); success = false; } } free(fname); } /* \x -- toggle expanded table representation */ else if (strcmp(cmd, "x") == 0) { char *opt = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, true); success = do_pset("expanded", opt, &pset.popt, pset.quiet); free(opt); } /* \z -- list table rights (equivalent to \dp) */ else if (strcmp(cmd, "z") == 0) { char *pattern = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, true); success = permissionsList(pattern); if (pattern) free(pattern); } /* \! -- shell escape */ else if (strcmp(cmd, "!") == 0) { char *opt = psql_scan_slash_option(scan_state, OT_WHOLE_LINE, NULL, false); success = do_shell(opt); free(opt); } /* \? -- slash command help */ else if (strcmp(cmd, "?") == 0) slashUsage(pset.popt.topt.pager); #if 0 /* * These commands don't do anything. I just use them to test the parser. */ else if (strcmp(cmd, "void") == 0 || strcmp(cmd, "#") == 0) { int i = 0; char *value; while ((value = psql_scan_slash_option(scan_state, OT_NORMAL, NULL, true))) { fprintf(stderr, "+ opt(%d) = |%s|\n", i++, value); free(value); } } #endif else status = PSQL_CMD_UNKNOWN; if (!success) status = PSQL_CMD_ERROR; return status; }
char * get_prompt(promptStatus_t status, ConditionalStack cstack) { #define MAX_PROMPT_SIZE 256 static char destination[MAX_PROMPT_SIZE + 1]; char buf[MAX_PROMPT_SIZE + 1]; bool esc = false; const char *p; const char *prompt_string = "? "; switch (status) { case PROMPT_READY: prompt_string = pset.prompt1; break; case PROMPT_CONTINUE: case PROMPT_SINGLEQUOTE: case PROMPT_DOUBLEQUOTE: case PROMPT_DOLLARQUOTE: case PROMPT_COMMENT: case PROMPT_PAREN: prompt_string = pset.prompt2; break; case PROMPT_COPY: prompt_string = pset.prompt3; break; } destination[0] = '\0'; for (p = prompt_string; *p && strlen(destination) < sizeof(destination) - 1; p++) { memset(buf, 0, sizeof(buf)); if (esc) { switch (*p) { /* Current database */ case '/': if (pset.db) strlcpy(buf, PQdb(pset.db), sizeof(buf)); break; case '~': if (pset.db) { const char *var; if (strcmp(PQdb(pset.db), PQuser(pset.db)) == 0 || ((var = getenv("PGDATABASE")) && strcmp(var, PQdb(pset.db)) == 0)) strlcpy(buf, "~", sizeof(buf)); else strlcpy(buf, PQdb(pset.db), sizeof(buf)); } break; /* DB server hostname (long/short) */ case 'M': case 'm': if (pset.db) { const char *host = PQhost(pset.db); /* INET socket */ if (host && host[0] && !is_absolute_path(host)) { strlcpy(buf, host, sizeof(buf)); if (*p == 'm') buf[strcspn(buf, ".")] = '\0'; } #ifdef HAVE_UNIX_SOCKETS /* UNIX socket */ else { if (!host || strcmp(host, DEFAULT_PGSOCKET_DIR) == 0 || *p == 'm') strlcpy(buf, "[local]", sizeof(buf)); else snprintf(buf, sizeof(buf), "[local:%s]", host); } #endif } break; /* DB server port number */ case '>': if (pset.db && PQport(pset.db)) strlcpy(buf, PQport(pset.db), sizeof(buf)); break; /* DB server user name */ case 'n': if (pset.db) strlcpy(buf, session_username(), sizeof(buf)); break; /* backend pid */ case 'p': if (pset.db) { int pid = PQbackendPID(pset.db); if (pid) snprintf(buf, sizeof(buf), "%d", pid); } break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': *buf = (char) strtol(p, (char **) &p, 8); --p; break; case 'R': switch (status) { case PROMPT_READY: if (cstack != NULL && !conditional_active(cstack)) buf[0] = '@'; else if (!pset.db) buf[0] = '!'; else if (!pset.singleline) buf[0] = '='; else buf[0] = '^'; break; case PROMPT_CONTINUE: buf[0] = '-'; break; case PROMPT_SINGLEQUOTE: buf[0] = '\''; break; case PROMPT_DOUBLEQUOTE: buf[0] = '"'; break; case PROMPT_DOLLARQUOTE: buf[0] = '$'; break; case PROMPT_COMMENT: buf[0] = '*'; break; case PROMPT_PAREN: buf[0] = '('; break; default: buf[0] = '\0'; break; } break; case 'x': if (!pset.db) buf[0] = '?'; else switch (PQtransactionStatus(pset.db)) { case PQTRANS_IDLE: buf[0] = '\0'; break; case PQTRANS_ACTIVE: case PQTRANS_INTRANS: buf[0] = '*'; break; case PQTRANS_INERROR: buf[0] = '!'; break; default: buf[0] = '?'; break; } break; case 'l': snprintf(buf, sizeof(buf), UINT64_FORMAT, pset.stmt_lineno); break; case '?': /* not here yet */ break; case '#': if (is_superuser()) buf[0] = '#'; else buf[0] = '>'; break; /* execute command */ case '`': { FILE *fd; char *file = pg_strdup(p + 1); int cmdend; cmdend = strcspn(file, "`"); file[cmdend] = '\0'; fd = popen(file, "r"); if (fd) { if (fgets(buf, sizeof(buf), fd) == NULL) buf[0] = '\0'; pclose(fd); } if (strlen(buf) > 0 && buf[strlen(buf) - 1] == '\n') buf[strlen(buf) - 1] = '\0'; free(file); p += cmdend + 1; break; } /* interpolate variable */ case ':': { char *name; const char *val; int nameend; name = pg_strdup(p + 1); nameend = strcspn(name, ":"); name[nameend] = '\0'; val = GetVariable(pset.vars, name); if (val) strlcpy(buf, val, sizeof(buf)); free(name); p += nameend + 1; break; } case '[': case ']': #if defined(USE_READLINE) && defined(RL_PROMPT_START_IGNORE) /* * readline >=4.0 undocumented feature: non-printing * characters in prompt strings must be marked as such, in * order to properly display the line during editing. */ buf[0] = (*p == '[') ? RL_PROMPT_START_IGNORE : RL_PROMPT_END_IGNORE; buf[1] = '\0'; #endif /* USE_READLINE */ break; default: buf[0] = *p; buf[1] = '\0'; break; } esc = false; } else if (*p == '%') esc = true; else { buf[0] = *p; buf[1] = '\0'; esc = false; } if (!esc) strlcat(destination, buf, sizeof(destination)); } return destination; }
Con_Handle * RS_PostgreSQL_newConnection(Mgr_Handle * mgrHandle, s_object * con_params) { S_EVALUATOR RS_DBI_connection * con; RS_PostgreSQL_conParams *conParams; Con_Handle *conHandle; PGconn *my_connection; const char *user = NULL, *password = NULL, *host = NULL, *dbname = NULL, *port = NULL, *tty = NULL, *options = NULL; if (!is_validHandle(mgrHandle, MGR_HANDLE_TYPE)) { RS_DBI_errorMessage("invalid PostgreSQLManager", RS_DBI_ERROR); } user = CHR_EL(con_params, 0); password = CHR_EL(con_params, 1); host = CHR_EL(con_params, 2); dbname = CHR_EL(con_params, 3); port = CHR_EL(con_params, 4); tty = CHR_EL(con_params, 5); options = CHR_EL(con_params, 6); my_connection = PQsetdbLogin(host, port, options, tty, dbname, user, password); conParams = RS_postgresql_allocConParams(); /* save actual connection parameters */ conParams->user = RS_DBI_copyString(PQuser(my_connection)); conParams->password = RS_DBI_copyString(PQpass(my_connection)); { const char *tmphost = PQhost(my_connection); if (tmphost) { conParams->host = RS_DBI_copyString(tmphost); } else { conParams->host = RS_DBI_copyString(""); } } conParams->dbname = RS_DBI_copyString(PQdb(my_connection)); conParams->port = RS_DBI_copyString(PQport(my_connection)); conParams->tty = RS_DBI_copyString(PQtty(my_connection)); conParams->options = RS_DBI_copyString(PQoptions(my_connection)); if (PQstatus(my_connection) != CONNECTION_OK) { char buf[1000]; sprintf(buf, "could not connect %s@%s on dbname \"%s\"\n", PQuser(my_connection), host?host:"local", PQdb(my_connection)); PQfinish(my_connection); my_connection = NULL; RS_PostgreSQL_freeConParams(conParams); /*free BEFORE emitting err message that do not come back */ RS_DBI_errorMessage(buf, RS_DBI_ERROR); return R_NilValue; /* don't reach here as it goes back to R proc */ } PROTECT(conHandle = RS_DBI_allocConnection(mgrHandle, (Sint) 1)); /* The second argument (1) specifies the number of result sets allocated */ con = RS_DBI_getConnection(conHandle); if (my_connection && !con) { PQfinish(my_connection); my_connection = NULL; RS_PostgreSQL_freeConParams(conParams); conParams = (RS_PostgreSQL_conParams *) NULL; RS_DBI_errorMessage("could not alloc space for connection object", RS_DBI_ERROR); } if(con) { con->drvConnection = (void *) my_connection; con->conParams = (void *) conParams; } UNPROTECT(1); return conHandle; }
std::string DTTablePostgres::getNameAndType() const { return "[" + std::string(PQuser(this->conn)) + "DTTablePostgres] "; }