コード例 #1
0
ファイル: database.cpp プロジェクト: benguillet/dcor_backend
void close_conne(PGconn * conn) {
    PQfinish(conn);
    getchar();
}
コード例 #2
0
ファイル: pgsql_query_util.c プロジェクト: segasai/pg_idl
int
pgsql_query_send(char *query, char *connect_info, IDL_VPTR *resultVptr)
{

    /* connection info */

    PGconn *conn=NULL;
    PGresult *res=NULL;

    int query_status;


    /* Infor about each field */
    field_info *fi;

    /* Structure definition info */
    idl_tag_info *ti;
    //UCHAR *dataPtr;
    char *dataPtr;


    /* temporary pointer to tag data */
    UCHAR *tptr;

    /* loop variables */
    long long row;
    int tag;

    /* binary or ascii? Only need ascii for file output */
    int binary;

    int verbose=0;

    /* Attempt to establish the connection */
    conn = PQconnectdb(connect_info);

    if (PQstatus(conn) != CONNECTION_OK)
    {
        pgsql_query_error("Could not establish connection",
                PQerrorMessage(conn));	
        PQfinish(conn);
        return(MYPG_CONNECT_FAILURE);
    }


    /* send the query and return the results */
    if (kw.file_there) 
        binary = 0;
    else
        binary = 1;

    if (kw.verbose_there)
        if (kw.verbose) 
            verbose = 1;

    if (verbose)
        IDL_Message(IDL_M_NAMED_GENERIC, IDL_MSG_INFO, 
                "Querying database non-asynchronously: you may not cancel. For requests you may cancel don't send the /no_async keyword");

    res = PQexecParams(conn,
            query,
            0,    /* number of parameters (none) */
            NULL, /* see doc for the parameter info */
            NULL,
            NULL,
            NULL,
            binary); /* 0 for text, 1 for binary (network order) */


    /* Success? */
    query_status = pgsql_query_checkstatus(res);
    if (query_status != MYPG_SUCCESS)
    {
        prepExit(conn, res);
        return(query_status);
    }

    /* See if the user input a file to write to */
    if (kw.file_there) 
    {
        int write_status;
        write_status = pgsql_write_file(res);
        prepExit(conn, res);
        return(write_status);
    }


    /* Get information for each returned field */
    fi = pgsql_get_field_info(res);

    /* Copy into output keywords, if they exist */
    pgsql_copy_info(fi);

    /* Get info to make struct and copy data */
    ti = pgsql_get_idl_tag_info(fi->tagdefs);


    /* Create the output structure */  
    if (verbose)
        IDL_Message(IDL_M_NAMED_GENERIC, IDL_MSG_INFO, "Creating output struct");  


    dataPtr = 
        IDL_MakeTempStructVector(ti->sdef, (IDL_MEMINT) fi->nTuples, 
                resultVptr, IDL_TRUE);

    /* Copy into output variable */
    if (verbose)
        IDL_Message(IDL_M_NAMED_GENERIC, IDL_MSG_INFO, "Copying data");  

    for (row=0; row< fi->nTuples; row++)
        for (tag = 0; tag < fi->nFields; tag++)
        {
            tptr = 
                ( (*resultVptr)->value.s.arr->data +
                  row*( (*resultVptr)->value.arr->elt_len) + ti->tagOffsets[tag]);
            pgsql_store_binary(ti->tagDesc[tag]->type, fi->field_isarray[tag],
                    PQgetvalue(res, row, tag), tptr);	      
        }

    if (verbose)
        IDL_Message(IDL_M_NAMED_GENERIC, IDL_MSG_INFO, "Cleaning up");  

    pgsql_freemem(fi, ti);

    PQclear(res);
    PQfinish(conn);

    if (verbose)
        IDL_Message(IDL_M_NAMED_GENERIC, IDL_MSG_INFO, "Done");  


    return(MYPG_SUCCESS);

}
コード例 #3
0
ファイル: dropdb.c プロジェクト: Aldizh/buffer_manager
int
main(int argc, char *argv[])
{
	static struct option long_options[] = {
		{"host", required_argument, NULL, 'h'},
		{"port", required_argument, NULL, 'p'},
		{"username", required_argument, NULL, 'U'},
		{"no-password", no_argument, NULL, 'w'},
		{"password", no_argument, NULL, 'W'},
		{"echo", no_argument, NULL, 'e'},
		{"interactive", no_argument, NULL, 'i'},
		{NULL, 0, NULL, 0}
	};

	const char *progname;
	int			optindex;
	int			c;

	char	   *dbname = NULL;
	char	   *host = NULL;
	char	   *port = NULL;
	char	   *username = NULL;
	enum trivalue prompt_password = TRI_DEFAULT;
	bool		echo = false;
	bool		interactive = false;

	PQExpBufferData sql;

	PGconn	   *conn;
	PGresult   *result;

	progname = get_progname(argv[0]);
	set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pgscripts"));

	handle_help_version_opts(argc, argv, "dropdb", help);

	while ((c = getopt_long(argc, argv, "h:p:U:wWei", long_options, &optindex)) != -1)
	{
		switch (c)
		{
			case 'h':
				host = optarg;
				break;
			case 'p':
				port = optarg;
				break;
			case 'U':
				username = optarg;
				break;
			case 'w':
				prompt_password = TRI_NO;
				break;
			case 'W':
				prompt_password = TRI_YES;
				break;
			case 'e':
				echo = true;
				break;
			case 'i':
				interactive = true;
				break;
			default:
				fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
				exit(1);
		}
	}

	switch (argc - optind)
	{
		case 0:
			fprintf(stderr, _("%s: missing required argument database name\n"), progname);
			fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
			exit(1);
		case 1:
			dbname = argv[optind];
			break;
		default:
			fprintf(stderr, _("%s: too many command-line arguments (first is \"%s\")\n"),
					progname, argv[optind + 1]);
			fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
			exit(1);
	}

	if (interactive)
	{
		printf(_("Database \"%s\" will be permanently removed.\n"), dbname);
		if (!yesno_prompt("Are you sure?"))
			exit(0);
	}

	initPQExpBuffer(&sql);

	appendPQExpBuffer(&sql, "DROP DATABASE %s;\n",
					  fmtId(dbname));

	conn = connectDatabase(strcmp(dbname, "postgres") == 0 ? "template1" : "postgres",
						   host, port, username, prompt_password, progname);

	if (echo)
		printf("%s", sql.data);
	result = PQexec(conn, sql.data);
	if (PQresultStatus(result) != PGRES_COMMAND_OK)
	{
		fprintf(stderr, _("%s: database removal failed: %s"),
				progname, PQerrorMessage(conn));
		PQfinish(conn);
		exit(1);
	}

	PQclear(result);
	PQfinish(conn);
	exit(0);
}
コード例 #4
0
ファイル: oid2name.c プロジェクト: amenonsen/postgres
/* establish connection with database. */
PGconn *
sql_conn(struct options * my_opts)
{
	PGconn	   *conn;
	char	   *password = NULL;
	bool		new_pass;

	/*
	 * Start the connection.  Loop until we have a password if requested by
	 * backend.
	 */
	do
	{
#define PARAMS_ARRAY_SIZE	7

		const char *keywords[PARAMS_ARRAY_SIZE];
		const char *values[PARAMS_ARRAY_SIZE];

		keywords[0] = "host";
		values[0] = my_opts->hostname;
		keywords[1] = "port";
		values[1] = my_opts->port;
		keywords[2] = "user";
		values[2] = my_opts->username;
		keywords[3] = "password";
		values[3] = password;
		keywords[4] = "dbname";
		values[4] = my_opts->dbname;
		keywords[5] = "fallback_application_name";
		values[5] = my_opts->progname;
		keywords[6] = NULL;
		values[6] = NULL;

		new_pass = false;
		conn = PQconnectdbParams(keywords, values, true);

		if (!conn)
		{
			fprintf(stderr, "%s: could not connect to database %s\n",
					"oid2name", my_opts->dbname);
			exit(1);
		}

		if (PQstatus(conn) == CONNECTION_BAD &&
			PQconnectionNeedsPassword(conn) &&
			password == NULL)
		{
			PQfinish(conn);
			password = simple_prompt("Password: "******"%s: could not connect to database %s: %s",
				"oid2name", my_opts->dbname, PQerrorMessage(conn));
		PQfinish(conn);
		exit(1);
	}

	/* return the conn if good */
	return conn;
}
コード例 #5
0
ファイル: oid2name.c プロジェクト: amenonsen/postgres
int
main(int argc, char **argv)
{
	struct options *my_opts;
	PGconn	   *pgconn;

	my_opts = (struct options *) pg_malloc(sizeof(struct options));

	my_opts->oids = (eary *) pg_malloc(sizeof(eary));
	my_opts->tables = (eary *) pg_malloc(sizeof(eary));
	my_opts->filenodes = (eary *) pg_malloc(sizeof(eary));

	my_opts->oids->num = my_opts->oids->alloc = 0;
	my_opts->tables->num = my_opts->tables->alloc = 0;
	my_opts->filenodes->num = my_opts->filenodes->alloc = 0;

	/* parse the opts */
	get_opts(argc, argv, my_opts);

	if (my_opts->dbname == NULL)
	{
		my_opts->dbname = "postgres";
		my_opts->nodb = true;
	}
	pgconn = sql_conn(my_opts);

	/* display only tablespaces */
	if (my_opts->tablespaces)
	{
		if (!my_opts->quiet)
			printf("All tablespaces:\n");
		sql_exec_dumpalltbspc(pgconn, my_opts);

		PQfinish(pgconn);
		exit(0);
	}

	/* display the given elements in the database */
	if (my_opts->oids->num > 0 ||
		my_opts->tables->num > 0 ||
		my_opts->filenodes->num > 0)
	{
		if (!my_opts->quiet)
			printf("From database \"%s\":\n", my_opts->dbname);
		sql_exec_searchtables(pgconn, my_opts);

		PQfinish(pgconn);
		exit(0);
	}

	/* no elements given; dump the given database */
	if (my_opts->dbname && !my_opts->nodb)
	{
		if (!my_opts->quiet)
			printf("From database \"%s\":\n", my_opts->dbname);
		sql_exec_dumpalltables(pgconn, my_opts);

		PQfinish(pgconn);
		exit(0);
	}

	/* no database either; dump all databases */
	if (!my_opts->quiet)
		printf("All databases:\n");
	sql_exec_dumpalldbs(pgconn, my_opts);

	PQfinish(pgconn);
	return 0;
}
コード例 #6
0
ファイル: info.c プロジェクト: EMARQUIS/postgres
/*
 * get_rel_infos()
 *
 * gets the relinfos for all the user tables of the database referred
 * by "db".
 *
 * NOTE: we assume that relations/entities with oids greater than
 * FirstNormalObjectId belongs to the user
 */
static void
get_rel_infos(ClusterInfo *cluster, DbInfo *dbinfo)
{
	PGconn	   *conn = connectToServer(cluster,
									   dbinfo->db_name);
	PGresult   *res;
	RelInfo    *relinfos;
	int			ntups;
	int			relnum;
	int			num_rels = 0;
	char	   *nspname = NULL;
	char	   *relname = NULL;
	int			i_spclocation,
				i_nspname,
				i_relname,
				i_oid,
				i_relfilenode,
				i_reltablespace;
	char		query[QUERY_ALLOC];

	/*
	 * pg_largeobject contains user data that does not appear in pg_dumpall
	 * --schema-only output, so we have to copy that system table heap and
	 * index.  We could grab the pg_largeobject oids from template1, but it is
	 * easy to treat it as a normal table. Order by oid so we can join old/new
	 * structures efficiently.
	 */

	snprintf(query, sizeof(query),
			 "CREATE TEMPORARY TABLE info_rels (reloid) AS SELECT c.oid "
			 "FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n "
			 "	   ON c.relnamespace = n.oid "
			 "LEFT OUTER JOIN pg_catalog.pg_index i "
			 "	   ON c.oid = i.indexrelid "
			 "WHERE relkind IN ('r', 'm', 'i'%s) AND "

	/*
	 * pg_dump only dumps valid indexes;  testing indisready is necessary in
	 * 9.2, and harmless in earlier/later versions.
	 */
			 " i.indisvalid IS DISTINCT FROM false AND "
			 " i.indisready IS DISTINCT FROM false AND "
	/* exclude possible orphaned temp tables */
			 "  ((n.nspname !~ '^pg_temp_' AND "
			 "    n.nspname !~ '^pg_toast_temp_' AND "
	/* skip pg_toast because toast index have relkind == 'i', not 't' */
			 "    n.nspname NOT IN ('pg_catalog', 'information_schema', "
			 "						'binary_upgrade', 'pg_toast') AND "
			 "	  c.oid >= %u) "
			 "  OR (n.nspname = 'pg_catalog' AND "
	"    relname IN ('pg_largeobject', 'pg_largeobject_loid_pn_index'%s) ));",
	/* see the comment at the top of old_8_3_create_sequence_script() */
			 (GET_MAJOR_VERSION(old_cluster.major_version) <= 803) ?
			 "" : ", 'S'",
			 FirstNormalObjectId,
	/* does pg_largeobject_metadata need to be migrated? */
			 (GET_MAJOR_VERSION(old_cluster.major_version) <= 804) ?
	"" : ", 'pg_largeobject_metadata', 'pg_largeobject_metadata_oid_index'");

	PQclear(executeQueryOrDie(conn, "%s", query));

	/*
	 * Get TOAST tables and indexes;  we have to gather the TOAST tables in
	 * later steps because we can't schema-qualify TOAST tables.
	 */
	PQclear(executeQueryOrDie(conn,
							  "INSERT INTO info_rels "
							  "SELECT reltoastrelid "
							  "FROM info_rels i JOIN pg_catalog.pg_class c "
							  "		ON i.reloid = c.oid "
							  "		AND c.reltoastrelid != %u", InvalidOid));
	PQclear(executeQueryOrDie(conn,
							  "INSERT INTO info_rels "
							  "SELECT indexrelid "
							  "FROM pg_index "
							  "WHERE indisvalid "
							  "    AND indrelid IN (SELECT reltoastrelid "
							  "        FROM info_rels i "
							  "            JOIN pg_catalog.pg_class c "
							  "            ON i.reloid = c.oid "
							  "            AND c.reltoastrelid != %u)",
							  InvalidOid));

	snprintf(query, sizeof(query),
			 "SELECT c.oid, n.nspname, c.relname, "
			 "	c.relfilenode, c.reltablespace, %s "
			 "FROM info_rels i JOIN pg_catalog.pg_class c "
			 "		ON i.reloid = c.oid "
			 "  JOIN pg_catalog.pg_namespace n "
			 "	   ON c.relnamespace = n.oid "
			 "  LEFT OUTER JOIN pg_catalog.pg_tablespace t "
			 "	   ON c.reltablespace = t.oid "
	/* we preserve pg_class.oid so we sort by it to match old/new */
			 "ORDER BY 1;",
	/* 9.2 removed the spclocation column */
			 (GET_MAJOR_VERSION(cluster->major_version) <= 901) ?
			 "t.spclocation" : "pg_catalog.pg_tablespace_location(t.oid) AS spclocation");

	res = executeQueryOrDie(conn, "%s", query);

	ntups = PQntuples(res);

	relinfos = (RelInfo *) pg_malloc(sizeof(RelInfo) * ntups);

	i_oid = PQfnumber(res, "oid");
	i_nspname = PQfnumber(res, "nspname");
	i_relname = PQfnumber(res, "relname");
	i_relfilenode = PQfnumber(res, "relfilenode");
	i_reltablespace = PQfnumber(res, "reltablespace");
	i_spclocation = PQfnumber(res, "spclocation");

	for (relnum = 0; relnum < ntups; relnum++)
	{
		RelInfo    *curr = &relinfos[num_rels++];
		const char *tblspace;

		curr->reloid = atooid(PQgetvalue(res, relnum, i_oid));

		nspname = PQgetvalue(res, relnum, i_nspname);
		curr->nspname = pg_strdup(nspname);

		relname = PQgetvalue(res, relnum, i_relname);
		curr->relname = pg_strdup(relname);

		curr->relfilenode = atooid(PQgetvalue(res, relnum, i_relfilenode));

		if (atooid(PQgetvalue(res, relnum, i_reltablespace)) != 0)
			/* Might be "", meaning the cluster default location. */
			tblspace = PQgetvalue(res, relnum, i_spclocation);
		else
			/* A zero reltablespace indicates the database tablespace. */
			tblspace = dbinfo->db_tblspace;

		strlcpy(curr->tablespace, tblspace, sizeof(curr->tablespace));
	}
	PQclear(res);

	PQfinish(conn);

	dbinfo->rel_arr.rels = relinfos;
	dbinfo->rel_arr.nrels = num_rels;
}
コード例 #7
0
ファイル: hb.c プロジェクト: nuko-yokohama/hb_worker
static void
exit_nicely(PGconn *conn)
{
	PQfinish(conn);
	exit(1);
}
コード例 #8
0
ファイル: pg_upgrade.c プロジェクト: mjw56/postgres
/*
 *	set_frozenxids()
 *
 *	We have frozen all xids, so set relfrozenxid and datfrozenxid
 *	to be the old cluster's xid counter, which we just set in the new
 *	cluster.  User-table frozenxid values will be set by pg_dumpall
 *	--binary-upgrade, but objects not set by the pg_dump must have
 *	proper frozen counters.
 */
static
void
set_frozenxids(void)
{
	int			dbnum;
	PGconn	   *conn,
			   *conn_template1;
	PGresult   *dbres;
	int			ntups;
	int			i_datname;
	int			i_datallowconn;

	prep_status("Setting frozenxid counters in new cluster");

	conn_template1 = connectToServer(&new_cluster, "template1");

	/* set pg_database.datfrozenxid */
	PQclear(executeQueryOrDie(conn_template1,
							  "UPDATE pg_catalog.pg_database "
							  "SET	datfrozenxid = '%u'",
							  old_cluster.controldata.chkpnt_nxtxid));

	/* get database names */
	dbres = executeQueryOrDie(conn_template1,
							  "SELECT	datname, datallowconn "
							  "FROM	pg_catalog.pg_database");

	i_datname = PQfnumber(dbres, "datname");
	i_datallowconn = PQfnumber(dbres, "datallowconn");

	ntups = PQntuples(dbres);
	for (dbnum = 0; dbnum < ntups; dbnum++)
	{
		char	   *datname = PQgetvalue(dbres, dbnum, i_datname);
		char	   *datallowconn = PQgetvalue(dbres, dbnum, i_datallowconn);

		/*
		 * We must update databases where datallowconn = false, e.g.
		 * template0, because autovacuum increments their datfrozenxids and
		 * relfrozenxids even if autovacuum is turned off, and even though all
		 * the data rows are already frozen  To enable this, we temporarily
		 * change datallowconn.
		 */
		if (strcmp(datallowconn, "f") == 0)
			PQclear(executeQueryOrDie(conn_template1,
									  "UPDATE pg_catalog.pg_database "
									  "SET	datallowconn = true "
									  "WHERE datname = '%s'", datname));

		conn = connectToServer(&new_cluster, datname);

		/* set pg_class.relfrozenxid */
		PQclear(executeQueryOrDie(conn,
								  "UPDATE	pg_catalog.pg_class "
								  "SET	relfrozenxid = '%u' "
		/* only heap and TOAST are vacuumed */
								  "WHERE	relkind IN ('r', 't')",
								  old_cluster.controldata.chkpnt_nxtxid));
		PQfinish(conn);

		/* Reset datallowconn flag */
		if (strcmp(datallowconn, "f") == 0)
			PQclear(executeQueryOrDie(conn_template1,
									  "UPDATE pg_catalog.pg_database "
									  "SET	datallowconn = false "
									  "WHERE datname = '%s'", datname));
	}

	PQclear(dbres);

	PQfinish(conn_template1);

	check_ok();
}
コード例 #9
0
ファイル: kc_pgsql.cpp プロジェクト: lonsharn/lsh_server
KCSQLResult* PgSQLConnection::ExecuteQueryEx(
    const char* queryStr,
    long iTimeout,
    int type
)
{
    CMutexGuard		guard(m_MutexQuery);

    if (m_iAutoConnect)
    {
        if (m_conn)
        {
            if ( PQstatus(m_conn) == CONNECTION_BAD )
            {
                PQreset(m_conn);
                // 重试一次不行,就关闭该连接
                if (PQstatus(m_conn) == CONNECTION_BAD)
                {
                    PQfinish(m_conn);
                    m_conn = NULL;
                }
            }
        }

        if (m_conn == NULL)
        {
            if ( !Connect(iTimeout) )
            {
                return	new PgSQLResult(-1, "连接出错");
            }
        }
    }

    if (m_conn == NULL)
    {
        return	new PgSQLResult(-1, "无数据库连接");
    }

    PGresult* result = PQexec(m_conn, queryStr);
    if (result == NULL)
    {
        // 重试
        Connect(iTimeout);
        result = PQexec(m_conn, queryStr);
    }

    if (result == NULL)
    {
        return	NULL;
    }

    ExecStatusType resultInfo = PQresultStatus(result);
    m_errorCode = resultInfo;

    switch (resultInfo)
    {
    case PGRES_COMMAND_OK:
        // 仅记录影响行数
        return	new PgSQLResult( PQcmdTuples(result) ? atoi(PQcmdTuples(result)) : 0 );
        break;
    case PGRES_TUPLES_OK:
        return	new PgSQLResult(this, result);
        break;

    default:
        return new PgSQLResult(resultInfo, PQresultErrorMessage(result));
        break;
    }
}
コード例 #10
0
ファイル: delagent.c プロジェクト: steffen-weber/fossology
/**
 * \brief main function for the delagent
 *
 * There are 2 ways to use the delagent agent:
 *   1. Command Line :: delete/list upload/folder/license from the command line
 *   2. Agent Based  :: run from the scheduler
 *
 * +-----------------------+
 * | Command Line Analysis |
 * +-----------------------+
 *
 * List or delete uploads.
 *   -h            :: help (print this message), then exit.
 *   -i            :: Initialize the DB
 *   -u            :: List uploads IDs.
 *   -U #          :: Delete upload ID.
 *   -L #          :: Delete ALL licenses associated with upload ID.
 *   -f            :: List folder IDs.
 *   -F #          :: Delete folder ID and all uploads under this folder.
 *   -T            :: TEST -- do not update the DB or delete any files (just pretend).
 *   -v            :: Verbose (-vv for more verbose).
 *   -V            :: print the version info, then exit.
 *   -c SYSCONFDIR :: Specify the directory for the system configuration.
 *   --user #      :: user name
 *   --password #  :: password
 *
 * +----------------------+
 * | Agent Based Analysis |
 * +----------------------+
 *
 * To run the delagent as an agent
 *   -s :: Run from the scheduler
 *
 *
 * \param argc the number of command line arguments
 * \param argv the command line arguments
 * \return 0 on a successful program execution
 */
int main (int argc, char *argv[])
{
  int c;
  int listProj=0, listFolder=0;
  long delUpload=0, delFolder=0, delLicense=0, delFolderParent=0;
  int scheduler=0; /* should it run from the scheduler? */
  int gotArg=0;
  char *agent_desc = "Deletes upload.  Other list/delete options available from the command line.";
  char *COMMIT_HASH;
  char *VERSION;
  char agent_rev[myBUFSIZ];
  int option_index = 0;
  char *user_name = NULL;
  char *password = NULL;
  int user_id = -1;
  int user_perm = -1;
  int returnedCode = 0;

  fo_scheduler_connect(&argc, argv, &db_conn);

  static struct option long_options[] =
  {
    {"user", required_argument, 0, 'n'},
    {"password", required_argument, 0, 'p'},
    {0, 0, 0, 0}
  };

  while ((c = getopt_long (argc, argv, "n:p:ifF:lL:sTuU:P:vVc:h",
         long_options, &option_index)) != -1)
  {
    switch (c)
    {
      case 'n':
        user_name = optarg;
        break;
      case 'p':
        password = optarg;
        break;
      case 'i':
        PQfinish(db_conn);
        return(0);
      case 'f':
        listFolder=1;
        gotArg=1;
        break;
      case 'F':
        delFolder=atol(optarg);
        gotArg=1;
        break;
      case 'L':
        delLicense=atol(optarg);
        gotArg=1;
        break;
      case 'P':
        delFolderParent=atol(optarg);
        gotArg=1;
        break;
      case 's':
        scheduler=1;
        gotArg=1;
        break;
      case 'T':
        Test++;
        break;
      case 'u':
        listProj=1;
        gotArg=1;
        break;
      case 'U':
        delUpload=atol(optarg);
        gotArg=1;
        break;
      case 'v':
        Verbose++;
        break;
      case 'c':
        gotArg=1;
        break; /* handled by fo_scheduler_connect() */
      case 'V':
        printf("%s", BuildVersion);
        PQfinish(db_conn);
        return(0);
      default:
        usage(argv[0]);
        exit(-1);
    }
  }

  if (!gotArg)
  {
    usage(argv[0]);
    exit(-1);
  }

  if (scheduler != 1)
  {
    if (0 != authentication(user_name, password, &user_id, &user_perm))
    {
      LOG_FATAL("User name or password is invalid.\n");
      exit(-1);
    }

    COMMIT_HASH = fo_sysconfig("delagent", "COMMIT_HASH");
    VERSION = fo_sysconfig("delagent", "VERSION");
    sprintf(agent_rev, "%s.%s", VERSION, COMMIT_HASH);
    /* Get the Agent Key from the DB */
    fo_GetAgentKey(db_conn, basename(argv[0]), 0, agent_rev, agent_desc);

    if (listProj)
    {
      returnedCode = listUploads(user_id, user_perm);
    }
    if (returnedCode < 0)
    {
      return returnedCode;
    }
    if (listFolder)
    {
      returnedCode = listFolders(user_id, user_perm);
    }
    if (returnedCode < 0)
    {
      return returnedCode;
    }

    alarm(60);  /* from this point on, handle the alarm */
    if (delUpload)
    {
      returnedCode = deleteUpload(delUpload, user_id, user_perm);

      writeMessageAfterDelete("upload", delUpload, user_name, returnedCode);
    }
    if (delFolder)
    {
      returnedCode = deleteFolder(delFolder, delFolderParent, user_id, user_perm);

      writeMessageAfterDelete("folder", delFolder, user_name, returnedCode);
    }
    if (delLicense)
    {
      returnedCode = deleteLicense(delLicense, user_perm);

      writeMessageAfterDelete("license", delLicense, user_name, returnedCode);
    }
  }
  else
  {
    /* process from the scheduler */
    doSchedulerTasks();
  }
  fo_scheduler_disconnect(0);

  PQfinish(db_conn);
  return(returnedCode);
} /* main() */
コード例 #11
0
ファイル: Plugin.cpp プロジェクト: egretinhaven/TrekCooker
void Plugin::saveValue(const char *tagname, const char *tablename, const char *valstring)
{
#ifdef WITHDB
  PGconn *conn = NULL;

  TObject *dummy=getMemoryObject("Runnumber");
  int runnumber=htonl(*(int*) &dummy); //ugly but works 
  // Make a connection to the database
  conn = PQconnectdb("user=runinfo password=runinfo dbname=runinfo host=CookerWorkerNodeLNS00");
  
  // Check to see that the backend connection was successfully made
  if (PQstatus(conn) != CONNECTION_OK)
    {
      debug(0,"Connection to database failed\n");
      PQfinish(conn);
      return ;
    }
  const char *params[]={tagname,(char *) &runnumber,valstring};

  int lengths[3]={strlen(tagname),sizeof(runnumber),strlen(valstring)};
  int binary[3]={0,1,0};
  debug(100,"Connection to database - OK\n");
  PGresult *res=PQexecParams(conn, "select tagid from tagnames where tagname=$1::varchar;",1,NULL,params,lengths,binary,0);
  if (PQresultStatus(res) != PGRES_TUPLES_OK)
    {
      debug(0, "select tagid command failed: %s\n", PQerrorMessage(conn));
      PQclear(res);
      PQfinish(conn);
      return;
    }
  debug(100,"Found %i\n",PQntuples(res));
  if (PQntuples(res)==0)
    {
      PQclear(res);
      debug(100,"Trying to insert\n");
      res=PQexecParams(conn, "insert into tagnames  (tagname) values ($1::varchar);",1,NULL,params,lengths,binary,0);
      if (PQresultStatus(res) != PGRES_COMMAND_OK)
	{
	  debug(0, "insert into tagid command failed: %s\n", PQerrorMessage(conn));
	  PQclear(res);
	  PQfinish(conn);
	  return;
	}
    }
  PQclear(res);
  debug(100,"Trying to insert\n");
  char command[1000];
  sprintf(command,"insert into %s (timestamp,runid,tagid,value) select now(),$2::int4,tagid,$3::double precision from tagnames where tagname=$1::varchar;",tablename);
  res=PQexecParams(conn, command,3,NULL,params,lengths,binary,0);
  if (PQresultStatus(res) != PGRES_COMMAND_OK)
    {
      debug(100, "insert into rundata command failed: %s\n Trying update", PQerrorMessage(conn));
      PQclear(res);
      sprintf(command,"update %s set timestamp=now(), value=$3::double precision where runid=$2::int4 and tagid=(select tagid from tagnames where tagname=$1::varchar);",tablename);
      res=PQexecParams(conn, command,3,NULL,params,lengths,binary,0);
      if (PQresultStatus(res) != PGRES_COMMAND_OK)
	{
	  debug(100, "update failed too: %s\n", PQerrorMessage(conn));
	  PQclear(res);
	  PQfinish(conn);
	  return;
	}
    }
  PQclear(res);
  
  PQfinish(conn);
#else
  debug(10000,"DB not compiled in\n");
#endif
}
コード例 #12
0
static void
BaseBackup(void)
{
	PGresult   *res;
	char	   *sysidentifier;
	uint32		timeline;
	char		current_path[MAXPGPATH];
	char		escaped_label[MAXPGPATH];
	int			i;
	char		xlogstart[64];
	char		xlogend[64];

	/*
	 * Connect in replication mode to the server
	 */
	conn = GetConnection();

	/*
	 * Run IDENTIFY_SYSTEM so we can get the timeline
	 */
	res = PQexec(conn, "IDENTIFY_SYSTEM");
	if (PQresultStatus(res) != PGRES_TUPLES_OK)
	{
		fprintf(stderr, _("%s: could not identify system: %s\n"),
				progname, PQerrorMessage(conn));
		disconnect_and_exit(1);
	}
	if (PQntuples(res) != 1 || PQnfields(res) != 3)
	{
		fprintf(stderr, _("%s: could not identify system, got %i rows and %i fields\n"),
				progname, PQntuples(res), PQnfields(res));
		disconnect_and_exit(1);
	}
	sysidentifier = strdup(PQgetvalue(res, 0, 0));
	timeline = atoi(PQgetvalue(res, 0, 1));
	PQclear(res);

	/*
	 * Start the actual backup
	 */
	PQescapeStringConn(conn, escaped_label, label, sizeof(escaped_label), &i);
	snprintf(current_path, sizeof(current_path), "BASE_BACKUP LABEL '%s' %s %s %s %s",
			 escaped_label,
			 showprogress ? "PROGRESS" : "",
			 includewal && !streamwal ? "WAL" : "",
			 fastcheckpoint ? "FAST" : "",
			 includewal ? "NOWAIT" : "");

	if (PQsendQuery(conn, current_path) == 0)
	{
		fprintf(stderr, _("%s: could not send base backup command: %s"),
				progname, PQerrorMessage(conn));
		disconnect_and_exit(1);
	}

	/*
	 * Get the starting xlog position
	 */
	res = PQgetResult(conn);
	if (PQresultStatus(res) != PGRES_TUPLES_OK)
	{
		fprintf(stderr, _("%s: could not initiate base backup: %s"),
				progname, PQerrorMessage(conn));
		disconnect_and_exit(1);
	}
	if (PQntuples(res) != 1)
	{
		fprintf(stderr, _("%s: no start point returned from server\n"),
				progname);
		disconnect_and_exit(1);
	}
	strcpy(xlogstart, PQgetvalue(res, 0, 0));
	if (verbose && includewal)
		fprintf(stderr, "xlog start point: %s\n", xlogstart);
	PQclear(res);
	MemSet(xlogend, 0, sizeof(xlogend));

	/*
	 * Get the header
	 */
	res = PQgetResult(conn);
	if (PQresultStatus(res) != PGRES_TUPLES_OK)
	{
		fprintf(stderr, _("%s: could not get backup header: %s"),
				progname, PQerrorMessage(conn));
		disconnect_and_exit(1);
	}
	if (PQntuples(res) < 1)
	{
		fprintf(stderr, _("%s: no data returned from server\n"), progname);
		disconnect_and_exit(1);
	}

	/*
	 * Sum up the total size, for progress reporting
	 */
	totalsize = totaldone = 0;
	tablespacecount = PQntuples(res);
	for (i = 0; i < PQntuples(res); i++)
	{
		if (showprogress)
			totalsize += atol(PQgetvalue(res, i, 2));

		/*
		 * Verify tablespace directories are empty. Don't bother with the
		 * first once since it can be relocated, and it will be checked before
		 * we do anything anyway.
		 */
		if (format == 'p' && !PQgetisnull(res, i, 1))
			verify_dir_is_empty_or_create(PQgetvalue(res, i, 1));
	}

	/*
	 * When writing to stdout, require a single tablespace
	 */
	if (format == 't' && strcmp(basedir, "-") == 0 && PQntuples(res) > 1)
	{
		fprintf(stderr, _("%s: can only write single tablespace to stdout, database has %d\n"),
				progname, PQntuples(res));
		disconnect_and_exit(1);
	}

	/*
	 * If we're streaming WAL, start the streaming session before we start
	 * receiving the actual data chunks.
	 */
	if (streamwal)
	{
		if (verbose)
			fprintf(stderr, _("%s: starting background WAL receiver\n"),
					progname);
		StartLogStreamer(xlogstart, timeline, sysidentifier);
	}

	/*
	 * Start receiving chunks
	 */
	for (i = 0; i < PQntuples(res); i++)
	{
		if (format == 't')
			ReceiveTarFile(conn, res, i);
		else
			ReceiveAndUnpackTarFile(conn, res, i);
	}							/* Loop over all tablespaces */

	if (showprogress)
	{
		progress_report(PQntuples(res), NULL);
		fprintf(stderr, "\n");	/* Need to move to next line */
	}
	PQclear(res);

	/*
	 * Get the stop position
	 */
	res = PQgetResult(conn);
	if (PQresultStatus(res) != PGRES_TUPLES_OK)
	{
		fprintf(stderr, _("%s: could not get WAL end position from server\n"),
				progname);
		disconnect_and_exit(1);
	}
	if (PQntuples(res) != 1)
	{
		fprintf(stderr, _("%s: no WAL end position returned from server\n"),
				progname);
		disconnect_and_exit(1);
	}
	strcpy(xlogend, PQgetvalue(res, 0, 0));
	if (verbose && includewal)
		fprintf(stderr, "xlog end point: %s\n", xlogend);
	PQclear(res);

	res = PQgetResult(conn);
	if (PQresultStatus(res) != PGRES_COMMAND_OK)
	{
		fprintf(stderr, _("%s: final receive failed: %s"),
				progname, PQerrorMessage(conn));
		disconnect_and_exit(1);
	}

	if (bgchild > 0)
	{
#ifndef WIN32
		int			status;
		int			r;
#else
		DWORD       status;
#endif

		if (verbose)
			fprintf(stderr, _("%s: waiting for background process to finish streaming...\n"), progname);

#ifndef WIN32
		if (pipewrite(bgpipe[1], xlogend, strlen(xlogend)) != strlen(xlogend))
		{
			fprintf(stderr, _("%s: could not send command to background pipe: %s\n"),
					progname, strerror(errno));
			disconnect_and_exit(1);
		}

		/* Just wait for the background process to exit */
		r = waitpid(bgchild, &status, 0);
		if (r == -1)
		{
			fprintf(stderr, _("%s: could not wait for child process: %s\n"),
					progname, strerror(errno));
			disconnect_and_exit(1);
		}
		if (r != bgchild)
		{
			fprintf(stderr, _("%s: child %i died, expected %i\n"),
					progname, r, bgchild);
			disconnect_and_exit(1);
		}
		if (!WIFEXITED(status))
		{
			fprintf(stderr, _("%s: child process did not exit normally\n"),
					progname);
			disconnect_and_exit(1);
		}
		if (WEXITSTATUS(status) != 0)
		{
			fprintf(stderr, _("%s: child process exited with error %i\n"),
					progname, WEXITSTATUS(status));
			disconnect_and_exit(1);
		}
		/* Exited normally, we're happy! */
#else							/* WIN32 */

		/*
		 * On Windows, since we are in the same process, we can just store the
		 * value directly in the variable, and then set the flag that says
		 * it's there.
		 */
		if (sscanf(xlogend, "%X/%X", &xlogendptr.xlogid, &xlogendptr.xrecoff) != 2)
		{
			fprintf(stderr, _("%s: could not parse xlog end position \"%s\"\n"),
					progname, xlogend);
			disconnect_and_exit(1);
		}
		InterlockedIncrement(&has_xlogendptr);

		/* First wait for the thread to exit */
		if (WaitForSingleObjectEx((HANDLE) bgchild, INFINITE, FALSE) != WAIT_OBJECT_0)
		{
			_dosmaperr(GetLastError());
			fprintf(stderr, _("%s: could not wait for child thread: %s\n"),
					progname, strerror(errno));
			disconnect_and_exit(1);
		}
		if (GetExitCodeThread((HANDLE) bgchild, &status) == 0)
		{
			_dosmaperr(GetLastError());
			fprintf(stderr, _("%s: could not get child thread exit status: %s\n"),
					progname, strerror(errno));
			disconnect_and_exit(1);
		}
		if (status != 0)
		{
			fprintf(stderr, _("%s: child thread exited with error %u\n"),
					progname, (unsigned int) status);
			disconnect_and_exit(1);
		}
		/* Exited normally, we're happy */
#endif
	}

	/*
	 * End of copy data. Final result is already checked inside the loop.
	 */
	PQclear(res);
	PQfinish(conn);

	if (verbose)
		fprintf(stderr, "%s: base backup completed\n", progname);
}
コード例 #13
0
ファイル: pgtclId.c プロジェクト: sunyangkobe/cscd43
/*
 * Remove a connection Id from the hash table and
 * close all portals the user forgot.
 */
int
PgDelConnectionId(DRIVER_DEL_PROTO)
{
	Tcl_HashEntry *entry;
	Tcl_HashSearch hsearch;
	Pg_ConnectionId *connid;
	Pg_TclNotifies *notifies;
	int			i;

	connid = (Pg_ConnectionId *) cData;

	for (i = 0; i < connid->res_max; i++)
	{
		if (connid->results[i])
			PQclear(connid->results[i]);
	}
	ckfree((void *) connid->results);

	/* Release associated notify info */
	while ((notifies = connid->notify_list) != NULL)
	{
		connid->notify_list = notifies->next;
		for (entry = Tcl_FirstHashEntry(&notifies->notify_hash, &hsearch);
			 entry != NULL;
			 entry = Tcl_NextHashEntry(&hsearch))
			ckfree((char *) Tcl_GetHashValue(entry));
		Tcl_DeleteHashTable(&notifies->notify_hash);
		if (notifies->conn_loss_cmd)
			ckfree((void *) notifies->conn_loss_cmd);
		if (notifies->interp)
			Tcl_DontCallWhenDeleted(notifies->interp, PgNotifyInterpDelete,
									(ClientData) notifies);
		ckfree((void *) notifies);
	}

	/*
	 * Turn off the Tcl event source for this connection, and delete any
	 * pending notify and connection-loss events.
	 */
	PgStopNotifyEventSource(connid, true);

	/* Close the libpq connection too */
	PQfinish(connid->conn);
	connid->conn = NULL;

	/*
	 * Kill the notifier channel, too.	We must not do this until after
	 * we've closed the libpq connection, because Tcl will try to close
	 * the socket itself!
	 *
	 * XXX Unfortunately, while this works fine if we are closing due to
	 * explicit pg_disconnect, all Tcl versions through 8.4.1 dump core if
	 * we try to do it during interpreter shutdown.  Not clear why. For
	 * now, we kill the channel during pg_disconnect, but during interp
	 * shutdown we just accept leakage of the (fairly small) amount of
	 * memory taken for the channel state representation. (Note we are not
	 * leaking a socket, since libpq closed that already.) We tell the
	 * difference between pg_disconnect and interpreter shutdown by
	 * testing for interp != NULL, which is an undocumented but apparently
	 * safe way to tell.
	 */
#if TCL_MAJOR_VERSION >= 8
	if (connid->notifier_channel != NULL && interp != NULL)
		Tcl_UnregisterChannel(NULL, connid->notifier_channel);
#endif

	/*
	 * We must use Tcl_EventuallyFree because we don't want the connid
	 * struct to vanish instantly if Pg_Notify_EventProc is active for it.
	 * (Otherwise, closing the connection from inside a pg_listen callback
	 * could lead to coredump.)  Pg_Notify_EventProc can detect that the
	 * connection has been deleted from under it by checking connid->conn.
	 */
	Tcl_EventuallyFree((ClientData) connid, TCL_DYNAMIC);

	return 0;
}
コード例 #14
0
ファイル: postgres.c プロジェクト: alayasix/LuoYunCloud
void ly_db_close(void)
{
    if (_db_conn)
        PQfinish(_db_conn);
}
コード例 #15
0
ファイル: populate.c プロジェクト: korisk/populator
int
main(int argc, char **argv)
{
    const char *conninfo;
    PGconn     *conn;
    PGresult   *res;
    int         nFields;
    int         i,
                j;

    if (argc > 1)
        conninfo = argv[1];
    else
        conninfo = "host=localhost port=5432 user=korisk dbname=test";

    /* Make a connection to the database */
    conn = PQconnectdb(conninfo);

    /* Check to see that the backend connection was successfully made */
    if (PQstatus(conn) != CONNECTION_OK)
    {
        fprintf(stderr, "Connection to database failed: %s",
                PQerrorMessage(conn));
        exit_nicely(conn);
    }

    /* Start a transaction block */
    res = PQexec(conn, "BEGIN");
    if (PQresultStatus(res) != PGRES_COMMAND_OK)
    {
        fprintf(stderr, "BEGIN command failed: %s", PQerrorMessage(conn));
        PQclear(res);
        exit_nicely(conn);
    }
    PQclear(res);

       /*
 *      * Should PQclear PGresult whenever it is no longer needed to avoid memory
 *      * leaks
 *      */
	
    res = PQprepare(conn, "qu", "insert into mrow values ($1::bigint, $2::bigint, $3::float);",3, NULL);
    if (PQresultStatus(res) != PGRES_COMMAND_OK)
    {
        fprintf(stderr, "Prepare query failed: %s", PQerrorMessage(conn));
        PQclear(res);
        exit_nicely(conn);
    }
    PQclear(res);
	
   const char *paramValues[3];
   int         paramLengths[3];
   int         paramFormats[3];	


   long time = 0, _time = 0;
   long id = 0, _id = 0;
  
   union{
	double  f;
	long     i;
   } _value, value;

   _value.f = 1.0;
    value.f = 1.0;
   
   paramValues[0] = (char*)(&time);
   paramLengths[0] = sizeof(time);
   paramFormats[0] = 1;

   paramValues[1] = (char*)(&id);
   paramLengths[1] = sizeof(id);
   paramFormats[1] = 1;
   
   paramValues[2] = (char*)(&value);
   paramLengths[2] = sizeof(value);
   paramFormats[2] = 1;

   for(i=0; i < 3; i++){
   	time = htobe64(_time);
   	id = htobe64(_id);
 	value.i = htobe64(_value.i);

	_time++;
   	_id++;
   	_value.f += 0.1;

	res = PQexecPrepared(conn, "qu", 3, paramValues, paramLengths, paramFormats, 1);
	if (PQresultStatus(res) != PGRES_COMMAND_OK){
		fprintf(stderr, "Exec Prepared query failed: %s", PQerrorMessage(conn));
        	PQclear(res);
	        exit_nicely(conn);
	}
    	PQclear(res);
   }




 /*
     end the transaction */
    res = PQexec(conn, "END");
    PQclear(res);

    /* close the connection to the database and cleanup */
    PQfinish(conn);

    return 0;
}
コード例 #16
0
ファイル: PgFileRepository.cpp プロジェクト: DNPA/OcfaLib
 /**
  * Destructor
  **/
 PgFileRepository::~PgFileRepository() {
   PQfinish(d_connection);
 }
コード例 #17
0
int
main(int argc, char **argv)
{
	const char *conninfo;
	TestSpec   *testspec;
	int			i;

	/*
	 * If the user supplies a parameter on the command line, use it as the
	 * conninfo string; otherwise default to setting dbname=postgres and
	 * using environment variables or defaults for all other connection
	 * parameters.
	 */
	if (argc > 1)
		conninfo = argv[1];
	else
		conninfo = "dbname = postgres";

	/* Read the test spec from stdin */
	spec_yyparse();
	testspec = &parseresult;
	printf("Parsed test spec with %d sessions\n", testspec->nsessions);

	/* Establish connections to the database, one for each session */
	nconns = testspec->nsessions;
	conns = calloc(nconns, sizeof(PGconn *));
	for (i = 0; i < testspec->nsessions; i++)
	{
		PGresult *res;

		conns[i] = PQconnectdb(conninfo);
		if (PQstatus(conns[i]) != CONNECTION_OK)
		{
			fprintf(stderr, "Connection %d to database failed: %s",
					i, PQerrorMessage(conns[i]));
			exit_nicely();
		}

		/*
		 * Suppress NOTIFY messages, which otherwise pop into results at odd
		 * places.
		 */
		res = PQexec(conns[i], "SET client_min_messages = warning;");
		if (PQresultStatus(res) != PGRES_COMMAND_OK)
		{
			fprintf(stderr, "message level setup failed: %s", PQerrorMessage(conns[i]));
			exit_nicely();
		}
		PQclear(res);
	}

	/* Set the session index fields in steps. */
	for (i = 0; i < testspec->nsessions; i++)
	{
		Session *session = testspec->sessions[i];
		int		stepindex;
		for (stepindex = 0; stepindex < session->nsteps; stepindex++)
			session->steps[stepindex]->session = i;
	}

	/*
	 * Run the permutations specified in the spec, or all if none were
	 * explicitly specified.
	 */
	if (testspec->permutations)
		run_named_permutations(testspec);
	else
		run_all_permutations(testspec);

	/* Clean up and exit */
	for (i = 0; i < nconns; i++)
		PQfinish(conns[i]);
	return 0;
}
コード例 #18
0
ファイル: common.c プロジェクト: denishpatel/postgres
/*
 * Make a database connection with the given parameters.  An
 * interactive password prompt is automatically issued if required.
 */
PGconn *
connectDatabase(const char *dbname, const char *pghost, const char *pgport,
				const char *pguser, enum trivalue prompt_password,
				const char *progname, bool fail_ok)
{
	PGconn	   *conn;
	char	   *password = NULL;
	bool		new_pass;

	if (prompt_password == TRI_YES)
		password = simple_prompt("Password: "******"%s: out of memory\n"), progname);
			exit(1);
		}

		keywords[0] = "host";
		values[0] = pghost;
		keywords[1] = "port";
		values[1] = pgport;
		keywords[2] = "user";
		values[2] = pguser;
		keywords[3] = "password";
		values[3] = password;
		keywords[4] = "dbname";
		values[4] = dbname;
		keywords[5] = "fallback_application_name";
		values[5] = progname;
		keywords[6] = NULL;
		values[6] = NULL;

		new_pass = false;
		conn = PQconnectdbParams(keywords, values, true);

		free(keywords);
		free(values);

		if (!conn)
		{
			fprintf(stderr, _("%s: could not connect to database %s\n"),
					progname, dbname);
			exit(1);
		}

		if (PQstatus(conn) == CONNECTION_BAD &&
			PQconnectionNeedsPassword(conn) &&
			password == NULL &&
			prompt_password != TRI_NO)
		{
			PQfinish(conn);
			password = simple_prompt("Password: "******"%s: could not connect to database %s: %s"),
				progname, dbname, PQerrorMessage(conn));
		exit(1);
	}

	return conn;
}
コード例 #19
0
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);
	  }
   
  }
}
コード例 #20
0
ファイル: startup.c プロジェクト: Princever/postgres
/*
 *
 * main
 *
 */
int
main(int argc, char *argv[])
{
	struct adhoc_opts options;
	int			successResult;
	char	   *password = NULL;
	char	   *password_prompt = NULL;
	bool		new_pass;

	set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("psql"));

	if (argc > 1)
	{
		if ((strcmp(argv[1], "-?") == 0) || (argc == 2 && (strcmp(argv[1], "--help") == 0)))
		{
			usage(NOPAGER);
			exit(EXIT_SUCCESS);
		}
		if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
		{
			showVersion();
			exit(EXIT_SUCCESS);
		}
	}

#ifdef WIN32
	setvbuf(stderr, NULL, _IONBF, 0);
#endif

	pset.progname = get_progname(argv[0]);

	pset.db = NULL;
	setDecimalLocale();
	pset.encoding = PQenv2encoding();
	pset.queryFout = stdout;
	pset.queryFoutPipe = false;
	pset.copyStream = NULL;
	pset.cur_cmd_source = stdin;
	pset.cur_cmd_interactive = false;

	/* We rely on unmentioned fields of pset.popt to start out 0/false/NULL */
	pset.popt.topt.format = PRINT_ALIGNED;
	pset.popt.topt.border = 1;
	pset.popt.topt.pager = 1;
	pset.popt.topt.pager_min_lines = 0;
	pset.popt.topt.start_table = true;
	pset.popt.topt.stop_table = true;
	pset.popt.topt.default_footer = true;

	pset.popt.topt.unicode_border_linestyle = UNICODE_LINESTYLE_SINGLE;
	pset.popt.topt.unicode_column_linestyle = UNICODE_LINESTYLE_SINGLE;
	pset.popt.topt.unicode_header_linestyle = UNICODE_LINESTYLE_SINGLE;

	refresh_utf8format(&(pset.popt.topt));

	/* We must get COLUMNS here before readline() sets it */
	pset.popt.topt.env_columns = getenv("COLUMNS") ? atoi(getenv("COLUMNS")) : 0;

	pset.notty = (!isatty(fileno(stdin)) || !isatty(fileno(stdout)));

	pset.getPassword = TRI_DEFAULT;

	EstablishVariableSpace();

	SetVariable(pset.vars, "VERSION", PG_VERSION_STR);

	/* Default values for variables */
	SetVariableBool(pset.vars, "AUTOCOMMIT");
	SetVariable(pset.vars, "VERBOSITY", "default");
	SetVariable(pset.vars, "SHOW_CONTEXT", "errors");
	SetVariable(pset.vars, "PROMPT1", DEFAULT_PROMPT1);
	SetVariable(pset.vars, "PROMPT2", DEFAULT_PROMPT2);
	SetVariable(pset.vars, "PROMPT3", DEFAULT_PROMPT3);

	parse_psql_options(argc, argv, &options);

	/*
	 * If no action was specified and we're in non-interactive mode, treat it
	 * as if the user had specified "-f -".  This lets single-transaction mode
	 * work in this case.
	 */
	if (options.actions.head == NULL && pset.notty)
		simple_action_list_append(&options.actions, ACT_FILE, NULL);

	/* Bail out if -1 was specified but will be ignored. */
	if (options.single_txn && options.actions.head == NULL)
	{
		fprintf(stderr, _("%s: -1 can only be used in non-interactive mode\n"), pset.progname);
		exit(EXIT_FAILURE);
	}

	if (!pset.popt.topt.fieldSep.separator &&
		!pset.popt.topt.fieldSep.separator_zero)
	{
		pset.popt.topt.fieldSep.separator = pg_strdup(DEFAULT_FIELD_SEP);
		pset.popt.topt.fieldSep.separator_zero = false;
	}
	if (!pset.popt.topt.recordSep.separator &&
		!pset.popt.topt.recordSep.separator_zero)
	{
		pset.popt.topt.recordSep.separator = pg_strdup(DEFAULT_RECORD_SEP);
		pset.popt.topt.recordSep.separator_zero = false;
	}

	if (options.username == NULL)
		password_prompt = pg_strdup(_("Password: "******"Password for user %s: "),
								   options.username);

	if (pset.getPassword == TRI_YES)
		password = simple_prompt(password_prompt, 100, false);

	/* loop until we have a password if requested by backend */
	do
	{
#define PARAMS_ARRAY_SIZE	8
		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] = options.host;
		keywords[1] = "port";
		values[1] = options.port;
		keywords[2] = "user";
		values[2] = options.username;
		keywords[3] = "password";
		values[3] = password;
		keywords[4] = "dbname";
		values[4] = (options.list_dbs && options.dbname == NULL) ?
			"postgres" : options.dbname;
		keywords[5] = "fallback_application_name";
		values[5] = pset.progname;
		keywords[6] = "client_encoding";
		values[6] = (pset.notty || getenv("PGCLIENTENCODING")) ? NULL : "auto";
		keywords[7] = NULL;
		values[7] = NULL;

		new_pass = false;
		pset.db = PQconnectdbParams(keywords, values, true);
		free(keywords);
		free(values);

		if (PQstatus(pset.db) == CONNECTION_BAD &&
			PQconnectionNeedsPassword(pset.db) &&
			password == NULL &&
			pset.getPassword != TRI_NO)
		{
			PQfinish(pset.db);
			password = simple_prompt(password_prompt, 100, false);
			new_pass = true;
		}
	} while (new_pass);

	free(password);
	free(password_prompt);

	if (PQstatus(pset.db) == CONNECTION_BAD)
	{
		fprintf(stderr, "%s: %s", pset.progname, PQerrorMessage(pset.db));
		PQfinish(pset.db);
		exit(EXIT_BADCONN);
	}

	setup_cancel_handler();

	PQsetNoticeProcessor(pset.db, NoticeProcessor, NULL);

	SyncVariables();

	if (options.list_dbs)
	{
		int			success;

		if (!options.no_psqlrc)
			process_psqlrc(argv[0]);

		success = listAllDbs(NULL, false);
		PQfinish(pset.db);
		exit(success ? EXIT_SUCCESS : EXIT_FAILURE);
	}

	if (options.logfilename)
	{
		pset.logfile = fopen(options.logfilename, "a");
		if (!pset.logfile)
		{
			fprintf(stderr, _("%s: could not open log file \"%s\": %s\n"),
					pset.progname, options.logfilename, strerror(errno));
			exit(EXIT_FAILURE);
		}
	}

	if (!options.no_psqlrc)
		process_psqlrc(argv[0]);

	/*
	 * If any actions were given by user, process them in the order in which
	 * they were specified.  Note single_txn is only effective in this mode.
	 */
	if (options.actions.head != NULL)
	{
		PGresult   *res;
		SimpleActionListCell *cell;

		successResult = EXIT_SUCCESS;	/* silence compiler */

		if (options.single_txn)
		{
			if ((res = PSQLexec("BEGIN")) == NULL)
			{
				if (pset.on_error_stop)
				{
					successResult = EXIT_USER;
					goto error;
				}
			}
			else
				PQclear(res);
		}

		for (cell = options.actions.head; cell; cell = cell->next)
		{
			if (cell->action == ACT_SINGLE_QUERY)
			{
				if (pset.echo == PSQL_ECHO_ALL)
					puts(cell->val);

				successResult = SendQuery(cell->val)
					? EXIT_SUCCESS : EXIT_FAILURE;
			}
			else if (cell->action == ACT_SINGLE_SLASH)
			{
				PsqlScanState scan_state;

				if (pset.echo == PSQL_ECHO_ALL)
					puts(cell->val);

				scan_state = psql_scan_create();
				psql_scan_setup(scan_state,
								cell->val,
								strlen(cell->val));

				successResult = HandleSlashCmds(scan_state, NULL) != PSQL_CMD_ERROR
					? EXIT_SUCCESS : EXIT_FAILURE;

				psql_scan_destroy(scan_state);
			}
			else if (cell->action == ACT_FILE)
			{
				successResult = process_file(cell->val, false);
			}
			else
			{
				/* should never come here */
				Assert(false);
			}

			if (successResult != EXIT_SUCCESS && pset.on_error_stop)
				break;
		}

		if (options.single_txn)
		{
			if ((res = PSQLexec("COMMIT")) == NULL)
			{
				if (pset.on_error_stop)
				{
					successResult = EXIT_USER;
					goto error;
				}
			}
			else
				PQclear(res);
		}

error:
		;
	}

	/*
	 * or otherwise enter interactive main loop
	 */
	else
	{
		connection_warnings(true);
		if (!pset.quiet)
			printf(_("Type \"help\" for help.\n\n"));
		initializeInput(options.no_readline ? 0 : 1);
		successResult = MainLoop(stdin);
	}

	/* clean up */
	if (pset.logfile)
		fclose(pset.logfile);
	PQfinish(pset.db);
	setQFout(NULL);

	return successResult;
}
コード例 #21
0
ファイル: hb.c プロジェクト: nuko-yokohama/hb_worker
int
hb_main(const char* conninfo)
{
	PGconn	   *conn;
	PGresult   *res;
	PGnotify   *notify;
	int			nnotifies;
	int checked;
	int result;

	char number[5];
	char notify_buf[1024];

	srand((unsigned)time(NULL));

	/* Make a connection to the database */
	conn = PQconnectdb(conninfo);

	/* Check to see that the backend connection was successfully made */
	if (PQstatus(conn) != CONNECTION_OK)
	{
		elog(WARNING, "Connection to database failed: %s",
				PQerrorMessage(conn));
		exit_nicely(conn);
	}

	/*
	 * Issue LISTEN command to enable notifications from the rule's NOTIFY.
	 */
	res = PQexec(conn, "LISTEN HB_SV");
	if (PQresultStatus(res) != PGRES_COMMAND_OK)
	{
		elog(WARNING, "LISTEN command failed: %s", PQerrorMessage(conn));
		PQclear(res);
		exit_nicely(conn);
	}

	/*
	 * should PQclear PGresult whenever it is no longer needed to avoid memory
	 * leaks
	 */
	PQclear(res);

	/* Set Secret Number */
	memset(number, 0x00, 5);
	create_random_number(number);
	elog(LOG , "hb_worker: set secret number=%s\n", number);

	/* Quit after four notifies are received. */
	nnotifies = 0;
	while (1)
	{
		/*
		 * Sleep until something happens on the connection.  We use select(2)
		 * to wait for input, but you could also use poll() or similar
		 * facilities.
		 */
		int			sock;
		fd_set		input_mask;

		sock = PQsocket(conn);

		if (sock < 0)
			break;				/* shouldn't happen */

		FD_ZERO(&input_mask);
		FD_SET(sock, &input_mask);

		if (select(sock + 1, &input_mask, NULL, NULL, NULL) < 0)
		{
			elog(WARNING, "select() failed: %s\n", strerror(errno));
			exit_nicely(conn);
		}

		/* Now check for input */
		PQconsumeInput(conn);
		while ((notify = PQnotifies(conn)) != NULL)
		{
			checked = check_number(notify->extra);
			switch (checked) {
				case NUMBER_COMMAND:
					result = compare_numbers(number, notify->extra);
					if (GET_HITS(result) == 4) {
						// Notify Game Clear, and Set new number.
						elog(LOG, "hb_worker: NOTIFY HB_CL,'4 Hit! Conguratulatoins!, next new game.'\n");
						strcpy(notify_buf, "NOTIFY HB_CL,'4 Hit! Conguratulatoins!, next new game.'");
						PQexec(conn, notify_buf);
						create_random_number(number);
						elog(LOG, "hb_worker: set secret number=%s\n", number);

					} else {
						// Notify Hit&blow
						elog(LOG, "NOTIFY HB_CL,'%d Hit / %d Blow.'",
							GET_HITS(result), GET_BLOWS(result));
						sprintf(notify_buf, "NOTIFY HB_CL,'%d Hit / %d Blow.'",
							GET_HITS(result), GET_BLOWS(result));
						PQexec(conn, notify_buf);
					}
					break;
				case START_COMMAND:
					// Set New number.
					elog(LOG, "hb_worker: Set New number.");
					create_random_number(number);
					break;
				case QUIT_COMMAND:
					// nop
					break;
				case INVALID_COMMAND:
				default:
					// NOTIFY error status
					sprintf(notify_buf, "NOTIFY HB_CL,'Invalid data.(%s)'", notify->extra);
					PQexec(conn, notify_buf);
					break;
			}
			

			PQfreemem(notify);
			nnotifies++;
		}
	}

	elog(LOG, "Done.\n");

	/* close the connection to the database and cleanup */
	PQfinish(conn);

	return 0;
}
コード例 #22
0
/* public: change password */
PAM_VISIBLE int
pam_sm_chauthtok(pam_handle_t *pamh, int flags, int argc, const char **argv)
{
	modopt_t *options = NULL;
	int rc;
	const char *user, *pass, *newpass, *rhost;
	const void *oldtok;
	char *newpass_crypt;
	PGconn *conn;
	PGresult *res;

	user = NULL; pass = NULL; newpass = NULL; rhost = NULL; newpass_crypt = NULL;

	if ((options = mod_options(argc, argv)) != NULL) {
		if ((rc = pam_get_item(pamh, PAM_RHOST, (const void **)&rhost)) == PAM_SUCCESS) 
			rc = pam_get_user(pamh, &user, NULL);
	} else
		rc = 1;

	if ((rc == PAM_SUCCESS) && (flags & PAM_PRELIM_CHECK)) {
		if (getuid() != 0) {
			if ((rc = pam_get_pass(pamh, PAM_OLDAUTHTOK, &pass, PASSWORD_PROMPT, options->std_flags)) == PAM_SUCCESS) {
				rc = backend_authenticate(pam_get_service(pamh), user, pass, rhost, options);
			} else {
				SYSLOG("could not retrieve password from '%s'", user);
			}
		} else {
			rc = PAM_SUCCESS;
		}
	} else if ((rc == PAM_SUCCESS) && (flags & PAM_UPDATE_AUTHTOK)) {

		/* only try to check old password if user is not root */
		pass = newpass = NULL;
		if (getuid() != 0) {

			if ((rc = pam_get_item(pamh, PAM_OLDAUTHTOK, &oldtok)) == PAM_SUCCESS) {
				pass = (const char*) oldtok;
				if ((rc = backend_authenticate(pam_get_service(pamh), user, pass, rhost, options)) != PAM_SUCCESS) {
					SYSLOG("(%s) user '%s' not authenticated.", pam_get_service(pamh), user);
				}
			} else {
				SYSLOG("could not retrieve old token");
			}

		} else {
			rc = PAM_SUCCESS;
		}

		if (rc == PAM_SUCCESS) {

			if ((rc = pam_get_confirm_pass(pamh, &newpass, PASSWORD_PROMPT_NEW, PASSWORD_PROMPT_CONFIRM, options->std_flags)) == PAM_SUCCESS) {
				if((newpass_crypt = password_encrypt(options, user, newpass, NULL))) {
					if(!(conn = db_connect(options))) {
						rc = PAM_AUTHINFO_UNAVAIL;
					}
					if (rc == PAM_SUCCESS) {
						DBGLOG("query: %s", options->query_pwd);
						if(pg_execParam(conn, &res, options->query_pwd, pam_get_service(pamh), user, newpass_crypt, rhost) != PAM_SUCCESS) {
							rc = PAM_AUTH_ERR;
						} else {
							SYSLOG("(%s) password for '%s' was changed.", pam_get_service(pamh), user);
							PQclear(res);
						}
						PQfinish(conn);
					}
					free (newpass_crypt);
				} else {
					rc = PAM_BUF_ERR;
				}
			} else {
				SYSLOG("could not retrieve new authentication tokens");
			}
		}
	}
	//free_module_options(options);
	if (flags & (PAM_PRELIM_CHECK | PAM_UPDATE_AUTHTOK))
		return rc;
	else
		return PAM_AUTH_ERR;

}
コード例 #23
0
ファイル: oid2name.c プロジェクト: amenonsen/postgres
/*
 * Actual code to make call to the database and print the output data.
 */
int
sql_exec(PGconn *conn, const char *todo, bool quiet)
{
	PGresult   *res;

	int			nfields;
	int			nrows;
	int			i,
				j,
				l;
	int		   *length;
	char	   *pad;

	/* make the call */
	res = PQexec(conn, todo);

	/* check and deal with errors */
	if (!res || PQresultStatus(res) > 2)
	{
		fprintf(stderr, "oid2name: query failed: %s\n", PQerrorMessage(conn));
		fprintf(stderr, "oid2name: query was: %s\n", todo);

		PQclear(res);
		PQfinish(conn);
		exit(-1);
	}

	/* get the number of fields */
	nrows = PQntuples(res);
	nfields = PQnfields(res);

	/* for each field, get the needed width */
	length = (int *) pg_malloc(sizeof(int) * nfields);
	for (j = 0; j < nfields; j++)
		length[j] = strlen(PQfname(res, j));

	for (i = 0; i < nrows; i++)
	{
		for (j = 0; j < nfields; j++)
		{
			l = strlen(PQgetvalue(res, i, j));
			if (l > length[j])
				length[j] = strlen(PQgetvalue(res, i, j));
		}
	}

	/* print a header */
	if (!quiet)
	{
		for (j = 0, l = 0; j < nfields; j++)
		{
			fprintf(stdout, "%*s", length[j] + 2, PQfname(res, j));
			l += length[j] + 2;
		}
		fprintf(stdout, "\n");
		pad = (char *) pg_malloc(l + 1);
		MemSet(pad, '-', l);
		pad[l] = '\0';
		fprintf(stdout, "%s\n", pad);
		free(pad);
	}

	/* for each row, dump the information */
	for (i = 0; i < nrows; i++)
	{
		for (j = 0; j < nfields; j++)
			fprintf(stdout, "%*s", length[j] + 2, PQgetvalue(res, i, j));
		fprintf(stdout, "\n");
	}

	/* cleanup */
	PQclear(res);
	free(length);

	return 0;
}
コード例 #24
0
/* public: authenticate user */
PAM_VISIBLE int
pam_sm_authenticate(pam_handle_t *pamh, int flags, int argc, const char **argv)
{
	modopt_t *options = NULL;
	const char *user, *password, *rhost;
	int rc;
	PGresult *res;
	PGconn *conn;	

	user = NULL; password = NULL; rhost = NULL;

	if ((rc = pam_get_item(pamh, PAM_RHOST, (const void **)&rhost)) == PAM_SUCCESS) {

		if ((rc = pam_get_user(pamh, &user, NULL)) == PAM_SUCCESS) {

			if ((options = mod_options(argc, argv)) != NULL) {

				DBGLOG("attempting to authenticate: %s, %s", user, options->query_auth);
				if ((rc = pam_get_pass(pamh, PAM_AUTHTOK, &password, PASSWORD_PROMPT, options->std_flags)) == PAM_SUCCESS) {

					if ((rc = backend_authenticate(pam_get_service(pamh), user, password, rhost, options)) == PAM_SUCCESS) {
						if ((password == 0 || *password == 0) && (flags & PAM_DISALLOW_NULL_AUTHTOK)) {
							rc = PAM_AUTH_ERR; 
						} else {
							SYSLOG("(%s) user %s authenticated.", pam_get_service(pamh), user);
						}

					} else {

                        char* rhost = NULL;
                        if (pam_get_item(pamh, PAM_RHOST, (void *) &rhost) == PAM_SUCCESS) {
                            SYSLOG("couldn't authenticate user %s (%s)", user, rhost);
                        } else {
                            SYSLOG("couldn't authenticate user %s", user);
                        }

					}

				} else {

					SYSLOG("couldn't get pass");

				}
			}
		}
	}
	
	if (rc == PAM_SUCCESS) {
		if (options->query_auth_succ) {
			if ((conn = db_connect(options))) {
				pg_execParam(conn, &res, options->query_auth_succ, pam_get_service(pamh), user, password, rhost);
				PQclear(res);
				PQfinish(conn);
			}
		}
	} else {
		if (options->query_auth_fail) {
			if ((conn = db_connect(options))) {
				pg_execParam(conn, &res, options->query_auth_fail, pam_get_service(pamh), user, password, rhost);
				PQclear(res);
				PQfinish(conn);
			}
		}
	}

	//free_mod_options(options);
	return rc;
}
コード例 #25
0
ファイル: pgsql_query_util.c プロジェクト: segasai/pg_idl
int pgsql_query_send_async(char *query, char *connect_info, IDL_VPTR *resultVptr)
{

    /* connection info */
    int query_status;


    PGconn *conn=NULL;
    PGresult *res=NULL;

    PGcancel *cancel_obj; 

    /* Information about each field */
    field_info *fi;

    /* Structure definition info */
    idl_tag_info *ti;
    //UCHAR *dataPtr;
    char *dataPtr;


    /* temporary pointer to tag data */
    UCHAR *tptr;

    /* loop variables */
    long long row;
    int tag;

    /* binary or ascii? Only need ascii for file output */
    int binary;

    int estatus;

    int verbose=0;

    /* We must reset this each time */
    cancel_query = 0;

    /* Attempt to establish the connection */
    conn = PQconnectdb(connect_info);

    if (PQstatus(conn) != CONNECTION_OK)
    {
        pgsql_query_error("Could not establish connection",
                PQerrorMessage(conn));	
        PQfinish(conn);
        return(MYPG_CONNECT_FAILURE);
    }



    /* send the query and return the results */
    if (kw.file_there) 
        binary = 0;
    else
        binary = 1;

    if (kw.verbose_there)
        if (kw.verbose) 
            verbose = 1;

    if (verbose)
        IDL_Message(IDL_M_NAMED_GENERIC, IDL_MSG_INFO, 
                "Querying database (^C to cancel)");


    if (! PQsendQueryParams(conn,
                query,
                0,
                NULL,
                NULL,
                NULL,
                NULL,
                binary) )
    {
        prepExit(conn, res);
        return(MYPG_DISPATCH_ERROR);
    }

    if (! (cancel_obj = PQgetCancel(conn)) )
    {
        IDL_Message(IDL_M_NAMED_GENERIC, IDL_MSG_INFO, 
                "Cancel object is NULL");
        return(MYPG_CANCEL_FAILURE);
    }

    /* Only allow SIGINT after this point, since it calls cancel */
    pgsql_sigint_register();


    /* note this is a busy loop. I tried sleeping, but it really slows
       down the job */
    PQconsumeInput(conn);        //Try to collect the results
    while (PQisBusy(conn))       // while not ready ...
    {

        if (cancel_query)
        {
            char errbuf[256];

            IDL_Message(IDL_M_NAMED_GENERIC, IDL_MSG_INFO, 
                    "Canceling query at user request");
            if (!PQcancel(cancel_obj, errbuf, 256) )
            {
                estatus = MYPG_CANCEL_FAILURE;
                IDL_Message(IDL_M_NAMED_GENERIC, IDL_MSG_INFO, 
                        errbuf);
            }
            else
                estatus = MYPG_QUERY_CANCELLED;

            pgsql_sigint_unregister();

            /* This will call PQfinish and PQclear clear the memory */
            prepExit(conn, res);
            return(estatus);

        }

        PQconsumeInput(conn); //...retry 
    }



    /* No signal handling beyond this point */
    pgsql_sigint_unregister();

    if (verbose)
        IDL_Message(IDL_M_NAMED_GENERIC, IDL_MSG_INFO, "Getting result");  

    res = PQgetResult(conn);

    /* Success? */
    query_status = pgsql_query_checkstatus(res);
    if (query_status != MYPG_SUCCESS)
    {
        prepExit(conn, res);
        return(query_status);
    }

    /* See if the user input a file to write to */
    if (kw.file_there) 
    {
        int write_status;
        write_status = pgsql_write_file(res);
        prepExit(conn, res);
        return(write_status);
    }


    /* Get information for each returned field */
    fi = pgsql_get_field_info(res);

    /* Copy into output keywords, if they exist */
    pgsql_copy_info(fi);

    /* Get info to make struct and copy data */
    ti = pgsql_get_idl_tag_info(fi->tagdefs);


    /* Create the output structure */  
    if (verbose)
        IDL_Message(IDL_M_NAMED_GENERIC, IDL_MSG_INFO, "Creating output struct");  

    dataPtr = 
        IDL_MakeTempStructVector(ti->sdef, (IDL_MEMINT) fi->nTuples, 
                resultVptr, IDL_TRUE);

    /* Copy into output variable */
    if (verbose)
        IDL_Message(IDL_M_NAMED_GENERIC, IDL_MSG_INFO, "Copying data");  

    for (row=0; row< fi->nTuples; row++)
        for (tag = 0; tag < fi->nFields; tag++)
        {
            tptr = 
                ( (*resultVptr)->value.s.arr->data +
                  row*( (*resultVptr)->value.arr->elt_len) + ti->tagOffsets[tag]);
            pgsql_store_binary(ti->tagDesc[tag]->type, fi->field_isarray[tag],
                    PQgetvalue(res, row, tag), tptr);	      
        }


    if (verbose)
        IDL_Message(IDL_M_NAMED_GENERIC, IDL_MSG_INFO, "Cleaning up");  

    pgsql_freemem(fi, ti);
    PQclear(res);
    PQfinish(conn);


    if (verbose)
        IDL_Message(IDL_M_NAMED_GENERIC, IDL_MSG_INFO, "Done");  

    return(MYPG_SUCCESS);

}
コード例 #26
0
ファイル: calculatelaylines.cpp プロジェクト: pcannon67/devel
CalculateLaylines::~CalculateLaylines()
{
    PQfinish(conn);
}
コード例 #27
0
ファイル: postgresql.c プロジェクト: pkrul/echoping
void
terminate()
{
    if (!connect_each_time)
        PQfinish(conn);
}
コード例 #28
0
ファイル: calculatelaylines.cpp プロジェクト: pcannon67/devel
void CalculateLaylines::closepostgreConnection(){
    PQfinish(conn);
}
コード例 #29
0
ファイル: rtgpgsql.c プロジェクト: Prophidys/RTG2
void pgsql_dbdisconnect(PGconn * pgsql)
{
    PQfinish(pgsql);
}
コード例 #30
0
ファイル: server3.c プロジェクト: dylanjacqu/hello_world
int
main (void)
{
  int sockfd = -1, new_fd, numbytes, highest = 0, i;
  int clients[MAXCLIENTS];
  char buffer[MAXDATASIZE];
  char localip[MAXDATASIZE];
  struct sockaddr_in my_addr, their_addr;
  socklen_t sin_size;
  struct timeval tv;
  fd_set readfds;
  const char *conninfo;
  PGconn *conn;
  PGresult *res;
  FILE *f;
  char line[100], *p, *c;
  const char *google_dns_server = "8.8.8.8";
  int dns_port = 53;
  struct sockaddr_in serv;
  int sock = socket (AF_INET, SOCK_DGRAM, 0);

  f = fopen ("/proc/net/route", "r");

  while (fgets (line, 100, f))
    {
      p = strtok (line, " \t");
      c = strtok (NULL, " \t");

      if (p != NULL && c != NULL)
	{
	  if (strcmp (c, "00000000") == 0)
	    {
	      printf ("Default interface is : %s \n", p);
	      break;
	    }
	}
    }

  if (sock < 0)
    {
      perror ("Socket error");
    }

  memset (&serv, 0, sizeof (serv));
  serv.sin_family = AF_INET;
  serv.sin_addr.s_addr = inet_addr (google_dns_server);
  serv.sin_port = htons (dns_port);

  int err = connect (sock, (const struct sockaddr *) &serv, sizeof (serv));

  struct sockaddr_in name;
  socklen_t namelen = sizeof (name);
  err = getsockname (sock, (struct sockaddr *) &name, &namelen);

  const char *p2 = inet_ntop (AF_INET, &name.sin_addr, localip, 100);

  if (p2 != NULL)
    {
      printf ("Local ip is : %s \n", localip);
    }
  else
    {
      //Some error
      printf ("Error number : %d . Error message : %s \n", errno,
	      strerror (errno));
      strcpy (localip, "Error");
    }

  close (sock);

  /*
  conninfo =
    "hostaddr=127.0.0.1 port=5432 dbname=postgres user=postgres password=password";
   */
   conninfo =
    "hostaddr=$POSTGRES2_PORT_5432_TCP_ADDR port=$POSTGRES2_PORT_5432_TCP_PORT user=postgres password=$POSTGRES2_ENV_POSTGRES_PASSWORD";

  if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) == -1)
    {
      perror ("socket");
      exit (-1);
    }
  my_addr.sin_family = AF_INET;
  my_addr.sin_port = htons (MYPORT);
  my_addr.sin_addr.s_addr = INADDR_ANY;
  bzero (&(my_addr.sin_zero), 8);

  if (bind (sockfd, (struct sockaddr *) &my_addr, sizeof (struct sockaddr)) ==
      -1)
    {
      perror ("bind");
      exit (-1);
    }
  if (listen (sockfd, BACKLOG) == -1)
    {
      perror ("listen");
      exit (-1);
    }
  bzero (clients, sizeof (clients));
  highest = sockfd;
  while (1)
    {
      sin_size = sizeof (struct sockaddr_in);
      tv.tv_sec = 0;
      tv.tv_usec = 250000;
      FD_ZERO (&readfds);
      for (i = 0; i < MAXCLIENTS; i++)
	{
	  if (clients[i] != 0)
	    {
	      FD_SET (clients[i], &readfds);
	    }
	}
      FD_SET (sockfd, &readfds);
      if (select (highest + 1, &readfds, NULL, NULL, &tv) >= 0)
	{
	  if (FD_ISSET (sockfd, &readfds))
	    {
	      if ((new_fd =
		   accept (sockfd, (struct sockaddr *) &their_addr,
			   &sin_size)) == -1)
		{
		  perror ("ACCEPT");
		  continue;
		}
	      for (i = 0; i < MAXCLIENTS; i++)
		{
		  if (clients[i] == 0)
		    {
		      clients[i] = new_fd;
		      break;
		    }
		}
	      if (i != MAXCLIENTS)
		{
		  if (new_fd > highest)
		    {
		      highest = clients[i];
		    }
		  printf ("Connexion received from %s (slot %i) ",
			  inet_ntoa (their_addr.sin_addr), i);
		  send (new_fd, "\nHELLO\n", 7, MSG_NOSIGNAL);
		}
	      else
		{
		  send (new_fd, "\nTOO MANY CLIENT\n", 17, MSG_NOSIGNAL);
		  close (new_fd);
		}
	    }
	  for (i = 0; i < MAXCLIENTS; i++)
	    {
	      if (FD_ISSET (clients[i], &readfds))
		{
		  if ((numbytes =
		       recv (clients[i], buffer, MAXDATASIZE, 0)) <= 0)
		    {
		      printf ("Connexion lost from slot %i", i);
		      close (clients[i]);
		      clients[i] = 0;
		    }
		  else
		    {
		      buffer[numbytes] = '\0';
		      printf ("Received from slot %i : %s", i, buffer);
		      if (strncmp (buffer, "POSTGRES", 6) == 0)
			{
			  conn = PQconnectdb (conninfo);
			  if (PQstatus (conn) != CONNECTION_OK)
			    {
			      fprintf (stderr,
				       "Connection to database failed: %s",
				       PQerrorMessage (conn));
			      send (new_fd, "\nDB KO\n", 7, MSG_NOSIGNAL);
			    }
			  else
			    {
			      send (new_fd, "\nDB OK\n", 7, MSG_NOSIGNAL);
			      /* INSERT CLIENT IP and timestamp */
			    }
			  PQfinish (conn);
			}
		      if ((strncmp (buffer, "QUIT", 4) == 0))
			{
			  printf ("Connexion QUIT from slot %i", i);
			  close (clients[i]);
			  clients[i] = 0;
			}
		      if ((strncmp (buffer, "EXIT", 4) == 0))
			{
			  printf ("Connexion EXIT from slot %i", i);
			  close (clients[i]);
			  clients[i] = 0;
			}
		      if ((strncmp (buffer, "CLOSE", 5) == 0))
			{
			  printf ("Connexion CLOSE from slot %i", i);
			  close (clients[i]);
			  clients[i] = 0;
			}
		      if ((strncmp (buffer, "INTERFACE", 9) == 0))
			{
			  send (new_fd, "\n", 1, MSG_NOSIGNAL);
			  send (new_fd, localip, strlen (localip),
				MSG_NOSIGNAL);
			  send (new_fd, "\n", 1, MSG_NOSIGNAL);
			}
		      if ((strncmp (buffer, "IP", 2) == 0))
			{
			  send (new_fd, "\n", 1, MSG_NOSIGNAL);
			  send (new_fd, p, strlen (p), MSG_NOSIGNAL);
			  send (new_fd, "\n", 1, MSG_NOSIGNAL);
			}
                      if ((strncmp (buffer, "DBCNX", 2) == 0))
                        {
                          send (new_fd, "\n", 1, MSG_NOSIGNAL);
                          send (new_fd, conninfo, strlen (conninfo), MSG_NOSIGNAL);
                          send (new_fd, "\n", 1, MSG_NOSIGNAL);
                        }
		    }
		}
	    }
	}
      else
	{
	  perror ("SELECT");
	  continue;
	}
    }
  return 0;
}