# 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))
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://pbmodular-docs.gitbook.io/eng-docs/extended-usage/database-usage.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
