2 * Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved.
3 * Copyright (C) 2007 Justin Haygood (jhaygood@reaktix.com)
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
15 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
18 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
19 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
20 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
21 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
22 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 #include "SQLiteDatabase.h"
31 #include "DatabaseAuthorizer.h"
33 #include "SQLiteFileSystem.h"
34 #include "SQLiteStatement.h"
36 #include <wtf/Threading.h>
37 #include <wtf/text/CString.h>
38 #include <wtf/text/WTFString.h>
42 const int SQLResultDone = SQLITE_DONE;
43 const int SQLResultError = SQLITE_ERROR;
44 const int SQLResultOk = SQLITE_OK;
45 const int SQLResultRow = SQLITE_ROW;
46 const int SQLResultSchema = SQLITE_SCHEMA;
47 const int SQLResultFull = SQLITE_FULL;
48 const int SQLResultInterrupt = SQLITE_INTERRUPT;
50 SQLiteDatabase::SQLiteDatabase()
53 , m_transactionInProgress(false)
56 , m_interrupted(false)
60 SQLiteDatabase::~SQLiteDatabase()
65 bool SQLiteDatabase::open(const String& filename, bool forWebSQLDatabase)
69 if (SQLiteFileSystem::openDatabase(filename, &m_db, forWebSQLDatabase) != SQLITE_OK) {
70 LOG_ERROR("SQLite database failed to load from %s\nCause - %s", filename.ascii().data(),
71 sqlite3_errmsg(m_db));
76 if (sqlite3_extended_result_codes(m_db, 1) != SQLITE_OK) {
77 LOG_ERROR("SQLite database error when enabling extended errors - %s", sqlite3_errmsg(m_db));
84 m_openingThread = currentThread();
86 if (!SQLiteStatement(*this, "PRAGMA temp_store = MEMORY;").executeCommand())
87 LOG_ERROR("SQLite database could not set temp_store to memory");
92 void SQLiteDatabase::close()
95 // FIXME: This is being called on themain thread during JS GC. <rdar://problem/5739818>
96 // ASSERT(currentThread() == m_openingThread);
99 MutexLocker locker(m_databaseClosingMutex);
108 void SQLiteDatabase::interrupt()
110 m_interrupted = true;
111 while (!m_lockingMutex.tryLock()) {
112 MutexLocker locker(m_databaseClosingMutex);
115 sqlite3_interrupt(m_db);
119 m_lockingMutex.unlock();
122 bool SQLiteDatabase::isInterrupted()
124 ASSERT(!m_lockingMutex.tryLock());
125 return m_interrupted;
128 void SQLiteDatabase::setFullsync(bool fsync)
131 executeCommand("PRAGMA fullfsync = 1;");
133 executeCommand("PRAGMA fullfsync = 0;");
136 int64_t SQLiteDatabase::maximumSize()
138 int64_t maxPageCount = 0;
141 MutexLocker locker(m_authorizerLock);
142 enableAuthorizer(false);
143 SQLiteStatement statement(*this, "PRAGMA max_page_count");
144 maxPageCount = statement.getColumnInt64(0);
145 enableAuthorizer(true);
148 return maxPageCount * pageSize();
151 void SQLiteDatabase::setMaximumSize(int64_t size)
156 int currentPageSize = pageSize();
158 ASSERT(currentPageSize);
159 int64_t newMaxPageCount = currentPageSize ? size / currentPageSize : 0;
161 MutexLocker locker(m_authorizerLock);
162 enableAuthorizer(false);
164 SQLiteStatement statement(*this, "PRAGMA max_page_count = " + String::number(newMaxPageCount));
166 if (statement.step() != SQLResultRow)
168 LOG_ERROR("Failed to set maximum size of database to %I64i bytes", static_cast<long long>(size));
170 LOG_ERROR("Failed to set maximum size of database to %lli bytes", static_cast<long long>(size));
173 enableAuthorizer(true);
177 int SQLiteDatabase::pageSize()
179 // Since the page size of a database is locked in at creation and therefore cannot be dynamic,
180 // we can cache the value for future use
181 if (m_pageSize == -1) {
182 MutexLocker locker(m_authorizerLock);
183 enableAuthorizer(false);
185 SQLiteStatement statement(*this, "PRAGMA page_size");
186 m_pageSize = statement.getColumnInt(0);
188 enableAuthorizer(true);
194 int64_t SQLiteDatabase::freeSpaceSize()
196 int64_t freelistCount = 0;
199 MutexLocker locker(m_authorizerLock);
200 enableAuthorizer(false);
201 // Note: freelist_count was added in SQLite 3.4.1.
202 SQLiteStatement statement(*this, "PRAGMA freelist_count");
203 freelistCount = statement.getColumnInt64(0);
204 enableAuthorizer(true);
207 return freelistCount * pageSize();
210 int64_t SQLiteDatabase::totalSize()
212 int64_t pageCount = 0;
215 MutexLocker locker(m_authorizerLock);
216 enableAuthorizer(false);
217 SQLiteStatement statement(*this, "PRAGMA page_count");
218 pageCount = statement.getColumnInt64(0);
219 enableAuthorizer(true);
222 return pageCount * pageSize();
225 void SQLiteDatabase::setSynchronous(SynchronousPragma sync)
227 executeCommand("PRAGMA synchronous = " + String::number(sync));
230 void SQLiteDatabase::setBusyTimeout(int ms)
233 sqlite3_busy_timeout(m_db, ms);
235 LOG(SQLDatabase, "BusyTimeout set on non-open database");
238 void SQLiteDatabase::setBusyHandler(int(*handler)(void*, int))
241 sqlite3_busy_handler(m_db, handler, NULL);
243 LOG(SQLDatabase, "Busy handler set on non-open database");
246 bool SQLiteDatabase::executeCommand(const String& sql)
248 return SQLiteStatement(*this, sql).executeCommand();
251 bool SQLiteDatabase::returnsAtLeastOneResult(const String& sql)
253 return SQLiteStatement(*this, sql).returnsAtLeastOneResult();
256 bool SQLiteDatabase::tableExists(const String& tablename)
261 String statement = "SELECT name FROM sqlite_master WHERE type = 'table' AND name = '" + tablename + "';";
263 SQLiteStatement sql(*this, statement);
265 return sql.step() == SQLITE_ROW;
268 void SQLiteDatabase::clearAllTables()
270 String query = "SELECT name FROM sqlite_master WHERE type='table';";
271 Vector<String> tables;
272 if (!SQLiteStatement(*this, query).returnTextResults(0, tables)) {
273 LOG(SQLDatabase, "Unable to retrieve list of tables from database");
277 for (Vector<String>::iterator table = tables.begin(); table != tables.end(); ++table ) {
278 if (*table == "sqlite_sequence")
280 if (!executeCommand("DROP TABLE " + *table))
281 LOG(SQLDatabase, "Unable to drop table %s", (*table).ascii().data());
285 void SQLiteDatabase::runVacuumCommand()
287 if (!executeCommand("VACUUM;"))
288 LOG(SQLDatabase, "Unable to vacuum database - %s", lastErrorMsg());
291 void SQLiteDatabase::runIncrementalVacuumCommand()
293 MutexLocker locker(m_authorizerLock);
294 enableAuthorizer(false);
296 if (!executeCommand("PRAGMA incremental_vacuum"))
297 LOG(SQLDatabase, "Unable to run incremental vacuum - %s", lastErrorMsg());
299 enableAuthorizer(true);
302 int64_t SQLiteDatabase::lastInsertRowID()
306 return sqlite3_last_insert_rowid(m_db);
309 int SQLiteDatabase::lastChanges()
313 return sqlite3_changes(m_db);
316 int SQLiteDatabase::lastError()
318 return m_db ? sqlite3_errcode(m_db) : SQLITE_ERROR;
321 const char* SQLiteDatabase::lastErrorMsg()
323 return sqlite3_errmsg(m_db);
327 void SQLiteDatabase::disableThreadingChecks()
329 // This doesn't guarantee that SQList was compiled with -DTHREADSAFE, or that you haven't turned off the mutexes.
330 #if SQLITE_VERSION_NUMBER >= 3003001
333 ASSERT(0); // Your SQLite doesn't support sharing handles across threads.
338 int SQLiteDatabase::authorizerFunction(void* userData, int actionCode, const char* parameter1, const char* parameter2, const char* /*databaseName*/, const char* /*trigger_or_view*/)
340 DatabaseAuthorizer* auth = static_cast<DatabaseAuthorizer*>(userData);
343 switch (actionCode) {
344 case SQLITE_CREATE_INDEX:
345 return auth->createIndex(parameter1, parameter2);
346 case SQLITE_CREATE_TABLE:
347 return auth->createTable(parameter1);
348 case SQLITE_CREATE_TEMP_INDEX:
349 return auth->createTempIndex(parameter1, parameter2);
350 case SQLITE_CREATE_TEMP_TABLE:
351 return auth->createTempTable(parameter1);
352 case SQLITE_CREATE_TEMP_TRIGGER:
353 return auth->createTempTrigger(parameter1, parameter2);
354 case SQLITE_CREATE_TEMP_VIEW:
355 return auth->createTempView(parameter1);
356 case SQLITE_CREATE_TRIGGER:
357 return auth->createTrigger(parameter1, parameter2);
358 case SQLITE_CREATE_VIEW:
359 return auth->createView(parameter1);
361 return auth->allowDelete(parameter1);
362 case SQLITE_DROP_INDEX:
363 return auth->dropIndex(parameter1, parameter2);
364 case SQLITE_DROP_TABLE:
365 return auth->dropTable(parameter1);
366 case SQLITE_DROP_TEMP_INDEX:
367 return auth->dropTempIndex(parameter1, parameter2);
368 case SQLITE_DROP_TEMP_TABLE:
369 return auth->dropTempTable(parameter1);
370 case SQLITE_DROP_TEMP_TRIGGER:
371 return auth->dropTempTrigger(parameter1, parameter2);
372 case SQLITE_DROP_TEMP_VIEW:
373 return auth->dropTempView(parameter1);
374 case SQLITE_DROP_TRIGGER:
375 return auth->dropTrigger(parameter1, parameter2);
376 case SQLITE_DROP_VIEW:
377 return auth->dropView(parameter1);
379 return auth->allowInsert(parameter1);
381 return auth->allowPragma(parameter1, parameter2);
383 return auth->allowRead(parameter1, parameter2);
385 return auth->allowSelect();
386 case SQLITE_TRANSACTION:
387 return auth->allowTransaction();
389 return auth->allowUpdate(parameter1, parameter2);
391 return auth->allowAttach(parameter1);
393 return auth->allowDetach(parameter1);
394 case SQLITE_ALTER_TABLE:
395 return auth->allowAlterTable(parameter1, parameter2);
397 return auth->allowReindex(parameter1);
398 #if SQLITE_VERSION_NUMBER >= 3003013
400 return auth->allowAnalyze(parameter1);
401 case SQLITE_CREATE_VTABLE:
402 return auth->createVTable(parameter1, parameter2);
403 case SQLITE_DROP_VTABLE:
404 return auth->dropVTable(parameter1, parameter2);
405 case SQLITE_FUNCTION:
406 return auth->allowFunction(parameter2);
409 ASSERT_NOT_REACHED();
414 void SQLiteDatabase::setAuthorizer(PassRefPtr<DatabaseAuthorizer> auth)
417 LOG_ERROR("Attempt to set an authorizer on a non-open SQL database");
418 ASSERT_NOT_REACHED();
422 MutexLocker locker(m_authorizerLock);
426 enableAuthorizer(true);
429 void SQLiteDatabase::enableAuthorizer(bool enable)
431 if (m_authorizer && enable)
432 sqlite3_set_authorizer(m_db, SQLiteDatabase::authorizerFunction, m_authorizer.get());
434 sqlite3_set_authorizer(m_db, NULL, 0);
437 bool SQLiteDatabase::isAutoCommitOn() const
439 return sqlite3_get_autocommit(m_db);
442 bool SQLiteDatabase::turnOnIncrementalAutoVacuum()
444 SQLiteStatement statement(*this, "PRAGMA auto_vacuum");
445 int autoVacuumMode = statement.getColumnInt(0);
446 int error = lastError();
448 // Check if we got an error while trying to get the value of the auto_vacuum flag.
449 // If we got a SQLITE_BUSY error, then there's probably another transaction in
450 // progress on this database. In this case, keep the current value of the
451 // auto_vacuum flag and try to set it to INCREMENTAL the next time we open this
452 // database. If the error is not SQLITE_BUSY, then we probably ran into a more
453 // serious problem and should return false (to log an error message).
454 if (error != SQLITE_ROW)
457 switch (autoVacuumMode) {
458 case AutoVacuumIncremental:
461 return executeCommand("PRAGMA auto_vacuum = 2");
464 if (!executeCommand("PRAGMA auto_vacuum = 2"))
468 return (error == SQLITE_OK);
472 } // namespace WebCore
474 #endif // ENABLE(DATABASE)