function DBDropColumn moved to libnxdb from nxdbmgr
[public/netxms.git] / src / server / tools / nxdbmgr / nxdbmgr.cpp
CommitLineData
2589cc10 1/*
5039dede 2** nxdbmgr - NetXMS database manager
74724c20 3** Copyright (C) 2004-2017 Victor Kirhenshtein
5039dede
AK
4**
5** This program is free software; you can redistribute it and/or modify
6** it under the terms of the GNU General Public License as published by
7** the Free Software Foundation; either version 2 of the License, or
8** (at your option) any later version.
9**
10** This program is distributed in the hope that it will be useful,
11** but WITHOUT ANY WARRANTY; without even the implied warranty of
12** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13** GNU General Public License for more details.
14**
15** You should have received a copy of the GNU General Public License
16** along with this program; if not, write to the Free Software
17** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18**
19** File: nxdbmgr.cpp
20**
21**/
22
23#include "nxdbmgr.h"
e6c91aac 24#include <nxconfig.h>
5039dede
AK
25
26#ifdef _WIN32
27#include <conio.h>
28#endif
29
69bb7f47
VK
30/**
31 * Global variables
32 */
5039dede
AK
33DB_HANDLE g_hCoreDB;
34BOOL g_bIgnoreErrors = FALSE;
35BOOL g_bTrace = FALSE;
a4743a0f 36bool g_isGuiMode = false;
0d9b58ef 37bool g_checkData = false;
daf3c104 38bool g_checkDataTablesOnly = false;
ffaafdce
VK
39bool g_dataOnlyMigration = false;
40bool g_skipDataMigration = false;
09f1c9bf
VK
41bool g_skipDataSchemaMigration = false;
42int g_migrationTxnSize = 4096;
2a964810 43int g_dbSyntax;
5039dede 44const TCHAR *g_pszTableSuffix = _T("");
2589cc10 45const TCHAR *g_pszSqlType[6][3] =
5039dede 46{
49e749f3 47 { _T("longtext"), _T("text"), _T("bigint") }, // MySQL
50da2d20
VK
48 { _T("text"), _T("varchar(4000)"), _T("bigint") }, // PostgreSQL
49 { _T("text"), _T("varchar(4000)"), _T("bigint") }, // Microsoft SQL
50 { _T("clob"), _T("varchar(4000)"), _T("number(20)") }, // Oracle
51 { _T("varchar"), _T("varchar(4000)"), _T("number(20)") }, // SQLite
52 { _T("long varchar"), _T("varchar(4000)"), _T("bigint") } // DB/2
5039dede
AK
53};
54
69bb7f47
VK
55/**
56 * Static data
57 */
29dc8792 58static char m_szCodePage[MAX_PATH] = ICONV_DEFAULT_CODEPAGE;
b8c1ec69
VK
59static TCHAR s_dbDriver[MAX_PATH] = _T("");
60static TCHAR s_dbDrvParams[MAX_PATH] = _T("");
61static TCHAR s_dbServer[MAX_PATH] = _T("127.0.0.1");
62static TCHAR s_dbLogin[MAX_DB_LOGIN] = _T("netxms");
07ca7d19 63static TCHAR s_dbPassword[MAX_PASSWORD] = _T("");
b8c1ec69 64static TCHAR s_dbName[MAX_DB_NAME] = _T("netxms_db");
f3c30cf5 65static TCHAR s_dbSchema[MAX_DB_NAME] = _T("");
5039dede
AK
66static NX_CFG_TEMPLATE m_cfgTemplate[] =
67{
dda7c270 68 { _T("CodePage"), CT_MB_STRING, 0, 0, MAX_PATH, 0, m_szCodePage },
08b214c6
VK
69 { _T("DBDriver"), CT_STRING, 0, 0, MAX_PATH, 0, s_dbDriver },
70 { _T("DBDrvParams"), CT_STRING, 0, 0, MAX_PATH, 0, s_dbDrvParams },
08b214c6
VK
71 { _T("DBLogin"), CT_STRING, 0, 0, MAX_DB_LOGIN, 0, s_dbLogin },
72 { _T("DBName"), CT_STRING, 0, 0, MAX_DB_NAME, 0, s_dbName },
07ca7d19 73 { _T("DBPassword"), CT_STRING, 0, 0, MAX_PASSWORD, 0, s_dbPassword },
74 { _T("DBEncryptedPassword"), CT_STRING, 0, 0, MAX_PASSWORD, 0, s_dbPassword },
d010c10e 75 { _T("DBSchema"), CT_STRING, 0, 0, MAX_DB_NAME, 0, s_dbSchema },
08b214c6 76 { _T("DBServer"), CT_STRING, 0, 0, MAX_PATH, 0, s_dbServer },
08b214c6 77 { _T(""), CT_END_OF_LIST, 0, 0, 0, 0, NULL }
5039dede
AK
78};
79static BOOL m_bForce = FALSE;
63604cda 80static DB_DRIVER s_driver = NULL;
5039dede 81
69bb7f47
VK
82/**
83 * Show query if trace mode is ON
84 */
5039dede
AK
85void ShowQuery(const TCHAR *pszQuery)
86{
f669df41 87 WriteToTerminalEx(_T("\x1b[1m>>> \x1b[32;1m%s\x1b[0m\n"), pszQuery);
5039dede
AK
88}
89
69bb7f47
VK
90/**
91 * Get Yes or No answer from keyboard
92 */
a4743a0f 93bool GetYesNo(const TCHAR *format, ...)
5039dede 94{
a4743a0f 95 va_list args;
5039dede 96
a4743a0f
VK
97 if (g_isGuiMode)
98 {
99 if (m_bForce)
100 return true;
101
102 TCHAR message[4096];
103 va_start(args, format);
104 _vsntprintf(message, 4096, format, args);
105 va_end(args);
106
107#ifdef _WIN32
108 return MessageBox(NULL, message, _T("NetXMS Database Manager"), MB_YESNO | MB_ICONQUESTION) == IDYES;
109#else
110 return false;
111#endif
112 }
113 else
114 {
115 va_start(args, format);
116 _vtprintf(format, args);
117 va_end(args);
9f24efb3 118 _tprintf(_T(" (Y/N) "));
a4743a0f
VK
119
120 if (m_bForce)
121 {
9f24efb3 122 _tprintf(_T("Y\n"));
a4743a0f
VK
123 return true;
124 }
125 else
126 {
127#ifdef _WIN32
128 int ch;
129
130 while(1)
131 {
132 ch = _getch();
133 if ((ch == 'y') || (ch == 'Y'))
134 {
9f24efb3 135 _tprintf(_T("Y\n"));
a4743a0f
VK
136 return true;
137 }
138 if ((ch == 'n') || (ch == 'N'))
139 {
9f24efb3 140 _tprintf(_T("N\n"));
a4743a0f
VK
141 return false;
142 }
143 }
5039dede 144#else
a4743a0f 145 TCHAR szBuffer[16];
5039dede 146
a4743a0f
VK
147 fflush(stdout);
148 _fgetts(szBuffer, 16, stdin);
149 StrStrip(szBuffer);
150 return ((szBuffer[0] == 'y') || (szBuffer[0] == 'Y'));
5039dede 151#endif
a4743a0f
VK
152 }
153 }
5039dede
AK
154}
155
69bb7f47
VK
156/**
157 * Execute SQL SELECT query and print error message on screen if query failed
158 */
5039dede
AK
159DB_RESULT SQLSelect(const TCHAR *pszQuery)
160{
161 DB_RESULT hResult;
162 TCHAR errorText[DBDRV_MAX_ERROR_TEXT];
163
164 if (g_bTrace)
165 ShowQuery(pszQuery);
166
167 hResult = DBSelectEx(g_hCoreDB, pszQuery, errorText);
168 if (hResult == NULL)
f669df41 169 WriteToTerminalEx(_T("SQL query failed (%s):\n\x1b[33;1m%s\x1b[0m\n"), errorText, pszQuery);
4c4c9b03
VK
170 return hResult;
171}
172
69bb7f47 173/**
f17cf019 174 * Execute SQL SELECT query via DBSelectUnbuffered and print error message on screen if query failed
69bb7f47 175 */
f17cf019 176DB_UNBUFFERED_RESULT SQLSelectUnbuffered(const TCHAR *pszQuery)
4c4c9b03 177{
4c4c9b03
VK
178 if (g_bTrace)
179 ShowQuery(pszQuery);
180
f17cf019
VK
181 TCHAR errorText[DBDRV_MAX_ERROR_TEXT];
182 DB_UNBUFFERED_RESULT hResult = DBSelectUnbufferedEx(g_hCoreDB, pszQuery, errorText);
4c4c9b03 183 if (hResult == NULL)
f669df41 184 WriteToTerminalEx(_T("SQL query failed (%s):\n\x1b[33;1m%s\x1b[0m\n"), errorText, pszQuery);
5039dede
AK
185 return hResult;
186}
187
69bb7f47 188/**
84ee0f9c
VK
189 * Execute prepared statement and print error message on screen if query failed
190 */
c85c8ef2 191bool SQLExecute(DB_STATEMENT hStmt)
84ee0f9c
VK
192{
193 TCHAR errorText[DBDRV_MAX_ERROR_TEXT];
194
195 if (g_bTrace)
196 ShowQuery(DBGetStatementSource(hStmt));
197
c85c8ef2 198 bool result = DBExecuteEx(hStmt, errorText);
84ee0f9c
VK
199 if (!result)
200 WriteToTerminalEx(_T("SQL query failed (%s):\n\x1b[33;1m%s\x1b[0m\n"), errorText, DBGetStatementSource(hStmt));
201 return result;
202}
203
204/**
69bb7f47
VK
205 * Execute SQL query and print error message on screen if query failed
206 */
c85c8ef2 207bool SQLQuery(const TCHAR *pszQuery)
5039dede 208{
5039dede 209 if (*pszQuery == 0)
c85c8ef2 210 return true;
5039dede 211
701726bc
VK
212 String query(pszQuery);
213
2a964810
VK
214 query.replace(_T("$SQL:TEXT"), g_pszSqlType[g_dbSyntax][SQL_TYPE_TEXT]);
215 query.replace(_T("$SQL:TXT4K"), g_pszSqlType[g_dbSyntax][SQL_TYPE_TEXT4K]);
216 query.replace(_T("$SQL:INT64"), g_pszSqlType[g_dbSyntax][SQL_TYPE_INT64]);
701726bc 217
5039dede 218 if (g_bTrace)
701726bc 219 ShowQuery(query);
5039dede 220
c85c8ef2
VK
221 TCHAR errorText[DBDRV_MAX_ERROR_TEXT];
222 bool success = DBQueryEx(g_hCoreDB, (const TCHAR *)query, errorText);
223 if (!success)
e10e890e 224 WriteToTerminalEx(_T("SQL query failed (%s):\n\x1b[33;1m%s\x1b[0m\n"), errorText, (const TCHAR *)query);
c85c8ef2 225 return success;
5039dede
AK
226}
227
69bb7f47
VK
228/**
229 * Execute SQL batch
230 */
c85c8ef2 231bool SQLBatch(const TCHAR *pszBatch)
5039dede 232{
8ec9bcc9 233 String batch(pszBatch);
5039dede
AK
234 TCHAR *pszBuffer, *pszQuery, *ptr;
235 TCHAR errorText[DBDRV_MAX_ERROR_TEXT];
c85c8ef2 236 bool success = true;
8ec9bcc9 237 TCHAR table[128], column[128];
5039dede 238
2a964810
VK
239 batch.replace(_T("$SQL:TEXT"), g_pszSqlType[g_dbSyntax][SQL_TYPE_TEXT]);
240 batch.replace(_T("$SQL:TXT4K"), g_pszSqlType[g_dbSyntax][SQL_TYPE_TEXT4K]);
241 batch.replace(_T("$SQL:INT64"), g_pszSqlType[g_dbSyntax][SQL_TYPE_INT64]);
5039dede 242
7618e362 243 pszQuery = pszBuffer = batch.getBuffer();
df5a4953 244 while(true)
5039dede
AK
245 {
246 ptr = _tcschr(pszQuery, _T('\n'));
247 if (ptr != NULL)
248 *ptr = 0;
249 if (!_tcscmp(pszQuery, _T("<END>")))
250 break;
251
8ec9bcc9
AK
252 if (_stscanf(pszQuery, _T("ALTER TABLE %128s DROP COLUMN %128s"), table, column) == 2)
253 {
16684f16 254 if (!DBDropColumn(g_hCoreDB, table, column))
8ec9bcc9 255 {
dc215562 256 WriteToTerminalEx(_T("Cannot drop column \x1b[37;1m%s.%s\x1b[0m\n"), table, column);
8ec9bcc9
AK
257 if (!g_bIgnoreErrors)
258 {
c85c8ef2 259 success = false;
8ec9bcc9
AK
260 break;
261 }
262 }
263 }
264 else
265 {
af0d0e51
VK
266 if (g_bTrace)
267 ShowQuery(pszQuery);
268
8ec9bcc9
AK
269 if (!DBQueryEx(g_hCoreDB, pszQuery, errorText))
270 {
271 WriteToTerminalEx(_T("SQL query failed (%s):\n\x1b[33;1m%s\x1b[0m\n"), errorText, pszQuery);
272 if (!g_bIgnoreErrors)
273 {
c85c8ef2 274 success = false;
8ec9bcc9
AK
275 break;
276 }
277 }
278 }
279
df5a4953
VK
280 if (ptr == NULL)
281 break;
5039dede
AK
282 ptr++;
283 pszQuery = ptr;
284 }
c85c8ef2 285 return success;
5039dede
AK
286}
287
69bb7f47 288/**
a43a5e7d
VK
289 * Read string value from metadata table
290 */
3783d300
VK
291BOOL MetaDataReadStr(const TCHAR *pszVar, TCHAR *pszBuffer, int iBufSize, const TCHAR *pszDefault)
292{
293 DB_RESULT hResult;
294 TCHAR szQuery[256];
295 BOOL bSuccess = FALSE;
296
297 nx_strncpy(pszBuffer, pszDefault, iBufSize);
298 if (_tcslen(pszVar) > 127)
299 return FALSE;
300
301 _sntprintf(szQuery, 256, _T("SELECT var_value FROM metadata WHERE var_name='%s'"), pszVar);
302 hResult = SQLSelect(szQuery);
303 if (hResult == NULL)
304 return FALSE;
305
306 if (DBGetNumRows(hResult) > 0)
307 {
308 DBGetField(hResult, 0, 0, pszBuffer, iBufSize);
309 bSuccess = TRUE;
310 }
311
312 DBFreeResult(hResult);
313 return bSuccess;
314}
315
a43a5e7d 316/**
2f1bc68b
VK
317 * Read integer value from configuration table
318 */
319int MetaDataReadInt(const TCHAR *pszVar, int iDefault)
320{
321 TCHAR szBuffer[64];
322
323 if (MetaDataReadStr(pszVar, szBuffer, 64, _T("")))
324 return _tcstol(szBuffer, NULL, 0);
325 else
326 return iDefault;
327}
328
329/**
a43a5e7d
VK
330 * Read string value from configuration table
331 */
5039dede
AK
332BOOL ConfigReadStr(const TCHAR *pszVar, TCHAR *pszBuffer, int iBufSize, const TCHAR *pszDefault)
333{
334 DB_RESULT hResult;
a50beeec 335 TCHAR szQuery[256];
5039dede
AK
336 BOOL bSuccess = FALSE;
337
338 nx_strncpy(pszBuffer, pszDefault, iBufSize);
339 if (_tcslen(pszVar) > 127)
340 return FALSE;
341
a50beeec 342 _sntprintf(szQuery, 256, _T("SELECT var_value FROM config WHERE var_name='%s'"), pszVar);
5039dede 343 hResult = SQLSelect(szQuery);
3783d300 344 if (hResult == NULL)
5039dede
AK
345 return FALSE;
346
347 if (DBGetNumRows(hResult) > 0)
348 {
349 DBGetField(hResult, 0, 0, pszBuffer, iBufSize);
5039dede
AK
350 bSuccess = TRUE;
351 }
352
353 DBFreeResult(hResult);
354 return bSuccess;
355}
356
c59466d2
VK
357/**
358 * Read integer value from configuration table
359 */
5039dede
AK
360int ConfigReadInt(const TCHAR *pszVar, int iDefault)
361{
362 TCHAR szBuffer[64];
363
364 if (ConfigReadStr(pszVar, szBuffer, 64, _T("")))
365 return _tcstol(szBuffer, NULL, 0);
366 else
367 return iDefault;
368}
369
c59466d2
VK
370/**
371 * Read unsigned long value from configuration table
372 */
5039dede
AK
373DWORD ConfigReadULong(const TCHAR *pszVar, DWORD dwDefault)
374{
375 TCHAR szBuffer[64];
376
377 if (ConfigReadStr(pszVar, szBuffer, 64, _T("")))
378 return _tcstoul(szBuffer, NULL, 0);
379 else
380 return dwDefault;
381}
382
c59466d2 383/**
06b83321
VK
384 * Check if given record exists in database
385 */
386bool IsDatabaseRecordExist(const TCHAR *table, const TCHAR *idColumn, UINT32 id)
387{
388 bool exist = false;
389
390 TCHAR query[256];
391 _sntprintf(query, 256, _T("SELECT %s FROM %s WHERE %s=?"), idColumn, table, idColumn);
392
393 DB_STATEMENT hStmt = DBPrepare(g_hCoreDB, query);
394 if (hStmt != NULL)
395 {
396 DBBind(hStmt, 1, DB_SQLTYPE_INTEGER, id);
397 DB_RESULT hResult = DBSelectPrepared(hStmt);
398 if (hResult != NULL)
399 {
400 exist = (DBGetNumRows(hResult) > 0);
401 DBFreeResult(hResult);
402 }
403 DBFreeStatement(hStmt);
404 }
405 return exist;
406}
407
408/**
c59466d2
VK
409 * Check that database has correct schema version and is not locked
410 */
c85c8ef2 411bool ValidateDatabase()
1e558daf
VK
412{
413 DB_RESULT hResult;
414 LONG nVersion = 0;
bd802b08 415 BOOL bLocked = FALSE;
1e558daf
VK
416 TCHAR szLockStatus[MAX_DB_STRING], szLockInfo[MAX_DB_STRING];
417
418 // Get database format version
28f5b9a4 419 nVersion = DBGetSchemaVersion(g_hCoreDB);
1e558daf
VK
420 if (nVersion < DB_FORMAT_VERSION)
421 {
422 _tprintf(_T("Your database has format version %d, this tool is compiled for version %d.\nUse \"upgrade\" command to upgrade your database first.\n"),
423 nVersion, DB_FORMAT_VERSION);
c85c8ef2 424 return false;
1e558daf
VK
425 }
426 else if (nVersion > DB_FORMAT_VERSION)
427 {
9f24efb3
VK
428 _tprintf(_T("Your database has format version %d, this tool is compiled for version %d.\n")
429 _T("You need to upgrade your server before using this database.\n"),
430 nVersion, DB_FORMAT_VERSION);
c85c8ef2 431 return false;
1e558daf
VK
432 }
433
434 // Check if database is locked
435 hResult = DBSelect(g_hCoreDB, _T("SELECT var_value FROM config WHERE var_name='DBLockStatus'"));
436 if (hResult != NULL)
437 {
438 if (DBGetNumRows(hResult) > 0)
439 {
bf7f9d94 440 DBGetField(hResult, 0, 0, szLockStatus, MAX_DB_STRING);
1e558daf
VK
441 bLocked = _tcscmp(szLockStatus, _T("UNLOCKED"));
442 }
443 DBFreeResult(hResult);
444
445 if (bLocked)
446 {
447 hResult = DBSelect(g_hCoreDB, _T("SELECT var_value FROM config WHERE var_name='DBLockInfo'"));
448 if (hResult != NULL)
449 {
450 if (DBGetNumRows(hResult) > 0)
451 {
bf7f9d94 452 DBGetField(hResult, 0, 0, szLockInfo, MAX_DB_STRING);
1e558daf
VK
453 }
454 DBFreeResult(hResult);
455 }
456 }
457 }
458
459 if (bLocked)
460 {
461 _tprintf(_T("Database is locked by server %s [%s]\n"), szLockStatus, szLockInfo);
c85c8ef2 462 return false;
1e558daf
VK
463 }
464
c85c8ef2 465 return true;
1e558daf
VK
466}
467
c59466d2 468/**
63604cda
VK
469 * Open database connection
470 */
471DB_HANDLE ConnectToDatabase()
472{
473 TCHAR errorText[DBDRV_MAX_ERROR_TEXT];
474 DB_HANDLE hdb = DBConnect(s_driver, s_dbServer, s_dbName, s_dbLogin, s_dbPassword, s_dbSchema, errorText);
475 if (hdb == NULL)
476 {
477 _tprintf(_T("Unable to connect to database %s@%s as %s: %s\n"), s_dbName, s_dbServer, s_dbLogin, errorText);
478 }
479 return hdb;
480}
481
482/**
c59466d2
VK
483 * Startup
484 */
5039dede
AK
485int main(int argc, char *argv[])
486{
6ba36557 487 BOOL bStart = TRUE, bQuiet = FALSE;
c85c8ef2 488 bool replaceValue = true;
5039dede 489 int ch;
5039dede 490
d37e7f10 491 InitNetXMSProcess(true);
5039dede 492
1039d7ee
VK
493 TCHAR configFile[MAX_PATH] = _T("");
494
495 // Try to read config location
5039dede 496#ifdef _WIN32
38ffd4b0 497 HKEY hKey;
1039d7ee 498 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("Software\\NetXMS\\Server"), 0, KEY_QUERY_VALUE, &hKey) == ERROR_SUCCESS)
5039dede 499 {
38ffd4b0 500 DWORD dwSize = MAX_PATH * sizeof(TCHAR);
1039d7ee 501 RegQueryValueEx(hKey, _T("ConfigFile"), NULL, NULL, (BYTE *)configFile, &dwSize);
5039dede
AK
502 RegCloseKey(hKey);
503 }
504#else
38ffd4b0
VK
505 const TCHAR *env = _tgetenv(_T("NETXMSD_CONFIG"));
506 if ((env != NULL) && (*env != 0))
1039d7ee
VK
507 nx_strncpy(configFile, env, MAX_PATH);
508#endif
509
510 // Search for config
511 if (configFile[0] == 0)
512 {
513#ifdef _WIN32
514 TCHAR path[MAX_PATH];
515 GetNetXMSDirectory(nxDirEtc, path);
516 _tcscat(path, _T("\\netxmsd.conf"));
517 if (_taccess(path, 4) == 0)
518 {
519 _tcscpy(configFile, path);
520 }
521 else
522 {
523 _tcscpy(configFile, _T("C:\\netxmsd.conf"));
524 }
525#else
526 const TCHAR *homeDir = _tgetenv(_T("NETXMS_HOME"));
527 if ((homeDir != NULL) && (*homeDir != 0))
528 {
529 TCHAR config[MAX_PATH];
530 _sntprintf(config, MAX_PATH, _T("%s/etc/netxmsd.conf"), homeDir);
531 if (_taccess(config, 4) == 0)
532 {
533 _tcscpy(configFile, config);
534 goto stop_search;
535 }
536 }
537 if (_taccess(PREFIX _T("/etc/netxmsd.conf"), 4) == 0)
538 {
539 _tcscpy(configFile, PREFIX _T("/etc/netxmsd.conf"));
540 }
541 else if (_taccess(_T("/usr/etc/netxmsd.conf"), 4) == 0)
542 {
543 _tcscpy(configFile, _T("/usr/etc/netxmsd.conf"));
544 }
545 else
546 {
547 _tcscpy(configFile, _T("/etc/netxmsd.conf"));
548 }
549stop_search:
550 ;
5039dede 551#endif
1039d7ee 552 }
5039dede
AK
553
554 // Parse command line
555 opterr = 1;
09f1c9bf 556 while((ch = getopt(argc, argv, "c:dDfGhIMNqsStT:vX")) != -1)
5039dede
AK
557 {
558 switch(ch)
559 {
560 case 'h': // Display help and exit
f62b7eab 561 _tprintf(_T("NetXMS Database Manager Version ") NETXMS_VERSION_STRING _T(" Build ") NETXMS_VERSION_BUILD_STRING _T(" (") NETXMS_BUILD_TAG _T(")") IS_UNICODE_BUILD_STRING _T("\n\n"));
08b214c6
VK
562 _tprintf(_T("Usage: nxdbmgr [<options>] <command>\n")
563 _T("Valid commands are:\n")
be737a59
VK
564 _T(" batch <file> : Run SQL batch file\n")
565 _T(" check : Check database for errors\n")
566 _T(" check-data-tables : Check database for missing data tables\n")
567 _T(" export <file> : Export database to file\n")
568 _T(" get <name> : Get value of server configuration variable\n")
569 _T(" import <file> : Import database from file\n")
570 _T(" init <file> : Initialize database\n")
571 _T(" migrate <source> : Migrate database from given source\n")
572 _T(" reset-system-account : Unlock user \"system\" and reset it's password to default\n")
573 _T(" set <name> <value> : Set value of server configuration variable\n")
574 _T(" unlock : Forced database unlock\n")
575 _T(" upgrade : Upgrade database to new version\n")
08b214c6 576 _T("Valid options are:\n")
1039d7ee 577 _T(" -c <config> : Use alternate configuration file. Default is %s\n")
0d9b58ef 578 _T(" -d : Check collected data (may take very long time).\n")
ffaafdce 579 _T(" -D : Migrate only collected data.\n")
08b214c6 580 _T(" -f : Force repair - do not ask for confirmation.\n")
a4743a0f 581#ifdef _WIN32
08b214c6 582 _T(" -G : GUI mode.\n")
a4743a0f 583#endif
08b214c6
VK
584 _T(" -h : Display help and exit.\n")
585 _T(" -I : MySQL only - specify TYPE=InnoDB for new tables.\n")
586 _T(" -M : MySQL only - specify TYPE=MyISAM for new tables.\n")
8038d371 587 _T(" -N : Do not replace existing configuration value (\"set\" command only).\n")
a43a5e7d 588 _T(" -q : Quiet mode (don't show startup banner).\n")
4da7f408
VK
589 _T(" -s : Skip collected data during migration or export.\n")
590 _T(" -S : Skip collected data during migration or export and do not clear or create data tables.\n")
08b214c6 591 _T(" -t : Enable trace mode (show executed SQL queries).\n")
09f1c9bf 592 _T(" -T <recs> : Transaction size for migration.\n")
08b214c6 593 _T(" -v : Display version and exit.\n")
300c7968 594 _T(" -X : Ignore SQL errors when upgrading (USE WITH CAUTION!!!)\n")
1039d7ee 595 _T("\n"), configFile);
5039dede
AK
596 bStart = FALSE;
597 break;
598 case 'v': // Print version and exit
f62b7eab 599 _tprintf(_T("NetXMS Database Manager Version ") NETXMS_VERSION_STRING _T(" Build ") NETXMS_VERSION_BUILD_STRING _T(" (") NETXMS_BUILD_TAG _T(")") IS_UNICODE_BUILD_STRING _T("\n\n"));
5039dede
AK
600 bStart = FALSE;
601 break;
602 case 'c':
08b214c6 603#ifdef UNICODE
1039d7ee
VK
604 MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, optarg, -1, configFile, MAX_PATH);
605 configFile[MAX_PATH - 1] = 0;
08b214c6 606#else
1039d7ee 607 nx_strncpy(configFile, optarg, MAX_PATH);
08b214c6 608#endif
5039dede 609 break;
0d9b58ef
VK
610 case 'd':
611 g_checkData = true;
612 break;
ffaafdce
VK
613 case 'D':
614 g_dataOnlyMigration = true;
615 break;
5039dede
AK
616 case 'f':
617 m_bForce = TRUE;
618 break;
a4743a0f
VK
619 case 'G':
620 g_isGuiMode = true;
621 break;
8038d371 622 case 'N':
c85c8ef2 623 replaceValue = false;
8038d371 624 break;
a43a5e7d
VK
625 case 'q':
626 bQuiet = TRUE;
627 break;
ffaafdce
VK
628 case 's':
629 g_skipDataMigration = true;
630 break;
09f1c9bf
VK
631 case 'S':
632 g_skipDataMigration = true;
633 g_skipDataSchemaMigration = true;
634 break;
5039dede
AK
635 case 't':
636 g_bTrace = TRUE;
637 break;
09f1c9bf
VK
638 case 'T':
639 g_migrationTxnSize = strtol(optarg, NULL, 0);
640 if ((g_migrationTxnSize < 1) || (g_migrationTxnSize > 100000))
641 {
642 _tprintf(_T("WARNING: invalid transaction size, reset to default"));
643 g_migrationTxnSize = 4096;
644 }
645 break;
5039dede
AK
646 case 'I':
647 g_pszTableSuffix = _T(" TYPE=InnoDB");
648 break;
649 case 'M':
650 g_pszTableSuffix = _T(" TYPE=MyISAM");
651 break;
652 case 'X':
653 g_bIgnoreErrors = TRUE;
654 break;
655 case '?':
656 bStart = FALSE;
657 break;
658 default:
659 break;
660 }
661 }
662
663 if (!bStart)
664 return 1;
665
a43a5e7d 666 if (!bQuiet)
f62b7eab 667 _tprintf(_T("NetXMS Database Manager Version ") NETXMS_VERSION_STRING _T(" Build ") NETXMS_VERSION_BUILD_STRING _T(" (") NETXMS_BUILD_TAG _T(")") IS_UNICODE_BUILD_STRING _T("\n\n"));
a43a5e7d 668
5039dede
AK
669 // Check parameter correctness
670 if (argc - optind == 0)
671 {
9f24efb3 672 _tprintf(_T("Command missing. Type nxdbmgr -h for command line syntax.\n"));
5039dede
AK
673 return 1;
674 }
2589cc10 675 if (strcmp(argv[optind], "batch") &&
676 strcmp(argv[optind], "check") &&
677 strcmp(argv[optind], "check-data-tables") &&
678 strcmp(argv[optind], "export") &&
679 strcmp(argv[optind], "get") &&
680 strcmp(argv[optind], "import") &&
a43a5e7d 681 strcmp(argv[optind], "init") &&
84ee0f9c 682 strcmp(argv[optind], "migrate") &&
be737a59 683 strcmp(argv[optind], "reset-system-account") &&
a43a5e7d 684 strcmp(argv[optind], "set") &&
5039dede 685 strcmp(argv[optind], "unlock") &&
84ee0f9c 686 strcmp(argv[optind], "upgrade"))
5039dede 687 {
9f24efb3 688 _tprintf(_T("Invalid command \"%hs\". Type nxdbmgr -h for command line syntax.\n"), argv[optind]);
5039dede
AK
689 return 1;
690 }
84ee0f9c 691 if (((!strcmp(argv[optind], "init") || !strcmp(argv[optind], "batch") || !strcmp(argv[optind], "export") || !strcmp(argv[optind], "import") || !strcmp(argv[optind], "get") || !strcmp(argv[optind], "migrate")) && (argc - optind < 2)) ||
a43a5e7d 692 (!strcmp(argv[optind], "set") && (argc - optind < 3)))
5039dede 693 {
2467ed57 694 _tprintf(_T("Required command argument(s) missing\n"));
5039dede
AK
695 return 1;
696 }
697
698 // Read configuration file
e6c91aac 699 Config *config = new Config();
1039d7ee 700 if (!config->loadIniConfig(configFile, _T("server")) || !config->parseTemplate(_T("server"), m_cfgTemplate))
5039dede 701 {
9f24efb3 702 _tprintf(_T("Error loading configuration file\n"));
5039dede
AK
703 return 2;
704 }
e6c91aac
VK
705 delete config;
706
d96bd4c7 707 // Decrypt password
07ca7d19 708 DecryptPassword(s_dbLogin, s_dbPassword, s_dbPassword, MAX_PASSWORD);
d96bd4c7 709
5039dede 710#ifndef _WIN32
35f836fe 711 SetDefaultCodepage(m_szCodePage);
5039dede
AK
712#endif
713
714 // Connect to database
b8c1ec69 715 if (!DBInit(0, 0))
5039dede 716 {
9f24efb3 717 _tprintf(_T("Unable to initialize database library\n"));
5039dede
AK
718 return 3;
719 }
720
63604cda
VK
721 s_driver = DBLoadDriver(s_dbDriver, s_dbDrvParams, false, NULL, NULL);
722 if (s_driver == NULL)
b8c1ec69
VK
723 {
724 _tprintf(_T("Unable to load and initialize database driver \"%s\"\n"), s_dbDriver);
725 return 3;
726 }
727
63604cda 728 g_hCoreDB = ConnectToDatabase();
5039dede
AK
729 if (g_hCoreDB == NULL)
730 {
63604cda 731 DBUnloadDriver(s_driver);
5039dede
AK
732 return 4;
733 }
734
735 if (!strcmp(argv[optind], "init"))
736 {
737 InitDatabase(argv[optind + 1]);
738 }
739 else
740 {
741 // Get database syntax
2a964810
VK
742 g_dbSyntax = DBGetSyntax(g_hCoreDB);
743 if (g_dbSyntax == DB_SYNTAX_UNKNOWN)
28f5b9a4 744 {
5039dede
AK
745 _tprintf(_T("Unable to determine database syntax\n"));
746 DBDisconnect(g_hCoreDB);
63604cda 747 DBUnloadDriver(s_driver);
5039dede
AK
748 return 5;
749 }
750
5039dede
AK
751 // Do requested operation
752 if (!strcmp(argv[optind], "batch"))
daf3c104 753 {
5039dede 754 ExecSQLBatch(argv[optind + 1]);
daf3c104 755 }
5039dede 756 else if (!strcmp(argv[optind], "check"))
daf3c104
VK
757 {
758 CheckDatabase();
759 }
760 else if (!strcmp(argv[optind], "check-data-tables"))
761 {
762 g_checkDataTablesOnly = true;
5039dede 763 CheckDatabase();
daf3c104 764 }
5039dede 765 else if (!strcmp(argv[optind], "upgrade"))
daf3c104 766 {
5039dede 767 UpgradeDatabase();
daf3c104 768 }
5039dede 769 else if (!strcmp(argv[optind], "unlock"))
daf3c104 770 {
5039dede 771 UnlockDatabase();
daf3c104 772 }
1e558daf 773 else if (!strcmp(argv[optind], "export"))
daf3c104 774 {
4f23eecc 775 ExportDatabase(argv[optind + 1]);
daf3c104 776 }
890a0930 777 else if (!strcmp(argv[optind], "import"))
daf3c104 778 {
890a0930 779 ImportDatabase(argv[optind + 1]);
daf3c104 780 }
84ee0f9c
VK
781 else if (!strcmp(argv[optind], "migrate"))
782 {
783#ifdef UNICODE
784 WCHAR *sourceConfig = WideStringFromMBString(argv[optind + 1]);
785#else
786 char *sourceConfig = argv[optind + 1];
787#endif
f82c865a
EJ
788 TCHAR destConfFields[2048];
789 _sntprintf(destConfFields, 2048, _T("\tDB Name: %s\n\tDB Server: %s\n\tDB Login: %s"), s_dbName, s_dbServer, s_dbLogin);
790 MigrateDatabase(sourceConfig, destConfFields);
84ee0f9c
VK
791#ifdef UNICODE
792 free(sourceConfig);
793#endif
794 }
a43a5e7d
VK
795 else if (!strcmp(argv[optind], "get"))
796 {
797#ifdef UNICODE
798 WCHAR *var = WideStringFromMBString(argv[optind + 1]);
799#else
800 char *var = argv[optind + 1];
801#endif
2589cc10 802 TCHAR buffer[MAX_CONFIG_VALUE];
803 ConfigReadStr(var, buffer, MAX_CONFIG_VALUE, _T(""));
a43a5e7d
VK
804 _tprintf(_T("%s\n"), buffer);
805#ifdef UNICODE
806 free(var);
807#endif
808 }
809 else if (!strcmp(argv[optind], "set"))
810 {
811#ifdef UNICODE
812 WCHAR *var = WideStringFromMBString(argv[optind + 1]);
813 WCHAR *value = WideStringFromMBString(argv[optind + 2]);
814#else
815 char *var = argv[optind + 1];
816 char *value = argv[optind + 2];
817#endif
c85c8ef2 818 CreateConfigParam(var, value, true, false, replaceValue);
a43a5e7d
VK
819#ifdef UNICODE
820 free(var);
821 free(value);
822#endif
823 }
be737a59 824 else if (!strcmp(argv[optind], "reset-system-account"))
c614ca60 825 {
be737a59 826 ResetSystemAccount();
c614ca60 827 }
5039dede
AK
828 }
829
830 // Shutdown
831 DBDisconnect(g_hCoreDB);
63604cda 832 DBUnloadDriver(s_driver);
5039dede
AK
833 return 0;
834}