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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include <comphelper/string.hxx>
#include <sal/log.hxx>
#include "createparser.hxx"
#include "utils.hxx"
#include <com/sun/star/sdbc/DataType.hpp>

using namespace ::comphelper;
using namespace css::sdbc;

namespace
{
/// Returns substring of sSql from the first occurrence of '(' until the
/// last occurrence of ')' (excluding the parenthesis)
OUString lcl_getColumnPart(const OUString& sSql)
{
    sal_Int32 nBeginIndex = sSql.indexOf("(") + 1;
    if (nBeginIndex < 0)
    {
        SAL_WARN("dbaccess", "No column definitions found");
        return OUString();
    }
    sal_Int32 nCount = sSql.lastIndexOf(")") - nBeginIndex;
    return sSql.copy(nBeginIndex, nCount);
}

/// Constructs a vector of strings that represents the definitions of each
/// column or constraint.
///
/// @param sColumnPart part of the create statement inside the parenthesis
/// containing the column definitions
std::vector<OUString> lcl_splitColumnPart(const OUString& sColumnPart)
{
    std::vector<OUString> sParts = string::split(sColumnPart, sal_Unicode(u','));
    std::vector<OUString> sReturn;

    OUStringBuffer current(128);
    for (auto const& part : sParts)
    {
        current.append(part);
        if (current.lastIndexOf("(") > current.lastIndexOf(")"))
            current.append(","); // it was false split
        else
        {
            sReturn.push_back(current.toString());
            current.setLength(0);
        }
    }
    return sReturn;
}

sal_Int32 lcl_getAutoIncrementDefault(const OUString& sColumnDef)
{
    // TODO what if there are more spaces?
    if (sColumnDef.indexOf("GENERATED BY DEFAULT AS IDENTITY") > 0)
    {
        // TODO parse starting sequence stated by "START WITH"
        return 0;
    }
    return -1;
}

OUString lcl_getDefaultValue(const OUString& sColumnDef)
{
    constexpr char DEFAULT_KW[] = "DEFAULT";
    auto nDefPos = sColumnDef.indexOf(DEFAULT_KW);
    if (nDefPos > 0 && lcl_getAutoIncrementDefault(sColumnDef) < 0)
    {
        const OUString& fromDefault = sColumnDef.copy(nDefPos + sizeof(DEFAULT_KW)).trim();

        // next word is the value
        auto nNextSpace = fromDefault.indexOf(" ");
        return nNextSpace > 0 ? fromDefault.copy(0, fromDefault.indexOf(" ")) : fromDefault;
    }
    return OUString{};
}

bool lcl_isNullable(const OUString& sColumnDef) { return sColumnDef.indexOf("NOT NULL") < 0; }

bool lcl_isPrimaryKey(const OUString& sColumnDef) { return sColumnDef.indexOf("PRIMARY KEY") >= 0; }

sal_Int32 lcl_getDataTypeFromHsql(const OUString& sTypeName)
{
    if (sTypeName == "CHAR")
        return DataType::CHAR;
    else if (sTypeName == "VARCHAR" || sTypeName == "VARCHAR_IGNORECASE")
        return DataType::VARCHAR;
    else if (sTypeName == "TINYINT")
        return DataType::TINYINT;
    else if (sTypeName == "SMALLINT")
        return DataType::SMALLINT;
    else if (sTypeName == "INTEGER")
        return DataType::INTEGER;
    else if (sTypeName == "BIGINT")
        return DataType::BIGINT;
    else if (sTypeName == "NUMERIC")
        return DataType::NUMERIC;
    else if (sTypeName == "DECIMAL")
        return DataType::DECIMAL;
    else if (sTypeName == "BOOLEAN")
        return DataType::BOOLEAN;
    else if (sTypeName == "LONGVARCHAR")
        return DataType::LONGVARCHAR;
    else if (sTypeName == "LONGVARBINARY")
        return DataType::LONGVARBINARY;
    else if (sTypeName == "CLOB")
        return DataType::CLOB;
    else if (sTypeName == "BLOB")
        return DataType::BLOB;
    else if (sTypeName == "BINARY")
        return DataType::BINARY;
    else if (sTypeName == "VARBINARY")
        return DataType::VARBINARY;
    else if (sTypeName == "DATE")
        return DataType::DATE;
    else if (sTypeName == "TIME")
        return DataType::TIME;
    else if (sTypeName == "TIMESTAMP")
        return DataType::TIMESTAMP;
    else if (sTypeName == "DOUBLE")
        return DataType::DOUBLE;
    else if (sTypeName == "REAL")
        return DataType::REAL;
    else if (sTypeName == "FLOAT")
        return DataType::FLOAT;

    assert(false);
    return -1;
}

void lcl_addDefaultParameters(std::vector<sal_Int32>& aParams, sal_Int32 eType)
{
    if (eType == DataType::CHAR || eType == DataType::BINARY || eType == DataType::VARBINARY
        || eType == DataType::VARCHAR)
        aParams.push_back(8000); // from SQL standard
}

struct ColumnTypeParts
{
    OUString typeName;
    std::vector<sal_Int32> params;
};

/**
 * Separates full type descriptions (e.g. NUMERIC(5,4)) to type name (NUMERIC) and
 * parameters (5,4)
 */
ColumnTypeParts lcl_getColumnTypeParts(const OUString& sFullTypeName)
{
    ColumnTypeParts parts;
    auto nParenPos = sFullTypeName.indexOf("(");
    if (nParenPos > 0)
    {
        parts.typeName = sFullTypeName.copy(0, nParenPos).trim();
        OUString sParamStr
            = sFullTypeName.copy(nParenPos + 1, sFullTypeName.indexOf(")") - nParenPos - 1);
        auto sParams = string::split(sParamStr, sal_Unicode(u','));
        for (const auto& sParam : sParams)
        {
            parts.params.push_back(sParam.toInt32());
        }
    }
    else
    {
        parts.typeName = sFullTypeName.trim();
        lcl_addDefaultParameters(parts.params, lcl_getDataTypeFromHsql(parts.typeName));
    }
    return parts;
}

} // unnamed namespace

namespace dbahsql
{
CreateStmtParser::CreateStmtParser() {}

void CreateStmtParser::parsePrimaryKeys(const OUString& sPrimaryPart)
{
    sal_Int32 nParenPos = sPrimaryPart.indexOf("(");
    if (nParenPos > 0)
    {
        OUString sParamStr
            = sPrimaryPart.copy(nParenPos + 1, sPrimaryPart.lastIndexOf(")") - nParenPos - 1);
        auto sParams = string::split(sParamStr, sal_Unicode(u','));
        for (const auto& sParam : sParams)
        {
            m_PrimaryKeys.push_back(sParam);<--- Consider using std::copy algorithm instead of a raw loop.
        }
    }
}

void CreateStmtParser::parseColumnPart(const OUString& sColumnPart)
{
    auto sColumns = lcl_splitColumnPart(sColumnPart);
    for (const OUString& sColumn : sColumns)
    {
        if (sColumn.startsWithIgnoreAsciiCase("PRIMARY KEY"))
        {
            parsePrimaryKeys(sColumn);
            continue;
        }

        if (sColumn.startsWithIgnoreAsciiCase("CONSTRAINT"))
        {
            m_aForeignParts.push_back(sColumn);
            continue;
        }

        bool bIsQuoteUsedForColumnName(sColumn[0] == '\"');

        // find next quote after the initial quote
        // or next space if quote isn't used as delimiter
        auto nEndColumnName
            = bIsQuoteUsedForColumnName ? sColumn.indexOf("\"", 1) + 1 : sColumn.indexOf(" ");
        OUString rColumnName = sColumn.copy(0, nEndColumnName);

        const OUString& sFromTypeName = sColumn.copy(nEndColumnName).trim();

        // Now let's manage the column type
        // search next space to get the whole type name
        // eg: INTEGER, VARCHAR(10), DECIMAL(6,3)
        auto nNextSpace = sFromTypeName.indexOf(" ");
        OUString sFullTypeName;
        if (nNextSpace > 0)
            sFullTypeName = sFromTypeName.copy(0, nNextSpace);
        // perhaps column type corresponds to the last info here
        else
            sFullTypeName = sFromTypeName;

        ColumnTypeParts typeParts = lcl_getColumnTypeParts(sFullTypeName);

        bool bCaseInsensitive = typeParts.typeName.indexOf("IGNORECASE") >= 0;
        bool isPrimaryKey = lcl_isPrimaryKey(sColumn);

        if (isPrimaryKey)
            m_PrimaryKeys.push_back(rColumnName);

        const OUString sColumnWithoutName = sColumn.copy(sColumn.indexOf(typeParts.typeName));

        ColumnDefinition aColDef(rColumnName, lcl_getDataTypeFromHsql(typeParts.typeName),
                                 typeParts.params, isPrimaryKey,
                                 lcl_getAutoIncrementDefault(sColumnWithoutName),
                                 lcl_isNullable(sColumnWithoutName), bCaseInsensitive,
                                 lcl_getDefaultValue(sColumnWithoutName));

        m_aColumns.push_back(aColDef);
    }
}

void CreateStmtParser::parse(const OUString& sSql)
{
    // TODO Foreign keys
    if (!sSql.startsWith("CREATE"))
    {
        SAL_WARN("dbaccess", "Not a create statement");
        return;
    }

    m_sTableName = utils::getTableNameFromStmt(sSql);
    OUString sColumnPart = lcl_getColumnPart(sSql);
    parseColumnPart(sColumnPart);
}

} // namespace dbahsql

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */