Next.js Discord

Discord Forum

[ERROR] When I Connect postgresql and query in multiple different scripts

Answered
Asian black bear posted this in #help-forum
Open in Discord
Asian black bearOP
I'm tryin to make one file that connects to the database then import just the connection to the scripts I need to do anything with the database like queries.

connect.js
`use server`;
import { Client } from 'pg';
import db from 'dbDetails.js';




var client = () => {

    client = new Client(db);
   return client.connect();
}
export default client;


but whenever I try to imported I get this error

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


how to do it right ?
Answered by alfonsus
try

import { Client } from 'pg';
import db from 'dbDetails.js';

var client = new Client(db);
return client.connect();

export default client;
View full answer

70 Replies

Asian black bearOP
also please tell me if that's the right approach
Asian black bearOP
up
up
I'm tryin to make one file that connects to the database then import just the connection to the scripts I need to do anything with the database like queries.

Can you try removing 'use server' and importing it in a server component to see if it works?
is this the right approach ?
we will see in a moment
@alfonsus you declared `client` as a function, and inside you declared `client` as new Client(db)
Asian black bearOP
`use server`;
import { Client } from 'pg';
import db from 'dbDetails.js';
var xx = () => { return Client(db).connect();}
export default xx;

same error
remove 'use server'
Asian black bearOP
ok
@alfonsus remove 'use server'
Asian black bearOP
that made no difference
something wrong with
import db from 'dbDetails.js';
then
are you using typescript?
Asian black bearOP
not really because I used to connect on the same script using import db from 'dbDetails.js'; and it worked, I can query normally if Im connecting the client on the same script but if I'm importing it, it doesnt work.
@alfonsus are you using typescript?
Asian black bearOP
yes I think i have .ts formates
im following a toturial im new to react and nextJS
Asian black bearOP
sure
im using VS 2019
they are using '@vercel/postgres'; but Im hosting pg locally
im interested to know if your project is using typescript or javascript
i dont think you can mix it up
try

import { Client } from 'pg';
import db from 'dbDetails.js';

var client = new Client(db);
return client.connect();

export default client;
Answer
@alfonsus try tsx import { Client } from 'pg'; import db from 'dbDetails.js'; var client = new Client(db); return client.connect(); export default client;
Asian black bearOP
[ Server ] Error: Cannot access '{default export}' before initialization
sorry for the delay i have a 1 yearsOld child
@Asian black bear sorry for the delay i have a 1 yearsOld child
its fine, how are they? i hope they are healthy
@alfonsus its fine, how are they? i hope they are healthy
Asian black bearOP
thank u that is very sweet, yes they are 🙂
@alfonsus can we see `dbDetails.js` ?
Asian black bearOP
sure its pretty basic
const { Client } = require('pg');

const db = new Client({
    user: 'user1',
    host: 'localhost',
    database: 'nextJSdb',
    password: "123456",
    port: 5332,
});
export default db ;
is it a typescript file or a javascript file?
is your project using typescript or no typescript?
@alfonsus is it a typescript file or a javascript file?
Asian black bearOP
im sorry how to know this ?
im new
check the name of the file
Asian black bearOP
its a js file
i see
Im not sure why its wrong
do you have a github repository?
Asian black bearOP
nope
its kinda odd, why can i just pass it
i've also noticed that db itself is Client
yeah
Asian black bearOP
so db.connect() should be fine right ?
yeah\
Asian black bearOP
Im so sorry for the delay again - its impossible to control a 1yearOld
-------------------
SUMMERY:
--------------------
so basically, I have 2 .ts scripts that attempts to connect to the database for two different reasons
dbDetails.js
const { Client } = require('pg');

const db = new Client({
    user: 'user1',
    host: 'localhost',
    database: 'nextJSdb',
    password: "123456",
    port: 5332,
});
export default db ;


and then the other two ts files connect to it the same way
import { Client } from 'pg';
import db from 'dbDetails';

  const client:Client = new Client(db);
  client.connect().catch(err => console.error('Failed to connect to the db [ERROR]: ', err));


this code works will when only 1 file is connected when I connect the other file I get an error

Failed to connect to the db [ERROR]:  [AggregateError: ] { code: 'ECANCELED' }
I've also tried to make and export client as mentioned above and import it in the two ts files
import { Client } from 'pg';
import db from 'dbDetails.js';

var client = new Client(db);
return client.connect();

export default client;

but again it rose an error [ Server ] Error: Cannot access '{default export}' before initialization
I've tried many things none of them worked
Yacare Caiman
this is how you connect to with pg import pg from "pg"; export const pool = new pg.Pool({ host: process.env.PG_HOST, user: process.env.PG_USER, password: process.env.PG_PASSWORD, port: 5432 || process.env.PG_PORT, database: process.env.PG_DATABASE, idleTimeoutMillis: 30000, ssl: { rejectUnauthorized: false } });
and futher
const client = await pool.connect();
const result = await client.query(SELECT * Users;,[]);
more specifically const query = "SELECT * FROM users WHERE id = $1 AND email = $2;"; const values = [123, "test@example.com"];
@alfonsus try tsx import { Client } from 'pg'; import db from 'dbDetails.js'; var client = new Client(db); return client.connect(); export default client;
Asian black bearOP
I finally got it to work
const client = new Client(db);
client.connect();
export default client;

I have no idea why it didnt work bk then maybe the error was caused by something else
Yacare Caiman
Client makes new req each time when u query data base. And create lot of connections
Pool re-use the previous connections
@Yacare Caiman Pool re-use the previous connections
Yacare Caiman
If connections exist
@Yacare Caiman If connections exist
Asian black bearOP
I love this ofc!
are all connections session based?
sorry for asking too many questions, Im new to react and nextJS
@Asian black bear I love this ofc! are all connections session based?
Yacare Caiman
Yes, both client and Pool connections are session based!