batch insertion does not support pattern sql, so here we do not print pattern sql.
508936
@Override
    protected void doLogSql() {
        //here we only print prepared sql statement.
        LOG.info("Prepared SQL：" + getSqlDriver().preparedBatchInsertionSql(this).fst);
    }
279084
def insert(self, model_instances, batch_size=1000):
        '''
        
        '''
        from six import next
        from io import BytesIO
        i = iter(model_instances)
        try:
            first_instance = next(i)
        except StopIteration:
            return  # model_instances is empty
        model_class = first_instance.__class__

        if first_instance.is_read_only() or first_instance.is_system_model():
            raise DatabaseException("You can't insert into read only and system tables")

        fields_list = ','.join(
            ['`%s`' % name for name in first_instance.fields(writable=True)])

        def gen():
            buf = BytesIO()
            query = 'INSERT INTO $table (%s) FORMAT TabSeparated\n' % fields_list
            buf.write(self._substitute(query, model_class).encode('utf-8'))
            first_instance.set_database(self)
            buf.write(first_instance.to_tsv(include_readonly=False).encode('utf-8'))
            buf.write('\n'.encode('utf-8'))
            # Collect lines in batches of batch_size
            lines = 2
            for instance in i:
                instance.set_database(self)
                buf.write(instance.to_tsv(include_readonly=False).encode('utf-8'))
                buf.write('\n'.encode('utf-8'))
                lines += 1
                if lines >= batch_size:
                    # Return the current batch of lines
                    yield buf.getvalue()
                    # Start a new batch
                    buf = BytesIO()
                    lines = 0
            # Return any remaining lines in partial batch
            if lines:
                yield buf.getvalue()
        self._send(gen())
803882
def insertData(self, tablename, list_value_pairs, list_SQLCMD_pairs=None):
		
		
		fields = self._getFieldsInDB(tablename)
		
		lst_field = []
		lst_value = []
		
		# normal field-value-pairs
		for pair in list_value_pairs:
			if pair[0] in fields:
				lst_field.append( pair[0] )
				lst_value.append( '"%s"' % pair[1] )
			else:
				print "err: field %s can't be found in the table" % pair[0]
				return False
			
		# field-SQL-command-pairs: the only difference is the missing double quotes in the SQL command
		if list_SQLCMD_pairs != None:
			for pair in list_SQLCMD_pairs:
				if pair[0] in fields:
					lst_field.append( pair[0] )
					lst_value.append( pair[1] )
				else:
					print "err: field %s can't be found in the table" % pair[0]
					return False
				
		# build the command
		SQL = 'INSERT INTO %s (%s) VALUES (%s)' % ( tablename, join(lst_field, ','), join(lst_value, ',') )
		self.execQuery( SQL )
		
		return True
1951
private void batchImport() {
        m_jdbcTemplate.batchUpdate(createInsertQuery(),
                                   new BatchPreparedStatementSetter() {
                                       public void setValues(
                                               PreparedStatement ps, int i)
                                               throws SQLException {
                                           int j = 1;
                                           for (String property : m_propertyNames) {
                                               Map params = (Map) m_batch.get(
                                                       i);
                                               ps.setObject(j++, params.get(
                                                       property));
                                           }
                                       }

                                       public int getBatchSize() {
                                           return m_batch.size();
                                       }
                                   });
    }
349288
public static int[] batch(@Nullable PreparedStatement stmt) throws SQLException {
		int[] rows = EMPTY_INT_ARRAY;
		if (stmt != null) {
			rows = stmt.executeBatch();
			stmt.close();
		}
		return rows;
	}
813670
def get_sql_insert_without_first_field(
        table: str,
        fieldlist: Sequence[str],
        delims: Tuple[str, str] = ("", "")) -> str:
    """"""
    return get_sql_insert(table, fieldlist[1:], delims)
1065069
public static <T, E extends Exception> long importData(final Iterator<T> iter, long offset, final long count, final Try.Predicate<? super T, E> filter,
            final PreparedStatement stmt, final int batchSize, final int batchInterval,
            final Try.BiConsumer<? super PreparedStatement, ? super T, SQLException> stmtSetter) throws UncheckedSQLException, E {
        N.checkArgument(offset >= 0 && count >= 0, "'offset'=%s and 'count'=%s can't be negative", offset, count);
        N.checkArgument(batchSize > 0 && batchInterval >= 0, "'batchSize'=%s must be greater than 0 and 'batchInterval'=%s can't be negative", batchSize,
                batchInterval);

        long result = 0;

        try {
            while (offset-- > 0 && iter.hasNext()) {
                iter.next();
            }
            T next = null;
            while (result < count && iter.hasNext()) {
                next = iter.next();

                if (filter != null && filter.test(next) == false) {
                    continue;
                }

                stmtSetter.accept(stmt, next);
                stmt.addBatch();

                if ((++result % batchSize) == 0) {
                    stmt.executeBatch();
                    stmt.clearBatch();

                    if (batchInterval > 0) {
                        N.sleep(batchInterval);
                    }
                }
            }

            if ((result % batchSize) > 0) {
                stmt.executeBatch();
                stmt.clearBatch();
            }
        } catch (SQLException e) {
            throw new UncheckedSQLException(e);
        }

        return result;
    }
448199
private static List<ArrayParameter> arrayParametersSortedAsc(Map<String, List<Integer>> parameterNamesToIndexes,
                                                                 Map<String, Query.ParameterSetter> parameters,
                                                                 boolean allowArrayParameters) {
        List<ArrayParameters.ArrayParameter> arrayParameters = new ArrayList<>();
        for(Map.Entry<String, Query.ParameterSetter> parameter : parameters.entrySet()) {
            if (parameter.getValue().parameterCount > 1) {
                if (!allowArrayParameters) {
                    throw new Sql2oException("Array parameters are not allowed in batch mode");
                }
                for(int i : parameterNamesToIndexes.get(parameter.getKey())) {
                    arrayParameters.add(new ArrayParameters.ArrayParameter(i, parameter.getValue().parameterCount));
                }
            }
        }
        Collections.sort(arrayParameters);

        return arrayParameters;
    }
697855
private StringBuilder appendPagingSortSQL(final StringBuilder sql, final Post.Sort sort,final Paging paging) {

      if(paging.interval != null) {
         sql.append(" AND post_date");
         sql.append(paging.startIsOpen ? " >" : " >=");
         sql.append("?");

         sql.append(" AND post_date");
         sql.append(paging.endIsOpen ? " <" : " <=");
         sql.append("?");
      }

      switch(sort) {
         case ASC:
            sql.append(" ORDER BY post_date ASC");
            break;
         case DESC:
            sql.append(" ORDER BY post_date DESC");
            break;
         case ASC_MOD:
            sql.append(" ORDER BY post_modified ASC");
            break;
         case DESC_MOD:
            sql.append(" ORDER BY post_modified DESC");
            break;
         case ID_ASC:
            sql.append(" ORDER BY ID ASC");
            break;
         case ID_DESC:
            sql.append(" ORDER BY ID DESC");
            break;
         default:
            sql.append(" ORDER BY post_date DESC");
            break;
      }
      sql.append(" LIMIT ?,?");
      return sql;
   }
1221959
def _batch_insert(self, inserts, intervals, **kwargs):
    '''
    
    '''
    updates = {}
    # TODO support flush interval
    for interval,config in self._intervals.items():
      for timestamp,names in inserts.iteritems():
        timestamps = self._normalize_timestamps(timestamp, intervals, config)
        for name,values in names.iteritems():
          for value in values:
            for tstamp in timestamps:
              query,insert = self._insert_data(
                name, value, tstamp, interval, config, dry_run=True)

              batch_key = self._batch_key(query)
              updates.setdefault(batch_key, {'query':query, 'interval':interval})
              new_insert = self._batch(insert, updates[batch_key].get('insert'))
              updates[batch_key]['insert'] = new_insert

    # now that we've collected a bunch of updates, flush them out
    for spec in updates.values():
      self._client[ spec['interval'] ].update(
        spec['query'], spec['insert'], upsert=True, check_keys=False )
1134676
def replace_nil_binds(sql, args)
      nils = []
      args.each_with_index { |value, i| nils << i if value.nil? }
      unless nils.empty? then
        logger.debug { "SQL executor working around RDBI bug by eliminating the nil arguments #{nils.to_series} for the SQL:\n#{sql}..." }
        # Quoted ? is too much of a pain for this hack; bail out.
        raise ArgumentError.new("RDBI work-around does not support quoted ? in transactional SQL: #{sql}") if sql =~ /'[^,]*[?][^,]*'/
        prefix, binds_s, suffix = /(.+\s*values\s*\()([^)]*)(\).*)/i.match(sql).captures
        sql = prefix
        binds = binds_s.split('?')
        last = binds_s[-1, 1]
        del_cnt = 0
        binds.each_with_index do |s, i|
          sql << s
          if nils.include?(i) then
            args.delete_at(i - del_cnt)
            del_cnt += 1
            sql << 'NULL'
          elsif i < binds.size - 1 or last == '?'
            sql << '?'
          end
        end
        sql << suffix
      end
      logger.debug { "SQL executor converted the SQL to:\n#{sql}\nwith arguments #{args.qp}" }
      return args.unshift(sql)
    end
441099
private boolean isSQLErrorTransient(SQLException sqlex) {
        if (tc.isEntryEnabled())
            Tr.entry(tc, "isSQLErrorTransient ", new Object[] { sqlex, this });
        boolean retryBatch = false;
        int sqlErrorCode = sqlex.getErrorCode();

        if (tc.isEventEnabled()) {
            Tr.event(tc, " SQL exception:");
            Tr.event(tc, " Message: " + sqlex.getMessage());
            Tr.event(tc, " SQLSTATE: " + sqlex.getSQLState());
            Tr.event(tc, " Error code: " + sqlErrorCode);
        }

        for (int transientCode : _sqlTransientErrorCodes) {
            Tr.event(tc, "Test against stored code: " + transientCode);
            if (transientCode == sqlErrorCode) {
                Tr.event(tc, "TRANSIENT: A connection failed but could be reestablished, retry.");
                retryBatch = true;
                break;
            }
        }

        if (!retryBatch && sqlex instanceof BatchUpdateException) {
            BatchUpdateException buex = (BatchUpdateException) sqlex;
            Tr.event(tc, "BatchUpdateException: Update Counts - ");
            int[] updateCounts = buex.getUpdateCounts();
            for (int i = 0; i < updateCounts.length; i++) {
                Tr.event(tc, "   Statement " + i + ":" + updateCounts[i]);
            }
            SQLException nextex = buex.getNextException();
            while (nextex != null) {
                sqlErrorCode = nextex.getErrorCode();
                if (tc.isEventEnabled()) {
                    Tr.event(tc, " SQL exception:");
                    Tr.event(tc, " Message: " + nextex.getMessage());
                    Tr.event(tc, " SQLSTATE: " + nextex.getSQLState());

                    Tr.event(tc, " Error code: " + sqlErrorCode);
                }

                for (int transientCode : _sqlTransientErrorCodes) {
                    Tr.event(tc, "Test against stored code: " + transientCode);
                    if (transientCode == sqlErrorCode) {
                        Tr.event(tc, "TRANSIENT: A connection failed but could be reestablished, retry.");
                        retryBatch = true;
                        break;
                    }
                }

                nextex = nextex.getNextException();
            }
        }

        if (tc.isEntryEnabled())
            Tr.exit(tc, "isSQLErrorTransient", retryBatch);
        return retryBatch;
    }
94738
@Override
	public int[] executeBatch() throws SQLException {
		Split s = prepare(batchSql);
		try {
			return stmt.executeBatch();
		} finally {
			finish(s);
		}
	}
501809
@Override
    public String prepareBatchQuery(List<String> statements) {

        StringBuilder sb = new StringBuilder("BEGIN BATCH \n");

        for (String statement : statements) {
            sb.append(statement).append("\n");
        }

        sb.append(" APPLY BATCH;");

        return sb.toString();
    }
1201542
def _print_sql_with_error(self, sql, error_line):
        
        if os.linesep in sql:
            lines = sql.split(os.linesep)
            digits = math.ceil(math.log(len(lines) + 1, 10))
            i = 1
            for line in lines:
                if i == error_line:
                    self._io.text('<error>{0:{width}} {1}</error>'.format(i, line, width=digits, ))
                else:
                    self._io.text('{0:{width}} {1}'.format(i, line, width=digits, ))
                i += 1
        else:
            self._io.text(sql)
543357
def dump(file_name, pattern):
    
    db = XonoticDB.load_path(file_name)
    items = sorted(db.filter(pattern), key=lambda x: natural_sort_key(x[0]))
    for k, v in items:
        click.echo('%s: %s' % (k, v))
1036746
def as_sql(self, qn, connection):
        
        engine = connection.settings_dict['ENGINE'].rsplit('.', -1)[-1]
        if engine.startswith('postgres'):
            XOR_OPERATOR = '#'
        elif engine.startswith('sqlite'):
            raise NotImplementedError
        else:
            XOR_OPERATOR = '^'

        if self.bit:
            return ("%s.%s | %d" % (qn(self.table_alias), qn(self.column), self.bit.mask),
                    [])
        return ("%s.%s %s %d" % (qn(self.table_alias), qn(self.column), XOR_OPERATOR, self.bit.mask),
                [])