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
#include "gate/gatemain.h"

#include "gate/console.hpp"
#include "gate/applications.hpp"
#include "gate/files.hpp"
#include "gate/environments.hpp"
#include "gate/utilities.hpp"

#include "gate/data/odbc_adapter.hpp"
#include "gate/data/sqlite3_adapter.hpp"
#include "gate/data/mysql_adapter.hpp"
#include "gate/wrappers.hpp"
#include "gate/runnables.hpp"

#include <stdio.h>

#if defined(GATE_COMPILER_MSVC) && defined(GATE_LEAK_DETECTION) && defined(GATE_SYS_WIN) && !defined(GATE_SYS_WINCE) && (GATE_ARCH != GATE_ARCH_ARM32) && (GATE_ARCH != GATE_ARCH_ARM64)
#	include <vld.h>
#endif

namespace gate
{
    namespace apps
    {
        static StaticString const dbProviderOdbcName = "odbc";
        static StaticString const dbProvSqlite = "sqlite";
        static StaticString const dbProvMysql = "mysql";

        typedef gate::data::DataConnection DataConnection;
        typedef gate::data::DataStatement DataStatement;
        typedef gate::data::DataReader DataReader;


        class GATE_API_LOCAL SqldbApp : public App
        {
        private:

            DataConnection createDataConnection(String const& provider, String const& dbPath, uint32_t dbflags)
            {
                if (provider.equalsIC(dbProviderOdbcName))
                {
                    Result<DataConnection> result = data::OdbcDataConnection::tryCreateConnection(dbPath, dbflags);
                    if (result.hasError())
                    {
                        ConError << "Failed to create ODBC DB connection" << strings::NewLine;
                        GATEXX_RAISE_ERROR(result.error());
                    }
                    return result.value();
                }
                else if (provider.equalsIC(dbProvSqlite))
                {
                    Result<DataConnection> result = data::Sqlite3DataConnection::tryCreateConnection(dbPath, dbflags);
                    if (result.hasError())
                    {
                        ConError << "Failed to create SQLITE3 DB connection" << strings::NewLine;
                        GATEXX_RAISE_ERROR(result.error());
                    }
                    return result.value();
                }
                else if (provider.equalsIC(dbProvMysql))
                {
                    Result<DataConnection> result = data::MysqlDataConnection::tryCreateConnection(dbPath, dbflags);
                    if (result.hasError())
                    {
                        ConError << "Failed to create MYSQL DB connection" << strings::NewLine;
                        GATEXX_RAISE_ERROR(result.error());
                    }
                    return result.value();
                }

                // else: 
                ConError << "Invalid data provider name" << strings::NewLine;
                GATEXX_RAISE_ERROR(results::InvalidArg);
                return DataConnection();
            }

            static void executeSqlCommand(DataConnection* dataConn, String const* sqlCommand)
            {
                Console << "Executing statement: " << *sqlCommand << strings::NewLine;
                DataStatement stmt = dataConn->createStatement(*sqlCommand);
                int32_t entries = stmt.execute();
                Console << "Sucessfully completed, " << entries << " entries affected" << strings::NewLine;
            }

            static void executeSqlQuery(DataConnection* dataConn, String const* sqlCommand, Stream* ptroutstream, bool csvFormat)
            {
                char const* const separatorChar = csvFormat ? ";" : "\t";

                Console << "Executing query: " << *sqlCommand << strings::NewLine;
                Console << "----------------" << strings::NewLine;
                DataStatement stmt = dataConn->createStatement(*sqlCommand);
                DataReader reader = stmt.query();

                Stream& outstream = ptroutstream ? *ptroutstream : static_cast<Stream&>(Console);

                bool isFirstRecord = true;
                uint32_t rowCounter = 0;
                while (reader.next())
                {
                    ++rowCounter;
                    size_t fieldsCount = reader.getFieldCount();

                    if (isFirstRecord)
                    {
                        isFirstRecord = false;
                        for (size_t ndx = 0; ndx != fieldsCount; ++ndx)
                        {
                            if (ndx > 0)
                            {
                                outstream << separatorChar;
                            }
                            outstream << reader.getFieldName(ndx);
                        }
                        outstream << strings::NewLine;
                    }
                    for (size_t ndx = 0; ndx != fieldsCount; ++ndx)
                    {
                        if (ndx > 0)
                        {
                            outstream << separatorChar;
                        }
                        Value entry = reader.getFieldValue(ndx);
                        String strEntry;
                        entry.exportAs(strEntry);
                        outstream << strEntry;
                    }
                    outstream << strings::NewLine;
                }
                Console << "----------------" << strings::NewLine;
                Console << rowCounter << " rows" << strings::NewLine;
            }

        public:
            virtual void run() override
            {
                static AppOptionDef help = AppOptionDef::createSwitch("help", "?", "show_help", "Shows help");
                static AppOptionDef dbprov = AppOptionDef::createString("db-provider", "P", "odbc", "db_provider", "Database provider (\"odbc\" or \"sqlite\")");
                static AppOptionDef dbpath = AppOptionDef::createString("db-path", "DB", "", "db_path", "Database connection path");
                static AppOptionDef outfile = AppOptionDef::createString("output-file", "O", "", "Path to query result output file");
                static AppOptionDef flags = AppOptionDef::createInt32("flags", "F", 0, "flags", "Provider specific config flags");<--- Shadowed declaration
                static AppOptionDef csvformat = AppOptionDef::createSwitch("csv-format", "C", "csvformat", "Print query result output in CSV format");
                static AppOptionDef dbquery = AppOptionDef::createSwitch("query", "Q", "query", "Execute query and print result");
                static AppOptionDef dbsql = AppOptionDef::createString("", "", "", "sql", "SQL statement to execute");

                static AppOptionDef* options[] =
                {
                    &help,
                    &dbprov,
                    &dbpath,
                    &outfile,
                    &flags,
                    &csvformat,
                    &dbquery,
                    &dbsql
                };

                static size_t const optionsCount = sizeof(options) / sizeof(options[0]);

                App::parseAppOptions(this->getArgs(), options, optionsCount);

                if (help.getBool())
                {
                    App::printAppOptions(options, optionsCount, Console);
                    return;
                }

                String dbprovName = dbprov.getString();
                String dbconnPath = dbpath.getString();
                String outFilePath = outfile.getString();
                bool printCsv = csvformat.getBool();
                bool runQuery = dbquery.getBool();
                uint32_t dbflags = static_cast<uint32_t>(flags.getInt32());
                String sqlCommand = dbsql.getString();

                DataConnection dataConn = createDataConnection(dbprovName, dbconnPath, dbflags);
                if (!dataConn)
                {
                    return;
                }

                if (sqlCommand.empty())
                {
                    ConError << "Missing SQL command" << strings::NewLine;
                    GATEXX_RAISE_ERROR(results::InvalidArg);
                    return;
                }

                Runnable task;
                if (!runQuery)
                {
                    task = RunnableBuilder::create(&SqldbApp::executeSqlCommand,
                        &dataConn, &sqlCommand);
                }
                else
                {
                    Optional<FileStream> fs;
                    if (!outFilePath.empty())
                    {
                        FileStream outfile(outFilePath, File::Open_Write);
                        fs.create(outfile);<--- Shadow variable
                    }
                    Stream* ptrFilestream = fs.get();
                    task = RunnableBuilder::create(&SqldbApp::executeSqlQuery,
                        &dataConn, &sqlCommand, ptrFilestream, printCsv);
                }

                ExceptionInfo xinfo = catchException(task);
                if (xinfo.failed())
                {
                    ConError << "Failed to execute SQL task" << strings::NewLine;
                    xinfo.raise();
                }
            }
        };

    }   // end of namespace apps
}	// end of namespace gate

#include <stdio.h>

int gate_main(char const* program, char const* const* arguments, gate_size_t argcount, gate_uintptr_t apphandle)
{
    gate::apps::SqldbApp app;
    return gate::App::runApp(app, program, arguments, argcount, apphandle);
}