Skip to main content

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:

  • sql.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'
    });
  • sql.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',
    });
  • sql.closeConnection() / sql.disconnect() Closes the current (default) connection.

    await sql.closeConnection();
    // or
    await sql.disconnect();
  • sql.getConnection() Returns a single connection from the pool (SQLite returns the Database instance). The caller is responsible for using it within transactions and ensuring proper lifecycle via transaction helpers.

    const connection = await sql.getConnection();

    // Type utility for specific connection types
    const mysqlConnection = await sql.getConnection("mysql");
    const pgConnection = await sql.getConnection("postgres");
    const sqliteConnection = await sql.getConnection("sqlite");
  • sql.getPool() Returns the underlying pool/driver instance (SQLite returns the Database instance). Use this for low-level operations only.

    const pool = sql.getPool();

    // Type utility for specific connection types
    const mysqlPool = sql.getPool("mysql");
    const pgPool = sql.getPool("postgres");
    const sqliteDb = sql.getPool("sqlite");

Example Usage

import { sql } from 'hysteria-orm';
await sql.connect();

import { User } from './models/User';
const users = await User.query().many();

Next: ORM Patterns