Convenience wrapper for database INSERT.
513504
def insert(table, values=(), **kwargs):
    """"""
    values = dict(values, **kwargs).items()
    sql, args = makeSQL("INSERT", table, values=values)
    return execute(sql, args).lastrowid
120883
def get_sql_insert(table: str,
                   fieldlist: Sequence[str],
                   delims: Tuple[str, str] = ("", "")) -> str:
    """"""
    return (
        "INSERT INTO " + delimit(table, delims) +
        " (" +
        ",".join([delimit(x, delims) for x in fieldlist]) +
        ") VALUES (" +
        ",".join(["?"] * len(fieldlist)) +
        ")"
    )
594397
def update_insert_values(bel_resource: Mapping, mapping: Mapping[str, Tuple[str, str]], values: Dict[str, str]) -> None:
    """"""
    for database_column, (section, key) in mapping.items():
        if section in bel_resource and key in bel_resource[section]:
            values[database_column] = bel_resource[section][key]
731091
def _sql_expand_insert(self, spec, key_prefix = '', col_prefix = ''):
        
        col = list(spec)
        sql = '('
        sql += ', '.join(col_prefix + key for key in col)
        sql += ') VALUES ('
        sql += ', '.join('%(' + key_prefix + key + ')s' for key in col)
        sql += ')'
        params = {}
        for key in spec:
            params[key_prefix + key] = spec[key]

        return sql, params
111351
def insert(self, table, data_list, return_cols='id'):
        
        data_list = copy.deepcopy(data_list)  # Create deepcopy so the original list does not get modified
        # Make sure that `data_list` is a list
        if not isinstance(data_list, list):
            data_list = [data_list]
        # Make sure data_list has content
        if len(data_list) == 0:
            # No need to continue
            return []

        # Data in the list must be dicts (just check the first one)
        if not isinstance(data_list[0], dict):
            logger.critical("Data must be a list of dicts")
            # Do not return here, let the exception handle the error that will be thrown when the query runs

        # Make sure return_cols is a list
        if return_cols is None or len(return_cols) == 0 or return_cols[0] is None:
            return_cols = ''
        elif not isinstance(return_cols, list):
            return_cols = [return_cols]

        if len(return_cols) > 0:
            return_cols = 'RETURNING ' + ','.join(return_cols)

        try:
            with self.getcursor() as cur:
                query = "INSERT INTO {table} ({fields}) VALUES {values} {return_cols}"\
                        .format(table=table,
                                fields='"{0}"'.format('", "'.join(data_list[0].keys())),
                                values=','.join(['%s'] * len(data_list)),
                                return_cols=return_cols,
                                )
                values = []
                for row in [tuple(v.values()) for v in data_list]:
                    values.append(_check_values(row))

                query = cur.mogrify(query, values)
                cur.execute(query)

                try:
                    return cur.fetchall()
                except Exception:
                    return None

        except Exception as e:
            logger.exception("Error inserting data")
            logger.debug("Error inserting data: {data}".format(data=data_list))
            raise e.with_traceback(sys.exc_info()[2])
647410
def _insert(self, sock_info, docs, ordered=True, check_keys=True,
                manipulate=False, write_concern=None, op_id=None,
                bypass_doc_val=False):
        """"""
        if isinstance(docs, collections.Mapping):
            return self._insert_one(
                sock_info, docs, ordered,
                check_keys, manipulate, write_concern, op_id, bypass_doc_val)

        ids = []

        if manipulate:
            def gen():
                """Generator that applies SON manipulators to each document
                and adds _id if necessary.
                """
                _db = self.__database
                for doc in docs:
                    # Apply user-configured SON manipulators. This order of
                    # operations is required for backwards compatibility,
                    # see PYTHON-709.
                    doc = _db._apply_incoming_manipulators(doc, self)
                    if not (isinstance(doc, RawBSONDocument) or '_id' in doc):
                        doc['_id'] = ObjectId()

                    doc = _db._apply_incoming_copying_manipulators(doc, self)
                    ids.append(doc['_id'])
                    yield doc
        else:
            def gen():
                """Generator that only tracks existing _ids."""
                for doc in docs:
                    # Don't inflate RawBSONDocument by touching fields.
                    if not isinstance(doc, RawBSONDocument):
                        ids.append(doc.get('_id'))
                    yield doc

        concern = (write_concern or self.write_concern).document
        acknowledged = concern.get("w") != 0

        command = SON([('insert', self.name),
                       ('ordered', ordered)])
        if concern:
            command['writeConcern'] = concern
        if op_id is None:
            op_id = message._randint()
        if bypass_doc_val and sock_info.max_wire_version >= 4:
            command['bypassDocumentValidation'] = True
        bwc = message._BulkWriteContext(
            self.database.name, command, sock_info, op_id,
            self.database.client._event_listeners)
        if sock_info.max_wire_version > 1 and acknowledged:
            # Batched insert command.
            results = message._do_batched_write_command(
                self.database.name + ".$cmd", message._INSERT, command,
                gen(), check_keys, self.__write_response_codec_options, bwc)
            _check_write_command_response(results)
        else:
            # Legacy batched OP_INSERT.
            message._do_batched_insert(self.__full_name, gen(), check_keys,
                                       acknowledged, concern, not ordered,
                                       self.__write_response_codec_options, bwc)
        return ids
1338088
def insert(self, table, records, create_cols=False, dtypes=None):
        
        if self._check_db() is False:
            return
        try:
            table = self.db[table]
        except Exception as e:
            self.err(e, "Can not find table " + table)
        t = type(records)
        if t == dict:
            func = table.insert
        elif t == list:
            func = table.insert_many
        else:
            msg = "Rows datatype " + \
                str(t) + " not valid: use a list or a dictionary"
            self.err(msg)
        if create_cols is True:
            try:
                func(records, ensure=True, types=dtypes)
            except Exception as e:
                self.err(e, "Can not insert create columns and insert data")
            return
        else:
            try:
                func(records, types=dtypes)
            except Exception as e:
                self.err(e, "Can not insert data")
            return
        self.ok("Rows inserted in the database")
1135452
def _insert(collection_name, docs, check_keys, flags, opts):
    """"""
    encode = _dict_to_bson  # Make local. Uses extensions.
    if len(docs) == 1:
        encoded = encode(docs[0], check_keys, opts)
        return b"".join([
            b"\x00\x00\x00\x00",  # Flags don't matter for one doc.
            _make_c_string(collection_name),
            encoded]), len(encoded)

    encoded = [encode(doc, check_keys, opts) for doc in docs]
    if not encoded:
        raise InvalidOperation("cannot do an empty bulk insert")
    return b"".join([
        _pack_int(flags),
        _make_c_string(collection_name),
        b"".join(encoded)]), max(map(len, encoded))
981955
def create_insert():
    
    insert = upkey("insert").setResultsName("action")

    # VALUES
    attrs = Group(delimitedList(var)).setResultsName("attrs")
    value_group = Group(Suppress("(") + delimitedList(value) + Suppress(")"))
    values = Group(delimitedList(value_group)).setResultsName("list_values")
    values_insert = Suppress("(") + attrs + Suppress(")") + upkey("values") + values

    # KEYWORDS
    keyword = Group(var + Suppress("=") + value)
    item = Group(Suppress("(") + delimitedList(keyword) + Suppress(")"))
    keyword_insert = delimitedList(item).setResultsName("map_values")

    return insert + into + table + (values_insert | keyword_insert) + Optional(throttle)
99695
def _insert_data(self, connection, name, value, timestamp, interval, config):
    ''''''
    cursor = connection.cursor()
    try:
      stmt = self._insert_stmt(name, value, timestamp, interval, config)
      if stmt:
        cursor.execute(stmt)
    finally:
      cursor.close()
824142
def setup(db_class, simple_object_cls, primary_keys):
    """"""
    table_name = simple_object_cls.__name__
    column_names = simple_object_cls.FIELDS

    metadata = MetaData()
    table = Table(table_name, metadata,
                  *[Column(cname, _get_best_column_type(cname),
                           primary_key=cname in primary_keys)
                    for cname in column_names])

    db_class.metadata = metadata
    db_class.mapper_class = simple_object_cls
    db_class.table = table

    mapper(simple_object_cls, table)
1007364
def kwinsert(clas,pool_or_cursor,**kwargs):
    ""
    returning = kwargs.pop('returning',None)
    fields,vals = zip(*kwargs.items())
    # note: don't do SpecialField resolution here; clas.insert takes care of it
    return clas.insert(pool_or_cursor,fields,vals,returning=returning)
67236
def insert(manager, graph: BELGraph):
    """"""
    to_database(graph, manager=manager, use_tqdm=True)
608200
def insert_all(db, schema_name, table_name, columns, items):
    
    table = '{0}.{1}'.format(schema_name, table_name) if schema_name else table_name
    columns_list = ', '.join(columns)
    values_list = ', '.join(['?'] * len(columns))
    query = 'INSERT INTO {table} ({columns}) VALUES ({values})'.format(
        table=table, columns=columns_list, values=values_list)
    for item in items:
        values = [getattr(item, col) for col in columns]
        db.execute(query, values)
898747
def _insert(self, query, vars):
        
        cursor = self.get_db().cursor()
        self._log(cursor, query, vars)
        cursor.execute(query, vars)
        self.get_db().commit()
        return cursor.fetchone()
1067696
def insert_many(self, table, columns, values, limit=MAX_ROWS_PER_QUERY, execute=True):
        
        # Make values a list of lists if it is a flat list
        if not isinstance(values[0], (list, set, tuple)):
            values = []
            for v in values:
                if v is not None and len(v) > 0:
                    values.append([v])
                else:
                    values.append([None])

        # Concatenate statement
        cols, vals = get_col_val_str(columns)
        statement = 'INSERT INTO {0} ({1}) VALUES ({2})'.format(wrap(table), cols, vals)

        if execute and len(values) > limit:
            while len(values) > 0:
                vals = [values.pop(0) for i in range(0, min(limit, len(values)))]
                self._cursor.executemany(statement, vals)
                self._commit()

        elif execute:
            # Execute statement
            self._cursor.executemany(statement, values)
            self._commit()
            self._printer('\tMySQL rows (' + str(len(values)) + ') successfully INSERTED')

        # Only return statement
        else:
            return statement
889582
def _before_insert(mapper, connection, target):
    """"""
    if target.position is None:
        func = sa.sql.func
        stmt = sa.select([func.coalesce(func.max(mapper.mapped_table.c.position), -1)])
        target.position = connection.execute(stmt).scalar() + 1