Skip to main content

Introduction

Love SQL? Love TypeScript? Hate ORMs. You're 🏡.

EmbraceSQL takes a different approach. Rather than have you model in code, or map database to code, or learn some new schema language, EmbraceSQL generates a fully typed database driver from your database.

Your schema is your model, why hand code another one?

A generated driver is a new approach compared to classic dynamic and untyped SQL embedded in application code. Cool advantages:

  • Code completion / Intellisense works
  • Strong types are made for you, no need for hand coding
  • Database access supports the full type system, not just primitive types

Steps

Requirements

You will need:

This example assumes a sample DVD rental database, source at dvdrental.sql.

You can use this database for testing with a local postgres, such as Postgres.app.

Create a Database

Create a sample dvdrental database if you like with:

curl "https://embracesql.github.io/dvdrental.sql" | psql

Generate Code with EmbraceSQL

Going with this dvdrental example, assuming you are in the root directory of your typescript project.

npm install @embracesql/express
npm pkg set type=module
mkdir -p ./src
npx embracesqlcli generate node --database postgres://postgres:postgres@localhost/dvdrental > ./src/dvdrental.ts

Configure TypeScript

Preconfigured ready to go TypeScript config.

tsconfig.json
{
"extends": "@embracesql/shared/tsconfig/tsconfig.json"
}

Create a Node Program

Now you can use your fully typed database from TypeScript in Node.

./src/main.ts
// import the generated database access object
import { Database } from "./dvdrental";

// connect with a good old fashioned Postgres connection string
const db = await Database.connect(
"postgres://postgres:postgres@localhost:5432/dvdrental",
);
// calling a stored database function with positional, typed parameters.
const value = await db.Public.Procedures.LastDay.call({
argument_0: new Date(),
});
console.log(value);
// bye now 👋
await db.disconnect();

Test It!

Time to run. Database access end to end with no mapping.

npx tsx ./src/main.ts

Learn about AutoCRUD to get at all the tables in your database without writing data access or re-modeling your database with an ORM.

Lear about SQL Scripts to get any data you want -- all strongly typed -- with any SQL script you can imagine.