Skip to content

Commit

Permalink
added test util scenario for spanner driver
Browse files Browse the repository at this point in the history
  • Loading branch information
pleerock committed Apr 2, 2022
1 parent e58c796 commit 22d21b0
Show file tree
Hide file tree
Showing 5 changed files with 107 additions and 29 deletions.
12 changes: 7 additions & 5 deletions src/data-source/DataSource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,23 @@ import { EntityTarget } from "../common/EntityTarget"
import { ObjectType } from "../common/ObjectType"
import { EntityManager } from "../entity-manager/EntityManager"
import { DefaultNamingStrategy } from "../naming-strategy/DefaultNamingStrategy"
import { CannotExecuteNotConnectedError } from "../error/CannotExecuteNotConnectedError"
import { CannotConnectAlreadyConnectedError } from "../error/CannotConnectAlreadyConnectedError"
import {
CannotConnectAlreadyConnectedError,
CannotExecuteNotConnectedError,
EntityMetadataNotFoundError,
QueryRunnerProviderAlreadyReleasedError,
} from "../error"
import { TreeRepository } from "../repository/TreeRepository"
import { NamingStrategyInterface } from "../naming-strategy/NamingStrategyInterface"
import { EntityMetadata } from "../metadata/EntityMetadata"
import { Logger } from "../logger/Logger"
import { EntityMetadataNotFoundError } from "../error/EntityMetadataNotFoundError"
import { MigrationInterface } from "../migration/MigrationInterface"
import { MigrationExecutor } from "../migration/MigrationExecutor"
import { Migration } from "../migration/Migration"
import { MongoRepository } from "../repository/MongoRepository"
import { MongoEntityManager } from "../entity-manager/MongoEntityManager"
import { EntityMetadataValidator } from "../metadata-builder/EntityMetadataValidator"
import { DataSourceOptions } from "./DataSourceOptions"
import { QueryRunnerProviderAlreadyReleasedError } from "../error/QueryRunnerProviderAlreadyReleasedError"
import { EntityManagerFactory } from "../entity-manager/EntityManagerFactory"
import { DriverFactory } from "../driver/DriverFactory"
import { ConnectionMetadataBuilder } from "../connection/ConnectionMetadataBuilder"
Expand All @@ -33,7 +35,7 @@ import { RelationLoader } from "../query-builder/RelationLoader"
import { ObjectUtils } from "../util/ObjectUtils"
import { IsolationLevel } from "../driver/types/IsolationLevel"
import { ReplicationMode } from "../driver/types/ReplicationMode"
import { TypeORMError } from "../error/TypeORMError"
import { TypeORMError } from "../error"
import { RelationIdLoader } from "../query-builder/RelationIdLoader"
import { DriverUtils } from "../driver/DriverUtils"
import { InstanceChecker } from "../util/InstanceChecker"
Expand Down
10 changes: 5 additions & 5 deletions src/query-builder/InsertQueryBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -336,15 +336,15 @@ export class InsertQueryBuilder<Entity> extends QueryBuilder<Entity> {

/**
* @deprecated
*
*
* `.orUpdate({ columns: [ "is_updated" ] }).setParameter("is_updated", value)`
*
*
* is now `.orUpdate(["is_updated"])`
*
*
* `.orUpdate({ conflict_target: ['date'], overwrite: ['title'] })`
*
*
* is now `.orUpdate(['title'], ['date'])`
*
*
*/
orUpdate(statement?: {
columns?: string[]
Expand Down
7 changes: 5 additions & 2 deletions test/functional/base-entity/base-entity.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import "../../utils/test-setup"
import { setupTestingConnections } from "../../utils/test-utils"
import {
createDataSource,
setupTestingConnections,
} from "../../utils/test-utils"
import { User } from "./entity/User"
import { expect } from "chai"
import { DataSource } from "../../../src"
Expand Down Expand Up @@ -37,7 +40,7 @@ describe("base entity", () => {
// reset data source just to make sure inside DataSource it's really being set
User.useDataSource(null)

const dataSource = new DataSource(dataSourceOptions[0])
const dataSource = createDataSource(dataSourceOptions[0])
await dataSource.initialize()
await dataSource.synchronize(true)

Expand Down
10 changes: 6 additions & 4 deletions test/functional/base-entity/entity/User.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { Entity } from "../../../../src/decorator/entity/Entity"
import { PrimaryGeneratedColumn } from "../../../../src/decorator/columns/PrimaryGeneratedColumn"
import { Column } from "../../../../src/decorator/columns/Column"
import { BaseEntity } from "../../../../src"
import {
BaseEntity,
Column,
Entity,
PrimaryGeneratedColumn,
} from "../../../../src"

@Entity()
export class User extends BaseEntity {
Expand Down
97 changes: 84 additions & 13 deletions test/utils/test-utils.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,19 @@
import { DataSource } from "../../src/data-source/DataSource"
import { DataSourceOptions } from "../../src/data-source/DataSourceOptions"
import { DatabaseType } from "../../src/driver/types/DatabaseType"
import { EntitySchema } from "../../src/entity-schema/EntitySchema"
import { createConnections } from "../../src/index"
import { NamingStrategyInterface } from "../../src/naming-strategy/NamingStrategyInterface"
import {
DatabaseType,
DataSource,
DataSourceOptions,
EntitySchema,
EntitySubscriberInterface,
getMetadataArgsStorage,
InsertEvent,
Logger,
NamingStrategyInterface,
} from "../../src"
import { QueryResultCache } from "../../src/cache/QueryResultCache"
import { Logger } from "../../src/logger/Logger"
import path from "path"
import { ObjectUtils } from "../../src/util/ObjectUtils"
import { EntitySubscriberMetadataArgs } from "../../src/metadata-args/EntitySubscriberMetadataArgs"
import { v4 as uuidv4 } from "uuid"

/**
* Interface in which data is stored in ormconfig.json of the project.
Expand Down Expand Up @@ -57,7 +64,7 @@ export interface TestingOptions {
/**
* Subscribers needs to be included in the connection for the given test suite.
*/
subscribers?: string[] | Function[]
subscribers?: (string | Function)[]

/**
* Indicates if schema sync should be performed or not.
Expand Down Expand Up @@ -293,18 +300,82 @@ export function setupTestingConnections(
})
}

export function createDataSource(options: DataSourceOptions): DataSource {
class GeneratedColumnReplacerSubscriber
implements EntitySubscriberInterface
{
static globalIncrementValues: { [entityName: string]: number } = {}
beforeInsert(event: InsertEvent<any>): Promise<any> | void {
event.metadata.generatedColumns.map((column) => {
if (column.generationStrategy === "increment") {
if (
!GeneratedColumnReplacerSubscriber
.globalIncrementValues[event.metadata.tableName]
) {
GeneratedColumnReplacerSubscriber.globalIncrementValues[
event.metadata.tableName
] = 0
}
GeneratedColumnReplacerSubscriber.globalIncrementValues[
event.metadata.tableName
] += 1

column.setEntityValue(
event.entity,
GeneratedColumnReplacerSubscriber.globalIncrementValues[
event.metadata.tableName
],
)
} else if (column.generationStrategy === "uuid") {
column.setEntityValue(event.entity, uuidv4())
}
})
}
}

// todo: uncomment later
if (options.type === ("spanner" as any)) {
getMetadataArgsStorage().entitySubscribers.push({
target: GeneratedColumnReplacerSubscriber,
} as EntitySubscriberMetadataArgs)

if (Array.isArray(options.subscribers)) {
options.subscribers.push(
GeneratedColumnReplacerSubscriber as Function,
)
} else if (ObjectUtils.isObject(options.subscribers)) {
options.subscribers["GeneratedColumnReplacer"] =
GeneratedColumnReplacerSubscriber
} else {
options = {
...options,
subscribers: {
GeneratedColumnReplacer: GeneratedColumnReplacerSubscriber,
},
}
}
}

return new DataSource(options)
}

/**
* Creates a testing connections based on the configuration in the ormconfig.json
* and given options that can override some of its configuration for the test-specific use case.
*/
export async function createTestingConnections(
options?: TestingOptions,
): Promise<DataSource[]> {
const connections = await createConnections(
setupTestingConnections(options),
)
const dataSourceOptions = setupTestingConnections(options)
const dataSources: DataSource[] = []
for (let options of dataSourceOptions) {
const dataSource = createDataSource(options)
await dataSource.initialize()
dataSources.push(dataSource)
}

await Promise.all(
connections.map(async (connection) => {
dataSources.map(async (connection) => {
// create new databases
const databases: string[] = []
connection.entityMetadatas.forEach((metadata) => {
Expand Down Expand Up @@ -388,7 +459,7 @@ export async function createTestingConnections(
}),
)

return connections
return dataSources
}

/**
Expand Down

0 comments on commit 22d21b0

Please sign in to comment.