SQLite¶
Some helper functions for aiosqlite
.
- class ezcord.sql.DBHandler(path, *, connection=None, auto_connect=False, auto_setup=True, conv_json=False, foreign_keys=False, **kwargs)[source]¶
A class that provides helper methods for SQLite databases.
- Parameters:
path (
str
) – The path to the database file.connection (
Connection
|None
) – A connection to the database. If not provided, a new connection will be created. Ifauto_connect
isTrue
, this will be ignored.auto_connect (
bool
) –Automatically create a new connection that will be used for all queries. This is used by
start()
.When used without a context manager, this must be closed with
close()
or by usingend=True
inexec()
.auto_setup (
bool
) – Whether to callsetup()
when the first instance of this class is created. Defaults toTrue
. This is called in theon_ready
event of the bot.conv_json (
bool
) – Whether to auto-convert JSON. Defaults toFalse
.foreign_keys (
bool
) – Whether to enforce foreign keys. Defaults toFalse
.**kwargs – Keyword arguments for
aiosqlite.connect()
.
Example
You can use this class with an asynchronous context manager:
async with DBHandler("ezcord.db") as db: await db.exec("CREATE TABLE IF NOT EXISTS vip (id INTEGER PRIMARY KEY, name TEXT)") await db.exec("INSERT INTO vip (name) VALUES (?)", "Timo")
- start(*, conv_json=None, foreign_keys=None, **kwargs)[source]¶
Opens a new connection with the current DB settings. Additional settings can be provided as keyword arguments.
This should be used as an asynchronous context manager. The connection will commit automatically after exiting the context manager.
- Parameters:
foreign_keys (
bool
|None
) – Whether to enforce foreign keys.**kwargs – Additional keyword arguments for
aiosqlite.connect()
.
- Return type:
Example
class VipDB(DBHandler): def __init__(self): super().__init__("ezcord.db") async def setup(self): async with self.start() as db: await db.exec( "CREATE TABLE IF NOT EXISTS vip (id INTEGER PRIMARY KEY, name TEXT)" ) await db.exec("INSERT INTO vip (name) VALUES (?)", "Timo")
- async close()[source]¶
Commits and closes the current connection to the database.
This is called automatically when using
start()
as a context manager.
- async one(sql, *args, fill=False, **kwargs)[source]¶
Returns one result row. If no row is found,
None
is returned.If the query returns only one column, the value of that column is returned.
- Parameters:
- Return type:
The result row or
None
. A result row is either a tuple or a single value.
- async all(sql, *args, **kwargs)[source]¶
Returns all result rows.
If the query returns only one column, the values of that column are returned.
- Parameters:
sql (
str
) – The SQL query to execute.*args – Arguments for the query.
**kwargs – Keyword arguments for the connection.
- Return type:
A list of result rows. A result row is either a tuple or a single value.