blob: 1de3a4118992d80bdb5b0cd6a4e0ac70889451e1 [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
Mike Lockwoodb14e5882010-06-29 18:11:52 -040017#define LOG_TAG "SqliteDatabase"
18
19#include "MtpDebug.h"
Mike Lockwood16864ba2010-05-11 17:16:59 -040020#include "SqliteDatabase.h"
21#include "SqliteStatement.h"
22
23#include <stdio.h>
24#include <sqlite3.h>
25
Mike Lockwood7850ef92010-05-14 10:10:36 -040026namespace android {
27
Mike Lockwood16864ba2010-05-11 17:16:59 -040028SqliteDatabase::SqliteDatabase()
29 : mDatabaseHandle(NULL)
30{
31}
32
33SqliteDatabase::~SqliteDatabase() {
34 close();
35}
36
37bool SqliteDatabase::open(const char* path, bool create) {
38 int flags = SQLITE_OPEN_READWRITE;
39 if (create) flags |= SQLITE_OPEN_CREATE;
40 // SQLITE_OPEN_NOMUTEX?
41 int ret = sqlite3_open_v2(path, &mDatabaseHandle, flags, NULL);
42 if (ret) {
Mike Lockwoodb14e5882010-06-29 18:11:52 -040043 LOGE("could not open database\n");
Mike Lockwood16864ba2010-05-11 17:16:59 -040044 return false;
45 }
46 return true;
47}
48
49void SqliteDatabase::close() {
50 if (mDatabaseHandle) {
51 sqlite3_close(mDatabaseHandle);
52 mDatabaseHandle = NULL;
53 }
54}
55
56bool SqliteDatabase::exec(const char* sql) {
57 return (sqlite3_exec(mDatabaseHandle, sql, NULL, NULL, NULL) == 0);
58}
59
60int SqliteDatabase::lastInsertedRow() {
61 return sqlite3_last_insert_rowid(mDatabaseHandle);
62}
63
64void SqliteDatabase::beginTransaction() {
65 exec("BEGIN TRANSACTION");
66}
67
68void SqliteDatabase::commitTransaction() {
69 exec("COMMIT TRANSACTION");
70}
71
72void SqliteDatabase::rollbackTransaction() {
73 exec("ROLLBACK TRANSACTION");
74}
75
76int SqliteDatabase::getVersion() {
77 SqliteStatement stmt(this);
78 stmt.prepare("PRAGMA user_version;");
79 stmt.step();
80 return stmt.getColumnInt(0);
81}
82void SqliteDatabase::setVersion(int version) {
83 char buffer[40];
84 snprintf(buffer, sizeof(buffer), "PRAGMA user_version = %d", version);
85 exec(buffer);
86}
Mike Lockwood7850ef92010-05-14 10:10:36 -040087
88} // namespace android