refactored driver stuff

This commit is contained in:
Umed Khudoiberdiev 2017-06-10 00:21:50 +05:00
parent d761f3c795
commit 10b5fb2a79
20 changed files with 286 additions and 447 deletions

View File

@ -1,4 +1,12 @@
/**
* Database type.
*/
export type DatabaseType = "mysql"|"postgres"|"mariadb"|"sqlite"|"oracle"|"mssql"|"websql"|"mongodb";
export type DatabaseType =
"mysql"|
"postgres"|
"mariadb"|
"sqlite"|
"oracle"|
"mssql"|
"websql"|
"mongodb";

View File

@ -1,9 +1,6 @@
import {DriverOptions} from "./DriverOptions";
import {QueryRunner} from "../query-runner/QueryRunner";
import {ColumnMetadata} from "../metadata/ColumnMetadata";
import {ObjectLiteral} from "../common/ObjectLiteral";
import {NamingStrategyInterface} from "../naming-strategy/NamingStrategyInterface";
import {LazyRelationsWrapper} from "../lazy-loading/LazyRelationsWrapper";
/**
* Driver organizes TypeORM communication with specific database management system.
@ -12,13 +9,12 @@ export interface Driver {
/**
* Performs connection to the database.
* Based on pooling options, it can either create connection immediately,
* either create a pool and create connection when needed.
* Depend on driver type it may create a connection pool.
*/
connect(): Promise<void>;
/**
* Closes connection with database.
* Closes connection with database and releases all resourc.
*/
disconnect(): Promise<void>;

View File

@ -9,7 +9,6 @@ import {ObjectLiteral} from "../../common/ObjectLiteral";
import {ColumnMetadata} from "../../metadata/ColumnMetadata";
import {DriverOptionNotSetError} from "../error/DriverOptionNotSetError";
import {PlatformTools} from "../../platform/PlatformTools";
import {EntityMetadata} from "../../metadata/EntityMetadata";
import {Connection} from "../../connection/Connection";
import {MongoConnectionOptions} from "./MongoConnectionOptions";
@ -24,7 +23,7 @@ export class MongoDriver implements Driver {
/**
* Mongodb does not require to dynamically create query runner each time,
* because it does not have a regular pool.
* because it does not have a regular connection pool as RDBMS systems have.
*/
queryRunner: MongoQueryRunner;
@ -33,16 +32,19 @@ export class MongoDriver implements Driver {
// -------------------------------------------------------------------------
/**
* Underlying mongodb driver.
* Connection options.
*/
protected options: MongoConnectionOptions;
/**
* Underlying mongodb library.
*/
protected mongodb: any;
/**
* Connection to mongodb database provided by native driver.
*/
protected pool: any;
protected options: MongoConnectionOptions;
protected databaseConnection: any;
// -------------------------------------------------------------------------
// Constructor
@ -55,11 +57,11 @@ export class MongoDriver implements Driver {
this.validateOptions(connection.options);
// load mongodb package
this.mongodb = this.loadDependencies();
this.loadDependencies();
}
// -------------------------------------------------------------------------
// Public Overridden Methods
// Public Methods
// -------------------------------------------------------------------------
/**
@ -67,13 +69,13 @@ export class MongoDriver implements Driver {
*/
connect(): Promise<void> {
return new Promise<void>((ok, fail) => {
this.mongodb.MongoClient.connect(this.buildConnectionUrl(), this.options.extra, (err: any, database: any) => {
this.mongodb.MongoClient.connect(this.buildConnectionUrl(), this.options.extra, (err: any, dbConnection: any) => {
if (err) return fail(err);
this.pool = database;
this.databaseConnection = dbConnection;
const databaseConnection: DatabaseConnection = {
id: 1,
connection: this.pool,
connection: dbConnection,
isTransactionActive: false
};
this.queryRunner = new MongoQueryRunner(this.connection, databaseConnection);
@ -86,21 +88,38 @@ export class MongoDriver implements Driver {
* Closes connection with the database.
*/
async disconnect(): Promise<void> {
if (!this.pool)
if (!this.databaseConnection)
throw new ConnectionIsNotSetError("mongodb");
return new Promise<void>((ok, fail) => {
const handler = (err: any) => err ? fail(err) : ok();
this.pool.close(handler);
this.pool = undefined;
this.databaseConnection.close(handler);
this.databaseConnection = undefined;
});
}
/**
* Synchronizes database schema (creates indices).
*/
async syncSchema(): Promise<void> {
if (!this.databaseConnection)
throw new ConnectionIsNotSetError("mongodb");
const promises: Promise<any>[] = [];
this.connection.entityMetadatas.forEach(metadata => {
metadata.indices.forEach(index => {
const options = { name: index.name };
promises.push(this.queryRunner.createCollectionIndex(metadata.tableName, index.columnNamesWithOrderingMap, options));
});
});
await Promise.all(promises);
}
/**
* Creates a query runner used for common queries.
*/
async createQueryRunner(): Promise<QueryRunner> {
if (!this.pool)
if (!this.databaseConnection)
return Promise.reject(new ConnectionIsNotSetError("mongodb"));
return this.queryRunner;
@ -112,7 +131,7 @@ export class MongoDriver implements Driver {
nativeInterface() {
return {
driver: this.mongodb,
connection: this.pool
connection: this.databaseConnection
};
}
@ -149,33 +168,6 @@ export class MongoDriver implements Driver {
* Prepares given value to a value to be persisted, based on its column type and metadata.
*/
preparePersistentValue(value: any, columnMetadata: ColumnMetadata): any {
if (value === null || value === undefined)
return null;
switch (columnMetadata.type) {
// case ColumnTypes.BOOLEAN:
// return value === true ? 1 : 0;
//
// case ColumnTypes.DATE:
// return DataTransformationUtils.mixedDateToDateString(value);
//
// case ColumnTypes.TIME:
// return DataTransformationUtils.mixedDateToTimeString(value);
//
// case ColumnTypes.DATETIME:
// if (columnMetadata.localTimezone) {
// return DataTransformationUtils.mixedDateToDatetimeString(value);
// } else {
// return DataTransformationUtils.mixedDateToUtcDatetimeString(value);
// }
//
// case ColumnTypes.JSON:
// return JSON.stringify(value);
//
// case ColumnTypes.SIMPLE_ARRAY:
// return DataTransformationUtils.simpleArrayToString(value);
}
return value;
}
@ -183,38 +175,9 @@ export class MongoDriver implements Driver {
* Prepares given value to a value to be persisted, based on its column type or metadata.
*/
prepareHydratedValue(value: any, columnMetadata: ColumnMetadata): any {
switch (columnMetadata.type) {
// case ColumnTypes.BOOLEAN:
// return value ? true : false;
//
// case ColumnTypes.JSON:
// return JSON.parse(value);
//
// case ColumnTypes.SIMPLE_ARRAY:
// return DataTransformationUtils.stringToSimpleArray(value);
}
// if (columnMetadata.isObjectId)
// return new ObjectID(value);
return value;
}
/**
* Synchronizes database schema (creates indices).
*/
async syncSchema(): Promise<void> {
const queryRunner = await this.createQueryRunner() as MongoQueryRunner;
const promises: Promise<any>[] = [];
await Promise.all(this.connection.entityMetadatas.map(metadata => {
metadata.indices.forEach(index => {
const options = { name: index.name };
promises.push(queryRunner.createCollectionIndex(metadata.tableName, index.columnNamesWithOrderingMap, options));
});
}));
await Promise.all(promises);
}
// -------------------------------------------------------------------------
// Protected Methods
// -------------------------------------------------------------------------
@ -230,11 +193,11 @@ export class MongoDriver implements Driver {
}
/**
* If driver dependency is not given explicitly, then try to load it via "require".
* Loads all driver dependencies.
*/
protected loadDependencies(): any {
try {
return PlatformTools.load("mongodb"); // try to load native driver dynamically
this.mongodb = PlatformTools.load("mongodb"); // try to load native driver dynamically
} catch (e) {
throw new DriverPackageNotInstalledError("MongoDB", "mongodb");

View File

@ -8,35 +8,35 @@ import {ForeignKeySchema} from "../../schema-builder/schema/ForeignKeySchema";
import {IndexSchema} from "../../schema-builder/schema/IndexSchema";
import {ColumnType} from "../../metadata/types/ColumnTypes";
import {
AggregationCursor,
BulkWriteOpResultObject,
Code,
Collection,
CollectionAggregationOptions,
CollectionBluckWriteOptions,
CollectionInsertManyOptions,
CollectionInsertOneOptions,
CollectionOptions,
CollStats,
CommandCursor,
Cursor,
Db,
Collection,
MongoCountPreferences,
CollectionAggregationOptions,
AggregationCursor,
CollectionBluckWriteOptions,
BulkWriteOpResultObject,
MongodbIndexOptions,
CollectionOptions,
DeleteWriteOpResultObject,
FindAndModifyWriteOpResultObject,
FindOneAndReplaceOption,
GeoHaystackSearchOptions,
GeoNearOptions,
ReadPreference,
Code,
OrderedBulkOperation,
UnorderedBulkOperation,
InsertWriteOpResult,
CollectionInsertManyOptions,
CollectionInsertOneOptions,
InsertOneWriteOpResult,
CommandCursor,
InsertWriteOpResult,
MapReduceOptions,
MongoCountPreferences,
MongodbIndexOptions,
OrderedBulkOperation,
ParallelCollectionScanOptions,
ReadPreference,
ReplaceOneOptions,
UpdateWriteOpResult,
CollStats
UnorderedBulkOperation,
UpdateWriteOpResult
} from "./typings";
import {Connection} from "../../connection/Connection";

View File

@ -1,20 +1,16 @@
import {Driver} from "../Driver";
import {ConnectionIsNotSetError} from "../error/ConnectionIsNotSetError";
import {DriverOptions} from "../DriverOptions";
import {DatabaseConnection} from "../DatabaseConnection";
import {DriverPackageNotInstalledError} from "../error/DriverPackageNotInstalledError";
import {DriverUtils} from "../DriverUtils";
import {Logger} from "../../logger/Logger";
import {QueryRunner} from "../../query-runner/QueryRunner";
import {MysqlQueryRunner} from "./MysqlQueryRunner";
import {ColumnTypes} from "../../metadata/types/ColumnTypes";
import {ObjectLiteral} from "../../common/ObjectLiteral";
import {ColumnMetadata} from "../../metadata/ColumnMetadata";
import {DriverOptionNotSetError} from "../error/DriverOptionNotSetError";
import {DataTransformationUtils} from "../../util/DataTransformationUtils";
import {DataUtils} from "../../util/DataUtils";
import {PlatformTools} from "../../platform/PlatformTools";
import {NamingStrategyInterface} from "../../naming-strategy/NamingStrategyInterface";
import {LazyRelationsWrapper} from "../../lazy-loading/LazyRelationsWrapper";
import {Connection} from "../../connection/Connection";
import {SchemaBuilder} from "../../schema-builder/SchemaBuilder";
import {MysqlConnectionOptions} from "./MysqlConnectionOptions";
@ -29,26 +25,24 @@ export class MysqlDriver implements Driver {
// -------------------------------------------------------------------------
/**
* Mysql library.
* Connection options.
*/
protected options: MysqlConnectionOptions;
/**
* Mysql underlying library.
*/
protected mysql: any;
/**
* Connection to mysql database.
*/
protected databaseConnection: DatabaseConnection|undefined;
/**
* Mysql pool.
* Database connection pool created by underlying driver.
*/
protected pool: any;
/**
* Pool of database connections.
*/
protected databaseConnectionPool: DatabaseConnection[] = [];
protected options: MysqlConnectionOptions;
protected databaseConnections: DatabaseConnection[] = [];
// -------------------------------------------------------------------------
// Constructor
@ -77,10 +71,8 @@ export class MysqlDriver implements Driver {
/**
* Performs connection to the database.
* Based on pooling options, it can either create connection immediately,
* either create a pool and create connection when needed.
*/
connect(): Promise<void> {
async connect(): Promise<void> {
// build connection options for the driver
const options = Object.assign({}, {
@ -91,34 +83,21 @@ export class MysqlDriver implements Driver {
port: this.options.port
}, this.options.extra || {});
// pooling is enabled either when its set explicitly to true,
// either when its not defined at all (e.g. enabled by default)
this.pool = this.mysql.createPool(options);
return Promise.resolve();
}
/**
* Closes connection with the database.
*/
disconnect(): Promise<void> {
if (!this.databaseConnection && !this.pool)
if (!this.pool)
throw new ConnectionIsNotSetError("mysql");
return new Promise<void>((ok, fail) => {
const handler = (err: any) => err ? fail(err) : ok();
// if pooling is used, then disconnect from it
if (this.pool) {
this.pool.end(handler);
this.pool = undefined;
this.databaseConnectionPool = [];
}
// if single connection is opened, then close it
if (this.databaseConnection) {
this.databaseConnection.connection.end(handler);
this.databaseConnection = undefined;
}
this.pool.end(handler);
this.pool = undefined;
this.databaseConnections = [];
});
}
@ -126,6 +105,9 @@ export class MysqlDriver implements Driver {
* Synchronizes database schema (creates tables, indices, etc).
*/
syncSchema(): Promise<void> {
if (!this.pool)
throw new ConnectionIsNotSetError("mysql");
const schemaBuilder = new SchemaBuilder(this.connection);
return schemaBuilder.build();
}
@ -134,7 +116,7 @@ export class MysqlDriver implements Driver {
* Creates a query runner used for common queries.
*/
async createQueryRunner(): Promise<QueryRunner> {
if (!this.databaseConnection && !this.pool)
if (!this.pool)
return Promise.reject(new ConnectionIsNotSetError("mysql"));
const databaseConnection = await this.retrieveDatabaseConnection();
@ -147,7 +129,6 @@ export class MysqlDriver implements Driver {
nativeInterface() {
return {
driver: this.mysql,
connection: this.databaseConnection ? this.databaseConnection.connection : undefined,
pool: this.pool
};
}
@ -159,6 +140,7 @@ export class MysqlDriver implements Driver {
escapeQueryWithParameters(sql: string, parameters: ObjectLiteral): [string, any[]] {
if (!parameters || !Object.keys(parameters).length)
return [sql, []];
const escapedParameters: any[] = [];
const keys = Object.keys(parameters).map(parameter => "(:" + parameter + "\\b)").join("|");
sql = sql.replace(new RegExp(keys, "g"), (key: string) => {
@ -201,23 +183,23 @@ export class MysqlDriver implements Driver {
return value === true ? 1 : 0;
case ColumnTypes.DATE:
return DataTransformationUtils.mixedDateToDateString(value);
return DataUtils.mixedDateToDateString(value);
case ColumnTypes.TIME:
return DataTransformationUtils.mixedDateToTimeString(value);
return DataUtils.mixedDateToTimeString(value);
case ColumnTypes.DATETIME:
if (columnMetadata.localTimezone) {
return DataTransformationUtils.mixedDateToDatetimeString(value);
return DataUtils.mixedDateToDatetimeString(value);
} else {
return DataTransformationUtils.mixedDateToUtcDatetimeString(value);
return DataUtils.mixedDateToUtcDatetimeString(value);
}
case ColumnTypes.JSON:
return JSON.stringify(value);
case ColumnTypes.SIMPLE_ARRAY:
return DataTransformationUtils.simpleArrayToString(value);
return DataUtils.simpleArrayToString(value);
}
return value;
@ -232,19 +214,19 @@ export class MysqlDriver implements Driver {
return value ? true : false;
case ColumnTypes.DATETIME:
return DataTransformationUtils.normalizeHydratedDate(value, columnMetadata.localTimezone === true);
return DataUtils.normalizeHydratedDate(value, columnMetadata.localTimezone === true);
case ColumnTypes.DATE:
return DataTransformationUtils.mixedDateToDateString(value);
return DataUtils.mixedDateToDateString(value);
case ColumnTypes.TIME:
return DataTransformationUtils.mixedTimeToString(value);
return DataUtils.mixedTimeToString(value);
case ColumnTypes.JSON:
return JSON.parse(value);
case ColumnTypes.SIMPLE_ARRAY:
return DataTransformationUtils.stringToSimpleArray(value);
return DataUtils.stringToSimpleArray(value);
}
return value;
@ -260,42 +242,35 @@ export class MysqlDriver implements Driver {
* Otherwise active connection will be returned.
*/
protected retrieveDatabaseConnection(): Promise<DatabaseConnection> {
return new Promise((ok, fail) => {
this.pool.getConnection((err: any, connection: any) => {
if (err)
return fail(err);
if (this.pool) {
return new Promise((ok, fail) => {
this.pool.getConnection((err: any, connection: any) => {
if (err)
return fail(err);
let dbConnection = this.databaseConnectionPool.find(dbConnection => dbConnection.connection === connection);
if (!dbConnection) {
dbConnection = {
id: this.databaseConnectionPool.length,
connection: connection,
isTransactionActive: false
};
dbConnection.releaseCallback = () => {
if (this.pool && dbConnection) {
let dbConnection = this.databaseConnections.find(dbConnection => dbConnection.connection === connection);
if (!dbConnection) {
const driver = this;
dbConnection = {
id: this.databaseConnections.length,
connection: connection,
isTransactionActive: false,
releaseCallback: function() {
if (driver.pool) {
connection.release();
this.databaseConnectionPool.splice(this.databaseConnectionPool.indexOf(dbConnection), 1);
driver.databaseConnections.splice(driver.databaseConnections.indexOf(this), 1);
}
return Promise.resolve();
};
this.databaseConnectionPool.push(dbConnection);
}
ok(dbConnection);
});
}
};
this.databaseConnections.push(dbConnection);
}
ok(dbConnection);
});
}
if (this.databaseConnection)
return Promise.resolve(this.databaseConnection);
throw new ConnectionIsNotSetError("mysql");
});
}
/**
* If driver dependency is not given explicitly, then try to load it via "require".
* Loads all driver dependencies.
*/
protected loadDependencies(): void {
try {

View File

@ -3,8 +3,6 @@ import {DatabaseConnection} from "../DatabaseConnection";
import {ObjectLiteral} from "../../common/ObjectLiteral";
import {TransactionAlreadyStartedError} from "../error/TransactionAlreadyStartedError";
import {TransactionNotStartedError} from "../error/TransactionNotStartedError";
import {Logger} from "../../logger/Logger";
import {MysqlDriver} from "./MysqlDriver";
import {DataTypeNotSupportedByDriverError} from "../error/DataTypeNotSupportedByDriverError";
import {ColumnSchema} from "../../schema-builder/schema/ColumnSchema";
import {ColumnMetadata} from "../../metadata/ColumnMetadata";

View File

@ -1,26 +1,21 @@
import {Driver} from "../Driver";
import {ConnectionIsNotSetError} from "../error/ConnectionIsNotSetError";
import {DriverOptions} from "../DriverOptions";
import {DatabaseConnection} from "../DatabaseConnection";
import {DriverPackageNotInstalledError} from "../error/DriverPackageNotInstalledError";
import {DriverUtils} from "../DriverUtils";
import {Logger} from "../../logger/Logger";
import {QueryRunner} from "../../query-runner/QueryRunner";
import {OracleQueryRunner} from "./OracleQueryRunner";
import {ColumnTypes} from "../../metadata/types/ColumnTypes";
import {ObjectLiteral} from "../../common/ObjectLiteral";
import {ColumnMetadata} from "../../metadata/ColumnMetadata";
import {DriverOptionNotSetError} from "../error/DriverOptionNotSetError";
import {DataTransformationUtils} from "../../util/DataTransformationUtils";
import {DataUtils} from "../../util/DataUtils";
import {PlatformTools} from "../../platform/PlatformTools";
import {NamingStrategyInterface} from "../../naming-strategy/NamingStrategyInterface";
import {LazyRelationsWrapper} from "../../lazy-loading/LazyRelationsWrapper";
import {Connection} from "../../connection/Connection";
import {SchemaBuilder} from "../../schema-builder/SchemaBuilder";
import {OracleConnectionOptions} from "./OracleConnectionOptions";
/**
* Organizes communication with Oracle DBMS.
* Organizes communication with Oracle RDBMS.
*
* todo: this driver is not 100% finished yet, need to fix all issues that are left
*/
@ -31,17 +26,17 @@ export class OracleDriver implements Driver {
// -------------------------------------------------------------------------
/**
* Oracle library.
* Connection options.
*/
oracle: any;
protected options: OracleConnectionOptions;
/**
* Connection to oracle database.
* Underlying oracle library.
*/
protected databaseConnection: DatabaseConnection|undefined;
protected oracle: any;
/**
* Oracle pool.
* Database connection pool created by underlying driver.
*/
protected pool: any;
@ -50,8 +45,6 @@ export class OracleDriver implements Driver {
*/
protected databaseConnectionPool: DatabaseConnection[] = [];
protected options: OracleConnectionOptions;
// -------------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------------
@ -72,6 +65,8 @@ export class OracleDriver implements Driver {
// load oracle package
this.loadDependencies();
// extra oracle setup
this.oracle.outFormat = this.oracle.OBJECT;
}
@ -110,24 +105,16 @@ export class OracleDriver implements Driver {
* Closes connection with the database.
*/
disconnect(): Promise<void> {
if (!this.databaseConnection && !this.pool)
if (!this.pool)
throw new ConnectionIsNotSetError("oracle");
return new Promise<void>((ok, fail) => {
const handler = (err: any) => err ? fail(err) : ok();
// if pooling is used, then disconnect from it
if (this.pool) {
this.pool.close(handler);
this.pool = undefined;
this.databaseConnectionPool = [];
}
// if single connection is opened, then close it
if (this.databaseConnection) {
this.databaseConnection.connection.close(handler);
this.databaseConnection = undefined;
}
this.pool.close(handler);
this.pool = undefined;
this.databaseConnectionPool = [];
});
}
@ -143,7 +130,7 @@ export class OracleDriver implements Driver {
* Creates a query runner used for common queries.
*/
async createQueryRunner(): Promise<QueryRunner> {
if (!this.databaseConnection && !this.pool)
if (!this.pool)
return Promise.reject(new ConnectionIsNotSetError("oracle"));
const databaseConnection = await this.retrieveDatabaseConnection();
@ -156,7 +143,6 @@ export class OracleDriver implements Driver {
nativeInterface() {
return {
driver: this.oracle,
connection: this.databaseConnection ? this.databaseConnection.connection : undefined,
pool: this.pool
};
}
@ -181,7 +167,7 @@ export class OracleDriver implements Driver {
* Escapes a column name.
*/
escapeColumnName(columnName: string): string {
return `"${columnName}"`; // "`" + columnName + "`";
return `"${columnName}"`;
}
/**
@ -210,23 +196,23 @@ export class OracleDriver implements Driver {
return value === true ? 1 : 0;
case ColumnTypes.DATE:
return DataTransformationUtils.mixedDateToDateString(value);
return DataUtils.mixedDateToDateString(value);
case ColumnTypes.TIME:
return DataTransformationUtils.mixedDateToTimeString(value);
return DataUtils.mixedDateToTimeString(value);
case ColumnTypes.DATETIME:
if (columnMetadata.localTimezone) {
return DataTransformationUtils.mixedDateToDatetimeString(value);
return DataUtils.mixedDateToDatetimeString(value);
} else {
return DataTransformationUtils.mixedDateToUtcDatetimeString(value);
return DataUtils.mixedDateToUtcDatetimeString(value);
}
case ColumnTypes.JSON:
return JSON.stringify(value);
case ColumnTypes.SIMPLE_ARRAY:
return DataTransformationUtils.simpleArrayToString(value);
return DataUtils.simpleArrayToString(value);
}
return value;
@ -241,19 +227,19 @@ export class OracleDriver implements Driver {
return value ? true : false;
case ColumnTypes.DATETIME:
return DataTransformationUtils.normalizeHydratedDate(value, columnMetadata.localTimezone === true);
return DataUtils.normalizeHydratedDate(value, columnMetadata.localTimezone === true);
case ColumnTypes.DATE:
return DataTransformationUtils.mixedDateToDateString(value);
return DataUtils.mixedDateToDateString(value);
case ColumnTypes.TIME:
return DataTransformationUtils.mixedTimeToString(value);
return DataUtils.mixedTimeToString(value);
case ColumnTypes.JSON:
return JSON.parse(value);
case ColumnTypes.SIMPLE_ARRAY:
return DataTransformationUtils.stringToSimpleArray(value);
return DataUtils.stringToSimpleArray(value);
}
return value;
@ -269,54 +255,46 @@ export class OracleDriver implements Driver {
* Otherwise active connection will be returned.
*/
protected retrieveDatabaseConnection(): Promise<DatabaseConnection> {
return new Promise((ok, fail) => {
this.pool.getConnection((err: any, connection: any) => {
if (err)
return fail(err);
if (this.pool) {
return new Promise((ok, fail) => {
this.pool.getConnection((err: any, connection: any) => {
if (err)
return fail(err);
let dbConnection = this.databaseConnectionPool.find(dbConnection => dbConnection.connection === connection);
if (!dbConnection) {
dbConnection = {
id: this.databaseConnectionPool.length,
connection: connection,
isTransactionActive: false
};
dbConnection.releaseCallback = () => {
return new Promise<void>((ok, fail) => {
connection.close((err: any) => {
if (err)
return fail(err);
let dbConnection = this.databaseConnectionPool.find(dbConnection => dbConnection.connection === connection);
if (!dbConnection) {
dbConnection = {
id: this.databaseConnectionPool.length,
connection: connection,
isTransactionActive: false
};
dbConnection.releaseCallback = () => {
return new Promise<void>((ok, fail) => {
connection.close((err: any) => {
if (err)
return fail(err);
if (this.pool && dbConnection) {
this.databaseConnectionPool.splice(this.databaseConnectionPool.indexOf(dbConnection), 1);
}
ok();
});
if (this.pool && dbConnection) {
this.databaseConnectionPool.splice(this.databaseConnectionPool.indexOf(dbConnection), 1);
}
ok();
});
};
this.databaseConnectionPool.push(dbConnection);
}
ok(dbConnection);
});
});
};
this.databaseConnectionPool.push(dbConnection);
}
ok(dbConnection);
});
}
if (this.databaseConnection)
return Promise.resolve(this.databaseConnection);
throw new ConnectionIsNotSetError("oracle");
});
}
/**
* If driver dependency is not given explicitly, then try to load it via "require".
* Loads all driver dependencies.
*/
protected loadDependencies(): void {
try {
this.oracle = PlatformTools.load("oracledb");
} catch (e) { // todo: better error for browser env
} catch (e) {
throw new DriverPackageNotInstalledError("Oracle", "oracledb");
}
}

View File

@ -13,7 +13,6 @@ import {IndexSchema} from "../../schema-builder/schema/IndexSchema";
import {QueryRunnerAlreadyReleasedError} from "../../query-runner/error/QueryRunnerAlreadyReleasedError";
import {ColumnType} from "../../metadata/types/ColumnTypes";
import {Connection} from "../../connection/Connection";
import {OracleDriver} from "./OracleDriver";
import {OracleConnectionOptions} from "./OracleConnectionOptions";
/**
@ -180,7 +179,7 @@ export class OracleQueryRunner implements QueryRunner {
: `INSERT INTO ${this.connection.driver.escapeTableName(tableName)} DEFAULT VALUES`;
if (generatedColumn) {
const sql2 = `declare lastId number; begin ${insertSql} returning "id" into lastId; dbms_output.enable; dbms_output.put_line(lastId); dbms_output.get_line(:ln, :st); end;`;
const oracle = (this.connection.driver as OracleDriver).oracle;
const oracle = this.connection.driver.nativeInterface().driver;
const saveResult = await this.query(sql2, parameters.concat([
{ dir: oracle.BIND_OUT, type: oracle.STRING, maxSize: 32767 },
{ dir: oracle.BIND_OUT, type: oracle.NUMBER }

View File

@ -1,6 +1,5 @@
import {Driver} from "../Driver";
import {ConnectionIsNotSetError} from "../error/ConnectionIsNotSetError";
import {DriverOptions} from "../DriverOptions";
import {ObjectLiteral} from "../../common/ObjectLiteral";
import {DatabaseConnection} from "../DatabaseConnection";
import {DriverPackageNotInstalledError} from "../error/DriverPackageNotInstalledError";
@ -11,19 +10,12 @@ import {Logger} from "../../logger/Logger";
import {PostgresQueryRunner} from "./PostgresQueryRunner";
import {QueryRunner} from "../../query-runner/QueryRunner";
import {DriverOptionNotSetError} from "../error/DriverOptionNotSetError";
import {DataTransformationUtils} from "../../util/DataTransformationUtils";
import {DataUtils} from "../../util/DataUtils";
import {PlatformTools} from "../../platform/PlatformTools";
import {NamingStrategyInterface} from "../../naming-strategy/NamingStrategyInterface";
import {LazyRelationsWrapper} from "../../lazy-loading/LazyRelationsWrapper";
import {Connection} from "../../connection/Connection";
import {SchemaBuilder} from "../../schema-builder/SchemaBuilder";
import {PostgresConnectionOptions} from "./PostgresConnectionOptions";
// todo(tests):
// check connection with url
// check if any of required option is not set exception to be thrown
//
/**
* Organizes communication with PostgreSQL DBMS.
*/
@ -34,17 +26,17 @@ export class PostgresDriver implements Driver {
// -------------------------------------------------------------------------
/**
* Postgres library.
* Connection options.
*/
protected options: PostgresConnectionOptions;
/**
* Postgres underlying library.
*/
protected postgres: any;
/**
* Connection to postgres database.
*/
protected databaseConnection: DatabaseConnection|undefined;
/**
* Postgres pool.
* Database connection pool created by underlying driver.
*/
protected pool: any;
@ -53,19 +45,6 @@ export class PostgresDriver implements Driver {
*/
protected databaseConnectionPool: DatabaseConnection[] = [];
/**
* Logger used to log queries and errors.
*/
protected logger: Logger;
/**
* Schema name. (Only used in Postgres)
* default: "public"
*/
public schemaName?: string;
protected options: PostgresConnectionOptions;
// -------------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------------
@ -75,7 +54,6 @@ export class PostgresDriver implements Driver {
this.options = connection.options as PostgresConnectionOptions;
Object.assign(this.options, DriverUtils.buildDriverOptions(connection.options)); // todo: do it better way
this.schemaName = this.options.schemaName || "public";
// validate options to make sure everything is set
if (!this.options.host)
@ -119,28 +97,20 @@ export class PostgresDriver implements Driver {
* Closes connection with database.
*/
disconnect(): Promise<void> {
if (!this.databaseConnection && !this.pool)
if (!this.pool)
throw new ConnectionIsNotSetError("postgres");
return new Promise<void>((ok, fail) => {
const handler = (err: any) => err ? fail(err) : ok();
if (this.databaseConnection) {
this.databaseConnection.connection.end(/*handler*/); // todo: check if it can emit errors
this.databaseConnection = undefined;
}
if (this.pool) {
this.databaseConnectionPool.forEach(dbConnection => {
if (dbConnection && dbConnection.releaseCallback) {
dbConnection.releaseCallback();
}
});
this.pool.end(handler);
this.pool = undefined;
this.databaseConnectionPool = [];
}
this.databaseConnectionPool.forEach(dbConnection => {
if (dbConnection && dbConnection.releaseCallback) {
dbConnection.releaseCallback();
}
});
this.pool.end(handler);
this.pool = undefined;
this.databaseConnectionPool = [];
ok();
});
}
@ -157,7 +127,7 @@ export class PostgresDriver implements Driver {
* Creates a query runner used for common queries.
*/
async createQueryRunner(): Promise<QueryRunner> {
if (!this.databaseConnection && !this.pool)
if (!this.pool)
return Promise.reject(new ConnectionIsNotSetError("postgres"));
const databaseConnection = await this.retrieveDatabaseConnection();
@ -170,7 +140,6 @@ export class PostgresDriver implements Driver {
nativeInterface() {
return {
driver: this.postgres,
connection: this.databaseConnection ? this.databaseConnection.connection : undefined,
pool: this.pool
};
}
@ -187,16 +156,16 @@ export class PostgresDriver implements Driver {
return value === true ? 1 : 0;
case ColumnTypes.DATE:
return DataTransformationUtils.mixedDateToDateString(value);
return DataUtils.mixedDateToDateString(value);
case ColumnTypes.TIME:
return DataTransformationUtils.mixedDateToTimeString(value);
return DataUtils.mixedDateToTimeString(value);
case ColumnTypes.DATETIME:
if (column.localTimezone) {
return DataTransformationUtils.mixedDateToDatetimeString(value);
return DataUtils.mixedDateToDatetimeString(value);
} else {
return DataTransformationUtils.mixedDateToUtcDatetimeString(value);
return DataUtils.mixedDateToUtcDatetimeString(value);
}
case ColumnTypes.JSON:
@ -204,7 +173,7 @@ export class PostgresDriver implements Driver {
return JSON.stringify(value);
case ColumnTypes.SIMPLE_ARRAY:
return DataTransformationUtils.simpleArrayToString(value);
return DataUtils.simpleArrayToString(value);
}
return value;
@ -219,13 +188,13 @@ export class PostgresDriver implements Driver {
return value ? true : false;
case ColumnTypes.DATETIME:
return DataTransformationUtils.normalizeHydratedDate(value, columnMetadata.localTimezone === true);
return DataUtils.normalizeHydratedDate(value, columnMetadata.localTimezone === true);
case ColumnTypes.DATE:
return DataTransformationUtils.mixedDateToDateString(value);
return DataUtils.mixedDateToDateString(value);
case ColumnTypes.TIME:
return DataTransformationUtils.mixedTimeToString(value);
return DataUtils.mixedTimeToString(value);
case ColumnTypes.JSON:
case ColumnTypes.JSONB:
@ -234,7 +203,7 @@ export class PostgresDriver implements Driver {
return value;
case ColumnTypes.SIMPLE_ARRAY:
return DataTransformationUtils.stringToSimpleArray(value);
return DataUtils.stringToSimpleArray(value);
}
return value;
@ -296,47 +265,40 @@ export class PostgresDriver implements Driver {
* Otherwise active connection will be returned.
*/
protected retrieveDatabaseConnection(): Promise<DatabaseConnection> {
if (this.pool) {
return new Promise((ok, fail) => {
this.pool.connect((err: any, connection: any, release: Function) => {
if (err) {
fail(err);
return;
}
return new Promise((ok, fail) => {
this.pool.connect((err: any, connection: any, release: Function) => {
if (err) {
fail(err);
return;
}
let dbConnection = this.databaseConnectionPool.find(dbConnection => dbConnection.connection === connection);
if (!dbConnection) {
dbConnection = {
id: this.databaseConnectionPool.length,
connection: connection,
isTransactionActive: false
};
this.databaseConnectionPool.push(dbConnection);
}
dbConnection.releaseCallback = () => {
if (dbConnection) {
this.databaseConnectionPool.splice(this.databaseConnectionPool.indexOf(dbConnection), 1);
}
release();
return Promise.resolve();
let dbConnection = this.databaseConnectionPool.find(dbConnection => dbConnection.connection === connection);
if (!dbConnection) {
dbConnection = {
id: this.databaseConnectionPool.length,
connection: connection,
isTransactionActive: false
};
dbConnection.connection.query(`SET search_path TO '${this.schemaName}', 'public';`, (err: any) => {
if (err) {
this.connection.logger.logFailedQuery(`SET search_path TO '${this.schemaName}', 'public';`);
this.connection.logger.logQueryError(err);
fail(err);
} else {
ok(dbConnection);
}
});
this.databaseConnectionPool.push(dbConnection);
}
dbConnection.releaseCallback = () => {
if (dbConnection) {
this.databaseConnectionPool.splice(this.databaseConnectionPool.indexOf(dbConnection), 1);
}
release();
return Promise.resolve();
};
dbConnection.connection.query(`SET search_path TO '${this.options.schemaName || "default"}', 'public';`, (err: any) => {
if (err) {
this.connection.logger.logFailedQuery(`SET search_path TO '${this.options.schemaName || "default"}', 'public';`);
this.connection.logger.logQueryError(err);
fail(err);
} else {
ok(dbConnection);
}
});
});
}
if (this.databaseConnection)
return Promise.resolve(this.databaseConnection);
throw new ConnectionIsNotSetError("postgres");
});
}
/**

View File

@ -1,10 +1,8 @@
import {QueryRunner} from "../../query-runner/QueryRunner";
import {ObjectLiteral} from "../../common/ObjectLiteral";
import {Logger} from "../../logger/Logger";
import {DatabaseConnection} from "../DatabaseConnection";
import {TransactionAlreadyStartedError} from "../error/TransactionAlreadyStartedError";
import {TransactionNotStartedError} from "../error/TransactionNotStartedError";
import {PostgresDriver} from "./PostgresDriver";
import {DataTypeNotSupportedByDriverError} from "../error/DataTypeNotSupportedByDriverError";
import {ColumnSchema} from "../../schema-builder/schema/ColumnSchema";
import {ColumnMetadata} from "../../metadata/ColumnMetadata";

View File

@ -1,19 +1,15 @@
import {Driver} from "../Driver";
import {ConnectionIsNotSetError} from "../error/ConnectionIsNotSetError";
import {DriverOptions} from "../DriverOptions";
import {ObjectLiteral} from "../../common/ObjectLiteral";
import {DatabaseConnection} from "../DatabaseConnection";
import {DriverPackageNotInstalledError} from "../error/DriverPackageNotInstalledError";
import {ColumnTypes} from "../../metadata/types/ColumnTypes";
import {ColumnMetadata} from "../../metadata/ColumnMetadata";
import {Logger} from "../../logger/Logger";
import {SqliteQueryRunner} from "./SqliteQueryRunner";
import {QueryRunner} from "../../query-runner/QueryRunner";
import {DriverOptionNotSetError} from "../error/DriverOptionNotSetError";
import {DataTransformationUtils} from "../../util/DataTransformationUtils";
import {DataUtils} from "../../util/DataUtils";
import {PlatformTools} from "../../platform/PlatformTools";
import {NamingStrategyInterface} from "../../naming-strategy/NamingStrategyInterface";
import {LazyRelationsWrapper} from "../../lazy-loading/LazyRelationsWrapper";
import {Connection} from "../../connection/Connection";
import {SchemaBuilder} from "../../schema-builder/SchemaBuilder";
import {SqliteConnectionOptions} from "./SqliteConnectionOptions";
@ -28,7 +24,12 @@ export class SqliteDriver implements Driver {
// -------------------------------------------------------------------------
/**
* SQLite library.
* Connection options.
*/
protected options: SqliteConnectionOptions;
/**
* SQLite underlying library.
*/
protected sqlite: any;
@ -37,8 +38,6 @@ export class SqliteDriver implements Driver {
*/
protected databaseConnection: DatabaseConnection|undefined;
protected options: SqliteConnectionOptions;
// -------------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------------
@ -137,23 +136,23 @@ export class SqliteDriver implements Driver {
return value === true ? 1 : 0;
case ColumnTypes.DATE:
return DataTransformationUtils.mixedDateToDateString(value);
return DataUtils.mixedDateToDateString(value);
case ColumnTypes.TIME:
return DataTransformationUtils.mixedDateToTimeString(value);
return DataUtils.mixedDateToTimeString(value);
case ColumnTypes.DATETIME:
if (columnMetadata.localTimezone) {
return DataTransformationUtils.mixedDateToDatetimeString(value);
return DataUtils.mixedDateToDatetimeString(value);
} else {
return DataTransformationUtils.mixedDateToUtcDatetimeString(value);
return DataUtils.mixedDateToUtcDatetimeString(value);
}
case ColumnTypes.JSON:
return JSON.stringify(value);
case ColumnTypes.SIMPLE_ARRAY:
return DataTransformationUtils.simpleArrayToString(value);
return DataUtils.simpleArrayToString(value);
}
return value;
@ -168,19 +167,19 @@ export class SqliteDriver implements Driver {
return value ? true : false;
case ColumnTypes.DATETIME:
return DataTransformationUtils.normalizeHydratedDate(value, columnMetadata.localTimezone === true);
return DataUtils.normalizeHydratedDate(value, columnMetadata.localTimezone === true);
case ColumnTypes.DATE:
return DataTransformationUtils.mixedDateToDateString(value);
return DataUtils.mixedDateToDateString(value);
case ColumnTypes.TIME:
return DataTransformationUtils.mixedTimeToString(value);
return DataUtils.mixedTimeToString(value);
case ColumnTypes.JSON:
return JSON.parse(value);
case ColumnTypes.SIMPLE_ARRAY:
return DataTransformationUtils.stringToSimpleArray(value);
return DataUtils.stringToSimpleArray(value);
}
return value;

View File

@ -1,10 +1,8 @@
import {QueryRunner} from "../../query-runner/QueryRunner";
import {ObjectLiteral} from "../../common/ObjectLiteral";
import {Logger} from "../../logger/Logger";
import {DatabaseConnection} from "../DatabaseConnection";
import {TransactionAlreadyStartedError} from "../error/TransactionAlreadyStartedError";
import {TransactionNotStartedError} from "../error/TransactionNotStartedError";
import {SqliteDriver} from "./SqliteDriver";
import {DataTypeNotSupportedByDriverError} from "../error/DataTypeNotSupportedByDriverError";
import {ColumnSchema} from "../../schema-builder/schema/ColumnSchema";
import {ColumnMetadata} from "../../metadata/ColumnMetadata";

View File

@ -1,20 +1,16 @@
import {Driver} from "../Driver";
import {ConnectionIsNotSetError} from "../error/ConnectionIsNotSetError";
import {DriverOptions} from "../DriverOptions";
import {DatabaseConnection} from "../DatabaseConnection";
import {DriverPackageNotInstalledError} from "../error/DriverPackageNotInstalledError";
import {DriverUtils} from "../DriverUtils";
import {Logger} from "../../logger/Logger";
import {QueryRunner} from "../../query-runner/QueryRunner";
import {SqlServerQueryRunner} from "./SqlServerQueryRunner";
import {ColumnTypes} from "../../metadata/types/ColumnTypes";
import {ObjectLiteral} from "../../common/ObjectLiteral";
import {ColumnMetadata} from "../../metadata/ColumnMetadata";
import {DriverOptionNotSetError} from "../error/DriverOptionNotSetError";
import {DataTransformationUtils} from "../../util/DataTransformationUtils";
import {DataUtils} from "../../util/DataUtils";
import {PlatformTools} from "../../platform/PlatformTools";
import {NamingStrategyInterface} from "../../naming-strategy/NamingStrategyInterface";
import {LazyRelationsWrapper} from "../../lazy-loading/LazyRelationsWrapper";
import {Connection} from "../../connection/Connection";
import {SchemaBuilder} from "../../schema-builder/SchemaBuilder";
import {SqlServerConnectionOptions} from "./SqlServerConnectionOptions";
@ -24,23 +20,19 @@ import {SqlServerConnectionOptions} from "./SqlServerConnectionOptions";
*/
export class SqlServerDriver implements Driver {
// -------------------------------------------------------------------------
// Public Properties
// -------------------------------------------------------------------------
/**
* SQL Server library.
*/
public mssql: any;
// -------------------------------------------------------------------------
// Protected Properties
// -------------------------------------------------------------------------
/**
* Connection to mssql database.
* Connection options.
*/
protected databaseConnection: DatabaseConnection|undefined;
protected options: SqlServerConnectionOptions;
/**
* SQL Server library.
*/
protected mssql: any;
/**
* SQL Server pool.
@ -51,15 +43,12 @@ export class SqlServerDriver implements Driver {
* Pool of database connections.
*/
protected databaseConnectionPool: DatabaseConnection[] = [];
protected options: SqlServerConnectionOptions;
// -------------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------------
constructor(protected connection: Connection) {
this.options = connection.options as SqlServerConnectionOptions;
Object.assign(connection.options, DriverUtils.buildDriverOptions(connection.options)); // todo: do it better way
@ -119,7 +108,6 @@ export class SqlServerDriver implements Driver {
this.connectionPool.close();
this.connectionPool = undefined;
this.databaseConnection = undefined;
this.databaseConnectionPool = [];
}
@ -148,7 +136,6 @@ export class SqlServerDriver implements Driver {
nativeInterface() {
return {
driver: this.mssql,
connection: this.databaseConnection ? this.databaseConnection.connection : undefined,
pool: this.connectionPool
};
}
@ -210,23 +197,23 @@ export class SqlServerDriver implements Driver {
return value === true ? 1 : 0;
case ColumnTypes.DATE:
return DataTransformationUtils.mixedDateToDateString(value);
return DataUtils.mixedDateToDateString(value);
case ColumnTypes.TIME:
return DataTransformationUtils.mixedDateToTimeString(value);
return DataUtils.mixedDateToTimeString(value);
case ColumnTypes.DATETIME:
if (columnMetadata.localTimezone) {
return DataTransformationUtils.mixedDateToDatetimeString(value);
return DataUtils.mixedDateToDatetimeString(value);
} else {
return DataTransformationUtils.mixedDateToUtcDatetimeString(value);
return DataUtils.mixedDateToUtcDatetimeString(value);
}
case ColumnTypes.JSON:
return JSON.stringify(value);
case ColumnTypes.SIMPLE_ARRAY:
return DataTransformationUtils.simpleArrayToString(value);
return DataUtils.simpleArrayToString(value);
}
return value;
@ -241,19 +228,19 @@ export class SqlServerDriver implements Driver {
return value ? true : false;
case ColumnTypes.DATETIME:
return DataTransformationUtils.normalizeHydratedDate(value, columnMetadata.localTimezone === true);
return DataUtils.normalizeHydratedDate(value, columnMetadata.localTimezone === true);
case ColumnTypes.DATE:
return DataTransformationUtils.mixedDateToDateString(value);
return DataUtils.mixedDateToDateString(value);
case ColumnTypes.TIME:
return DataTransformationUtils.mixedTimeToString(value);
return DataUtils.mixedTimeToString(value);
case ColumnTypes.JSON:
return JSON.parse(value);
case ColumnTypes.SIMPLE_ARRAY:
return DataTransformationUtils.stringToSimpleArray(value);
return DataUtils.stringToSimpleArray(value);
}
return value;
@ -274,32 +261,12 @@ export class SqlServerDriver implements Driver {
throw new ConnectionIsNotSetError("mssql");
return new Promise((ok, fail) => {
if (this.databaseConnection)
return ok(this.databaseConnection);
// let dbConnection: DatabaseConnection|undefined;
// const connection = this.pool.connect((err: any) => {
// if (err)
// return fail(err);
// ok(dbConnection);
// });
//
// console.log(connection);
// console.log(this.pool);
// console.log(this.pool === connection);
// const request = new this.mssql.Request(this.connection);
// console.log("request:", request);
// let dbConnection = this.databaseConnectionPool.find(dbConnection => dbConnection.connection === connection);
// if (!dbConnection) {
let dbConnection: DatabaseConnection = {
id: this.databaseConnectionPool.length,
connection: this.connectionPool,
isTransactionActive: false
};
dbConnection.releaseCallback = () => {
// }
// if (this.connection && dbConnection) {
// request.release();
this.databaseConnectionPool.splice(this.databaseConnectionPool.indexOf(dbConnection), 1);
return Promise.resolve();
};

View File

@ -3,8 +3,6 @@ import {DatabaseConnection} from "../DatabaseConnection";
import {ObjectLiteral} from "../../common/ObjectLiteral";
import {TransactionAlreadyStartedError} from "../error/TransactionAlreadyStartedError";
import {TransactionNotStartedError} from "../error/TransactionNotStartedError";
import {Logger} from "../../logger/Logger";
import {SqlServerDriver} from "./SqlServerDriver";
import {DataTypeNotSupportedByDriverError} from "../error/DataTypeNotSupportedByDriverError";
import {ColumnSchema} from "../../schema-builder/schema/ColumnSchema";
import {ColumnMetadata} from "../../metadata/ColumnMetadata";
@ -15,8 +13,6 @@ import {IndexSchema} from "../../schema-builder/schema/IndexSchema";
import {QueryRunnerAlreadyReleasedError} from "../../query-runner/error/QueryRunnerAlreadyReleasedError";
import {ColumnType} from "../../metadata/types/ColumnTypes";
import {Connection} from "../../connection/Connection";
import {MysqlDriver} from "../mysql/MysqlDriver";
import {SqliteConnectionOptions} from "../sqlite/SqliteConnectionOptions";
import {SqlServerConnectionOptions} from "./SqlServerConnectionOptions";
/**
@ -198,7 +194,8 @@ export class SqlServerQueryRunner implements QueryRunner {
return new Promise((ok, fail) => {
this.connection.logger.logQuery(query, parameters);
const request = new (this.connection.driver as SqlServerDriver).mssql.Request(this.isTransactionActive() ? this.databaseConnection.transaction : this.databaseConnection.connection);
const mssql = this.connection.driver.nativeInterface().driver;
const request = new mssql.Request(this.isTransactionActive() ? this.databaseConnection.transaction : this.databaseConnection.connection);
if (parameters && parameters.length) {
parameters.forEach((parameter, index) => {
request.input(index, parameters![index]);

View File

@ -1,15 +1,13 @@
import {Driver} from "../Driver";
import {ConnectionIsNotSetError} from "../error/ConnectionIsNotSetError";
import {DriverOptions} from "../DriverOptions";
import {DatabaseConnection} from "../DatabaseConnection";
import {DriverUtils} from "../DriverUtils";
import {Logger} from "../../logger/Logger";
import {QueryRunner} from "../../query-runner/QueryRunner";
import {ColumnTypes} from "../../metadata/types/ColumnTypes";
import {ObjectLiteral} from "../../common/ObjectLiteral";
import {ColumnMetadata} from "../../metadata/ColumnMetadata";
import {DriverOptionNotSetError} from "../error/DriverOptionNotSetError";
import {DataTransformationUtils} from "../../util/DataTransformationUtils";
import {DataUtils} from "../../util/DataUtils";
import {WebsqlQueryRunner} from "./WebsqlQueryRunner";
import {Connection} from "../../connection/Connection";
import {SchemaBuilder} from "../../schema-builder/SchemaBuilder";
@ -29,12 +27,15 @@ export class WebsqlDriver implements Driver {
// Protected Properties
// -------------------------------------------------------------------------
/**
* Connection options.
*/
protected options: WebSqlConnectionOptions;
/**
* Connection to database.
*/
protected databaseConnection: DatabaseConnection|undefined;
protected options: WebSqlConnectionOptions;
// -------------------------------------------------------------------------
// Constructor
@ -178,23 +179,23 @@ export class WebsqlDriver implements Driver {
return value === true ? 1 : 0;
case ColumnTypes.DATE:
return DataTransformationUtils.mixedDateToDateString(value);
return DataUtils.mixedDateToDateString(value);
case ColumnTypes.TIME:
return DataTransformationUtils.mixedDateToTimeString(value);
return DataUtils.mixedDateToTimeString(value);
case ColumnTypes.DATETIME:
if (columnMetadata.localTimezone) {
return DataTransformationUtils.mixedDateToDatetimeString(value);
return DataUtils.mixedDateToDatetimeString(value);
} else {
return DataTransformationUtils.mixedDateToUtcDatetimeString(value);
return DataUtils.mixedDateToUtcDatetimeString(value);
}
case ColumnTypes.JSON:
return JSON.stringify(value);
case ColumnTypes.SIMPLE_ARRAY:
return DataTransformationUtils.simpleArrayToString(value);
return DataUtils.simpleArrayToString(value);
}
return value;
@ -209,19 +210,19 @@ export class WebsqlDriver implements Driver {
return value ? true : false;
case ColumnTypes.DATETIME:
return DataTransformationUtils.normalizeHydratedDate(value, columnMetadata.localTimezone === true);
return DataUtils.normalizeHydratedDate(value, columnMetadata.localTimezone === true);
case ColumnTypes.DATE:
return DataTransformationUtils.mixedDateToDateString(value);
return DataUtils.mixedDateToDateString(value);
case ColumnTypes.TIME:
return DataTransformationUtils.mixedTimeToString(value);
return DataUtils.mixedTimeToString(value);
case ColumnTypes.JSON:
return JSON.parse(value);
case ColumnTypes.SIMPLE_ARRAY:
return DataTransformationUtils.stringToSimpleArray(value);
return DataUtils.stringToSimpleArray(value);
}
return value;

View File

@ -3,7 +3,6 @@ import {DatabaseConnection} from "../DatabaseConnection";
import {ObjectLiteral} from "../../common/ObjectLiteral";
import {TransactionAlreadyStartedError} from "../error/TransactionAlreadyStartedError";
import {TransactionNotStartedError} from "../error/TransactionNotStartedError";
import {Logger} from "../../logger/Logger";
import {DataTypeNotSupportedByDriverError} from "../error/DataTypeNotSupportedByDriverError";
import {ColumnSchema} from "../../schema-builder/schema/ColumnSchema";
import {ColumnMetadata} from "../../metadata/ColumnMetadata";
@ -11,7 +10,6 @@ import {TableSchema} from "../../schema-builder/schema/TableSchema";
import {ForeignKeySchema} from "../../schema-builder/schema/ForeignKeySchema";
import {IndexSchema} from "../../schema-builder/schema/IndexSchema";
import {QueryRunnerAlreadyReleasedError} from "../../query-runner/error/QueryRunnerAlreadyReleasedError";
import {WebsqlDriver} from "./WebsqlDriver";
import {ColumnType} from "../../metadata/types/ColumnTypes";
import {Connection} from "../../connection/Connection";

View File

@ -76,6 +76,7 @@ export * from "./schema-builder/schema/PrimaryKeySchema";
export * from "./schema-builder/schema/TableSchema";
export * from "./driver/mongodb/typings";
export {ConnectionOptionsReader} from "./connection/ConnectionOptionsReader";
export {Connection} from "./connection/Connection";
export {ConnectionManager} from "./connection/ConnectionManager";
export {ConnectionOptions} from "./connection/ConnectionOptions";

View File

@ -3,7 +3,7 @@ import {EntityMetadata} from "../metadata/EntityMetadata";
import {ColumnMetadata} from "../metadata/ColumnMetadata";
import {RelationMetadata} from "../metadata/RelationMetadata";
import {ColumnTypes} from "../metadata/types/ColumnTypes";
import {DataTransformationUtils} from "../util/DataTransformationUtils";
import {DataUtils} from "../util/DataUtils";
/**
* Holds information about insert operation into junction table.
@ -327,18 +327,18 @@ export class Subject {
// normalize special values to make proper comparision
if (entityValue !== null && entityValue !== undefined) {
if (column.type === ColumnTypes.DATE) {
entityValue = DataTransformationUtils.mixedDateToDateString(entityValue);
entityValue = DataUtils.mixedDateToDateString(entityValue);
} else if (column.type === ColumnTypes.TIME) {
entityValue = DataTransformationUtils.mixedDateToTimeString(entityValue);
entityValue = DataUtils.mixedDateToTimeString(entityValue);
} else if (column.type === ColumnTypes.DATETIME) {
// if (column.loadInLocalTimezone) {
// entityValue = DataTransformationUtils.mixedDateToDatetimeString(entityValue);
// databaseValue = DataTransformationUtils.mixedDateToDatetimeString(databaseValue);
// } else {
entityValue = DataTransformationUtils.mixedDateToUtcDatetimeString(entityValue);
databaseValue = DataTransformationUtils.mixedDateToUtcDatetimeString(databaseValue);
entityValue = DataUtils.mixedDateToUtcDatetimeString(entityValue);
databaseValue = DataUtils.mixedDateToUtcDatetimeString(databaseValue);
// }
} else if (column.type === ColumnTypes.JSON) {
@ -347,8 +347,8 @@ export class Subject {
databaseValue = JSON.stringify(databaseValue);
} else if (column.type === ColumnTypes.SIMPLE_ARRAY) {
entityValue = DataTransformationUtils.simpleArrayToString(entityValue);
databaseValue = DataTransformationUtils.simpleArrayToString(databaseValue);
entityValue = DataUtils.simpleArrayToString(entityValue);
databaseValue = DataUtils.simpleArrayToString(databaseValue);
}
}
// todo: this mechanism does not get in count embeddeds in embeddeds

View File

@ -1,7 +1,7 @@
/**
* Provides utilities to transform hydrated and persisted data.
*/
export class DataTransformationUtils {
export class DataUtils {
// -------------------------------------------------------------------------
// Public Static Methods

View File

@ -23,6 +23,7 @@ import {Question} from "./modules/question/entity/Question";
import {Video} from "./modules/video/entity/Video";
import {ConnectionOptions} from "../../../src/connection/ConnectionOptions";
import {DefaultNamingStrategy} from "../../../src/naming-strategy/DefaultNamingStrategy";
import {PostgresConnectionOptions} from "../../../src/driver/postgres/PostgresConnectionOptions";
describe("Connection", () => {
const resourceDir = __dirname + "/../../../../../test/functional/connection/";
@ -294,7 +295,7 @@ describe("Connection", () => {
it("schema name can be set", () => {
return Promise.all(connections.map(async connection => {
await connection.syncSchema(true);
const schemaName = (connection.driver as PostgresDriver).schemaName;
const schemaName = (connection.options as PostgresConnectionOptions).schemaName;
const comment = new CommentV1();
comment.title = "Change SchemaName";
comment.context = `To ${schemaName}`;