aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/clickhouse/src/Processors/Formats/RowInputFormatWithDiagnosticInfo.cpp
blob: 6358a99d6b4cd7f75630911536eb45b219db825a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
#include <Processors/Formats/RowInputFormatWithDiagnosticInfo.h>
#include <Formats/verbosePrintString.h>
#include <IO/Operators.h>
#include <IO/WriteBufferFromString.h>


namespace DB
{

namespace ErrorCodes
{
    extern const int LOGICAL_ERROR;
}

static String alignedName(const String & name, size_t max_length)
{
    size_t spaces_count = max_length >= name.size() ? max_length - name.size() : 0;
    return name + ", " + std::string(spaces_count, ' ');
}


RowInputFormatWithDiagnosticInfo::RowInputFormatWithDiagnosticInfo(const Block & header_, ReadBuffer & in_, const Params & params_)
    : IRowInputFormat(header_, in_, params_)
{
}

void RowInputFormatWithDiagnosticInfo::updateDiagnosticInfo()
{
    ++row_num;

    bytes_read_at_start_of_buffer_on_prev_row = bytes_read_at_start_of_buffer_on_current_row;
    bytes_read_at_start_of_buffer_on_current_row = in->count() - in->offset();

    offset_of_prev_row = offset_of_current_row;
    offset_of_current_row = in->offset();
}

std::pair<String, String> RowInputFormatWithDiagnosticInfo::getDiagnosticAndRawDataImpl(bool is_errors_record)
{
    WriteBufferFromOwnString out_diag;
    WriteBufferFromOwnString out_data;

    if (in->eof())
        return std::make_pair(
            "Buffer has gone, cannot extract information about what has been parsed.",
            "Buffer has gone, cannot extract information about what has been parsed.");

    const auto & header = getPort().getHeader();
    MutableColumns columns = header.cloneEmptyColumns();

    /// It is possible to display detailed diagnostics only if the last and next to last rows are still in the read buffer.
    size_t bytes_read_at_start_of_buffer = in->count() - in->offset();
    if (bytes_read_at_start_of_buffer != bytes_read_at_start_of_buffer_on_prev_row)
    {
        out_diag << "Could not print diagnostic info because two last rows aren't in buffer (rare case)\n";
        out_data << "Could not collect raw data because two last rows aren't in buffer (rare case)\n";
        return std::make_pair(out_diag.str(), out_data.str());
    }

    max_length_of_column_name = 0;
    for (size_t i = 0; i < header.columns(); ++i)
        if (header.safeGetByPosition(i).name.size() > max_length_of_column_name)
            max_length_of_column_name = header.safeGetByPosition(i).name.size();

    max_length_of_data_type_name = 0;
    for (size_t i = 0; i < header.columns(); ++i)
        if (header.safeGetByPosition(i).type->getName().size() > max_length_of_data_type_name)
            max_length_of_data_type_name = header.safeGetByPosition(i).type->getName().size();

    /// Roll back the cursor to the beginning of the previous or current row and parse all over again. But now we derive detailed information.

    if (!is_errors_record && offset_of_prev_row <= in->buffer().size())
    {
        in->position() = in->buffer().begin() + offset_of_prev_row;

        out_diag << "\nRow " << (row_num - 1) << ":\n";
        if (!parseRowAndPrintDiagnosticInfo(columns, out_diag))
            return std::make_pair(out_diag.str(), out_data.str());
    }
    else
    {
        if (in->buffer().size() < offset_of_current_row)
        {
            out_diag << "Could not print diagnostic info because parsing of data hasn't started.\n";
            out_data << "Could not collect raw data because parsing of data hasn't started.\n";
            return std::make_pair(out_diag.str(), out_data.str());
        }

        in->position() = in->buffer().begin() + offset_of_current_row;
    }

    char * data = in->position();
    while (data < in->buffer().end() && *data != '\n' && *data != '\r' && *data != '\0')
    {
        out_data << *data;
        ++data;
    }

    out_diag << "\nRow " << row_num << ":\n";
    parseRowAndPrintDiagnosticInfo(columns, out_diag);
    out_diag << "\n";

    return std::make_pair(out_diag.str(), out_data.str());
}

String RowInputFormatWithDiagnosticInfo::getDiagnosticInfo()
{
    auto diagnostic_and_raw_data = getDiagnosticAndRawDataImpl(false);
    return std::get<0>(diagnostic_and_raw_data);
}

std::pair<String, String> RowInputFormatWithDiagnosticInfo::getDiagnosticAndRawData()
{
    return getDiagnosticAndRawDataImpl(true);
}

bool RowInputFormatWithDiagnosticInfo::deserializeFieldAndPrintDiagnosticInfo(const String & col_name,
                                                                              const DataTypePtr & type,
                                                                              IColumn & column,
                                                                              WriteBuffer & out,
                                                                              size_t file_column)
{
    out << "Column " << file_column << ", " << std::string((file_column < 10 ? 2 : file_column < 100 ? 1 : 0), ' ')
        << "name: " << alignedName(col_name, max_length_of_column_name)
        << "type: " << alignedName(type->getName(), max_length_of_data_type_name);

    auto * prev_position = in->position();
    std::exception_ptr exception;

    try
    {
        tryDeserializeField(type, column, file_column);
    }
    catch (...)
    {
        exception = std::current_exception();
    }
    auto * curr_position = in->position();

    if (curr_position < prev_position)
        throw Exception(ErrorCodes::LOGICAL_ERROR, "Logical error: parsing is non-deterministic.");

    if (isNativeNumber(type) || isDate(type) || isDateTime(type) || isDateTime64(type))
    {
        /// An empty string instead of a value.
        if (curr_position == prev_position)
        {
            out << "ERROR: text ";
            verbosePrintString(prev_position, std::min(prev_position + 10, in->buffer().end()), out);
            out << " is not like " << type->getName() << "\n";
            return false;
        }
    }

    out << "parsed text: ";
    verbosePrintString(prev_position, curr_position, out);

    if (exception)
    {
        if (type->getName() == "DateTime")
            out << "ERROR: DateTime must be in YYYY-MM-DD hh:mm:ss or NNNNNNNNNN (unix timestamp, exactly 10 digits) format.\n";
        else if (type->getName() == "Date")
            out << "ERROR: Date must be in YYYY-MM-DD format.\n";
        else
            out << "ERROR\n";
        // Print exception message
        out << getExceptionMessage(exception, false) << '\n';
        return false;
    }

    out << "\n";

    if (type->haveMaximumSizeOfValue())
    {
        if (isGarbageAfterField(file_column, curr_position))
        {
            out << "ERROR: garbage after " << type->getName() << ": ";
            verbosePrintString(curr_position, std::min(curr_position + 10, in->buffer().end()), out);
            out << "\n";

            if (type->getName() == "DateTime")
                out << "ERROR: DateTime must be in YYYY-MM-DD hh:mm:ss or NNNNNNNNNN (unix timestamp, exactly 10 digits) format.\n";
            else if (type->getName() == "Date")
                out << "ERROR: Date must be in YYYY-MM-DD format.\n";

            return false;
        }
    }

    return true;
}

void RowInputFormatWithDiagnosticInfo::resetParser()
{
    IRowInputFormat::resetParser();
    row_num = 0;
    bytes_read_at_start_of_buffer_on_current_row = 0;
    bytes_read_at_start_of_buffer_on_prev_row = 0;
    offset_of_current_row = std::numeric_limits<size_t>::max();
    offset_of_prev_row = std::numeric_limits<size_t>::max();
    max_length_of_column_name = 0;
    max_length_of_data_type_name = 0;
}


}