Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

injecting postgresQueryBuilder interperted as values this is critical #17215

Closed
moeelbadri opened this issue Feb 9, 2025 · 4 comments · Fixed by #17273
Closed

injecting postgresQueryBuilder interperted as values this is critical #17215

moeelbadri opened this issue Feb 9, 2025 · 4 comments · Fixed by #17273
Labels
bug Something isn't working

Comments

@moeelbadri
Copy link

moeelbadri commented Feb 9, 2025

What version of Bun is running?

1.2.2

What platform is your computer?

Microsoft Windows NT 10.0.22631.0 x64

What steps can reproduce the bug?

        const orderBypg = (x: string) => database.sql(`ORDER BY ${database.sql(`alerts.${x}`)} DESC`) // sortBy.field is created_at
        console.log(orderBypg(sortBy.field)) // PostgresQuery {     }
        const results = await database.sql(`
        SELECT alerts.* , profiles.Full_name
        FROM alerts
        LEFT JOIN profiles ON profiles.user_id = alerts.user_id
        ${sortBy.direction == "desc" ? 
            orderBypg(sortBy.field) :
            orderBypg(sortBy.field)
         }
         WHERE alerts.hotel_id = ${user.hotel_id}
        `);

What is the expected behavior?

i get the results of the query

What do you see instead?

instead im getting syntax error near promise

"err":{"type":"SyntaxError","message":"syntax error at or near \"Promise\"","stack":"","errno":"42601","position":147,"name":"PostgresError","code":"ERR_POSTGRES_SYNTAX_ERROR"},"msg":"syntax error at or near \"Promise\"

Additional information

No response

@moeelbadri moeelbadri added bug Something isn't working needs triage labels Feb 9, 2025
@moeelbadri
Copy link
Author

moeelbadri commented Feb 9, 2025

  const orderBypg = (x: string) => database.sql`ORDER BY ${x} DESC`
        console.log(orderBypg(sortBy.field))
        const results = await database.sql(`
        SELECT alerts.* , profiles.Full_name
        FROM alerts
        LEFT JOIN profiles ON profiles.user_id = alerts.user_id
        ${sortBy.direction == "desc" ? 
            orderBypg(sortBy.field) :
            orderBypg(sortBy.field)
         }
         WHERE alerts.hotel_id = ${user.hotel_id}
        `);

tried this too same ,, syntax error near promise
i might be not doing it correctly

thats from bun sql

// Optional WHERE clauses
const filterAge = true;
const minAge = 21;
const ageFilter = sql`AND age > ${minAge}`;
await sql`
  SELECT * FROM users
  WHERE active = ${true}
  ${filterAge ? ageFilter : sql``}
`;

cant see the differenece

@RiskyMH RiskyMH added sql Something to do with `sql` in the "bun" module node.js Compatibility with Node.js APIs and removed needs triage sql Something to do with `sql` in the "bun" module node.js Compatibility with Node.js APIs labels Feb 10, 2025
@moeelbadri moeelbadri changed the title injecting postgresQuery interperted as values this is critical injecting postgresQueryBuilder interperted as values this is critical Feb 10, 2025
@RiskyMH
Copy link
Member

RiskyMH commented Feb 10, 2025

I have some questions to understand what the issue is:

  1. in your first code snippet are you using the pg npm libary?
  2. if it is a JS postgres lib, whats the outcome of running in node?

@moeelbadri
Copy link
Author

moeelbadri commented Feb 10, 2025

no its not, im using sql from bun , both codes bun.sql ..... i think i miss-explained my problem abit

@moeelbadri
Copy link
Author

moeelbadri commented Feb 10, 2025

import { Sequelize, Model, ModelStatic, } from 'sequelize-typescript';
import { PostgrestClient } from '@supabase/postgrest-js'
import Redis from "ioredis"
import { SQL } from 'bun';

// import { fetch } from 'undici'
class Database {
  // public sequelize: Sequelize;
  public postgrest: PostgrestClient;
  public redis : Redis;
  public sql : SQL;
//   public posts: Model<postsAttributes, postsAttributes> = new posts();
//   public comments: Model<commentsAttributes, commentsAttributes> = new comments;
//   public users: Model<usersAttributes, usersAttributes> = new users;
  constructor() {
    // initialize redis with your database connection information
    this.redis = new Redis({host: 'localhost', port: 6379});
    this.redis.info().then((info) => {
      console.log(`Connected to Redis server`);
      //info: ${info.redis_version} ${info.uptime_in_days} days ${info.uptime_in_seconds} seconds ${info.hz} hz
    })
    // initialize bun sql with your database connection information 
    this.sql = new SQL({
        url: 'postgres://postgres:postgres@localhost:5432/facebook',
        host: '127.0.0.1',
        port: 5432,
        database: 'hotel',
        username: 'postgres',
        password: 'postgres',
        max: 10,
        idleTimeout : 0,
        maxLifetime : 0,
        connectionTimeout : 30,
        tls: false,
        adapter: 'postgresql',
        bigint: false,
        onconnect : () => {
            console.log('Connected to database');
        },
        onclose : () => {
            console.log('Disconnected from database');
        }
    })
    this.sql.connect();
    // Initialize Sequelize with your database connection information
    this.postgrest =  new PostgrestClient("http://127.0.0.1:3000",
      {
        fetch: (...args) => fetch(...args),
        // fetch:fetch
      }
    );
  //   this.sequelize = new Sequelize("facebook", "postgres", "postgres", {
  //     host: "127.0.0.1",
  //     dialect: "postgres", // Choose the appropriate dialect
  //     // logging: true,
  //     define: { timestamps: false },
  //     pool: {
  //       max: 10,
  //       min: 0,
  //       acquire: 30000,
  //       idle: 10000,
  //     },
  //   //   models: [posts, comments, users],
  //   });
  //   this.sequelize.authenticate().then(() => {
  //     console.log('Connection has been established successfully.');
  //   }).catch((error) => {
  //     console.error('Unable to connect to the database:', error);
  //   })
  }
}

// Export an instance of the Database class
const database: Database = new Database();
export { database };

database.sql derived from this file i have in my project

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants