Database
The Database module provides a simple and efficient way to interact with databases with read-only interfaces. It offers table management and query capabilities through a clean and intuitive API.
Overview
The DB module is implemented as a singleton, ensuring a single database connection throughout your application. It provides a clean and intuitive interface for database operations.
Features
Table Management
- List all tables in the database
- Get detailed table structure information
- View field properties and constraints
Data Query
- Flexible query options
- Field selection
- Conditional filtering
- Pagination support
- Sorting capabilities
Examples
Table Operations
// List all tables
const tables = await db.show();
console.log('Available tables:', tables.tables);
// Get table structure
const tableInfo = await db.describe('users');
console.log('Table fields:', tableInfo.fields);
Data Query
// Basic query
const result = await db.select('users', {
fields: ['id', 'name'],
where: { status: 'active' },
limit: 10,
offset: 0,
orderBy: 'id',
order: 'desc'
});
Best Practices
-
Query Optimization
- Select only needed fields
- Use appropriate limit and offset for pagination
- Add proper ordering for consistent results
- Use specific where conditions to filter data
- Implement proper error handling:
try {
const result = await db.select('users', {
where: { status: 'active' }
});
// ... use result
} catch (error) {
console.error('Error querying database:', error);
} -
Error Handling
- Always handle potential database errors
- Validate table names before queries
- Check field existence before using them in queries
-
Performance
- Use appropriate pagination for large datasets
- Optimize query conditions
- Cache frequently accessed data
- Monitor query performance
-
Data Validation
- Validate query parameters
Limitations
- The module currently supports read operations only
- Complex queries (joins, subqueries) are not supported
- No direct support for data modification operations