Skip to main content

DataSource

The DataSource manages your database connection and registers all models.

Basic Configuration

import { DataSource } from '@phrasecode/odata';

const dataSource = new DataSource({
dialect: 'postgres', // Database type: 'postgres' | 'mysql' | 'sqlite' | 'mariadb' | 'mssql' | 'oracle'
database: 'mydb', // Database name
username: 'user',
password: 'password',
host: 'localhost',
port: 5432,
pool: {
max: 5,
min: 0,
idle: 10000,
},
schema: 'public', // Database schema
ssl: true, // Enable SSL
models: [User, Order, Product], // Array of model classes
});

Configuration Options

Database Connection

OptionTypeDescription
dialectstringType of database: 'postgres', 'mysql', 'sqlite', 'mariadb', 'mssql', 'oracle'
databasestringName of the database
usernamestringDatabase username
passwordstringDatabase password
hoststringDatabase server hostname or IP
portnumberDatabase port number
schemastringDatabase schema name (optional)
sslbooleanEnable SSL connection (optional)
modelsarrayArray of Model classes to register

Connection Pool Configuration

Connection pooling is critical for production applications. It reuses database connections instead of creating new ones for each query.

OptionTypeDescriptionRecommended
maxnumberMaximum number of connections5-20
minnumberMinimum number of connections1-5
idlenumberMaximum time (ms) a connection can be idle10000
acquirenumberMaximum time (ms) to wait for a connection30000
evictnumberInterval (ms) to check for idle connections1000

Example with connection pooling:

const dataSource = new DataSource({
dialect: 'postgres',
database: 'mydb',
username: 'user',
password: 'password',
host: 'localhost',
port: 5432,
pool: {
max: 10, // Maximum connections
min: 2, // Minimum connections to maintain
idle: 10000, // Close idle connections after 10 seconds
acquire: 30000, // Wait up to 30 seconds for a connection
evict: 1000, // Check for idle connections every 1 second
},
models: [User, Order, Department],
});

Database-Specific Examples

PostgreSQL

const dataSource = new DataSource({
dialect: 'postgres',
database: 'mydb',
username: 'postgres',
password: 'password',
host: 'localhost',
port: 5432,
schema: 'public',
ssl: true,
models: [User, Order],
});

MySQL

const dataSource = new DataSource({
dialect: 'mysql',
database: 'mydb',
username: 'root',
password: 'password',
host: 'localhost',
port: 3306,
models: [User, Order],
});

SQLite

const dataSource = new DataSource({
dialect: 'sqlite',
database: './database.sqlite',
models: [User, Order],
});

Microsoft SQL Server

const dataSource = new DataSource({
dialect: 'mssql',
database: 'mydb',
username: 'sa',
password: 'password',
host: 'localhost',
port: 1433,
models: [User, Order],
});