| 1 | #include <Processors/Formats/Impl/CSVRowOutputFormat.h> |
| 2 | #include <Formats/FormatFactory.h> |
| 3 | |
| 4 | #include <IO/WriteHelpers.h> |
| 5 | |
| 6 | |
| 7 | namespace DB |
| 8 | { |
| 9 | |
| 10 | |
| 11 | CSVRowOutputFormat::CSVRowOutputFormat(WriteBuffer & out_, const Block & , bool with_names_, FormatFactory::WriteCallback callback, const FormatSettings & format_settings_) |
| 12 | : IRowOutputFormat(header_, out_, callback), with_names(with_names_), format_settings(format_settings_) |
| 13 | { |
| 14 | auto & sample = getPort(PortKind::Main).getHeader(); |
| 15 | size_t columns = sample.columns(); |
| 16 | data_types.resize(columns); |
| 17 | for (size_t i = 0; i < columns; ++i) |
| 18 | data_types[i] = sample.safeGetByPosition(i).type; |
| 19 | } |
| 20 | |
| 21 | |
| 22 | void CSVRowOutputFormat::writePrefix() |
| 23 | { |
| 24 | auto & sample = getPort(PortKind::Main).getHeader(); |
| 25 | size_t columns = sample.columns(); |
| 26 | |
| 27 | if (with_names) |
| 28 | { |
| 29 | for (size_t i = 0; i < columns; ++i) |
| 30 | { |
| 31 | writeCSVString(sample.safeGetByPosition(i).name, out); |
| 32 | |
| 33 | char delimiter = format_settings.csv.delimiter; |
| 34 | if (i + 1 == columns) |
| 35 | delimiter = '\n'; |
| 36 | |
| 37 | writeChar(delimiter, out); |
| 38 | } |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | |
| 43 | void CSVRowOutputFormat::writeField(const IColumn & column, const IDataType & type, size_t row_num) |
| 44 | { |
| 45 | type.serializeAsTextCSV(column, row_num, out, format_settings); |
| 46 | } |
| 47 | |
| 48 | |
| 49 | void CSVRowOutputFormat::writeFieldDelimiter() |
| 50 | { |
| 51 | writeChar(format_settings.csv.delimiter, out); |
| 52 | } |
| 53 | |
| 54 | |
| 55 | void CSVRowOutputFormat::writeRowEndDelimiter() |
| 56 | { |
| 57 | writeChar('\n', out); |
| 58 | } |
| 59 | |
| 60 | void CSVRowOutputFormat::writeBeforeTotals() |
| 61 | { |
| 62 | writeChar('\n', out); |
| 63 | } |
| 64 | |
| 65 | void CSVRowOutputFormat::writeBeforeExtremes() |
| 66 | { |
| 67 | writeChar('\n', out); |
| 68 | } |
| 69 | |
| 70 | |
| 71 | |
| 72 | void registerOutputFormatProcessorCSV(FormatFactory & factory) |
| 73 | { |
| 74 | for (bool with_names : {false, true}) |
| 75 | { |
| 76 | factory.registerOutputFormatProcessor(with_names ? "CSVWithNames" : "CSV" , [=]( |
| 77 | WriteBuffer & buf, |
| 78 | const Block & sample, |
| 79 | FormatFactory::WriteCallback callback, |
| 80 | const FormatSettings & format_settings) |
| 81 | { |
| 82 | return std::make_shared<CSVRowOutputFormat>(buf, sample, with_names, callback, format_settings); |
| 83 | }); |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | } |
| 88 | |