DatabaseUtilities.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989
  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 "Path.h"
  10. #include "InternetUpdate.h"
  11. //////////////////////////////////////////////////////////////////////
  12. // Construction/Destruction
  13. //////////////////////////////////////////////////////////////////////
  14. BOOL CreateBackup(CString csPath)
  15. {
  16. CString csOriginal;
  17. int count = 0;
  18. // create a backup of the existing database
  19. do
  20. {
  21. count++;
  22. csOriginal = csPath + StrF(_T(".%03d"), count);
  23. // in case of some weird infinite loop
  24. if( count > 50 )
  25. {
  26. ASSERT(0);
  27. return FALSE;
  28. }
  29. } while( !::CopyFile(csPath, csOriginal, TRUE));
  30. return TRUE;
  31. }
  32. CString GetDBName()
  33. {
  34. return CGetSetOptions::GetDBPath();
  35. }
  36. CString GetOLDDefaultDBName()
  37. {
  38. CString csDefaultPath;
  39. LPMALLOC pMalloc;
  40. if(SUCCEEDED(::SHGetMalloc(&pMalloc)))
  41. {
  42. LPITEMIDLIST pidlPrograms;
  43. SHGetSpecialFolderLocation(NULL, CSIDL_APPDATA, &pidlPrograms);
  44. TCHAR string[MAX_PATH];
  45. SHGetPathFromIDList(pidlPrograms, string);
  46. pMalloc->Free(pidlPrograms);
  47. pMalloc->Release();
  48. csDefaultPath = string;
  49. csDefaultPath += "\\Ditto\\";
  50. csDefaultPath += "DittoDB.mdb";
  51. }
  52. return csDefaultPath;
  53. }
  54. CString GetDefaultDBName()
  55. {
  56. CString csDefaultPath = _T("c:\\program files\\Ditto\\");
  57. //If portable then default to the running path
  58. if(CGetSetOptions::GetIsPortableDitto())
  59. {
  60. csDefaultPath.Empty();
  61. }
  62. else
  63. {
  64. csDefaultPath = CGetSetOptions::GetAppDataPath();
  65. }
  66. CString csTempName = csDefaultPath + "Ditto.db";
  67. int i = 1;
  68. while(FileExists(csTempName))
  69. {
  70. csTempName.Format(_T("%sDitto_%d.db"), csDefaultPath, i);
  71. i++;
  72. }
  73. csDefaultPath = csTempName;
  74. return csDefaultPath;
  75. }
  76. BOOL CheckDBExists(CString csDBPath)
  77. {
  78. //If this is the first time running this version then convert the old database to the new db
  79. if(csDBPath.IsEmpty())
  80. {
  81. csDBPath = GetDefaultDBName();
  82. CGetSetOptions::SetDBPath(csDBPath);
  83. }
  84. BOOL bRet = FALSE;
  85. if(FileExists(csDBPath) == FALSE)
  86. {
  87. csDBPath = GetDefaultDBName();
  88. nsPath::CPath FullPath(csDBPath);
  89. CString csPath = FullPath.GetPath().GetStr();
  90. if(csPath.IsEmpty() == false && FileExists(csDBPath) == FALSE)
  91. {
  92. CreateDirectory(csPath, NULL);
  93. }
  94. // -- create a new one
  95. bRet = CreateDB(csDBPath);
  96. }
  97. else
  98. {
  99. if(ValidDB(csDBPath) == FALSE)
  100. {
  101. //Db existed but was bad
  102. CString csMarkAsBad;
  103. csMarkAsBad = csDBPath;
  104. csMarkAsBad.Replace(_T("."), _T("_BAD."));
  105. CString csPath = GetDefaultDBName();
  106. CString cs;
  107. cs.Format(_T("%s \"%s\",\n")
  108. _T("%s \"%s\",\n")
  109. _T("%s,\n")
  110. _T("\"%s\""),
  111. theApp.m_Language.GetString("Database_Format", "Unrecognized Database Format"),
  112. csDBPath,
  113. theApp.m_Language.GetString("File_Renamed", "the file will be renamed"),
  114. csMarkAsBad,
  115. theApp.m_Language.GetString("New_Database", "and a new database will be created"),
  116. csPath);
  117. AfxMessageBox(cs);
  118. CFile::Rename(csDBPath, csMarkAsBad);
  119. csDBPath = csPath;
  120. bRet = CreateDB(csDBPath);
  121. CGetSetOptions::SetDBPath(csDBPath);
  122. }
  123. else
  124. {
  125. bRet = TRUE;
  126. }
  127. }
  128. if(bRet)
  129. {
  130. bRet = OpenDatabase(csDBPath);
  131. }
  132. return bRet;
  133. }
  134. BOOL OpenDatabase(CString csDB)
  135. {
  136. try
  137. {
  138. theApp.m_db.close();
  139. theApp.m_db.open(csDB);
  140. theApp.m_db.setBusyTimeout(CGetSetOptions::GetDbTimeout());
  141. return TRUE;
  142. }
  143. CATCH_SQLITE_EXCEPTION
  144. return FALSE;
  145. }
  146. void ReOrderStickyClips(int parentID, CppSQLite3DB &db)
  147. {
  148. try
  149. {
  150. Log(StrF(_T("Start of ReOrderStickyClips, ParentId %d"), parentID));
  151. //groups where created with 0 in these fields, fix them up if they are 0
  152. if(parentID == -1)
  153. {
  154. db.execDMLEx(_T("Update Main Set stickyClipOrder = -(2147483647) where bIsGroup = 1 AND stickyClipOrder = 0"));
  155. db.execDMLEx(_T("Update Main Set stickyClipGroupOrder = -(2147483647) where bIsGroup = 1 AND stickyClipGroupOrder = 0"));
  156. }
  157. CppSQLite3Query qGroup = db.execQueryEx(_T("SELECT lID, mText FROM Main WHERE bIsGroup = 1 AND lParentID = %d"), parentID);
  158. if (qGroup.eof() == false)
  159. {
  160. while (!qGroup.eof())
  161. {
  162. //Get all sticky clips at the top level or group
  163. CString sql = StrF(_T("SELECT lID FROM Main WHERE stickyClipOrder <> -(2147483647) AND lParentID = %d ORDER BY stickyClipOrder DESC"), parentID);
  164. if (parentID > -1)
  165. {
  166. sql = StrF(_T("SELECT lID FROM Main WHERE stickyClipGroupOrder <> -(2147483647) AND lParentID = %d ORDER BY stickyClipGroupOrder DESC"), parentID);
  167. }
  168. CppSQLite3Query qSticky = db.execQueryEx(sql);
  169. int order = 1;
  170. if (qSticky.eof() == false)
  171. {
  172. while (!qSticky.eof())
  173. {
  174. //set the new order
  175. if (parentID > -1)
  176. {
  177. db.execDMLEx(_T("Update Main Set stickyClipGroupOrder = %d where lID = %d"), order, qSticky.getIntField(_T("lID")));
  178. }
  179. else
  180. {
  181. db.execDMLEx(_T("Update Main Set stickyClipOrder = %d where lID = %d"), order, qSticky.getIntField(_T("lID")));
  182. }
  183. qSticky.nextRow();
  184. order--;
  185. }
  186. }
  187. ReOrderStickyClips(qGroup.getIntField(_T("lID")), db);
  188. qGroup.nextRow();
  189. }
  190. }
  191. Log(StrF(_T("End of ReOrderStickyClips, ParentId %d"), parentID));
  192. }
  193. CATCH_SQLITE_EXCEPTION
  194. }
  195. BOOL ValidDB(CString csPath, BOOL bUpgrade)
  196. {
  197. CDittoPopupWindow *popUpMsg = NULL;
  198. try
  199. {
  200. BOOL didBackup = FALSE;
  201. CString backupFilePrefix = _T("Before_Update_To");
  202. CppSQLite3DB db;
  203. db.open(csPath);
  204. db.execQuery(_T("SELECT lID, lDate, mText, lShortCut, lDontAutoDelete, ")
  205. _T("CRC, bIsGroup, lParentID, QuickPasteText ")
  206. _T("FROM Main"));
  207. db.execQuery(_T("SELECT lID, lParentID, strClipBoardFormat, ooData FROM Data"));
  208. db.execQuery(_T("SELECT lID, TypeText FROM Types"));
  209. try
  210. {
  211. db.execDML(_T("DROP TRIGGER delete_data_trigger"));
  212. }
  213. catch(CppSQLite3Exception& e)
  214. {
  215. e.errorCode();
  216. }
  217. try
  218. {
  219. db.execDML(_T("DROP TRIGGER delete_copy_buffer_trigger"));
  220. }
  221. catch(CppSQLite3Exception& e)
  222. {
  223. e.errorCode();
  224. }
  225. //This was added later so try to add each time and catch the exception here
  226. try
  227. {
  228. db.execDML(_T("CREATE TRIGGER delete_data_trigger BEFORE DELETE ON Main FOR EACH ROW\n")
  229. _T("BEGIN\n")
  230. _T("INSERT INTO MainDeletes VALUES(old.lID, datetime('now'));\n")
  231. _T("END\n"));
  232. }
  233. catch(CppSQLite3Exception& e)
  234. {
  235. if(didBackup == FALSE)
  236. didBackup = BackupDB(csPath, backupFilePrefix, &popUpMsg);
  237. e.errorCode();
  238. }
  239. //This was added later so try to add each time and catch the exception here
  240. try
  241. {
  242. db.execQuery(_T("SELECT lID, lClipID, lCopyBuffer FROM CopyBuffers"));
  243. }
  244. catch(CppSQLite3Exception& e)
  245. {
  246. if(didBackup == FALSE)
  247. didBackup = BackupDB(csPath, backupFilePrefix, &popUpMsg);
  248. e.errorCode();
  249. db.execDML(_T("CREATE TABLE CopyBuffers(")
  250. _T("lID INTEGER PRIMARY KEY AUTOINCREMENT, ")
  251. _T("lClipID INTEGER,")
  252. _T("lCopyBuffer INTEGER)"));
  253. }
  254. //This was added later so try to add each time and catch the exception here
  255. try
  256. {
  257. db.execQuery(_T("SELECT clipId FROM MainDeletes"));
  258. }
  259. catch(CppSQLite3Exception& e)
  260. {
  261. if(didBackup == FALSE)
  262. didBackup = BackupDB(csPath, backupFilePrefix, &popUpMsg);
  263. e.errorCode();
  264. db.execDML(_T("CREATE TABLE MainDeletes(")
  265. _T("clipID INTEGER,")
  266. _T("modifiedDate)"));
  267. db.execDML(_T("CREATE TRIGGER MainDeletes_delete_data_trigger BEFORE DELETE ON MainDeletes FOR EACH ROW\n")
  268. _T("BEGIN\n")
  269. _T("DELETE FROM CopyBuffers WHERE lClipID = old.clipID;\n")
  270. _T("DELETE FROM Data WHERE lParentID = old.clipID;\n")
  271. _T("END\n"));
  272. }
  273. try
  274. {
  275. db.execDML(_T("CREATE INDEX Main_ParentId on Main(lParentID DESC)"));
  276. db.execDML(_T("CREATE INDEX Main_IsGroup on Main(bIsGroup DESC)"));
  277. db.execDML(_T("CREATE INDEX Main_ShortCut on Main(lShortCut DESC)"));
  278. }
  279. catch(CppSQLite3Exception& e)
  280. {
  281. e.errorCode();
  282. }
  283. try
  284. {
  285. db.execQuery(_T("SELECT clipOrder, clipGroupOrder FROM Main"));
  286. }
  287. catch(CppSQLite3Exception& e)
  288. {
  289. if(didBackup == FALSE)
  290. didBackup = BackupDB(csPath, backupFilePrefix, &popUpMsg);
  291. db.execDML(_T("ALTER TABLE Main ADD clipOrder REAL"));
  292. db.execDML(_T("ALTER TABLE Main ADD clipGroupOrder REAL"));
  293. db.execDML(_T("Update Main set clipOrder = lDate, clipGroupOrder = lDate"));
  294. db.execDML(_T("CREATE INDEX Main_ClipOrder on Main(clipOrder DESC)"));
  295. db.execDML(_T("CREATE INDEX Main_ClipGroupOrder on Main(clipGroupOrder DESC)"));
  296. db.execDML(_T("DROP INDEX Main_Date"));
  297. e.errorCode();
  298. }
  299. try
  300. {
  301. db.execQuery(_T("SELECT globalShortCut FROM Main"));
  302. }
  303. catch(CppSQLite3Exception& e)
  304. {
  305. if(didBackup == FALSE)
  306. didBackup = BackupDB(csPath, backupFilePrefix, &popUpMsg);
  307. db.execDML(_T("ALTER TABLE Main ADD globalShortCut INTEGER"));
  308. e.errorCode();
  309. }
  310. try
  311. {
  312. db.execQuery(_T("SELECT lastPasteDate FROM Main"));
  313. }
  314. catch(CppSQLite3Exception& e)
  315. {
  316. if(didBackup == FALSE)
  317. didBackup = BackupDB(csPath, backupFilePrefix, &popUpMsg);
  318. db.execDML(_T("ALTER TABLE Main ADD lastPasteDate INTEGER"));
  319. db.execDML(_T("Update Main set lastPasteDate = lDate"));
  320. db.execDMLEx(_T("Update Main set lastPasteDate = %d where lastPasteDate <= 0"), (int)CTime::GetCurrentTime().GetTime());
  321. e.errorCode();
  322. }
  323. try
  324. {
  325. db.execQuery(_T("SELECT stickyClipOrder FROM Main"));
  326. }
  327. catch (CppSQLite3Exception& e)
  328. {
  329. if (didBackup == FALSE)
  330. didBackup = BackupDB(csPath, backupFilePrefix, &popUpMsg);
  331. db.execDML(_T("ALTER TABLE Main ADD stickyClipOrder REAL"));
  332. db.execDML(_T("ALTER TABLE Main ADD stickyClipGroupOrder REAL"));
  333. e.errorCode();
  334. }
  335. try
  336. {
  337. CppSQLite3Query q = db.execQuery(_T("PRAGMA index_info(Main_NoGroup);"));
  338. int count = 0;
  339. while (q.eof() == false)
  340. {
  341. count++;
  342. q.nextRow();
  343. }
  344. if(count == 0)
  345. {
  346. if (didBackup == FALSE)
  347. didBackup = BackupDB(csPath, backupFilePrefix, &popUpMsg);
  348. db.execDML(_T("Update Main set stickyClipOrder = -(2147483647) where stickyClipOrder IS NULL;"));
  349. db.execDML(_T("Update Main set stickyClipGroupOrder = -(2147483647) where stickyClipGroupOrder IS NULL;"));
  350. db.execDML(_T("Update Main set stickyClipOrder = -(2147483647) where stickyClipOrder = 0;"));
  351. db.execDML(_T("Update Main set stickyClipGroupOrder = -(2147483647) where stickyClipGroupOrder = 0;"));
  352. db.execDML(_T("CREATE INDEX Main_NoGroup ON Main(bIsGroup ASC, stickyClipOrder DESC, clipOrder DESC);"));
  353. db.execDML(_T("CREATE INDEX Main_InGroup ON Main(lParentId ASC, bIsGroup ASC, stickyClipGroupOrder DESC, clipGroupOrder DESC);"));
  354. db.execDML(_T("CREATE INDEX Data_ParentId_Format ON Data(lParentID COLLATE BINARY ASC, strClipBoardFormat COLLATE NOCASE ASC);"));
  355. }
  356. }
  357. catch (CppSQLite3Exception& e)
  358. {
  359. if (didBackup == FALSE)
  360. didBackup = BackupDB(csPath, backupFilePrefix, &popUpMsg);
  361. e.errorCode();
  362. }
  363. try
  364. {
  365. db.execQuery(_T("SELECT MoveToGroupShortCut FROM Main"));
  366. db.execQuery(_T("SELECT GlobalMoveToGroupShortCut FROM Main"));
  367. }
  368. catch(CppSQLite3Exception& e)
  369. {
  370. if(didBackup == FALSE)
  371. didBackup = BackupDB(csPath, backupFilePrefix, &popUpMsg);
  372. db.execDML(_T("ALTER TABLE Main ADD MoveToGroupShortCut INTEGER"));
  373. db.execDML(_T("ALTER TABLE Main ADD GlobalMoveToGroupShortCut INTEGER"));
  374. e.errorCode();
  375. }
  376. }
  377. CATCH_SQLITE_EXCEPTION_AND_RETURN(FALSE)
  378. if(popUpMsg != NULL &&
  379. IsWindow(popUpMsg->m_hWnd))
  380. {
  381. popUpMsg->CloseWindow();
  382. popUpMsg->DestroyWindow();
  383. delete popUpMsg;
  384. popUpMsg = NULL;
  385. }
  386. return TRUE;
  387. }
  388. BOOL BackupDB(CString dbPath, CString prefix, CDittoPopupWindow **popUpMsg)
  389. {
  390. if ((*popUpMsg) == NULL)
  391. {
  392. CRect r;
  393. GetMonitorRect(0, r);
  394. *popUpMsg = new CDittoPopupWindow();
  395. (*popUpMsg)->Create(CRect(r.right - 400, r.bottom - 130, r.right - 10, r.bottom - 10), NULL);
  396. ::SetWindowPos((*popUpMsg)->m_hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_SHOWWINDOW);
  397. (*popUpMsg)->ShowWindow(SW_SHOW);
  398. (*popUpMsg)->UpdateText(_T("Backing up Ditto's Database"));
  399. }
  400. CString backup = GetFilePath(dbPath);
  401. CInternetUpdate update;
  402. long runningVersion = update.GetRunningVersion();
  403. CString versionString = update.GetVersionString(runningVersion);
  404. backup += GetFileName(dbPath) += _T("_") + prefix + _T("_") + versionString;
  405. backup.Replace(_T(".db"), _T(""));
  406. backup.Replace(_T("."), _T("_"));
  407. CString temp = backup;
  408. temp += _T(".db");
  409. int i = 1;
  410. while(FileExists(temp))
  411. {
  412. temp.Format(_T("%s_%d.db"), backup, i);
  413. i++;
  414. }
  415. backup = temp;
  416. BOOL ret = FALSE;
  417. try
  418. {
  419. CFile file;
  420. CFileException ex;
  421. if(file.Open(dbPath, CFile::modeRead|CFile::typeBinary|CFile::shareDenyNone, &ex))
  422. {
  423. ULONGLONG fileSize = file.GetLength();
  424. ULONGLONG totalReadSize = 0;
  425. int percentageComplete = 0;
  426. UINT readBytes = 0;
  427. char *pBuffer = new char[65536];
  428. if(pBuffer != NULL)
  429. {
  430. CFile writeFile;
  431. if(writeFile.Open(backup, CFile::modeCreate|CFile::modeWrite|CFile::typeBinary|CFile::shareDenyNone, &ex))
  432. {
  433. do
  434. {
  435. readBytes = file.Read(pBuffer, 65536);
  436. writeFile.Write(pBuffer, readBytes);
  437. totalReadSize+= readBytes;
  438. int percent = (int)((totalReadSize * 100) / fileSize);
  439. if(percent != percentageComplete)
  440. {
  441. percentageComplete = percent;
  442. (*popUpMsg)->SetProgressBarPercent(percentageComplete);
  443. }
  444. }while(readBytes >= 65536);
  445. writeFile.Close();
  446. ret = TRUE;
  447. }
  448. }
  449. file.Close();
  450. }
  451. }
  452. catch(...)
  453. {
  454. }
  455. //BOOL ret = CopyFile(dbPath, backup, TRUE);
  456. if ((*popUpMsg) != NULL)
  457. {
  458. (*popUpMsg)->HideProgressBar();
  459. (*popUpMsg)->UpdateText(_T("Running Ditto database scripts ..."));
  460. }
  461. return ret;
  462. }
  463. BOOL CreateDB(CString csFile)
  464. {
  465. try
  466. {
  467. CppSQLite3DB db;
  468. db.open(csFile);
  469. db.execDML(_T("PRAGMA auto_vacuum = 1"));
  470. db.execDML(_T("CREATE TABLE Main(")
  471. _T("lID INTEGER PRIMARY KEY AUTOINCREMENT, ")
  472. _T("lDate INTEGER, ")
  473. _T("mText TEXT, ")
  474. _T("lShortCut INTEGER, ")
  475. _T("lDontAutoDelete INTEGER, ")
  476. _T("CRC INTEGER, ")
  477. _T("bIsGroup INTEGER, ")
  478. _T("lParentID INTEGER, ")
  479. _T("QuickPasteText TEXT, ")
  480. _T("clipOrder REAL, ")
  481. _T("clipGroupOrder REAL, ")
  482. _T("globalShortCut INTEGER, ")
  483. _T("lastPasteDate INTEGER, ")
  484. _T("stickyClipOrder REAL, ")
  485. _T("stickyClipGroupOrder REAL, ")
  486. _T("MoveToGroupShortCut INTEGER, ")
  487. _T("GlobalMoveToGroupShortCut INTEGER);"));
  488. db.execDML(_T("CREATE TABLE Data(")
  489. _T("lID INTEGER PRIMARY KEY AUTOINCREMENT, ")
  490. _T("lParentID INTEGER, ")
  491. _T("strClipBoardFormat TEXT, ")
  492. _T("ooData BLOB);"));
  493. db.execDML(_T("CREATE TABLE Types(")
  494. _T("lID INTEGER PRIMARY KEY AUTOINCREMENT, ")
  495. _T("TypeText TEXT);"));
  496. db.execDML(_T("CREATE UNIQUE INDEX Main_ID on Main(lID ASC)"));
  497. db.execDML(_T("CREATE UNIQUE INDEX Data_ID on Data(lID ASC)"));
  498. db.execDML(_T("CREATE INDEX Main_ClipOrder on Main(clipOrder DESC)"));
  499. db.execDML(_T("CREATE INDEX Main_ClipGroupOrder on Main(clipGroupOrder DESC)"));
  500. db.execDML(_T("CREATE INDEX Main_ParentId on Main(lParentID DESC)"));
  501. db.execDML(_T("CREATE INDEX Main_IsGroup on Main(bIsGroup DESC)"));
  502. db.execDML(_T("CREATE INDEX Main_ShortCut on Main(lShortCut DESC)"));
  503. db.execDML(_T("CREATE TRIGGER delete_data_trigger BEFORE DELETE ON Main FOR EACH ROW\n")
  504. _T("BEGIN\n")
  505. _T("INSERT INTO MainDeletes VALUES(old.lID, datetime('now'));\n")
  506. _T("END\n"));
  507. db.execDML(_T("CREATE TABLE CopyBuffers(")
  508. _T("lID INTEGER PRIMARY KEY AUTOINCREMENT, ")
  509. _T("lClipID INTEGER, ")
  510. _T("lCopyBuffer INTEGER)"));
  511. db.execDML(_T("CREATE TABLE MainDeletes(")
  512. _T("clipID INTEGER,")
  513. _T("modifiedDate)"));
  514. db.execDML(_T("CREATE TRIGGER MainDeletes_delete_data_trigger BEFORE DELETE ON MainDeletes FOR EACH ROW\n")
  515. _T("BEGIN\n")
  516. _T("DELETE FROM CopyBuffers WHERE lClipID = old.clipID;\n")
  517. _T("DELETE FROM Data WHERE lParentID = old.clipID;\n")
  518. _T("END\n"));
  519. db.execDML(_T("CREATE INDEX Main_NoGroup ON Main(bIsGroup ASC, stickyClipOrder DESC, clipOrder DESC);"));
  520. db.execDML(_T("CREATE INDEX Main_InGroup ON Main(lParentId ASC, bIsGroup ASC, stickyClipGroupOrder DESC, clipGroupOrder DESC);"));
  521. db.execDML(_T("CREATE INDEX Data_ParentId_Format ON Data(lParentID COLLATE BINARY ASC, strClipBoardFormat COLLATE NOCASE ASC);"));
  522. db.close();
  523. }
  524. CATCH_SQLITE_EXCEPTION_AND_RETURN(FALSE)
  525. return TRUE;
  526. }
  527. BOOL CompactDatabase()
  528. {
  529. // if(!theApp.CloseDB())
  530. // return FALSE;
  531. //
  532. // CString csDBName = GetDBName();
  533. // CString csTempDBName = csDBName;
  534. // csTempDBName.Replace(".mdb", "TempDBName.mdb");
  535. //
  536. // //Compact the database
  537. // try
  538. // {
  539. // CDaoWorkspace::CompactDatabase(csDBName, csTempDBName);//, dbLangGeneral, 0, "andrew");//DATABASE_PASSWORD);
  540. // }
  541. // catch(CDaoException* e)
  542. // {
  543. // AfxMessageBox(e->m_pErrorInfo->m_strDescription);
  544. // DeleteFile(csTempDBName);
  545. // e->Delete();
  546. // return FALSE;
  547. // }
  548. // catch(CMemoryException* e)
  549. // {
  550. // AfxMessageBox("Memory Exception");
  551. // DeleteFile(csTempDBName);
  552. // e->Delete();
  553. // return FALSE;
  554. // }
  555. //
  556. // //Since compacting the database creates a new db delete the old one and replace it
  557. // //with the compacted db
  558. // if(DeleteFile(csDBName))
  559. // {
  560. // try
  561. // {
  562. // CFile::Rename(csTempDBName, csDBName);
  563. // }
  564. // catch(CFileException *e)
  565. // {
  566. // e->ReportError();
  567. // e->Delete();
  568. // return FALSE;
  569. // }
  570. // }
  571. // else
  572. // AfxMessageBox("Error Compacting Database");
  573. return TRUE;
  574. }
  575. BOOL RepairDatabase()
  576. {
  577. // if(!theApp.CloseDB())
  578. // return FALSE;
  579. // try
  580. // {
  581. // CDaoWorkspace::RepairDatabase(GetDBName());
  582. // }
  583. // catch(CDaoException *e)
  584. // {
  585. // AfxMessageBox(e->m_pErrorInfo->m_strDescription);
  586. // e->Delete();
  587. // return FALSE;
  588. // }
  589. return TRUE;
  590. }
  591. BOOL RemoveOldEntries(bool checkIdleTime)
  592. {
  593. Log(StrF(_T("Beginning of RemoveOldEntries MaxEntries: %d - Keep days: %d"), CGetSetOptions::GetMaxEntries(), CGetSetOptions::GetExpiredEntries()));
  594. try
  595. {
  596. CppSQLite3DB db;
  597. CString csDbPath = CGetSetOptions::GetDBPath();
  598. db.open(csDbPath);
  599. if(CGetSetOptions::GetCheckForMaxEntries())
  600. {
  601. long lMax = CGetSetOptions::GetMaxEntries();
  602. if(lMax >= 0)
  603. {
  604. CClipIDs IDs;
  605. int clipId;
  606. CppSQLite3Query q = db.execQueryEx(_T("SELECT lID, lShortCut, lParentID, lDontAutoDelete, stickyClipOrder, stickyClipGroupOrder FROM Main WHERE bIsGroup = 0 ORDER BY clipOrder DESC LIMIT -1 OFFSET %d"), lMax);
  607. while(q.eof() == false)
  608. {
  609. int shortcut = q.getIntField(_T("lShortCut"));
  610. int dontDelete = q.getIntField(_T("lDontAutoDelete"));
  611. int parentId = q.getIntField(_T("lParentID"));
  612. double stickyClipOrder = q.getFloatField(_T("stickyClipOrder"));
  613. double stickyClipGroupOrder = q.getFloatField(_T("stickyClipGroupOrder"));
  614. //Only delete entries that have no shortcut and don't have the flag set and aren't in groups and
  615. if(shortcut == 0 &&
  616. dontDelete == 0 &&
  617. parentId <= 0 &&
  618. stickyClipOrder == -(2147483647) &&
  619. stickyClipGroupOrder == -(2147483647))
  620. {
  621. clipId = q.getIntField(_T("lID"));
  622. IDs.Add(clipId);
  623. Log(StrF(_T("From MaxEntries - Deleting Id: %d"), clipId));
  624. }
  625. q.nextRow();
  626. }
  627. if(IDs.GetCount() > 0)
  628. {
  629. IDs.DeleteIDs(false, db);
  630. }
  631. }
  632. }
  633. if(CGetSetOptions::GetCheckForExpiredEntries())
  634. {
  635. long lExpire = CGetSetOptions::GetExpiredEntries();
  636. if(lExpire)
  637. {
  638. CTime now = CTime::GetCurrentTime();
  639. now -= CTimeSpan(lExpire, 0, 0, 0);
  640. CClipIDs IDs;
  641. CppSQLite3Query q = db.execQueryEx(_T("SELECT lID FROM Main ")
  642. _T("WHERE lastPasteDate < %d AND ")
  643. _T("bIsGroup = 0 AND lShortCut = 0 AND lParentID <= 0 AND lDontAutoDelete = 0 AND stickyClipOrder = -(2147483647) AND stickyClipGroupOrder = -(2147483647)"), (int)now.GetTime());
  644. while(q.eof() == false)
  645. {
  646. IDs.Add(q.getIntField(_T("lID")));
  647. Log(StrF(_T("From Clips Expire - Deleting Id: %d"), q.getIntField(_T("lID"))));
  648. q.nextRow();
  649. }
  650. if(IDs.GetCount() > 0)
  651. {
  652. IDs.DeleteIDs(false, db);
  653. }
  654. }
  655. }
  656. int toDeleteCount = db.execScalar(_T("SELECT COUNT(clipID) FROM MainDeletes"));
  657. Log(StrF(_T("Before Deleting emptied out data, count: %d, Idle Seconds: %f"), toDeleteCount, IdleSeconds()));
  658. //Only delete 1 at a time, was finding that it was taking a long time to delete clips, locking the db and causing other queries
  659. //to lock up
  660. CppSQLite3Query q = db.execQueryEx(_T("SELECT * FROM MainDeletes LIMIT %d"), CGetSetOptions::GetMainDeletesDeleteCount());
  661. int deleteCount = 0;
  662. while(q.eof() == false)
  663. {
  664. double idleSeconds = IdleSeconds();
  665. if(checkIdleTime == false || idleSeconds > CGetSetOptions::GetIdleSecondsBeforeDelete())
  666. {
  667. //delete any data items sitting out there that the main table data was deleted
  668. //this was done to speed up deleted from the main table
  669. deleteCount = db.execDMLEx(_T("DELETE FROM MainDeletes WHERE clipID=%d"), q.getIntField(_T("clipID")));
  670. }
  671. else
  672. {
  673. Log(StrF(_T("Computer has not been idle long enough to delete clips, Min Idle: %d, current Idle: %d"),
  674. CGetSetOptions::GetIdleSecondsBeforeDelete(), idleSeconds));
  675. break;
  676. }
  677. q.nextRow();
  678. }
  679. toDeleteCount = db.execScalar(_T("SELECT COUNT(clipID) FROM MainDeletes"));
  680. Log(StrF(_T("After Deleting emptied out data rows, Count: %d, toDelete: %d"), deleteCount, toDeleteCount));
  681. }
  682. CATCH_SQLITE_EXCEPTION
  683. Log(_T("End of RemoveOldEntries"));
  684. return TRUE;
  685. }
  686. BOOL EnsureDirectory(CString csPath)
  687. {
  688. TCHAR drive[_MAX_DRIVE];
  689. TCHAR dir[_MAX_DIR];
  690. TCHAR fname[_MAX_FNAME];
  691. TCHAR ext[_MAX_EXT];
  692. SPLITPATH(csPath, drive, dir, fname, ext);
  693. CString csDir(drive);
  694. csDir += dir;
  695. if(FileExists(csDir) == FALSE)
  696. {
  697. if(CreateDirectory(csDir, NULL))
  698. return TRUE;
  699. }
  700. else
  701. return TRUE;
  702. return FALSE;
  703. }
  704. // BOOL RunZippApp(CString csCommandLine)
  705. // {
  706. // CString csLocalPath = GETENV(_T("U3_HOST_EXEC_PATH"));
  707. // FIX_CSTRING_PATH(csLocalPath);
  708. //
  709. // CString csZippApp = GETENV(_T("U3_DEVICE_EXEC_PATH"));
  710. // FIX_CSTRING_PATH(csZippApp);
  711. // csZippApp += "7za.exe";
  712. //
  713. // csZippApp += " ";
  714. // csZippApp += csCommandLine;
  715. //
  716. // Log(csZippApp);
  717. //
  718. // STARTUPINFO StartupInfo;
  719. // PROCESS_INFORMATION ProcessInformation;
  720. //
  721. // ZeroMemory(&StartupInfo, sizeof(StartupInfo));
  722. // StartupInfo.cb = sizeof(StartupInfo);
  723. // ZeroMemory(&ProcessInformation, sizeof(ProcessInformation));
  724. //
  725. // StartupInfo.dwFlags = STARTF_USESHOWWINDOW;
  726. // StartupInfo.wShowWindow = SW_HIDE;
  727. //
  728. // BOOL bRet = CreateProcess(NULL, csZippApp.GetBuffer(csZippApp.GetLength()), NULL, NULL, FALSE,
  729. // CREATE_DEFAULT_ERROR_MODE | NORMAL_PRIORITY_CLASS, NULL, csLocalPath,
  730. // &StartupInfo, &ProcessInformation);
  731. //
  732. // if(bRet)
  733. // {
  734. // WaitForSingleObject(ProcessInformation.hProcess, INFINITE);
  735. //
  736. // DWORD dwExitCode;
  737. // GetExitCodeProcess(ProcessInformation.hProcess, &dwExitCode);
  738. //
  739. // CString cs;
  740. // cs.Format(_T("Exit code from unzip = %d"), dwExitCode);
  741. // Log(cs);
  742. //
  743. // if(dwExitCode != 0)
  744. // {
  745. // bRet = FALSE;
  746. // }
  747. // }
  748. // else
  749. // {
  750. // bRet = FALSE;
  751. // Log(_T("Create Process Failed"));
  752. // }
  753. //
  754. // csZippApp.ReleaseBuffer();
  755. //
  756. // return bRet;
  757. // }
  758. // BOOL CopyDownDatabase()
  759. // {
  760. // BOOL bRet = FALSE;
  761. //
  762. // CString csZippedPath = GETENV(_T("U3_APP_DATA_PATH"));
  763. // FIX_CSTRING_PATH(csZippedPath);
  764. //
  765. // CString csUnZippedPath = csZippedPath;
  766. // csUnZippedPath += "Ditto.db";
  767. //
  768. // csZippedPath += "Ditto.7z";
  769. //
  770. // CString csLocalPath = GETENV(_T("U3_HOST_EXEC_PATH"));
  771. // FIX_CSTRING_PATH(csLocalPath);
  772. //
  773. // if(FileExists(csZippedPath))
  774. // {
  775. // CString csCommandLine;
  776. //
  777. // //e = extract
  778. // //surround command line arguments with quotes
  779. // //-aoa = overight files with extracted files
  780. //
  781. // csCommandLine += "e ";
  782. // csCommandLine += "\"";
  783. // csCommandLine += csZippedPath;
  784. // csCommandLine += "\"";
  785. // csCommandLine += " -o";
  786. // csCommandLine += "\"";
  787. // csCommandLine += csLocalPath;
  788. // csCommandLine += "\"";
  789. // csCommandLine += " -aoa";
  790. //
  791. // bRet = RunZippApp(csCommandLine);
  792. //
  793. // csLocalPath += "Ditto.db";
  794. // }
  795. // else if(FileExists(csUnZippedPath))
  796. // {
  797. // csLocalPath += "Ditto.db";
  798. // bRet = CopyFile(csUnZippedPath, csLocalPath, FALSE);
  799. // }
  800. //
  801. // if(FileExists(csLocalPath) == FALSE)
  802. // {
  803. // Log(_T("Failed to copy files from device zip file"));
  804. // }
  805. //
  806. // g_Opt.nLastDbWriteTime = GetLastWriteTime(csLocalPath);
  807. //
  808. // return bRet;
  809. // }
  810. //BOOL CopyUpDatabase()
  811. //{
  812. // CStringA csZippedPath = "C:\\";//getenv("U3_APP_DATA_PATH");
  813. // FIX_CSTRING_PATH(csZippedPath);
  814. // csZippedPath += "Ditto.zip";
  815. // CStringA csLocalPath = GetDBName();//getenv("U3_HOST_EXEC_PATH");
  816. // //FIX_CSTRING_PATH(csLocalPath);
  817. // //csLocalPath += "Ditto.db";
  818. //
  819. // CZipper Zip;
  820. //
  821. // if(Zip.OpenZip(csZippedPath))
  822. // {
  823. // Zip.AddFileToZip(csLocalPath);
  824. // }
  825. //
  826. // return TRUE;
  827. //}