function DBDropColumn moved to libnxdb from nxdbmgr
[public/netxms.git] / src / server / tools / nxdbmgr / nxdbmgr.cpp
1 /*
2 ** nxdbmgr - NetXMS database manager
3 ** Copyright (C) 2004-2017 Victor Kirhenshtein
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"
24 #include <nxconfig.h>
25
26 #ifdef _WIN32
27 #include <conio.h>
28 #endif
29
30 /**
31 * Global variables
32 */
33 DB_HANDLE g_hCoreDB;
34 BOOL g_bIgnoreErrors = FALSE;
35 BOOL g_bTrace = FALSE;
36 bool g_isGuiMode = false;
37 bool g_checkData = false;
38 bool g_checkDataTablesOnly = false;
39 bool g_dataOnlyMigration = false;
40 bool g_skipDataMigration = false;
41 bool g_skipDataSchemaMigration = false;
42 int g_migrationTxnSize = 4096;
43 int g_dbSyntax;
44 const TCHAR *g_pszTableSuffix = _T("");
45 const TCHAR *g_pszSqlType[6][3] =
46 {
47 { _T("longtext"), _T("text"), _T("bigint") }, // MySQL
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
53 };
54
55 /**
56 * Static data
57 */
58 static char m_szCodePage[MAX_PATH] = ICONV_DEFAULT_CODEPAGE;
59 static TCHAR s_dbDriver[MAX_PATH] = _T("");
60 static TCHAR s_dbDrvParams[MAX_PATH] = _T("");
61 static TCHAR s_dbServer[MAX_PATH] = _T("127.0.0.1");
62 static TCHAR s_dbLogin[MAX_DB_LOGIN] = _T("netxms");
63 static TCHAR s_dbPassword[MAX_PASSWORD] = _T("");
64 static TCHAR s_dbName[MAX_DB_NAME] = _T("netxms_db");
65 static TCHAR s_dbSchema[MAX_DB_NAME] = _T("");
66 static NX_CFG_TEMPLATE m_cfgTemplate[] =
67 {
68 { _T("CodePage"), CT_MB_STRING, 0, 0, MAX_PATH, 0, m_szCodePage },
69 { _T("DBDriver"), CT_STRING, 0, 0, MAX_PATH, 0, s_dbDriver },
70 { _T("DBDrvParams"), CT_STRING, 0, 0, MAX_PATH, 0, s_dbDrvParams },
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 },
73 { _T("DBPassword"), CT_STRING, 0, 0, MAX_PASSWORD, 0, s_dbPassword },
74 { _T("DBEncryptedPassword"), CT_STRING, 0, 0, MAX_PASSWORD, 0, s_dbPassword },
75 { _T("DBSchema"), CT_STRING, 0, 0, MAX_DB_NAME, 0, s_dbSchema },
76 { _T("DBServer"), CT_STRING, 0, 0, MAX_PATH, 0, s_dbServer },
77 { _T(""), CT_END_OF_LIST, 0, 0, 0, 0, NULL }
78 };
79 static BOOL m_bForce = FALSE;
80 static DB_DRIVER s_driver = NULL;
81
82 /**
83 * Show query if trace mode is ON
84 */
85 void ShowQuery(const TCHAR *pszQuery)
86 {
87 WriteToTerminalEx(_T("\x1b[1m>>> \x1b[32;1m%s\x1b[0m\n"), pszQuery);
88 }
89
90 /**
91 * Get Yes or No answer from keyboard
92 */
93 bool GetYesNo(const TCHAR *format, ...)
94 {
95 va_list args;
96
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);
118 _tprintf(_T(" (Y/N) "));
119
120 if (m_bForce)
121 {
122 _tprintf(_T("Y\n"));
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 {
135 _tprintf(_T("Y\n"));
136 return true;
137 }
138 if ((ch == 'n') || (ch == 'N'))
139 {
140 _tprintf(_T("N\n"));
141 return false;
142 }
143 }
144 #else
145 TCHAR szBuffer[16];
146
147 fflush(stdout);
148 _fgetts(szBuffer, 16, stdin);
149 StrStrip(szBuffer);
150 return ((szBuffer[0] == 'y') || (szBuffer[0] == 'Y'));
151 #endif
152 }
153 }
154 }
155
156 /**
157 * Execute SQL SELECT query and print error message on screen if query failed
158 */
159 DB_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)
169 WriteToTerminalEx(_T("SQL query failed (%s):\n\x1b[33;1m%s\x1b[0m\n"), errorText, pszQuery);
170 return hResult;
171 }
172
173 /**
174 * Execute SQL SELECT query via DBSelectUnbuffered and print error message on screen if query failed
175 */
176 DB_UNBUFFERED_RESULT SQLSelectUnbuffered(const TCHAR *pszQuery)
177 {
178 if (g_bTrace)
179 ShowQuery(pszQuery);
180
181 TCHAR errorText[DBDRV_MAX_ERROR_TEXT];
182 DB_UNBUFFERED_RESULT hResult = DBSelectUnbufferedEx(g_hCoreDB, pszQuery, errorText);
183 if (hResult == NULL)
184 WriteToTerminalEx(_T("SQL query failed (%s):\n\x1b[33;1m%s\x1b[0m\n"), errorText, pszQuery);
185 return hResult;
186 }
187
188 /**
189 * Execute prepared statement and print error message on screen if query failed
190 */
191 bool SQLExecute(DB_STATEMENT hStmt)
192 {
193 TCHAR errorText[DBDRV_MAX_ERROR_TEXT];
194
195 if (g_bTrace)
196 ShowQuery(DBGetStatementSource(hStmt));
197
198 bool result = DBExecuteEx(hStmt, errorText);
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 /**
205 * Execute SQL query and print error message on screen if query failed
206 */
207 bool SQLQuery(const TCHAR *pszQuery)
208 {
209 if (*pszQuery == 0)
210 return true;
211
212 String query(pszQuery);
213
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]);
217
218 if (g_bTrace)
219 ShowQuery(query);
220
221 TCHAR errorText[DBDRV_MAX_ERROR_TEXT];
222 bool success = DBQueryEx(g_hCoreDB, (const TCHAR *)query, errorText);
223 if (!success)
224 WriteToTerminalEx(_T("SQL query failed (%s):\n\x1b[33;1m%s\x1b[0m\n"), errorText, (const TCHAR *)query);
225 return success;
226 }
227
228 /**
229 * Execute SQL batch
230 */
231 bool SQLBatch(const TCHAR *pszBatch)
232 {
233 String batch(pszBatch);
234 TCHAR *pszBuffer, *pszQuery, *ptr;
235 TCHAR errorText[DBDRV_MAX_ERROR_TEXT];
236 bool success = true;
237 TCHAR table[128], column[128];
238
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]);
242
243 pszQuery = pszBuffer = batch.getBuffer();
244 while(true)
245 {
246 ptr = _tcschr(pszQuery, _T('\n'));
247 if (ptr != NULL)
248 *ptr = 0;
249 if (!_tcscmp(pszQuery, _T("<END>")))
250 break;
251
252 if (_stscanf(pszQuery, _T("ALTER TABLE %128s DROP COLUMN %128s"), table, column) == 2)
253 {
254 if (!DBDropColumn(g_hCoreDB, table, column))
255 {
256 WriteToTerminalEx(_T("Cannot drop column \x1b[37;1m%s.%s\x1b[0m\n"), table, column);
257 if (!g_bIgnoreErrors)
258 {
259 success = false;
260 break;
261 }
262 }
263 }
264 else
265 {
266 if (g_bTrace)
267 ShowQuery(pszQuery);
268
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 {
274 success = false;
275 break;
276 }
277 }
278 }
279
280 if (ptr == NULL)
281 break;
282 ptr++;
283 pszQuery = ptr;
284 }
285 return success;
286 }
287
288 /**
289 * Read string value from metadata table
290 */
291 BOOL 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
316 /**
317 * Read integer value from configuration table
318 */
319 int 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 /**
330 * Read string value from configuration table
331 */
332 BOOL ConfigReadStr(const TCHAR *pszVar, TCHAR *pszBuffer, int iBufSize, const TCHAR *pszDefault)
333 {
334 DB_RESULT hResult;
335 TCHAR szQuery[256];
336 BOOL bSuccess = FALSE;
337
338 nx_strncpy(pszBuffer, pszDefault, iBufSize);
339 if (_tcslen(pszVar) > 127)
340 return FALSE;
341
342 _sntprintf(szQuery, 256, _T("SELECT var_value FROM config WHERE var_name='%s'"), pszVar);
343 hResult = SQLSelect(szQuery);
344 if (hResult == NULL)
345 return FALSE;
346
347 if (DBGetNumRows(hResult) > 0)
348 {
349 DBGetField(hResult, 0, 0, pszBuffer, iBufSize);
350 bSuccess = TRUE;
351 }
352
353 DBFreeResult(hResult);
354 return bSuccess;
355 }
356
357 /**
358 * Read integer value from configuration table
359 */
360 int 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
370 /**
371 * Read unsigned long value from configuration table
372 */
373 DWORD 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
383 /**
384 * Check if given record exists in database
385 */
386 bool 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 /**
409 * Check that database has correct schema version and is not locked
410 */
411 bool ValidateDatabase()
412 {
413 DB_RESULT hResult;
414 LONG nVersion = 0;
415 BOOL bLocked = FALSE;
416 TCHAR szLockStatus[MAX_DB_STRING], szLockInfo[MAX_DB_STRING];
417
418 // Get database format version
419 nVersion = DBGetSchemaVersion(g_hCoreDB);
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);
424 return false;
425 }
426 else if (nVersion > DB_FORMAT_VERSION)
427 {
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);
431 return false;
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 {
440 DBGetField(hResult, 0, 0, szLockStatus, MAX_DB_STRING);
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 {
452 DBGetField(hResult, 0, 0, szLockInfo, MAX_DB_STRING);
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);
462 return false;
463 }
464
465 return true;
466 }
467
468 /**
469 * Open database connection
470 */
471 DB_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 /**
483 * Startup
484 */
485 int main(int argc, char *argv[])
486 {
487 BOOL bStart = TRUE, bQuiet = FALSE;
488 bool replaceValue = true;
489 int ch;
490
491 InitNetXMSProcess(true);
492
493 TCHAR configFile[MAX_PATH] = _T("");
494
495 // Try to read config location
496 #ifdef _WIN32
497 HKEY hKey;
498 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("Software\\NetXMS\\Server"), 0, KEY_QUERY_VALUE, &hKey) == ERROR_SUCCESS)
499 {
500 DWORD dwSize = MAX_PATH * sizeof(TCHAR);
501 RegQueryValueEx(hKey, _T("ConfigFile"), NULL, NULL, (BYTE *)configFile, &dwSize);
502 RegCloseKey(hKey);
503 }
504 #else
505 const TCHAR *env = _tgetenv(_T("NETXMSD_CONFIG"));
506 if ((env != NULL) && (*env != 0))
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 }
549 stop_search:
550 ;
551 #endif
552 }
553
554 // Parse command line
555 opterr = 1;
556 while((ch = getopt(argc, argv, "c:dDfGhIMNqsStT:vX")) != -1)
557 {
558 switch(ch)
559 {
560 case 'h': // Display help and exit
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"));
562 _tprintf(_T("Usage: nxdbmgr [<options>] <command>\n")
563 _T("Valid commands are:\n")
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")
576 _T("Valid options are:\n")
577 _T(" -c <config> : Use alternate configuration file. Default is %s\n")
578 _T(" -d : Check collected data (may take very long time).\n")
579 _T(" -D : Migrate only collected data.\n")
580 _T(" -f : Force repair - do not ask for confirmation.\n")
581 #ifdef _WIN32
582 _T(" -G : GUI mode.\n")
583 #endif
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")
587 _T(" -N : Do not replace existing configuration value (\"set\" command only).\n")
588 _T(" -q : Quiet mode (don't show startup banner).\n")
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")
591 _T(" -t : Enable trace mode (show executed SQL queries).\n")
592 _T(" -T <recs> : Transaction size for migration.\n")
593 _T(" -v : Display version and exit.\n")
594 _T(" -X : Ignore SQL errors when upgrading (USE WITH CAUTION!!!)\n")
595 _T("\n"), configFile);
596 bStart = FALSE;
597 break;
598 case 'v': // Print version and exit
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"));
600 bStart = FALSE;
601 break;
602 case 'c':
603 #ifdef UNICODE
604 MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, optarg, -1, configFile, MAX_PATH);
605 configFile[MAX_PATH - 1] = 0;
606 #else
607 nx_strncpy(configFile, optarg, MAX_PATH);
608 #endif
609 break;
610 case 'd':
611 g_checkData = true;
612 break;
613 case 'D':
614 g_dataOnlyMigration = true;
615 break;
616 case 'f':
617 m_bForce = TRUE;
618 break;
619 case 'G':
620 g_isGuiMode = true;
621 break;
622 case 'N':
623 replaceValue = false;
624 break;
625 case 'q':
626 bQuiet = TRUE;
627 break;
628 case 's':
629 g_skipDataMigration = true;
630 break;
631 case 'S':
632 g_skipDataMigration = true;
633 g_skipDataSchemaMigration = true;
634 break;
635 case 't':
636 g_bTrace = TRUE;
637 break;
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;
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
666 if (!bQuiet)
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"));
668
669 // Check parameter correctness
670 if (argc - optind == 0)
671 {
672 _tprintf(_T("Command missing. Type nxdbmgr -h for command line syntax.\n"));
673 return 1;
674 }
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") &&
681 strcmp(argv[optind], "init") &&
682 strcmp(argv[optind], "migrate") &&
683 strcmp(argv[optind], "reset-system-account") &&
684 strcmp(argv[optind], "set") &&
685 strcmp(argv[optind], "unlock") &&
686 strcmp(argv[optind], "upgrade"))
687 {
688 _tprintf(_T("Invalid command \"%hs\". Type nxdbmgr -h for command line syntax.\n"), argv[optind]);
689 return 1;
690 }
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)) ||
692 (!strcmp(argv[optind], "set") && (argc - optind < 3)))
693 {
694 _tprintf(_T("Required command argument(s) missing\n"));
695 return 1;
696 }
697
698 // Read configuration file
699 Config *config = new Config();
700 if (!config->loadIniConfig(configFile, _T("server")) || !config->parseTemplate(_T("server"), m_cfgTemplate))
701 {
702 _tprintf(_T("Error loading configuration file\n"));
703 return 2;
704 }
705 delete config;
706
707 // Decrypt password
708 DecryptPassword(s_dbLogin, s_dbPassword, s_dbPassword, MAX_PASSWORD);
709
710 #ifndef _WIN32
711 SetDefaultCodepage(m_szCodePage);
712 #endif
713
714 // Connect to database
715 if (!DBInit(0, 0))
716 {
717 _tprintf(_T("Unable to initialize database library\n"));
718 return 3;
719 }
720
721 s_driver = DBLoadDriver(s_dbDriver, s_dbDrvParams, false, NULL, NULL);
722 if (s_driver == NULL)
723 {
724 _tprintf(_T("Unable to load and initialize database driver \"%s\"\n"), s_dbDriver);
725 return 3;
726 }
727
728 g_hCoreDB = ConnectToDatabase();
729 if (g_hCoreDB == NULL)
730 {
731 DBUnloadDriver(s_driver);
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
742 g_dbSyntax = DBGetSyntax(g_hCoreDB);
743 if (g_dbSyntax == DB_SYNTAX_UNKNOWN)
744 {
745 _tprintf(_T("Unable to determine database syntax\n"));
746 DBDisconnect(g_hCoreDB);
747 DBUnloadDriver(s_driver);
748 return 5;
749 }
750
751 // Do requested operation
752 if (!strcmp(argv[optind], "batch"))
753 {
754 ExecSQLBatch(argv[optind + 1]);
755 }
756 else if (!strcmp(argv[optind], "check"))
757 {
758 CheckDatabase();
759 }
760 else if (!strcmp(argv[optind], "check-data-tables"))
761 {
762 g_checkDataTablesOnly = true;
763 CheckDatabase();
764 }
765 else if (!strcmp(argv[optind], "upgrade"))
766 {
767 UpgradeDatabase();
768 }
769 else if (!strcmp(argv[optind], "unlock"))
770 {
771 UnlockDatabase();
772 }
773 else if (!strcmp(argv[optind], "export"))
774 {
775 ExportDatabase(argv[optind + 1]);
776 }
777 else if (!strcmp(argv[optind], "import"))
778 {
779 ImportDatabase(argv[optind + 1]);
780 }
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
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);
791 #ifdef UNICODE
792 free(sourceConfig);
793 #endif
794 }
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
802 TCHAR buffer[MAX_CONFIG_VALUE];
803 ConfigReadStr(var, buffer, MAX_CONFIG_VALUE, _T(""));
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
818 CreateConfigParam(var, value, true, false, replaceValue);
819 #ifdef UNICODE
820 free(var);
821 free(value);
822 #endif
823 }
824 else if (!strcmp(argv[optind], "reset-system-account"))
825 {
826 ResetSystemAccount();
827 }
828 }
829
830 // Shutdown
831 DBDisconnect(g_hCoreDB);
832 DBUnloadDriver(s_driver);
833 return 0;
834 }