<commit_before><?php
/*
 @version   v5.21.0-dev  ??-???-2016
 @copyright (c) 2000-2013 <NAME> (<EMAIL>). All rights reserved.
 @copyright (c) 2014      <NAME>, <NAME> and the ADOdb community
  Released under both BSD license and Lesser GPL library license.
  Whenever there is any discrepancy between the two licenses,
  the BSD license will take precedence.
  Set tabs to 8.

  Original version derived from <NAME> (<EMAIL>) - DBNet Informatica & Comunicaciones.
  08 Nov 2000 jlim - Minor corrections, removing mysql stuff
  09 Nov 2000 jlim - added insertid support suggested by "<NAME>" <<EMAIL>>
			  jlim - changed concat operator to || and data types to MetaType to match documented pgsql types
					 see http://www.postgresql.org/devel-corner/docs/postgres/datatype.htm
  22 Nov 2000 jlim - added changes to FetchField() and MetaTables() contributed by "raser" <<EMAIL>>
  27 Nov 2000 jlim - added changes to _connect/_pconnect from ideas by "Lennie" <<EMAIL>>
  15 Dec 2000 jlim - added changes suggested by Additional code changes by "<NAME>" <EMAIL>.
  31 Jan 2002 jlim - finally installed postgresql. testing
  01 Mar 2001 jlim - Freek Dijkstra changes, also support for text type

  See http://www.varlena.com/varlena/GeneralBits/47.php

	-- What indexes are on my table?
	select * from pg_indexes where tablename = 'tablename';

	-- What triggers are on my table?
	select c.relname as "Table", t.tgname as "Trigger Name",
	   t.tgconstrname as "Constraint Name", t.tgenabled as "Enabled",
	   t.tgisconstraint as "Is Constraint", cc.relname as "Referenced Table",
	   p.proname as "Function Name"
	from pg_trigger t, pg_class c, pg_class cc, pg_proc p
	where t.tgfoid = p.oid and t.tgrelid = c.oid
	   and t.tgconstrrelid = cc.oid
	   and c.relname = 'tablename';

	-- What constraints are on my table?
	select r.relname as "Table", c.conname as "Constraint Name",
	   contype as "Constraint Type", conkey as "Key Columns",
	   confkey as "Foreign Columns", consrc as "Source"
	from pg_class r, pg_constraint c
	where r.oid = c.conrelid
	   and relname = 'tablename';

*/

// security - hide paths
if (!defined('ADODB_DIR')) die();

function adodb_addslashes($s)
{
	$len = strlen($s);
	if ($len == 0) return "''";
	if (strncmp($s,"'",1) === 0 && substr($s,$len-1) == "'") return $s; // already quoted

	return "'".addslashes($s)."'";
}

class ADODB_postgres64 extends ADOConnection{
	var $databaseType = 'postgres64';
	var $dataProvider = 'postgres';
	var $hasInsertID = true;
	var $_resultid = false;
	var $concat_operator='||';
	var $metaDatabasesSQL = "select datname from pg_database where datname not in ('template0','template1') order by 1";
	var $metaTablesSQL = "select tablename,'T' from pg_tables where tablename not like 'pg\_%'
		and tablename not in ('sql_features', 'sql_implementation_info', 'sql_languages',
			'sql_packages', 'sql_sizing', 'sql_sizing_profiles')
	union
		select viewname,'V' from pg_views where viewname not like 'pg\_%'";
	//"select tablename from pg_tables where tablename not like 'pg_%' order by 1";
	var $isoDates = true; // accepts dates in ISO format
	var $sysDate = "CURRENT_DATE";
	var $sysTimeStamp = "CURRENT_TIMESTAMP";
	var $blobEncodeType = 'C';
	var $metaColumnsSQL = "SELECT a.attname,t.typname,a.attlen,a.atttypmod,a.attnotnull,a.atthasdef,a.attnum
		FROM pg_class c, pg_attribute a,pg_type t
		WHERE relkind in ('r','v') AND (c.relname='%s' or c.relname = lower('%s')) and a.attname not like '....%%'
		AND a.attnum > 0 AND a.atttypid = t.oid AND a.attrelid = c.oid ORDER BY a.attnum";

	// used when schema defined
	var $metaColumnsSQL1 = "SELECT a.attname, t.typname, a.attlen, a.atttypmod, a.attnotnull, a.atthasdef, a.attnum
		FROM pg_class c, pg_attribute a, pg_type t, pg_namespace n
		WHERE relkind in ('r','v') AND (c.relname='%s' or c.relname = lower('%s'))
		and c.relnamespace=n.oid and n.nspname='%s'
		and a.attname not like '....%%' AND a.attnum > 0
		AND a.atttypid = t.oid AND a.attrelid = c.oid ORDER BY a.attnum";

	// get primary key etc -- from Freek Dijkstra
	var $metaKeySQL = "SELECT ic.relname AS index_name, a.attname AS column_name,i.indisunique AS unique_key, i.indisprimary AS primary_key
		FROM pg_class bc, pg_class ic, pg_index i, pg_attribute a
		WHERE bc.oid = i.indrelid AND ic.oid = i.indexrelid
		AND (i.indkey[0] = a.attnum OR i.indkey[1] = a.attnum OR i.indkey[2] = a.attnum OR i.indkey[3] = a.attnum OR i.indkey[4] = a.attnum OR i.indkey[5] = a.attnum OR i.indkey[6] = a.attnum OR i.indkey[7] = a.attnum)
		AND a.attrelid = bc.oid AND bc.relname = '%s'";

	var $hasAffectedRows = true;
	var $hasLimit = false;	// set to true for pgsql 7 only. support pgsql/mysql SELECT * FROM TABLE LIMIT 10
	// below suggested by <NAME>
	var $true = 'TRUE';		// string that represents TRUE for a database
	var $false = 'FALSE';		// string that represents FALSE for a database
	var $fmtDate = "'Y-m-d'";	// used by DBDate() as the default date format used by the database
	var $fmtTimeStamp = "'Y-m-d H:i:s'"; // used by DBTimeStamp as the default timestamp fmt.
	var $hasMoveFirst = true;
	var $hasGenID = true;
	var $_genIDSQL = "SELECT NEXTVAL('%s')";
	var $_genSeqSQL = "CREATE SEQUENCE %s START %s";
	var $_dropSeqSQL = "DROP SEQUENCE %s";
	var $metaDefaultsSQL = "SELECT d.adnum as num, d.adsrc as def from pg_attrdef d, pg_class c where d.adrelid=c.oid and c.relname='%s' order by d.adnum";
	var $random = 'random()';		/// random function
	var $autoRollback = true; // apparently pgsql does not autorollback properly before php 4.3.4
							// http://bugs.php.net/bug.php?id=25404

	var $uniqueIisR = true;
	var $_bindInputArray = false; // requires postgresql 7.3+ and ability to modify database
	var $disableBlobs = false; // set to true to disable blob checking, resulting in 2-5% improvement in performance.

	var $_pnum = 0;

	// The last (fmtTimeStamp is not entirely correct:
	// PostgreSQL also has support for time zones,
	// and writes these time in this format: "2001-03-01 18:59:26+02".
	// There is no code for the "+02" time zone information, so I just left that out.
	// I'm not familiar enough with both ADODB as well as Postgres
	// to know what the concequences are. The other values are correct (wheren't in 0.94)
	// -- Freek Dijkstra

	function ServerInfo()
	{
		if (isset($this->version)) return $this->version;

		$arr['description'] = $this->GetOne("select version()");
		$arr['version'] = ADOConnection::_findvers($arr['description']);
		$this->version = $arr;
		return $arr;
	}

	function IfNull( $field, $ifNull )
	{
		return " coalesce($field, $ifNull) ";
	}

	// get the last id - never tested
	function pg_insert_id($tablename,$fieldname)
	{
		$result=pg_query($this->_connectionID, 'SELECT last_value FROM '. $tablename .'_'. $fieldname .'_seq');
		if ($result) {
			$arr = @pg_fetch_row($result,0);
			pg_free_result($result);
			if (isset($arr[0])) return $arr[0];
		}
		return false;
	}

	/**
	 * Warning from http://www.php.net/manual/function.pg-getlastoid.php:
	 * Using a OID as a unique identifier is not generally wise.<commit_msg>pgsql: new ServerInfo() param to avoid unnecessary SELECT<commit_after><?php
/*
 @version   v5.21.0-dev  ??-???-2016
 @copyright (c) 2000-2013 <NAME> (<EMAIL>). All rights reserved.
 @copyright (c) 2014      <NAME>, <NAME> and the ADOdb community
  Released under both BSD license and Lesser GPL library license.
  Whenever there is any discrepancy between the two licenses,
  the BSD license will take precedence.
  Set tabs to 8.

  Original version derived from <NAME> (<EMAIL>) - DBNet Informatica & Comunicaciones.
  08 Nov 2000 jlim - Minor corrections, removing mysql stuff
  09 Nov 2000 jlim - added insertid support suggested by "<NAME>" <<EMAIL>>
			  jlim - changed concat operator to || and data types to MetaType to match documented pgsql types
					 see http://www.postgresql.org/devel-corner/docs/postgres/datatype.htm
  22 Nov 2000 jlim - added changes to FetchField() and MetaTables() contributed by "raser" <<EMAIL>>
  27 Nov 2000 jlim - added changes to _connect/_pconnect from ideas by "Lennie" <<EMAIL>>
  15 Dec 2000 jlim - added changes suggested by Additional code changes by "<NAME>" <EMAIL>.
  31 Jan 2002 jlim - finally installed postgresql. testing
  01 Mar 2001 jlim - Freek Dijkstra changes, also support for text type

  See http://www.varlena.com/varlena/GeneralBits/47.php

	-- What indexes are on my table?
	select * from pg_indexes where tablename = 'tablename';

	-- What triggers are on my table?
	select c.relname as "Table", t.tgname as "Trigger Name",
	   t.tgconstrname as "Constraint Name", t.tgenabled as "Enabled",
	   t.tgisconstraint as "Is Constraint", cc.relname as "Referenced Table",
	   p.proname as "Function Name"
	from pg_trigger t, pg_class c, pg_class cc, pg_proc p
	where t.tgfoid = p.oid and t.tgrelid = c.oid
	   and t.tgconstrrelid = cc.oid
	   and c.relname = 'tablename';

	-- What constraints are on my table?
	select r.relname as "Table", c.conname as "Constraint Name",
	   contype as "Constraint Type", conkey as "Key Columns",
	   confkey as "Foreign Columns", consrc as "Source"
	from pg_class r, pg_constraint c
	where r.oid = c.conrelid
	   and relname = 'tablename';

*/

// security - hide paths
if (!defined('ADODB_DIR')) die();

function adodb_addslashes($s)
{
	$len = strlen($s);
	if ($len == 0) return "''";
	if (strncmp($s,"'",1) === 0 && substr($s,$len-1) == "'") return $s; // already quoted

	return "'".addslashes($s)."'";
}

class ADODB_postgres64 extends ADOConnection{
	var $databaseType = 'postgres64';
	var $dataProvider = 'postgres';
	var $hasInsertID = true;
	var $_resultid = false;
	var $concat_operator='||';
	var $metaDatabasesSQL = "select datname from pg_database where datname not in ('template0','template1') order by 1";
	var $metaTablesSQL = "select tablename,'T' from pg_tables where tablename not like 'pg\_%'
		and tablename not in ('sql_features', 'sql_implementation_info', 'sql_languages',
			'sql_packages', 'sql_sizing', 'sql_sizing_profiles')
	union
		select viewname,'V' from pg_views where viewname not like 'pg\_%'";
	//"select tablename from pg_tables where tablename not like 'pg_%' order by 1";
	var $isoDates = true; // accepts dates in ISO format
	var $sysDate = "CURRENT_DATE";
	var $sysTimeStamp = "CURRENT_TIMESTAMP";
	var $blobEncodeType = 'C';
	var $metaColumnsSQL = "SELECT a.attname,t.typname,a.attlen,a.atttypmod,a.attnotnull,a.atthasdef,a.attnum
		FROM pg_class c, pg_attribute a,pg_type t
		WHERE relkind in ('r','v') AND (c.relname='%s' or c.relname = lower('%s')) and a.attname not like '....%%'
		AND a.attnum > 0 AND a.atttypid = t.oid AND a.attrelid = c.oid ORDER BY a.attnum";

	// used when schema defined
	var $metaColumnsSQL1 = "SELECT a.attname, t.typname, a.attlen, a.atttypmod, a.attnotnull, a.atthasdef, a.attnum
		FROM pg_class c, pg_attribute a, pg_type t, pg_namespace n
		WHERE relkind in ('r','v') AND (c.relname='%s' or c.relname = lower('%s'))
		and c.relnamespace=n.oid and n.nspname='%s'
		and a.attname not like '....%%' AND a.attnum > 0
		AND a.atttypid = t.oid AND a.attrelid = c.oid ORDER BY a.attnum";

	// get primary key etc -- from Freek Dijkstra
	var $metaKeySQL = "SELECT ic.relname AS index_name, a.attname AS column_name,i.indisunique AS unique_key, i.indisprimary AS primary_key
		FROM pg_class bc, pg_class ic, pg_index i, pg_attribute a
		WHERE bc.oid = i.indrelid AND ic.oid = i.indexrelid
		AND (i.indkey[0] = a.attnum OR i.indkey[1] = a.attnum OR i.indkey[2] = a.attnum OR i.indkey[3] = a.attnum OR i.indkey[4] = a.attnum OR i.indkey[5] = a.attnum OR i.indkey[6] = a.attnum OR i.indkey[7] = a.attnum)
		AND a.attrelid = bc.oid AND bc.relname = '%s'";

	var $hasAffectedRows = true;
	var $hasLimit = false;	// set to true for pgsql 7 only. support pgsql/mysql SELECT * FROM TABLE LIMIT 10
	// below suggested by <NAME>
	var $true = 'TRUE';		// string that represents TRUE for a database
	var $false = 'FALSE';		// string that represents FALSE for a database
	var $fmtDate = "'Y-m-d'";	// used by DBDate() as the default date format used by the database
	var $fmtTimeStamp = "'Y-m-d H:i:s'"; // used by DBTimeStamp as the default timestamp fmt.
	var $hasMoveFirst = true;
	var $hasGenID = true;
	var $_genIDSQL = "SELECT NEXTVAL('%s')";
	var $_genSeqSQL = "CREATE SEQUENCE %s START %s";
	var $_dropSeqSQL = "DROP SEQUENCE %s";
	var $metaDefaultsSQL = "SELECT d.adnum as num, d.adsrc as def from pg_attrdef d, pg_class c where d.adrelid=c.oid and c.relname='%s' order by d.adnum";
	var $random = 'random()';		/// random function
	var $autoRollback = true; // apparently pgsql does not autorollback properly before php 4.3.4
							// http://bugs.php.net/bug.php?id=25404

	var $uniqueIisR = true;
	var $_bindInputArray = false; // requires postgresql 7.3+ and ability to modify database
	var $disableBlobs = false; // set to true to disable blob checking, resulting in 2-5% improvement in performance.

	var $_pnum = 0;

	// The last (fmtTimeStamp is not entirely correct:
	// PostgreSQL also has support for time zones,
	// and writes these time in this format: "2001-03-01 18:59:26+02".
	// There is no code for the "+02" time zone information, so I just left that out.
	// I'm not familiar enough with both ADODB as well as Postgres
	// to know what the concequences are. The other values are correct (wheren't in 0.94)
	// -- <NAME>

	/**
	 * Retrieve Server version and information.
	 * @param bool $detailed If true, retrieve detailed version string (executes
	 *                       a SQL query) in addition to the version number
	 * @return array|bool Server info or false if version could not be retrieved
	 *                    e.g. if there is no active connection
	 */
	function ServerInfo($detailed = true)
	{
		if (empty($this->version['version'])) {
			// We don't have a connection, so we can't retrieve server info
			if (!$this->_connectionID) {
				return false;
			}

			// Use pg_parameter_status() instead of pg_version() to retrieve the
			// version number, as the former includes logic to obtain values for
			// server_version, even when PHP has been compiled with PostgreSQL
			// 7.3 or lower.
			$version = pg_parameter_status($this->_connectionID, 'server_version');
			$this->version = array(
				'version' => $version,
				'description' => null,
			);
		}
		if ($detailed && $this->version['description'] === null) {
			$this->version['description'] = $this->GetOne('select version()');
		}

		return $this->version;
	}

	function IfNull( $field, $ifNull )
	{
		return " coalesce($field, $ifNull) ";
	}

	// get the last id - never tested
	function pg_insert_id($tablename,$fieldname)
	{
		$result=pg_query($this->_connectionID, 'SELECT last_value FROM '. $tablename .'_'. $fieldname .'_seq');
		if ($result) {
			$arr = @pg_fetch_row($result,0);
			pg_free_result($result);
			if (isset($arr[0])) return $arr[0];
		}
		return false;
	}

	/**
	 * Warning from http://www.php.net/manual/function.pg-getlastoid.php:
	 * Using a OID as a unique identifier is not generally wise.
{'fraction_non_alphanumeric': 0.12867402580130335, 'fraction_numerical': 0.017156536773507116, 'mean_word_length': 3.7606837606837606, 'pattern_counts': {'":': 0, '<': 38, '<?xml version=': 0, '>': 56, 'https://': 0, 'lorem ipsum': 0, 'www.': 6, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5606968', 'n_tokens_mistral': 5530, 'n_tokens_neox': 5108, 'n_words': 1756}