Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Do not create tables when in read-only mode #128

Merged
merged 3 commits into from
Jan 9, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions sqlitedict.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,10 +168,14 @@ def __init__(self, filename=None, tablename='unnamed', flag='c',
self.decode = decode

logger.info("opening Sqlite table %r in %r" % (tablename, filename))
MAKE_TABLE = 'CREATE TABLE IF NOT EXISTS "%s" (key TEXT PRIMARY KEY, value BLOB)' % self.tablename
self.conn = self._new_conn()
self.conn.execute(MAKE_TABLE)
self.conn.commit()
if self.flag == 'r':
piskvorky marked this conversation as resolved.
Show resolved Hide resolved
if not self.tablename in SqliteDict.get_tablenames(self.filename):
raise RuntimeError('Refusing to create a new table "%s" in read-only DB mode' % tablename)
else:
MAKE_TABLE = 'CREATE TABLE IF NOT EXISTS "%s" (key TEXT PRIMARY KEY, value BLOB)' % self.tablename
self.conn.execute(MAKE_TABLE)
self.conn.commit()
if flag == 'w':
self.clear()

Expand Down
20 changes: 20 additions & 0 deletions tests/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,26 @@ def attempt_terminate():
with self.assertRaises(RuntimeError):
func()

def test_readonly_table(self):
"""
Read-only access on a non-existant tablename should raise RuntimeError,
and not create a new (empty) table.
"""
fname = norm_file('tests/db/sqlitedict-override-test.sqlite')
dummy_tablename = 'table404'
orig_db = SqliteDict(filename=fname)
orig_db['key'] = 'value'
orig_db['key_two'] = 2
orig_db.commit()
orig_db.close()

self.assertFalse(dummy_tablename in SqliteDict.get_tablenames(fname))

with self.assertRaises(RuntimeError):
SqliteDict(filename=fname, tablename=dummy_tablename, flag='r')

self.assertFalse(dummy_tablename in SqliteDict.get_tablenames(fname))

def test_irregular_tablenames(self):
"""Irregular table names need to be quoted"""
def __test_irregular_tablenames(tablename):
Expand Down