Add the given name record to the database,
    if it doesn't exist already.
481080
def namedb_name_insert( cur, input_name_rec ):
    
   
    name_rec = copy.deepcopy( input_name_rec )
    namedb_name_fields_check( name_rec )

    try:
        query, values = namedb_insert_prepare( cur, name_rec, "name_records" )
    except Exception, e:
        log.exception(e)
        log.error("FATAL: Failed to insert name '%s'" % name_rec['name'])
        os.abort()

    namedb_query_execute( cur, query, values )

    return True
1000625
def declare(self, name):
        

        if name in self._data:
            raise KeyError("Declared name {} that already existed".format(name))

        self._data[name] = self._loop.create_future()
892885
def present(name, character_set=None, collate=None, **connection_args):
    '''
    
    '''
    ret = {'name': name,
           'changes': {},
           'result': True,
           'comment': 'Database {0} is already present'.format(name)}
    # check if database exists
    existing = __salt__['mysql.db_get'](name, **connection_args)
    if existing:
        alter = False
        if character_set and character_set != existing.get('character_set'):
            log.debug('character set differes from %s : %s',
                      character_set, existing.get('character_set'))
            alter = True
        if collate and collate != existing.get('collate'):
            log.debug('collate set differs from %s : %s',
                      collate, existing.get('collate'))
            alter = True
        if alter:
            __salt__['mysql.alter_db'](
                name, character_set=character_set, collate=collate,
                **connection_args)
        current = __salt__['mysql.db_get'](name, **connection_args)
        if existing.get('collate', None) != current.get('collate', None):
            ret['changes'].update({'collate': {
                'before': existing.get('collate', None),
                'now': current.get('collate', None)}})
        if existing.get('character_set', None) != current.get('character_set', None):
            ret['changes'].update({'character_set': {
                'before': existing.get('character_set', None),
                'now': current.get('character_set', None)}})
        return ret
    else:
        err = _get_mysql_error()
        if err is not None:
            ret['comment'] = err
            ret['result'] = False
            return ret

    if __opts__['test']:
        ret['result'] = None
        ret['comment'] = ('Database {0} is not present and needs to be created'
                ).format(name)
        return ret
    # The database is not present, make it!
    if __salt__['mysql.db_create'](
            name, character_set=character_set, collate=collate,
            **connection_args):
        ret['comment'] = 'The database {0} has been created'.format(name)
        ret['changes'][name] = 'Present'
    else:
        ret['comment'] = 'Failed to create database {0}'.format(name)
        err = _get_mysql_error()
        if err is not None:
            ret['comment'] += ' ({0})'.format(err)
        ret['result'] = False

    return ret
1320599
def _update_record_with_name(self, old_record, rtype, new_name, content):
        """"""
        new_type = rtype if rtype else old_record['type']

        new_ttl = self._get_lexicon_option('ttl')
        if new_ttl is None and 'ttl' in old_record:
            new_ttl = old_record['ttl']

        new_priority = self._get_lexicon_option('priority')
        if new_priority is None and 'priority' in old_record:
            new_priority = old_record['priority']

        new_content = content
        if new_content is None and 'content' in old_record:
            new_content = old_record['content']

        record = self._create_request_record(None,
                                             new_type,
                                             new_name,
                                             new_content,
                                             new_ttl,
                                             new_priority)

        # This will be a different domain name, so no name collision should
        # happen. First create a new entry and when it succeeds, delete the old
        # one.
        self._request_add_dns_record(record)
        self._request_delete_dns_record_by_id(old_record['id'])
533923
def _add_or_update_records(cls, conn: Connection, table: Table,
                               records: List["I2B2CoreWithUploadId"]) -> Tuple[int, int]:
        
        num_updates = 0
        num_inserts = 0
        inserts = []
        # Iterate over the records doing updates
        # Note: This is slow as molasses - definitely not optimal for batch work, but hopefully we'll be dealing with
        #    thousands to tens of thousands of records.  May want to move to ORM model if this gets to be an issue
        for record in records:
            keys = [(table.c[k] == getattr(record, k)) for k in cls.key_fields]
            key_filter = I2B2CoreWithUploadId._nested_fcn(and_, keys)
            rec_exists = conn.execute(select([table.c.upload_id]).where(key_filter)).rowcount
            if rec_exists:
                known_values = {k: v for k, v in as_dict(record).items()
                                if v is not None and k not in cls._no_update_fields and
                                k not in cls.key_fields}
                vals = [table.c[k] != v for k, v in known_values.items()]
                val_filter = I2B2CoreWithUploadId._nested_fcn(or_, vals)
                known_values['update_date'] = record.update_date
                upd = update(table).where(and_(key_filter, val_filter)).values(known_values)
                num_updates += conn.execute(upd).rowcount
            else:
                inserts.append(as_dict(record))
        if inserts:
            if cls._check_dups:
                dups = cls._check_for_dups(inserts)
                nprints = 0
                if dups:
                    print("{} duplicate records encountered".format(len(dups)))
                    for k, vals in dups.items():
                        if len(vals) == 2 and vals[0] == vals[1]:
                            inserts.remove(vals[1])
                        else:
                            if nprints < 20:
                                print("Key: {} has a non-identical dup".format(k))
                            elif nprints == 20:
                                print(".... more ...")
                            nprints += 1
                            for v in vals[1:]:
                                inserts.remove(v)
            # TODO: refactor this to load on a per-resource basis.  Temporary fix
            for insert in ListChunker(inserts, 500):
                num_inserts += conn.execute(table.insert(), insert).rowcount
        return num_inserts, num_updates
873061
def add_object(self, object):
        """"""
        if object.id is None:
            object.get_id()
        self.db.engine.save(object)
1294689
def new_table(self, name, add_id=True, **kwargs):
        '''
        '''
        from . import Table
        from .exc import NotFoundError

        try:
            table = self.table(name)
            extant = True
        except NotFoundError:

            extant = False

            if 'sequence_id' not in kwargs:
                kwargs['sequence_id'] = self._database.next_sequence_id(Dataset, self.vid, Table)

            table = Table(name=name, d_vid=self.vid, **kwargs)

            table.update_id()

        # Update possibly extant data
        table.data = dict(
            (list(table.data.items()) if table.data else []) + list(kwargs.get('data', {}).items()))

        for key, value in list(kwargs.items()):

            if not key:
                continue
            if key[0] != '_' and key not in ['vid', 'id', 'id_', 'd_id', 'name', 'sequence_id', 'table', 'column', 'data']:
                setattr(table, key, value)

        if add_id:
            table.add_id_column()

        if not extant:
            self.tables.append(table)

        return table
887675
def name_insert_prefix(records, prefix):
    
    logging.info('Applying _name_insert_prefix generator: '
                 'Inserting prefix ' + prefix + ' for all '
                 'sequence IDs.')
    for record in records:
        new_id = prefix + record.id
        _update_id(record, new_id)
        yield record
161892
def create_db(name, **client_args):
    '''
    
    '''
    if db_exists(name, **client_args):
        log.info('DB \'%s\' already exists', name)
        return False

    client = _client(**client_args)
    client.create_database(name)

    return True
511381
def add_names(self, tax_id, names, execute=True):
        

        primary_names = [n['tax_name'] for n in names if n.get('is_primary')]
        if len(primary_names) > 1:
            raise ValueError(
                '`is_primary` may be True for no more than one name in `names`')

        statements = []

        for namevals in names:
            if 'tax_id' in namevals:
                del namevals['tax_id']
            statements.extend(
                self.add_name(tax_id=tax_id, execute=False, **namevals))

        if execute:
            self.execute(statements)
        else:
            return statements
492418
def create(self, name):
        """"""
        with contextlib.closing(self.database.cursor()) as cursor:
            cursor.execute('INSERT INTO users(name) VALUES (?)', (name,))
            return cursor.lastrowid
1320627
public void add(Rec record) throws DBException
    {
        if (this.getRecord().getEditMode() != Constants.EDIT_ADD)
            throw new DBException(Constants.INVALID_RECORD);
        m_record = (FieldList)record;
        this.fieldsToData(record);
        this.doAdd(record);
        this.setDataSource(null);
        this.getRecord().setEditMode(Constants.EDIT_NONE);
    }
150783
private function AddNameField()
    {
        $name = 'Name';
        $this->AddField(Input::Text($name, $this->page->GetName()));
        $this->SetRequired($name);
        $this->AddValidator($name, DatabaseCount::UniqueFieldAnd($this->page, $name, $this->SiteCondition()));
    }
324412
def add(self, record):
        """"""
        self._field.validate_value(record)
        self._elements[record.id] = record
        self._sync_field()
1288121
def _create_record(self, rtype, name, content):
        """"""
        if not self._list_records(rtype, name, content):
            self._update_records([{}], {
                'type': rtype,
                'hostname': self._relative_name(name),
                'destination': content,
                'priority': self._get_lexicon_option('priority'),
            })
        LOGGER.debug('create_record: %s', True)
        return True
1118297
def update_record(self, name, new_data, condition, update_only=False,
                      debug=False):
        
        # add numeric index column temporarily
        self.df['num'] = list(range(len(self.df)))
        df_data = self.df
        condition2 = (df_data.index == name)
        # edit first of existing data that meets condition
        if len(df_data[condition & condition2]) > 0:  #we have one or more records to update or delete
            # list of all rows where condition is true and index == name
            inds = df_data[condition & condition2]['num']
            #inds = df_data[condition]['num'] # list of all rows where condition is true
            existing_data = dict(df_data.iloc[inds.iloc[0]]) # get first record of existing_data from dataframe
            existing_data.update(new_data) # update existing data with new interpretations
            # update row
            self.update_row(inds.iloc[0], existing_data)
            # now remove all the remaining records of same condition
            if len(inds) > 1:
                for ind in inds[1:]:
                    print("deleting redundant records for:", name)
                    df_data = self.delete_row(ind)
        else:
            if update_only:
                print("no record found for that condition, not updating ", name)
            else:
                print('no record found - creating new one for ', name)
                # add new row
                df_data = self.add_row(name, new_data)
        # sort so that all rows for an item are together
        df_data.sort_index(inplace=True)
        # redo temporary index
        df_data['num'] = list(range(len(df_data)))
        self.df = df_data
        return df_data
628546
def add_record(cls, fqdn, name, type, value, ttl):
        """"""
        data = {
            "rrset_name": name,
            "rrset_type": type,
            "rrset_values": value,
        }
        if ttl:
            data['rrset_ttl'] = int(ttl)
        meta = cls.get_fqdn_info(fqdn)
        url = meta['domain_records_href']
        return cls.json_post(url, data=json.dumps(data))