How to compute a hash of a sqlite database file without causing harm
<p>I have a function like the following that I want to use to compute the hash of a sqlite database file, in order to compare it to the last backup I made to detect any changes.</p>

<pre>
def get_hash(file_path):
    # http://stackoverflow.com/a/3431838/1391717
    hash_sha1 = hashlib.sha1
    with open(file_path, "rb") as f:
        for chunk in iter(lambda: f.read(4096), b""):
            hash_sha1.update(chunk)

    return hash_sha1.hexdigest()
</pre>

<p>I plan on locking the database, so no one can write to it while I'm computing the hash. Is it possible for me to cause any harm while doing this?</p>

<pre>
// http://codereview.stackexchange.com/questions/78643/create-sqlite-backups
connection = sqlite3.connect(database_file)
cursor = connection.cursor()
cursor.execute("begin immediate")

db_hash = get_hash(args.database)
</pre>

<p>The sqlite3 database files, can and may be read by many different readers at the same time. There is no problem with concurrency in that respect with sqlite3. The problems which is native to sqlite3 concerns writing to the file, only one writer is allowed. </p>

<p>So if you only read your fine. </p>

<p>If you are planning to lock the database and succeed with that, while you compute the hash, you become a writer with exclusive access. </p>

python sqlite sqlite3