EzDev.org

typeorm

typeorm - ORM for TypeScript and JavaScript (ES7, ES6, ES5). Supports MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, WebSQL databases. Works in NodeJS, Browser, Ionic, Cordova and Electron platforms. TypeORM - Amazing ORM for TypeScript and JavaScript (ES7, ES6, ES5). Supports MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, WebSQL databases. Works in NodeJS, Browser, Ionic, Cordova and Electron platforms.


TypeORM upsert - create if not exist

Does TypeORM include some functionnality to avoid this :

let contraption = await thingRepository.findOne({ name : "Contraption"});

if(!contraption) // Create if not exist
{
    let newThing = new Thing();
    newThing.name = "Contraption"
    await thingRepository.save(newThing);
    contraption = newThing;
}

Something like :

let contraption = await thingRepository.upsert({name : "Contraption"});

Source: (StackOverflow)

Error: SQLITE_CONSTRAINT: NOT NULL constraint typeorm

We are struggling for this almost whole day and we don't see where is the problem. Everything seems good but we realized that somehow after second connection to database and calling different queries we loose PRIMARY KEY at files table.

Here is what we have and what we call to get error Error: SQLITE_CONSTRAINT: NOT NULL constraint failed: files.id

user.entity.ts

import { Entity } from 'typeorm/decorator/entity/Entity';
import {Column, OneToMany, PrimaryGeneratedColumn} from 'typeorm';
import {Sources} from './sources.entity';

@Entity()
export class Users {

  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @Column("varchar", { nullable: true})
  email: string;

  @OneToMany(type => Sources, source => source.user, {
    cascadeInsert: true,
    cascadeUpdate: true,
    cascadeRemove: true
  })
  source: Sources[];
}

source_type.entity.ts

import {Entity} from 'typeorm/decorator/entity/Entity';
import {Column, OneToOne, PrimaryGeneratedColumn} from 'typeorm';
import { Sources } from './sources.entity';

@Entity()
export class SourceType {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @OneToOne(type => Sources, sourcesType => sourcesType.sourceType, {
    cascadeInsert: true,
    cascadeUpdate: true,
    cascadeRemove: true
  })
  source: Sources;
}

sources.entity.ts

import {Entity} from 'typeorm/decorator/entity/Entity';
import {Column, JoinColumn, ManyToOne, OneToMany, OneToOne, PrimaryGeneratedColumn} from 'typeorm';
import { SourceType } from './source_type.entity';
import { Users } from './user.entity';
import {SourcesPaths} from "./sources_paths.entity";
import {Files} from "./files.entity";

@Entity()
export class Sources {

  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @OneToOne(type => SourceType)
  @JoinColumn()
  sourceType: SourceType;

  @ManyToOne(type => Users, users => users.source)
  @JoinColumn()
  user: Users;

  @OneToMany(type => SourcesPaths, sourcesPaths => sourcesPaths.source)
  sourcePath: SourcesPaths[];

  @OneToMany(type => Files, file => file.source)
  file: Files[];

}

files.entity.ts

import {Entity} from 'typeorm/decorator/entity/Entity';
import { Column, JoinColumn, ManyToOne, OneToMany, OneToOne, PrimaryGeneratedColumn } from 'typeorm';
import {Sources} from './sources.entity';
import {FilesTags} from './files_tags.entity';

@Entity()
export class Files {

  @PrimaryGeneratedColumn()
  id: number;

  @Column('varchar', {length: 45})
  name: string;

  @Column('varchar', {length: 45, nullable: true})
  family_name: string;

  @Column('varchar', {length: 45, nullable: true})
  created_at: string;

  @ManyToOne(type => Sources, source => source.file)
  @JoinColumn()
  source: Sources;

  @OneToMany(type => FilesTags, fileTag => fileTag.file)
  fileTag: FilesTags[];
}

insertUser function When we call insert function for the first time everything goes well. Data is inserted including data into files entity also. But on second call to insertUser() we are getting error

Error: SQLITE_CONSTRAINT: NOT NULL constraint failed: files.id

In SQLite studio we saw that after first insert of files we loose primary key on files.id. Are we doing something wrong or there is an issue in typeorm?

insertUser(): void {

    createConnection({

      type: 'sqlite',
      database: '../user.sqlite',
      entities: [
        Users,
        Sources,
        SourceType,
        Files
      ],
      autoSchemaSync: true,
    }).then( async connection => {

      // Here you can start to work with your entities
      const user = new Users();
      user.name = 'Mezenga1234';

     await connection.manager.save(user);

      const sourcetype = new SourceType();
      sourcetype.name = 'my_library';
     await connection.manager.save(sourcetype);

      const source = new Sources();
      source.name = 'my_source';
      source.sourceType = sourcetype;
      source.user = user;

     await connection.manager.save(source);

      const files = new Files();
      files.name = 'Haris.rvt';
      files.source = source;

      await connection.manager.save(files);

      console.log('Inserted');
      connection.close();

    }).catch(error => console.log(error));

  }

Source: (StackOverflow)

MySQL Events in TypeORM

Is it possible to make MySQL events in TypeORM?

In my app I have an entity called USERS and there is a boolean field "parent_approval" ('true' - if user has approval from parent or user is adult and 'false' - if user doesn't have approval)

What I want to do is remove user after 7 days if this field will be false after this time.

Any tips?


Source: (StackOverflow)

RepositoryNotFoundError : Typeorm

I am trying to get the following example working https://github.com/typeorm/javascript-example/tree/master/src/app3-es6

I am running into the following error

Error at new RepositoryNotFoundError (...\node_modules\typeorm\connection\error\RepositoryNotFoundError.js:24:23) at Connection.findRepositoryAggregator (...\node_modules\typeorm\connection\Connection.js:513:19) at Connection.getRepository (...\node_modules\typeorm\connection\Connection.js:405:21) at ...\index.js:27:37

name: 'RepositoryNotFoundError',
  message: 'No repository for "Post" was found. Looks like this entity is not registered in current "default" connection?'

here is index.js

const typeorm = require("typeorm"); // import * as typeorm from "typeorm";
const Post = require("./model/Post"); // import {Post} from "./model/Post";
// import Post from './model/Post.js';
const Category = require("./model/Category"); // import {Category} from "./model/Category";

typeorm.createConnection({
    driver: {
        type: "oracle",
        host: "localhost",
        port: 1521,
        username: "uname",
        password: "pwd",
        sid: "dev"
    },
    entities: [
        __dirname + "/entity/*.js"
    ],
    autoSchemaSync: true
}).then(function (connection) {
    console.log(connection);

    let post = new Post.Post();
    post.title = "Control flow based type analysis";
    post.text = "TypeScript 2.0 implements a control flow-based type analysis for local variables and parameters.";
    post.categories = [new Category.Category(0, "TypeScript"), new Category.Category(0, "Programming")];

    let postRepository = connection.getRepository(Post.Post);
    postRepository.persist(post)
        .then(function(savedPost) {
            console.log("Post has been saved: ", savedPost);
            console.log("Now lets load all posts: ");

            return postRepository.find();
        })
        .then(function(allPosts) {
            console.log("All posts: ", allPosts);
        });
}).catch(function(error) {
    console.log("Error: ", error);
});

Post.js in /model/

/*export */ class Post {
    constructor(id, title, text, categories) {
        this.id = id;
        this.title = title;
        this.text = text;
        this.categories = categories;
    }
}

module.exports = {
    Post: Post
};

Category.js

/*export */ class Category {
    constructor(id, name) {
        this.id = id;
        this.name = name;
    }
}

module.exports = {
    Category: Category
};

PostSchema.js in /entity/

const Post = require("../model/Post"); // import {Post} from "../model/Post";
const Category = require("../model/Category"); // import {Category} from "../model/Category";
const PostSchema = {
    target: Post,
    columns: {
        id: {
            primary: true,
            type: "int",
            generated: true
        },
        title: {
            type: "string"
        },
        text: {
            type: "text"
        }
    },
    relations: {
        categories: {
            target: Category,
            type: "many-to-many",
            joinTable: true,
            cascadeInsert: true
        }
    }
};

module.exports = {
    PostSchema: PostSchema
};

CategorySchema.js

const Category = require("../model/Category"); // import {Category} from "../model/Category";
const CategorySchema = {
    target: Category,
    columns: {
        id: {
            primary: true,
            type: "int",
            generated: true
        },
        name: {
            type: "string"
        }
    }
};

module.exports = {
    CategorySchema: CategorySchema
};

i dont know what i am doing wrong


Source: (StackOverflow)

Javascript node.js ORM that follows data-mapper pattern

I've been working with active record and data mapper implementations of ORM enough to know the problems with using active record implemented ORM in my large projects. Right now I'm thinking to migrate one of my projects to node.js and trying to find the similar tools Im using right now. After research I didn't found any node.js ORM that follows data mapper pattern. They all are active record. Maybe I missing something, and you can tell me is there is a good popular ORM for node.js that doesn't follow active record pattern?

The libraries Ive looked on:


Source: (StackOverflow)

How to inject an asynchronous dependency in inversify?

I have TypeScript application and I'm using Inversify for IoC.

I have a connection class:

'use strict';
import { injectable } from 'inversify';
import { createConnection, Connection } from "typeorm";
import { Photo, PhotoMetadata, Author, Album } from '../index';

@injectable()
class DBConnectionManager {

    public createPGConnection(): Promise<Connection> {
        return createConnection({
            driver: {
                type: "postgres",
                host: "host",
                port: 5432,
                username: "username",
                password: "password",
                database: "username"
            },
            entities: [
                Photo, PhotoMetadata, Author, Album
            ],
            autoSchemaSync: true,
        });

    }

}

export { DBConnectionManager };

After I created my connection I want to bind a connection into my container:

kernel.bind<Connection>('DefaultConnection').toConstantValue(getConnectionManager().get());

and then I want to inject it into another class:

import { injectable, inject } from 'inversify';
import { Connection, FindOptions } from "typeorm";
import { IGenericRepository, ObjectType } from '../index';


    @injectable()
    class GenericRepository<T> implements IGenericRepository<T> {

        private connection: Connection;
        private type: ObjectType<T>;

        constructor( @inject('DefaultConnection') connection: Connection) {
            this.connection = connection;
        }

So in my container configuration how can I bind DefaultConnection that needs to wait for CreateConnection I can do with async and wait but I'm wonder if there is a cleaner way to achive this in inversify


Source: (StackOverflow)

How do i prevent decorators from importing node modules in TypeScript?

I'm trying to use the typeorm library in typescript to create a DTO/DAO pattern between a TypeScript 2 Express server and Angular 2.

I'm calling these objects DTOs for brevity, but they are just a bunch of fields, and annotations.

import {autoserialize} from "cerialize";
import {DTOReport} from "./reports.dto";

import { PrimaryGeneratedColumn} from "typeorm/decorator/columns/PrimaryGeneratedColumn"
import { CreateDateColumn } from "typeorm/decorator/columns/CreateDateColumn";
import { Column } from "typeorm/decorator/columns/Column";
import { JoinColumn } from "typeorm/decorator/relations/JoinColumn";
import { OneToOne } from "typeorm/decorator/relations/OneToOne";
import { ManyToOne } from "typeorm/decorator/relations/ManyToOne";
import { OneToMany } from "typeorm/decorator/relations/OneToMany";
import { Table } from "typeorm/decorator/tables/Table";
import { ColumnTypes } from "typeorm/metadata/types/ColumnTypes";

@Table()
export class DTOSourceFile {
  @PrimaryGeneratedColumn()
  @autoserialize
  id: number;

  @Column()
  @autoserialize
  locationURL: string;

  @CreateDateColumn()
  @autoserialize
  createdAt: Date;

  @OneToMany(type => DTOReport, report => report.source, {nullable: true})
  @autoserialize report: DTOReport;
  @autoserialize reportId: number;

  @Column(ColumnTypes.TEXT)
  @autoserialize
  originalname: string;

  @Column(ColumnTypes.JSON)
  @autoserialize
  mutler: string;
}

I'm carefully importing only the decorators. However, at compile time i see a request go back to the root index.ts file.

"use strict";
const ColumnTypes_1 = require("../../metadata/types/ColumnTypes");
const ColumnTypeUndefinedError_1 = require("../error/ColumnTypeUndefinedError");
const index_1 = require("../../index");  // < --- THIS
const PrimaryColumnCannotBeNullableError_1 = require("../error/PrimaryColumnCannotBeNullableError");
/**
 * Column decorator is used to mark a specific class property as a table column.
 * Only properties decorated with this decorator will be persisted to the database when entity be saved.
 * Primary columns also creates a PRIMARY KEY for this column in a db.
 */
function PrimaryColumn(typeOrOptions, options) {
    let type;
    if (typeof typeOrOptions === "string") {
        type = typeOrOptions;
    }
    else {
        options = typeOrOptions;
    }
    return function (object, propertyName) {
        const reflectedType = ColumnTypes_1.ColumnTypes.typeToString(Reflect.getMetadata("design:type", object, propertyName));
        // if type is not given implicitly then try to guess it
        if (!type)
            type = ColumnTypes_1.ColumnTypes.determineTypeFromFunction(Reflect.getMetadata("design:type", object, propertyName));
        // if column options are not given then create a new empty options
        if (!options)
            options = {};
        // check if there is no type in column options then set type from first function argument, or guessed one
        if (!options.type)
            options = Object.assign({ type: type }, options);
        // if we still don't have a type then we need to give error to user that type is required
        if (!options.type)
            throw new ColumnTypeUndefinedError_1.ColumnTypeUndefinedError(object, propertyName);
        // check if column is not nullable, because we cannot allow a primary key to be nullable
        if (options.nullable)
            throw new PrimaryColumnCannotBeNullableError_1.PrimaryColumnCannotBeNullableError(object, propertyName);
        // implicitly set a primary to column options
        options = Object.assign({ primary: true }, options);
        // create and register a new column metadata
        const args = {
            target: object.constructor,
            propertyName: propertyName,
            propertyType: reflectedType,
            mode: "regular",
            options: options
        };
        index_1.getMetadataArgsStorage().columns.add(args); // < --- THIS
    };
}
exports.PrimaryColumn = PrimaryColumn;

//# sourceMappingURL=PrimaryColumn.js.map

The resulting error from Angular 2's webpack compiler clearly shows the issue as it then tries to load node dependencies.

WARNING in ./~/typeorm/driver/sqlserver/SqlServerDriver.js
Module not found: Error: Can't resolve 'mssql' in '/Users/jmurphy/projects/ubq/web/node_modules/typeorm/driver/sqlserver'
 @ ./~/typeorm/driver/sqlserver/SqlServerDriver.js 256:25-41
 @ ./~/typeorm/connection/ConnectionManager.js
 @ ./~/typeorm/index.js
 @ ./~/typeorm/decorator/columns/PrimaryGeneratedColumn.js
 @ ./src/app/dtos/lens.dto.ts
 @ ./src/app/lens/lens.component.ts
 @ ./src/app/app.module.ts
 @ ./src/app/index.ts
 @ ./src/main.ts
 @ multi main
Child html-webpack-plugin for "index.html":
         Asset     Size  Chunks       Chunk Names
    index.html  2.88 kB       0
webpack: bundle is now VALID.

Is there a way to allow TypeORM decorators to exist in a browser project without trying to load node dependencies?

Links:

TypeORM Source: https://github.com/typeorm/typeorm/blob/master/src/decorator/columns/PrimaryColumn.ts


Source: (StackOverflow)

typeorm issue while creating connection in ionic 2

When I try to create a connection in Ionic Orm it throws the following error:

Driver option (storage) is not set. Please set it to perform connection to the database

Here is my code to connect in app.ts

createConnection({
        driver: {
        type: "sqlite",
        database: "test"
        },
        entities: [
         Products
        ],
        autoSchemaSync: true,
        }).then(connection => {
            alert(connection);
                let product = new Products();

        }).catch(error => console.log(error));

Source: (StackOverflow)

Postgres enum in typeorm

In typeorm, how can I create a postgres enum type Gender as in this raw query

CREATE TYPE public.Gender AS ENUM (
    'male', 'female'
);
ALTER TABLE public.person ALTER COLUMN gender TYPE public.gender USING gender::gender;

and use it in the Entity class?

I have tried

@Entity()
export class Person {
    @Column('enum')
    gender: 'male' | 'female'
}

but obviously this isn't the right way, since I got the error message "type enum does not exist".

I don't want to use typescript enum either, since it will give me a bunch of 0s and 1s in the database.


Source: (StackOverflow)

TypeORM FindById doesn't work with MongoDB

I'm trying to use TypeORM with MongoDB and express but I'm having problems with the basic stuff.

I just created a controller with basic CRUD operations for an entity. The methods save, findAll and find by Filter works ok, but I can't make the methods that require an mongo id work.

router.get("/", async(req: Request, res: Response) => {
    const investmentRepository = getMongoRepository(Investment);

    const investments = await investmentRepository.find();
    res.send(investments);
});

router.get("/:id", async(req: Request, res: Response) => {
    const investmentRepository = getMongoRepository(Investment);
    const investment = await 
    investmentRepository.findOneById(req.params.id);
    if (!investment) {
        res.status(404);
        res.end();
    }
    res.send(investment);
});

The second method is always returning 404. For example, this is an entity returned on get all "investment/"

{
    "id": "59dfd8cadcbd9d1720457008",
    "name": "Teste LCI",
    "startDate": 1466305200,
    "numberOfDays": 365,
    "type": "LCI_LCA"
}

If I try to send a request for this specific object calling

investment/59dfd8cadcbd9d1720457008

the response is always 404.

The same behavior happen with the delete method, raising an exception

Cannot find entity to remove by a given id

I also tried to convert the string to ObjectID using:

new ObjectID(req.params.id);

but it fails with the error ObjectID is not a constructor.


Source: (StackOverflow)

Connecting postgres from typeorm docker container

I am trying to connect a postgres db to nodejs using typeorm.

I tried doing this with both postgres and nodejs in localhost and it worked fine. However I am having problems when I put postgres and nodejs into docker containers.

(The "IPAdress" field in docker inspect for postgres container is 172.19.0.3)

Error from Nodejs:

web_1    | error: TypeORM connection error:  Error: connect ECONNREFUSED 172.19.0.3:5433

docker-compose.yml

services:
  web:
    build: .
    volumes:
      - ./:/app
    ports:
      - "9001:9001"
    links:
      - pg_db

  pg_db:
    image: postgres
    ports:
      - "5433:5433"
    env_file: 
      - docker.env

ormconfig.json

[
  {
    "name": "default",
    "driver": {
      "type": "postgres",
      "host": "pg_db",
      "port": 5433,
      "username": "postgres",
      "password": "test",
      "database": "testDB"
    },
    "autoSchemaSync": true,
    "entities": [
      "src/controller/entity/*.js"
    ],
    "cli": {
      "entitiesDir": "src/controller/entity"
    }
  }
]

Thanks


Source: (StackOverflow)

TypeORM not creating tables, columns etc

I have set up a system with typeorm (https://github.com/typeorm/typeorm) and NEST (https://github.com/nestjs/nest), but TypeORM isn't creating the tables or columns. My setup is like this:

import {UserPassword} from '../user/user-password.entity';
import {User} from '../user/user.entity';

createConnection({
    type: 'mysql',
    host: 'typeorm2.cn32tstd6wqk.eu-central-1.rds.amazonaws.com',
    port: 1234,
    username: 'username',
    password: 'password',
    database: 'dbname',
    entities: [
      // __dirname + '/../**/*.entity{.ts,.js}'
      UserPassword,
      User
    ]
  })

And the entities are:

import {Entity, Column, PrimaryGeneratedColumn, OneToOne, JoinColumn} from 'typeorm';

@Entity()
export class UserPassword {

  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  hash: string;

  @Column()
  algorithm: string;

}

and

import {Entity, Column, PrimaryGeneratedColumn, OneToOne, JoinColumn} from 'typeorm';
import {UserPassword} from './user-password.entity';

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ length: 35 })
  firstName: string;

  @Column({ length: 35 })
  lastName: string;

  @Column({ length: 50})
  mail: string;

  @OneToOne(type => UserPassword)
  @JoinColumn()
  password: UserPassword;

}

Then I try to create a user like this:

// ... some code
await this.userPasswordRepository.save(userPassword);
return await this.userRepository.save(user);

But I get the following error:

QueryFailedError: ER_NO_SUCH_TABLE: Table 'typeorm2.user_password' doesn't exist

When I insert the table manually then I get the error:

QueryFailedError: ER_BAD_FIELD_ERROR: Unknown column 'hash' in 'field list'

So it seems like typeorm doesn't generate the tables / columns. Does anyone know why this could be?


Source: (StackOverflow)

typeorm: How to do a RIGHT JOIN and SELECT

How does one do the following query using typeorm please

SELECT *
FROM "UserStrength"
RIGHT JOIN "Strength" ON "Strength"."id" = "UserStrength"."strengthId"

Where the UserStrengthEntity is defined as:

@Entity("UserStrength")
export class UserStrengthEntity extends BaseEntity implements IUserStrength {
    @Column({default: false}) isCompleted: boolean;

    @ManyToOne(type => UserEntity, user => user.userStrengthArray, {
        cascadeAll: true
    })
    @JoinColumn({name: "userId"})
    user: UserEntity;

    @OneToMany(type => UserStrengthItemEntity, userStrengthItem => userStrengthItem.userStrength, {
        cascadeInsert: true,
        cascadeUpdate: true
    })
    userStrengthItemArray?: UserStrengthItemEntity[];

    @ManyToOne(type => StrengthEntity, strength => strength.userStrengthArray, {
        cascadeAll: true
    })
    @JoinColumn({name: "strengthId"})
    strength: StrengthEntity;
}

and the StrengthEntity is:

@Entity("Strength")
export class StrengthEntity extends BaseEntity implements IStrength {
    @Column({length: 50}) name: string;
    @Column({length: 100}) title: string;
    @Column() strengthType: StrengthType;
    @Column({length: 10, nullable: true}) titleColor: string;
    @Column({nullable: true}) titleIcon: string;

    @ManyToOne(type => ClientEntity, clientEntity => clientEntity.strengthArray, {
        cascadeAll: true
    })
    @JoinColumn({name: "clientId"}) client: ClientEntity

    @OneToMany(type => StrengthItemEntity, strengthItem => strengthItem.strength, {
        cascadeInsert: true,
        cascadeUpdate: true
    })
    strengthItemArray: StrengthItemEntity[];

    @OneToMany(type => UserStrengthEntity, userStrength => userStrength.strength, {
        cascadeInsert: true,
        cascadeUpdate: true
    })
    userStrengthArray: UserStrengthEntity[];
}

I want to load a UserStrength which may or may not exist along with the Strength with a given strengthType (I would also need to RIGHT JOIN to the UserEntity to further filter by UserEntity.id)

Could anyone explain how this is accomplished with typeorm please?


Source: (StackOverflow)

TypeOrm - Update with OneToOne join attempts to delete related record

I have a project which uses TypeORM and I have the following two entities

@Entity("Email")
export class EmailEntity extends BaseEntity implements IEmail {
    @Column({length: 100}) to: string;
    @Column({length: 100}) from: string;
    @Column({length: 255}) subject: string;
    @Column({nullable: true}) html: string;
    @Column({nullable: true}) text: string;
}

and

@Entity("QueuedEmail")
export class QueuedEmailEntity extends BaseEntity implements IQueuedEmail {
    @OneToOne(email => EmailEntity, {nullable: false, cascadeAll: true})
    @JoinColumn()
    email: EmailEntity;

    @Column() retryCount: number;
    @Column() status: QueuedEmailStatus;

    constructor() {
        super();
        this.retryCount = 0;
        this.status = QueuedEmailStatus.QueuedForDispatch;
    }
}

BaseEntity is an abstract class which has an id column with the @PrimaryGeneratedColumn

I have the following code which updates the status on a QueuedEmail

const queuedEmailEntityArray: QueuedEmailEntity[] =
    await this.queuedEmailRepository.createQueryBuilder("queuedEmail")
        .where("queuedEmail.status = :queuedEmailStatus", {queuedEmailStatus: QueuedEmailStatus.QueuedForDispatch})
        .innerJoinAndSelect("queuedEmail.email", "email")
        .orderBy("queuedEmail.id", "DESC")
        .getMany();

queuedEmailEntityArray.forEach(async (value, index) => {
    let queuedEmailEntity: QueuedEmailEntity = queuedEmailEntityArray.pop();
    queuedEmailEntity.status = QueuedEmailStatus.AttemptingToDispatch;
    await this.queuedEmailRepository.persist(queuedEmailEntity);
});

Now, the select correctly loads the array or QueuedEmailEntity objects, the foreach runs but throws the following exception

query failed: DELETE FROM "Email" WHERE "id"=$1 -- PARAMETERS: [1]
error during executing query:error: update or delete on table "Email" violates foreign key constraint "fk_d438362cf2adecbcc5b17f45606" on table "QueuedEmail"

The debug query output shows that TypeORM is updating the status field but also updating the emailId' and then attempting to delete theEmailEntity` record

UPDATE "QueuedEmail" SET "status"=$1, "emailId"=$2 WHERE "id"=$3 -- PARAMETERS: [1,1,1]
DELETE FROM "Email" WHERE "id"=$1 -- PARAMETERS: [1]

I don't understand why TypeORM would need to update the emailId field when I have not changed the reference, much less why it would try to delete a record that is still referenced. can anyone see what is wrong with the above code?


Source: (StackOverflow)

TypeError: Class extends value undefined is not a function or null

I am getting the following error when trying to create these entities.

TypeError: Class extends value undefined is not a function or null

I am assuming this has something to do with circular dependencies, but how is that supposed to be avoided when using table inheritance and one to many relationships?

It is complaining about the following javascript at BaseComic_1.BaseComic.

let Variant = class Variant extends BaseComic_1.BaseComic {

Here is the complete file.

"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
const typeorm_1 = require("typeorm");
const Comic_1 = require("./Comic");
const BaseComic_1 = require("./BaseComic");
let Variant = class Variant extends BaseComic_1.BaseComic {
};
__decorate([
    typeorm_1.ManyToOne(type => Comic_1.Comic, comic => comic.variants),
    __metadata("design:type", Comic_1.Comic)
], Variant.prototype, "comic", void 0);
Variant = __decorate([
    typeorm_1.ClassEntityChild()
], Variant);
exports.Variant = Variant;
//# sourceMappingURL=Variant.js.map

import {Entity, Column, PrimaryGeneratedColumn, OneToMany} from "typeorm";
import {Comic} from "./Comic";

@Entity()
export class Series {

    @PrimaryGeneratedColumn()
    public id: number;

    @Column("text", {
        length: 30
    })
    public copyright: string;

    @Column("text", {
        length: 100
    })
    public attributionText: string;

    @Column("text", {
        length: 150
    })
    public attributionHTML: string;

    @Column("text", {
        length: 50
    })
    public etag: string;

    @Column("text", {
        length: 200
    })
    public title: string;

    @Column("text")
    public description: string;

    @Column("number", {
        length: 4
    })
    public startYear: number;

    @Column("number", {
        length: 4
    })
    public endYear: number;

    @Column("text", {
        length: 20
    })
    public rating: string;

    @Column("text", {
        length: 20
    })
    public type: string;

    @Column("text")
    public thumbnail: string;

    @OneToMany(type => Comic, comic => comic.series)
    public comics: Array<Comic>;
}

import {Entity, TableInheritance, PrimaryGeneratedColumn, Column, ManyToOne, DiscriminatorColumn} from "typeorm";
import {Series} from "./Series";

@Entity()
@TableInheritance("class-table")
@DiscriminatorColumn({ name: "type", type: "string"})
export class BaseComic {

    @PrimaryGeneratedColumn()
    public id: number;

    @Column("text", {
        length: 30
    })
    public copyright: string;

    @Column("text", {
        length: 100
    })
    public attributionText: string;

    @Column("text", {
        length: 150
    })
    public attributionHTML: string;

    @Column("text", {
        length: 50
    })
    public etag: string;

    @Column("text", {
        length: 200
    })
    public title: string;

    @Column("int")
    public issue: number;

    @Column("text")
    public variantDescription: string;

    @Column("boolean")
    public variant: boolean;

    @Column("text")
    public description: string;

    @Column("int")
    public pageCount: number;

    @Column("date")
    public onSaleDate: Date;

    @Column("date")
    public unlimitedDate: Date;

    @Column("text")
    public thumbnail: string;

    @ManyToOne(type => Series, series => series.comics)
    public series: Series;
}

import {OneToMany, ClassEntityChild} from "typeorm";
import {Variant} from "./Variant";
import {BaseComic} from "./BaseComic";

@ClassEntityChild()
export class Comic extends BaseComic {

    @OneToMany(type => Variant, variant => variant.comic)
    public variants: Variant[];
}

import {ManyToOne, ClassEntityChild} from "typeorm";
import {Comic} from "./Comic";
import {BaseComic} from "./BaseComic";

@ClassEntityChild()
export class Variant extends BaseComic {

    @ManyToOne(type => Comic, comic => comic.variants)
    public comic: Comic;
}

Source: (StackOverflow)