Giter Club home page Giter Club logo

typeorm / typeorm Goto Github PK

View Code? Open in Web Editor NEW
33.3K 33.3K 6.2K 26.65 MB

ORM for TypeScript and JavaScript. Supports MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, SAP Hana, WebSQL databases. Works in NodeJS, Browser, Ionic, Cordova and Electron platforms.

Home Page: http://typeorm.io

License: MIT License

TypeScript 99.83% JavaScript 0.17% Dockerfile 0.01%
active-record cockroachdb data-mapper database electron hacktoberfest javascript mariadb mysql oracle orm postgresql react-native sap sap-hana sqlite sqlserver typeorm typescript websql

typeorm's Introduction

TypeORM is an ORM that can run in NodeJS, Browser, Cordova, PhoneGap, Ionic, React Native, NativeScript, Expo, and Electron platforms and can be used with TypeScript and JavaScript (ES2021). Its goal is to always support the latest JavaScript features and provide additional features that help you to develop any kind of application that uses databases - from small applications with a few tables to large-scale enterprise applications with multiple databases.

TypeORM supports both Active Record and Data Mapper patterns, unlike all other JavaScript ORMs currently in existence, which means you can write high-quality, loosely coupled, scalable, maintainable applications in the most productive way.

TypeORM is highly influenced by other ORMs, such as Hibernate, Doctrine and Entity Framework.

Features

  • Supports both DataMapper and ActiveRecord (your choice).
  • Entities and columns.
  • Database-specific column types.
  • Entity manager.
  • Repositories and custom repositories.
  • Clean object-relational model.
  • Associations (relations).
  • Eager and lazy relations.
  • Uni-directional, bi-directional, and self-referenced relations.
  • Supports multiple inheritance patterns.
  • Cascades.
  • Indices.
  • Transactions.
  • Migrations and automatic migrations generation.
  • Connection pooling.
  • Replication.
  • Using multiple database instances.
  • Working with multiple database types.
  • Cross-database and cross-schema queries.
  • Elegant-syntax, flexible and powerful QueryBuilder.
  • Left and inner joins.
  • Proper pagination for queries using joins.
  • Query caching.
  • Streaming raw results.
  • Logging.
  • Listeners and subscribers (hooks).
  • Supports closure table pattern.
  • Schema declaration in models or separate configuration files.
  • Supports MySQL / MariaDB / Postgres / CockroachDB / SQLite / Microsoft SQL Server / Oracle / SAP Hana / sql.js.
  • Supports MongoDB NoSQL database.
  • Works in NodeJS / Browser / Ionic / Cordova / React Native / NativeScript / Expo / Electron platforms.
  • TypeScript and JavaScript support.
  • ESM and CommonJS support.
  • Produced code is performant, flexible, clean, and maintainable.
  • Follows all possible best practices.
  • CLI.

And more...

With TypeORM your models look like this:

import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"

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

    @Column()
    firstName: string

    @Column()
    lastName: string

    @Column()
    age: number
}

And your domain logic looks like this:

const userRepository = MyDataSource.getRepository(User)

const user = new User()
user.firstName = "Timber"
user.lastName = "Saw"
user.age = 25
await userRepository.save(user)

const allUsers = await userRepository.find()
const firstUser = await userRepository.findOneBy({
    id: 1,
}) // find by id
const timber = await userRepository.findOneBy({
    firstName: "Timber",
    lastName: "Saw",
}) // find by firstName and lastName

await userRepository.remove(timber)

Alternatively, if you prefer to use the ActiveRecord implementation, you can use it as well:

import { Entity, PrimaryGeneratedColumn, Column, BaseEntity } from "typeorm"

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

    @Column()
    firstName: string

    @Column()
    lastName: string

    @Column()
    age: number
}

And your domain logic will look this way:

const user = new User()
user.firstName = "Timber"
user.lastName = "Saw"
user.age = 25
await user.save()

const allUsers = await User.find()
const firstUser = await User.findOneBy({
    id: 1,
})
const timber = await User.findOneBy({
    firstName: "Timber",
    lastName: "Saw"
})

await timber.remove()

Installation

  1. Install the npm package:

    npm install typeorm --save

  2. You need to install reflect-metadata shim:

    npm install reflect-metadata --save

    and import it somewhere in the global place of your app (for example in app.ts):

    import "reflect-metadata"

  3. You may need to install node typings:

    npm install @types/node --save-dev

  4. Install a database driver:

    • for MySQL or MariaDB

      npm install mysql --save (you can install mysql2 instead as well)

    • for PostgreSQL or CockroachDB

      npm install pg --save

    • for SQLite

      npm install sqlite3 --save

    • for Microsoft SQL Server

      npm install mssql --save

    • for sql.js

      npm install sql.js --save

    • for Oracle

      npm install oracledb --save

      To make the Oracle driver work, you need to follow the installation instructions from their site.

    • for SAP Hana

      npm install @sap/hana-client
      npm install hdb-pool
      

      SAP Hana support made possible by the sponsorship of Neptune Software.

    • for Google Cloud Spanner

      npm install @google-cloud/spanner --save
      

      Provide authentication credentials to your application code by setting the environment variable GOOGLE_APPLICATION_CREDENTIALS:

      # Linux/macOS
      export GOOGLE_APPLICATION_CREDENTIALS="KEY_PATH"
      
      # Windows
      set GOOGLE_APPLICATION_CREDENTIALS=KEY_PATH
      
      # Replace KEY_PATH with the path of the JSON file that contains your service account key.

      To use Spanner with the emulator you should set SPANNER_EMULATOR_HOST environment variable:

      # Linux/macOS
      export SPANNER_EMULATOR_HOST=localhost:9010
      
      # Windows
      set SPANNER_EMULATOR_HOST=localhost:9010
    • for MongoDB (experimental)

      npm install mongodb@^5.2.0 --save

    • for NativeScript, react-native and Cordova

      Check documentation of supported platforms

    Install only one of them, depending on which database you use.

TypeScript configuration

Also, make sure you are using TypeScript version 4.5 or higher, and you have enabled the following settings in tsconfig.json:

"emitDecoratorMetadata": true,
"experimentalDecorators": true,

You may also need to enable es6 in the lib section of compiler options, or install es6-shim from @types.

Quick Start

The quickest way to get started with TypeORM is to use its CLI commands to generate a starter project. Quick start works only if you are using TypeORM in a NodeJS application. If you are using other platforms, proceed to the step-by-step guide.

To create a new project using CLI, run the following command:

npx typeorm init --name MyProject --database postgres

Where name is the name of your project and database is the database you'll use. Database can be one of the following values: mysql, mariadb, postgres, cockroachdb, sqlite, mssql, sap, spanner, oracle, mongodb, cordova, react-native, expo, nativescript.

This command will generate a new project in the MyProject directory with the following files:

MyProject
├── src                   // place of your TypeScript code
│   ├── entity            // place where your entities (database models) are stored
│   │   └── User.ts       // sample entity
│   ├── migration         // place where your migrations are stored
│   ├── data-source.ts    // data source and all connection configuration
│   └── index.ts          // start point of your application
├── .gitignore            // standard gitignore file
├── package.json          // node module dependencies
├── README.md             // simple readme file
└── tsconfig.json         // TypeScript compiler options

You can also run typeorm init on an existing node project, but be careful - it may override some files you already have.

The next step is to install new project dependencies:

cd MyProject
npm install

After you have all dependencies installed, edit the data-source.ts file and put your own database connection configuration options in there:

export const AppDataSource = new DataSource({
    type: "postgres",
    host: "localhost",
    port: 5432,
    username: "test",
    password: "test",
    database: "test",
    synchronize: true,
    logging: true,
    entities: [Post, Category],
    subscribers: [],
    migrations: [],
})

Particularly, most of the time you'll only need to configure host, username, password, database and maybe port options.

Once you finish with configuration and all node modules are installed, you can run your application:

npm start

That's it, your application should successfully run and insert a new user into the database. You can continue to work with this project and integrate other modules you need and start creating more entities.

You can generate an ESM project by running npx typeorm init --name MyProject --database postgres --module esm command.

You can generate an even more advanced project with express installed by running npx typeorm init --name MyProject --database mysql --express command.

You can generate a docker-compose file by running npx typeorm init --name MyProject --database postgres --docker command.

Step-by-Step Guide

What are you expecting from ORM? First of all, you are expecting it will create database tables for you and find / insert / update / delete your data without the pain of having to write lots of hardly maintainable SQL queries. This guide will show you how to set up TypeORM from scratch and make it do what you are expecting from an ORM.

Create a model

Working with a database starts with creating tables. How do you tell TypeORM to create a database table? The answer is - through the models. Your models in your app are your database tables.

For example, you have a Photo model:

export class Photo {
    id: number
    name: string
    description: string
    filename: string
    views: number
    isPublished: boolean
}

And you want to store photos in your database. To store things in the database, first, you need a database table, and database tables are created from your models. Not all models, but only those you define as entities.

Create an entity

Entity is your model decorated by an @Entity decorator. A database table will be created for such models. You work with entities everywhere in TypeORM. You can load/insert/update/remove and perform other operations with them.

Let's make our Photo model an entity:

import { Entity } from "typeorm"

@Entity()
export class Photo {
    id: number
    name: string
    description: string
    filename: string
    views: number
    isPublished: boolean
}

Now, a database table will be created for the Photo entity and we'll be able to work with it anywhere in our app. We have created a database table, however, what table can exist without columns? Let's create a few columns in our database table.

Adding table columns

To add database columns, you simply need to decorate an entity's properties you want to make into a column with a @Column decorator.

import { Entity, Column } from "typeorm"

@Entity()
export class Photo {
    @Column()
    id: number

    @Column()
    name: string

    @Column()
    description: string

    @Column()
    filename: string

    @Column()
    views: number

    @Column()
    isPublished: boolean
}

Now id, name, description, filename, views, and isPublished columns will be added to the photo table. Column types in the database are inferred from the property types you used, e.g. number will be converted into integer, string into varchar, boolean into bool, etc. But you can use any column type your database supports by explicitly specifying a column type into the @Column decorator.

We generated a database table with columns, but there is one thing left. Each database table must have a column with a primary key.

Creating a primary column

Each entity must have at least one primary key column. This is a requirement and you can't avoid it. To make a column a primary key, you need to use the @PrimaryColumn decorator.

import { Entity, Column, PrimaryColumn } from "typeorm"

@Entity()
export class Photo {
    @PrimaryColumn()
    id: number

    @Column()
    name: string

    @Column()
    description: string

    @Column()
    filename: string

    @Column()
    views: number

    @Column()
    isPublished: boolean
}

Creating an auto-generated column

Now, let's say you want your id column to be auto-generated (this is known as auto-increment / sequence / serial / generated identity column). To do that, you need to change the @PrimaryColumn decorator to a @PrimaryGeneratedColumn decorator:

import { Entity, Column, PrimaryGeneratedColumn } from "typeorm"

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

    @Column()
    name: string

    @Column()
    description: string

    @Column()
    filename: string

    @Column()
    views: number

    @Column()
    isPublished: boolean
}

Column data types

Next, let's fix our data types. By default, the string is mapped to a varchar(255)-like type (depending on the database type). The number is mapped to an integer-like type (depending on the database type). We don't want all our columns to be limited varchars or integers. Let's setup the correct data types:

import { Entity, Column, PrimaryGeneratedColumn } from "typeorm"

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

    @Column({
        length: 100,
    })
    name: string

    @Column("text")
    description: string

    @Column()
    filename: string

    @Column("double")
    views: number

    @Column()
    isPublished: boolean
}

Column types are database-specific. You can set any column type your database supports. More information on supported column types can be found here.

Creating a new DataSource

Now, when our entity is created, let's create index.ts file and set up our DataSource there:

import "reflect-metadata"
import { DataSource } from "typeorm"
import { Photo } from "./entity/Photo"

const AppDataSource = new DataSource({
    type: "postgres",
    host: "localhost",
    port: 5432,
    username: "root",
    password: "admin",
    database: "test",
    entities: [Photo],
    synchronize: true,
    logging: false,
})

// to initialize the initial connection with the database, register all entities
// and "synchronize" database schema, call "initialize()" method of a newly created database
// once in your application bootstrap
AppDataSource.initialize()
    .then(() => {
        // here you can start to work with your database
    })
    .catch((error) => console.log(error))

We are using Postgres in this example, but you can use any other supported database. To use another database, simply change the type in the options to the database type you are using: mysql, mariadb, postgres, cockroachdb, sqlite, mssql, oracle, sap, spanner, cordova, nativescript, react-native, expo, or mongodb. Also make sure to use your own host, port, username, password, and database settings.

We added our Photo entity to the list of entities for this data source. Each entity you are using in your connection must be listed there.

Setting synchronize makes sure your entities will be synced with the database, every time you run the application.

Running the application

Now if you run your index.ts, a connection with the database will be initialized and a database table for your photos will be created.

+-------------+--------------+----------------------------+
|                         photo                           |
+-------------+--------------+----------------------------+
| id          | int(11)      | PRIMARY KEY AUTO_INCREMENT |
| name        | varchar(100) |                            |
| description | text         |                            |
| filename    | varchar(255) |                            |
| views       | int(11)      |                            |
| isPublished | boolean      |                            |
+-------------+--------------+----------------------------+

Creating and inserting a photo into the database

Now let's create a new photo to save it in the database:

import { Photo } from "./entity/Photo"
import { AppDataSource } from "./index"

const photo = new Photo()
photo.name = "Me and Bears"
photo.description = "I am near polar bears"
photo.filename = "photo-with-bears.jpg"
photo.views = 1
photo.isPublished = true

await AppDataSource.manager.save(photo)
console.log("Photo has been saved. Photo id is", photo.id)

Once your entity is saved it will get a newly generated id. save method returns an instance of the same object you pass to it. It's not a new copy of the object, it modifies its "id" and returns it.

Using Entity Manager

We just created a new photo and saved it in the database. We used EntityManager to save it. Using entity manager you can manipulate any entity in your app. For example, let's load our saved entity:

import { Photo } from "./entity/Photo"
import { AppDataSource } from "./index"

const savedPhotos = await AppDataSource.manager.find(Photo)
console.log("All photos from the db: ", savedPhotos)

savedPhotos will be an array of Photo objects with the data loaded from the database.

Learn more about EntityManager here.

Using Repositories

Now let's refactor our code and use Repository instead of EntityManager. Each entity has its own repository which handles all operations with its entity. When you deal with entities a lot, Repositories are more convenient to use than EntityManagers:

import { Photo } from "./entity/Photo"
import { AppDataSource } from "./index"

const photo = new Photo()
photo.name = "Me and Bears"
photo.description = "I am near polar bears"
photo.filename = "photo-with-bears.jpg"
photo.views = 1
photo.isPublished = true

const photoRepository = AppDataSource.getRepository(Photo)

await photoRepository.save(photo)
console.log("Photo has been saved")

const savedPhotos = await photoRepository.find()
console.log("All photos from the db: ", savedPhotos)

Learn more about Repository here.

Loading from the database

Let's try more load operations using the Repository:

import { Photo } from "./entity/Photo"
import { AppDataSource } from "./index"

const photoRepository = AppDataSource.getRepository(Photo)
const allPhotos = await photoRepository.find()
console.log("All photos from the db: ", allPhotos)

const firstPhoto = await photoRepository.findOneBy({
    id: 1,
})
console.log("First photo from the db: ", firstPhoto)

const meAndBearsPhoto = await photoRepository.findOneBy({
    name: "Me and Bears",
})
console.log("Me and Bears photo from the db: ", meAndBearsPhoto)

const allViewedPhotos = await photoRepository.findBy({ views: 1 })
console.log("All viewed photos: ", allViewedPhotos)

const allPublishedPhotos = await photoRepository.findBy({ isPublished: true })
console.log("All published photos: ", allPublishedPhotos)

const [photos, photosCount] = await photoRepository.findAndCount()
console.log("All photos: ", photos)
console.log("Photos count: ", photosCount)

Updating in the database

Now let's load a single photo from the database, update it and save it:

import { Photo } from "./entity/Photo"
import { AppDataSource } from "./index"

const photoRepository = AppDataSource.getRepository(Photo)
const photoToUpdate = await photoRepository.findOneBy({
    id: 1,
})
photoToUpdate.name = "Me, my friends and polar bears"
await photoRepository.save(photoToUpdate)

Now photo with id = 1 will be updated in the database.

Removing from the database

Now let's remove our photo from the database:

import { Photo } from "./entity/Photo"
import { AppDataSource } from "./index"

const photoRepository = AppDataSource.getRepository(Photo)
const photoToRemove = await photoRepository.findOneBy({
    id: 1,
})
await photoRepository.remove(photoToRemove)

Now photo with id = 1 will be removed from the database.

Creating a one-to-one relation

Let's create a one-to-one relationship with another class. Let's create a new class in PhotoMetadata.ts. This PhotoMetadata class is supposed to contain our photo's additional meta-information:

import {
    Entity,
    Column,
    PrimaryGeneratedColumn,
    OneToOne,
    JoinColumn,
} from "typeorm"
import { Photo } from "./Photo"

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

    @Column("int")
    height: number

    @Column("int")
    width: number

    @Column()
    orientation: string

    @Column()
    compressed: boolean

    @Column()
    comment: string

    @OneToOne(() => Photo)
    @JoinColumn()
    photo: Photo
}

Here, we are using a new decorator called @OneToOne. It allows us to create a one-to-one relationship between two entities. type => Photo is a function that returns the class of the entity with which we want to make our relationship. We are forced to use a function that returns a class, instead of using the class directly, because of the language specifics. We can also write it as () => Photo, but we use type => Photo as a convention to increase code readability. The type variable itself does not contain anything.

We also add a @JoinColumn decorator, which indicates that this side of the relationship will own the relationship. Relations can be unidirectional or bidirectional. Only one side of relational can be owning. Using @JoinColumn decorator is required on the owner side of the relationship.

If you run the app, you'll see a newly generated table, and it will contain a column with a foreign key for the photo relation:

+-------------+--------------+----------------------------+
|                     photo_metadata                      |
+-------------+--------------+----------------------------+
| id          | int(11)      | PRIMARY KEY AUTO_INCREMENT |
| height      | int(11)      |                            |
| width       | int(11)      |                            |
| comment     | varchar(255) |                            |
| compressed  | boolean      |                            |
| orientation | varchar(255) |                            |
| photoId     | int(11)      | FOREIGN KEY                |
+-------------+--------------+----------------------------+

Save a one-to-one relation

Now let's save a photo, and its metadata and attach them to each other.

import { Photo } from "./entity/Photo"
import { PhotoMetadata } from "./entity/PhotoMetadata"

// create a photo
const photo = new Photo()
photo.name = "Me and Bears"
photo.description = "I am near polar bears"
photo.filename = "photo-with-bears.jpg"
photo.views = 1
photo.isPublished = true

// create a photo metadata
const metadata = new PhotoMetadata()
metadata.height = 640
metadata.width = 480
metadata.compressed = true
metadata.comment = "cybershoot"
metadata.orientation = "portrait"
metadata.photo = photo // this way we connect them

// get entity repositories
const photoRepository = AppDataSource.getRepository(Photo)
const metadataRepository = AppDataSource.getRepository(PhotoMetadata)

// first we should save a photo
await photoRepository.save(photo)

// photo is saved. Now we need to save a photo metadata
await metadataRepository.save(metadata)

// done
console.log(
    "Metadata is saved, and the relation between metadata and photo is created in the database too",
)

Inverse side of the relationship

Relations can be unidirectional or bidirectional. Currently, our relation between PhotoMetadata and Photo is unidirectional. The owner of the relation is PhotoMetadata, and Photo doesn't know anything about PhotoMetadata. This makes it complicated to access PhotoMetadata from the Photo side. To fix this issue we should add an inverse relation, and make relations between PhotoMetadata and Photo bidirectional. Let's modify our entities:

import {
    Entity,
    Column,
    PrimaryGeneratedColumn,
    OneToOne,
    JoinColumn,
} from "typeorm"
import { Photo } from "./Photo"

@Entity()
export class PhotoMetadata {
    /* ... other columns */

    @OneToOne(() => Photo, (photo) => photo.metadata)
    @JoinColumn()
    photo: Photo
}
import { Entity, Column, PrimaryGeneratedColumn, OneToOne } from "typeorm"
import { PhotoMetadata } from "./PhotoMetadata"

@Entity()
export class Photo {
    /* ... other columns */

    @OneToOne(() => PhotoMetadata, (photoMetadata) => photoMetadata.photo)
    metadata: PhotoMetadata
}

photo => photo.metadata is a function that returns the name of the inverse side of the relation. Here we show that the metadata property of the Photo class is where we store PhotoMetadata in the Photo class. Instead of passing a function that returns a property of the photo, you could alternatively simply pass a string to @OneToOne decorator, like "metadata". But we used this function-typed approach to make our refactoring easier.

Note that we should use the @JoinColumn decorator only on one side of a relation. Whichever side you put this decorator on will be the owning side of the relationship. The owning side of a relationship contains a column with a foreign key in the database.

Relations in ESM projects

If you use ESM in your TypeScript project, you should use the Relation wrapper type in relation properties to avoid circular dependency issues. Let's modify our entities:

import {
    Entity,
    Column,
    PrimaryGeneratedColumn,
    OneToOne,
    JoinColumn,
    Relation,
} from "typeorm"
import { Photo } from "./Photo"

@Entity()
export class PhotoMetadata {
    /* ... other columns */

    @OneToOne(() => Photo, (photo) => photo.metadata)
    @JoinColumn()
    photo: Relation<Photo>
}
import {
    Entity,
    Column,
    PrimaryGeneratedColumn,
    OneToOne,
    Relation,
} from "typeorm"
import { PhotoMetadata } from "./PhotoMetadata"

@Entity()
export class Photo {
    /* ... other columns */

    @OneToOne(() => PhotoMetadata, (photoMetadata) => photoMetadata.photo)
    metadata: Relation<PhotoMetadata>
}

Loading objects with their relations

Now let's load our photo and its photo metadata in a single query. There are two ways to do it - using find* methods or using QueryBuilder functionality. Let's use find* method first. find* methods allow you to specify an object with the FindOneOptions / FindManyOptions interface.

import { Photo } from "./entity/Photo"
import { PhotoMetadata } from "./entity/PhotoMetadata"
import { AppDataSource } from "./index"

const photoRepository = AppDataSource.getRepository(Photo)
const photos = await photoRepository.find({
    relations: {
        metadata: true,
    },
})

Here, photos will contain an array of photos from the database, and each photo will contain its photo metadata. Learn more about Find Options in this documentation.

Using find options is good and dead simple, but if you need a more complex query, you should use QueryBuilder instead. QueryBuilder allows more complex queries to be used in an elegant way:

import { Photo } from "./entity/Photo"
import { PhotoMetadata } from "./entity/PhotoMetadata"
import { AppDataSource } from "./index"

const photos = await AppDataSource.getRepository(Photo)
    .createQueryBuilder("photo")
    .innerJoinAndSelect("photo.metadata", "metadata")
    .getMany()

QueryBuilder allows the creation and execution of SQL queries of almost any complexity. When you work with QueryBuilder, think like you are creating an SQL query. In this example, "photo" and "metadata" are aliases applied to selected photos. You use aliases to access columns and properties of the selected data.

Using cascades to automatically save related objects

We can set up cascade options in our relations, in the cases when we want our related object to be saved whenever the other object is saved. Let's change our photo's @OneToOne decorator a bit:

export class Photo {
    // ... other columns

    @OneToOne(() => PhotoMetadata, (metadata) => metadata.photo, {
        cascade: true,
    })
    metadata: PhotoMetadata
}

Using cascade allows us not to separately save photos and separately save metadata objects now. Now we can simply save a photo object, and the metadata object will be saved automatically because of cascade options.

import { AppDataSource } from "./index"

// create photo object
const photo = new Photo()
photo.name = "Me and Bears"
photo.description = "I am near polar bears"
photo.filename = "photo-with-bears.jpg"
photo.isPublished = true

// create photo metadata object
const metadata = new PhotoMetadata()
metadata.height = 640
metadata.width = 480
metadata.compressed = true
metadata.comment = "cybershoot"
metadata.orientation = "portrait"

photo.metadata = metadata // this way we connect them

// get repository
const photoRepository = AppDataSource.getRepository(Photo)

// saving a photo also save the metadata
await photoRepository.save(photo)

console.log("Photo is saved, photo metadata is saved too.")

Notice that we now set the photo's metadata property, instead of the metadata's photo property as before. The cascade feature only works if you connect the photo to its metadata from the photo's side. If you set the metadata side, the metadata would not be saved automatically.

Creating a many-to-one / one-to-many relation

Let's create a many-to-one/one-to-many relation. Let's say a photo has one author, and each author can have many photos. First, let's create an Author class:

import {
    Entity,
    Column,
    PrimaryGeneratedColumn,
    OneToMany,
    JoinColumn,
} from "typeorm"
import { Photo } from "./Photo"

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

    @Column()
    name: string

    @OneToMany(() => Photo, (photo) => photo.author) // note: we will create author property in the Photo class below
    photos: Photo[]
}

Author contains an inverse side of a relation. OneToMany is always an inverse side of the relation, and it can't exist without ManyToOne on the other side of the relation.

Now let's add the owner side of the relation into the Photo entity:

import { Entity, Column, PrimaryGeneratedColumn, ManyToOne } from "typeorm"
import { PhotoMetadata } from "./PhotoMetadata"
import { Author } from "./Author"

@Entity()
export class Photo {
    /* ... other columns */

    @ManyToOne(() => Author, (author) => author.photos)
    author: Author
}

In many-to-one / one-to-many relations, the owner side is always many-to-one. It means that the class that uses @ManyToOne will store the id of the related object.

After you run the application, the ORM will create the author table:

+-------------+--------------+----------------------------+
|                          author                         |
+-------------+--------------+----------------------------+
| id          | int(11)      | PRIMARY KEY AUTO_INCREMENT |
| name        | varchar(255) |                            |
+-------------+--------------+----------------------------+

It will also modify the photo table, adding a new author column and creating a foreign key for it:

+-------------+--------------+----------------------------+
|                         photo                           |
+-------------+--------------+----------------------------+
| id          | int(11)      | PRIMARY KEY AUTO_INCREMENT |
| name        | varchar(255) |                            |
| description | varchar(255) |                            |
| filename    | varchar(255) |                            |
| isPublished | boolean      |                            |
| authorId    | int(11)      | FOREIGN KEY                |
+-------------+--------------+----------------------------+

Creating a many-to-many relation

Let's create a many-to-many relation. Let's say a photo can be in many albums, and each album can contain many photos. Let's create an Album class:

import {
    Entity,
    PrimaryGeneratedColumn,
    Column,
    ManyToMany,
    JoinTable,
} from "typeorm"

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

    @Column()
    name: string

    @ManyToMany(() => Photo, (photo) => photo.albums)
    @JoinTable()
    photos: Photo[]
}

@JoinTable is required to specify that this is the owner side of the relationship.

Now let's add the inverse side of our relation to the Photo class:

export class Photo {
    // ... other columns

    @ManyToMany(() => Album, (album) => album.photos)
    albums: Album[]
}

After you run the application, the ORM will create a album_photos_photo_albums junction table:

+-------------+--------------+----------------------------+
|                album_photos_photo_albums                |
+-------------+--------------+----------------------------+
| album_id    | int(11)      | PRIMARY KEY FOREIGN KEY    |
| photo_id    | int(11)      | PRIMARY KEY FOREIGN KEY    |
+-------------+--------------+----------------------------+

Don't forget to register the Album class with your connection in the ORM:

const options: DataSourceOptions = {
    // ... other options
    entities: [Photo, PhotoMetadata, Author, Album],
}

Now let's insert albums and photos into our database:

import { AppDataSource } from "./index"

// create a few albums
const album1 = new Album()
album1.name = "Bears"
await AppDataSource.manager.save(album1)

const album2 = new Album()
album2.name = "Me"
await AppDataSource.manager.save(album2)

// create a few photos
const photo = new Photo()
photo.name = "Me and Bears"
photo.description = "I am near polar bears"
photo.filename = "photo-with-bears.jpg"
photo.views = 1
photo.isPublished = true
photo.albums = [album1, album2]
await AppDataSource.manager.save(photo)

// now our photo is saved and albums are attached to it
// now lets load them:
const loadedPhoto = await AppDataSource.getRepository(Photo).findOne({
    where: {
        id: 1,
    },
    relations: {
        albums: true,
    },
})

loadedPhoto will be equal to:

{
    id: 1,
    name: "Me and Bears",
    description: "I am near polar bears",
    filename: "photo-with-bears.jpg",
    albums: [{
        id: 1,
        name: "Bears"
    }, {
        id: 2,
        name: "Me"
    }]
}

Using QueryBuilder

You can use QueryBuilder to build SQL queries of almost any complexity. For example, you can do this:

const photos = await AppDataSource.getRepository(Photo)
    .createQueryBuilder("photo") // first argument is an alias. Alias is what you are selecting - photos. You must specify it.
    .innerJoinAndSelect("photo.metadata", "metadata")
    .leftJoinAndSelect("photo.albums", "album")
    .where("photo.isPublished = true")
    .andWhere("(photo.name = :photoName OR photo.name = :bearName)")
    .orderBy("photo.id", "DESC")
    .skip(5)
    .take(10)
    .setParameters({ photoName: "My", bearName: "Mishka" })
    .getMany()

This query selects all published photos with "My" or "Mishka" names. It will select results from position 5 (pagination offset) and will select only 10 results (pagination limit). The selection result will be ordered by id in descending order. The photo albums will be left joined and their metadata will be inner joined.

You'll use the query builder in your application a lot. Learn more about QueryBuilder here.

Samples

Take a look at the samples in sample for examples of usage.

There are a few repositories that you can clone and start with:

Extensions

There are several extensions that simplify working with TypeORM and integrating it with other modules:

Contributing

Learn about contribution here and how to set up your development environment here.

This project exists thanks to all the people who contribute:

Sponsors

Open source is hard and time-consuming. If you want to invest in TypeORM's future you can become a sponsor and allow our core team to spend more time on TypeORM's improvements and new features. Become a sponsor

Gold Sponsors

Become a gold sponsor and get premium technical support from our core contributors. Become a gold sponsor

typeorm's People

Contributors

abingoal avatar alexmesser avatar bednic avatar championswimmer avatar daniel-lang avatar dependabot[bot] avatar eyalhakim avatar giladgd avatar hajekj14 avatar hmil avatar imnotjames avatar iz-iznogood avatar juddling avatar kononnable avatar luchillo17 avatar matt-neal avatar michallytek avatar mingyang91 avatar mojodna avatar mrkmg avatar pleerock avatar pravdomil avatar rohantalip avatar rustamwin avatar salimlou avatar szbuli avatar tjme avatar typokign avatar v1d3rm3 avatar yehezkielsaputra avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

typeorm's Issues

Empty d.ts files are causing consumer errors due to @internal classes not being emitted

See microsoft/TypeScript#6022 - this may have actually been fixed, but the npm package needs to be recompiled with a later version that includes that fix? I get the following errors (using `typescript@next)

Building ts for [server]
/Users/zak/ubiquits/ubiquits/node_modules/typeorm/query-builder/QueryBuilder.d.ts(1,23): error TS2306: File '/Users/zak/ubiquits/ubiquits/node_modules/typeorm/query-builder/alias/Alias.d.ts' is not a module.
/Users/zak/ubiquits/ubiquits/node_modules/typeorm/repository/Repository.d.ts(4,51): error TS2306: File '/Users/zak/ubiquits/ubiquits/node_modules/typeorm/query-builder/transformer/PlainObjectToNewEntityTransformer.d.ts' is not a module.
/Users/zak/ubiquits/ubiquits/node_modules/typeorm/repository/Repository.d.ts(5,56): error TS2306: File '/Users/zak/ubiquits/ubiquits/node_modules/typeorm/query-builder/transformer/PlainObjectToDatabaseEntityTransformer.d.ts' is not a module.
/Users/zak/ubiquits/ubiquits/node_modules/typeorm/repository/Repository.d.ts(6,47): error TS2306: File '/Users/zak/ubiquits/ubiquits/node_modules/typeorm/persistment/EntityPersistOperationsBuilder.d.ts' is not a module.
/Users/zak/ubiquits/ubiquits/node_modules/typeorm/repository/Repository.d.ts(7,42): error TS2306: File '/Users/zak/ubiquits/ubiquits/node_modules/typeorm/persistment/PersistOperationExecutor.d.ts' is not a module.
[17:55:21] TypeScript: 5 semantic errors

On inspection, those d.ts files reporting errors are empty, and the source files have only classes with @internal jsdoc.

json column type not supported

Hi,

I am trying to save an object into a column. Although the json column type is supported the jsonb column type in (i.e. postgres) is not. Can this please be added?

Cheers

JT

@IdColumn decorator

It would be nice to have an alias @IdColumn for @PrimaryColumn("int", { generated: true }).

It should be easy to do and I think I might be able to do the PR but not know, I have to learn TypeORM better and build some app using it first 😉

Integration with Inversify

Hi, firstly thanks for creating such an awesome project!

I am trying to integrate TypeOrm with Inversify IoC, I am using the useContainer() method but I am really struggling to get my head around how to setup a connection and make it injectable. I know there are good integrations with typedi, however typedi is missing some key features that I need so it's not a viable approach for my use case. Here is what I have tried:

@injectable()
class Orm {

    @inject("Provider<Connection>")
    private connectionProvider: interfaces.Provider<Connection>;

    private connection: Connection; 

    async init() {
        this.connection = await this.connectionProvider();
    }
}

let kernel = new Kernel();
useContainer(kernel);

kernel.bind<interfaces.Provider<Connection>>("Provider<Connection>").toProvider<Connection>((context) => {
    return () => {
        return createConnection({
            driver: {
                type: 'sqlite',
                storage: 'foo.sqlite'
            },
            entities: [
                __dirname + '/entities/*.js'
            ],
            autoSchemaSync: true
        });
    };
});

kernel.bind<ConnectionManager>(ConnectionManager).to(ConnectionManager);
kernel.bind<Orm>(Orm).to(Orm);

let orm = kernel.get<Orm>(Orm);
orm.init().then(() => console.log('DONE')).catch((e) => console.log(e));

The result is the catch handler triggers with the error: Missing required @injectable annotation in: ConnectionManager.

Is it possible to hook up the ConnectionManager to Inversify and make it injectable? Am I missing something obvious and stupid here?

async/await support

Hi! This project looks great. Is there any plan to support (or document, if supported) async/await keywords? For example:

let photoId = 1;
let repository = connection.getRepository(Photo);
photo  = await repository.findById(photoId);

in place of

let photoId = 1;
let repository = connection.getRepository(Photo);
repository.findById(photoId).then(photo => {
    console.log("Photo is loaded: ", photo);
});

Wrong sql syntax when loading lazy relation

I have modified my last example from #46:

let loadedPost = await connection.getRepository(Post).findOneById(3);
console.log(loadedPost);
console.log(await loadedPost.details);

And my Post entity:

@JoinColumn()
@OneToOne(type => PostDetails, { cascadeInsert: true, nullable: true })
details: Promise<PostDetails | null>;

The problem is that await loadedPost.details return wrong PostDetails entity. TypeORM generate this query:
executing query: SELECT details.id AS details_id, details.testField AS details_testField FROM post_details details INNER JOIN post Post ON Post.details=? -- PARAMETERS: [3]
which join one row from post with all rows from post_details and then took only first row from query result. You can see that by running the query SELECT * FROM post_details details INNER JOIN post Post ON Post.details=3.

The correct join syntax should be:
INNER JOIN post Post ON Post.details=details.id WHERE Post.details=? -- PARAMETERS: [3]
or even if it's lazy loading the relation, it could just ommit join and use:
WHERE details.id=? -- PARAMETERS: [3]

Not loading data from @OneToOne relation

There is a problem with loading object from database. The creating and saving works (I looked in the database) but when loading from database it doesn't load the data from relation.

import "reflect-metadata";

import { createConnection } from "typeorm";

import { Post } from "./post";
import { PostDetails } from "./post-details";

async function main() {
    try {
        console.log(`Before connection!`);
        let connection = await createConnection({
            driver: {
                type: "mysql",
                host: "localhost",
                port: 3306,
                username: "root",
                password: "qwerty123",
                database: "typeorm"
            },
            entities: [
                Post, PostDetails
            ],
            logging: {
                logQueries: true,
                logFailedQueryError: true,
            },
            autoSchemaSync: true,
        });
        console.log(`Connected!`);

        let post = new Post();
        post.title = "Title";
        post.text = "Lorem ipsum";
        post.details = new PostDetails();
        post.details.testField = "test";
        console.log(post);
        post = await connection.getRepository(Post).persist(post);
        console.log(post);
        let loadedPost = await connection.getRepository(Post).findOneById(post.id);
        console.log(loadedPost);

        console.log(`Saved ok!`);
        process.exit(0);
    } catch (error) {
        console.log(`Error!`, error);
        process.exit(1);
    }
}

main();

My entities:

import { Table, PrimaryGeneratedColumn, Column, OneToOne, JoinColumn } from "typeorm";
import { PostDetails } from "./post-details";

@Table()
export class Post {
    @PrimaryGeneratedColumn()
    public id: number;

    @Column()
    title: string;

    @Column("text")
    text: string;

    @JoinColumn()
    @OneToOne(type => PostDetails, { cascadeInsert: true, nullable: true })
    details: PostDetails | null;
}
import { Table, PrimaryGeneratedColumn, Column } from "typeorm";

@Table()
export class PostDetails {
    @PrimaryGeneratedColumn()
    public id: number;

    @Column()
    testField: string;
}

Created object looks like this:

Post {
  title: 'Title',
  text: 'Lorem ipsum',
  details: PostDetails { testField: 'test', id: 1 },
  id: 1 }

But it generates sql without joins on relation, so only id is returned not the data:
SELECT post.id AS post_id, post.title AS post_title, post.text AS post_text, post.details AS post_details FROM post post WHERE post.id=? -- PARAMETERS: [1]
So the loaded object has empty details field:

Post { id: 1, title: 'Title', text: 'Lorem ipsum' }

This is a bug or I should add some decorator in PostDetails?

add complete es6/es5 support with examples

Its possible to implement this ORM to work not only with Typescript, but also with es6 and es5. Need help in implementing features that will make it easy for developers to use this library with es6 and es5.

Cordova Sqlite & WebSql Support

I'd like to see some support to use this in Hybrid Mobile Apps with Cordova & Angular2.
I've forked this repository and will be working on a branch of this to support Sqlite on an IOS/Android environment and WebSql so we can support these features. I can definitely see something like this being widely used in the Hybrid Mobile App environment.

I absolutely love the library you've created here. Awesome idea how to create an ORM in Typescript.

Truly reactive repositories with postgres pub/sub

Ok this is a pretty difficult feature request, so bear with me, but postgres has pub/sub capabilities where it can subscribe to table events, and emit them back to the connection.

See this article for a good rundown - https://blog.andyet.com/2015/04/06/postgres-pubsub-with-json

With this integrated into the ReactiveRespository, an observable could be subscribed to, and bound to a websocket in a controller making the backend app effectively a dumb pub/sub proxy to the database.

Now unfortunately there doesn't appear to be equivalent capabilities in MySQL, so that may put a damper on the idea.

Relations with multiple primary keys

I want to model a relation of two entities where the relation has some properties (eg. a Post has a many-to-many relation with Categories, but since the relation has some properties - like order or categerizedAt or whatever property you can imagine for such a relation - I have to introduce a join table I guess.
I have tried to get the correct mapping with typeorm but failed:

  • how to define the primary key in the jointable?
  • persisting fails with [ERROR] [default] - Error: Entity PostCategoryRelation has multiple primary keys. This operation is not supported on entities with multiple primary keys at EntityMetadata.firstPrimaryColumn

First try:

@Table()
export class Post {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    title: string;

    @Column()
    text: string;

    @OneToMany(type => PostCategoryRelation, postCategoryRelation => postCategoryRelation.post)
    categories: PostCategoryRelation[];
}

@Table()
export class PostCategory {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    name: string;

    @OneToMany(type => PostCategoryRelation, postCategoryRelation => postCategoryRelation.category)
    posts: PostCategoryRelation[];
}

@Table()
export class PostCategoryRelation {
  @ManyToOne(type => Post, post => post.categories)
  @PrimaryColumn()
  post: Post;

  @ManyToOne(type => PostCategory, category => category.posts)
  @PrimaryColumn()
  category: PostCategory;

  @Column()
  addedByAdmin: boolean;

  @Column()
  addedByUser: boolean;
}

Did not work since PrimaryKey type cannot be determined.
Next try:

@Table()
export class Post {

  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  title: string;

  @Column()
  text: string;

  @OneToMany(type => PostCategoryRelation, postCategoryRelation => postCategoryRelation.post)
  categories: PostCategoryRelation[];
}

@Table()
export class PostCategory {

  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @OneToMany(type => PostCategoryRelation, postCategoryRelation => postCategoryRelation.category)
  posts: PostCategoryRelation[];
}

@Table()
export class PostCategoryRelation {

  @PrimaryColumn('int', { name: 'id_post' })
  private postRef: number;

  @PrimaryColumn('int', { name: 'id_cat' })
  private catRef: number;

  @ManyToOne(type => Post, post => post.categories)
  @JoinColumn({ name: 'id_post', referencedColumnName: 'id' })
  post: Post;

  @ManyToOne(type => PostCategory, category => category.posts)
  @JoinColumn({ name: 'id_cat', referencedColumnName: 'id' })
  category: PostCategory;

  @Column()
  addedByAdmin: boolean;

  @Column()
  addedByUser: boolean;
}

Now I get the above mentioned [ERROR] [default] - Error: Entity PostCategoryRelation has multiple primary keys. This operation is not supported on entities with multiple primary keys at EntityMetadata.firstPrimaryColumn

What is the right way to model this?

Schema generation fails silently when @PrimaryColumn is ommitted

I have the following working entity:

export class AddressDbSchema implements AddressDTO {
    @PrimaryColumn()
    public _id?: string;
    @Column()
    public address1: string;
    @Column()
    public address2?: string;
    @Column()
    public city: string;
    @Column()
    public state: string;
    @Column()
    public zip: string;
    @Column()
    public country: string;
}

Here's the calling code:

export class AddressRepositoryImplDb implements AddressRepository {
    private addressRepository: Repository<AddressDbSchema>;

    constructor() {
        this.connect().then(async connection => {
            this.addressRepository = connection.getRepository(AddressDbSchema);
        });
    }

    public async findAll(): Promise<Array<AddressDTO>> {
        return await this.addressRepository.find();
    }

    public async create(addressDTO: AddressDTO): Promise<AddressDTO> {
        return await this.addressRepository.persist(addressDTO);
    }

    public async update(addressDTO: AddressDTO): Promise<AddressDTO> {
        return await this.addressRepository.persist(addressDTO);
    }

    public async find(id: string): Promise<AddressDTO> {
        return await this.addressRepository.findOneById(id);
    }

    private connect(): Promise<Connection> {
        return createConnection({
            driver: {
                type: 'sqlite',
                storage: 'tmp/sqlitedb.db'
            },
            logging: {
                logQueries: true,
                logSchemaCreation: true
            },
            autoSchemaSync: true,
            entities: [
                AddressDbSchema
            ]
        });
    }
}

If I modify the entity to look like this, schema generation fails, but I get no error messages.

export class AddressDbSchema implements AddressDTO {
    @Column()
    public _id?: string;
    @Column()
    public address1: string;
    @Column()
    public address2?: string;
    @Column()
    public city: string;
    @Column()
    public state: string;
    @Column()
    public zip: string;
    @Column()
    public country: string;
}

Cannot read property 'name' of undefined

Hi,

I'm using postgres as my backend and I have a simple entity that I am trying to create. To keep it simple I have removed all of my relationships.

import {Table, PrimaryColumn, Column} from 'typeorm';

@Table("USER")
export class UserDB {

    @PrimaryColumn('int', { generated: true })
    id: number;

    @Column('string', {name: 'USERNAME', length: '50'})
    username: string;

    @Column('string', {name: 'PASSWORD', length: '50'})
    password: string;

    @Column('string', {name: 'LAST_NAME', length: '50'})
    lastName: string;

    @Column('string', {name: 'FIRST_NAME', length: '50'})
    firstName: string;

    @Column('string', {name: 'EMAIL', length: '250'})
    email: string;

    @Column('string', {name: 'PHONE_NUMBER', length: '20'})
    phoneNumber: string;

}

I seem to be connecting to the server OK using this code:

let dbHost = process.env.DB_HOST || 'localhost'
        let dbPort = process.env.DB_PORT || 5432;
        let dbName = process.env.DB_NAME || 'TEST_DB';
        let dbUserName = process.env.DB_PASS || 'testuser';
        let dbPassword = process.env.DB_USER || 'testpw';

        const options: ConnectionOptions = {
            driver: {
                type: 'postgres', // specify driver type here.
                host: dbHost,
                port: dbPort,
                username: dbUserName,
                password: dbPassword,
                database: dbName
            },
            autoSchemaCreate: true,
            entities: [UserDB],
            logging: {
                logQueries: true,
                logSchemaCreation: true
            }
            // entityDirectories: ['./server/model/**/{*.ts,*.js}'],
            // subscriberDirectories: ['./server/subscriber/**/{*.ts,*.js}']
        };

        createConnection(options).then(connection => {

            // at this point you are connected to the database, and you can
            // perform queries

        }).catch(error => console.log('Error during connection to the db: ', error));

After running this I receive the following error.

/Users/jt/Documents/workspace/tester/node_modules/typeorm/metadata/types/ColumnTypes.js:64
        return type.name.toLowerCase();
                   ^

TypeError: Cannot read property 'name' of undefined
    at Function.typeToString (/Users/jt/Documents/workspace/tester/node_modules/typeorm/metadata/types/ColumnTypes.js:64:20)
    at /Users/jt/Documents/workspace/tester/node_modules/typeorm/decorator/columns/PrimaryColumn.js:20:57
    at DecoratePropertyWithoutDescriptor (/Users/jt/Documents/workspace/tester/node_modules/reflect-metadata/Reflect.js:555:13)
    at Object.decorate (/Users/jt/Documents/workspace/tester/node_modules/reflect-metadata/Reflect.js:108:20)
    at __decorate (/Users/jt/Documents/workspace/tester/src/server/model/user.db.js:4:92)
    at /Users/jt/Documents/workspace/tester/src/server/model/user.db.js:12:5
    at Object.<anonymous> (/Users/jt/Documents/workspace/tester/src/server/model/user.db.js:37:2)
    at Module._compile (module.js:556:32)
    at Object.Module._extensions..js (module.js:565:10)
    at Module.load (module.js:473:32)
events.js:160
      throw er; // Unhandled 'error' event
      ^

Is this an issue or have I configured things incorrectly? Is there a workaround?

Many thanks

JT

Eager load relations?

Hey pleerock, been exploring your library for a bit now and can't seem to figure out how to have an entity's relations returned alongside it, at least, generically at any rate. my entityManager.findOne() is returning the entity without even a reference to the relation.

Critical error! Wrong SQL syntax on cascade insert

Here is my index.ts:

import "reflect-metadata";

import { createConnection } from "typeorm";

import { Test } from "./test";
import { Product } from "./product";
import { User } from "./user";
import { Company } from "./company";
import { Category } from "./category";

async function main() {
    try {
        console.log(`Before connection!`);
        let connection = await createConnection({
            driver: {
                type: "mysql",
                host: "localhost",
                port: 3306,
                username: "root",
                password: "qwerty123",
                database: "typeorm"
            },
            entities: [
                Category, Company, Product, Test, User
            ],
            logging: {
                logQueries: true,
                logFailedQueryError: true,
            },
            autoSchemaSync: true,
        });

        console.log(`Connected!`);

        let user1 = new User();
        user1.name = "User1";
        user1.password = "qwerty";

        let category1 = new Category();
        category1.name = "Category1";
        category1.user = user1;

        let product1 = new Product();
        product1.name = "Product1";
        product1.description = "Description";
        product1.category = category1;

        let productRepository = connection.getRepository(Product);
        product1 = await productRepository.persist(product1);
        console.log(`Saved ok!`, product1);

        let category2 = new Category();
        category2.name = "Category2";
        category2.user = user1;
        let product2 = new Product();
        product2.name = "New Product 2";
        product2.description = "Description 2";
        product2.category = category2;

        product2 = await productRepository.persist(product2);
        console.log(`Saved ok!`, product2);
    } catch (error) {
        console.log(`Error!`, error);
    }
}

main();

And my entities:

import { Table, PrimaryGeneratedColumn, Column } from "typeorm";

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

    @Column()
    public name: string;

    @Column()
    public password: string;
}
import { User } from "./user";

import { Table, PrimaryGeneratedColumn, Column, ManyToOne } from "typeorm";

@Table()
export class Category {
    @PrimaryGeneratedColumn()
    public id: number;

    @Column()
    public name: string;

    @ManyToOne(type => User, { cascadeInsert: true })
    public user: User;
}
import { Category } from "./category";

import { Table, PrimaryGeneratedColumn, Column, ManyToOne } from "typeorm";

@Table()
export class Product {
    @PrimaryGeneratedColumn()
    public id: number;

    @Column()
    public name: string;

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

    @ManyToOne(type => Category, { cascadeInsert: true })
    public category: Category;
}

The first insert has wrong syntax:

executing query: START TRANSACTION
executing query: INSERT INTO product(name, description, category) VALUES (?,?,?) -- PARAMETERS: ["Product1","Description",null]
executing query: INSERT INTO category(name, user) VALUES (?,?) -- PARAMETERS: ["Category1",null]
executing query: INSERT INTO user(name, password) VALUES (?,?) -- PARAMETERS: ["User1","qwerty"]
executing query: UPDATE product SET category=?  -- PARAMETERS: [4]
executing query: UPDATE category SET user=?  -- PARAMETERS: [4]
executing query: COMMIT

It don't have WHERE clausule and it overwrite all earlier added entities - now all products have a foreign key matches with new added category, etc.

Image

Maybe it should insert entities in reverse order - user, category, product - which reduce update sql querys.

cascade insert not working

Here is what I have

@Table()
export class AccessToken {
  @PrimaryColumn('int',{generated:true})
  primaryKey: number;

  @OneToOne(type => User, user => user.access_token, {cascadeInsert:true, cascadeUpdate:true})
  user:User
}

@Table()
export class User {
  @PrimaryColumn("int", { generated: true })
  primaryKey: number;

  @Column()
  email: string;

  @OneToOne(type => AccessToken, token => token.user, {cascadeInsert:true, cascadeUpdate:true})
  @JoinColumn()
  access_token: AccessToken;
}

var token = new AccessToken();
var user = new User();
user.email = '[email protected]'
user.access_token = token;

return connection.getRepository(AccessToken).persist(token).then(token => {
  connection.close();
  return token;
});

it is saving the access token fine but not saving the User.

index.js Unexpected token using node

Hello,

My program transpile correctly with tsc but I can't run it with node because of an issue with index.js in typeorm lib.

node_modules/typeorm/index.js:106
function getConnection(connectionName = "default") {
^

SyntaxError: Unexpected token =
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:387:25)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
at Function.Module.runMain (module.js:447:10)
at startup (node.js:148:18)

And its returning the same thing using node index.js
In my package.json
"typeorm": "0.0.2-alpha.69"
"reflect-metadata": "^0.1.8"

tsconfig.json

{
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "sourceMap": true,
        "moduleResolution": "node",
        "experimentalDecorators": true
    },"exclude": [
    "typings",
    "node_modules"
  ]
}

npm version 3.8.6
node version v5.12.0

I don't know if there is something I am missing or is that a real issue ?

create a site

this project needs separate site with good documentation and navigation over it

MissingPrimaryColumnError when primary defined in relation

I have an entity described that:

import { Test } from "./test";
import { Product } from "./product";

import { Table, Column, ManyToOne } from "typeorm";

@Table()
export class Result {
    @ManyToOne(type => Test, { primary: true, nullable: false })
    public test: Test;

    @ManyToOne(type => Product, { primary: true, nullable: false })
    public product: Product;

    @Column()
    public primaryValue: number;

    @Column()
    public secondaryValue: number;
}

And I have an error on launch:
Error! { MissingPrimaryColumnError: Entity "Result" does not have a primary column. Primary column is required to have in all your entities. Use @PrimaryColumn decorator to add a primary column to your entity.

Does the primary in relations option doesn't work yet or it's just a bug in checking if primary is defined?

INSERT INTO instead of UPDATE

Hi,

I classically want to update user informations as below:

public update(userFromRequest: User) {
        return new Promise((resolve: any, reject: any) => {
            let repository = this.connection.getRepository("User");
            repository
                .findOneById(userFromRequest.id)
                .then((loadedUser: User) => {
                    if (_.isUndefined(loadedUser)) {
                        reject();
                    } else {
                        // Only update new values 
                        for (let prop in userFromRequest) {
                            _.set(loadedUser, prop, _.get(userFromRequest, prop));
                        }
                        repository.persist(loadedUser)
                            .then(userUpdated => resolve(userUpdated))
                            .catch(error => reject(error));
                    }
                })
                .catch((error: Error) => {
                    console.error(`UserRepository > update() > error: ${error}`);
                    reject(error);
                }
            );
        });
    }

But after retrieving the user record/object, an insert operation is executed (Error: ER_DUP_ENTRY: Duplicate entry '1' for key 'PRIMARY') instead of update operation, why?

Thanks!

Date: Timezone problem

Currently dates are parsed with moment(dateString). This assumes that the dateStringis in the local timezone. However this is not necessary the case. Especialy with DATE columns, where you only store the date, but not the time. If your environemnt is not in UTC, you will end with really strange behaviours. Given you are in UTC+1, when you get 2016-10-02 from the DB, you will have a Date object with the value 2016-10-02 00:00:00 UTC+1. When you use a UTC method like toISOString you will get 2016-10-01T23:00:00.000Z. As toISOString is how JSON.stringify serializes date, this is kind of problematic.

That's why I would argue to use moment.utc(dateString) to parse dates from the DB.

Column name in relations

Is it somehow possible to set the column name for a relation on the owning side?
Example:
books and chapters, one book has many chapters. In code I want the property be named "book" in the chapter class, but in database I usually set "book_id".
Is that possible to configure?

Timestamp column support

Can you please add support for timestamp column inside ColumnTypes.js
This will also need to support precision.

Cheers

JT

Multiple TypeScript syntax errors during gulp-typescript task

Hi !

package.json:

"dependencies": {
    "async": "^2.0.1",
    "body-parser": "^1.15.2",
    "cluster-service": "^2.0.0-alpha4",
    "convert-excel-to-json": "^1.0.0",
    "del": "^2.2.1",
    "es6-promise": "^3.2.1",
    "es6-shim": "^0.35.1",
    "express": "^4.14.0",
    "fcm-node": "^1.0.14",
    "giuseppe": "^1.1.1",
    "google-cloud": "^0.38.3",
    "gulp": "^3.9.1",
    "gulp-concat": "^2.6.0",
    "gulp-sourcemaps": "^1.6.0",
    "gulp-typescript": "^2.13.6",
    "lodash": "^4.15.0",
    "moment": "^2.14.1",
    "morgan": "^1.7.0",
    "multer": "^1.2.0",
    "mysql": "^2.11.1",
    "nconf": "^0.8.4",
    "passport": "^0.3.2",
    "passport-jwt": "^2.1.0",
    "password-generator": "^2.0.2",
    "reflect-metadata": "^0.1.8",
    "run-sequence": "^1.2.2",
    "typeorm": "0.0.2-alpha.62"
  },
  "devDependencies": {
    "chai": "^3.5.0",
    "istanbul": "^0.4.4",
    "mocha": "^3.0.0",
    "apidoc": "^0.16.0",
    "sinon": "^1.17.5"
  },

tsconfig.json:

{
    "version": "1.8.10",
    "compilerOptions": {
        "target": "es6",
        "module": "commonjs",
        "moduleResolution": "node",
        "sourceMap": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "removeComments": true,
        "noImplicitAny": true,
        "noImplicitReturns": true,
        "stripInternal": true,
        "pretty": true
    },
    "compileOnSave": false,
    "exclude": [
        "node_modules",
        "typings"
    ]
}

Some errors pick randomly (among 571):

project/node_modules/typeorm/connection/Connection.d.ts(23,18): error TS1005: ';' expected.
project/node_modules/typeorm/connection/Connection.d.ts(27,14): error TS1005: '=' expected.
project/node_modules/typeorm/connection/Connection.d.ts(27,20): error TS1005: ';' expected.
project/node_modules/typeorm/connection/Connection.d.ts(31,14): error TS1005: '=' expected.
project/node_modules/typeorm/connection/Connection.d.ts(31,29): error TS1005: ';' expected.
project/node_modules/typeorm/decorator/options/RelationOptions.d.ts(30,23): error TS1109: Expression expected.
project/node_modules/typeorm/decorator/options/RelationOptions.d.ts(31,1): error TS1128: Declaration or statement expected.
project/node_modules/typeorm/driver/Driver.d.ts(12,5): error TS1131: Property or signature expected.
project/node_modules/typeorm/driver/Driver.d.ts(12,14): error TS1005: ';' expected.
project/node_modules/typeorm/driver/Driver.d.ts(18,14): error TS1005: ';' expected.
project/node_modules/typeorm/driver/Driver.d.ts(18,29): error TS1005: '(' expected.
$ node -v
v6.5.0
$ npm -v
3.10.3
$ tsc -v
Version 1.8.10

What part of my code declaration is wrong?

Thanks!

Connection pooling in express app

Hi,

Using TypeOrm what is the best way to create a pool of connections using express?

Will this code in my server.ts be sufficient?

db = createConnection();
app.locals.db = db; 

Then just call app.local.db in my application whenever I need a database connection. Is this likely to cause a problem with the library?

Are there any examples of how this is done?

Cheers

JT

update docs

Docs are not up-to-date right now. This is because api changes a lot. Need to make docs up-to-date.

Can't build ts project

Hi, I get 2700 errors when building my ts project including typeorm. Most of the errors are Build:'=' expected. node_modules\typeorm\schema-builder\schema\TableSchema.d.ts or Build:';' expected. node_modules\typeorm\schema-builder\schema\TableSchema.d.ts

import express = require('express');
import routes = require('./routes/index');
import http = require('http');
import path = require('path');
import "reflect-metadata";
import {createConnection, ConnectionOptions} from "typeorm";

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);

import stylus = require('stylus');
app.use(stylus.middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' === app.get('env')) {
    app.use(express.errorHandler());
}

app.get('/', routes.index);
app.get('/about', routes.about);
app.get('/contact', routes.contact);

http.createServer(app).listen(app.get('port'), () => {
    console.log('Express server listening on port ' + app.get('port'));
});

const options: ConnectionOptions = {
    driver: {
        type: "mysql",
        host: "localhost",
        port: 3306,
        username: "root",
        password: "admin",
        database: "test"
    },
    autoSchemaSync: true,
    entities: [__dirname + "/entity/*"]
};

createConnection(options).then(connection => {

    // at this point you are connected to the database, and you can
    // perform queries

}).catch(error => console.log("Error during connection to the db: ", error));

use TypeORM entity models for class-transformer models on angular2 client side

Trying to use a single typescript model for both client and server side using angular2. It works as expected on the server side. You are unable to use the typeorm library due to needing the node fs module for connection management.

Still working my way through the inter-workings of TypeORM. Would it be possible break out the decorators and looks like a dependency of metadata-args. So the typeorm decorators can be loaded on the client side without any of the connection management. Thanks!

Error during connection to the db: { error: syntax error at or near ")"

Hi,

I am trying to connect to postgres with the following code. To try and narrow things down I have pulled out all of my entities.

let dbHost = process.env.DB_HOST || 'localhost'
        let dbPort = process.env.DB_PORT || 5432;
        let dbName = process.env.DB_NAME || 'TEST_DB';
        let dbUserName = process.env.DB_PASS || 'testuser';
        let dbPassword = process.env.DB_USER || 'testpw';

        const options: ConnectionOptions = {
            driver: {
                type: 'postgres', // specify driver type here.
                host: dbHost,
                port: dbPort,
                username: dbUserName,
                password: dbPassword,
                database: dbName
            },
            autoSchemaCreate: true,
            entities: []
            // entityDirectories: ['./server/model/**/{*.ts,*.js}'],
            // subscriberDirectories: ['./server/subscriber/**/{*.ts,*.js}']
        };

        createConnection(options).then(connection => {

            // at this point you are connected to the database, and you can
            // perform queries

        }).catch(error => console.log('Error during connection to the db: ', error));

The error I am receiving is:

Error during connection to the db:  { error: syntax error at or near ")"
    at Connection.parseE (/Users/jt/Documents/workspace/tester/node_modules/pg/lib/connection.js:554:11)
    at Connection.parseMessage (/Users/jt/Documents/workspace/tester/node_modules/pg/lib/connection.js:381:17)
    at Socket.<anonymous> (/Users/jt/Documents/workspace/tester/node_modules/pg/lib/connection.js:117:22)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:188:7)
    at readableAddChunk (_stream_readable.js:176:18)
    at Socket.Readable.push (_stream_readable.js:134:10)
    at TCP.onread (net.js:543:20)
  name: 'error',
  length: 84,
  severity: 'ERROR',
  code: '42601',
  detail: undefined,
  hint: undefined,
  position: '380',
  internalPosition: undefined,
  internalQuery: undefined,
  where: undefined,
  schema: undefined,
  table: undefined,
  column: undefined,
  dataType: undefined,
  constraint: undefined,
  file: 'scan.l',
  line: '1081',
  routine: 'scanner_yyerror' }

Has this problem been encountered by anyone and is this an issue or a config problem? It looks like an issue as it appears that there is some sort of connection string problem. I may be wrong.

Cheers

JT

optimize all queries and performance

There are places where queries are not performed efficiently, redundant queries are getting performed. Find such places and optimize them all

Cascade remove option not working

Hi,

I'm trying to remove rows using cascade option but it's not working.
I'm using insert and update cascade options and it's working well.

Here is my model :
@OneToMany(type => TemplateAnswer, templateAnswer => templateAnswer.block, { cascadeInsert: true, cascadeUpdate: true, cascadeRemove: true }) templateAnswers: TemplateAnswer[] = [];

And my controller :
@Delete('/:id') deleteOne(@Req() request, @Res() response, @Param('id') id) { var entityManager; return DatabaseManager.getInstance().getConnection() .then(connection => { entityManager = connection.entityManager; return entityManager.findOneById(Block, id); }) .then(block => { return entityManager.remove(block); }) .catch((error: HttpError) => { response.status(error.code).send({message: error.message}); }) .catch(error => { response.status(500).send({message: "Internal error"}); }) }

AdriVig

add more database drivers

Need to add database drivers for at least these databases:

  • PostgreSQL
  • SQLite
  • Microsoft SQL Server
  • MariaDB
  • Mongodb
  • Cassandra?
  • Redis?
  • Oracle
  • DB2 ?
  • mixed databases like indexeddb

Cannot read property 'name' of undefined

I'm hitting an error when my Entity class is parsed. This is the stack trace

c:\Users\mwelnick\Source\TypeOrm\node_modules\typeorm\metadata\types\ColumnTypes.js:64
        return type.name.toLowerCase();
                   ^

TypeError: Cannot read property 'name' of undefined
    at Function.typeToString (c:\Users\mwelnick\Source\TypeOrm\node_modules\typeorm\metadata\types\ColumnTypes.js:64:20)
    at exports.PrimaryColumn (c:\Users\mwelnick\Source\TypeOrm\node_modules\typeorm\decorator\columns\PrimaryColumn.js:20:57)
    at DecoratePropertyWithoutDescriptor (c:\Users\mwelnick\Source\TypeOrm\node_modules\reflect-metadata\Reflect.js:555:13)
    at Object.decorate (c:\Users\mwelnick\Source\TypeOrm\node_modules\reflect-metadata\Reflect.js:108:20)
    at __decorate (c:\Users\mwelnick\Source\TypeOrm\bin\server.js:4:92)
    at Object.<anonymous> (c:\Users\mwelnick\Source\TypeOrm\bin\server.js:14:1)
    at Module._compile (module.js:556:32)
    at Object.Module._extensions..js (module.js:565:10)
    at Module.load (module.js:473:32)
    at tryModuleLoad (module.js:432:12)

Im using
version 0.0.2-alpha.67
node v6.7.0
tsc v2.1.0

This is the code

import "reflect-metadata"
import {createConnection} from "typeorm";
import {Table} from "typeorm";
import {PrimaryColumn, Column} from "typeorm";

@Table("photo")
export class Photo {

    @PrimaryColumn("int", { generated: true })
    id: number;

    @Column()
    name: string;

    @Column()
    description: string;

    @Column()
    filename: string;

    @Column()
    isPublished: boolean;

}

createConnection({
    driver: {
        type: "mssql",
        host: "localhost",
        //port: 3306,
        //username: "root",
        password: "admin",
        database: "test"
    },
    entities: [
        Photo
    ],
    autoSchemaSync: true,
}).then(connection => {
    // here you can start to work with your entities
});

Multi-column primary key

Hi, I really like the idea behind your project and your effort you put in.
A question about primary keys (since they are required by your framework): are multi-column primary keys supported?
Do you just annotate two or more columns with the @PrimaryKey decorator?

Entity metadata not found.

Hi,

I have the following two classes with a M2M relationship.

DatabaseConnectionDB.ts

...
private connect() {

        const loggerOptions: LoggerOptions = {
            logger: (message: string, level: string) => console.log(level, message),
            logQueries: true,
            logFailedQueryError: true
        };

        const options: ConnectionOptions = {
            driver: {
                type: 'postgres', // specify driver type here.
                host: this.dbHost,
                port: this.dbPort,
                username: this.dbUserName,
                password: this.dbPassword,
                database: this.dbName
            },
            autoSchemaCreate: true,
            logging: loggerOptions,
            entities: [UserDB, OrganisationDB]
            // entityDirectories: [__dirname + '/model/**/{*.js}']
        };

        createConnection(options).then((connection: Connection) => {
            // at this point you are connected to the database, and you can
            // perform queries
            console.log('######### Connected to Database: ' + connection);
            this.connection = connection;
            this.isConnected = true;
        }).catch(error => console.log('Error during connection to the db: ', error));
    }
...

UserDB.ts

import 'reflect-metadata';
import {User} from '../../shared/model';
import {Table, PrimaryColumn, Column, JoinTable, ManyToMany} from 'typeorm';
import {UserGroupDB, OrganisationDB} from './';

@Table("USER")
export class UserDB {

    /**************************************************************
     * Instance variables.
     **************************************************************/

    @PrimaryColumn('int', {generated: true })
    id: number;

    @Column()
    username: string;

    @Column()
    password: string;

    @Column()
    firstName: string;

    @Column()
    lastName: string;

    @Column()
    email: string;

    @Column()
    phoneNumber: string;

    @ManyToMany(type => OrganisationDB, organisation => organisation.users)
    @JoinTable()
    organisations: OrganisationDB[];
}

OrganisationDB.ts

import 'reflect-metadata';
import {Table, PrimaryColumn, Column, JoinTable, ManyToMany, OneToMany, ManyToOne, JoinColumn} from 'typeorm';
import {UserDB} from './';

@Table('ORGANISATION')
export class OrganisationDB {

    @PrimaryColumn('int', {generated: true })
    id: number;

    // @Column('string', {name: 'ORGANISATION_NAME', length: '250'})
    @Column()
    organisationName: string;

    // @Column('string', {name: 'PRIMARY_CONTACT_NAME', length: '50'})
    @Column()
    primaryContactName: string;

    // @Column('string', {name: 'PRIMARY_EMAIL', length: '50'})
    @Column()
    primaryEmail: string;

    // @Column('string', {name: 'PRIMARY_PHONE', length: '50'})
    @Column()
    primaryPhone: string;

    // @Column('string', {name: 'SECONDARY_CONTACT_NAME', length: '50', nullable: true})
    @Column()
    secondaryContactName: string;

    // @Column('string', {name: 'SECONDARY_EMAIL', length: '100', nullable: true})
    @Column()
    secondaryEmail: string;

    // @Column('string', {name: 'SECONDARY_PHONE', length: '50', nullable: true})
    @Column()
    secondaryPhone: string;

    @ManyToOne(type => OrganisationDB, parentOrganisation => parentOrganisation.childOrganisations)
    parentOrganisation: OrganisationDB;

    @OneToMany(type => OrganisationDB, childOrganisations => childOrganisations.parentOrganisation)
    childOrganisations: OrganisationDB[];

    @ManyToMany(type => UserDB, user => user.organisations)
    users: UserDB[] = []; // we initialize array for convinience here
}

These two classes return the following error:

Error during connection to the db:  Error: Entity metadata for UserDB#organisations was not found.
    at entityMetadata.relations.forEach.relation (/Users/jt/Documents/workspace/testproject/node_modules/typeorm/metadata-builder/EntityMetadataBuilder.js:249:27)
    at PropertyMetadataArgsCollection.forEach (native)
    at entityMetadatas.forEach.entityMetadata (/Users/jt/Documents/workspace/testproject/node_modules/typeorm/metadata-builder/EntityMetadataBuilder.js:246:38)
    at TargetMetadataArgsCollection.forEach (native)
    at EntityMetadataBuilder.build (/Users/jt/Documents/workspace/testproject/node_modules/typeorm/metadata-builder/EntityMetadataBuilder.js:245:25)
    at EntityMetadataBuilder.buildFromMetadataArgsStorage (/Users/jt/Documents/workspace/testproject/node_modules/typeorm/metadata-builder/EntityMetadataBuilder.js:154:21)
    at Connection.buildMetadatas (/Users/jt/Documents/workspace/testproject/node_modules/typeorm/connection/Connection.js:355:18)
    at Connection.<anonymous> (/Users/jt/Documents/workspace/testproject/node_modules/typeorm/connection/Connection.js:121:18)
    at next (native)
    at fulfilled (/Users/jt/Documents/workspace/testproject/node_modules/typeorm/connection/Connection.js:4:58)

From what I can see the various fields are matching up as per the examples. Can you see an issue here?

JT

syncSchema attempts to sync schema multiple times

Hi,

I've just starting toying with typeorm and so far it's working better then other js orms I've tried. So thanks for the work you're putting in!

I've come across an issue where if I reuse the same connection, I'm seeing strange behavior with syncSchema attempting to create the tables x number of times (where x is the number of times syncSchema has been called on this connection).

As a use case, the flow of my tests is as follows (no public code yet, apologies)

  1. array of ConnectionOptions is defined (for mysql and postgres)
  2. forEach item in the array, do:
    1. create the connection and syncSchema
    2. perform tests
    3. close the connection

If I create a new connection with a different connectionName, I don't see this behavior.

In addition to this, it would be good if we have the ability to remove connections from ConnectionManager.

Thanks!

mixed todos

These are the most relative todos that needs to be done:

  • all persist and remove operations needs to be performed in correct order to prevent errors. need to analyse this order somehow
  • in query builder should we use property names or table names? (right now its kinda mixed)
  • think about indices
  • think more about cascades
  • add cascadeAll to cascades?
  • need to finish naming strategy
  • fix all propertyName/tableName problems and make sure everything work correctly
  • foreign keys for relations
  • exceptions everywhere!
  • add ability to load only ids of the relation (similar to loading only single id)
  • make Index and CompoundIndex to work properly
  • make relations to connect not only to primary key (e.g. relation#referencedColumnName)
  • multiple primary key support?
  • ability to specify many-to-many column names in relation options
  • investigate relations support in abstract tables
  • allow inherited tables to work like abstract tables
  • check query builder query to function support
  • versioning?
  • check relations without inverse sides
  • check group by functionality
  • send entity changeset in update event
  • create a cli for schema update
  • fixtures and migrations
  • lazy loading of properties throw promises? Property can have a Promise type.
  • logging, allow to provide a custom logger
  • check entities without generated ids
  • fix issue with onDelete is not updated on each run (only initialized on first create)
  • add @DefaultOrder(order: "DESC"|"ASC") decorator to specify by which field qb will order by default?
  • use container everywhere to allow orm extensibility?
  • in memory strategy and unit of work?
  • support of embeddables ?
  • support table inheritance patterns?
  • multiple auto generation strategies?
  • rename event subscriber to entity event subcriber?
  • caching strategies
  • connection pool
  • add option for the addToRelation and others to prevent duplicate keys to be inserted
  • implement extend of the entity schemas
  • add @where decorator
  • add order decorator to relations
  • internationalization features (for example @internationalization() name can create fields for languages set in the configuration (lets say name_tj, name_ru, name_en, name_es) and during selection only fields of the current internationalization will be selected and mapped to their original name (e.g. name_en mapped to name)
  • special collections support for the relational arrays?
  • Where decorator should be supported by RelationCount as well
  • check persistence when there are circular references
  • database DEFAULT values
  • global table prefix
  • allow to specify a prefixes into embedded columns
  • add result caching capabilities to query builder
  • custom id / value generation
  • bulk operations in specific repository?
  • throw exceptions in persist if entity was updated with a new version/updated date
  • support nestedset and materialized path
  • functionality for soft deletion?
  • functionality for versioning and revisions?
  • pessimistic / optimistic locking?
  • add support of typeorm-config.json, maybe cli can use it instead of parameters
  • add support of configuration from ENV variables
  • fix naming strategy issues, use naming strategy everywhere possible
  • partial loading (sometimes really needed)
  • add support for CHECK sql constraint or support ENUM data type?
  • tree repository should be able to work with adjacency list, self referenced relations with tree decorators used
  • add ability to use custom repository classes
  • add persistment options? (like UPDATE_COLUMNS|UPDATE_RELATIONS)?
  • implement abstraction for webbased usage (browser/websql, ionic, etc.)
  • implement streaming for big data sets
  • make sure array column works in both relational and mongodb
  • implement true relations and joins in mongo
  • reorganize docs to cover both relational and mongo databases
  • try to add more document storage databases
  • make sure lazy loading is working with mongo once mongo relations are setup
  • make sure create date / update date are working properly with mongo
  • investigate multiple database queries issue

feel free to contribute. Open discussion on any of items here.

Primary key value not detected with alias'ed Column

When using a Primary key colum with an alias, the persisting of an entity fails:
Given object does not have a primary column, cannot transform it to database entity.
The problem is that the PlainObjectToDatabaseEntityTransformer uses metadata.primaryColumn.name instead of metadata.primaryColumn.propertyName.
Could you please fix this? I hope there are not too many other cases where an alias breaks the whole application.

ColumnOptions not exported properly

I'm getting TS compile errors when providing object literals for ColumnOptions.

{ generated: true }

"Object literal may only specify known properties and 'generated' does not exist on ColumnOptions"

ColumnOptions length not working?

Hello,

With the option "autoSchemaCreate: true" and the below column declaration, the 'token' column stays VARCHAR(255) in the MySQL database (the 'nullable' option works fine).

@Column({ length: 300, nullable: true })
 token: string;

Why?

Relationships only work when both primary keys have the same name

Heres my two classes

@Table()
export class AccessToken {
  @PrimaryColumn()
  access_token: string;
}

@Table()
export class User {
  @PrimaryColumn("int", { generated: true })
  id: number;

  @Column()
  email: string;

  @OneToOne(type => AccessToken)
  @JoinColumn()
  access_token: AccessToken;
}

Heres what I used to persist

var token = new AccessToken();
token.access_token = '12345';
var user = new User();
user.email = '[email protected]'
user.access_token = token;

return connection.getRepository(AccessToken).persist(token).then(token => {
  return connection.getRepository(User).persist(user);
})
.then (user => {
  // doesn't get here
})

when persisting the user I get the error
`Error: ER_BAD_FIELD_ERROR: Unknown column 'AccessToken.id' in 'where clause'

But when i rename the primary column on AccessToken to "id" or rename them both to "primaryKey" it works. Also when I use "key" instead of id I get a sql syntax error when persisting.

complete test coverage

Need to cover every aspect, every part of the orm test good tests, otherwise will we face loot of problems very soon. First of all needs functional coverage to make all orm functions are working properly

ConnectionOptions.entityDirectories not detecting files

Hi, I am using the following ConnectionOptions object when setting up my connection.

ConnectionOptions = {
            driver: {
                type: 'postgres', // specify driver type here.
                host: this.dbHost,
                port: this.dbPort,
                username: this.dbUserName,
                password: this.dbPassword,
                database: this.dbName
            },
            autoSchemaCreate: true,
            logging: loggerOptions,
            entityDirectories: ['../model/**/{*.js}']
        };

It is not detecting the files in the entityDirectories property. I am just looking for the .js files. Am I doing something wrong?

JT

Problem with connection to database [postgres]

This is the error I am getting:

\typeorm\connection\ConnectionManager.js:51
    get(name = "default") {
             ^

SyntaxError: Unexpected token =
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:373:25)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Module.require (module.js:353:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (C:\Users\Jan Burda\Documents\Visual Studio 2015\Projects\NodejsApppp\NodejsApppp\node_modules\typeorm\index.js:7:29)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)

this is my code

const options: ConnectionOptions = {
    driver: {
        type: "postgres",
        host: "localhost",
        port: 5432,
        username: "postgres",
        password: "toor",
        database: "TypeTest"
    },
    autoSchemaSync: true,
    entitySchemas: [
        require(__dirname + "/schemas/records.json")
    ]
};

createConnection(options).then(connection => {
    let repo = connection.getRepository<Record.IRecord>("Record");
    // at this point you are connected to the database, and you can
    // perform queries

}).catch(error => console.log("Error during connection to the db: ", error));

node version: 4.5
typescript version: 2.0.3

A good companion to Ubiquits?

Hey, just came across Typeorm and was wondering if it would be a good fit for the TS framework I'm building over at http://github.com/ubiquits/ubiquits or http://ubiquits.com? I'm still in early stage development - intending to release developer preview next week and am currently building on Sequelize, but it looks like Typeorm might be an easier implementation.

Also regarding your issue on the need to build a documentation site, you might want to consider the infrastructure I've built up to document Ubiquits

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.