DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Database Connection Pooling at Scale: PgBouncer + Multi-Tenant Postgres (10K Concurrent Connections)
  • Monorepo Development With React, Node.js, and PostgreSQL With Prisma and ClickHouse
  • Building and Integrating REST APIs With AWS RDS Databases: A Node.js Example
  • Migrating From MySQL to YugabyteDB Using YugabyteDB Voyager

Trending

  • Mocking Kafka for Local Spring Development
  • Agentic Testing: Moving Quality From Checkpoint to Control Layer
  • OpenAPI From Code With Spring and Java: A Recipe for Your CI
  • Architecting Zero-Trust AI Agents: How to Handle Data Safely
  1. DZone
  2. Data Engineering
  3. Databases
  4. The Easiest Way to Securely Query Postgres in Node.js

The Easiest Way to Securely Query Postgres in Node.js

Need a better way to query your Postgres DB?

By 
Forbes Lindesay user avatar
Forbes Lindesay
·
Oct. 09, 19 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
15.1K Views

Join the DZone community and get the full member experience.

Join For Free

baby-elephant-with-mother


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

  • Using an ORM. This gives you “native” feeling APIs to query the database.
  • Using raw SQL. This gives you the ultimate flexibility and 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 postgrescd 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.

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 theDATABASE_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.


Further Reading

  • Understanding Recursive Queries in Postgres.
  • PostgreSQL Backup and Recovery Automation.
Database connection PostgreSQL Node.js

Published at DZone with permission of Forbes Lindesay. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Database Connection Pooling at Scale: PgBouncer + Multi-Tenant Postgres (10K Concurrent Connections)
  • Monorepo Development With React, Node.js, and PostgreSQL With Prisma and ClickHouse
  • Building and Integrating REST APIs With AWS RDS Databases: A Node.js Example
  • Migrating From MySQL to YugabyteDB Using YugabyteDB Voyager

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook