/*
Insert a row, or update it if there is a duplicate key clash

$data array A structured array to be inserted into the KVS.
The array must be completely key-value at its top level.  Below
that, anything that can be serialized into JSON is allowed.
963215
public function insertOrUpdate($data) {
        $map = $this->extractMap($data);
        $sql = "INSERT INTO $this->KVS_TABLE ($this->KVS_FK_NAME, $this->KVS_SK_NAME,
            uk1, sk1, tk1, co1, co2, json_body, created_at)
            VALUES (:foreign_key, :uk1, :sk1, :tk1, :co1, :co2, :json_body, $this->NOW)
            ON DUPLICATE KEY UPDATE
            $this->KVS_FK_NAME=:foreign_key, $this->KVS_SK_NAME=:secondary_key,
            sk1=:sk1, tk1=:tk1,
            co1=:co1, co2=:co2, json_body=:json_body, updated_at=$this->NOW ";
        $map[':foreign_key'] = $this->KVS_FK;
        $map[':secondary_key'] = $this->KVS_SK;
        $map[':json_body'] = json_encode($data);
        $stmt = $this->PDOX->queryDie($sql, $map);

        if ( $stmt->success) return($this->PDOX->lastInsertId());
        return false;
    }
1029173
public static function array_insert(&$array, $item, $position) {
        if ($position == 0) {
            /* Prepend the item */
            array_unshift($array, $item);
        } else {
            if (count($array) == $position) {
                $array[] = $item;
            } else {
                array_splice($array, $position, 0, array($item));
            }
        }
    }
1328770
protected function _rawInsert($m, $row)
    {
        $m->reload_after_save = false;
        $m->unload();

        if (!is_array($row)) {
            $row = [$m->title_field => $row];
        }

        // Find any row values that do not correspond to fields, and they may correspond to
        // references instead
        $refs = [];
        foreach ($row as $key => $value) {

            // no field exists
            if ($field = $this->hasField($key)) {

                // In certain cases, there may be exceptions when providing field values
                if ($field instanceof Field_SQL_Expression && $field->concat && is_string($value) && $field->aggregate_relation) {
                    $refs[$field->aggregate_relation->link] = explode($field->concat, $value);
                    unset($row[$key]);
                }
            }

            // and we only support array values
            if (!is_array($value)) {
                continue;
            }

            // and reference must exist with same name
            if (!$this->hasRef($key)) {
                continue;
            }

            // Then we move value for later
            $refs[$key] = $value;
            unset($row[$key]);
        }

        // save data fields
        $m->save($row);

        // store id value
        if ($this->id_field) {
            $m->data[$m->id_field] = $m->id;
        }

        // if there was referenced data, then import it
        foreach ($refs as $key => $value) {
            $m->ref($key)->import($value);
        }
    }
195062
function pushChildRows(row, level) {
    var keyValue = row.keyValue;
    var oThis = this;
    var nowLevel = parseInt(level) + 1;
    var hasChild = false;
    var childRowArray = new Array();
    var childRowIndexArray = new Array();
    var spliceHasParentRows = new Array();
    $.each(this.hasParentRows, function (i) {
        if (this && this.parentKeyValue == keyValue) {
            hasChild = true;
            this.level = nowLevel;
            oThis.rows.push(this);
            childRowArray.push(this);
            var index = parseInt(oThis.rows.length - 1);
            childRowIndexArray.push(index);
            spliceHasParentRows.push(this);
            oThis.pushChildRows(this, nowLevel);
        }
    });
    $.each(spliceHasParentRows, function () {
        var index = oThis.hasParentRows.indexOf(this);
        oThis.hasParentRows.splice(index, 1);
    });
    row.hasChild = hasChild;
    row.childRow = childRowArray;
    row.childRowIndex = childRowIndexArray;
}
1054904
public function add(array $data, $cols = null) {
		if (is_array($cols)) {
			//筛选$data列
			foreach ($data as $k => $v) {
				if (!in_array($k, $cols, true)) {
					unset($data[$k]);
				}
			}
		}
		$query = $this->newInsert()->map($data);
		$result = $this->execute($query);
		if (!empty($this->_primary_key)) {
			return intval($result['_insert_id']);
		} else {
			return null;
		}
	}
1042864
function insert(argh, key, value, option) {
  //
  // Automatic value conversion. This makes sure we store the correct "type"
  //
  if ('string' === typeof value && !isNaN(+value)) value = +value;
  if (value === 'true' || value === 'false') value = value === 'true';

  var single = option.charAt(1) !== '-'
    , properties = key.split('.')
    , position = argh;

  if (single && key.length > 1) return key.split('').forEach(function short(char) {
    insert(argh, char, value, option);
  });

  //
  // We don't have any deeply nested properties, so we should just bail out
  // early enough so we don't have to do any processing
  //
  if (!properties.length) return argh[key] = value;

  while (properties.length) {
    var property = properties.shift();

    if (properties.length) {
      if ('object' !== typeof position[property] && !Array.isArray(position[property])) {
        position[property] = Object.create(null);
      }
    } else {
      position[property] = value;
    }

    position = position[property];
  }
}
312801
public function insert(KDatabaseRowInterface $row)
    {
        // Create query object.
        $query = $this->getObject('lib:database.query.insert')
            ->table($this->getBase());

        //Create commandchain context
        $context = $this->getContext();
        $context->table     = $this->getBase();
        $context->data      = $row;
        $context->query     = $query;
        $context->affected = false;

        if ($this->invokeCommand('before.insert', $context) !== false)
        {
            // Filter the data and remove unwanted columns.
            $data = $this->filter($context->data->getProperties());
            $context->query->values($this->mapColumns($data));

            // Execute the insert query.
            $context->affected = $this->getAdapter()->insert($context->query);

            // Set the status and data before calling the command chain
            if ($context->affected !== false)
            {
                if ($context->affected)
                {
                    if(($column = $this->getIdentityColumn()) && $this->getColumn($this->mapColumns($column, true), true)->autoinc) {
                        $data[$this->getIdentityColumn()] = $this->getAdapter()->getInsertId();
                    }

                    $context->data->setProperties($this->mapColumns($data, true))->setStatus(KDatabase::STATUS_CREATED);
                }
                else $context->data->setStatus(KDatabase::STATUS_FAILED);
            }

            $this->invokeCommand('after.insert', $context);
        }

        return $context->affected;
    }
649003
def insert(self, key, value, data={}):
        
        if value < self.min_value or value > self.max_value:
            raise BoundsError('item value out of bounds')

        item = self.Item(key, value, data)
        index = self.get_bin_index(value)

        self.bins[index].append(item)
1013382
public function insert(array $data) : bool {
    $this->query_builder->resetProperties();
    $this->query_builder->setMode('insert');

    $columns = array_keys($data);

    $this->query_builder->setColumns($columns);
    $this->query_builder->setValues($columns);

    try {
      $stmt = parent::prepare($this->query_builder->getQuery());

      return $stmt->execute($data);
    } catch (PDOException $e) {
      $this->pdo_exception = $e;

      return false;
    }
  }
1242280
public function addValues(array $values)
    {
        // Check if this is a multi-dimensional array
        $isMultiDimensional = 0 == count($values) || (isset($values[0]) && is_array($values[0]));

        if ($isMultiDimensional) {
            $this->insertRows = array_merge($this->insertRows, $values);
        } else {
            // If a single row is provided then it is added
            // to the last row, or a new row if there are none.
            // This is done to maintain BC
            if (count($this->insertRows) > 0) {
                $k = count($this->insertRows) - 1;
                $this->insertRows[$k] = array_replace($this->insertRows[$k], $values);
            } else {
                $this->insertRows = [$values];
            }
        }

        return $this;
    }
1317633
function insert() {
    var insertValues = this.single.insert || [];
    var sql = 'insert into ' + this.tableName + ' ';

    if (Array.isArray(insertValues)) {
      if (insertValues.length === 0) {
        return '';
      }
    } else if (typeof insertValues === 'object' && isEmpty(insertValues)) {
      return sql + this._emptyInsertValue;
    }

    var insertData = this._prepInsert(insertValues);
    this.__insertValues = insertData.values;
    if (typeof insertData === 'string') {
      sql += insertData;
    } else {
      if (insertData.columns.length) {
        sql += '(' + this.formatter.columnize(insertData.columns);
        sql += ') values (';
        sql += this.formatter.parameterize(insertData.columns);
        sql += ')';
      } else if (insertValues.length === 1 && insertValues[0]) {
        sql += this._emptyInsertValue;
      } else {
        sql = '';
      }
    }
    var out = {
      sql: sql,
      bindings: insertData.values
    };
    if (out.sql !== '') {
      out.returning = this.single.returning;
    }
    return out;
  }
275727
private function add_index_row($mailbox, $sort_field,
        $data, $mbox_data = array(), $exists = false, $modseq = null)
    {
        $data = array(
            $this->db->encode($data, true),
            $sort_field,
            (int) $this->skip_deleted,
            (int) $mbox_data['UIDVALIDITY'],
            (int) $mbox_data['UIDNEXT'],
            $modseq ? $modseq : $mbox_data['HIGHESTMODSEQ'],
        );

        $data    = implode('@', $data);
        $expires = $this->ttl ? $this->db->now($this->ttl) : 'NULL';

        if ($exists) {
            $res = $this->db->query(
                "UPDATE {$this->index_table}"
                ." SET `data` = ?, `valid` = 1, `expires` = $expires"
                ." WHERE `user_id` = ?"
                    ." AND `mailbox` = ?",
                $data, $this->userid, $mailbox);

            if ($this->db->affected_rows($res)) {
                return;
            }
        }

        $this->db->set_option('ignore_key_errors', true);

        $res = $this->db->query(
            "INSERT INTO {$this->index_table}"
            ." (`user_id`, `mailbox`, `valid`, `expires`, `data`)"
            ." VALUES (?, ?, 1, $expires, ?)",
            $this->userid, $mailbox, $data);

        // race-condition, insert failed so try update (#1489146)
        // thanks to ignore_key_errors "duplicate row" errors will be ignored
        if (!$exists && !$res && !$this->db->is_error($res)) {
            $res = $this->db->query(
                "UPDATE {$this->index_table}"
                ." SET `data` = ?, `valid` = 1, `expires` = $expires"
                ." WHERE `user_id` = ?"
                    ." AND `mailbox` = ?",
                $data, $this->userid, $mailbox);
        }

        $this->db->set_option('ignore_key_errors', false);
    }
110412
public function insert($params)
    {
        if (is_array($params)) {
            $count_rows = count($params['columns']);
            $increment = 1;
            foreach ($params['columns'] as $keys => $value) {
                for ($i = 1; $i <= $count_rows; $i++) {
                    $data[$keys] = $value;
                }
            }
            foreach ($data as $keys => $values) {
                if ($increment == $count_rows) {
                    $columns[] = "{$keys} = '{$values}'";
                } else {
                    $columns[] = "{$keys} = '{$values}'";
                }
                $increment++;
            }
            $columns = implode(' , ', $columns);
            $query = "INSERT INTO `{$params['table']}`SET {$columns}";
            if (isset($params['debug']) and strtolower($params['debug']) === 'on') {
                var_dump($query);
            }

            return $query;
        } else {
            return false;
        }
    }
1046695
function insertSiblingData($FieldValueArray=array(),$ConditionString=null,$Rest=null)
    {
		$this->lock();
    	//Find the Sibling
        $Arguments=func_get_args();
        array_shift($Arguments); //first argument, the array
        array_shift($Arguments);
        if ($ConditionString) $ConditionString="WHERE $ConditionString";
        $Query="SELECT {$this->right()} AS `Right`".
        	" FROM {$this->table()} $ConditionString";

        array_unshift($Arguments,$Query);
        $Sibl=call_user_func_array("Jf::sql",$Arguments);

        $Sibl=$Sibl[0];
        if ($Sibl==null)
        {
            $Sibl["Left"]=$Sibl["Right"]=0;
        }
        Jf::sql("UPDATE {$this->table()} SET {$this->right()} = {$this->right()} + 2 WHERE {$this->right()} > ?",$Sibl["Right"]);
        Jf::sql("UPDATE {$this->table()} SET {$this->left()} = {$this->left()} + 2 WHERE {$this->left()} > ?",$Sibl["Right"]);

        $FieldsString=$ValuesString="";
        $Values=array();
        if ($FieldValueArray)
        foreach($FieldValueArray as $k=>$v)
        {
            $FieldsString.=",";
            $FieldsString.="`".$k."`";
            $ValuesString.=",?";
            $Values[]=$v;
        }

        $Query= "INSERT INTO {$this->table()} ({$this->left()},{$this->right()} $FieldsString) ".
        	"VALUES(?,? $ValuesString)";
        array_unshift($Values,$Sibl["Right"]+2);
        array_unshift($Values,$Sibl["Right"]+1);
        array_unshift($Values,$Query);

        $Res=call_user_func_array("Jf::sql",$Values);
		$this->unlock();
        return $Res;
    }
620325
public function inserts(array $kvs): int
    {
        $params = [];
        foreach ($kvs as $key => $val) {
            $params[] = $val; //分数(值)
            $params[] = $key; //元素(键)
        }
        return $this->handle->zAdd($this->name, ...$params);
    }
1033667
function insert($data, $priority = 0)
    {
        if (! is_array($priority) )
            $priority = [$priority, $this->__sdec--];

        $this->__mapped_items[] = [
            'priority' => $priority,
            'data'     => $data
        ];

        parent::insert($data, $priority);
    }
817054
function putRow() {
    var putParams = {
        tableName: tableName,
        condition: new TableStore.Condition(TableStore.RowExistenceExpectation.IGNORE, null),
        primaryKey: [
            { pk1: 'pk1' },
            { pk2: TableStore.PK_AUTO_INCR }
        ],
        attributeColumns: [
            { 'col1': 'col1val' }
        ],
        returnContent: { returnType: TableStore.ReturnType.Primarykey }
    };

    client.putRow(putParams, function (err, data) {
        if (err) {
            console.log('error:', err);
            return;
        }

        console.log('put row success,autoIncrement pk value:' + JSON.stringify(data.row.primaryKey));
    });

}