A compatibility trigger to upsert users from legacy persons table.
763901
def upsert_users_from_legacy_publication_trigger(plpy, td):
    """"""
    modified_state = "OK"
    authors = td['new']['authors'] and td['new']['authors'] or []
    maintainers = td['new']['maintainers'] and td['new']['maintainers'] or []
    licensors = td['new']['licensors'] and td['new']['licensors'] or []
    is_legacy_publication = td['new']['version'] is not None

    if not is_legacy_publication:
        return modified_state

    # Upsert all roles into the users table.
    users = []
    users.extend(authors)
    users.extend(maintainers)
    users.extend(licensors)
    users = list(set(users))

    plan = plpy.prepare("""\
SELECT username FROM users WHERE username = any($1)""",
                        ['text[]'])
    existing_users = set([r['username'] for r in plpy.execute(plan, (users,))])

    new_users = set(users).difference(existing_users)
    for username in new_users:
        plan = plpy.prepare("""\
INSERT INTO users (username, first_name, last_name, full_name, title)
SELECT personid, firstname, surname, fullname, honorific
FROM persons where personid = $1""", ['text'])
        plpy.execute(plan, (username,))

    return modified_state
1184761
def upsert_keys(session, key_table, keys):
    
    # Do nothing if empty
    if not keys:
        return

    for key_batch in _batch_postgres_query(
        key_table, [{"name": k[0], "candidate_classes": k[1]} for k in keys.items()]
    ):
        stmt = insert(key_table.__table__)
        stmt = stmt.on_conflict_do_update(
            constraint=key_table.__table__.primary_key,
            set_={
                "name": stmt.excluded.get("name"),
                "candidate_classes": stmt.excluded.get("candidate_classes"),
            },
        )
        while True:
            try:
                session.execute(stmt, key_batch)
                session.commit()
                break
            except Exception as e:
                logger.debug(e)
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
  };
}
1243417
public function upsert($table, $insertColumns, $updateColumns, &$params)
    {
        /**
 * @var Constraint[] $constraints 
*/
        list($uniqueNames, $insertNames, $updateNames) = $this->prepareUpsertColumns($table, $insertColumns, $updateColumns, $constraints);
        if (empty($uniqueNames)) {
            return $this->insert($table, $insertColumns, $params);
        }

        list(, $placeholders, $values, $params) = $this->prepareInsertValues($table, $insertColumns, $params);
        $insertSql = 'INSERT OR IGNORE INTO ' . $this->db->quoteTableName($table)
            . (!empty($insertNames) ? ' (' . implode(', ', $insertNames) . ')' : '')
            . (!empty($placeholders) ? ' VALUES (' . implode(', ', $placeholders) . ')' : $values);
        if ($updateColumns === false) {
            return $insertSql;
        }

        $updateCondition = ['or'];
        $quotedTableName = $this->db->quoteTableName($table);
        foreach ($constraints as $constraint) {
            $constraintCondition = ['and'];
            foreach ($constraint->columnNames as $name) {
                $quotedName = $this->db->quoteColumnName($name);
                $constraintCondition[] = "$quotedTableName.$quotedName=(SELECT $quotedName FROM `EXCLUDED`)";
            }
            $updateCondition[] = $constraintCondition;
        }
        if ($updateColumns === true) {
            $updateColumns = [];
            foreach ($updateNames as $name) {
                $quotedName = $this->db->quoteColumnName($name);
                if (strrpos($quotedName, '.') === false) {
                    $quotedName = "(SELECT $quotedName FROM `EXCLUDED`)";
                }
                $updateColumns[$name] = new Expression($quotedName);
            }
        }
        $updateSql = 'WITH "EXCLUDED" (' . implode(', ', $insertNames)
            . ') AS (' . (!empty($placeholders) ? 'VALUES (' . implode(', ', $placeholders) . ')' : ltrim($values, ' ')) . ') '
            . $this->update($table, $updateColumns, $updateCondition, $params);
        return "$updateSql; $insertSql;";
    }
1293064
public function upgradeDatabase()
    {
        $this->refreshEntities([
            OneAssociation::class,
            ManyAssociation::class,
            AssociationEntry::class,
            Entry::class,
            Entry\Association::class,
        ]);

        // Migrate data from old entries table to new
        if ($this->connection->tableExists('ExpressEntityAssociationSelectedEntries')) {
            $this->connection->transactional(function ($db) {
                $r = $db->query('select * from ExpressEntityAssociationSelectedEntries');
                while ($row = $r->fetchRow()) {
                    $db->insert('ExpressEntityAssociationEntries', [
                        'association_id' => $row['id'], 'exEntryID' => $row['exSelectedEntryID']
                    ]);
                }
                $this->connection->Execute('alter table ExpressEntityAssociationSelectedEntries rename _ExpressEntityAssociationSelectedEntries');
            });
        }

    }
564472
public function upsert($table, $insertFieldValues, $updateFieldValues = [], $primaryKey = null)
    {
        if (!$primaryKey) {
            $primaryKey = (string)key($insertFieldValues);
        }

        if ($this->query($table)->whereEq($primaryKey, $insertFieldValues[$primaryKey])->exists()) {
            $bind = [];
            $updates = [];
            foreach ($updateFieldValues as $k => $v) {
                $field = is_string($k) ? $k : $v;
                if ($primaryKey === $field) {
                    continue;
                }

                if (is_int($k)) {
                    $updates[] = "[$field]=:$field";
                    $bind[$field] = $insertFieldValues[$field];
                } elseif ($v instanceof AssignmentInterface) {
                    $v->setFieldName($k);
                    $updates[] = $v->getSql();
                    /** @noinspection SlowArrayOperationsInLoopInspection */
                    $bind = array_merge($bind, $v->getBind());
                } else {
                    $updates[] = $v;
                }
            }
            return $this->update($table, $updates, [$primaryKey => $insertFieldValues[$primaryKey]], $bind);
        } else {
            return $this->insert($table, $insertFieldValues);
        }
    }
948971
def upsert(self, events):
        """"""
        existing = self.get_existing_keys(events)
        inserts = [e for e in events if not e[self.key] in existing]
        updates = [e for e in events if e[self.key] in existing]
        self.insert(inserts)
        self.update(updates)
492418
def create(self, name):
        """"""
        with contextlib.closing(self.database.cursor()) as cursor:
            cursor.execute('INSERT INTO users(name) VALUES (?)', (name,))
            return cursor.lastrowid
1303580
def upsert(self, doc, namespace, timestamp):
        
        database, coll = self._db_and_collection(namespace)

        meta_collection_name = self._get_meta_collection(namespace)

        self.meta_database[meta_collection_name].replace_one(
            {self.id_field: doc["_id"], "ns": namespace},
            {self.id_field: doc["_id"], "_ts": timestamp, "ns": namespace},
            upsert=True,
        )

        self.mongo[database][coll].replace_one({"_id": doc["_id"]}, doc, upsert=True)
975924
def _update(self, sock_info, criteria, document, upsert=False,
                check_keys=True, multi=False, manipulate=False,
                write_concern=None, op_id=None, ordered=True,
                bypass_doc_val=False, collation=None, array_filters=None,
                session=None, retryable_write=False):
        """"""
        common.validate_boolean("upsert", upsert)
        if manipulate:
            document = self.__database._fix_incoming(document, self)
        collation = validate_collation_or_none(collation)
        write_concern = write_concern or self.write_concern
        acknowledged = write_concern.acknowledged
        update_doc = SON([('q', criteria),
                          ('u', document),
                          ('multi', multi),
                          ('upsert', upsert)])
        if collation is not None:
            if sock_info.max_wire_version < 5:
                raise ConfigurationError(
                    'Must be connected to MongoDB 3.4+ to use collations.')
            elif not acknowledged:
                raise ConfigurationError(
                    'Collation is unsupported for unacknowledged writes.')
            else:
                update_doc['collation'] = collation
        if array_filters is not None:
            if sock_info.max_wire_version < 6:
                raise ConfigurationError(
                    'Must be connected to MongoDB 3.6+ to use array_filters.')
            elif not acknowledged:
                raise ConfigurationError(
                    'arrayFilters is unsupported for unacknowledged writes.')
            else:
                update_doc['arrayFilters'] = array_filters
        command = SON([('update', self.name),
                       ('ordered', ordered),
                       ('updates', [update_doc])])
        if not write_concern.is_server_default:
            command['writeConcern'] = write_concern.document

        if not sock_info.op_msg_enabled and not acknowledged:
            # Legacy OP_UPDATE.
            return self._legacy_write(
                sock_info, 'update', command, op_id,
                bypass_doc_val, message.update, self.__full_name, upsert,
                multi, criteria, document, False, write_concern.document,
                check_keys, self.__write_response_codec_options)

        # Update command.
        if bypass_doc_val and sock_info.max_wire_version >= 4:
            command['bypassDocumentValidation'] = True

        # The command result has to be published for APM unmodified
        # so we make a shallow copy here before adding updatedExisting.
        result = sock_info.command(
            self.__database.name,
            command,
            write_concern=write_concern,
            codec_options=self.__write_response_codec_options,
            session=session,
            client=self.__database.client,
            retryable_write=retryable_write).copy()
        _check_write_command_response(result)
        # Add the updatedExisting field for compatibility.
        if result.get('n') and 'upserted' not in result:
            result['updatedExisting'] = True
        else:
            result['updatedExisting'] = False
            # MongoDB >= 2.6.0 returns the upsert _id in an array
            # element. Break it out for backward compatibility.
            if 'upserted' in result:
                result['upserted'] = result['upserted'][0]['_id']

        if not acknowledged:
            return None
        return result
41030
def up(self):
        """"""
        with self.schema.create('users') as table:
            table.increments('id')
            table.string('name')
            table.string('email').unique()
            table.string('password')
            table.string('remember_token').nullable()
            table.timestamp('verified_at').nullable()
            table.timestamps()
512411
public UpdateResponse upsertData(Map<String, ?> source, String index,
            String type, String id) {
        return upsertQuery(buildPrepareUpsert(index, type, id, source));
    }
546745
def upgrade():
    """"""
    op.drop_constraint('fk_oauth2server_client_user_id_accounts_user',
                       'oauth2server_client', type_='foreignkey')
    op.create_foreign_key(op.f('fk_oauth2server_client_user_id_accounts_user'),
                          'oauth2server_client', 'accounts_user', ['user_id'],
                          ['id'], ondelete='CASCADE')
    op.create_index(op.f('ix_oauth2server_client_user_id'),
                    'oauth2server_client', ['user_id'], unique=False)
    op.drop_constraint('fk_oauth2server_token_user_id_accounts_user',
                       'oauth2server_token', type_='foreignkey')
    op.create_foreign_key(op.f('fk_oauth2server_token_user_id_accounts_user'),
                          'oauth2server_token', 'accounts_user', ['user_id'],
                          ['id'], ondelete='CASCADE')
    op.create_index(op.f('ix_oauth2server_token_user_id'),
                    'oauth2server_token', ['user_id'], unique=False)
    op.drop_constraint('fk_oauth2server_token_client_id_oauth2server_client',
                       'oauth2server_token', type_='foreignkey')
    op.create_foreign_key(
        op.f('fk_oauth2server_token_client_id_oauth2server_client'),
        'oauth2server_token', 'oauth2server_client', ['client_id'],
        ['client_id'], ondelete='CASCADE')
    op.create_index(op.f('ix_oauth2server_token_client_id'),
                    'oauth2server_token', ['client_id'], unique=False)
664172
public function upsert($table, $insertFieldValues, $updateFieldValues = [], $primaryKey = null)
    {
        if (!$primaryKey) {
            $primaryKey = (string)key($insertFieldValues);
        }

        if (!$updateFieldValues) {
            $updateFieldValues = $insertFieldValues;
        }

        $fields = array_keys($insertFieldValues);

        $bind = $insertFieldValues;
        $updates = [];
        foreach ($updateFieldValues as $k => $v) {
            $field = is_string($k) ? $k : $v;
            if ($primaryKey === $field) {
                continue;
            }

            if (is_int($k)) {
                $updates[] = "[$field]=:{$field}_dku";
                $bind["{$field}_dku"] = $insertFieldValues[$field];
            } elseif ($v instanceof AssignmentInterface) {
                $v->setFieldName($k);
                $updates[] = $v->getSql();
                /** @noinspection SlowArrayOperationsInLoopInspection */
                $bind = array_merge($bind, $v->getBind());
            } else {
                $updates[] = $v;
            }
        }

        $insertFieldsSql = '[' . implode('],[', $fields) . ']';
        $insertValuesSql = ':' . implode(',:', $fields);

        $updateFieldsSql = implode(',', $updates);

        $sql = 'INSERT' . " INTO {$this->_escapeIdentifier($table)}($insertFieldsSql) VALUES($insertValuesSql) ON DUPLICATE KEY UPDATE $updateFieldsSql";

        return $this->execute('insert', $sql, $bind);
    }
495689
def update(self, table_name, primary_key, instance):
        
        assert isinstance(primary_key, dict)
        assert isinstance(instance, BaseDocument)
        collection = self._db[table_name]

        # work with a copy of the document, as the direct type change of the _id field
        # is later negated by the `BaseDocument.to_json` method
        document = instance.document
        if '_id' in document:
            document['_id'] = ObjectId(document['_id'])

        update_result = collection.replace_one(filter=primary_key, replacement=document, upsert=True)
        if update_result.upserted_id:
            instance['_id'] = update_result.upserted_id
        return update_result.upserted_id
1092996
public function migrateUp()
    {
        try {
            $this->builder->table(
                $this->table,
                function ($table) {
                    $table->dropUnique('tracker_agents_name_unique');

                    $table->string('name_hash', 65)->nullable();
                }
            );

            Agent::all()->each(function ($agent) {
                $agent->name_hash = hash('sha256', $agent->name);

                $agent->save();
            });

            $this->builder->table(
                $this->table,
                function ($table) {
                    $table->unique('name_hash');
                }
            );
        } catch (\Exception $e) {
            dd($e->getMessage());
        }
    }
1169193
def init(ctx):
    ''''''

    log.info('Apply DB migrations if needed')
    ctx.invoke(migrate, record=True)

    ctx.invoke(index)

    if IS_TTY:
        text = _('Do you want to create a superadmin user?')
        if click.confirm(text, default=True):
            user = ctx.invoke(user_commands.create)
            ctx.invoke(user_commands.set_admin, email=user.email)

        text = _('Do you want to import some data-related license?')
        if click.confirm(text, default=True):
            ctx.invoke(licenses)

        text = _('Do you want to create some sample data?')
        if click.confirm(text, default=True):
            ctx.invoke(generate_fixtures)

    success(_('Your udata instance is ready!'))