SQL ORM Introduction
Hysteria ORM provides a powerful, partially type-safe ORM for SQL databases, supporting:
- PostgreSQL
- MySQL
- MariaDB
- SQLite
- CockroachDB
Key Features
- Partially Type-safe models and queries
- Decorator-based schema definition
- Advanced query builder
- Migrations and schema management
- Rich relation support (hasOne, hasMany, belongsTo, manyToMany)
- Transaction management (global, nested, concurrent)
- Hooks and lifecycle events
- Factory support for testing and seeding
Connecting and Disconnecting
Hysteria ORM provides flexible methods to manage your SQL database connections:
-
SqlDataSource.connect([config], [callback])
Establishes the default connection used by all models.- If no config is provided, environment variables are used.
- Optionally, you can pass a callback to run after connection.
import { sql } from 'hysteria-orm';
// Using environment variables
await sql.connect();
// Or with configuration
await sql.connect({
type: 'postgres',
host: 'localhost',
port: 5432,
username: 'user',
password: 'pass',
database: 'mydb',
}); -
SqlDataSource.connectToSecondarySource([config], [callback])
Opens a separate connection (not the global one used by models). Useful for migrations, background jobs, or multi-database scenarios.const anotherDb = await sql.connectToSecondarySource({
type: 'mysql',
host: 'localhost',
port: 3306,
username: 'user',
password: 'pass',
database: 'otherdb',
}); -
SqlDataSource.closeConnection()
/SqlDataSource.disconnect()
Closes the current (default) connection.await sql.closeConnection();
// or
await sql.disconnect();
Tip: Always close connections in scripts or CLI tools to avoid hanging processes.
Example Usage
import { sql } from 'hysteria-orm';
await sql.connect();
import { User } from './models/User';
const users = await User.query().many();
Next: Defining Models