Prepares append SQL based on schema.
@param bool $primaryKey
@param bool $autoIncrement
@return string|null
160459
public function prepareSchemaAppend(bool $primaryKey, bool $autoIncrement): ?string
    {
        switch ($this->schema) {
            case TableStructure::SCHEMA_MSSQL:
                $append = $primaryKey ? 'IDENTITY PRIMARY KEY' : '';
                break;

            case TableStructure::SCHEMA_OCI:
            case TableStructure::SCHEMA_PGSQL:
                $append = $primaryKey ? 'PRIMARY KEY' : '';
                break;

            case TableStructure::SCHEMA_SQLITE:
                $append = trim(($primaryKey ? 'PRIMARY KEY ' : '') . ($autoIncrement ? 'AUTOINCREMENT' : ''));
                break;

            case TableStructure::SCHEMA_CUBRID:
            case TableStructure::SCHEMA_MYSQL:
            default:
                $append = trim(($autoIncrement ? 'AUTO_INCREMENT ' : '') . ($primaryKey ? 'PRIMARY KEY' : ''));
        }

        return empty($append) ? null : $append;
    }
1354234
private function preparePrimaryKey(array $primaryKey)
	{
		$result = array();
		foreach ($primaryKey as $key => $value) {
			$result[$key] = array(
				$this->getValueType($value) => $value
			);
		}
Debugger::barDump($result);
		return $result;
	}
454346
public function alterDatabase($table, array $primaryKey, $data) {
		//Unset query cache, otherwise it causes:
		// SQLSTATE[HY000]: General error: 17 database schema has changed
		$this->stmtCache->clearCache();

        // Create temp table to create a new structure
		$affix = '_'.substr(md5($table), 0, 6);
        $tempTable = $table . $affix;
		$this->generalEditor->createTable($tempTable, $primaryKey, $data);
        $this->alterColumns($tempTable, $primaryKey, $data);
		$this->copyTableData($table, $tempTable);

		$this->pdo->query('DROP TABLE IF EXISTS ' . $table );
		$this->pdo->query('ALTER TABLE ' . $tempTable . ' RENAME TO '. $table );

	}
70858
public function insertAndGetId(array $values, string $primaryKey = 'id')
	{
		return $this->helper->insertAndGetId($this, $values, $primaryKey);
	}
123302
public static function convertPrimaryKeyArrayToString(array $primaryKey) : string
    {
        $wrappedElements = \iRAP\CoreLibs\ArrayLib::wrapElements($primaryKey, '`');
        $csv = implode(',', $wrappedElements);
        return $csv;
    }
431602
protected function _get($primaryKey)
    {
        $this->hydrateModel($primaryKey);

        return ($this->getModel() instanceof ActiveRecordInterface) ? $this->getModel() : NULL;
    }
796066
public function getPrimaryKeyDDL(Table $table)
    {
        if ($table->hasPrimaryKey()) {

            $keys = $table->getPrimaryKey();

            //MySQL throws an 'Incorrect table definition; there can be only one auto column and it must be defined as a key'
            //if the primary key consists of multiple columns and if the first is not the autoIncrement one. So
            //this push the autoIncrement column to the first position if its not already.
            $autoIncrement = $table->getAutoIncrementPrimaryKey();
            if ($autoIncrement && $keys[0] != $autoIncrement) {
                $idx = array_search($autoIncrement, $keys);
                if ($idx !== false) {
                    unset($keys[$idx]);
                    array_unshift($keys, $autoIncrement);
                }
            }

            return 'PRIMARY KEY (' . $this->getColumnListDDL($keys) . ')';
        }
    }
328230
public function save($automatic_reload = true)
    {
        // Run Pre-saver.
        $this->preSave();

        // Run Field Fixer.
        $this->__fieldFix();

        // Calculate row to save_down
        $this->__calculateSaveDownRows();
        $primary_key_column = $this->getIDField();

        // Make an array out of the objects columns.
        $data = array();
        foreach ($this->_columns as $column) {
            // Never update the primary key. Bad bad bad. Except if we're versioned.
            if ($column != $primary_key_column ||
              $this instanceof VersionedActiveRecord ||
              $this->_force_insert
            ) {
                $data["`{$column}`"] = $this->$column;
            }
        }

        // If we already have an ID, this is an update.
        $database = DatabaseLayer::getInstance();
        if (!$this->getId() ||
          (property_exists($this, '_is_versioned') && $this->_is_versioned == true) ||
          $this->_force_insert
        ) {
            $operation = $database->insert($this->getTableName(), $this->getTableAlias());
            $this->_force_insert = false;
        } else { // Else, we're an insert.
            $operation = $database->update($this->getTableName(), $this->getTableAlias());
        }

        $operation->setData($data);

        if ($this->getId() && $primary_key_column) {
            $operation->condition($primary_key_column, $this->$primary_key_column);
            $operation->execute();
        } else { // Else, we're an insert.
            $new_id = $operation->execute($this->getClass());
            if ($primary_key_column) {
                $this->$primary_key_column = $new_id;
            }
        }

        // Expire cache.
        if (DatabaseLayer::getInstance()->useCache()) {
            $cache = DatabaseLayer::getInstance()->getCache();
            $cache->delete($this->getCacheIdentifier());
        }

        // Expire any existing copy of this object.
        SearchIndex::getInstance()->expire(get_called_class() . "/" . $this->getTableName(), $this->getId());

        if ($automatic_reload && $primary_key_column) {
            $this->reload();
        }

        // Run Post Save.
        $this->postSave();

        // Return object. Should this return true/false based on success instead?
        return $this;
    }
1003700
protected function retrieveByPrimaryKey(array $primary_key_values) {
		/** @var DynamicEntity $entity */
		$entity = parent::retrieveByPrimaryKey($primary_key_values);
		if ($entity) {
			$entity->definition = $this->definition;
		}
		return $entity;
	}
263529
public static function buildQueryUpdate( QuoteInterface $quoting, $table, array $primaryKeys, array $data, array $dataInitial, array $returning = null )
    {

        if( !count($data) === 0 ) {
            throw new NothingToDoException("Nothing to generate.");
        }

        $columnNames = array_keys( $data[0] );
        $columnNamesInitial = array_keys( $dataInitial[0] );

        // select statement
        $dataAsSql = "VALUES " . (
            $columnNamesInitial
                ? self::dataTuplesInitial( $data, $dataInitial )
                : self::dataTuples( $data )
        );

        $columns = array();
        $where = array();

        // core data
        foreach( array_keys( $data[0] ) as $key => $column ) {

            $sqlFragment = sprintf(
                '%s = "uc"."%s"',
                $quoting->quoteIdent( $column ),
                $columnNames[$key]
            );

            $columns[] = $sqlFragment;

            if( array_key_exists( $column, $primaryKeys ) ) {
                $where[$column] = '"t".'.$sqlFragment;
            }

        }

        // dataInitial
        // all dataInitial columns are primary keys, see self::extractColumnInfoFromDataTypes()
        foreach( array_keys( $dataInitial[0] ) as $key => $column ) {

            // overwrite existing where definition
            $where[$column] = sprintf(
                '"t".%s = "uc"."__initial_%s"',
                $quoting->quoteIdent( $column ),
                $columnNames[$key]
            );

            $columnNames[] = "__initial_{$column}";

        }

        if( !count($columns) ) {
            throw new NothingToDoException("Nothing to update for `{$table}`. Every column passed in the data array is a primary key column.");
        }

        return sprintf( <<<SQL
UPDATE
    %s AS "t"
SET
    %s
FROM
    (
       %s
    ) AS uc ( "%s" )
WHERE
    %s
%s;
SQL
,
            $quoting->quoteIdent( $table ),
            implode( ', ', $columns ),
            $dataAsSql,
            implode( '", "', $columnNames ),
            implode( ' AND ', $where ),
            '' #static::getReturningClause( $returning, 't' )
        );

    }
32888
final public function update(array $datas, $noApplyPrimaryKey = false) {
      if (is_array($datas) && count($datas)) {
         if (!is_array(@$datas[0])) {
            $datas = [$datas];
         }

         $this->connection();
         $this->columns();
         
         $this->last_sql = [];
         $this->placeholder_data = [];

         $where = $this->where;
         $whereTemp = str_replace('WHERE', '', $this->where);

         $rowCount = [];
         foreach ($datas as $data) {
            $placeholder = [];
            $isID = NULL;
            foreach($this->columnsData as $column) {
               if(isset($data[$column])) {
                  if($this->primaryKey==$column && $noApplyPrimaryKey===false) {
                     $isID = $data[$column];
                  } 
                  else {
                     $placeholder[$column] = "{$column}=NULL";
                     if ( gettype($data[$column])==='boolean' )
                        $placeholder[$column] = $data[$column] ? "{$column}=TRUE" : "{$column}=FALSE";
                     elseif ( $data[$column]!=='' && $data[$column]!==NULL ) {
                        $placeholder[$column] = "{$column}=?";
                        $this->placeholder_data[] = $data[$column];
                     }
                  }
               }
            }


            if($isID!==NULL) {
               $this->where = '';
               $this->where( $this->primaryKey, '=', $isID );
               if (trim($whereTemp)) {
                  $where = $this->where .' AND '. $whereTemp;
               }
               else {
                  $where = $this->where;
               }
            }

            $schema = '';
            if($this->driver=='pgsql' && $this->schema) {
               if (!preg_match('/\./', $this->table)) {
                  $schema = $this->schema ? $this->schema.'.' : '';	
               }
            }

            $placeholders = implode(",", $placeholder);
            $this->last_sql[] = $this->sql = "UPDATE {$schema}{$this->table} SET {$placeholders} {$where}";

            // $this->fetch(false);
            $this->fetch();

            $rowCount[] = $this->rowCount;

            $this->reset();

            if ( $this->tableOrig!==null ) {
               $this->table = $this->tableOrig;
            }

            $error = $this->error();
            if($error['message']) return false;
         }
         if ( count( $rowCount )===1 ) {
            $this->rowCount = $rowCount[0];
         }
         else {
            $this->rowCount = $rowCount;
         }
         
         return true;
      }
      return false;
   }
1099831
public function hasAutoIncrementPrimaryKey()
    {
        if ($this->getIdMethod() != IDMethod::NO_ID_METHOD) {
            $pks = $this->getPrimaryKey();
            foreach ($pks as $pk) {
                if ($pk->isAutoIncrement()) {
                    return true;
                }
            }
        }

        return false;
    }
154896
public function updateByPrimary($table, $primaryKeyValue, $column, $value)
    {
        $where = $this->buildWhereForArray($primaryKeyValue);
        $quotedValue = $value === null ? 'null' : $this->pdo->quote($value);

        $sql = "UPDATE
                    {$table}
                SET
                    {$column} = {$quotedValue}
                WHERE
                    {$where}";

        $this->pdo->query($sql);
    }
1130589
protected function doInsert()
    {
        /**
         * Run pre-INSERT logic
         */
        $this->beforeInsert();

        $data = $this->toArray();
        /**
         * Execute validator logic
         * Can throw ValidatorException
         */
        $this->assert($data);

        $table = $this->getTable();

        /**
         * Execute the INSERT (this may throw an exception)
         */
        $primaryKey = $table::insert($data);

        /**
         * Normalize the result to an array indexed by primary key column(s)
         */
        $tempPrimaryKey = $table->getPrimaryKey();
        $newPrimaryKey = [current($tempPrimaryKey) => $primaryKey];

        /**
         * Save the new primary key value in object. The primary key may have
         * been generated by a sequence or auto-increment mechanism, and this
         * merge should be done before the afterInsert() method is run, so the
         * new values are available for logging, etc.
         */
        $this->setFromArray($newPrimaryKey);

        /**
         * Run post-INSERT logic
         */
        $this->afterInsert();

        /**
         * Update the "clean" to reflect that the data has been inserted.
         */
        $this->clean = $this->toArray();

        return $newPrimaryKey;
    }
130471
public function setPrimaryKey(PrimaryKey $primaryKey)
    {
        foreach ($primaryKey->getColumnNames() as $columnName) {
            $this->getColumn($columnName)->setNotNull(true);
        }

        $this->primaryKey = $primaryKey;
    }
77229
protected function getNewPrimaryKey(Field $primaryKey = null, $defaultName = 'id')
    {
        $stub = $this->getStubContent('model-primary-key');

        $this->replacePrimaryKey($stub, $this->getPrimaryKeyName($primaryKey, $defaultName));

        if (!is_null($primaryKey) && !$primaryKey->isNumeric()) {
            $lines = explode("\n", $stub);
            $last = end($lines);
            $spaces = str_repeat(' ', $this->getIndent($last, 'p'));
            $stub .= PHP_EOL . $spaces . 'protected $keyType = \'string\';' . PHP_EOL;
            $stub .= $spaces . 'public $incrementing = false;' . PHP_EOL;
        }

        return $stub;
    }
679343
protected function getPrimaryKeyName(Field $primaryField = null, $primaryKey = 'id')
    {
        return !is_null($primaryField) ? $primaryField->name : $primaryKey;
    }