Insert or update `data` as a row into specified db table
484229
def db(context, data):
    """"""
    table = context.params.get("table", context.crawler.name)
    params = context.params
    params["table"] = table
    _recursive_upsert(context, params, data)
175859
def update(self, table_name, where_slice, new_values):
        
        new_values = quote_param(new_values)

        where_clause = SQL_AND.join([
            quote_column(k) + "=" + quote_value(v) if v != None else quote_column(k) + SQL_IS_NULL
            for k, v in where_slice.items()
        ])

        command = (
            "UPDATE " + quote_column(table_name) + "\n" +
            "SET " +
            sql_list([quote_column(k) + "=" + v for k, v in new_values.items()]) +
            SQL_WHERE +
            where_clause
        )
        self.execute(command, {})
1089766
def insert_statement(table, columns, values):
    """"""
    if not all(isinstance(r, (list, set, tuple)) for r in values):
        values = [[r] for r in values]
    rows = []
    for row in values:
        new_row = []
        for col in row:
            if col is None:
                new_col = 'NULL'
            elif isinstance(col, (int, float, Decimal)):
                new_col = str(MySQLConverterBase().to_mysql(col))
            else:
                string = str(MySQLConverterBase().to_mysql(col))
                if "'" in string:
                    new_col = '"' + string + '"'
                else:
                    new_col = "'" + string + "'"
            new_row.append(new_col)
        rows.append(', '.join(new_row))
    vals = '(' + '),\n\t('.join(rows) + ')'
    statement = "INSERT INTO\n\t{0} ({1}) \nVALUES\n\t{2}".format(wrap(table), cols_str(columns), vals)
    return statement
887087
def populate_from_staging(self, staging_table, from_column_list, output_table):
        
        self.sql_text += 'INSERT INTO ' + output_table + ' (\n'
        for c in self.col_list:
            if c != '':
                self.sql_text += '    ' + c + ',\n'
        self.sql_text += '    ' + self.date_updated_col + ') (\n'
        self.sql_text += '    SELECT \n'
        for c in from_column_list:
            if c != '':
                self.sql_text += '        ' + c + ',\n'
        self.sql_text += '        SYSDATE \n    FROM ' + staging_table
        self.sql_text += '\n);\n'
522363
def insert(self, table, columns, values, execute=True):
        """"""
        # TODO: Cant accept lists?
        # Concatenate statement
        cols, vals = get_col_val_str(columns)
        statement = "INSERT INTO {0} ({1}) VALUES ({2})".format(wrap(table), cols, vals)

        # Execute statement
        if execute:
            self._cursor.execute(statement, values)
            self._commit()
            self._printer('\tMySQL row successfully inserted into {0}'.format(table))

        # Only return statement
        else:
            return statement
709473
function mkInsert(table, obj) {
  const ks = Object.keys(obj).map(x => `\`${x}\``);
  const vs = Object.values(obj).map(toMysqlObj);

  return `INSERT INTO \`${table}\`(${ks}) VALUES(${vs})`;
}
1329529
def build_insert(table_name, attributes):
    
    sql = "INSERT INTO %s" %(table_name)
    column_str = u""
    value_str = u""
    for index, (key, value) in enumerate(attributes.items()):
        if index > 0:
            column_str += u","
            value_str += u","
        column_str += key
        value_str += value_to_sql_str(value)
    sql = sql + u"(%s) VALUES(%s)" %(column_str, value_str)
    return sql
509458
def _insert(self, name, value, timestamp, intervals, **kwargs):
    '''
    
    '''
    if 'pipeline' in kwargs:
      pipe = kwargs.get('pipeline')
    else:
      pipe = self._client.pipeline(transaction=False)

    for interval,config in self._intervals.iteritems():
      timestamps = self._normalize_timestamps(timestamp, intervals, config)
      for tstamp in timestamps:
        self._insert_data(name, value, tstamp, interval, config, pipe,
          ttl_batch=kwargs.get('ttl_batch'))

    if 'pipeline' not in kwargs:
      pipe.execute()
627707
def insert(self, row):
        
        data = self._convert_value(row)
        self._service.InsertRow(data, self._ss.id, self.id)
301736
def update(self, rows):
        
        if len(rows) == 0:
            return

        sql, sql_args = self.get_update_sql(rows)

        # get the cursor to execute the query
        cursor = self.get_cursor()

        # execute the query
        cursor.execute(sql, sql_args)
1053595
async def execute_insert(
        self, sql: str, parameters: Iterable[Any] = None
    ) -> Optional[sqlite3.Row]:
        """"""
        if parameters is None:
            parameters = []
        return await self._execute(self._execute_insert, sql, parameters)
1037083
def insert(self, row):
        
        self._check_dropped()
        res = self.engine.execute(self.table.insert(row))
        if len(res.inserted_primary_key) > 0:
            return res.inserted_primary_key[0]
381996
function insert( $rows, $method = null ) {

        return $this->db->insert( $this->table, $rows, $method );

    }
322598
def upsert(db, table, key_cols, update_dict):
    
    with db:
        cur = db.cursor()
        cur.execute(
            'UPDATE {} SET {} WHERE {}'.format(
                table,
                ','.join(_sqlpformat(col) for col in update_dict.keys()),
                ' AND '.join(_sqlpformat(col) for col in key_cols),
            ),
            update_dict,
        )
        if db.changes() == 0:
            keys, values = zip(*update_dict.items())
            cur.execute(
                'INSERT INTO {} ({}) VALUES ({})'.format(
                    table,
                    ','.join(keys),
                    ','.join('?' for _ in values)),
                values)
1122858
def load_table(self, table, rows, colnames=None, limit=None):
        

        conn = self.engine.raw_connection()
        cur = conn.cursor()

        colnames = colnames or next(rows)

        cmd = 'INSERT INTO {table} ({colnames}) VALUES ({placeholders})'.format(
            table=self.tables[table],
            colnames=', '.join(colnames),
            placeholders=', '.join([self.placeholder] * len(colnames)))

        cur.executemany(cmd, itertools.islice(rows, limit))
        conn.commit()
301274
def insert_object_into_db_pk_unknown(self,
                                         obj: Any,
                                         table: str,
                                         fieldlist: Sequence[str]) -> None:
        """"""
        self.ensure_db_open()
        valuelist = []
        for f in fieldlist[1:]:
            valuelist.append(getattr(obj, f))
        cursor = self.db.cursor()
        self.db_exec_with_cursor(
            cursor,
            get_sql_insert_without_first_field(table, fieldlist,
                                               self.get_delims()),
            *valuelist
        )
        pkvalue = get_pk_of_last_insert(cursor)
        setattr(obj, fieldlist[0], pkvalue)
576441
def _insert_data(self, name, value, timestamp, interval, config, **kwargs):
    ''''''
    # Mongo does not allow mixing atomic modifiers and non-$set sets in the
    # same update, so the choice is to either run the first upsert on
    # {'_id':id} to ensure the record is in place followed by an atomic update
    # based on the series type, or use $set for all of the keys to be used in
    # creating the record, which then disallows setting our own _id because
    # that "can't be updated". So the tradeoffs are:
    #   * 2 updates for every insert, maybe a local cache of known _ids and the
    #     associated memory overhead
    #   * Query by the 2 or 3 key tuple for this interval and the associated
    #     overhead of that index match vs. the presumably-faster match on _id
    #   * Yet another index for the would-be _id of i_key or r_key, where each
    #     index has a notable impact on write performance.
    # For now, choosing to go with matching on the tuple until performance
    # testing can be done. Even then, there may be a variety of factors which
    # make the results situation-dependent.
    insert = {'name':name, 'interval':config['i_calc'].to_bucket(timestamp)}
    if not config['coarse']:
      insert['resolution'] = config['r_calc'].to_bucket(timestamp)
    # copy the query before expire_from as that is not indexed
    query = insert.copy()

    if config['expire']:
      insert['expire_from'] = datetime.utcfromtimestamp( timestamp )

    # switch to atomic updates
    insert = {'$set':insert.copy()}

    # need to hide the period of any values. best option seems to be to pick
    # a character that "no one" uses.
    if isinstance(value, (str,unicode)):
      value = value.replace('.', self._escape_character)
    elif isinstance(value, float):
      value = str(value).replace('.', self._escape_character)

    self._insert_type( insert, value )

    # TODO: use write preference settings if we have them
    if not kwargs.get('dry_run',False):
      self._client[interval].update( query, insert, upsert=True, check_keys=False )
    return query, insert