When you’re querying Postgres, you need to choose between:

Use an ORM . This givers you “native” feeling APIs to query the database.

. This givers you “native” feeling APIs to query the database. Use raw SQL. This gives you the ultimate flexibility & performance, and gives you more transferable skills – it’s always helpful to know how to write SQL.

Postgres ORM 📦

If you want to use an ORM to query Postgres, I recommend using https://typeorm.io. If you’re starting with a fresh project, you can use their typeorm init CLI command:

npx typeorm init --name MyProject --database postgres

cd MyProject && yarn

You’ll then need to edit ormconfig.json to add your database connection options. You’ll need to add a file in src/entity for each table in your database.

“ORMs do not give you transferable skills”

https://typeorm.io/#undefined/quick-start has detailed instructions on how to configure this. You can then use a JavaScript API to create records in your database:

import {createConnection} from "typeorm";

import {Photo} from "./entity/Photo"; async function createPhoto() {

const connection = await createConnection({

type: 'postgres',

url:

process.env.DATABASE_URL

|| 'postgres://test:test@localhost/test'

}); const photo = new Photo();

photo.name = "Me and Bears";

photo.description = "I am near polar bears";

photo.filename = "photo-with-bears.jpg";

photo.views = 1;

photo.isPublished = true; const {id} = await connection.manager.save(photo);

console.log("Photo has been saved. Photo id is", photo.id);

} createPhoto();

There are advantages to this approach (the biggest being that it supports strong types), but I personally feel that it makes the code pretty hard to read/follow, and the skills you learn on TypeORM will be of no use if you move to a different ORM.

Raw SQL 🚀

I believe that the simplest and easiest way to query Postgres is to directly write the SQL that will be run against your database.

“Using SQL directly, means there’s nothing to configure”

yarn add @databases/pg

You’ll need to set the DATABASE_URL environment variable to a database connection string.

import connect, {sql} from '@databases/pg';

const db = connect(); export async function getAllUsers() {

return await db.query(sql`SELECT * FROM users;`);

} export async function getUserById(userId) {

return (await db.query(sql`

SELECT * FROM users WHERE user_id=${userId}

`))[0];

} export async function createUser(u) {

return (await db.query(sql`

INSERT INTO users (name, email)

VALUES (${u.name}, ${u.email})

RETURNING user_id;

`))[0].user_id;

} export async function deleteUserById(userId) {

await db.query(sql`DELELTE FROM users WHERE user_id=${userId}`);

} export async function updateUserById(userId, u) {

await db.query(sql`

UPDATE users

SET name=${u.name}, email=${u.email}

WHERE user_id=${userId}

`);

} export async function upsertUser(userId, u) {

return (await db.query(sql`

INSERT INTO users (user_id, name, email)

VALUES (${userId}, ${u.name}, ${u.email})

ON CONFLICT (user_id)

DO UPDATE SET name=${u.name}, email={u.email}

RETURNING *;

`))[0];

}

Using SQL lets us be very explicit about handling conflicts

For a complete list of all the ways you can dynamically combine queries, check out the documentation at https://www.atdatabases.org/docs/sql. For full docs on the Postgres API, including how to handle transactions, see https://www.atdatabases.org/docs/pg

N.B. The @databases library does not just concatenate your user input into a string of SQL, it separates your parameters from the actual query, and uses prepared statements to run the query. It throws a clear runtime exception if you forget to tag your sql with the sql tag. This means it’s virtually impossible for you to introduce SQL Injection vulnerabilities by accident.

Conclusion

For most projects, I recommend querying your postgres database directly using @databases/pg , it gives you the ultimate flexibility. If you need TypeScript types, I recommend declaring the types along with the SQL that queries. TypeScript isn’t currently able to check that the types match your database schema, but at least if they’re in the same file, you’ll probably remember to keep them in sync.

@databases logo