blob: 5a70dfe753b47d061fd1b95649a1d796fe8d0e7c [file] [log] [blame]
Mike Lockwood56118b52010-05-11 17:16:59 -04001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "SqliteDatabase.h"
18#include "SqliteStatement.h"
19
20#include <stdio.h>
21#include <sqlite3.h>
22
23SqliteDatabase::SqliteDatabase()
24 : mDatabaseHandle(NULL)
25{
26}
27
28SqliteDatabase::~SqliteDatabase() {
29 close();
30}
31
32bool SqliteDatabase::open(const char* path, bool create) {
33 int flags = SQLITE_OPEN_READWRITE;
34 if (create) flags |= SQLITE_OPEN_CREATE;
35 // SQLITE_OPEN_NOMUTEX?
36 int ret = sqlite3_open_v2(path, &mDatabaseHandle, flags, NULL);
37 if (ret) {
38 fprintf(stderr, "could not open database\n");
39 return false;
40 }
41 return true;
42}
43
44void SqliteDatabase::close() {
45 if (mDatabaseHandle) {
46 sqlite3_close(mDatabaseHandle);
47 mDatabaseHandle = NULL;
48 }
49}
50
51bool SqliteDatabase::exec(const char* sql) {
52 return (sqlite3_exec(mDatabaseHandle, sql, NULL, NULL, NULL) == 0);
53}
54
55int SqliteDatabase::lastInsertedRow() {
56 return sqlite3_last_insert_rowid(mDatabaseHandle);
57}
58
59void SqliteDatabase::beginTransaction() {
60 exec("BEGIN TRANSACTION");
61}
62
63void SqliteDatabase::commitTransaction() {
64 exec("COMMIT TRANSACTION");
65}
66
67void SqliteDatabase::rollbackTransaction() {
68 exec("ROLLBACK TRANSACTION");
69}
70
71int SqliteDatabase::getVersion() {
72 SqliteStatement stmt(this);
73 stmt.prepare("PRAGMA user_version;");
74 stmt.step();
75 return stmt.getColumnInt(0);
76}
77void SqliteDatabase::setVersion(int version) {
78 char buffer[40];
79 snprintf(buffer, sizeof(buffer), "PRAGMA user_version = %d", version);
80 exec(buffer);
81}