Skip to content

Commit

Permalink
Merge branch 'master' into next
Browse files Browse the repository at this point in the history
* master: (25 commits)
  version bump
  skipped failing test for now
  version bump
  fixed issue with entity order by applied to update query builder
  Update README.md
  Add TYPEORM_DATABASE to available env options
  Provide failing test
  chore: fix typo in repository clear test filename
  minor lint fix
  delete entities using tablePath
  implement timezone based tests for multiple database drivers
  remove UTC transformation from drivers on write and read
  fixed broken lazy relation behaviour with broadcaster
  Fixes to Postgres, MySQL and MSSQL drivers propagating unhandled errors and crashing the hosting application
  remove array cast apply on function typed columns
  exit process on migrations:run command complete
  removed only test
  fixes #1720
  added test for #1703
  Update cli docs for create migration
  ...

# Conflicts:
#	CHANGELOG.md
#	README.md
#	package-lock.json
#	package.json
#	src/driver/mysql/MysqlDriver.ts
#	src/driver/postgres/PostgresDriver.ts
#	src/driver/sqlite-abstract/AbstractSqliteDriver.ts
#	src/persistence/SubjectOperationExecutor.ts
#	src/subscriber/Broadcaster.ts
#	test/github-issues/1716/issue-1716.ts
  • Loading branch information
Umed Khudoiberdiev committed Mar 26, 2018
2 parents bfa92fd + d2701f1 commit 6089131
Show file tree
Hide file tree
Showing 28 changed files with 470 additions and 61 deletions.
8 changes: 8 additions & 0 deletions CHANGELOG.md
Expand Up @@ -65,6 +65,14 @@ composite check constraint, on table level. E.g. `@Check("chk_name", "name <> 'a
* implemented migrations functionality in all drivers
* CLI commands changed from `migrations:create`, `migrations:generate`, `migrations:revert` and `migrations:run` to `migration:create`, `migration:generate`, `migration:revert` and `migration:run`

## 0.1.18

* fixed timestamp issues

## 0.1.17

* fixed issue with entity order by applied to update query builder

## 0.1.16

* security and bug fixes
Expand Down
52 changes: 26 additions & 26 deletions README.md
Expand Up @@ -23,20 +23,20 @@
TypeORM is an [ORM](https://en.wikipedia.org/wiki/Object-relational_mapping)
that can run in NodeJS, Browser, Cordova, PhoneGap and Ionic platforms
and can be used with TypeScript and JavaScript (ES5, ES6, ES7).
Its goal to always support latest JavaScript features and provide features
that help you to develop any kind of applications that use databases - from
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 exist,
unlike all other JavaScript ORMs currently in existance,
which means you can write high quality, loosely coupled, scalable,
maintainable applications the most productive way.

TypeORM is highly influenced by other ORMs, such as [Hibernate](http://hibernate.org/orm/),
[Doctrine](http://www.doctrine-project.org/) and [Entity Framework](https://www.asp.net/entity-framework).

Some of TypeORM features:
Some TypeORM features:

* supports both DataMapper and ActiveRecord (your choice)
* entities and columns
Expand Down Expand Up @@ -116,7 +116,7 @@ const timber = await repository.findOne({ firstName: "Timber", lastName: "Saw" }
await repository.remove(timber);
```

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

```typescript
import {Entity, PrimaryGeneratedColumn, Column, BaseEntity} from "typeorm";
Expand Down Expand Up @@ -158,7 +158,7 @@ await timber.remove();
## Installation


1. Install npm package:
1. Install the npm package:

`npm install typeorm --save`

Expand All @@ -174,7 +174,7 @@ await timber.remove();

`npm install @types/node --save`

4. Install database driver:
4. Install a database driver:

* for **MySQL** or **MariaDB**

Expand All @@ -200,16 +200,16 @@ await timber.remove();

`npm install oracledb --save`

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

To make the Oracle driver work, you need to follow the installation instructions from
[their](https://github.com/oracle/node-oracledb) site.
Oracle support is experimental at the moment and isn't bug-free.
Expect to see more stable Oracle support in a near future.
Expect to see more stable Oracle support in the near future.

##### TypeScript configuration

Also make sure you are using TypeScript compiler version **2.3** or greater,
Also, make sure you are using TypeScript compiler version **2.3** or greater,
and you have enabled the following settings in `tsconfig.json`:

```json
Expand All @@ -222,26 +222,26 @@ You may also need to enable `es6` in the `lib` section of compiler options, or i
## 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 NodeJS application.
If you are using other platforms, proceed to [step-by-step guide](#step-by-step-guide).
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](#step-by-step-guide).

First, install TypeORM globally:

```
npm install typeorm -g
```

Then go to the directory where you want to create a new project and run:
Then go to the directory where you want to create a new project and run the command:

```
typeorm init --name MyProject --database mysql
```

Where `name` is the name of your project and `database` is the database you'll use.
It can be one of the following values: `mysql`, `mariadb`, `postgres`, `sqlite`, `mssql`, `oracle`,
Database can be one of the following values: `mysql`, `mariadb`, `postgres`, `sqlite`, `mssql`, `oracle`,
`websql`, `mongodb`.

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

```
MyProject
Expand All @@ -257,16 +257,16 @@ MyProject
└── tsconfig.json // TypeScript compiler options
```

> You can also run `typeorm init` on exist node project, but be careful - it may override some files you may already have.
> You can also run `typeorm init` on an existing node project, but be careful - it may override some files you already have.
Next step is to install new project dependencies:
The next step is to install new project dependencies:

```
cd MyProject
npm install
```

While installation in the progress edit `ormconfig.json` file and put your own database connection configuration options in there:
While installation is in progress, edit the `ormconfig.json` file and put your own database connection configuration options in there:

```json
{
Expand All @@ -290,20 +290,20 @@ While installation in the progress edit `ormconfig.json` file and put your own d
}
```

Particularly most of the time you'll only need to configure
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:
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 now and insert a new user into the database.
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 even more advanced project with express installed by running
> You can generate an even more advanced project with express installed by running
`typeorm init --name MyProject --database mysql --express` command.

## Step-by-Step Guide
Expand All @@ -312,14 +312,14 @@ 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 setup TypeORM from scratch and make it do what you are expecting from ORM.
This guide will show you how to setup TypeORM from scratch and make it do what you are expecting from an ORM.

### Create a model

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

For example, you have a `Photo` model:

Expand Down
7 changes: 5 additions & 2 deletions docs/connection.md
Expand Up @@ -69,10 +69,13 @@ import {createConnection, Connection} from "typeorm";
// here createConnection will load connection options from
// ormconfig.json / ormconfig.js / ormconfig.yml / ormconfig.env / ormconfig.xml
// files, or from special environment variables
// if ormconfig contains multiple connections then it will load connection named "default"
// if ormconfig contains multiple connections and no `name` is specified, then it will load connection named "default"
// or connection without name at all (which means it will be named "default" by default)
const connection: Connection = await createConnection();

// or you can specify the name of the connection to create
const secondConnection: Connection = await createConnection("test2-connection");

// if createConnections is called instead of createConnection then
// it will initialize and return all connections defined in ormconfig file
```
Expand Down Expand Up @@ -188,4 +191,4 @@ export class UserController {
}

}
```
```
15 changes: 15 additions & 0 deletions docs/multiple-connections.md
Expand Up @@ -42,6 +42,21 @@ and each database will have its own configuration, own entities and overall ORM
For each connection a new `Connection` instance will be created.
You must specify a unique name for each connection you create.

The connection options can also be loaded from an ormconfig file. You can load all connections from
the ormconfig file:
```typescript
import {createConnections} from "typeorm";

const connections = await createConnections();
```

or you can specify which connection to create by name:
```typescript
import {createConnection} from "typeorm";

const connection = await createConnection("db2Connection");
```

When working with connections you must specify a connection name to get a specific connection:

```typescript
Expand Down
6 changes: 3 additions & 3 deletions docs/using-cli.md
Expand Up @@ -131,7 +131,7 @@ Learn more about [Subscribers](./listeners-and-subscribers.md).
You can create a new migration using CLI:

```
typeorm migration:create -n UserMigration
typeorm migrations:create -n UserMigration
```

where `UserMigration` is a migration file and class name.
Expand All @@ -151,7 +151,7 @@ If you have a multi-module project structure with multiple migrations in differe
you can provide a path to the CLI command where you want to generate a migration:

```
typeorm migration:create -n UserMigration -d src/user/migration
typeorm migrations:create -n UserMigration -d src/user/migration
```

Learn more about [Migrations](./migrations.md).
Expand All @@ -162,7 +162,7 @@ Automatic migration generation creates a new migration file
and writes all sql queries that must be executed to update the database.

```
typeorm migration:generate -n UserMigration
typeorm migrations:generate -n UserMigration
```

The rule of thumb is to generate a migration after each entity change.
Expand Down
4 changes: 3 additions & 1 deletion docs/using-ormconfig.md
Expand Up @@ -89,6 +89,7 @@ TYPEORM_CONNECTION = mysql
TYPEORM_HOST = localhost
TYPEORM_USERNAME = root
TYPEORM_PASSWORD = admin
TYPEORM_DATABASE = test
TYPEORM_PORT = 3000
TYPEORM_SYNCHRONIZE = true
TYPEORM_LOGGING = true
Expand All @@ -101,6 +102,7 @@ List of available env variables you can set:
* TYPEORM_HOST
* TYPEORM_USERNAME
* TYPEORM_PASSWORD
* TYPEORM_DATABASE
* TYPEORM_PORT
* TYPEORM_URL
* TYPEORM_SID
Expand Down Expand Up @@ -174,4 +176,4 @@ Create `ormconfig.xml` in the project root (near `package.json`). It should have
</connections>
```

You can use any connection options available.
You can use any connection options available.
4 changes: 3 additions & 1 deletion src/commands/MigrationRunCommand.ts
Expand Up @@ -44,6 +44,8 @@ export class MigrationRunCommand {

await connection.runMigrations();
await connection.close();
// exit process if no errors
process.exit(0);

} catch (err) {
if (connection) await (connection as Connection).close();
Expand All @@ -54,4 +56,4 @@ export class MigrationRunCommand {
}
}

}
}
29 changes: 21 additions & 8 deletions src/driver/mysql/MysqlDriver.ts
Expand Up @@ -161,7 +161,7 @@ export class MysqlDriver implements Driver {
// -------------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------------

constructor(connection: Connection) {
this.connection = connection;
this.options = connection.options as MysqlConnectionOptions;
Expand Down Expand Up @@ -335,7 +335,7 @@ export class MysqlDriver implements Driver {
prepareHydratedValue(value: any, columnMetadata: ColumnMetadata): any {
if (value === null || value === undefined)
return value;

if (columnMetadata.type === Boolean) {
value = value ? true : false;

Expand All @@ -353,7 +353,7 @@ export class MysqlDriver implements Driver {

} else if (columnMetadata.type === "simple-array") {
value = DateUtils.stringToSimpleArray(value);

} else if (columnMetadata.type === "simple-json") {
value = DateUtils.stringToSimpleJson(value);
}
Expand Down Expand Up @@ -437,11 +437,11 @@ export class MysqlDriver implements Driver {

const normalizedType = this.normalizeType(column) as string;
if (this.dataTypeDefaults && this.dataTypeDefaults[normalizedType] && this.dataTypeDefaults[normalizedType].length)
return this.dataTypeDefaults[normalizedType].length!.toString();
return this.dataTypeDefaults[normalizedType].length!.toString();

return "";
}
}

createFullType(column: TableColumn): string {
let type = column.type;

Expand Down Expand Up @@ -472,12 +472,12 @@ export class MysqlDriver implements Driver {
return new Promise<any>((ok, fail) => {
if (this.poolCluster) {
this.poolCluster.getConnection("MASTER", (err: any, dbConnection: any) => {
err ? fail(err) : ok(dbConnection);
err ? fail(err) : ok(this.prepareDbConnection(dbConnection));
});

} else if (this.pool) {
this.pool.getConnection((err: any, dbConnection: any) => {
err ? fail(err) : ok(dbConnection);
err ? fail(err) : ok(this.prepareDbConnection(dbConnection));
});
} else {
fail(new Error(`Connection is not established with mysql database`));
Expand Down Expand Up @@ -659,6 +659,19 @@ export class MysqlDriver implements Driver {
});
}

/**
* Attaches all required base handlers to a database connection, such as the unhandled error handler.
*/
private prepareDbConnection(connection: any): any {
const { logger } = this.connection;
/*
Attaching an error handler to connection errors is essential, as, otherwise, errors raised will go unhandled and
cause the hosting app to crash.
*/
connection.on("error", (error: any) => logger.log("warn", `MySQL connection raised an error. ${error}`));
return connection;
}

/**
* Checks if "DEFAULT" values in the column metadata and in the database are equal.
*/
Expand Down
6 changes: 6 additions & 0 deletions src/driver/postgres/PostgresDriver.ts
Expand Up @@ -747,6 +747,12 @@ export class PostgresDriver implements Driver {

// create a connection pool
const pool = new this.postgres.Pool(connectionOptions);
const { logger } = this.connection;
/*
Attaching an error handler to pool errors is essential, as, otherwise, errors raised will go unhandled and
cause the hosting app to crash.
*/
pool.on("error", (error: any) => logger.log("warn", `Postgres pool raised an error. ${error}`));

return new Promise((ok, fail) => {
pool.connect((err: any, connection: any, release: Function) => {
Expand Down

0 comments on commit 6089131

Please sign in to comment.