Insert (or update if already existing) a list of Sosa individuals
@param array $sosa_records
13446
public function insertOrUpdate($sosa_records) {
        if(!$this->is_setup) return;
        
        $treeid = $this->tree->getTreeId();
        $userid = $this->user->getUserId();
        $questionmarks_table = array();
        $values_table = array();
        
        $i = 0;
        foreach  ($sosa_records as $row) {
            $gen = Functions::getGeneration($row['sosa']);
            if($gen <= self::MAX_DB_GENERATIONS) {
                $questionmarks_table[] = 
                    '(:tree_id'.$i.', :user_id'.$i.', :sosa'.$i.', :indi_id'.$i.', :gen'.$i.', :byear'.$i.', :dyear'.$i.')';
                $values_table = array_merge(
                    $values_table, 
                    array(
                        'tree_id'.$i => $treeid, 
                        'user_id'.$i => $userid, 
                        'sosa'.$i => $row['sosa'], 
                        'indi_id'.$i => $row['indi'], 
                        'gen'.$i => Functions::getGeneration($row['sosa']),
                        'byear'.$i => $row['birth_year'],
                        'dyear'.$i => $row['death_year']
                    )
                );
            }
            $i++;
        }
        
        $sql = 'REPLACE INTO `##maj_sosa`' .
            ' (majs_gedcom_id, majs_user_id, majs_sosa, majs_i_id, majs_gen, majs_birth_year, majs_death_year)' .
            ' VALUES '. implode(',', $questionmarks_table);
        Database::prepare($sql)->execute($values_table);
    }
457758
function add_to_group($group_id, $ids)
    {
        if (!is_array($ids)) {
            $ids = explode(self::SEPARATOR, $ids);
        }

        $added  = 0;
        $exists = array();

        // get existing assignments ...
        $sql_result = $this->db->query(
            "SELECT `contact_id` FROM " . $this->db->table_name($this->db_groupmembers, true).
            " WHERE `contactgroup_id` = ?".
                " AND `contact_id` IN (".$this->db->array2list($ids, 'integer').")",
            $group_id
        );

        while ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
            $exists[] = $sql_arr['contact_id'];
        }

        // ... and remove them from the list
        $ids = array_diff($ids, $exists);

        foreach ($ids as $contact_id) {
            $this->db->query(
                "INSERT INTO " . $this->db->table_name($this->db_groupmembers, true).
                " (`contactgroup_id`, `contact_id`, `created`)".
                " VALUES (?, ?, ".$this->db->now().")",
                $group_id,
                $contact_id
            );

            if ($error = $this->db->is_error()) {
                $this->set_error(self::ERROR_SAVING, $error);
            }
            else {
                $added++;
            }
        }

        return $added;
    }
1034976
protected function flushTmpSosaTable($force = false) {
        if( count($this->tmp_sosa_table)> 0 && 
            ($force ||  count($this->tmp_sosa_table) >= self::TMP_SOSA_TABLE_LIMIT)){            
                $this->sosa_provider->insertOrUpdate($this->tmp_sosa_table);
                $this->tmp_sosa_table = array();
        }
    }
282476
protected function prepareInsert($inserts)
    {
        if ($this->isHasOneRelation($inserts)) {
            $inserts = array_dot($inserts);
        }

        foreach ($inserts as $column => $value) {
            if (is_null($field = $this->getFieldByColumn($column))) {
                unset($inserts[$column]);

                continue;
            }

            $inserts[$column] = $field->prepare($value);
        }

        $prepared = [];

        foreach ($inserts as $key => $value) {
            array_set($prepared, $key, $value);
        }

        return $prepared;
    }
1150871
public function write($sessid, $sessdata)
    {
        $this->_cache->set(
            $sessid,
            $sessdata,
            array('expiry' => $this->_sessionExpiryInterval)
        );
        $sql  = 'INSERT INTO tbl_sessions (SESSION_ID, SESSION_DATA) 
            values (:SESSID, :SESSDATA) ON DUPLICATE KEY 
            UPDATE SESSION_DATA=:SDATA, LAST_ACCESSED=NOW()';
        $stmt = $this->_db->prepare($sql);
        $stmt->execute(
            array(
             ':SESSID'   => $sessid,
             ':SESSDATA' => $sessdata,
             ':SDATA'    => $sessdata,
            )
        );

        return true;

    }
407633
public static function makeInsertQuery(string $p_table, array $p_fields)
    {
        $fields = '';
        $values = '';
        foreach ($p_fields as $field => $value) {
            $local = str_replace(':', '', $field);
            if ($fields == '') {
                $fields = $local;
                $values = ':' . $local;
            } else {
                $fields = $fields . ', ' . $local;
                $values = $values . ', :' . $local;
            }
        }
        $sql    = 'INSERT INTO ' . $p_table . ' (' . $fields . ') VALUES (' . $values . ')';
        return $sql;
    }
664172
public function upsert($table, $insertFieldValues, $updateFieldValues = [], $primaryKey = null)
    {
        if (!$primaryKey) {
            $primaryKey = (string)key($insertFieldValues);
        }

        if (!$updateFieldValues) {
            $updateFieldValues = $insertFieldValues;
        }

        $fields = array_keys($insertFieldValues);

        $bind = $insertFieldValues;
        $updates = [];
        foreach ($updateFieldValues as $k => $v) {
            $field = is_string($k) ? $k : $v;
            if ($primaryKey === $field) {
                continue;
            }

            if (is_int($k)) {
                $updates[] = "[$field]=:{$field}_dku";
                $bind["{$field}_dku"] = $insertFieldValues[$field];
            } elseif ($v instanceof AssignmentInterface) {
                $v->setFieldName($k);
                $updates[] = $v->getSql();
                /** @noinspection SlowArrayOperationsInLoopInspection */
                $bind = array_merge($bind, $v->getBind());
            } else {
                $updates[] = $v;
            }
        }

        $insertFieldsSql = '[' . implode('],[', $fields) . ']';
        $insertValuesSql = ':' . implode(',:', $fields);

        $updateFieldsSql = implode(',', $updates);

        $sql = 'INSERT' . " INTO {$this->_escapeIdentifier($table)}($insertFieldsSql) VALUES($insertValuesSql) ON DUPLICATE KEY UPDATE $updateFieldsSql";

        return $this->execute('insert', $sql, $bind);
    }
683810
protected function AddInsertFields(&$Fields) {
      $this->DefineSchema();
      if ($this->Schema->FieldExists($this->Name, $this->DateInserted)) {
         if (!isset($Fields[$this->DateInserted]))
            $Fields[$this->DateInserted] = Gdn_Format::ToDateTime();
      }

      $Session = Gdn::Session();
      if ($Session->UserID > 0 && $this->Schema->FieldExists($this->Name, $this->InsertUserID))
         if (!isset($Fields[$this->InsertUserID]))
            $Fields[$this->InsertUserID] = $Session->UserID;

      if ($this->Schema->FieldExists($this->Name, 'InsertIPAddress') && !isset($Fields['InsertIPAddress'])) {
         $Fields['InsertIPAddress'] = Gdn::Request()->IpAddress();
      }
   }
459436
public function insert(Google_Service_Tasks_TaskList $postBody, $optParams = array())
  {
    $params = array('postBody' => $postBody);
    $params = array_merge($params, $optParams);
    return $this->call('insert', array($params), "Google_Service_Tasks_TaskList");
  }
618423
public function bulkInsert($table, $records)
    {
        if (!$records) {
            throw new InvalidArgumentException(['Unable to insert into :table table without data', 'table' => $table]);
        }

        $fields = array_keys($records[0]);
        $insertedFields = '[' . implode('],[', $fields) . ']';

        $pdo = $this->_getPdo();

        $rows = [];
        foreach ($records as $record) {
            $row = [];
            foreach ($record as $field => $value) {
                $row[] = is_string($value) ? $pdo->quote($value) : $value;
            }

            $rows[] = '(' . implode(',', $row) . ')';
        }

        $sql = 'INSERT' . ' INTO ' . $this->_escapeIdentifier($table) . " ($insertedFields) VALUES " . implode(', ', $rows);

        return $this->execute($sql);
    }
25078
protected function appendPsForUniqueClauseTo(&$sb, array &$params)
    {
        $bindParams = [];
        $index = count($params); // to avoid counting the number of parameters for each element in the array
        $values = ($this->value instanceof \Traversable) ? iterator_to_array($this->value) : (array) $this->value;
        foreach ($values as $value) {
            $params[] = ['table' => $this->realtable, 'column' => $this->column, 'value' => $value];
            $index++; // increment this first to correct for wanting bind params to start with :p1
            $bindParams[] = ':p' . $index;
        }
        if (count($bindParams)) {
            $field = ($this->table === null) ? $this->column : $this->table . '.' . $this->column;
            $sb .= $field . $this->comparison . '(' . implode(',', $bindParams) . ')';
        } else {
            $sb .= (Criteria::IN === $this->comparison) ? '1<>1' : '1=1';
        }
    }
917199
public function addFailedRecords(SS_List $records, $message)
    {
        foreach ($records as $record) {
            $this->failedRecords[] = array('id' => $record->ID, 'class' => $record->ClassName, 'message' => $message);
        }
        return $this;
    }
691925
protected function insertRecordSets(array &$sets)
    {
        $timestamp = $this->unixTimestamp === true ? strtotime(date('Y-m-d H:i:s')) : date('Y-m-d H:i:s');

        if(is_null($this->recordUser)) {
            if(globals()->offsetExists('account')) {
                $this->setRecordUser(globals()->account->id);
            }
        }

        if ( ! isset($sets[ 'record_status' ])) {
            $sets[ 'record_status' ] = $this->recordStatus;
        }

        if (empty($this->primaryKeys)) {
            $primaryKey = isset($this->primaryKey) ? $this->primaryKey : 'id';

            if (isset($sets[ $primaryKey ])) {
                if (empty($sets[ $primaryKey ])) {
                    unset($sets[ $primaryKey ]);
                }
            }

            if (empty($sets[ $primaryKey ])) {
                if ( ! isset($sets[ 'record_create_user' ])) {
                    $sets[ 'record_create_user' ] = $this->recordUser;
                }

                if ( ! isset($sets[ 'record_create_timestamp' ])) {
                    $sets[ 'record_create_timestamp' ] = $timestamp;
                } elseif ($this->unixTimestamp) {
                    $sets[ 'record_create_timestamp' ] = strtotime($sets[ 'record_create_timestamp' ]);
                }
            }
        } else {
            foreach ($this->primaryKeys as $primaryKey) {
                if (empty($sets[ $primaryKey ])) {
                    if ( ! isset($sets[ 'record_create_user' ])) {
                        $sets[ 'record_create_user' ] = $this->recordUser;
                    }

                    if ( ! isset($sets[ 'record_create_timestamp' ])) {
                        $sets[ 'record_create_timestamp' ] = $timestamp;
                    } elseif ($this->unixTimestamp) {
                        $sets[ 'record_create_timestamp' ] = strtotime($sets[ 'record_create_timestamp' ]);
                    }
                }
            }
        }

        if ( ! isset($sets[ 'record_update_user' ])) {
            $sets[ 'record_update_user' ] = $this->recordUser;
        }

        if ( ! isset($sets[ 'record_update_timestamp' ])) {
            $sets[ 'record_update_timestamp' ] = $timestamp;
        } elseif ($this->unixTimestamp) {
            $sets[ 'record_update_timestamp' ] = strtotime($sets[ 'record_update_timestamp' ]);
        }

        if ( ! isset($sets[ 'record_ordering' ]) && $this->recordOrdering === true) {
            $sets[ 'record_ordering' ] = $this->getRecordOrdering();
        }
    }
876562
protected function insertPivotRecords(
        Connection $connection,
        array $pivotTables,
        array $pivotRecords,
        array $foreignKeys,
        array $insertedParentPKs
    ) {
        if (!$pivotRecords) {
            return;
        }

        // $pivotRecords is structured like this, with one base level element per parent model:
        // [
        //     'App\Role' => [$row, $row, $row], 'App\Club' => [$row, $row, $row],
        //     'App\Role' => [$row, $row, $row], 'App\Club' => [$row, $row, $row],
        // ]

        // The IDs of the parent model weren't known when preparing the bulk insert,
        // so we'll set the values of the foreign key referring to the parent now.
        $idKey = 0;

        foreach ($pivotRecords as &$recordsOfOneParent) {
            foreach ($recordsOfOneParent as $relatedClass => &$recordsOfOneRelation) {
                foreach ($recordsOfOneRelation as &$record) {
                    $record[$foreignKeys[$relatedClass]] = $insertedParentPKs[$idKey];
                }
            }

            $idKey++;
        }
        unset($recordsOfOneParent, $recordsOfOneRelation, $record);

        foreach (array_keys($pivotRecords[0]) as $relatedClass) {
            $recordsOfCurrentRelation = array_column($pivotRecords, $relatedClass);

            // We'll flatten the records since they're grouped by parent model.
            $recordsOfCurrentRelation = Arr::flatten($recordsOfCurrentRelation, 1);

            foreach (array_chunk($recordsOfCurrentRelation, 500) as $chunk) {
                $connection->table($pivotTables[$relatedClass])->insert($chunk);
            }
        }
    }
1252052
protected function _insert($postdata, $no_processing = false, $no_processing_fields = array())
    {
        if (!$postdata)
        {
            self::error('$postdata array is empty');
        }
        $set = array();
        $db = Fruit_db::get_instance($this->connection);
        $fields = array_merge($this->fields, $this->hidden_fields);
        $fk_queries = array();
        foreach ($postdata as $key => $val)
        {
            if (isset($fields[$key]) && !isset($this->locked_fields[$key]) && !isset($this->custom_fields[$key]))
            {
                if (isset($this->field_type[$key]))
                {
                    switch ($this->field_type[$key])
                    {
                        case 'password':
                            if (trim($val) == '')
                            {
                                continue 2;
                            }
                            elseif ($this->defaults[$key])
                            {
                                $val = hash($this->defaults[$key], $val);
                            }
                            break;
                        case 'fk_relation': //
                            continue 2;
                            break;
                    }
                }

                $set[$fields[$key]['table']]['`' . $fields[$key]['field'] . '`'] = $this->prepare_query_field($val, $key, 'create');

                /*if (is_array($val))
                {
                $set[$fields[$key]['table']]['`' . $fields[$key]['field'] . '`'] = $db->escape(implode(',', $val), false, $this->
                field_type[$key], $this->field_null[$key], isset($this->bit_field[$key]));
                }
                elseif (isset($this->point_field[$key]))
                {
                $set[$fields[$key]['table']]['`' . $fields[$key]['field'] . '`'] = 'Point(' . $db->escape($val, true, 'point', $this->
                field_null[$key], isset($this->bit_field[$key])) . ')';
                }
                elseif (isset($this->float_field[$key]))
                {

                }
                elseif (isset($this->float_field[$key]))
                {

                }
                else
                $set[$fields[$key]['table']]['`' . $fields[$key]['field'] . '`'] = ((isset($this->no_quotes[$key]) && isset($this->
                pass_var['create'][$key])) ? $db->escape($val, true) : $db->escape($val, false, $this->field_type[$key], $this->
                field_null[$key], isset($this->bit_field[$key])));*/
            }
            elseif ($no_processing)
            {
                /*$set[$no_processing_fields[$key]['table']]['`' . $no_processing_fields[$key]['field'] . '`'] = ((isset($this->no_quotes[$key]) &&
                isset($this->pass_var['create'][$key])) ? $db->escape($val, true) : $db->escape($val, false, $this->field_type[$key], $this->
                field_null[$key], isset($this->bit_field[$key])));*/
                $set[$no_processing_fields[$key]['table']]['`' . $no_processing_fields[$key]['field'] . '`'] = $this->
                    prepare_query_field($val, $key, 'create', true);
            }
        }
        //$keys = array_keys($set[$this->table]);
        if (!$set)
        {
            self::error('Nothing to insert');
        }
        if (!$this->primary_ai && !isset($postdata[$this->table . '.' . $this->primary_key]))
        {
            self::error('Can\'t insert a row. No primary value.');
        }
        if (!$this->demo_mode)
            $db->query('INSERT INTO `' . $this->table . '` (' . implode(',', array_keys($set[$this->table])) . ') VALUES (' .
                implode(',', $set[$this->table]) . ')');
        if ($this->primary_ai)
        {
            $ins_id = $db->insert_id();
            $set[$this->table]['`' . $this->primary_key . '`'] = $ins_id;
            $postdata[$this->table . '.' . $this->primary_key] = $ins_id;
        }
        else
        {
            $ins_id = $postdata[$this->table . '.' . $this->primary_key];
        }
        if ($this->join)
        {
            foreach ($this->join as $alias => $param)
            {
                $set[$alias]['`' . $param['join_field'] . '`'] = $set[$param['table']]['`' . $param['field'] . '`'];
                if (!$this->demo_mode && !$param['not_insert'])
                {
                    $db->query("INSERT INTO `{$param['join_table']}` (" . implode(',', array_keys($set[$alias])) . ") VALUES (" . implode(',',
                        $set[$alias]) . ")");
                }
            }
        }

        if ($this->fk_relation)
        {
            foreach ($this->fk_relation as $fk)
            {
                $field = $fk['table'] . '.' . $fk['field'];
                if (array_key_exists($fk['alias'], $postdata) && array_key_exists($field, $postdata))
                {
                    $in_val = $db->escape($postdata[$field], false, $this->field_type[$field], $this->field_null[$field], isset($this->
                        bit_field[$field]));
                    $db->query('DELETE FROM `' . $fk['fk_table'] . '` WHERE `' . $fk['in_fk_field'] . '` = ' . $in_val);
                    $fkids = $this->parse_comma_separated($postdata[$fk['alias']]);
                    if ($fkids)
                    {
                        $ins_vals = array();
                        $ins_keys = array();
                        $ins_add = array();
                        if ($fk['add_data'])
                        {
                            foreach ($fk['add_data'] as $add_key => $add_val)
                            {
                                $ins_keys[] = '`' . $add_key . '`';
                                $ins_add[] = $db->escape($add_val);
                            }
                        }
                        $ins_add[] = /*$db->escape(*/ $in_val /*)*/;
                        $ins_keys[] = '`' . $fk['in_fk_field'] . '`';
                        $ins_keys[] = '`' . $fk['out_fk_field'] . '`';
                        foreach ($fkids as $fkid)
                        {
                            $ins_vals[] = '(' . implode(',', $ins_add) . ',' . $db->escape($fkid) . ')';
                        }
                        $db->query('INSERT INTO `' . $fk['fk_table'] . '` (' . implode(',', $ins_keys) . ') VALUES ' . implode(',', $ins_vals));
                    }
                }
            }
        }

        unset($set, $postdata);
        return $ins_id;
    }
1196571
public function addRows(array $rows): void
    {
        if (empty($rows)) {
            throw new DatabaseException('Can not perform insert with empty rows.');
        }

        // Collect column names and add to statement:
        $cols = array_keys(reset($rows));
        foreach ($cols as $i => $col) {
            $cols[$i] = $this->quoteName($col);
        }
        $pattern = " (%s) VALUES" . PHP_EOL;
        $this->statement .= sprintf($pattern, implode(',', $cols));

        // Add values for each row to insert statement:
        $rowValues = [];
        foreach ($rows as $row) {
            $placeholders = $this->bindRowValues($row);
            array_push($rowValues, sprintf('(%s)', implode(',', $placeholders)));
        }
        $this->statement .= implode(',', $rowValues);
    }
462385
public function buildRecords($tableName, array $records)
    {
        $insertedRecords = array();
        $this->tables[$tableName] = $tableName;

        foreach ($records as $recordName => $recordValues) {
            array_walk($recordValues, function (&$value) use ($recordValues) {
                if (is_callable($value)) {
                    $value = call_user_func($value, $recordValues);
                }
            });

            $recordValues = $this->setForeignKeys($recordValues);

            list($table, $label) = $this->parseRecordLabel(
                $recordName[0] === "."
                ? $tableName . $recordName[0]
                : $recordName
            );

            if (!is_int($recordName)) {
                $recordValues['id'] = $this->generateKey($label, $table);
            }

            $cols = array();
            foreach (array_keys($recordValues) as $col) {
                $cols[] = $this->quoteIdentifier($col);
            }
            $fields = implode(', ', $cols);
            $values = array_values($recordValues);
            $placeholders = rtrim(str_repeat('?, ', count($recordValues)), ', ');
            $sql = "INSERT INTO " . $this->quoteIdentifier($tableName)
                . " ($fields) VALUES ($placeholders)";

            $sth = $this->db->prepare($sql);
            $sth->execute($values);

            $insertedRecords[$label] = (object) $recordValues;
        }

        return $insertedRecords;
    }