# Database usage

**The bot uses SQLAlchemy ORM in asynchronous mode to work with the database.** [**Documentation.**](https://docs.sqlalchemy.org/en/20/)

**Before you can use the database, you must add the `use_db` or `require_db` permission to the `info.yaml` file!**

To use the database, the module must declare models according to SQLAlchemy documentation and later specify the metadata object in the `db_meta` property method:

```
# db.py
from sqlalchemy.orm import Mapped, mapped_column, DeclarativeBase

class Base(DeclarativeBase):
    pass
...

# main.py
from .db import Base
...
# Оверрайд метода db_meta
@property
def db_meta(self):
    return Base.metadata
```

After that, if the database initialization is successful, a Database object appears in the db attribute of the module object, containing the attributes

* `engine` - object of AsyncEngine type (SQLAlchemy)
* `session_maker` - object of `async_sessionmaker`type (SQLAlchemy)

A different database is used for each module. By default SQLite is used, but this can be changed in the bot config (not yet fully supported)

You can then operate the database in the same way as in the SQLAlchemy documentation, using the `engine` and `session_maker` objects. Example:

```
async with self.db.session_maker() as session:
    result = await session.scalar(select(User))
```
