SQLite Utilities (ligo.skymap.util.sqlite)

Tools for reading and writing SQLite databases.

ligo.skymap.util.sqlite.get_filename(connection)[source] [edit on github]

Get the name of the file associated with an SQLite connection.

Parameters:
connectionsqlite3.Connection

The database connection

Returns:
str

The name of the file that contains the SQLite database

Raises:
RuntimeError

If more than one database is attached to the connection

Examples

>>> import tempfile
>>> import os
>>> with tempfile.TemporaryDirectory() as d:
...     with sqlite3.connect(os.path.join(d, 'test.sqlite')) as db:
...         print(get_filename(db))
...
/.../test.sqlite
>>> with tempfile.TemporaryDirectory() as d:
...     with sqlite3.connect(os.path.join(d, 'test1.sqlite')) as db1, \
...          sqlite3.connect(os.path.join(d, 'test2.sqlite')) as db2:
...         filename = get_filename(db1)
...         db2.execute('ATTACH DATABASE "{}" AS db2'.format(filename))
...         print(get_filename(db2))
...
Traceback (most recent call last):
  ...
RuntimeError: Expected exactly one attached database
ligo.skymap.util.sqlite.open(string, mode)[source] [edit on github]

Open an SQLite database with an open-style mode flag.

Parameters:
stringstr

Path of the SQLite database file

mode{‘r’, ‘w’, ‘a’}

Access mode: read only, clobber and overwrite, or modify in place.

Returns:
connectionsqlite3.Connection
Raises:
ValueError

If the filename is invalid (e.g. /dev/stdin), or if the requested mode is invalid

OSError

If the database could not be opened in the specified mode

Examples

>>> import tempfile
>>> import os
>>> with tempfile.TemporaryDirectory() as d:
...     open(os.path.join(d, 'test.sqlite'), 'w')
...
<sqlite3.Connection object at 0x...>
>>> with tempfile.TemporaryDirectory() as d:
...     open(os.path.join(d, 'test.sqlite'), 'r')
...
Traceback (most recent call last):
  ...
OSError: Failed to open database ...
>>> open('/dev/stdin', 'r')
Traceback (most recent call last):
  ...
ValueError: Cannot open stdin/stdout as an SQLite database
>>> open('test.sqlite', 'x')
Traceback (most recent call last):
  ...
ValueError: Invalid mode "x". Must be one of "arw".