Is there an improved method for designing a schema?

Having 4 schemas in this example, namely Picture, Video, and Game, where each can have multiple Download instances. While this setup works well when searching downloads from the invoker side (Picture, Video, and Game), it becomes messy with multiple tables. The real challenge arises when trying to determine the invoker from the Download side, as I need to look up 3 many-to-many tables before fetching the data.

I'm wondering if there is a feature in typeorm that could simplify this process or if my approach of designing many-to-many relationships with multiple schemas is fundamentally flawed. Have any of you encountered a similar issue? If yes, how did you go about solving it?

Thank you in advance

@Entity()
export class Picture {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    name: string

    @ManyToMany(() => Download)
    @JoinTable()
    downloads: Download[]
}

@Entity()
export class Video {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    name: string

    @ManyToMany(() => Download)
    @JoinTable()
    downloads: Download[]
}

@Entity()
export class Game {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    name: string

    @ManyToMany(() => Download)
    @JoinTable()
    downloads: Download[]
}

@Entity()
export class Download {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    source: string

    @Column()
    status: string

    @Column()
    path: string
}

Answer №1

Since we are unsure of the specific join technique being used due to lack of relevant field information in the schema description (noting that one schema has string type for source while others have int IDs), it might be beneficial to introduce indexes on key columns to improve the speed of SELECT statements.

A suggested solution could involve querying as follows:

select *
from downloads d
join game g on g.id = CAST(coalesce(d.source, '0') AS integer)
join video v on v.id = CAST(coalesce(d.source, '0') AS integer)
join picture p on p.id = CAST(coalesce(d.source, '0') AS integer)

If the downloads table had a structure like this:

CREATE OR REPLACE TABLE Download(
id int,
source_id int,
source varchar,
status varchar,
primary key id);

create index source_id_index on Download(source_id);

This would optimize query performance by indexing both the source_id in the Downloads table and the IDs in related tables, resulting in faster query execution:

select * from downloads d
join video v on v.id = d.source_id
join picture p on p.id = d.source_id
join game g on g.id = d.source_id

It's important to consider potential duplicates in neighboring tables; if present, introducing a content_source_id int variable with case when logic could be helpful. There are additional details regarding indexes in Postgres' documentation: https://www.postgresql.org/docs/current/sql-createindex.html

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

Is there a way to help my KafkaJS consumer stay patient while waiting for a broker to become available?

My KafkaJS consumer setup looks like this: // Create the kafka client const kafka = new Kafka({ clientId, brokers, }); // Create the consumer const consumer = this.kafka.consumer({ groupId, heartbeatInterval: 3000, sessionTimeout: 30000, }); // ...

The FormData object appears to be blank, even though it was supposed to be populated when attempting to send a PDF file using a multipart FormData POST request in Cypress

I am attempting to send a PDF file as a POST request. The API supports the use of @RequestPart and @RequestParam: @RequestPart("file") MultipartFile file; @RequestParam(value = "document-types", required = false) Set<String> documentTypes; My appro ...

Arranging Alphanumeric Characters in Angular in Ascending Order

I am trying to sort a list of characters first, followed by alphanumeric values. Here is what I have: [Austria , Germany , 123aed , 234eds] This is my current sorting attempt: obj.sort((a,b) => { if ( (isNaN(a.text) && isNaN(b.text)) || ...

Make TextField with type number forcibly show dot as decimal separator

I am currently utilizing the material-ui library to display a TextField component in my react application. Strangely, all instances of <TextField type="number /> are displaying decimal separators as commas (,) instead of dots (.), causing confusion f ...

Best practice in Angular 2: The difference between binding an object as a whole versus binding its individual

What is the best approach for a child component when dealing with object properties and change events? Example 1 <parent-component> <child-component [exampleInput]="object.val" (valueChanged)="updateObjectValue($event)"> ...

Steps to adding an item to a TypeScript array

My code involved creating an array called dataArray of type dataRows, which is an interface. dataArray: Array<dataRows>; In a function, I attempted to push a dataRows object into the array like this: this.dataArray.push(row) But for some ...

Why doesn't package.json typically utilize the preset values stored in the .npmrc file?

Windows 10 x64 Based on the information found here, I created a file called C:\Users\bushm\.npmrc with the following content: author = "Andrey Bushman" However, when I run the command npm init -y in a new directory, I noticed that the pac ...

Mocking a named class-export in TypeScript using Jest

I have a node module that exports several classes, including one called Client, which I utilize to create clients with various APIs as methods. I'm currently attempting to test my module, which has a dependency on this node module, using Jest. Howeve ...

Guide on sending JSON object to Angular custom components

I have implemented a custom element in Angular 7 using the CUSTOM_ELEMENTS_SCHEMA. My app.module.ts code is as follows: export class AppModule { constructor(private injector: Injector) {} ngDoBootstrap() { this.registerCustomElements( ...

How can I send 'blocking' parameter to getStaticPaths function in Next.js using TypeScript?

Whenever I try to use fallback: 'blocking', in my Next.js page, TypeScript throws an error. I am using the latest 12.2.0 version of Next.js. What could be causing this issue? Type '() => Promise<{ paths: any; fallback: string; }>&ap ...

What is the best way to refresh my component following a delete operation in React?

I am currently facing an issue with using Sweetalert2 and React (tsx) where I am unsure how to refresh my item list after deleting methods. Below is the code snippet that I have for a button that implements these functions: function DeleteCard(item: DataI ...

The return value depends on the type of function argument passed

I am currently developing a type-safe JSON:API specification parser for handling API responses that can either contain a single object or an array of objects (). For example, when making a request like GET /article: { data: { type: 'article&ap ...

Creating an Angular table using reactive forms: a step-by-step guide

After reviewing the HTML snippet provided below, it is evident that there is a table with looping through mat cell using *matCellDef="let model". Inside each cell, there are input fields which are reactive forms. Each row or cell needs to have it ...

Clearing the filename in a file type input field using React

When using this input field, only video files are accepted. If any other types of files are uploaded by enabling the "all files" option, an alert will be displayed. While this functionality is working correctly, a problem arises if a non-video file is adde ...

The async and await functions do not necessarily wait for one another

I am working with Typescript and have the following code: import sql = require("mssql"); const config: sql.config = {.... } const connect = async() => { return new Promise((resolve, reject) => { new sql.ConnectionPool(config).connect((e ...

Develop a "Read More" button using Angular and JavaScript

I am in search of all tags with the class containtText. I want to retrieve those tags which have a value consisting of more than 300 characters and then use continue for the value. However, when I implement this code: <div class=" col-md-12 col-xl-12 c ...

Discovering the clicked element within a QueryList<ElementRef> in Angular

Having a ElementRef(QueryList) of a group of dynamically created Table cells (td html elements) using ViewChildren, I have successfully debugged and verified the availability of the element set. When clicking on a specific td html element, a function is c ...

Attaching the JSON data to ngModel in Angular 2

I have received a json response containing various fields, including the rewards.rewardName value. I'm trying to figure out how to bind this specific value to [(ngModel)] in Angular 2. [ { "id": 18, "gname": "learning ramayanam", "goalCat ...

Show a combined result of various queries with distinct row types

In my PostgreSQL 8.3 setup on Ubuntu, I have three tables named T1, T2, and T3, each with different schemas. These tables contain records related to a specific ID that I am aware of. Using 'psql', I regularly execute the following three operation ...

When I delete the initial element from the array, the thumbnail image disappears

Using react-dropzone, I am attempting to implement image drag and drop functionality. The dropped image is stored in the React state within a files array. However, a problem arises when removing an image from the array causing the thumbnails of the remain ...