What is the functionality and operation of `getManager().query()` in TypeORM?

I am currently studying TypeORM and I am struggling to grasp the functionality of the 'query' method.

Here is an example of some code:

    export const lists = async (
      roleFilter: RoleFilter,
      filter: Filter,
      dateFilter: BetweenDate,
    ) => {
      const carLists = await getCars(roleFilter, filter);
      if (carLists.length === 0) {
        return { totalCount: 0, lists: [] };
      }
      const carIds = carLists.map(car => car.id); // **2 Extracting only IDs here

      const isCheckParam: number[] = [];
      let isCheckSQL = '';

      if (filter.isCheck !== null) {
      ....
      }

      const typeParamArray: string[] = [];
      const typeSQLArray: string[] = [];
      if (filter.impact === 1) {
        typeParamArray.push('impact');
        typeSQLArray.push('car_alarm.type = ?');
      }
      ....

      const typeSQL =
        typeSQLArray.length === 0 ? '' : `(${typeSQLArray.join(' OR ')}) AND`;

      const countQuery = `
        SELECT
          count(*) AS cnt
        FROM
          car_alarm
        WHERE ${typeSQL} ${isCheckSQL} car_alarm.carId IN (?) AND DATE(alarmAt) BETWEEN ? AND ?

      const countQuery = `
        SELECT
      count(*) AS cnt
    FROM
      car_alarm
    WHERE ${typeSQL} ${isCheckSQL} car_alarm.carId IN (?) AND DATE(alarmAt) BETWEEN ? AND ?
  `;

  const countResult = await getManager().query(countQuery, [
    ...typeParamArray,
    ...isCheckParam,
    carIds,
    dateFilter.start,
    dateFilter.end
  ]);

The use of getManager().query() in this section is essential.

  const countResult = await getManager().query(countQuery, [
    ...typeParamArray,
    ...isCheckParam,
    carIds,
    dateFilter.start,
    dateFilter.end
  ]);

Can someone provide me with an explanation on how the 'query()' function operates? I have been unsuccessful in finding any examples or explanations regarding its usage.

Answer №1

The query() function is designed to execute a raw parameterized SQL query, meaning that you must craft a SQL query specific to the database being used. The second argument of the query() function is an array containing parameters for the SQL query, which are then inserted into the query.

When it comes to executing raw SQL queries, there is no requirement for TypeORM; hence, any database driver package (such as mysql, pg) can be utilized. However, utilizing TypeORM offers the advantage of automatically generating and mapping queries to entity objects.

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

Having trouble utilizing yarn to import Mapbox into TypeScript

My process involves using the command: yarn add --dev @types/mapbox-gl @types/geojson This successfully adds mapbox and geojson to my project. I can see them when attempting to import mapboxgl. Next, I create something similar to this: import * as L ...

The object is classified as 'undetermined' (2571) upon implementation of map() function

Despite conducting a thorough search about this error online, I still haven't been able to find a solution. Let's jump into an example with data that looks like this: const earthData = { distanceFromSun: 149280000, continents: { asia: {a ...

Extracting information from console output and displaying it in a table with angular2

https://i.stack.imgur.com/BMt6J.pngI am facing an issue with retrieving data from the console output and populating it into an HTML table. Can someone please assist me with this? Here is the HTML Code: <table class="table"> <tr> <t ...

What steps can I take to resolve the "Unable to call a potentially 'undefined' object" error?

I'm currently working with CreateContext in Typescript and I have encountered a problem in the code that I can't seem to resolve. I am trying to use typesafe TX to provide state and dispatch (via useReducer) in a component hierarchy. Here is the ...

Can a file be transferred from the private path to the document directory?

I wrote this code using the captureVideo() method from the Ionic Native MediaCapture plugin. Here is the file path I obtained: /private/var/mobile/Containers/Data/Application/95DB5A64-700B-4E3D-9C2C-562C46520BEC/tmp/52515367181__BBC39D42-69EC-4384-A36F-7 ...

Tips for saving metadata about properties within a class

I am looking to add metadata to properties within classes, specifically using abbreviations for property names. By using annotations like @shortName(abbreviated), you can label each property as follows: function shortName(shortName: string){ return fu ...

Unable to retrieve data list in Angular TypeScript

After sending a request to the server and receiving a list of data, I encountered an issue where the data appears to be empty when trying to use it in another function within the same file. The code snippet below initializes an array named tree: tree:any ...

What is the best way for me to bring in this function?

Currently, I am in the process of developing a point-of-sale (POS) system that needs to communicate with the kitchen. My challenge lies in importing the reducer into my express server. Despite multiple attempts, I have been unable to import it either as a ...

What is the best way to convert a `readonly string[]` to a regular `string[]`?

My data setup is as follows (I am not declaring it as an enum because it is used in both TypeScript server code and non-TypeScript client code): import { enumType } from 'nexus'; export const TYPE_ENUM = Object.freeze({ H: 'H', S: ...

Ensuring that files adhere to the required format, whether they be images

Three separate input fields are being used, each with its own name for identification. A validation method is called to ensure that the files selected in these input fields are not duplicates and that they are either images or PDFs but not both. While thi ...

Ways to verify if TypeScript declaration files successfully compile with local JavaScript library

I have recently updated the typescript definitions in HunterLarco/twitter-v2, which now follows this structure: package.json src/ twitter.js twitter.d.ts Credentials.js Credentials.d.ts My goal is to verify that the .js files correspond correctly ...

You can't observe the behavior of simulated functions in a class with a manually created mock

Kindly note that I have set up a comprehensive Github repository where you can download and explore the content yourself here I am currently working on mocking a non-default exported class within a module using a manual mock placed in the folder __mocks__ ...

The expect.objectContaining() function in Jest does not work properly when used in expect.toHaveBeenCalled()

Currently, I am working on writing a test to validate code that interacts with AWS DynamoDB using aws-sdk. Despite following a similar scenario outlined in the official documentation (https://jestjs.io/docs/en/expect#expectobjectcontainingobject), my asser ...

Tips for Effectively Declaring a Variable with React's useState

How should I correctly specify variable types in useState? In the code below, the value for alert must be either "success","warning", "error", or "info" const [alertValue, setAlertValue] = useState("error" ...

Steps to access email template through an Excel web add-in

Currently, I am developing a new addin that aims to extract data from Excel and insert it into a word document. The final step would be attaching this document to an email in Outlook. While I have managed to achieve this using Power Automate, I prefer to ...

Error encountered while installing Material UI in Next.js with TypeScript and pure JavaScript configurations

I'm brand new to React and Next.js, so please forgive me for asking what may seem like a silly question. I'm attempting to install Material UI in a fresh Next.js application that I created using "npx create-next-app@latest". I've been refere ...

The type definition file for '@types' is not present in Ionic's code base

After updating my Ionic 6 project to use Angular 3, everything works perfectly in debug mode. However, when I attempt to compile for production using 'ionic build --prod' or 'ionic cordova build android --prod', I encounter the followin ...

What is the best approach to implementing a blur function for a specific input within a parent component?

I have created a custom input field as a separate component. I want to include multiple input fields in the parent component using directives: <app-input ...></app-input> My goal is to pass the blur event/function to the parent component speci ...

How can nested arrays be utilized in Angular 2 reactive forms?

After successfully using a tutorial to create reactive forms in Angular 2, I encountered a new challenge. The tutorial helped me set up an 'Organisation' form with an array of 'Contact' groups, but now I am struggling to add an array wi ...