fix: respect database from connection urls (#5640) · typeorm/typeorm@ed75d59

3 files changed

lines changed

Original file line numberDiff line numberDiff line change

@@ -38,6 +38,7 @@ import {ObjectUtils} from "../util/ObjectUtils";

3838

import {PromiseUtils} from "../";

3939

import {IsolationLevel} from "../driver/types/IsolationLevel";

4040

import {AuroraDataApiDriver} from "../driver/aurora-data-api/AuroraDataApiDriver";

41+

import {DriverUtils} from "../driver/DriverUtils";

4142
4243

/**

4344

* Connection is a single database ORM connection to a specific database.

@@ -524,17 +525,17 @@ export class Connection {

524525
525526

// This database name property is nested for replication configs.

526527

protected getDatabaseName(): string {

527-

const options = this.options;

528-

switch (options.type) {

529-

case "mysql" :

530-

case "mariadb" :

531-

case "postgres":

532-

case "cockroachdb":

533-

case "mssql":

534-

case "oracle":

535-

return (options.replication ? options.replication.master.database : options.database) as string;

536-

default:

537-

return options.database as string;

528+

const options = this.options;

529+

switch (options.type) {

530+

case "mysql" :

531+

case "mariadb" :

532+

case "postgres":

533+

case "cockroachdb":

534+

case "mssql":

535+

case "oracle":

536+

return DriverUtils.buildDriverOptions(options.replication ? options.replication.master : options).database;

537+

default:

538+

return DriverUtils.buildDriverOptions(options).database;

538539

}

539540

}

540541
Original file line numberDiff line numberDiff line change

@@ -0,0 +1,9 @@

1+

import {Entity, PrimaryGeneratedColumn} from "../../../../src";

2+
3+

@Entity()

4+

export class TestEntity {

5+
6+

@PrimaryGeneratedColumn()

7+

id: number;

8+
9+

}

Original file line numberDiff line numberDiff line change

@@ -0,0 +1,24 @@

1+

import "reflect-metadata";

2+

import { expect } from "chai";

3+

import { createConnection } from "../../../src";

4+

import { getTypeOrmConfig } from "../../utils/test-utils";

5+
6+

describe("github issues > #2096 [mysql] Database name isn't read from url", () => {

7+

it("should be possible to define a database by connection url for mysql", async () => {

8+

const config = getTypeOrmConfig();

9+
10+

// it is important to synchronize here, to trigger EntityMetadataValidator.validate

11+

// that previously threw the error where the database on the driver object was undefined

12+

if (config.find(c => c.name === "mysql" && !c.skip)) {

13+

const connection = await createConnection({

14+

name: "#2096",

15+

url: "mysql://root:admin@localhost:3306/test",

16+

entities: [__dirname + "/entity/*{.js,.ts}"],

17+

synchronize: true,

18+

type: "mysql"

19+

});

20+

expect(connection.isConnected).to.eq(true);

21+

await connection.close();

22+

}

23+

});

24+

});