Backward compatibility helper for insert error handling.
353094
def _raise_last_error(bulk_write_result):
    
    # Prefer write errors over write concern errors
    write_errors = bulk_write_result.get("writeErrors")
    if write_errors:
        _raise_last_write_error(write_errors)

    _raise_write_concern_error(bulk_write_result["writeConcernErrors"][-1])
658926
function safeInsert(root, curr, next) {
      root.insertBefore(curr, next.parentNode && next);
    }
9553
def make_err(self, errtype, message, original, loc, ln=None, reformat=True, *args, **kwargs):
        """"""
        if ln is None:
            ln = self.adjust(lineno(loc, original))
        errstr, index = getline(loc, original), col(loc, original) - 1
        if reformat:
            errstr, index = self.reformat(errstr, index)
        return errtype(message, errstr, index, ln, *args, **kwargs)
630655
def _construct_inserts(self, record, new_columns, rename_columns, retype_columns, resize_columns):

        '''  '''

        insert_kwargs = {}

        for key, value in new_columns.items():

        # retrieve value for key (or from old key name)
            if key in rename_columns.keys():
                record_value = getattr(record, rename_columns[key], None)
            else:
                record_value = getattr(record, key, None)

        # attempt to convert datatype
            if record_value:
                if key in retype_columns.keys():
                    try:
                        old_list = False
                        if isinstance(record_value, bytes):
                            record_value = pickle.loads(record_value)
                            old_list = True
                        if retype_columns[key] == 'boolean':
                            record_value = bool(record_value)
                        elif retype_columns[key] == 'string':
                            if old_list:
                                record_value = ','.join(record_value)
                            else:
                                record_value = str(record_value)
                        elif retype_columns[key] == 'integer':
                            if old_list:
                                record_value = int(record_value[0])
                            else:
                                record_value = int(record_value)
                        elif retype_columns[key] == 'float':
                            if old_list:
                                record_value = int(record_value[0])
                            else:
                                record_value = float(record_value)
                        elif retype_columns[key] == 'list':
                            if isinstance(record_value, str):
                                record_value = pickle.dumps(record_value.split(','))
                            else:
                                record_value = pickle.dumps([record_value])
                    except:
                        record_value = None
        
        # attempt to resize string data 
                if key in resize_columns.keys():
                    max_length = resize_columns[key]
                    try:
                        if len(record_value) > max_length:
                            record_value = record_value[0:max_length]
                    except:
                        record_value = None

                insert_kwargs[key] = record_value

        return insert_kwargs
11104
def _onError(self, message):
        """"""
        self.isOK = False
        if message.strip() != "":
            self.errors.append(message)
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
1089766
def insert_statement(table, columns, values):
    """"""
    if not all(isinstance(r, (list, set, tuple)) for r in values):
        values = [[r] for r in values]
    rows = []
    for row in values:
        new_row = []
        for col in row:
            if col is None:
                new_col = 'NULL'
            elif isinstance(col, (int, float, Decimal)):
                new_col = str(MySQLConverterBase().to_mysql(col))
            else:
                string = str(MySQLConverterBase().to_mysql(col))
                if "'" in string:
                    new_col = '"' + string + '"'
                else:
                    new_col = "'" + string + "'"
            new_row.append(new_col)
        rows.append(', '.join(new_row))
    vals = '(' + '),\n\t('.join(rows) + ')'
    statement = "INSERT INTO\n\t{0} ({1}) \nVALUES\n\t{2}".format(wrap(table), cols_str(columns), vals)
    return statement
86937
def __insert_wrapper(func):
        """"""
        def check_func(self, key, new_item, instance=0):
            if key not in self.keys():
                raise KeyError("%s not a key in label" % (key))
            if not isinstance(new_item, (list, OrderedMultiDict)):
                raise TypeError("The new item must be a list or PVLModule")
            if isinstance(new_item, OrderedMultiDict):
                new_item = list(new_item)
            return func(self, key, new_item, instance)
        return check_func
589560
def pattern_error(self, original, loc, value_var, check_var):
        """"""
        base_line = clean(self.reformat(getline(loc, original)))
        line_wrap = self.wrap_str_of(base_line)
        repr_wrap = self.wrap_str_of(ascii(base_line))
        return (
            "if not " + check_var + ":\n" + openindent
            + match_err_var + ' = _coconut_MatchError("pattern-matching failed for " '
            + repr_wrap + ' " in " + _coconut.repr(_coconut.repr(' + value_var + ")))\n"
            + match_err_var + ".pattern = " + line_wrap + "\n"
            + match_err_var + ".value = " + value_var
            + "\nraise " + match_err_var + "\n" + closeindent
        )
860106
private static void handleSQLException(SQLException e, String poolName, String sql) {

    YankSQLException yankSQLException = new YankSQLException(e, poolName, sql);

    if (throwWrappedExceptions) {
      throw yankSQLException;
    } else {
      logger.error(yankSQLException.getMessage(), yankSQLException);
    }
  }
1315244
def visit_insert(self, insert_stmt, asfrom=False, **kw):
        

        self.stack.append(
            {'correlate_froms': set(),
             "asfrom_froms": set(),
             "selectable": insert_stmt})

        self.isinsert = True
        crud_params = crud._get_crud_params(self, insert_stmt, **kw)

        if not crud_params and \
                not self.dialect.supports_default_values and \
                not self.dialect.supports_empty_insert:
            raise NotImplementedError(
                "The '%s' dialect with current database version settings does "
                "not support empty inserts." % self.dialect.name)

        if insert_stmt._has_multi_parameters:
            if not self.dialect.supports_multivalues_insert:
                raise NotImplementedError(
                    "The '%s' dialect with current database "
                    "version settings does not support "
                    "in-place multirow inserts." % self.dialect.name)
            crud_params_single = crud_params[0]
        else:
            crud_params_single = crud_params

        preparer = self.preparer
        supports_default_values = self.dialect.supports_default_values

        text = "INSERT "

        if insert_stmt._prefixes:
            text += self._generate_prefixes(insert_stmt,
                                            insert_stmt._prefixes, **kw)

        text += "INTO "
        table_text = preparer.format_table(insert_stmt.table)

        if insert_stmt._hints:
            dialect_hints = dict([
                (table, hint_text)
                for (table, dialect), hint_text in
                insert_stmt._hints.items()
                if dialect in ('*', self.dialect.name)
            ])
            if insert_stmt.table in dialect_hints:
                table_text = self.format_from_hint_text(
                    table_text,
                    insert_stmt.table,
                    dialect_hints[insert_stmt.table],
                    True
                )

        text += table_text

        if crud_params_single or not supports_default_values:
            text += " (%s)" % ', '.join([preparer.format_column(c[0])
                                         for c in crud_params_single])

        if self.returning or insert_stmt._returning:
            self.returning = self.returning or insert_stmt._returning
            returning_clause = self.returning_clause(
                insert_stmt, self.returning)

            if self.returning_precedes_values:
                text += " " + returning_clause

        if insert_stmt.select is not None:
            text += " (%s)" % self.process(self._insert_from_select, **kw)
        elif not crud_params and supports_default_values:
            text += " DEFAULT VALUES"
        elif insert_stmt._has_multi_parameters:
            text += " VALUES %s" % (
                ", ".join(
                    "(%s)" % (
                        ', '.join(c[1] for c in crud_param_set)
                    )
                    for crud_param_set in crud_params
                )
            )
        else:
            text += " VALUES (%s)" % \
                ', '.join([c[1] for c in crud_params])

        if self.returning and not self.returning_precedes_values:
            text += " " + returning_clause

        self.stack.pop(-1)

        return text
1369861
private void addErrorCorrection(StringBuilder adjustedString, int codewordSize, int dataBlocks, int eccBlocks) {

        int x, poly, startWeight;

        /* Split into codewords and calculate Reed-Solomon error correction codes */
        switch (codewordSize) {
            case 6:
                x = 32;
                poly = 0x43;
                startWeight = 0x20;
                break;
            case 8:
                x = 128;
                poly = 0x12d;
                startWeight = 0x80;
                break;
            case 10:
                x = 512;
                poly = 0x409;
                startWeight = 0x200;
                break;
            case 12:
                x = 2048;
                poly = 0x1069;
                startWeight = 0x800;
                break;
            default:
                throw new OkapiException("Unrecognized codeword size: " + codewordSize);
        }

        ReedSolomon rs = new ReedSolomon();
        int[] data = new int[dataBlocks + 3];
        int[] ecc = new int[eccBlocks + 3];

        for (int i = 0; i < dataBlocks; i++) {
            for (int weight = 0; weight < codewordSize; weight++) {
                if (adjustedString.charAt((i * codewordSize) + weight) == '1') {
                    data[i] += (x >> weight);
                }
            }
        }

        rs.init_gf(poly);
        rs.init_code(eccBlocks, 1);
        rs.encode(dataBlocks, data);

        for (int i = 0; i < eccBlocks; i++) {
            ecc[i] = rs.getResult(i);
        }

        for (int i = (eccBlocks - 1); i >= 0; i--) {
            for (int weight = startWeight; weight > 0; weight = weight >> 1) {
                if ((ecc[i] & weight) != 0) {
                    adjustedString.append('1');
                } else {
                    adjustedString.append('0');
                }
            }
        }
    }
756963
def upsert(self, table, value, update_columns=None, commit=True):
        
        if not isinstance(value, dict):
            raise TypeError('Input value should be a dictionary')

        if not update_columns:
            update_columns = value.keys()

        value_q, _args = self._value_parser(value, columnname=False)

        _sql = ''.join(['INSERT INTO ', self._backtick(table), ' (', self._backtick_columns(value), ') VALUES ',
                        '(', value_q, ') ',
                        'ON DUPLICATE KEY UPDATE ',
                        ', '.join(['='.join([k, 'VALUES('+k+')']) for k in update_columns]), ';'])

        if self.debug:
            return self.cur.mogrify(_sql, _args)

        self.cur.execute(_sql, _args)
        if commit:
            self.conn.commit()
        return self.cur.lastrowid
1299027
def insert(dbconn, packet):
    """"""
    values = [ ]
    pd     = packet._defn

    for defn in pd.fields:
        if defn.enum:
            val = getattr(packet.raw, defn.name)
        else:
            val = getattr(packet, defn.name)

        if val is None and defn.name in pd.history:
            val = getattr(packet.history, defn.name)

        values.append(val)

    qmark = ['?'] * len(values)
    sql   = 'INSERT INTO %s VALUES (%s)' % (pd.name, ', '.join(qmark))

    dbconn.execute(sql, values)
124887
function insertIntoDB() {
                    lastQry = connection.query('INSERT INTO ?? SET ?', [req.params.table , insertJson] , function (err, rows) {
                        if (err) {
                            console.error(err);
                            res.statusCode = 500;
                            res.send({
                                result: 'error',
                                err: err.code
                            });
                        } else {
                            sendSuccessAnswer(req.params.table , res, rows.insertId);
                        }

                    });
                }
294837
def _handle_upsert(self, parts, unwritten_lobs=()):
        """"""
        self.description = None
        self._received_last_resultset_part = True  # set to 'True' so that cursor.fetch*() returns just empty list

        for part in parts:
            if part.kind == part_kinds.ROWSAFFECTED:
                self.rowcount = part.values[0]
            elif part.kind in (part_kinds.TRANSACTIONFLAGS, part_kinds.STATEMENTCONTEXT, part_kinds.PARAMETERMETADATA):
                pass
            elif part.kind == part_kinds.WRITELOBREPLY:
                # This part occurrs after lobs have been submitted not at all or only partially during an insert.
                # In this case the parameter part of the Request message contains a list called 'unwritten_lobs'
                # with LobBuffer instances.
                # Those instances are in the same order as 'locator_ids' received in the reply message. These IDs
                # are then used to deliver the missing LOB data to the server via WRITE_LOB_REQUESTs.
                for lob_buffer, lob_locator_id in izip(unwritten_lobs, part.locator_ids):
                    # store locator_id in every lob buffer instance for later reference:
                    lob_buffer.locator_id = lob_locator_id
                self._perform_lob_write_requests(unwritten_lobs)
            else:
                raise InterfaceError("Prepared insert statement response, unexpected part kind %d." % part.kind)
        self._executed = True
935415
def insert(self):
    """"""
    if not self.curs:
      raise LIGOLwDBError, "Database connection not initalized"
    if len(self.table) == 0:
      raise LIGOLwDBError, 'attempt to insert empty table'
    for tab in self.table.keys():
      # find and add any missing unique ids
      generate = []
      missingcols = [k for k in self.ldb.uniqueids[tab] 
        if k not in self.table[tab]['column']]
      for m in missingcols:
        generate.append(',BLOB(GENERATE_UNIQUE())')
        self.table[tab]['orderedcol'].append(m)
      # and construct the sql query
      self.table[tab]['query'] = ' '.join( 
        ['INSERT INTO', tab, '(', ','.join(self.table[tab]['orderedcol']), 
        ') VALUES (', ','.join(['?' for x in self.table[tab]['column']]) , 
        ''.join(generate), ')'])
    for tabtup in self.ldb.tables:
      tab = tabtup[0].lower()
      try:
        try: 
          self.curs.executemany(self.table[tab]['query'],
            self.table[tab]['stream'])
          rowcount = self.curs.rowcount
        except DB2.Error, e:
          self.curs.execute('rollback')
          msg = e[2] 
          msg += self.xml() + '\n' 
          msg += str(self.table[tab]['query']) + '\n' 
          msg += str(self.table[tab]['stream']) + '\n'
          raise LIGOLwDBError, msg
        except DB2.Warning, e:
          self.curs.execute('rollback')
          raise LIGOLwDBError, e[2]
        #except Exception, e:
        #  self.curs.execute('rollback')
        #  raise LIGOLwDBError, e[2]
      except KeyError:
        pass
    self.curs.execute('commit')
    return rowcount