DatabaseUtilities.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  1. // DatabaseUtilites.cpp: implementation of the CDatabaseUtilites class.
  2. //
  3. //////////////////////////////////////////////////////////////////////
  4. #include "stdafx.h"
  5. #include "CP_Main.h"
  6. #include "DatabaseUtilities.h"
  7. #include "ProcessPaste.h"
  8. #include <io.h>
  9. #include "AccessToSqlite.h"
  10. //////////////////////////////////////////////////////////////////////
  11. // Construction/Destruction
  12. //////////////////////////////////////////////////////////////////////
  13. BOOL CreateBackup(CString csPath)
  14. {
  15. CString csOriginal;
  16. int count = 0;
  17. // create a backup of the existing database
  18. do
  19. {
  20. count++;
  21. csOriginal = csPath + StrF(_T(".%03d"), count);
  22. // in case of some weird infinite loop
  23. if( count > 50 )
  24. {
  25. ASSERT(0);
  26. return FALSE;
  27. }
  28. } while( !::CopyFile(csPath, csOriginal, TRUE));
  29. return TRUE;
  30. }
  31. CString GetDBName()
  32. {
  33. return CGetSetOptions::GetDBPath();
  34. }
  35. CString GetOLDDefaultDBName()
  36. {
  37. CString csDefaultPath;
  38. LPMALLOC pMalloc;
  39. if(SUCCEEDED(::SHGetMalloc(&pMalloc)))
  40. {
  41. LPITEMIDLIST pidlPrograms;
  42. SHGetSpecialFolderLocation(NULL, CSIDL_APPDATA, &pidlPrograms);
  43. TCHAR string[MAX_PATH];
  44. SHGetPathFromIDList(pidlPrograms, string);
  45. pMalloc->Free(pidlPrograms);
  46. pMalloc->Release();
  47. csDefaultPath = string;
  48. csDefaultPath += "\\Ditto\\";
  49. csDefaultPath += "DittoDB.mdb";
  50. }
  51. return csDefaultPath;
  52. }
  53. CString GetDefaultDBName()
  54. {
  55. CString csDefaultPath = _T("c:\\program files\\Ditto\\");
  56. if(g_Opt.m_bU3)
  57. {
  58. csDefaultPath = CGetSetOptions::GetPath(PATH_DATABASE);
  59. }
  60. else
  61. {
  62. LPMALLOC pMalloc;
  63. if(SUCCEEDED(::SHGetMalloc(&pMalloc)))
  64. {
  65. LPITEMIDLIST pidlPrograms;
  66. SHGetSpecialFolderLocation(NULL, CSIDL_APPDATA, &pidlPrograms);
  67. TCHAR string[MAX_PATH];
  68. SHGetPathFromIDList(pidlPrograms, string);
  69. pMalloc->Free(pidlPrograms);
  70. pMalloc->Release();
  71. csDefaultPath = string;
  72. }
  73. FIX_CSTRING_PATH(csDefaultPath);
  74. csDefaultPath += "Ditto\\";
  75. }
  76. if(FileExists(csDefaultPath) == FALSE)
  77. CreateDirectory(csDefaultPath, NULL);
  78. CString csTempName = csDefaultPath + "Ditto.db";
  79. int i = 1;
  80. while(FileExists(csTempName))
  81. {
  82. csTempName.Format(_T("%sDitto_%d.db"), csDefaultPath, i);
  83. i++;
  84. }
  85. csDefaultPath = csTempName;
  86. return csDefaultPath;
  87. }
  88. BOOL CheckDBExists(CString csDBPath)
  89. {
  90. //If this is the first time running this version then convert the old database to the new db
  91. if(csDBPath.IsEmpty() && g_Opt.m_bU3 == false)
  92. {
  93. csDBPath = GetDefaultDBName();
  94. if(FileExists(csDBPath) == FALSE)
  95. {
  96. CString csOldDB = CGetSetOptions::GetDBPathOld();
  97. if(csOldDB.IsEmpty())
  98. {
  99. csOldDB = GetOLDDefaultDBName();
  100. }
  101. if(FileExists(csOldDB))
  102. {
  103. //create the new sqlite db
  104. CreateDB(csDBPath);
  105. CAccessToSqlite Convert;
  106. Convert.ConvertDatabase(csDBPath, csOldDB);
  107. }
  108. }
  109. }
  110. BOOL bRet = FALSE;
  111. if(FileExists(csDBPath) == FALSE)
  112. {
  113. csDBPath = GetDefaultDBName();
  114. // -- create a new one
  115. bRet = CreateDB(csDBPath);
  116. }
  117. else
  118. {
  119. if(ValidDB(csDBPath) == FALSE)
  120. {
  121. //Db existed but was bad
  122. CString csMarkAsBad;
  123. csMarkAsBad = csDBPath;
  124. csMarkAsBad.Replace(_T("."), _T("_BAD."));
  125. CString csPath = GetDefaultDBName();
  126. CString cs;
  127. cs.Format(_T("%s \"%s\",\n")
  128. _T("%s \"%s\",\n")
  129. _T("%s,\n")
  130. _T("\"%s\""),
  131. theApp.m_Language.GetString("Database_Format", "Unrecognized Database Format"),
  132. csDBPath,
  133. theApp.m_Language.GetString("File_Renamed", "the file will be renamed"),
  134. csMarkAsBad,
  135. theApp.m_Language.GetString("New_Database", "and a new database will be created"),
  136. csPath);
  137. AfxMessageBox(cs);
  138. CFile::Rename(csDBPath, csMarkAsBad);
  139. csDBPath = csPath;
  140. bRet = CreateDB(csDBPath);
  141. }
  142. else
  143. bRet = TRUE;
  144. }
  145. if(bRet)
  146. {
  147. bRet = OpenDatabase(csDBPath);
  148. }
  149. return bRet;
  150. }
  151. BOOL OpenDatabase(CString csDB)
  152. {
  153. try
  154. {
  155. theApp.m_db.close();
  156. theApp.m_db.open(csDB);
  157. CGetSetOptions::SetDBPath(csDB);
  158. return TRUE;
  159. }
  160. CATCH_SQLITE_EXCEPTION
  161. return FALSE;
  162. }
  163. BOOL ValidDB(CString csPath, BOOL bUpgrade)
  164. {
  165. try
  166. {
  167. CppSQLite3DB db;
  168. db.open(csPath);
  169. db.execQuery(_T("SELECT lID, lDate, mText, lShortCut, lDontAutoDelete, ")
  170. _T("CRC, bIsGroup, lParentID, QuickPasteText ")
  171. _T("FROM Main"));
  172. db.execQuery(_T("SELECT lID, lParentID, strClipBoardFormat, ooData FROM Data"));
  173. db.execQuery(_T("SELECT lID, TypeText FROM Types"));
  174. //This was added later so try to add each time and catch the exception here
  175. try
  176. {
  177. db.execDML(_T("CREATE TRIGGER delete_data_trigger BEFORE DELETE ON Main FOR EACH ROW\n")
  178. _T("BEGIN\n")
  179. _T("DELETE FROM Data WHERE lParentID = old.lID;\n")
  180. _T("END\n"));
  181. }
  182. catch(CppSQLite3Exception& e)
  183. {
  184. e.errorCode();
  185. }
  186. //This was added later so try to add each time and catch the exception here
  187. try
  188. {
  189. db.execQuery(_T("SELECT lID, lClipID, lCopyBuffer FROM CopyBuffers"));
  190. }
  191. catch(CppSQLite3Exception& e)
  192. {
  193. e.errorCode();
  194. db.execDML(_T("CREATE TABLE CopyBuffers(")
  195. _T("lID INTEGER PRIMARY KEY AUTOINCREMENT, ")
  196. _T("lClipID INTEGER,")
  197. _T("lCopyBuffer INTEGER)"));
  198. db.execDML(_T("CREATE TRIGGER delete_copy_buffer_trigger BEFORE DELETE ON Main FOR EACH ROW\n")
  199. _T("BEGIN\n")
  200. _T("DELETE FROM CopyBuffers WHERE lClipID = old.lID;\n")
  201. _T("END\n"));
  202. }
  203. }
  204. CATCH_SQLITE_EXCEPTION_AND_RETURN(FALSE)
  205. return TRUE;
  206. }
  207. BOOL CreateDB(CString csPath)
  208. {
  209. try
  210. {
  211. CppSQLite3DB db;
  212. db.open(csPath);
  213. db.execDML(_T("CREATE TABLE Main(")
  214. _T("lID INTEGER PRIMARY KEY AUTOINCREMENT, ")
  215. _T("lDate INTEGER, ")
  216. _T("mText TEXT, ")
  217. _T("lShortCut INTEGER, ")
  218. _T("lDontAutoDelete INTEGER, ")
  219. _T("CRC INTEGER, ")
  220. _T("bIsGroup INTEGER, ")
  221. _T("lParentID INTEGER, ")
  222. _T("QuickPasteText TEXT)"));
  223. db.execDML(_T("CREATE TABLE Data(")
  224. _T("lID INTEGER PRIMARY KEY AUTOINCREMENT, ")
  225. _T("lParentID INTEGER, ")
  226. _T("strClipBoardFormat TEXT, ")
  227. _T("ooData BLOB);"));
  228. db.execDML(_T("CREATE TABLE Types(")
  229. _T("lID INTEGER PRIMARY KEY AUTOINCREMENT, ")
  230. _T("TypeText TEXT)"));
  231. db.execDML(_T("CREATE UNIQUE INDEX Main_ID on Main(lID ASC)"));
  232. db.execDML(_T("CREATE UNIQUE INDEX Data_ID on Data(lID ASC)"));
  233. db.execDML(_T("CREATE INDEX Main_Date on Main(lDate DESC)"));
  234. db.execDML(_T("CREATE TRIGGER delete_data_trigger BEFORE DELETE ON Main FOR EACH ROW\n")
  235. _T("BEGIN\n")
  236. _T("DELETE FROM Data WHERE lParentID = old.lID;\n")
  237. _T("END\n"));
  238. db.execDML(_T("CREATE TABLE CopyBuffers(")
  239. _T("lID INTEGER PRIMARY KEY AUTOINCREMENT, ")
  240. _T("lClipID INTEGER, ")
  241. _T("lCopyBuffer INTEGER)"));
  242. db.execDML(_T("CREATE TRIGGER delete_copy_buffer_trigger BEFORE DELETE ON Main FOR EACH ROW\n")
  243. _T("BEGIN\n")
  244. _T("DELETE FROM CopyBuffers WHERE lClipID = old.lID;\n")
  245. _T("END\n"));
  246. db.close();
  247. }
  248. CATCH_SQLITE_EXCEPTION_AND_RETURN(FALSE)
  249. return TRUE;
  250. }
  251. BOOL CompactDatabase()
  252. {
  253. // if(!theApp.CloseDB())
  254. // return FALSE;
  255. //
  256. // CString csDBName = GetDBName();
  257. // CString csTempDBName = csDBName;
  258. // csTempDBName.Replace(".mdb", "TempDBName.mdb");
  259. //
  260. // //Compact the database
  261. // try
  262. // {
  263. // CDaoWorkspace::CompactDatabase(csDBName, csTempDBName);//, dbLangGeneral, 0, "andrew");//DATABASE_PASSWORD);
  264. // }
  265. // catch(CDaoException* e)
  266. // {
  267. // AfxMessageBox(e->m_pErrorInfo->m_strDescription);
  268. // DeleteFile(csTempDBName);
  269. // e->Delete();
  270. // return FALSE;
  271. // }
  272. // catch(CMemoryException* e)
  273. // {
  274. // AfxMessageBox("Memory Exception");
  275. // DeleteFile(csTempDBName);
  276. // e->Delete();
  277. // return FALSE;
  278. // }
  279. //
  280. // //Since compacting the database creates a new db delete the old one and replace it
  281. // //with the compacted db
  282. // if(DeleteFile(csDBName))
  283. // {
  284. // try
  285. // {
  286. // CFile::Rename(csTempDBName, csDBName);
  287. // }
  288. // catch(CFileException *e)
  289. // {
  290. // e->ReportError();
  291. // e->Delete();
  292. // return FALSE;
  293. // }
  294. // }
  295. // else
  296. // AfxMessageBox("Error Compacting Database");
  297. return TRUE;
  298. }
  299. BOOL RepairDatabase()
  300. {
  301. // if(!theApp.CloseDB())
  302. // return FALSE;
  303. // try
  304. // {
  305. // CDaoWorkspace::RepairDatabase(GetDBName());
  306. // }
  307. // catch(CDaoException *e)
  308. // {
  309. // AfxMessageBox(e->m_pErrorInfo->m_strDescription);
  310. // e->Delete();
  311. // return FALSE;
  312. // }
  313. return TRUE;
  314. }
  315. BOOL RemoveOldEntries()
  316. {
  317. try
  318. {
  319. if(CGetSetOptions::GetCheckForMaxEntries())
  320. {
  321. long lMax = CGetSetOptions::GetMaxEntries();
  322. if(lMax >= 0)
  323. {
  324. CClipIDs IDs;
  325. CppSQLite3Query q = theApp.m_db.execQueryEx(_T("SELECT lID, lShortCut, lDontAutoDelete FROM Main ORDER BY lDate DESC LIMIT -1 OFFSET %d"), lMax);
  326. while(q.eof() == false)
  327. {
  328. //Only delete entries that have no shortcut and don't have the flag set
  329. if(q.getIntField(_T("lShortCut")) == 0 && q.getIntField(_T("lDontAutoDelete")) == 0)
  330. IDs.Add(q.getIntField(_T("lID")));
  331. q.nextRow();
  332. }
  333. IDs.DeleteIDs();
  334. }
  335. }
  336. if(CGetSetOptions::GetCheckForExpiredEntries())
  337. {
  338. long lExpire = CGetSetOptions::GetExpiredEntries();
  339. if(lExpire)
  340. {
  341. CTime now = CTime::GetCurrentTime();
  342. now -= CTimeSpan(lExpire, 0, 0, 0);
  343. CClipIDs IDs;
  344. CppSQLite3Query q = theApp.m_db.execQueryEx(_T("SELECT lID FROM Main ")
  345. _T("WHERE lDate < %d AND ")
  346. _T("lShortCut = 0 AND lDontAutoDelete = 0"), now.GetTime());
  347. while(q.eof() == false)
  348. {
  349. IDs.Add(q.getIntField(_T("lID")));
  350. q.nextRow();
  351. }
  352. IDs.DeleteIDs();
  353. }
  354. }
  355. }
  356. CATCH_SQLITE_EXCEPTION
  357. return TRUE;
  358. }
  359. BOOL EnsureDirectory(CString csPath)
  360. {
  361. TCHAR drive[_MAX_DRIVE];
  362. TCHAR dir[_MAX_DIR];
  363. TCHAR fname[_MAX_FNAME];
  364. TCHAR ext[_MAX_EXT];
  365. SPLITPATH(csPath, drive, dir, fname, ext);
  366. CString csDir(drive);
  367. csDir += dir;
  368. if(FileExists(csDir) == FALSE)
  369. {
  370. if(CreateDirectory(csDir, NULL))
  371. return TRUE;
  372. }
  373. else
  374. return TRUE;
  375. return FALSE;
  376. }
  377. // BOOL RunZippApp(CString csCommandLine)
  378. // {
  379. // CString csLocalPath = GETENV(_T("U3_HOST_EXEC_PATH"));
  380. // FIX_CSTRING_PATH(csLocalPath);
  381. //
  382. // CString csZippApp = GETENV(_T("U3_DEVICE_EXEC_PATH"));
  383. // FIX_CSTRING_PATH(csZippApp);
  384. // csZippApp += "7za.exe";
  385. //
  386. // csZippApp += " ";
  387. // csZippApp += csCommandLine;
  388. //
  389. // Log(csZippApp);
  390. //
  391. // STARTUPINFO StartupInfo;
  392. // PROCESS_INFORMATION ProcessInformation;
  393. //
  394. // ZeroMemory(&StartupInfo, sizeof(StartupInfo));
  395. // StartupInfo.cb = sizeof(StartupInfo);
  396. // ZeroMemory(&ProcessInformation, sizeof(ProcessInformation));
  397. //
  398. // StartupInfo.dwFlags = STARTF_USESHOWWINDOW;
  399. // StartupInfo.wShowWindow = SW_HIDE;
  400. //
  401. // BOOL bRet = CreateProcess(NULL, csZippApp.GetBuffer(csZippApp.GetLength()), NULL, NULL, FALSE,
  402. // CREATE_DEFAULT_ERROR_MODE | NORMAL_PRIORITY_CLASS, NULL, csLocalPath,
  403. // &StartupInfo, &ProcessInformation);
  404. //
  405. // if(bRet)
  406. // {
  407. // WaitForSingleObject(ProcessInformation.hProcess, INFINITE);
  408. //
  409. // DWORD dwExitCode;
  410. // GetExitCodeProcess(ProcessInformation.hProcess, &dwExitCode);
  411. //
  412. // CString cs;
  413. // cs.Format(_T("Exit code from unzip = %d"), dwExitCode);
  414. // Log(cs);
  415. //
  416. // if(dwExitCode != 0)
  417. // {
  418. // bRet = FALSE;
  419. // }
  420. // }
  421. // else
  422. // {
  423. // bRet = FALSE;
  424. // Log(_T("Create Process Failed"));
  425. // }
  426. //
  427. // csZippApp.ReleaseBuffer();
  428. //
  429. // return bRet;
  430. // }
  431. // BOOL CopyDownDatabase()
  432. // {
  433. // BOOL bRet = FALSE;
  434. //
  435. // CString csZippedPath = GETENV(_T("U3_APP_DATA_PATH"));
  436. // FIX_CSTRING_PATH(csZippedPath);
  437. //
  438. // CString csUnZippedPath = csZippedPath;
  439. // csUnZippedPath += "Ditto.db";
  440. //
  441. // csZippedPath += "Ditto.7z";
  442. //
  443. // CString csLocalPath = GETENV(_T("U3_HOST_EXEC_PATH"));
  444. // FIX_CSTRING_PATH(csLocalPath);
  445. //
  446. // if(FileExists(csZippedPath))
  447. // {
  448. // CString csCommandLine;
  449. //
  450. // //e = extract
  451. // //surround command line arguments with quotes
  452. // //-aoa = overight files with extracted files
  453. //
  454. // csCommandLine += "e ";
  455. // csCommandLine += "\"";
  456. // csCommandLine += csZippedPath;
  457. // csCommandLine += "\"";
  458. // csCommandLine += " -o";
  459. // csCommandLine += "\"";
  460. // csCommandLine += csLocalPath;
  461. // csCommandLine += "\"";
  462. // csCommandLine += " -aoa";
  463. //
  464. // bRet = RunZippApp(csCommandLine);
  465. //
  466. // csLocalPath += "Ditto.db";
  467. // }
  468. // else if(FileExists(csUnZippedPath))
  469. // {
  470. // csLocalPath += "Ditto.db";
  471. // bRet = CopyFile(csUnZippedPath, csLocalPath, FALSE);
  472. // }
  473. //
  474. // if(FileExists(csLocalPath) == FALSE)
  475. // {
  476. // Log(_T("Failed to copy files from device zip file"));
  477. // }
  478. //
  479. // g_Opt.nLastDbWriteTime = GetLastWriteTime(csLocalPath);
  480. //
  481. // return bRet;
  482. // }
  483. //BOOL CopyUpDatabase()
  484. //{
  485. // CStringA csZippedPath = "C:\\";//getenv("U3_APP_DATA_PATH");
  486. // FIX_CSTRING_PATH(csZippedPath);
  487. // csZippedPath += "Ditto.zip";
  488. // CStringA csLocalPath = GetDBName();//getenv("U3_HOST_EXEC_PATH");
  489. // //FIX_CSTRING_PATH(csLocalPath);
  490. // //csLocalPath += "Ditto.db";
  491. //
  492. // CZipper Zip;
  493. //
  494. // if(Zip.OpenZip(csZippedPath))
  495. // {
  496. // Zip.AddFileToZip(csLocalPath);
  497. // }
  498. //
  499. // return TRUE;
  500. //}