2 * This file is part of NeverNote
3 * Copyright 2009 Randy Baumgarte
5 * This file may be licensed under the terms of of the
6 * GNU General Public License Version 2 (the ``GPL'').
8 * Software distributed under the License is distributed
9 * on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either
10 * express or implied. See the GPL for the specific language
11 * governing rights and limitations.
13 * You should have received a copy of the GPL along with this
14 * program. If not, go to http://www.gnu.org/licenses/gpl.html
15 * or write to the Free Software Foundation, Inc.,
16 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 package cx.fbn.nevernote.sql;
22 import java.sql.Connection;
23 import java.sql.DriverManager;
24 import java.sql.SQLException;
26 import cx.fbn.nevernote.Global;
27 import cx.fbn.nevernote.sql.driver.NSqlQuery;
28 import cx.fbn.nevernote.utilities.ApplicationLogger;
31 public class DatabaseConnection {
33 private WordsTable wordsTable;
34 private TagTable tagTable;
35 private NotebookTable notebookTable;
36 private NoteTable noteTable;
37 private DeletedTable deletedTable;
38 private SavedSearchTable searchTable;
39 private WatchFolderTable watchFolderTable;
40 private InvalidXMLTable invalidXMLTable;
41 private LinkedNotebookTable linkedNotebookTable;
42 private SharedNotebookTable sharedNotebookTable;
43 private InkImagesTable inkImagesTable;
44 private SyncTable syncTable;
45 private SystemIconTable systemIconTable;
46 private final ApplicationLogger logger;
47 private Connection conn;
48 private Connection indexConn;
49 private Connection resourceConn;
54 public DatabaseConnection(ApplicationLogger l, String url, String iurl, String rurl, String userid, String password, String cypherPassword, int throttle) {
56 this.throttle = throttle;
57 dbSetup(url, iurl, rurl, userid, password, cypherPassword);
60 private void setupTables() {
61 tagTable = new TagTable(logger, this);
62 notebookTable = new NotebookTable(logger, this);
63 noteTable = new NoteTable(logger, this);
64 deletedTable = new DeletedTable(logger, this);
65 searchTable = new SavedSearchTable(logger, this);
66 watchFolderTable = new WatchFolderTable(logger, this);
67 invalidXMLTable = new InvalidXMLTable(logger, this);
68 wordsTable = new WordsTable(logger, this);
69 syncTable = new SyncTable(logger, this);
70 linkedNotebookTable = new LinkedNotebookTable(logger, this);
71 sharedNotebookTable = new SharedNotebookTable(logger, this);
72 systemIconTable = new SystemIconTable(logger, this);
73 inkImagesTable = new InkImagesTable(logger, this);
77 // Compact the database
78 public void compactDatabase() {
82 // Initialize the database connection
83 public void dbSetup(String url,String indexUrl, String resourceUrl, String userid, String userPassword, String cypherPassword) {
84 logger.log(logger.HIGH, "Entering DatabaseConnection.dbSetup " +id);
88 Class.forName("org.h2.Driver");
89 } catch (ClassNotFoundException e1) {
94 // QJdbc.initialize();
98 File f = Global.getFileManager().getDbDirFile(Global.databaseName + ".h2.db");
99 boolean dbExists = f.exists();
100 f = Global.getFileManager().getDbDirFile(Global.indexDatabaseName + ".h2.db");
101 boolean indexDbExists = f.exists();
102 f = Global.getFileManager().getDbDirFile(Global.resourceDatabaseName + ".h2.db");
103 boolean resourceDbExists = f.exists();
105 logger.log(logger.HIGH, "Entering RDatabaseConnection.dbSetup");
107 String passwordString = null;
110 if (cypherPassword==null || cypherPassword.trim().equals(""))
111 passwordString = userPassword;
113 passwordString = cypherPassword+" "+userPassword;
114 // conn = DriverManager.getConnection(url,userid,passwordString);
115 // conn = DriverManager.getConnection(url,userid,passwordString);
116 // conn = DriverManager.getConnection(url+";CACHE_SIZE=4096",userid,passwordString);
118 conn = DriverManager.getConnection(url+";CACHE_SIZE="+Global.databaseCache,userid,passwordString);
120 conn = DriverManager.getConnection(url+";THROTTLE=" +new Integer(throttle).toString()+";CACHE_SIZE="+Global.databaseCache,userid,passwordString);
122 indexConn = DriverManager.getConnection(indexUrl,userid,passwordString);
123 resourceConn = DriverManager.getConnection(resourceUrl,userid,passwordString);
124 // conn = DriverManager.getConnection(url+";AUTO_SERVER=TRUE",userid,passwordString);
125 } catch (SQLException e) {
130 // If it doesn't exist and we are the main thread, then we need to create stuff.
133 Global.setAutomaticLogin(false);
135 if (!resourceDbExists) {
136 createResourceTables();
137 if (dbTableExists("NoteResources")) {
138 // Begin migration of database
139 NSqlQuery query = new NSqlQuery(resourceConn);
140 String linkcmd = "create linked table oldnoteresources "+
141 "('org.h2.Driver', '"+url+"', '"+userid+"', '"+passwordString+"', 'NoteResources')";
143 query.exec("insert into noteresources (select * from oldnoteresources)");
144 query.exec("Drop table oldnoteresources;");
145 query.exec("Update noteresources set indexneeded='true'");
149 if (!indexDbExists) {
151 executeSql("Update note set indexneeded='true'");
154 logger.log(logger.HIGH, "Leaving DatabaseConnection.dbSetup" +id);
158 public void dbShutdown() {
159 logger.log(logger.HIGH, "Entering RDatabaseConnection.dbShutdown");
162 } catch (SQLException e) {
165 logger.log(logger.HIGH, "Leaving RDatabaseConnection.dbShutdown");
168 public void upgradeDb(String version) {
169 if (version.equals("0.85")) {
170 executeSql("alter table note add column titleColor integer");
171 executeSql("alter table note add column thumbnail blob");
172 executeSql("alter table note add column thumbnailneeded boolean");
173 executeSql("Update note set thumbnailneeded = true;");
174 executeSql("create index NOTE_NOTEBOOK_INDEX on note (notebookguid, guid);");
175 executeSql("create index NOTETAGS_TAG_INDEX on notetags (tagguid, noteguid);");
177 Global.setDatabaseVersion(version);
179 if (version.equals("0.86")) {
181 executeSql("alter table notebook add column publishingUri VarChar");
182 executeSql("alter table notebook add column publishingOrder Integer");
183 executeSql("alter table notebook add column publishingAscending Boolean");
184 executeSql("alter table notebook add column publishingPublicDescription varchar");
185 executeSql("alter table notebook add column stack varchar");
186 executeSql("alter table notebook add column icon blob");
187 executeSql("alter table notebook add column readOnly boolean");
188 executeSql("alter table notebook add column linked boolean");
190 executeSql("alter table tag add column realname varchar");
191 executeSql("alter table tag add column linked boolean");
192 executeSql("alter table tag add column icon blob");
193 executeSql("alter table tag add column notebookguid varchar");
194 executeSql("alter table SavedSearch add column icon blob");
196 executeSql("create index NOTE_THUMBNAIL_INDEX on note (thumbnailneeded, guid);");
197 executeSql("create index NOTE_EXPUNGED_INDEX on note (isExpunged, guid);");
198 executeSql("create index NOTE_DUEDATE_INDEX on note (attributeSubjectDate, guid);");
199 executeSql("create index TAG_NOTEBOOK_INDEX on tag (notebookGuid);");
201 executeSql("update note set thumbnailneeded=true, thumbnail=null;");
202 executeSql("update notebook set publishingUri='', " +
203 "publishingAscending=false, stack='', readonly=false, publishingOrder=1, " +
204 "publishingPublicDescription='', linked=false");
205 executeSql("update tag set linked=false, realname='', notebookguid=''");
207 sharedNotebookTable.createTable();
208 linkedNotebookTable.createTable();
209 systemIconTable.createTable();
210 inkImagesTable.createTable();
213 executeSql("Insert into Sync (key, value) values ('FullNotebookSync', 'true')");
214 executeSql("Insert into Sync (key, value) values ('FullLinkedNotebookSync', 'true')");
215 executeSql("Insert into Sync (key, value) values ('FullSharedNotebookSync', 'true')");
216 executeSql("Insert into Sync (key, value) values ('FullInkNoteImageSync', 'true')");
217 Global.setDatabaseVersion(version);
219 if (version.equals("0.95")) {
220 if (dbTableExists("words"))
221 executeSql("Drop table words;");
222 if (dbTableExists("NoteResources"))
223 executeSql("Drop table NoteResources;");
225 if (!dbTableColumnExists("NOTE", "ORIGINAL_GUID")) {
226 executeSql("alter table note add column ORIGINAL_GUID VarChar");
227 executeSql("create index NOTE_ORIGINAL_GUID_INDEX on note (original_guid, guid);");
233 public void executeSql(String sql) {
234 NSqlQuery query = new NSqlQuery(conn);
238 public void checkDatabaseVersion() {
239 if (!Global.getDatabaseVersion().equals("0.86")) {
240 upgradeDb(Global.getDatabaseVersion());
242 if (!Global.getDatabaseVersion().equals("0.95")) {
243 upgradeDb(Global.getDatabaseVersion());
245 if (!Global.getDatabaseVersion().equals("0.97")) {
246 upgradeDb(Global.getDatabaseVersion());
251 public void backupDatabase(int highSequence, long date) {
256 public void createTables() {
257 Global.setDatabaseVersion("0.85");
258 Global.setAutomaticLogin(false);
259 Global.saveCurrentNoteGuid("");
260 Global.saveUploadAmount(0);
262 getTagTable().createTable();
263 notebookTable.createTable(true);
264 noteTable.createTable();
265 deletedTable.createTable();
266 searchTable.createTable();
267 watchFolderTable.createTable();
268 invalidXMLTable.createTable();
269 syncTable.createTable();
272 public void createIndexTables() {
273 wordsTable.createTable();
276 public void createResourceTables() {
277 noteTable.noteResourceTable.createTable();
280 public Connection getConnection() {
283 public Connection getIndexConnection() {
286 public Connection getResourceConnection() {
290 //***************************************************************
291 //* Table get methods
292 //***************************************************************
293 public DeletedTable getDeletedTable() {
296 public TagTable getTagTable() {
299 public NoteTable getNoteTable() {
302 public NotebookTable getNotebookTable() {
303 return notebookTable;
305 public SavedSearchTable getSavedSearchTable() {
308 public WatchFolderTable getWatchFolderTable() {
309 return watchFolderTable;
311 public WordsTable getWordsTable() {
314 public InvalidXMLTable getInvalidXMLTable() {
315 return invalidXMLTable;
317 public SyncTable getSyncTable() {
320 public LinkedNotebookTable getLinkedNotebookTable() {
321 return linkedNotebookTable;
323 public SharedNotebookTable getSharedNotebookTable() {
324 return sharedNotebookTable;
326 public SystemIconTable getSystemIconTable() {
327 return systemIconTable;
329 public InkImagesTable getInkImagesTable() {
330 return inkImagesTable;
333 //****************************************************************
334 //* Begin/End transactions
335 //****************************************************************
336 public void beginTransaction() {
338 NSqlQuery query = new NSqlQuery(getConnection());
339 if (!query.exec("Begin Transaction"))
340 logger.log(logger.EXTREME, "Begin transaction has failed: " +query.lastError());
343 public void commitTransaction() {
344 NSqlQuery query = new NSqlQuery(getConnection());
346 if (!query.exec("Commit"))
347 logger.log(logger.EXTREME, "Transaction commit has failed: " +query.lastError());
350 //****************************************************************
351 //* Check if a table exists
352 //****************************************************************
353 public boolean dbTableExists(String name) {
354 NSqlQuery query = new NSqlQuery(getConnection());
355 query.prepare("select TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_NAME=:name");
356 query.bindValue(":name", name.toUpperCase());
364 //****************************************************************
365 //* Check if a row in a table exists
366 //****************************************************************
367 public boolean dbTableColumnExists(String tableName, String columnName) {
368 NSqlQuery query = new NSqlQuery(getConnection());
369 query.prepare("select TABLE_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME=:name and COLUMN_NAME=:column");
370 query.bindValue(":name", tableName.toUpperCase());
371 query.bindValue(":column", columnName);