Using a Sequelize query in a subsequent query for reusability

I am facing an issue with reusing a query from another function within a WITH clause of a separate query. I experimented with the following code snippet to tackle this challenge.

Here is a snippet to provide a general overview.

const reuseQuery = async (IdType, eventID) => {
    try {
        const sqlQuery = `SELECT *
        FROM TableA TA 
        WHERE TA.IdType = :IdType AND TA.eventID = :eventID`;
        const replacements = {IdType, eventID};
        const result = await this.sequelize.query(sqlQuery, {replacements, type: this.sequelize.QueryTypes.SELECT});
        return result;
    } catch (error) {
        console.log(error);
    }
};


const useReuseQuery = async () => {
    try {
        const sqlQuery = `WITH Query1 AS (${await reuseQuery(1, 1)}),
        Query2 AS (${await reuseQuery(2, 1)})
        Select q1.name AS Captain, q2.name AS Player
        FROM Query1 q1, Query2 q2
        WHERE q1.partnerID = q2.ID AND q2.partnerID = q1.ID`;

        const result = await this.sequelize.query(sqlQuery, {type: this.sequelize.QueryTypes.SELECT});
        return result;
    } catch(error) {
        
    }
};

Upon testing this approach, I encountered the following error message:

UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'query' of undefined

Answer №1

When looking at the second function, it appears that you are combining two result sets into a query string, which is not the correct approach for creating valid SQL.

Instead of concatenating the two result sets directly, it would be better to reuse the first sqlQuery within the second sqlQuery. Here is an example of how you can do this:

const reusableSqlQuery = `SELECT *
    FROM TableA TA 
    WHERE TA.IdType = :IdType AND TA.eventID = :eventID`;

const useReuseQuery = async () => {
try {
    const sqlQuery = `WITH Query1 AS (` + reusableSqlQuery +`),
    Query2 AS (` + reusableSqlQuery +`)
    Select q1.name AS Captain, q2.name AS Player
    FROM Query1 q1, Query2 q2
    WHERE q1.partnerID = q2.ID AND q2.partnerID = q1.ID`;
    const replacements = {1,1,2,1};
    const result = await this.sequelize.query(sqlQuery, {replacements, type: this.sequelize.QueryTypes.SELECT});
    return result;
} catch(error) {
    
}

};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Vanishing HTML upon initial entry to the site using Gatsby and Material UI exclusively in live deployment

I run a blog using Gatsby that includes Material UI components to fetch markdown files through GraphQL. During development, everything operates smoothly. However, in production (after running gatsby build && gatsby serve), the HTML doesn't di ...

I'm considering incorporating the "react-picky" third-party library for a filterable multiselect component in React Material UI, but it seems to deviate from the principles of Material Design

https://i.sstatic.net/dxpJO.pngInterested in using the third-party library "react-picky" for a filterable multiselect component with React Material UI, but finding that it doesn't align well with Material Design styles. Is there a way to style any th ...

Are there any other options besides using the React Material-UI makeStyles() function for styling class Components?

While experimenting with the makeStyles() function in Material-UI's React library, I encountered a specific error message: The use of hooks is limited to the body of a function component. Below is a snippet of the code that triggered this error: ...

The combination of AngularJS, jQuery, mobile angular ui, and phonegap results in disappointment

I'm embarking on my first venture into mobile app development. I'll be utilizing AngularJS, Mobile Angular UI, jQuery, and PhoneGap for this project. Here is a snippet of my code: <!doctype html> <html> <head> <script s ...

Leveraging the result of one ajax function within a different ajax function

My current project involves the following steps: 1. User creates a template with various elements. 2. When the user clicks a button: *The first ajax function establishes a new entry in the custom template database. *The second ajax function retrieves the ...

Avoid repeat sending of post requests using AJAX

I'm facing an issue with my ajax functionality. It seems to send my request only once. I am using a cssmap plugin that contains the 'onSecondClick' option, allowing me to perform an action when clicking twice. Upon clicking, a post request i ...

Unraveling the Mystery Behind Zero Array Problems

DESCRIPTION: A collection of elements is classified as zero-plentifull if it contains multiple occurrences of zeros, and each sequence of zeros consists of at least 4 items. The objective is to determine the number of zero sequences in the array if it mee ...

Incorporate information into a JSON structure within SAPUI5

While diving into SAPUI5, I decided to challenge myself by creating a basic form. Unfortunately, my attempts are falling short as the new entry I'm trying to add to my JSON model isn't showing up in the file when I run my code. No error messages ...

"Creating a delay within a loop using the setTimeout function

When using setTimeout in a loop, I noticed that all the operations are executed only after the loop ends. I followed the advice from multiple articles and tried putting setTimeout in a separate function, but it didn't make any difference. Here is the ...

Enhancing Images in Next JS

Is there a way to incorporate the NextJS Image element into raw HTML response from the server, such as the following example: HTML = "<div> <p> Some Random text</p> <img src="image1.jpg" /> <img src="image2. ...

Implement a custom email template for the contact form utilizing Express and Sendgrid

I have set up a basic contact form that utilizes the Node Sendgrid helper library for sending emails. My goal is to incorporate a template email/contact.jade that will convert to HTML and include the necessary context. I understand that this template shou ...

Conceal the Tab Bar in Stack Navigator Excluding the tabBarVisible Setting

I discovered some solutions using outdated versions of navigation, specifically involving the "tabBarVisible" option in Tab Navigator. However, this option is no longer available, so I am seeking guidance on how to hide the Tab Bar on specific screens with ...

Directing JSON POST Request Data to View/Controller in a Node.js Application

Currently, I am working on a project hosted on a local server at http://localhost:3000/. This server receives a post request from another server in the following manner: return requestLib.post({ url: 'http://localhost:3000/test', timeout ...

How can I ensure a header is displayed on each page by utilizing CSS or JavaScript/jQuery?

On a lengthy page with approximately 15 pages of text, I would like to insert a header at the beginning of each page when the document is printed by the user. Can this functionality be achieved using CSS or JavaScript/jQuery? ...

Guide on utilizing automatic intellisense in a standard TextArea within a web application

I have successfully created an Online compiler web application that is currently running smoothly. However, I am now looking to enhance my application by implementing intellisense in the TextArea where the program is being typed. For instance, if I type "S ...

AngularJs: Safely cleaning and rendering HTML content

I have been attempting to dynamically display HTML inside a div, but the ng-bind-html attribute isn't showing up at all on Firefox, Chrome, and Safari. After browsing through other posts on this website, I learned that ngSanitize needs to be included ...

The Sequelize database is experiencing an issue that is not providing an error message

My journey with PostgreSQL begins as I delve into creating a REST API using Sequelize for PostgreSQL, Express.js, and Node.js. One of the challenges I encountered was setting up a user system where each user can have multiple parcels associated with them. ...

Tips on increasing the width of the 'select' option once the user decides to make a selection

Here's a question for you: I have a <select> box where I set the width to 120px: <select style="width: 120px"> <option>REALLY LONG TEXT, REALLY LONG TEXT, REALLY LONG TEXT</option> <option>ABC</option> < ...

The initial material UI button conceals itself

I have encountered an issue with Material UI buttons in my code. Here's how I am using them: <main className="content"> <div className="buttons"> <Button variant="contained&qu ...

What is the Javascript equivalent to "new Audio()" but for video files?

When working in Javascript, accessing the HTML-5 audio object can be done like so: var audio = new Audio('nameOfFile.mp3'); However, it seems that using a similar syntax for the video element does not work (at least on Chrome). var video = new ...