Next.js Discord

Discord Forum

@vercel/postgres: dynamic table name

Unanswered
Cape lion posted this in #help-forum
Open in Discord
Cape lionOP
Not sure if this is welcome here, but here's the issue I'm facing
Say I want users to each get their own table. To do this, I want to set the table being queried dynamically. So my thought was to try using the sql tagged template literal.
import { sql } from '@vercel/postgres';
import { Note } from './definitions';
import { unstable_noStore as noStore } from 'next/cache';

function get_user_table_name(user_id: string) {
  return `notes_${user_id}`;
}

export async function getNotes(user_id: string) {
  noStore();
  try {
    const notes = await sql<Note>`SELECT * FROM ${get_user_table_name(user_id)}`;
    return notes.rows;
  } catch (error) {
    console.error('Database Error:', error);
    throw new Error('Failed to fetch notes.');
  }
}

Unfortunately, neon counts this as a syntax error 😦
So then I thought maybe usng the sql.query method instead:
    await sql.query(`
    CREATE TABLE IF NOT EXISTS ${get_user_table_name(user_id)} (
      id SERIAL PRIMARY KEY,
      title TEXT,
      content TEXT
    )`);

Problem is user_id comes from an external provider. What if that provider allows id's that can be used for SQL injection, now or some point in the future? I know that's not super realistic, but this just feels like bad practice. Has anyone ever run into this pattern before, and how did you handle it?

1 Reply

Cape lionOP
bump