aboutsummaryrefslogtreecommitdiffstats
path: root/SQLiteStudio3/sqlitestudiocli/commands/clicommandsql.cpp
blob: 3f2c4b33f6da191324862a32b2e93ecda3ce8357 (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
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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
#include "clicommandsql.h"
#include "cli.h"
#include "parser/ast/sqliteselect.h"
#include "parser/parser.h"
#include "parser/parsererror.h"
#include "db/queryexecutor.h"
#include "qio.h"
#include "common/unused.h"
#include "cli_config.h"
#include "cliutils.h"
#include <QList>
#include <QDebug>

void CliCommandSql::execute()
{
    if (!cli->getCurrentDb())
    {
        println(tr("No working database is set.\n"
                   "Call %1 command to set working database.\n"
                   "Call %2 to see list of all databases.")
                .arg(cmdName("use")).arg(cmdName("dblist")));

        return;
    }

    Db* db = cli->getCurrentDb();
    if (!db || !db->isOpen())
    {
        println(tr("Database is not open."));
        return;
    }

    // Executor deletes itself later when called with lambda.
    QueryExecutor *executor = new QueryExecutor(db, syntax.getArgument(STRING));
    connect(executor, SIGNAL(executionFinished(SqlQueryPtr)), this, SIGNAL(execComplete()));
    connect(executor, SIGNAL(executionFailed(int,QString)), this, SLOT(executionFailed(int,QString)));
    connect(executor, SIGNAL(executionFailed(int,QString)), this, SIGNAL(execComplete()));

    executor->exec([=](SqlQueryPtr results)
    {
        if (results->isError())
            return; // should not happen, since results handler function is called only for successful executions

        switch (CFG_CLI.Console.ResultsDisplayMode.get())
        {
            case CliResultsDisplay::FIXED:
                printResultsFixed(executor, results);
                break;
            case CliResultsDisplay::COLUMNS:
                printResultsColumns(executor, results);
                break;
            case CliResultsDisplay::ROW:
                printResultsRowByRow(executor, results);
                break;
            default:
                printResultsClassic(executor, results);
                break;
        }
    });
}

QString CliCommandSql::shortHelp() const
{
    return tr("executes SQL query");
}

QString CliCommandSql::fullHelp() const
{
    return tr(
                "This command is executed every time you enter SQL query in command prompt. "
                "It executes the query on the current working database (see help for %1 for details). "
                "There's no sense in executing this command explicitly. Instead just type the SQL query "
                "in the command prompt, without any command prefixed."
                ).arg(cmdName("use"));
}

bool CliCommandSql::isAsyncExecution() const
{
    return true;
}

void CliCommandSql::defineSyntax()
{
    syntax.setName("query");
    syntax.addArgument(STRING, tr("sql", "CLI command syntax"));
    syntax.setStrictArgumentCount(false);
}

void CliCommandSql::printResultsClassic(QueryExecutor* executor, SqlQueryPtr results)
{
    int metaColumns = executor->getMetaColumnCount();
    int resultColumnCount = executor->getResultColumns().size();

    // Columns
    foreach (const QueryExecutor::ResultColumnPtr& resCol, executor->getResultColumns())
        qOut << resCol->displayName << "|";

    qOut << "\n";

    // Data
    SqlResultsRowPtr row;
    QList<QVariant> values;
    int i;
    while (results->hasNext())
    {
        row = results->next();
        i = 0;
        values = row->valueList().mid(metaColumns);
        foreach (QVariant value, values)
        {
            qOut << getValueString(value);
            if ((i + 1) < resultColumnCount)
                qOut << "|";

            i++;
        }

        qOut << "\n";
    }
    qOut.flush();
}

void CliCommandSql::printResultsFixed(QueryExecutor* executor, SqlQueryPtr results)
{
    QList<QueryExecutor::ResultColumnPtr> resultColumns = executor->getResultColumns();
    int resultColumnsCount = resultColumns.size();
    int metaColumns = executor->getMetaColumnCount();
    int termCols = getCliColumns();
    int baseColWidth = termCols / resultColumns.size() - 1;

    if (resultColumnsCount == 0)
        return;

    if ((resultColumnsCount * 2 - 1) > termCols)
    {
        println(tr("Too many columns to display in %1 mode.").arg("FIXED"));
        return;
    }

    int width;
    QList<int> widths;
    for (int i = 0; i < resultColumnsCount; i++)
    {
        width = baseColWidth;
        if (i+1 == resultColumnsCount)
            width += (termCols - resultColumnsCount * (baseColWidth + 1) + 1);

        widths << width;
    }

    // Columns
    QStringList columns;
    foreach (const QueryExecutor::ResultColumnPtr& resCol, executor->getResultColumns())
        columns << resCol->displayName;

    printColumnHeader(widths, columns);

    // Data
    while (results->hasNext())
        printColumnDataRow(widths, results->next(), metaColumns);

    qOut.flush();
}

void CliCommandSql::printResultsColumns(QueryExecutor* executor, SqlQueryPtr results)
{
    // Check if we don't have more columns than we can display
    QList<QueryExecutor::ResultColumnPtr> resultColumns = executor->getResultColumns();
    int termCols = getCliColumns();
    int resultColumnsCount = resultColumns.size();
    QStringList headerNames;
    if (resultColumnsCount == 0)
        return;

    // Every column requires at least 1 character width + column separators between them
    if ((resultColumnsCount * 2 - 1) > termCols)
    {
        println(tr("Too many columns to display in %1 mode.").arg("COLUMNS"));
        return;
    }

    // Preload data (we will calculate column widths basing on real values)
    QList<SqlResultsRowPtr> allRows = results->getAll();
    int metaColumns = executor->getMetaColumnCount();

    // Get widths of each column in every data row, remember the longest ones
    QList<SortedColumnWidth*> columnWidths;
    SortedColumnWidth* colWidth = nullptr;
    foreach (const QueryExecutor::ResultColumnPtr& resCol, resultColumns)
    {
        colWidth = new SortedColumnWidth();
        colWidth->setHeaderWidth(resCol->displayName.length());
        columnWidths << colWidth;
        headerNames << resCol->displayName;
    }

    int dataLength;
    foreach (const SqlResultsRowPtr& row, allRows)
    {
        for (int i = 0; i < resultColumnsCount; i++)
        {
            dataLength = row->value(metaColumns + i).toString().length();
            columnWidths[i]->setMinDataWidth(dataLength);
        }
    }

    // Calculate width as it would be required to display entire rows
    int totalWidth = 0;
    foreach (colWidth, columnWidths)
        totalWidth += colWidth->getWidth();

    totalWidth += (resultColumnsCount - 1); // column separators

    // Adjust column sizes to fit into terminal window
    if (totalWidth < termCols)
    {
        // Expanding last column
        int diff = termCols - totalWidth;
        columnWidths.last()->incrWidth(diff);
    }
    else if (totalWidth > termCols)
    {
        // Shrinking columns
        shrinkColumns(columnWidths, termCols, resultColumnsCount, totalWidth);
    }

    // Printing
    QList<int> finalWidths;
    foreach (colWidth, columnWidths)
        finalWidths << colWidth->getWidth();

    printColumnHeader(finalWidths, headerNames);

    foreach (SqlResultsRowPtr row, allRows)
        printColumnDataRow(finalWidths, row, metaColumns);

    qOut.flush();
}

void CliCommandSql::printResultsRowByRow(QueryExecutor* executor, SqlQueryPtr results)
{
    // Columns
    int metaColumns = executor->getMetaColumnCount();
    int colWidth = 0;
    foreach (const QueryExecutor::ResultColumnPtr& resCol, executor->getResultColumns())
    {
        if (resCol->displayName.length() > colWidth)
            colWidth = resCol->displayName.length();
    }

    QStringList columns;
    foreach (const QueryExecutor::ResultColumnPtr& resCol, executor->getResultColumns())
        columns << pad(resCol->displayName, -colWidth, ' ');

    // Data
    static const QString rowCntTemplate = tr("Row %1");
    int termWidth = getCliColumns();
    QString rowCntString;
    int i;
    int rowCnt = 1;
    SqlResultsRowPtr row;
    while (results->hasNext())
    {
        row = results->next();
        i = 0;
        rowCntString = " " + rowCntTemplate.arg(rowCnt) + " ";
        qOut << center(rowCntString, termWidth - 1, '-') << "\n";
        foreach (QVariant value, row->valueList().mid(metaColumns))
        {
            qOut << columns[i] + ": " + getValueString(value) << "\n";
            i++;
        }
        rowCnt++;
    }
    qOut.flush();
}

void CliCommandSql::shrinkColumns(QList<CliCommandSql::SortedColumnWidth*>& columnWidths, int termCols, int resultColumnsCount, int totalWidth)
{
    // This implements quite a smart shrinking algorithm:
    // All columns are sorted by their current total width (data and header width)
    // and then longest headers are shrinked first, then if headers are no longer a problem,
    // but the data is - then longest data values are shrinked.
    // If either the hader or the data value is huge (way more than fits into terminal),
    // then such column is shrinked in one step to a reasonable width, so it can be later
    // shrinked more precisely.
    int maxSingleColumnWidth = (termCols - (resultColumnsCount - 1) * 2 );
    bool shrinkData;
    int previousTotalWidth = -1;
    while (totalWidth > termCols && totalWidth != previousTotalWidth)
    {
        shrinkData = true;
        previousTotalWidth = totalWidth;

        // Sort columns by current widths
        qSort(columnWidths);

        // See if we can shrink headers only, or we already need to shrink the data
        foreach (SortedColumnWidth* colWidth, columnWidths)
        {
            if (colWidth->isHeaderLonger())
            {
                shrinkData = false;
                break;
            }
        }

        // Do the shrinking
        if (shrinkData)
        {
            for (int i = resultColumnsCount - 1; i >= 0; i--)
            {
                // If the data is way larger then the terminal, shrink it to reasonable length in one step.
                // We also make sure that after data shrinking, the header didn't become longer than the data,
                // cause at this moment, we were finished with headers and we enforce shrinking data
                // and so do with headers.
                if (columnWidths[i]->getDataWidth() > maxSingleColumnWidth)
                {
                    totalWidth -= (columnWidths[i]->getDataWidth() - maxSingleColumnWidth);
                    columnWidths[i]->setDataWidth(maxSingleColumnWidth);
                    columnWidths[i]->setMaxHeaderWidth(maxSingleColumnWidth);
                    break;
                }
                else if (columnWidths[i]->getDataWidth() > 1) // just shrink it by 1
                {
                    totalWidth -= 1;
                    columnWidths[i]->decrDataWidth();
                    columnWidths[i]->setMaxHeaderWidth(columnWidths[i]->getDataWidth());
                    break;
                }
            }
        }
        else // shrinking headers
        {
            for (int i = resultColumnsCount - 1; i >= 0; i--)
            {
                // We will shrink only the header that
                if (!columnWidths[i]->isHeaderLonger())
                    continue;

                // If the header is way larger then the terminal, shrink it to reasonable length in one step
                if (columnWidths[i]->getHeaderWidth() > maxSingleColumnWidth)
                {
                    totalWidth -= (columnWidths[i]->getHeaderWidth() - maxSingleColumnWidth);
                    columnWidths[i]->setHeaderWidth(maxSingleColumnWidth);
                    break;
                }
                else if (columnWidths[i]->getHeaderWidth() > 1) // otherwise just shrink it by 1
                {
                    totalWidth -= 1;
                    columnWidths[i]->decrHeaderWidth();
                    break;
                }
            }
        }
    }

    if (totalWidth == previousTotalWidth && totalWidth > termCols)
        qWarning() << "The shrinking algorithm in printResultsColumns() failed, it could not shrink columns enough.";
}

void CliCommandSql::printColumnHeader(const QList<int>& widths, const QStringList& columns)
{
    QStringList line;
    int i = 0;
    foreach (const QString& col, columns)
    {
        line << pad(col.left(widths[i]), widths[i], ' ');
        i++;
    }

    qOut << line.join("|");

    line.clear();
    QString hline("-");
    for (i = 0; i < columns.count(); i++)
        line << hline.repeated(widths[i]);

    qOut << line.join("+");
}

void CliCommandSql::printColumnDataRow(const QList<int>& widths, const SqlResultsRowPtr& row, int rowIdOffset)
{
    int i = 0;
    QStringList line;
    foreach (const QVariant& value, row->valueList().mid(rowIdOffset))
    {
        line << pad(getValueString(value).left(widths[i]), widths[i], ' ');
        i++;
    }

    qOut << line.join("|");
}

QString CliCommandSql::getValueString(const QVariant& value)
{
    if (value.isValid() && !value.isNull())
        return value.toString();

    return CFG_CLI.Console.NullValue.get();
}

void CliCommandSql::executionFailed(int code, const QString& msg)
{
    UNUSED(code);
    qOut << tr("Query execution error: %1").arg(msg) << "\n\n";
    qOut.flush();
}

CliCommandSql::SortedColumnWidth::SortedColumnWidth()
{
    dataWidth = 0;
    headerWidth = 0;
    width = 0;
}

bool CliCommandSql::SortedColumnWidth::operator<(const CliCommandSql::SortedColumnWidth& other)
{
    return width < other.width;
}

int CliCommandSql::SortedColumnWidth::getHeaderWidth() const
{
    return headerWidth;
}

void CliCommandSql::SortedColumnWidth::setHeaderWidth(int value)
{
    headerWidth = value;
    updateWidth();
}

void CliCommandSql::SortedColumnWidth::setMaxHeaderWidth(int value)
{
    if (headerWidth > value)
    {
        headerWidth = value;
        updateWidth();
    }
}

void CliCommandSql::SortedColumnWidth::incrHeaderWidth(int value)
{
    headerWidth += value;
    updateWidth();
}

void CliCommandSql::SortedColumnWidth::decrHeaderWidth(int value)
{
    headerWidth -= value;
    updateWidth();
}

int CliCommandSql::SortedColumnWidth::getDataWidth() const
{
    return dataWidth;
}

void CliCommandSql::SortedColumnWidth::setDataWidth(int value)
{
    dataWidth = value;
    updateWidth();
}

void CliCommandSql::SortedColumnWidth::setMinDataWidth(int value)
{
    if (dataWidth < value)
    {
        dataWidth = value;
        updateWidth();
    }
}

void CliCommandSql::SortedColumnWidth::incrDataWidth(int value)
{
    dataWidth += value;
    updateWidth();
}

void CliCommandSql::SortedColumnWidth::decrDataWidth(int value)
{
    dataWidth -= value;
    updateWidth();
}

void CliCommandSql::SortedColumnWidth::incrWidth(int value)
{
    width += value;
    dataWidth = width;
    headerWidth = width;
}

int CliCommandSql::SortedColumnWidth::getWidth() const
{
    return width;
}

bool CliCommandSql::SortedColumnWidth::isHeaderLonger() const
{
    return headerWidth > dataWidth;
}

void CliCommandSql::SortedColumnWidth::updateWidth()
{
    width = qMax(headerWidth, dataWidth);
}