summaryrefslogtreecommitdiffstats
path: root/mobile/android/base/java/org/mozilla/gecko/db/SharedBrowserDatabaseProvider.java
blob: 8be18c089e5dff61a75c081c942d3bfe0a8cd995 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

package org.mozilla.gecko.db;

import org.mozilla.gecko.AppConstants.Versions;
import org.mozilla.gecko.db.BrowserContract.CommonColumns;
import org.mozilla.gecko.db.BrowserContract.SyncColumns;
import org.mozilla.gecko.db.PerProfileDatabases.DatabaseHelperFactory;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.util.Log;

/**
 * A ContentProvider subclass that provides per-profile browser.db access
 * that can be safely shared between multiple providers.
 *
 * If multiple ContentProvider classes wish to share a database, it's
 * vitally important that they use the same SQLiteOpenHelpers for access.
 *
 * Failure to do so can cause accidental concurrent writes, with the result
 * being unexpected SQLITE_BUSY errors.
 *
 * This class provides a static {@link PerProfileDatabases} instance, lazily
 * initialized within {@link SharedBrowserDatabaseProvider#onCreate()}.
 */
public abstract class SharedBrowserDatabaseProvider extends AbstractPerProfileDatabaseProvider {
    private static final String LOGTAG = SharedBrowserDatabaseProvider.class.getSimpleName();

    private static PerProfileDatabases<BrowserDatabaseHelper> databases;

    @Override
    protected PerProfileDatabases<BrowserDatabaseHelper> getDatabases() {
        return databases;
    }

    @Override
    public void shutdown() {
        synchronized (SharedBrowserDatabaseProvider.class) {
            databases.shutdown();
            databases = null;
        }
    }

    @Override
    public boolean onCreate() {
        // If necessary, do the shared DB work.
        synchronized (SharedBrowserDatabaseProvider.class) {
            if (databases != null) {
                return true;
            }

            final DatabaseHelperFactory<BrowserDatabaseHelper> helperFactory = new DatabaseHelperFactory<BrowserDatabaseHelper>() {
                @Override
                public BrowserDatabaseHelper makeDatabaseHelper(Context context, String databasePath) {
                    final BrowserDatabaseHelper helper = new BrowserDatabaseHelper(context, databasePath);
                    if (Versions.feature16Plus) {
                        helper.setWriteAheadLoggingEnabled(true);
                    }
                    return helper;
                }
            };

            databases = new PerProfileDatabases<BrowserDatabaseHelper>(getContext(), BrowserDatabaseHelper.DATABASE_NAME, helperFactory);
        }

        return true;
    }

    /**
     * Clean up some deleted records from the specified table.
     *
     * If called in an existing transaction, it is the caller's responsibility
     * to ensure that the transaction is already upgraded to a writer, because
     * this method issues a read followed by a write, and thus is potentially
     * vulnerable to an unhandled SQLITE_BUSY failure during the upgrade.
     *
     * If not called in an existing transaction, no new explicit transaction
     * will be begun.
     */
    protected void cleanUpSomeDeletedRecords(Uri fromUri, String tableName) {
        Log.d(LOGTAG, "Cleaning up deleted records from " + tableName);

        // We clean up records marked as deleted that are older than a
        // predefined max age. It's important not be too greedy here and
        // remove only a few old deleted records at a time.

        // we cleanup records marked as deleted that are older than a
        // predefined max age. It's important not be too greedy here and
        // remove only a few old deleted records at a time.

        // Maximum age of deleted records to be cleaned up (20 days in ms)
        final long MAX_AGE_OF_DELETED_RECORDS = 86400000 * 20;

        // Number of records marked as deleted to be removed
        final long DELETED_RECORDS_PURGE_LIMIT = 5;

        // Android SQLite doesn't have LIMIT on DELETE. Instead, query for the
        // IDs of matching rows, then delete them in one go.
        final long now = System.currentTimeMillis();
        final String selection = getDeletedItemSelection(now - MAX_AGE_OF_DELETED_RECORDS);

        final String profile = fromUri.getQueryParameter(BrowserContract.PARAM_PROFILE);
        final SQLiteDatabase db = getWritableDatabaseForProfile(profile, isTest(fromUri));
        final String limit = Long.toString(DELETED_RECORDS_PURGE_LIMIT, 10);
        final Cursor cursor = db.query(tableName, new String[] { CommonColumns._ID }, selection, null, null, null, null, limit);
        final String inClause;
        try {
            inClause = DBUtils.computeSQLInClauseFromLongs(cursor, CommonColumns._ID);
        } finally {
            cursor.close();
        }

        db.delete(tableName, inClause, null);
    }

    // Override this, or override cleanUpSomeDeletedRecords.
    protected String getDeletedItemSelection(long earlierThan) {
        if (earlierThan == -1L) {
            return SyncColumns.IS_DELETED + " = 1";
        }
        return SyncColumns.IS_DELETED + " = 1 AND " + SyncColumns.DATE_MODIFIED + " <= " + earlierThan;
    }
}