Exports the data from database to CVS.

@param out
@param conn
@param querySQL
@param offset
@param count
@param writeTitle
@param quoted
@return
358436
public static long exportCSV(final File out, final Connection conn, final String querySQL, final long offset, final long count, final boolean writeTitle,
            final boolean quoted) throws UncheckedSQLException, UncheckedIOException {
        return exportCSV(out, conn, querySQL, null, offset, count, writeTitle, quoted);
    }
1368994
def copy_from_csv_sql(qualified_name: str, delimiter=',', encoding='utf8',
                      null_str='', header=True, escape_str='\\', quote_char='"',
                      force_not_null=None, force_null=None):
    """"""

    options = []
    options.append("DELIMITER '%s'" % delimiter)
    options.append("NULL '%s'" % null_str)

    if header:
        options.append('HEADER')

    options.append("QUOTE '%s'" % quote_char)
    options.append("ESCAPE '%s'" % escape_str)

    if force_not_null:
        options.append(_format_force_not_null(column_names=force_not_null))

    if force_null:
        options.append(_format_force_null(column_names=force_null))

    postgres_encoding = get_postgres_encoding(encoding)
    options.append("ENCODING '%s'" % postgres_encoding)

    copy_sql = _format_copy_csv_sql(qualified_name, copy_options=options)

    return copy_sql
1168803
public static void writeCsv(final ResultStream<GraphObject> result, final Writer out, final String propertyView) throws IOException {

		final StringBuilder row      = new StringBuilder();
		boolean headerWritten        = false;

		for (final GraphObject obj : result) {

			// Write column headers
			if (!headerWritten) {

				row.setLength(0);

				for (PropertyKey key : obj.getPropertyKeys(propertyView)) {

					row.append("\"").append(key.dbName()).append("\"").append(DEFAULT_FIELD_SEPARATOR);
				}

				// remove last ;
				int pos = row.lastIndexOf("" + DEFAULT_FIELD_SEPARATOR);
				if (pos >= 0) {

					row.deleteCharAt(pos);
				}

				// append DOS-style line feed as defined in RFC 4180
				out.append(row).append("\r\n");

				// flush each line
				out.flush();

				headerWritten = true;

			}

			row.setLength(0);

			for (PropertyKey key : obj.getPropertyKeys(propertyView)) {

				Object value = obj.getProperty(key);

				row.append("\"").append((value != null
					? escapeForCsv(value)
					: "")).append("\"").append(DEFAULT_FIELD_SEPARATOR);

			}

			// remove last ;
			row.deleteCharAt(row.lastIndexOf("" + DEFAULT_FIELD_SEPARATOR));
			out.append(row).append("\r\n");

			// flush each line
			out.flush();
		}

	}
820679
def export_as_string(self):
        
        cql = "\n\n".join([self.as_cql_query() + ';'] +
                          self.user_type_strings() +
                          [f.export_as_string() for f in self.functions.values()] +
                          [a.export_as_string() for a in self.aggregates.values()] +
                          [t.export_as_string() for t in self.tables.values()])
        if self._exc_info:
            import traceback
            ret = "/*\nWarning: Keyspace %s is incomplete because of an error processing metadata.\n" % \
                  (self.name)
            for line in traceback.format_exception(*self._exc_info):
                ret += line
            ret += "\nApproximate structure, for reference:\n(this should not be used to reproduce this schema)\n\n%s\n*/" % cql
            return ret
        if self.virtual:
            return ("/*\nWarning: Keyspace {ks} is a virtual keyspace and cannot be recreated with CQL.\n"
                    "Structure, for reference:*/\n"
                    "{cql}\n"
                    "").format(ks=self.name, cql=cql)
        return cql
530718
protected void export(Map<String, String> out, RequestContext ctx, RequestLog log) {
        assert exporter != null;
        exporter.export(out, ctx, log);
    }
559538
public static <T> T query(Connection conn, String sql, RsHandler<T> rsh, Map<String, Object> paramMap) throws SQLException {
		final NamedSql namedSql = new NamedSql(sql, paramMap);
		return query(conn, namedSql.getSql(), rsh, namedSql.getParams());
	}
199511
public final Cursor<T> select (Connection conn, String condition)
    {
        String query = "select " + listOfFields + " from " + name +
            " " + condition;
        return new Cursor<T>(this, conn, query);
    }
564186
public boolean export() throws QueryException, NoDataFoundException {

		start = true;
		
        testForData();        
        
		if (needsFirstCrossing() && !(this instanceof FirstCrossingExporter)) {			
			FirstCrossingExporter fe = new FirstCrossingExporter(bean);
			fe.export();
			// get template values from FirstCrossing
			templatesValues = fe.getTemplatesValues();
			groupTemplateKeys = fe.getGroupTemplateKeys();			
		} 

        initExport();

        printHeaderBand();
        if (!printContentBands()) {
            return false;
        }
        printFooterBand();

        finishExport();
        
        if ((bean.getResult() != null) && (!(this instanceof FirstCrossingExporter)) )  {
        	bean.getResult().close();
        }       
        
        if (this instanceof FirstCrossingExporter) {
        	// after FirstCrossing go to the beginning of the result set
        	try {
				bean.getResult().getResultSet().beforeFirst();
			} catch (SQLException ex) {
				LOG.error(ex.getMessage(), ex);
			}
        }               

        return true;
    }
355793
public void get_table( String sql, String args[], TableResult tbl ) throws jsqlite.Exception {
        tbl.clear();
        if (!is3()) {
            try {
                exec(sql, tbl, args);
            } catch (jsqlite.Exception e) {
                if (tbl.maxrows <= 0 || !tbl.atmaxrows) {
                    throw e;
                }
            }
        } else {
            synchronized (this) {
                /* only one statement !!! */
                Vm vm = compile(sql, args);
                if (tbl.maxrows > 0) {
                    while( tbl.nrows < tbl.maxrows && vm.step(tbl) ) {
                        set_last_error(vm.error_code);
                    }
                } else {
                    while( vm.step(tbl) ) {
                        set_last_error(vm.error_code);
                    }
                }
                vm.finalize();
            }
        }
    }
948814
function writeFile(cvs, data, callback) {
    if (typeof data.path !== 'string') {
      return callback(new TypeError('Invalid path type: ' + typeof data.path));
    }

    var fd, buff;

    // Write the buffer to the open file stream once both prerequisites are met.
    function writeBuffer() {
      fs.write(fd, buff, 0, buff.length, 0, function (error) {
        fs.close(fd);

        callback(error);
      });
    }

    // Create a buffer of the canvas' data.
    cvs.toBuffer(function (error, _buff) {
      if (error) return callback(error);

      buff = _buff;
      if (fd) {
        writeBuffer();
      }
    });

    // Open a stream for the file to be written.
    fs.open(data.path, 'w', WRITE_MODE, function (error, _fd) {
      if (error) return callback(error);

      fd = _fd;
      if (buff) {
        writeBuffer();
      }
    });
  }
728952
public static long exportCSV(final File out, final Connection conn, final String querySQL) throws UncheckedSQLException, UncheckedIOException {
        return exportCSV(out, conn, querySQL, 0, Long.MAX_VALUE, true, true);
    }
812956
async function runQuery(query, connection) {
  // Connection here doesn't actually matter.
  // Someday this mock could get fancy and change output based on some connection value
  // For now validate that it is getting passed
  const { maxRows } = connection;

  // To determine the content of this mock query, inspect values from comments
  // Example format
  // -- dimensions = department 10, color 10, product 10, orderdate|orderdatetime 500
  // -- measures = cost, revenue, profit, <anythingyouwant>
  // -- orderby = department asc, product desc
  // -- limit = 100
  const dimensions = [];
  const measures = [];
  const orderByFields = [];
  const orderByDirections = [];
  let limit;

  query
    .split('\n')
    .map(line => line.trim())
    .filter(line => line.startsWith('--'))
    .map(line => line.replace('--', ''))
    .forEach(line => {
      const [fieldType, fieldData] = line
        .split('=')
        .map(p => p.trim().toLowerCase());

      if (!fieldData) {
        return;
      }

      // fieldData is something like <fieldname> <direction>, <field2> <direction>
      // or 100
      fieldData
        .split(',')
        .map(p => p.trim())
        .forEach(part => {
          if (fieldType === 'limit') {
            limit = parseInt(part);
          } else if (fieldType === 'dimensions') {
            const [fieldName, numString] = part.split(' ').map(p => p.trim());
            if (!fieldValues[fieldName]) {
              throw new Error(
                `Unknown ${fieldName}. must be one of: ${Object.keys(
                  fieldValues
                ).join(', ')}`
              );
            }
            dimensions.push({
              name: fieldName,
              values: fieldValues[fieldName].slice(0, parseInt(numString))
            });
          } else if (fieldType === 'measures') {
            measures.push(part);
          } else if (fieldType === 'orderby') {
            const [fieldName, direction] = part.split(' ').map(p => p.trim());
            if (!direction) {
              throw new Error('direction required. Must be asc or desc');
            }
            orderByFields.push(fieldName);
            orderByDirections.push(direction);
          } else {
            throw new Error(
              `Unknown ${fieldType}. Must be dimensions, measures, orderby, or limit`
            );
          }
        });
    });

  if (!dimensions.length) {
    throw new Error('dimensions required');
  }

  // Assemble dimensions and things
  let rows = [];
  dimensions.forEach(dimension => {
    rows = cartesianify(rows, dimension);
  });

  if (measures.length) {
    rows.forEach(row => {
      measures.forEach(measure => {
        const date = row.orderdate || row.orderdatetime;
        if (date) {
          const doy = moment.utc(date).dayOfYear();
          row[measure] = 10 + Math.round(doy * Math.random());
        } else {
          row[measure] = Math.round(Math.random() * 1000);
        }
      });
    });
  }

  if (orderByFields.length) {
    rows = _.orderBy(rows, orderByFields, orderByDirections);
  }

  if (limit) {
    rows = rows.slice(0, limit);
  }

  return { rows: rows.slice(0, maxRows), incomplete: rows.length > maxRows };
}
7801
public function exportCsv($appId, $scanId, $outFile, array $queryParams = [])
    {
        $response = $this->api
            ->applications()
            ->scans()
            ->exports()
            ->exportCsv($appId, $scanId, $outFile, $queryParams);

        return new BaseResponse($response);
    }
1325681
public String exportAliasesAsCsv(CmsObject cms) throws CmsException {

        String siteRoot = cms.getRequestContext().getSiteRoot();
        List<CmsAlias> aliases = OpenCms.getAliasManager().getAliasesForSite(cms, siteRoot);
        StringWriter writer = new StringWriter();
        CSVWriter csvWriter = new CSVWriter(writer);
        StringBuffer resultBuffer = writer.getBuffer();
        for (CmsAlias alias : aliases) {
            try {
                CmsResource resource = cms.readResource(alias.getStructureId());
                csvWriter.writeNext(
                    new String[] {alias.getAliasPath(), cms.getSitePath(resource), alias.getMode().toString()});
            } catch (CmsException e) {
                LOG.warn("Could not read alias resource", e);
                continue;
            }
        }

        List<CmsRewriteAlias> rewriteAliases = OpenCms.getAliasManager().getRewriteAliases(cms, siteRoot);
        for (CmsRewriteAlias rewrite : rewriteAliases) {
            csvWriter.writeNext(
                new String[] {
                    rewrite.getPatternString(),
                    rewrite.getReplacementString(),
                    rewrite.getMode().toString(),
                    "rewrite"});
        }
        try {
            csvWriter.flush();
            csvWriter.close();
        } catch (IOException e) {
            // can't happen
        }
        return resultBuffer.toString();
    }
700282
private void writeRowsToCSV(List<String[]> rows) throws BindException
  {
    int numBytes;
    int rowNum = 0;
    int fileCount = 0;

    while (rowNum < rows.size())
    {
      File file = getFile(++fileCount);

      try (OutputStream out = openFile(file))
      {
        // until we reach the last row or the file is too big, write to the file
        numBytes = 0;
        while (numBytes < fileSize && rowNum < rows.size())
        {
          byte[] csv = createCSVRecord(rows.get(rowNum));
          numBytes += csv.length;
          out.write(csv);
          rowNum++;
        }
      }
      catch (IOException ex)
      {
        throw new BindException(
            String.format("Exception encountered while writing to file: %s", ex.getMessage()), BindException.Type.SERIALIZATION);
      }
    }
  }
132253
static void export(String path, DbConn cnx) throws JqmXmlException
    {
        if (cnx == null)
        {
            throw new IllegalArgumentException("database connection cannot be null");
        }
        export(path, JobDef.select(cnx, "jd_select_all"), cnx);
    }
198388
def export_txt(cls, feed):
        ''''''
        objects = cls.objects.in_feed(feed)

        # If no records, return None
        if not objects.exists():
            return

        # Get the columns used in the dataset
        column_map = objects.populated_column_map()
        columns, fields = zip(*column_map)
        extra_columns = feed.meta.get(
            'extra_columns', {}).get(cls.__name__, [])

        # Get sort order
        if hasattr(cls, '_sort_order'):
            sort_fields = cls._sort_order
        else:
            sort_fields = []
            for field in fields:
                base_field = field.split('__', 1)[0]
                point_match = re_point.match(base_field)
                if point_match:
                    continue
                field_type = cls._meta.get_field(base_field)
                assert not isinstance(field_type, ManyToManyField)
                sort_fields.append(field)

        # Create CSV writer
        out = StringIO()
        csv_writer = writer(out, lineterminator='\n')

        # Write header row
        header_row = [text_type(c) for c in columns]
        header_row.extend(extra_columns)
        write_text_rows(csv_writer, [header_row])

        # Report the work to be done
        total = objects.count()
        logger.info(
            '%d %s to export...',
            total, cls._meta.verbose_name_plural)

        # Populate related items cache
        model_to_field_name = {}
        cache = {}
        for field_name in fields:
            if '__' in field_name:
                local_field_name, subfield_name = field_name.split('__', 1)
                field = cls._meta.get_field(local_field_name)
                field_type = field.related_model
                model_name = field_type.__name__
                if model_name in model_to_field_name:
                    # Already loaded this model under a different field name
                    cache[field_name] = cache[model_to_field_name[model_name]]
                else:
                    # Load all feed data for this model
                    pairs = field_type.objects.in_feed(
                        feed).values_list('id', subfield_name)
                    cache[field_name] = dict(
                        (i, text_type(x)) for i, x in pairs)
                    cache[field_name][None] = u''
                    model_to_field_name[model_name] = field_name

        # Assemble the rows, writing when we hit batch size
        count = 0
        rows = []
        for item in objects.order_by(*sort_fields).iterator():
            row = []
            for csv_name, field_name in column_map:
                obj = item
                point_match = re_point.match(field_name)
                if '__' in field_name:
                    # Return relations from cache
                    local_field_name = field_name.split('__', 1)[0]
                    field_id = getattr(obj, local_field_name + '_id')
                    row.append(cache[field_name][field_id])
                elif point_match:
                    # Get the lat or long from the point
                    name, index = point_match.groups()
                    field = getattr(obj, name)
                    row.append(field.coords[int(index)])
                else:
                    # Handle other field types
                    field = getattr(obj, field_name) if obj else ''
                    if isinstance(field, date):
                        formatted = field.strftime(u'%Y%m%d')
                        row.append(text_type(formatted))
                    elif isinstance(field, bool):
                        row.append(1 if field else 0)
                    elif field is None:
                        row.append(u'')
                    else:
                        row.append(text_type(field))
            for col in extra_columns:
                row.append(obj.extra_data.get(col, u''))
            rows.append(row)
            if len(rows) % batch_size == 0:  # pragma: no cover
                write_text_rows(csv_writer, rows)
                count += len(rows)
                logger.info(
                    "Exported %d %s",
                    count, cls._meta.verbose_name_plural)
                rows = []

        # Write rows smaller than batch size
        write_text_rows(csv_writer, rows)
        return out.getvalue()