aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/clickhouse/src/Processors/Formats/Impl/SQLInsertRowOutputFormat.cpp
blob: 6f490c8b0853031ddb6f3f09c9dd16e31453da36 (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
#include <Processors/Formats/Impl/SQLInsertRowOutputFormat.h>
#include <IO/WriteHelpers.h>


namespace DB
{

SQLInsertRowOutputFormat::SQLInsertRowOutputFormat(WriteBuffer & out_, const Block & header_, const FormatSettings & format_settings_)
    : IRowOutputFormat(header_, out_), column_names(header_.getNames()), format_settings(format_settings_)
{
}

void SQLInsertRowOutputFormat::writeRowStartDelimiter()
{
    if (rows_in_line == 0)
        printLineStart();
    writeChar('(', out);
}

void SQLInsertRowOutputFormat::printLineStart()
{
    if (format_settings.sql_insert.use_replace)
        writeCString("REPLACE INTO ", out);
    else
        writeCString("INSERT INTO ", out);

    writeString(format_settings.sql_insert.table_name, out);

    if (format_settings.sql_insert.include_column_names)
        printColumnNames();

    writeCString(" VALUES ", out);
}

void SQLInsertRowOutputFormat::printColumnNames()
{
    writeCString(" (", out);
    for (size_t i = 0; i != column_names.size(); ++i)
    {
        if (format_settings.sql_insert.quote_names)
            writeChar('`', out);

        writeString(column_names[i], out);

        if (format_settings.sql_insert.quote_names)
            writeChar('`', out);

        if (i + 1 != column_names.size())
            writeCString(", ", out);
    }
    writeChar(')', out);
}

void SQLInsertRowOutputFormat::writeField(const IColumn & column, const ISerialization & serialization, size_t row_num)
{
    serialization.serializeTextQuoted(column, row_num, out, format_settings);
}

void SQLInsertRowOutputFormat::writeFieldDelimiter()
{
    writeCString(", ", out);
}

void SQLInsertRowOutputFormat::writeRowEndDelimiter()
{
    writeChar(')', out);
    ++rows_in_line;
}

void SQLInsertRowOutputFormat::writeRowBetweenDelimiter()
{
    if (rows_in_line >= format_settings.sql_insert.max_batch_size)
    {
        writeCString(";\n", out);
        rows_in_line = 0;
    }
    else
    {
        writeCString(", ", out);
    }
}

void SQLInsertRowOutputFormat::writeSuffix()
{
    writeCString(";\n", out);
}

void SQLInsertRowOutputFormat::resetFormatterImpl()
{
    rows_in_line = 0;
}

void registerOutputFormatSQLInsert(FormatFactory & factory)
{
    factory.registerOutputFormat("SQLInsert", [](
        WriteBuffer & buf,
        const Block & sample,
        const FormatSettings & settings)
    {
        return std::make_shared<SQLInsertRowOutputFormat>(buf, sample, settings);
    });
}


}