blob: e1156301406a419584b64b55a1f655f58b4b7578 [file] [log] [blame]
Mike Lockwood16864ba2010-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
Mike Lockwood7850ef92010-05-14 10:10:36 -040023namespace android {
24
Mike Lockwood16864ba2010-05-11 17:16:59 -040025SqliteDatabase::SqliteDatabase()
26 : mDatabaseHandle(NULL)
27{
28}
29
30SqliteDatabase::~SqliteDatabase() {
31 close();
32}
33
34bool SqliteDatabase::open(const char* path, bool create) {
35 int flags = SQLITE_OPEN_READWRITE;
36 if (create) flags |= SQLITE_OPEN_CREATE;
37 // SQLITE_OPEN_NOMUTEX?
38 int ret = sqlite3_open_v2(path, &mDatabaseHandle, flags, NULL);
39 if (ret) {
40 fprintf(stderr, "could not open database\n");
41 return false;
42 }
43 return true;
44}
45
46void SqliteDatabase::close() {
47 if (mDatabaseHandle) {
48 sqlite3_close(mDatabaseHandle);
49 mDatabaseHandle = NULL;
50 }
51}
52
53bool SqliteDatabase::exec(const char* sql) {
54 return (sqlite3_exec(mDatabaseHandle, sql, NULL, NULL, NULL) == 0);
55}
56
57int SqliteDatabase::lastInsertedRow() {
58 return sqlite3_last_insert_rowid(mDatabaseHandle);
59}
60
61void SqliteDatabase::beginTransaction() {
62 exec("BEGIN TRANSACTION");
63}
64
65void SqliteDatabase::commitTransaction() {
66 exec("COMMIT TRANSACTION");
67}
68
69void SqliteDatabase::rollbackTransaction() {
70 exec("ROLLBACK TRANSACTION");
71}
72
73int SqliteDatabase::getVersion() {
74 SqliteStatement stmt(this);
75 stmt.prepare("PRAGMA user_version;");
76 stmt.step();
77 return stmt.getColumnInt(0);
78}
79void SqliteDatabase::setVersion(int version) {
80 char buffer[40];
81 snprintf(buffer, sizeof(buffer), "PRAGMA user_version = %d", version);
82 exec(buffer);
83}
Mike Lockwood7850ef92010-05-14 10:10:36 -040084
85} // namespace android