The :meth:`sqlalchemy.crud.updating.upsert_all` function in ORM syntax.

        :param engine: an engine created by``sqlalchemy.create_engine``.
        :param obj_or_data: single object or list of object
90
def upsert_all(cls, engine, obj_or_data):
        
        cls.update_all(
            engine=engine,
            obj_or_data=obj_or_data,
            upsert=True,
        )
931770
def upsert(self, table: str, record: dict, create_cols: bool=False,
               dtypes: list=None, pks=["id"], namefields=["id"]):
        
        try:
            self.db[table].upsert(record, pks, create_cols, dtypes)
        except Exception as e:
            self.err(e, "Can not upsert data")
            return
        names = ""
        for el in namefields:
            names += " " + record[el]
        self.ok("Upserted record"+names)
364813
def by_id(cls, _id, engine_or_session):
        
        ses, auto_close = ensure_session(engine_or_session)
        obj = ses.query(cls).get(_id)
        if auto_close:
            ses.close()
        return obj
1017433
async def get_or_create(self, model_, defaults=None, **kwargs):
        
        try:
            return (await self.get(model_, **kwargs)), False
        except model_.DoesNotExist:
            data = defaults or {}
            data.update({k: v for k, v in kwargs.items() if '__' not in k})
            return (await self.create(model_, **data)), True
1159904
def update_or_create(cls, org, provider, exists):
        
        instance, created = cls.objects.update_or_create(
            org=org,
            provider=provider,
            defaults={'exists': exists},
        )

        return instance, created
777551
function mergeHelpers(engine, options) {
  if (!options || typeof options !== 'object') {
    throw new TypeError('expected an object');
  }

  var opts = extend({}, options);
  var helpers = merge({}, engine.helpers.cache, opts.helpers);
  var keys = Object.keys(helpers);
  for (var i = 0; i < keys.length; i++) {
    var key = keys[i];
    engine.asyncHelpers.set(key, helpers[key]);
  }

  opts.helpers = engine.asyncHelpers.get({wrap: opts.async});
  return opts;
}
1076436
def dump_orm_object_as_insert_sql(engine: Engine,
                                  obj: object,
                                  fileobj: TextIO) -> None:
    
    # literal_query = make_literal_query_fn(engine.dialect)
    insp = inspect(obj)
    # insp: an InstanceState
    # http://docs.sqlalchemy.org/en/latest/orm/internals.html#sqlalchemy.orm.state.InstanceState  # noqa
    # insp.mapper: a Mapper
    # http://docs.sqlalchemy.org/en/latest/orm/mapping_api.html#sqlalchemy.orm.mapper.Mapper  # noqa

    # Don't do this:
    #   table = insp.mapper.mapped_table
    # Do this instead. The method above gives you fancy data types like list
    # and Arrow on the Python side. We want the bog-standard datatypes drawn
    # from the database itself.
    meta = MetaData(bind=engine)
    table_name = insp.mapper.mapped_table.name
    # log.debug("table_name: {}", table_name)
    table = Table(table_name, meta, autoload=True)
    # log.debug("table: {}", table)

    # NewRecord = quick_mapper(table)
    # columns = table.columns.keys()
    query = select(table.columns)
    # log.debug("query: {}", query)
    for orm_pkcol in insp.mapper.primary_key:
        core_pkcol = table.columns.get(orm_pkcol.name)
        pkval = getattr(obj, orm_pkcol.name)
        query = query.where(core_pkcol == pkval)
    # log.debug("query: {}", query)
    cursor = engine.execute(query)
    row = cursor.fetchone()  # should only be one...
    row_dict = dict(row)
    # log.debug("obj: {}", obj)
    # log.debug("row_dict: {}", row_dict)
    statement = table.insert(values=row_dict)
    # insert_str = literal_query(statement)
    insert_str = get_literal_query(statement, bind=engine)
    writeline_nl(fileobj, insert_str)
1172652
async def update(self, obj, only=None):
        
        field_dict = dict(obj.__data__)
        pk_field = obj._meta.primary_key

        if only:
            self._prune_fields(field_dict, only)

        if obj._meta.only_save_dirty:
            self._prune_fields(field_dict, obj.dirty_fields)

        if obj._meta.composite_key:
            for pk_part_name in pk_field.field_names:
                field_dict.pop(pk_part_name, None)
        else:
            field_dict.pop(pk_field.name, None)

        query = obj.update(**field_dict).where(obj._pk_expr())
        result = await self.execute(query)
        obj._dirty.clear()
        return result
944177
def set_object(model, instance, fields=None, engine_name=None):
    
    from uliweb import settings
    
    if not check_enable():
        return
    
    redis = get_redis()
    if not redis: return
    
    tablename = model._alias or model.tablename
    exclude = []
    if not fields:
        fields, exclude = get_fields(tablename)
    
    v = instance.dump(fields, exclude=exclude)
    info = settings.get_var('OBJCACHE_TABLES/%s' % tablename, {})
    
    if info is None:
        return
    
    expire = settings.get_var('OBJCACHE/timeout', 0)
    key = 'id'
    if info and isinstance(info, dict):
        expire = info.get('expire', expire)
        key = info.get('key', key)
    
    if '.' in key or key not in model.properties:
        _key = import_attr(key)(instance)
    else:
        _key = getattr(instance, key)
    _id = get_id(engine_name or model.get_engine_name(), tablename, _key)
    try:
        pipe = redis.pipeline()
        p = pipe.delete(_id).hmset(_id, v)
        expire_msg = ''
        if expire:
            p = p.expire(_id, expire)
            expire_msg = ':expire=%d' % expire
        r = p.execute()
        log.debug("Saving to cache objcache:set:table=%s:id=[%s]:%s" % (tablename, _id, expire_msg))
    except Exception as e:
        log.exception(e)
160311
def _insert_or_update(self, resourcetype, source, mode='insert', hhclass='Service'):
        

        keywords = []

        if self.filter is not None:
            catalog = Catalog.objects.get(id=int(self.filter.split()[-1]))

        try:
            if hhclass == 'Layer':
                # TODO: better way of figuring out duplicates
                match = Layer.objects.filter(name=source.name,
                                             title=source.title,
                                             abstract=source.abstract,
                                             is_monitored=False)
                matches = match.all()
                if matches:
                    if mode == 'insert':
                        raise RuntimeError('HHypermap error: Layer %d \'%s\' already exists' % (
                                           matches[0].id, source.title))
                    elif mode == 'update':
                        match.update(
                            name=source.name,
                            title=source.title,
                            abstract=source.abstract,
                            is_monitored=False,
                            xml=source.xml,
                            wkt_geometry=source.wkt_geometry,
                            anytext=util.get_anytext([source.title, source.abstract, source.keywords_csv])
                        )

                service = get_service(source.xml)
                res, keywords = create_layer_from_metadata_xml(resourcetype, source.xml,
                                                               monitor=False, service=service,
                                                               catalog=catalog)

                res.save()

                LOGGER.debug('Indexing layer with id %s on search engine' % res.uuid)
                index_layer(res.id, use_cache=True)

            else:
                if resourcetype == 'http://www.opengis.net/cat/csw/2.0.2':
                    res = Endpoint(url=source, catalog=catalog)
                else:
                    res = Service(type=HYPERMAP_SERVICE_TYPES[resourcetype], url=source, catalog=catalog)

                res.save()

            if keywords:
                for kw in keywords:
                    res.keywords.add(kw)
        except Exception as err:
            raise RuntimeError('HHypermap error: %s' % err)

        # return a list of ids that were inserted or updated
        ids = []

        if hhclass == 'Layer':
            ids.append({'identifier': res.uuid, 'title': res.title})
        else:
            if resourcetype == 'http://www.opengis.net/cat/csw/2.0.2':
                for res in Endpoint.objects.filter(url=source).all():
                    ids.append({'identifier': res.uuid, 'title': res.url})
            else:
                for res in Service.objects.filter(url=source).all():
                    ids.append({'identifier': res.uuid, 'title': res.title})

        return ids
1192774
def _recursive_upsert(context, params, data):
    """"""
    children = params.get("children", {})
    nested_calls = []
    for child_params in children:
        key = child_params.get("key")
        child_data_list = ensure_list(data.pop(key))
        if isinstance(child_data_list, dict):
            child_data_list = [child_data_list]
        if not (isinstance(child_data_list, list) and
                all(isinstance(i, dict) for i in child_data_list)):
            context.log.warn(
                "Expecting a dict or a lost of dicts as children for key", key
            )
            continue
        if child_data_list:
            table_suffix = child_params.get("table_suffix", key)
            child_params["table"] = params.get("table") + "_" + table_suffix
            # copy some properties over from parent to child
            inherit = child_params.get("inherit", {})
            for child_data in child_data_list:
                for dest, src in inherit.items():
                    child_data[dest] = data.get(src)
                nested_calls.append((child_params, child_data))
    # Insert or update data
    _upsert(context, params, data)
    for child_params, child_data in nested_calls:
        _recursive_upsert(context, child_params, child_data)
1254251
def _get_upserts(queryset, model_objs_updated, model_objs_created, unique_fields):
    
    updated, created = _get_upserts_distinct(queryset, model_objs_updated, model_objs_created, unique_fields)
    return updated + created
183645
def create_update():
    
    update = upkey("update").setResultsName("action")
    returns, none, all_, updated, old, new = map(
        upkey, ["returns", "none", "all", "updated", "old", "new"]
    )
    return_ = returns + Group(
        none | (all_ + old) | (all_ + new) | (updated + old) | (updated + new)
    ).setResultsName("returns")
    return (
        update
        + table
        + update_expr
        + Optional(keys_in)
        + Optional(where)
        + Optional(using)
        + Optional(return_)
        + Optional(throttle)
    )
1352403
def save(coll, to_save):
	
	filter = Projection(['_id'], to_save)
	upsert_replace = functools.partial(coll.replace_one, filter, upsert=True)
	op = upsert_replace if filter else coll.insert_one
	return op(to_save)
468128
def obj_update_or_create(model, defaults=None, update_fields=UNSET, **kwargs):
    
    obj, created = model.objects.get_or_create(defaults=defaults, **kwargs)
    if created:
        logger.debug('CREATED %s %s',
                     model._meta.object_name,
                     obj.pk,
                     extra={'pk': obj.pk})
    else:
        obj_update(obj, defaults, update_fields=update_fields)
    return obj, created
549544
def create_or_update(cls, object_version, key, value):
        """"""
        assert len(key) < 256
        assert len(value) < 256
        obj = cls.get(object_version, key)
        if obj:
            obj.value = value
            db.session.merge(obj)
        else:
            obj = cls.create(object_version, key, value)
        return obj
604114
function sqliteBulkUpsert(model, data) {
  var queries = ["BEGIN"];
  var values = [];

  // Transform data
  _.each(data, function(d) {
    var query = "INSERT OR REPLACE INTO " + model.tableName + " ([[COLUMNS]]) VALUES ([[VALUES]])";
    query = query.replace("[[COLUMNS]]", _.keys(d).join(", "));

    // Put in ?'s
    query = query.replace("[[VALUES]]", _.map(d, function(v) {
      return "?";
    }).join(", "));

    // Get values
    values = values.concat(_.values(d));
    queries.push(query);
  });

  // Create final output and format
  queries.push("COMMIT");
  return {
    query: queries.join("; "),
    replacements: values
  };
}