See, http://www.postgresql.org/docs/8.4/interactive/catalog-pg-constraint.html
@return bool. Populate the static variables $this->references $this->isReferencedBy
542470
private function loadReferences()
    {

        // References defined in pg_catalog
        $sql = new Raw('SELECT * FROM dev."vAttributeReferences" WHERE "isInherited" = false');
        $sql = new Raw( <<<SQL
-- Based on. http://code.google.com/p/pgutils/ but very heavily modified
-- Potentially inheritance aware/compensating. Be careful. Use the unit tests.
WITH "vRelationDescendants" as (
    SELECT
        c.oid,
        c.relname,
        (
            WITH RECURSIVE
            q( oid ) AS
            (
                SELECT
                    crd.oid
                FROM
                    pg_class crd
                WHERE
                    crd.oid = c.oid

                UNION ALL

                SELECT i.inhrelid FROM q INNER JOIN pg_inherits i ON q.oid = i.inhparent
            )
            SELECT oid FROM q WHERE oid = c.oid
        ) as childoid
    FROM
        pg_class c
    INNER JOIN
        pg_namespace n ON n.oid = c.relnamespace
    ORDER BY
        n.nspname, c.relname
), "vAttributeReferences"  as (
    SELECT
        fkr.oid <> fkrd.oid AS "isInheritedSource",
        pkr.oid <> pkrd.oid AS "isInheritedTarget",
        ( fkr.oid <> fkrd.oid OR pkr.oid <> pkrd.oid ) as "isInherited",

        fkn.nspname AS fk_namespace,
        fkr.relname AS fk_relation,
        fkr.oid AS fk_oid,
        fka.attname AS fk_column,
        fka.attnum as "fk_attnum",

        -- initByData
        fkr.oid::text || '.' || fka.attnum::text AS fk_key,

        (
            EXISTS (
                SELECT
                    pg_index.indexrelid,
                    pg_index.indrelid,
                    pg_index.indkey,
                    pg_index.indclass,
                    pg_index.indnatts,
                    pg_index.indisunique,
                    pg_index.indisprimary,
                    pg_index.indisclustered,
                    pg_index.indexprs,
                    pg_index.indpred
                FROM
                    pg_index
                WHERE
                    pg_index.indrelid = fkr.oid AND pg_index.indkey[0] = fka.attnum
            )
        ) AS fk_indexed,
        pkn.nspname AS pk_namespace,
        pkr.relname AS pk_relation,
        pkr.oid AS pk_oid,
        pka.attname AS pk_column,
        pka.attnum as "pk_attnum",

        -- initByData
        pkr.oid::text || '.' || pka.attnum::text AS pk_key,

        (
            EXISTS (
                SELECT
                    pg_index.indexrelid,
                    pg_index.indrelid,
                    pg_index.indkey,
                    pg_index.indclass,
                    pg_index.indnatts,
                    pg_index.indisunique,
                    pg_index.indisprimary,
                    pg_index.indisclustered,
                    pg_index.indexprs,
                    pg_index.indpred
                FROM
                    pg_index
                WHERE
                    pg_index.indrelid = pkr.oid AND
                    pg_index.indkey[0] = pka.attnum
            )
        ) AS pk_indexed,
        c.confupdtype::text || c.confdeltype::text AS ud,
        cn.nspname AS c_namespace,
        c.conname AS c_name
    FROM (
        (
            (
                (
                    (
                        (
                            (
                                pg_constraint c
                                    JOIN
                                pg_namespace cn ON cn.oid = c.connamespace
                            )
                            INNER JOIN
                                "vRelationDescendants" as fkrd ON c.conrelid = fkrd.oid
                            INNER JOIN
                                pg_class fkr ON fkr.oid = fkrd.childoid
                        )
                        JOIN
                            pg_namespace fkn ON fkn.oid = fkr.relnamespace
                    )
                    JOIN
                        pg_attribute fka ON fka.attrelid = c.conrelid AND fka.attnum = ANY (c.conkey)
                )
                INNER JOIN
                    "vRelationDescendants" as pkrd ON c.confrelid = pkrd.oid
                INNER JOIN
                    pg_class pkr ON pkr.oid = pkrd.childoid
            )
            JOIN
                pg_namespace pkn ON pkn.oid = pkr.relnamespace
        )
        JOIN
            pg_attribute pka ON pka.attrelid = c.confrelid AND pka.attnum = ANY (c.confkey)
    )
    WHERE
        c.contype = 'f'::"char" AND
        fkn.nspname = ANY( current_schemas(false) ) AND
        pkn.nspname = ANY( current_schemas(false) )
)
SELECT * FROM "vAttributeReferences" WHERE "isInherited" = false
SQL
        );

        $relationships = $this->db->query($sql);

        foreach( $relationships as $relationship ) {

            $fk = $this->pgAttributes->findOneByKey($relationship['fk_key']);
            $pk = $this->pgAttributes->findOneByKey($relationship['pk_key']);

            if( !$fk or !$pk ) {
                d_pr( $relationship );
                die();
            }

            $fk->addReference($pk);

        }

        // look for normality defined relationships
        $profiler = new Profiler( __FUNCTION__ );
        $profiler->log();

        foreach( $this->pgClasses as $relation ) {

            $tags = $relation->getTags();

            if( isset( $tags['references'] ) ) {

                foreach( $tags['references'] as $reference ) {

                    $reference = array_map( 'trim', explode( '=', $reference) );
                    $reference[1] = explode( '.', $reference[1] );

                    $fk = $relation->getAttributeByName($reference[0]);

                    // referencing
                    $pkTable = $this->pgClasses->findOneByName($reference[1][0]);
                    $pk = $pkTable->getAttributeByName($reference[1][1]);

                    $fk->addReference($pk);

                }

            }

        }

//        echo $profiler->log()->output();

    }
1143634
private function bindParameters()
    {
        $bindedParameterReferences = array(implode('', $this->bindedTypes));
        $lobParameters = array();
        $null = null;

        foreach ($this->bindedParameters as $key => &$parameter) {
            if (isset($this->bindedTypes[$key - 1])
                && ($this->bindedTypes[$key - 1] === self::$mappedTypes[\PDO::PARAM_LOB])) {
                $lobParameters[$key - 1] = $parameter;
                $bindedParameterReferences[$key] = &$null;
            } else {
                $bindedParameterReferences[$key] = &$parameter;
            }
        }

        call_user_func_array(array($this->mysqliStatement, 'bind_param'), $bindedParameterReferences);

        foreach ($lobParameters as $key => $lobParameter) {
            rewind($lobParameter);

            while (!feof($lobParameter)) {
                $this->mysqliStatement->send_long_data(
                    $key,
                    fread($lobParameter, $this->connection->getMaxAllowedPacket())
                );
            }
        }
    }
55690
private function update ()
	{
		$this->before_update();

		$statement = 'UPDATE ' . static::$table_name . ' SET ';

		$sets = [];
		$values = [];

		foreach ($this->storage as $key => $value) {
			if ($value !== null) {
				$sets[] = $this->db->quote_column($key) . ' = ?';
				$values[] = $value;
			}
		}

		$statement .= implode(', ', $sets);

		$pk = $this->primary_key_condition();

		$statement .= ' WHERE ' . $pk->statement;

		$values = array_merge($values, $pk->values->getArrayCopy());

		$result = $this->db->query($statement, $values, 'multi', null, false);

		$this->stored = true;
		$this->updated = false;

		$this->after_update();

		return true;
	}
649706
private function getDataDeclaration()
    {

        $vars = $this->pgClass->getAttributes()->map(
            function ($column) {
                $dataType = $this->dataTypes[$column->name];

                // initial value
                $initialValue = null;

                // is bool with default
                if( $dataType->isBool( $default ) and is_bool( $default ) ) {
                    $initialValue = $dataType->getDefault();
                }

                $comment = '';

                // primary key
                if( $column->isPrimaryKey() ) {
                    $comment .= 'PK; ';
                }

                // references
                if( count( $references = $column->getReferences() ) ) {
                    $comment .= sprintf( "references %s", $references->implode(', ') );
                }

                // isReferencedBy
                if( count( $isReferencedBy = $column->getIsReferencedBy() ) ) {
                    $comment .= sprintf( "is referenced by %s", $isReferencedBy->implode(', ') );
                }

                // form options
                if( $formOptions = $column->getTags('form') ) {
                    $comment .= "Form options ".json_encode( $formOptions );
                }

                // explode, trim, implode comment
                $comment = implode( ", ", array_map( 'trim', explode( "\n", $comment ) ) );

                return sprintf(
                    "'%s' => %s,%s",
                    $column->name,
                    Php::varExport( $initialValue ),
                    $comment ? " # {$comment}" : ''
                );
            }
        );

        $vars = (new Format($vars))->indent(4);

        $this->class->classComponents[] = new VariableDeclaration(
            'data',
            new Sformatf( <<<'PHP'
/**
 * Columns defined in %s
 * @var array
 */
protected $data = array(
%s
);
PHP
                , $this->pgClass->getFullyQualifiedName()
                , $vars
            )
        );

        return $this;

    }
225025
public function isMySqlAvailable() {
    if (is_null($this->isMySqlAvailable)) {
      $this->isMySqlAvailable = $this->getMySqlAvailable();
    }

    return $this->isMySqlAvailable;
  }
307057
public function addReference($p1, $p2 = null)
    {
        if (is_array($p1)) {
            $this->addReference(@$p1["local"], @$p1["foreign"]);
        } else {
            if ($p1 instanceof Column) {
                $p1 = $p1->getName();
            }
            if ($p2 instanceof Column) {
                $p2 = $p2->getName();
            }
            $this->localColumns[] = $p1;
            $this->foreignColumns[] = $p2;
        }
    }
391624
private function getSymfonyValidatorConstraints()
    {

        $constraints = array();

        $this->loadUnsettableProperties();

        foreach ( $this->dataTypes as $column => $type ) {

            // skip inherited columns
            if( $type->isInherited() ) {
                continue;
            }

            // Skip Columns designated unsetable.
            if( in_array( $column, $this->unsetableProperties ) ) {
                continue;
            }

            // Check if column is nullable.
            if( !$type->isNullable() and !$type->hasDefault() ){
                $constraints[] = $this->getSymfonyConstraint( $column, 'NotNull');
            }

            // Normality entity type constraints.
            if( $type->getEntity() === 'normality' ) {

                $dataType = $this->options['entityPlaceholder']."\\{$type->getNormality()}";
                $constraints[] = $this->getSymfonyTypeConstraint( $column, $dataType );

            } elseif( $type->getEntity() ){

                $dataType = "Bond\\Entity\\Types\\{$type->getEntity()}";
                $constraints[] = $this->getSymfonyTypeConstraint( $column, $dataType );

            } elseif( $type->isEnum( $enumName ) ) {

                $constraints[] = $this->getSymfonyChoiceConstraint(
                    $column,
                    $this->pgClass->getCatalog()->enum->getValues($enumName)
                );

            } else {

                switch( $type->getType() ) {

                    case 'int':

                        $constraints[] = $this->getSymfonyConstraint( $column, 'RealInt', null, false );
                        $this->class->addUses( 'Bond\\Bridge\\Normality\\Constraint\\RealInt' );
                        break;

                    case 'citext':
                    case 'text':

                        $constraints[] = $this->getSymfonyTypeConstraint( $column, 'string' );
                        if( is_numeric( $type->getLength() ) ) {
                            $constraints[] = $this->getSymfonyConstraint( $column, 'MaxLength', $type->getLength() );
                        }
                        break;

                    case 'bool':

                        $constraints[] = $this->getSymfonyTypeConstraint( $column, 'bool' );
                        break;

                }

            }

            $constraints[] = '';

        }

        return implode( "\n", $constraints );

    }
535660
public function getCreateConstraintSQL(Constraint $constraint, $table)
    {
        if ($table instanceof Table) {
            $table = $table->getQuotedName($this);
        }

        $query = 'ALTER TABLE ' . $table . ' ADD CONSTRAINT ' . $constraint->getQuotedName($this);

        $columnList = '(' . implode(', ', $constraint->getQuotedColumns($this)) . ')';

        $referencesClause = '';
        if ($constraint instanceof Index) {
            if ($constraint->isPrimary()) {
                $query .= ' PRIMARY KEY';
            } elseif ($constraint->isUnique()) {
                $query .= ' UNIQUE';
            } else {
                throw new InvalidArgumentException(
                    'Can only create primary or unique constraints, no common indexes with getCreateConstraintSQL().'
                );
            }
        } elseif ($constraint instanceof ForeignKeyConstraint) {
            $query .= ' FOREIGN KEY';

            $referencesClause = ' REFERENCES ' . $constraint->getQuotedForeignTableName($this) .
                ' (' . implode(', ', $constraint->getQuotedForeignColumns($this)) . ')';
        }
        $query .= ' ' . $columnList . $referencesClause;

        return $query;
    }
767271
public function isForeignPrimaryKey()
    {
        $lfmap = $this->getLocalForeignMapping();
        $foreignTable = $this->getForeignTable();

        $foreignPKCols = array();
        foreach ($foreignTable->getPrimaryKey() as $fPKCol) {
            $foreignPKCols[] = $fPKCol->getName();
        }

        $foreignCols = array();
        foreach ($this->getLocalColumns() as $colName) {
            $foreignCols[] = $foreignTable->getColumn($lfmap[$colName])->getName();
        }

        return ((count($foreignPKCols) === count($foreignCols)) && !array_diff($foreignPKCols, $foreignCols));
    }
86901
public function getPHP() {

        $result = '';

        // The type
        switch ($this->getType()) {
            case XMLDB_KEY_PRIMARY:
                $result .= 'XMLDB_KEY_PRIMARY' . ', ';
                break;
            case XMLDB_KEY_UNIQUE:
                $result .= 'XMLDB_KEY_UNIQUE' . ', ';
                break;
            case XMLDB_KEY_FOREIGN:
                $result .= 'XMLDB_KEY_FOREIGN' . ', ';
                break;
            case XMLDB_KEY_FOREIGN_UNIQUE:
                $result .= 'XMLDB_KEY_FOREIGN_UNIQUE' . ', ';
                break;
        }
        // The fields
        $keyfields = $this->getFields();
        if (!empty($keyfields)) {
            $result .= "['".  implode("', '", $keyfields) . "']";
        } else {
            $result .= 'null';
        }
        // The FKs attributes
        if ($this->getType() == XMLDB_KEY_FOREIGN ||
            $this->getType() == XMLDB_KEY_FOREIGN_UNIQUE) {
            // The reftable
            $reftable = $this->getRefTable();
            if (!empty($reftable)) {
                $result .= ", '" . $reftable . "', ";
            } else {
                $result .= 'null, ';
            }
            // The reffields
            $reffields = $this->getRefFields();
            if (!empty($reffields)) {
                $result .= "['".  implode("', '", $reffields) . "']";
            } else {
                $result .= 'null';
            }
        }
        // Return result
        return $result;
    }
1289173
protected function insert()
    {
        if ($this->isDirty()) {
            $sql = 'INSERT INTO '.$this->getTableName().'  SET ';
            $data = [];
            $params = [];

            $pk_name = $this->getPkName();

            foreach ((new \ReflectionObject($this))->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) {
                if ($this->{$property->getName()}) {
                    if ($this->{$property->getName()} instanceof Expression) {
                        $data[] = "`{$property->getName()}` = ".$this->{$property->getName()}->toSql();
                    } else {
                        $data[] = "`{$property->getName()}` = :{$property->getName()}";
                        $params[":{$property->getName()}"] = $this->{$property->getName()};
                    }
                }
            }

            $sql .= implode(',', $data);

            $stmt = $this->getDB()->prepare($sql);
            $stmt->execute($params);
            $last_insert_id = $this->getDB()->lastInsertId();

            if (is_array($pk_name)) {
                /*
                 * @TODO: Composite PK
                 */
            } else {
                $this->{$pk_name} = $last_insert_id;
            }

            $this->setDirty(false);
            $stmt->closeCursor();
            $this->_is_new = false;
        }

        return true;
    }
321276
public function isCreate()
    {
        $primary = $this->primaryKey();
        foreach ($primary as $column) {
            if (!empty($this->_context['defaults'][$column])) {
                return false;
            }
        }

        return true;
    }
1004659
protected function resolveReferences()
    {
        $references = $this->config['references'] ?? [];

        if (! is_array($references) || empty($references)) {
            return;
        }

        foreach ($references as $config) {
            $this->resolveReference($config);
        }
    }
745973
public function AsSQLConstraint( ) {

	  $sql_constraint ="";

	  for ( $i = 0; $i < count( $this->m_a_fields); $i++ ) {

	      $sql_constraint .= ( $i > 0 ? ' AND ' : '' );
	      $sql_constraint .= $this->m_a_fields[ $i ] . '="' . $this->m_a_values[ $i ] . '"';

	  }

	  return $sql_constraint;

      }
1155214
protected function insert()
    {
        $aggregate = $this->aggregate;

        $attributes = $aggregate->getRawAttributes();

        $keyName = $aggregate->getEntityMap()->getKeyName();

        // Check if the primary key is defined in the attributes
        if (array_key_exists($keyName, $attributes) && $attributes[$keyName] != null) {
            $this->query->insert($attributes);
        } else {
            // Prevent inserting with a null ID
            if (array_key_exists($keyName, $attributes)) {
                unset($attributes[$keyName]);
            }

            if (isset($attributes['attributes'])) {
                unset($attributes['attributes']);
            }

            $id = $this->query->insertGetId($attributes, $keyName);

            $aggregate->setEntityAttribute($keyName, $id);
        }
    }
985887
public static function insert()
    {
        $result = null;

        switch (static::getDriver()) {
            case self::DRIVER_MYSQL:
                $result = new \pwf\components\querybuilder\adapters\MySQL\InsertBuilder();
                break;
            case self::DRIVER_PG:
                $result = new \pwf\components\querybuilder\adapters\PostgreSQL\InsertBuilder();
                break;
            default:
                throw new \Exception('Wrong query builder driver');
        }

        return $result;
    }
1164893
public function isPreparedStatementUsed()
    {
        if ($this->executeMode === self::QUERY_MODE_AUTO) {
            // Mysqli doesn't support client side prepared statement emulation
            if ($this->getAdapter()->getDriver() instanceof ZendMysqliDriver) {
                return false;
            }

            // By default, we use PDO prepared statement emulation
            return true;
        }

        if ($this->executeMode === self::QUERY_MODE_PREPARED) {
            return true;
        }

        return false;
    }