2 * This file is part of NixNote/NeighborNote
3 * Copyright 2009 Randy Baumgarte
4 * Copyright 2013 Yuki Takahashi
6 * This file may be licensed under the terms of of the
7 * GNU General Public License Version 2 (the ``GPL'').
9 * Software distributed under the License is distributed
10 * on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either
11 * express or implied. See the GPL for the specific language
12 * governing rights and limitations.
14 * You should have received a copy of the GPL along with this
15 * program. If not, go to http://www.gnu.org/licenses/gpl.html
16 * or write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 package cx.fbn.nevernote.sql;
23 import java.sql.Connection;
24 import java.sql.DriverManager;
25 import java.sql.SQLException;
27 import cx.fbn.nevernote.Global;
28 import cx.fbn.nevernote.sql.driver.NSqlQuery;
29 import cx.fbn.nevernote.utilities.ApplicationLogger;
32 public class DatabaseConnection {
34 private WordsTable wordsTable;
35 private TagTable tagTable;
36 private NotebookTable notebookTable;
37 private NoteTable noteTable;
38 private DeletedTable deletedTable;
39 private SavedSearchTable searchTable;
40 private WatchFolderTable watchFolderTable;
41 private InvalidXMLTable invalidXMLTable;
42 private LinkedNotebookTable linkedNotebookTable;
43 private SharedNotebookTable sharedNotebookTable;
44 private InkImagesTable inkImagesTable;
45 private SyncTable syncTable;
46 private SystemIconTable systemIconTable;
47 private HistoryTable historyTable;
48 private ExcludedTable excludedTable;
49 private StaredTable staredTable;
51 private final ApplicationLogger logger;
52 private Connection conn;
53 private Connection indexConn;
54 private Connection resourceConn;
55 private Connection behaviorConn;
60 public DatabaseConnection(ApplicationLogger l, String url, String iurl, String rurl, String burl, String userid, String password, String cypherPassword, int throttle) {
62 this.throttle = throttle;
63 dbSetup(url, iurl, rurl, burl, userid, password, cypherPassword);
66 private void setupTables() {
67 tagTable = new TagTable(logger, this);
68 notebookTable = new NotebookTable(logger, this);
69 noteTable = new NoteTable(logger, this);
70 deletedTable = new DeletedTable(logger, this);
71 searchTable = new SavedSearchTable(logger, this);
72 watchFolderTable = new WatchFolderTable(logger, this);
73 invalidXMLTable = new InvalidXMLTable(logger, this);
74 wordsTable = new WordsTable(logger, this);
75 syncTable = new SyncTable(logger, this);
76 linkedNotebookTable = new LinkedNotebookTable(logger, this);
77 sharedNotebookTable = new SharedNotebookTable(logger, this);
78 systemIconTable = new SystemIconTable(logger, this);
79 inkImagesTable = new InkImagesTable(logger, this);
80 historyTable = new HistoryTable(logger, this);
81 excludedTable = new ExcludedTable(logger, this);
82 staredTable = new StaredTable(logger, this);
87 // Compact the database
88 public void compactDatabase() {
92 // Initialize the database connection
93 public void dbSetup(String url,String indexUrl, String resourceUrl, String behaviorUrl, String userid, String userPassword, String cypherPassword) {
94 logger.log(logger.HIGH, "Entering DatabaseConnection.dbSetup " +id);
98 Class.forName("org.h2.Driver");
99 } catch (ClassNotFoundException e1) {
100 e1.printStackTrace();
104 // QJdbc.initialize();
108 File f = Global.getFileManager().getDbDirFile(Global.databaseName + ".h2.db");
109 boolean dbExists = f.exists();
110 f = Global.getFileManager().getDbDirFile(Global.indexDatabaseName + ".h2.db");
111 boolean indexDbExists = f.exists();
112 f = Global.getFileManager().getDbDirFile(Global.resourceDatabaseName + ".h2.db");
113 boolean resourceDbExists = f.exists();
114 f = Global.getFileManager().getDbDirFile(Global.behaviorDatabaseName + ".h2.db");
115 boolean behaviorDbExists = f.exists();
117 logger.log(logger.HIGH, "Entering RDatabaseConnection.dbSetup");
119 String passwordString = null;
122 if (cypherPassword==null || cypherPassword.trim().equals(""))
123 passwordString = userPassword;
125 passwordString = cypherPassword+" "+userPassword;
126 // conn = DriverManager.getConnection(url,userid,passwordString);
127 // conn = DriverManager.getConnection(url,userid,passwordString);
128 // conn = DriverManager.getConnection(url+";CACHE_SIZE=4096",userid,passwordString);
130 conn = DriverManager.getConnection(url+";CACHE_SIZE="+Global.databaseCache,userid,passwordString);
132 conn = DriverManager.getConnection(url+";THROTTLE=" +new Integer(throttle).toString()+";CACHE_SIZE="+Global.databaseCache,userid,passwordString);
134 indexConn = DriverManager.getConnection(indexUrl,userid,passwordString);
135 resourceConn = DriverManager.getConnection(resourceUrl,userid,passwordString);
136 behaviorConn = DriverManager.getConnection(behaviorUrl, userid, passwordString);
138 // conn = DriverManager.getConnection(url+";AUTO_SERVER=TRUE",userid,passwordString);
139 } catch (SQLException e) {
144 // If it doesn't exist and we are the main thread, then we need to create stuff.
147 Global.setAutomaticLogin(false);
149 if (!resourceDbExists) {
150 createResourceTables();
151 if (dbTableExists("NoteResources")) {
152 // Begin migration of database
153 NSqlQuery query = new NSqlQuery(resourceConn);
154 String linkcmd = "create linked table oldnoteresources "+
155 "('org.h2.Driver', '"+url+"', '"+userid+"', '"+passwordString+"', 'NoteResources')";
157 query.exec("insert into noteresources (select * from oldnoteresources)");
158 query.exec("Drop table oldnoteresources;");
159 query.exec("Update noteresources set indexneeded='true'");
163 if (!indexDbExists) {
165 executeSql("Update note set indexneeded='true'");
168 // 操作履歴テーブルと除外ノートテーブルとスター付きノートテーブルを作る
169 if (!behaviorDbExists) {
170 createHistoryTables();
171 createExcludedTables();
172 createStaredTables();
175 // If we encrypted/decrypted it the last time, we need to reconnect the tables.
176 // if (Global.relinkTables) {
177 // NSqlQuery query = new NSqlQuery(conn);
178 // query.exec("Drop table NoteResources;");
179 // String linkcmd = "create linked table NoteResources "
180 // +"('org.h2.Driver', '"+url+"', '"+userid+"', '"+passwordString+ "', 'NoteResources')";
181 // System.out.println(linkcmd);
182 // query.exec(linkcmd);
183 // System.err.println(query.lastError());
184 // Global.relinkTables = false;
188 logger.log(logger.HIGH, "Leaving DatabaseConnection.dbSetup" +id);
192 public void dbShutdown() {
193 logger.log(logger.HIGH, "Entering RDatabaseConnection.dbShutdown");
196 } catch (SQLException e) {
199 logger.log(logger.HIGH, "Leaving RDatabaseConnection.dbShutdown");
202 public void upgradeDb(String version) {
203 if (version.equals("0.85")) {
204 executeSql("alter table note add column titleColor integer");
205 executeSql("alter table note add column thumbnail blob");
206 executeSql("alter table note add column thumbnailneeded boolean");
207 executeSql("Update note set thumbnailneeded = true;");
208 executeSql("create index NOTE_NOTEBOOK_INDEX on note (notebookguid, guid);");
209 executeSql("create index NOTETAGS_TAG_INDEX on notetags (tagguid, noteguid);");
211 Global.setDatabaseVersion(version);
213 if (version.equals("0.86")) {
215 executeSql("alter table notebook add column publishingUri VarChar");
216 executeSql("alter table notebook add column publishingOrder Integer");
217 executeSql("alter table notebook add column publishingAscending Boolean");
218 executeSql("alter table notebook add column publishingPublicDescription varchar");
219 executeSql("alter table notebook add column stack varchar");
220 executeSql("alter table notebook add column icon blob");
221 executeSql("alter table notebook add column readOnly boolean");
222 executeSql("alter table notebook add column linked boolean");
224 executeSql("alter table tag add column realname varchar");
225 executeSql("alter table tag add column linked boolean");
226 executeSql("alter table tag add column icon blob");
227 executeSql("alter table tag add column notebookguid varchar");
228 executeSql("alter table SavedSearch add column icon blob");
230 executeSql("create index NOTE_THUMBNAIL_INDEX on note (thumbnailneeded, guid);");
231 executeSql("create index NOTE_EXPUNGED_INDEX on note (isExpunged, guid);");
232 executeSql("create index NOTE_DUEDATE_INDEX on note (attributeSubjectDate, guid);");
233 executeSql("create index TAG_NOTEBOOK_INDEX on tag (notebookGuid);");
235 executeSql("update note set thumbnailneeded=true, thumbnail=null;");
236 executeSql("update notebook set publishingUri='', " +
237 "publishingAscending=false, stack='', readonly=false, publishingOrder=1, " +
238 "publishingPublicDescription='', linked=false");
239 executeSql("update tag set linked=false, realname='', notebookguid=''");
241 sharedNotebookTable.createTable();
242 linkedNotebookTable.createTable();
243 systemIconTable.createTable();
244 inkImagesTable.createTable();
247 executeSql("Insert into Sync (key, value) values ('FullNotebookSync', 'true')");
248 executeSql("Insert into Sync (key, value) values ('FullLinkedNotebookSync', 'true')");
249 executeSql("Insert into Sync (key, value) values ('FullSharedNotebookSync', 'true')");
250 executeSql("Insert into Sync (key, value) values ('FullInkNoteImageSync', 'true')");
251 Global.setDatabaseVersion(version);
253 if (version.equals("0.95")) {
254 if (dbTableExists("words"))
255 executeSql("Drop table words;");
256 if (dbTableExists("NoteResources"))
257 executeSql("Drop table NoteResources;");
259 if (!dbTableColumnExists("NOTE", "ORIGINAL_GUID")) {
260 executeSql("alter table note add column ORIGINAL_GUID VarChar");
261 executeSql("create index NOTE_ORIGINAL_GUID_INDEX on note (original_guid, guid);");
263 if (!dbTableColumnExists("NOTEBOOK", "NARROW_SORT_ORDER")) {
264 executeSql("alter table notebook add column NARROW_SORT_ORDER integer");
265 executeSql("update notebook set NARROW_SORT_ORDER = -1");
267 executeSql("alter table notebook add column WIDE_SORT_ORDER integer");
268 executeSql("update notebook set WIDE_SORT_ORDER = -1");
270 executeSql("alter table notebook add column WIDE_SORT_COLUMN integer");
271 executeSql("update notebook set WIDE_SORT_COLUMN = -1");
273 executeSql("alter table notebook add column NARROW_SORT_COLUMN integer");
274 executeSql("update notebook set NARROW_SORT_COLUMN = -1");
276 if (!dbTableColumnExists("NOTE", "PINNED")) {
277 executeSql("alter table note add column pinned integer");
278 executeSql("update note set pinned = 0");
280 if (!dbTableColumnExists("NOTE", "ATTRIBUTECONTENTCLASS")) {
281 executeSql("alter table note add column attributeContentClass VarChar");
282 executeSql("update note set attributeContentClass = ''");
285 // Apache Luceneを使った日本語検索のためのプレーンテキストノートコンテンツカラムを準備
286 if (!dbTableColumnExists("NOTE", "CONTENTTEXT")) {
287 executeSql("alter table note add column contentText VarChar");
288 executeSql("update note set contentText = ''");
289 NSqlQuery query = new NSqlQuery(conn);
290 query.exec("Select guid, content from Note where contentText = ''");
291 while (query.next()) {
292 String guid = query.valueString(0);
293 String content = query.valueString(1);
294 String contentText = Global.extractPlainText(content);
295 NSqlQuery query2 = new NSqlQuery(conn);
296 query2.prepare("update note set contentText=:contentText where guid=:guid");
297 query2.bindValue(":contentText", contentText);
298 query2.bindValue(":guid", guid);
302 // Apache Luceneを使った全文検索のための準備
303 query.exec("CREATE ALIAS IF NOT EXISTS FTL_INIT FOR \"org.h2.fulltext.FullTextLuceneEx.init\"");
304 query.exec("CALL FTL_INIT()");
306 Global.rebuildFullTextNoteTarget(this);
309 // Apache Luceneを使った日本語検索のためのプレーンテキストノートリソースカラムを準備
310 NSqlQuery rQuery = new NSqlQuery(resourceConn);
311 rQuery.exec("select TABLE_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='NOTERESOURCES' and COLUMN_NAME='RESOURCETEXT'");
312 if (!rQuery.next()) {
313 rQuery.exec("alter table noteResources add column resourceText VarChar");
314 rQuery.exec("update noteResources set resourceText = ''");
316 // Apache Luceneを使った全文検索のための準備
317 rQuery.exec("CREATE ALIAS IF NOT EXISTS FTL_INIT FOR \"org.h2.fulltext.FullTextLuceneEx.init\"");
318 rQuery.exec("CALL FTL_INIT()");
320 Global.rebuildFullTextResourceTarget(this);
324 public void executeSql(String sql) {
325 NSqlQuery query = new NSqlQuery(conn);
329 public void checkDatabaseVersion() {
330 if (!Global.getDatabaseVersion().equals("0.86")) {
331 upgradeDb(Global.getDatabaseVersion());
333 if (!Global.getDatabaseVersion().equals("0.95")) {
334 upgradeDb(Global.getDatabaseVersion());
336 if (!Global.getDatabaseVersion().equals("0.97")) {
337 upgradeDb(Global.getDatabaseVersion());
342 public void backupDatabase(int highSequence, long date) {
347 public void createTables() {
348 Global.setDatabaseVersion("0.85");
349 Global.setAutomaticLogin(false);
350 Global.saveCurrentNoteGuid("");
351 Global.saveUploadAmount(0);
353 getTagTable().createTable();
354 notebookTable.createTable(true);
355 noteTable.createTable();
356 deletedTable.createTable();
357 searchTable.createTable();
358 watchFolderTable.createTable();
359 invalidXMLTable.createTable();
360 syncTable.createTable();
363 public void createIndexTables() {
364 wordsTable.createTable();
367 public void createResourceTables() {
368 noteTable.noteResourceTable.createTable();
371 public void createHistoryTables() {
372 historyTable.createTable();
375 public void createExcludedTables() {
376 excludedTable.createTable();
379 public void createStaredTables() {
380 staredTable.createTable();
383 public Connection getConnection() {
386 public Connection getIndexConnection() {
389 public Connection getResourceConnection() {
393 public Connection getBehaviorConnection() {
397 //***************************************************************
398 //* Table get methods
399 //***************************************************************
400 public DeletedTable getDeletedTable() {
403 public TagTable getTagTable() {
406 public NoteTable getNoteTable() {
409 public NotebookTable getNotebookTable() {
410 return notebookTable;
412 public SavedSearchTable getSavedSearchTable() {
415 public WatchFolderTable getWatchFolderTable() {
416 return watchFolderTable;
418 public WordsTable getWordsTable() {
421 public InvalidXMLTable getInvalidXMLTable() {
422 return invalidXMLTable;
424 public SyncTable getSyncTable() {
427 public LinkedNotebookTable getLinkedNotebookTable() {
428 return linkedNotebookTable;
430 public SharedNotebookTable getSharedNotebookTable() {
431 return sharedNotebookTable;
433 public SystemIconTable getSystemIconTable() {
434 return systemIconTable;
436 public InkImagesTable getInkImagesTable() {
437 return inkImagesTable;
440 public HistoryTable getHistoryTable() {
444 public ExcludedTable getExcludedTable() {
445 return excludedTable;
448 public StaredTable getStaredTable() {
452 //****************************************************************
453 //* Begin/End transactions
454 //****************************************************************
455 public void beginTransaction() {
457 NSqlQuery query = new NSqlQuery(getConnection());
458 if (!query.exec("Begin Transaction"))
459 logger.log(logger.EXTREME, "Begin transaction has failed: " +query.lastError());
462 public void commitTransaction() {
463 NSqlQuery query = new NSqlQuery(getConnection());
465 if (!query.exec("Commit"))
466 logger.log(logger.EXTREME, "Transaction commit has failed: " +query.lastError());
469 //****************************************************************
470 //* Check if a table exists
471 //****************************************************************
472 public boolean dbTableExists(String name) {
473 NSqlQuery query = new NSqlQuery(getConnection());
474 query.prepare("select TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_NAME=:name");
475 query.bindValue(":name", name.toUpperCase());
483 //****************************************************************
484 //* Check if a row in a table exists
485 //****************************************************************
486 public boolean dbTableColumnExists(String tableName, String columnName) {
487 NSqlQuery query = new NSqlQuery(getConnection());
488 query.prepare("select TABLE_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME=:name and COLUMN_NAME=:column");
489 query.bindValue(":name", tableName.toUpperCase());
490 query.bindValue(":column", columnName);