Perform INSERT query asynchronously. Returns last insert ID.
    This function is called by object.create for single objects only.
170621
async def insert(query):
    
    assert isinstance(query, peewee.Insert),\
        ("Error, trying to run insert coroutine"
         "with wrong query class %s" % str(query))

    cursor = await _execute_query_async(query)

    try:
        if query._returning:
            row = await cursor.fetchone()
            result = row[0]
        else:
            database = _query_db(query)
            last_id = await database.last_insert_id_async(cursor)
            result = last_id
    finally:
        await cursor.release()

    return result
427295
def insert(cls, jobs_data, queue=None, statuses_no_storage=None, return_jobs=True, w=None, j=None):
        

        now = datetime.datetime.utcnow()
        for data in jobs_data:
            if data["status"] == "started":
                data["datestarted"] = now

        no_storage = (statuses_no_storage is not None) and ("started" in statuses_no_storage)
        if no_storage and return_jobs:
            for data in jobs_data:
                data["_id"] = ObjectId()  # Give the job a temporary ID
        else:
            inserted = context.connections.mongodb_jobs.mrq_jobs.insert(
                jobs_data,
                manipulate=True,
                w=w,
                j=j
            )

        if return_jobs:
            jobs = []
            for data in jobs_data:
                job = cls(data["_id"], queue=queue)
                job.set_data(data)
                job.statuses_no_storage = statuses_no_storage
                job.stored = (not no_storage)
                if data["status"] == "started":
                    job.datestarted = data["datestarted"]
                jobs.append(job)

            return jobs
        else:
            return inserted
1252273
public void performInsert()
    {
        if(insertMap == null)
            return;
        else
        {
            PersistenceBroker broker = tx.getBroker();
            Iterator it = insertMap.values().iterator();
            while(it.hasNext())
            {
                NamedEntry namedEntry = (NamedEntry) it.next();
                namedEntry.prepareForStore(broker);
                broker.store(namedEntry, ObjectModification.INSERT);
            }
        }
    }
513504
def insert(table, values=(), **kwargs):
    """"""
    values = dict(values, **kwargs).items()
    sql, args = makeSQL("INSERT", table, values=values)
    return execute(sql, args).lastrowid
1041207
public int insert(DatabaseType databaseType, DatabaseConnection databaseConnection, T data, ObjectCache objectCache)
			throws SQLException {
		KeyHolder keyHolder = null;
		if (idField != null) {
			boolean assignId;
			if (idField.isAllowGeneratedIdInsert() && !idField.isObjectsFieldValueDefault(data)) {
				assignId = false;
			} else {
				assignId = true;
			}
			if (idField.isSelfGeneratedId() && idField.isGeneratedId()) {
				if (assignId) {
					idField.assignField(connectionSource, data, idField.generateId(), false, objectCache);
				}
			} else if (idField.isGeneratedIdSequence() && databaseType.isSelectSequenceBeforeInsert()) {
				if (assignId) {
					assignSequenceId(databaseConnection, data, objectCache);
				}
			} else if (idField.isGeneratedId()) {
				if (assignId) {
					// get the id back from the database
					keyHolder = new KeyHolder(idField.getColumnName());
				}
			} else {
				// the id should have been set by the caller already
			}
		}

		try {
			// implement {@link DatabaseField#foreignAutoCreate()}, need to do this _before_ getFieldObjects() below
			if (tableInfo.isForeignAutoCreate()) {
				for (FieldType fieldType : tableInfo.getFieldTypes()) {
					if (!fieldType.isForeignAutoCreate()) {
						continue;
					}
					// get the field value
					Object foreignObj = fieldType.extractRawJavaFieldValue(data);
					if (foreignObj != null && fieldType.getForeignIdField().isObjectsFieldValueDefault(foreignObj)) {
						fieldType.createWithForeignDao(foreignObj);
					}
				}
			}

			Object[] args = getFieldObjects(data);
			Object versionDefaultValue = null;
			// implement {@link DatabaseField#version()}
			if (versionFieldTypeIndex >= 0 && args[versionFieldTypeIndex] == null) {
				// if the version is null then we need to initialize it before create
				FieldType versionFieldType = argFieldTypes[versionFieldTypeIndex];
				versionDefaultValue = versionFieldType.moveToNextValue(null);
				args[versionFieldTypeIndex] = versionFieldType.convertJavaFieldToSqlArgValue(versionDefaultValue);
			}

			int rowC;
			try {
				rowC = databaseConnection.insert(statement, args, argFieldTypes, keyHolder);
			} catch (SQLException e) {
				// NOTE: don't log full exception here
				logger.debug("insert data with statement '{}' and {} args, threw exception: {}", statement, args.length,
						e);
				if (args.length > 0) {
					// need to do the (Object) cast to force args to be a single object
					logger.trace("insert arguments: {}", (Object) args);
				}
				throw e;
			}
			logger.debug("insert data with statement '{}' and {} args, changed {} rows", statement, args.length, rowC);
			if (args.length > 0) {
				// need to do the (Object) cast to force args to be a single object
				logger.trace("insert arguments: {}", (Object) args);
			}
			if (rowC > 0) {
				if (versionDefaultValue != null) {
					argFieldTypes[versionFieldTypeIndex].assignField(connectionSource, data, versionDefaultValue, false,
							null);
				}
				if (keyHolder != null) {
					// assign the key returned by the database to the object's id field after it was inserted
					Number key = keyHolder.getKey();
					if (key == null) {
						// may never happen but let's be careful out there
						throw new SQLException(
								"generated-id key was not set by the update call, maybe a schema mismatch between entity and database table?");
					}
					if (key.longValue() == 0L) {
						// sanity check because the generated-key returned is 0 by default, may never happen
						throw new SQLException(
								"generated-id key must not be 0 value, maybe a schema mismatch between entity and database table?");
					}
					assignIdValue(data, key, "keyholder", objectCache);
				}
				/*
				 * If we have a cache and if all of the foreign-collection fields have been assigned then add to cache.
				 * However, if one of the foreign collections has not be assigned then don't add it to the cache.
				 */
				if (objectCache != null && foreignCollectionsAreAssigned(tableInfo.getForeignCollections(), data)) {
					Object id = idField.extractJavaFieldValue(data);
					objectCache.put(clazz, id, data);
				}
			}

			return rowC;
		} catch (SQLException e) {
			throw SqlExceptionUtil.create("Unable to run insert stmt on object " + data + ": " + statement, e);
		}
	}
166567
private function insert()
    {
        $insert = $this->dsql();

        // Performs the actual database changes. Throw exception if problem occurs
        foreach ($this->elements as $name => $f) {
            if ($f instanceof Field) {
                if (!$f->editable() && !$f->system()) {
                    continue;
                }
                if (!isset($this->dirty[$name]) && $f->defaultValue() === null) {
                    continue;
                }

                $f->updateInsertQuery($insert);
            }
        }
        $this->hook('beforeInsert', array(&$insert));
        //delayed is not supported by INNODB, but what's worse - it shows error.
        //if($this->_save_as===false)$insert->option_insert('delayed');
        $id = $insert->insert();
        if ($id == 0) {
            // no auto-increment column present
            $id = $this->get($this->id_field);

            if ($id === null && $this->_save_as !== false) {
                throw $this->exception('Please add auto-increment ID column to your table or specify ID manually');
            }
        }
        $res = $this->hook('afterInsert', array($id));
        if ($res === false) {
            return $this;
        }

        if ($this->_save_as === false) {
            return $this->unload();
        }
        if ($this->_save_as) {
            $this->unload();
        }
        $o = $this->_save_as ?: $this;

        if ($this->fast && !$this->_save_as) {
            $this[$this->id_field] = $this->id = $id;

            return $this;
        }
        $res = $o->tryLoad($id);
        if (!$res->loaded()) {
            throw $this->exception('Saved model did not match conditions. Save aborted.');
        }

        return $res;
    }
53972
function(obj, callback, error) {
      var that = this
      objs = (this.isArray(obj) ? obj : [obj]).map(function(o) {
        if (!o.key) {
          o.key = that.uuid()
        }
        return o
      }),
        ins = "INSERT OR REPLACE INTO " + this.record + " (value, timestamp, id) VALUES (?,?,?)",
        win = function() {
          if (callback) {
            that.lambda(callback).call(that, that.isArray(obj) ? objs : objs[0])
          }
        }, error = error || function() {}, insvals = [],
        ts = now()

        try {
          for (var i = 0, l = objs.length; i < l; i++) {
            insvals[i] = [JSON.stringify(objs[i]), ts, objs[i].key];
          }
        } catch (e) {
          fail(e)
          throw e;
        }

      that.db.transaction(function(t) {
        for (var i = 0, l = objs.length; i < l; i++)
          t.executeSql(ins, insvals[i])
      }, function(e, i) {
        fail(e, i)
      }, win)

      return this
    }
1373903
def db_insert(self):
        
        assert self.has_db
        # Connect to MongoDb and get the collection.
        coll = self.manager.db_connector.get_collection()
        print("Mongodb collection %s with count %d", coll, coll.count())

        start = time.time()
        for work in self:
            for task in work:
                results = task.get_results()
                pprint(results)
                results.update_collection(coll)
            results = work.get_results()
            pprint(results)
            results.update_collection(coll)
        print("MongoDb update done in %s [s]" % time.time() - start)

        results = self.get_results()
        pprint(results)
        results.update_collection(coll)

        # Update the pickle file to save the mongo ids.
        self.pickle_dump()

        for d in coll.find():
            pprint(d)
747006
function insert(values, returning) {
    this._method = 'insert';
    if (!isEmpty(returning)) {
      this.returning(returning);
    }
    this._single.insert = values;
    return this;
  }
568778
def insert_query(**kw):
    
    with current_app.app_context():
        result = db.execute(text(fetch_query_string('select_query_where_name.sql')), **kw).fetchall()
        if result:
            kw['query_id'] = result[0]['id']
        else:
            result = db.execute(text(fetch_query_string('insert_query.sql')), **kw)
            kw['query_id'] = result.lastrowid
            if (not kw['query_id']):
                result = result.fetchall()
                kw['query_id']  = result[0]['id']
        db.execute(text(fetch_query_string('insert_query_node.sql')), **kw)
694412
public function insert_id()
	{
		$query = version_compare($this->version(), '8', '>=')
			? 'SELECT SCOPE_IDENTITY() AS last_id'
			: 'SELECT @@IDENTITY AS last_id';

		$query = $this->query($query);
		$query = $query->row();
		return $query->last_id;
	}
456771
def execute_insert_no_results(self, sock_info, run, op_id, acknowledged):
        
        command = SON([('insert', self.collection.name),
                       ('ordered', self.ordered)])
        concern = {'w': int(self.ordered)}
        command['writeConcern'] = concern
        if self.bypass_doc_val and sock_info.max_wire_version >= 4:
            command['bypassDocumentValidation'] = True
        db = self.collection.database
        bwc = _BulkWriteContext(
            db.name, command, sock_info, op_id, db.client._event_listeners,
            session=None)
        # Legacy batched OP_INSERT.
        _do_batched_insert(
            self.collection.full_name, run.ops, True, acknowledged, concern,
            not self.ordered, self.collection.codec_options, bwc)
244360
def insert(self, n=1, interval=0, pre_dl=None, post_dl=None):
        
        self.delay(pre_dl)
        self.k.tap_key(self.k.insert_key, n, interval)
        self.delay(post_dl)
909969
public long getLastInsertId() throws SQLException {
    // A default connection: autocommit = true.
    long num = -1;
    try {
      num = ((Number) this.queryRunner
          .query(this.conn, "SELECT LAST_INSERT_ID();", new ScalarHandler<>(1)))
          .longValue();
    } catch (final SQLException ex) {
      logger.error("can not get last insertion ID");
      throw ex;
    }
    return num;
  }
1293768
async def insert(self, **kwargs):
		
		
		if kwargs:
			# Create autoincrement for account
			pk = await self.autoincrement()
			kwargs.update({"id": pk})

			# Create account with received data and autoincrement
			await self.collection.insert_one(kwargs)

			row = await self.collection.find_one({"id": pk})

		else:
			row = None

		if row:
			return {i:row[i] for i in row if i != "_id"}
		else:
			return {"error":500, 
					"reason":"Not created"}
1259501
def insert_record(self,
                      table: str,
                      fields: Sequence[str],
                      values: Sequence[Any],
                      update_on_duplicate_key: bool = False) -> int:
        """"""
        self.ensure_db_open()
        if len(fields) != len(values):
            raise AssertionError("Field/value mismatch")
        if update_on_duplicate_key:
            sql = get_sql_insert_or_update(table, fields, self.get_delims())
        else:
            sql = get_sql_insert(table, fields, self.get_delims())
        sql = self.localize_sql(sql)
        log.debug("About to insert_record with SQL template: " + sql)
        try:
            cursor = self.db.cursor()
            debug_sql(sql, values)
            cursor.execute(sql, values)
            # ... binds the placeholders (?, %s) to values in the process
            new_pk = get_pk_of_last_insert(cursor)
            log.debug("Record inserted.")
            return new_pk
        except:  # nopep8
            log.exception("insert_record: Failed to insert record.")
            raise
714029
public synchronized QueryId createNextQueryId()
    {
        // only generate 100,000 ids per day
        if (counter > 99_999) {
            // wait for the second to rollover
            while (MILLISECONDS.toSeconds(nowInMillis()) == lastTimeInSeconds) {
                Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
            }
            counter = 0;
        }

        // if it has been a second since the last id was generated, generate a new timestamp
        long now = nowInMillis();
        if (MILLISECONDS.toSeconds(now) != lastTimeInSeconds) {
            // generate new timestamp
            lastTimeInSeconds = MILLISECONDS.toSeconds(now);
            lastTimestamp = TIMESTAMP_FORMAT.print(now);

            // if the day has rolled over, restart the counter
            if (MILLISECONDS.toDays(now) != lastTimeInDays) {
                lastTimeInDays = MILLISECONDS.toDays(now);
                counter = 0;
            }
        }

        return new QueryId(String.format("%s_%05d_%s", lastTimestamp, counter++, coordinatorId));
    }