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 "SQLiteAuthorizer.h"
32 #include "SQLiteStatement.h"
38 const int SQLResultDone = SQLITE_DONE;
39 const int SQLResultError = SQLITE_ERROR;
40 const int SQLResultOk = SQLITE_OK;
41 const int SQLResultRow = SQLITE_ROW;
42 const int SQLResultSchema = SQLITE_SCHEMA;
43 const int SQLResultFull = SQLITE_FULL;
46 SQLiteDatabase::SQLiteDatabase()
49 , m_transactionInProgress(false)
54 SQLiteDatabase::~SQLiteDatabase()
59 bool SQLiteDatabase::open(const String& filename)
63 // SQLite expects a null terminator on its UTF-16 strings.
64 String path = filename;
65 m_lastError = sqlite3_open16(path.charactersWithNullTermination(), &m_db);
66 if (m_lastError != SQLITE_OK) {
67 LOG_ERROR("SQLite database failed to load from %s\nCause - %s", filename.ascii().data(),
68 sqlite3_errmsg(m_db));
75 m_openingThread = currentThread();
77 if (!SQLiteStatement(*this, "PRAGMA temp_store = MEMORY;").executeCommand())
78 LOG_ERROR("SQLite database could not set temp_store to memory");
83 void SQLiteDatabase::close()
93 void SQLiteDatabase::setFullsync(bool fsync)
96 executeCommand("PRAGMA fullfsync = 1;");
98 executeCommand("PRAGMA fullfsync = 0;");
101 int64_t SQLiteDatabase::maximumSize()
103 MutexLocker locker(m_authorizerLock);
104 enableAuthorizer(false);
106 SQLiteStatement statement(*this, "PRAGMA max_page_count");
107 int64_t size = statement.getColumnInt64(0) * pageSize();
109 enableAuthorizer(true);
113 void SQLiteDatabase::setMaximumSize(int64_t size)
118 int currentPageSize = pageSize();
120 ASSERT(currentPageSize);
121 int64_t newMaxPageCount = currentPageSize ? size / currentPageSize : 0;
123 MutexLocker locker(m_authorizerLock);
124 enableAuthorizer(false);
126 SQLiteStatement statement(*this, "PRAGMA max_page_count = " + String::number(newMaxPageCount));
128 if (statement.step() != SQLResultRow)
129 LOG_ERROR("Failed to set maximum size of database to %lli bytes", size);
131 enableAuthorizer(true);
135 int SQLiteDatabase::pageSize()
137 // Since the page size of a database is locked in at creation and therefore cannot be dynamic,
138 // we can cache the value for future use
139 if (m_pageSize == -1) {
140 MutexLocker locker(m_authorizerLock);
141 enableAuthorizer(false);
143 SQLiteStatement statement(*this, "PRAGMA page_size");
144 m_pageSize = statement.getColumnInt(0);
146 enableAuthorizer(true);
152 void SQLiteDatabase::setSynchronous(SynchronousPragma sync)
154 executeCommand(String::format("PRAGMA synchronous = %i", sync));
157 void SQLiteDatabase::setBusyTimeout(int ms)
160 sqlite3_busy_timeout(m_db, ms);
162 LOG(SQLDatabase, "BusyTimeout set on non-open database");
165 void SQLiteDatabase::setBusyHandler(int(*handler)(void*, int))
168 sqlite3_busy_handler(m_db, handler, NULL);
170 LOG(SQLDatabase, "Busy handler set on non-open database");
173 bool SQLiteDatabase::executeCommand(const String& sql)
175 return SQLiteStatement(*this, sql).executeCommand();
178 bool SQLiteDatabase::returnsAtLeastOneResult(const String& sql)
180 return SQLiteStatement(*this, sql).returnsAtLeastOneResult();
183 bool SQLiteDatabase::tableExists(const String& tablename)
188 String statement = "SELECT name FROM sqlite_master WHERE type = 'table' AND name = '" + tablename + "';";
190 SQLiteStatement sql(*this, statement);
192 return sql.step() == SQLITE_ROW;
195 void SQLiteDatabase::clearAllTables()
197 String query = "SELECT name FROM sqlite_master WHERE type='table';";
198 Vector<String> tables;
199 if (!SQLiteStatement(*this, query).returnTextResults(0, tables)) {
200 LOG(SQLDatabase, "Unable to retrieve list of tables from database");
204 for (Vector<String>::iterator table = tables.begin(); table != tables.end(); ++table ) {
205 if (*table == "sqlite_sequence")
207 if (!executeCommand("DROP TABLE " + *table))
208 LOG(SQLDatabase, "Unable to drop table %s", (*table).ascii().data());
212 void SQLiteDatabase::runVacuumCommand()
214 if (!executeCommand("VACUUM;"))
215 LOG(SQLDatabase, "Unable to vacuum database - %s", lastErrorMsg());
218 int64_t SQLiteDatabase::lastInsertRowID()
222 return sqlite3_last_insert_rowid(m_db);
225 int SQLiteDatabase::lastChanges()
229 return sqlite3_changes(m_db);
232 int SQLiteDatabase::lastError()
234 return m_db ? sqlite3_errcode(m_db) : SQLITE_ERROR;
237 const char* SQLiteDatabase::lastErrorMsg()
239 return sqlite3_errmsg(m_db);
242 int SQLiteDatabase::authorizerFunction(void* userData, int actionCode, const char* parameter1, const char* parameter2, const char* /*databaseName*/, const char* /*trigger_or_view*/)
244 SQLiteAuthorizer* auth = static_cast<SQLiteAuthorizer*>(userData);
247 switch (actionCode) {
248 case SQLITE_CREATE_INDEX:
249 return auth->createIndex(parameter1, parameter2);
250 case SQLITE_CREATE_TABLE:
251 return auth->createTable(parameter1);
252 case SQLITE_CREATE_TEMP_INDEX:
253 return auth->createTempIndex(parameter1, parameter2);
254 case SQLITE_CREATE_TEMP_TABLE:
255 return auth->createTempTable(parameter1);
256 case SQLITE_CREATE_TEMP_TRIGGER:
257 return auth->createTempTrigger(parameter1, parameter2);
258 case SQLITE_CREATE_TEMP_VIEW:
259 return auth->createTempView(parameter1);
260 case SQLITE_CREATE_TRIGGER:
261 return auth->createTrigger(parameter1, parameter2);
262 case SQLITE_CREATE_VIEW:
263 return auth->createView(parameter1);
265 return auth->allowDelete(parameter1);
266 case SQLITE_DROP_INDEX:
267 return auth->dropIndex(parameter1, parameter2);
268 case SQLITE_DROP_TABLE:
269 return auth->dropTable(parameter1);
270 case SQLITE_DROP_TEMP_INDEX:
271 return auth->dropTempIndex(parameter1, parameter2);
272 case SQLITE_DROP_TEMP_TABLE:
273 return auth->dropTempTable(parameter1);
274 case SQLITE_DROP_TEMP_TRIGGER:
275 return auth->dropTempTrigger(parameter1, parameter2);
276 case SQLITE_DROP_TEMP_VIEW:
277 return auth->dropTempView(parameter1);
278 case SQLITE_DROP_TRIGGER:
279 return auth->dropTrigger(parameter1, parameter2);
280 case SQLITE_DROP_VIEW:
281 return auth->dropView(parameter1);
283 return auth->allowInsert(parameter1);
285 return auth->allowPragma(parameter1, parameter2);
287 return auth->allowRead(parameter1, parameter2);
289 return auth->allowSelect();
290 case SQLITE_TRANSACTION:
291 return auth->allowTransaction();
293 return auth->allowUpdate(parameter1, parameter2);
295 return auth->allowAttach(parameter1);
297 return auth->allowDetach(parameter1);
298 case SQLITE_ALTER_TABLE:
299 return auth->allowAlterTable(parameter1, parameter2);
301 return auth->allowReindex(parameter1);
302 #if SQLITE_VERSION_NUMBER >= 3003013
304 return auth->allowAnalyze(parameter1);
305 case SQLITE_CREATE_VTABLE:
306 return auth->createVTable(parameter1, parameter2);
307 case SQLITE_DROP_VTABLE:
308 return auth->dropVTable(parameter1, parameter2);
309 case SQLITE_FUNCTION:
310 return auth->allowFunction(parameter1);
313 ASSERT_NOT_REACHED();
318 void SQLiteDatabase::setAuthorizer(PassRefPtr<SQLiteAuthorizer> auth)
321 LOG_ERROR("Attempt to set an authorizer on a non-open SQL database");
322 ASSERT_NOT_REACHED();
326 MutexLocker locker(m_authorizerLock);
330 enableAuthorizer(true);
333 void SQLiteDatabase::enableAuthorizer(bool enable)
335 if (m_authorizer && enable)
336 sqlite3_set_authorizer(m_db, SQLiteDatabase::authorizerFunction, m_authorizer.get());
338 sqlite3_set_authorizer(m_db, NULL, 0);
341 void SQLiteDatabase::lock()
343 m_lockingMutex.lock();
346 void SQLiteDatabase::unlock()
348 m_lockingMutex.unlock();
351 } // namespace WebCore