Next.js Discord

Discord Forum

postgreSQL - raises Errors when I connect in multiple scrips

Unanswered
Asian black bear posted this in #help-forum
Open in Discord
Avatar
Asian black bearOP
I connected client this way in one file

(file1)
import pg from 'pg';
import db from 'DatabaseDetails';

const client = new pg.Client(db);
client.connect();

 const q = `SELECT COUNT(*)
    FROM invoices
    JOIN customers ON invoices.customer_id = customers.id
    WHERE
      customers.name ILIKE $1`
        const v = [query];
      const r = await client.query(q,v);


then in form action file

(action.ts)
const client = new pg.Client(db);
client.connect(); //*****


export async function createInvoice(formData: FormData) {
const q=`
    INSERT INTO invoices (customer_id, amount, status, date)
    VALUES ($1,$2,$3,$4)
  `;
    const v = [customerId, amountInCents, status, date];
    client.query(q, v);

}


it fails
unless I comment this client.connect(); on the action file, but then the data never adds anything

13 Replies

Avatar
Giant panda
The issue arises because you’re trying to create and manage multiple connections to the database in your code. Specifically, calling client.connect() multiple times for the same database can lead to conflicts or mismanagement of the connection lifecycle.
Avatar
@Asian black bear ok , what i should do ? how do i query inside action.ts correctly?
Avatar
have you tried putting const client and client.connect() in the export async function?
Avatar
Asian black bearOP
am I suppose to connect and disconnect as soon as I;m done with query ?
I've added
'use server'; and this seems to have fixed the issue after including const client and client.connect() in the function as well
but why ?? why do I have to put both of the in the function if the whole script is on the server ?
Avatar
Flemish Giant
1. Create a client module to manage the connection

// dbClient.ts
import { Client } from 'pg';
import db from './DatabaseDetails';

let client: Client;

export const getClient = () => {
if (!client) {
client = new Client(db);
client.connect().catch(err => console.error('Failed to connect to the database', err));
}
return client;
};
2. Update your query files to use the shared client:

import { getClient } from './dbClient';

const client = getClient();

const q = SELECT COUNT(*) FROM invoices JOIN customers ON invoices.customer_id = customers.id WHERE customers.name ILIKE $1;
const v = [query];
const r = await client.query(q, v);
this is the content of file1.ts (where you use the client):
And then "action.ts (where you perform the INSERT query):"
import { getClient } from './dbClient';

const client = getClient();

export async function createInvoice(formData: FormData) {
const q = INSERT INTO invoices (customer_id, amount, status, date) VALUES ($1, $2, $3, $4);
const v = [customerId, amountInCents, status, date];
await client.query(q, v); // Make sure to await the query
}
Avatar
@Alfonsus Ardani have you tried putting `const client` and `client.connect()` in the export async function?
Avatar
Asian black bearOP
when I added them to the function with 'use server'; i got [AggregateError: ] { code: 'ECANCELED' }
Avatar
@Flemish Giant 1. Create a client module to manage the connection // dbClient.ts import { Client } from 'pg'; import db from './DatabaseDetails'; let client: Client; export const getClient = () => { if (!client) { client = new Client(db); client.connect().catch(err => console.error('Failed to connect to the database', err)); } return client; };
Avatar
Asian black bearOP
I keep getting error here

Parsing ecmascript source code failed
  4 |
  5 |
> 6 | let client: Client;


i've tried let client; instead but I got another error

Export default doesn't exist in target module

Parsing ecmascript source code failed


so I added default

First as const:
>  8 | export default const getClient = () => {


Then as a function:

export default function getClient () {
[ Server ] Error: {imported module [project]/clientConn.js [app-rsc] (ecmascript)}.default.query is not a function


I'm a bit confused