Overview
The database module provides SQLAlchemy-based data persistence with async support. It uses a repository pattern throughdb_service.py to abstract database operations.
Stack:
- SQLAlchemy 2.0 (async)
- PostgreSQL (via asyncpg)
- Declarative models
Architecture
Module Structure
Initialization Flow
database.py
Location:data/database.py
Core database engine and session management.
Global Variables
initialize_database_components()
Location: data/database.py:17
CRITICAL: Must be called before any database operations.
init_db()
Location: data/database.py:51
Creates all database tables.
RuntimeError if initialize_database_components() not called
get_session()
Location: data/database.py:71
Creates a database session (used internally by db_service).
AsyncSession instance
Models
Location:data/models/
Users Model
Location:data/models/users.py
Stores user/chat information and settings.
user_id- Telegram user/chat ID (primary key)registered_at- Registration timestamplang- Language code (en, ru, es, etc.)link- Referral link parameterfile_mode- Send as file (True) or media (False)ad_count- Number of downloads since last adad_cooldown- Timestamp when ad cooldown expires
Video Model
Location:data/models/video.py
Records video/slideshow downloads for analytics.
pk_id- Auto-incrementing primary keyuser_id- Foreign key to Users.user_iddownloaded_at- Download timestampvideo_link- TikTok/Instagram URLis_images- True for slideshows, False for videosis_processed- True if images were converted/optimizedis_inline- True if downloaded via inline query
Music Model
Location:data/models/music.py
Records music/audio extractions.
pk_id- Auto-incrementing primary keyuser_id- Foreign key to Users.user_iddownloaded_at- Download timestampvideo_id- TikTok video ID
db_service.py
Location:data/db_service.py
Repository pattern implementation - all database operations go through these functions.
User Management
get_user()
Location: data/db_service.py:11
Retrieves user by ID.
Users object or None
create_user()
Location: data/db_service.py:18
Creates new user record.
user_id- Telegram user/chat IDlang- Language codelink- Optional referral link parameter
Users object
update_user_mode()
Location: data/db_service.py:34
Toggles file mode setting.
update_user_lang()
Location: data/db_service.py:159
Updates user language.
get_user_settings()
Location: data/db_service.py:133
Retrieves user language and file mode.
(lang, file_mode) tuple or None
Example:
Video/Download Tracking
add_video()
Location: data/db_service.py:143
Records video/slideshow download.
user_id- Telegram user/chat IDvideo_link- TikTok/Instagram URLis_images- True for slideshowsis_processed- True if images were convertedis_inline- True if inline query
add_music()
Location: data/db_service.py:152
Records music extraction.
Statistics
get_user_stats()
Location: data/db_service.py:41
Retrieves user statistics.
(user, videos_count, images_count) tuple
get_stats_by_period()
Location: data/db_service.py:112
Retrieves downloads within time period.
period- Time period in seconds (0 for all time)chat_type- Filter by chat type: ‘all’, ‘users’, ‘groups’
(downloaded_at, video_link) tuples
get_referral_stats()
Location: data/db_service.py:70
Top 10 referral links.
(link, count) tuples (top 10)
get_other_stats()
Location: data/db_service.py:83
Miscellaneous statistics.
(file_mode_count, top_langs, top_users) tuple
file_mode_count- Users with file mode enabledtop_langs-[(lang, count), ...]top_users-[(user_id, download_count), ...](top 10)
Advertisement Tracking
should_show_ad()
Location: data/db_service.py:197
Checks if ad should be shown to user.
True if ad should be shown
record_ad_show()
Location: data/db_service.py:175
Records ad display and resets counter.
increase_ad_count()
Location: data/db_service.py:186
Increments ad counter.
Admin Functions
get_user_ids()
Location: data/db_service.py:166
Retrieves all user IDs (for broadcasts).
only_positive- If True, exclude groups (negative IDs)
get_user_videos()
Location: data/db_service.py:63
Retrieves all videos for a user.
(downloaded_at, video_link) tuples
Usage Examples
User Registration Flow
Download Tracking
Advertisement Logic
Best Practices
- Always call
initialize_database_components()before any DB operations - Use
db_servicefunctions - never query models directly - Handle
Nonereturns - users may not exist - Use transactions -
db_servicefunctions auto-commit - Log database errors - don’t let DB issues crash handlers
- Use Unix timestamps - consistent timezone handling
- Validate user_id - check for existence before operations
- Clean up sessions -
async withhandles this automatically

