Comparing version 0.0.2-alpha.55 to 0.0.2-alpha.56
@@ -161,3 +161,3 @@ "use strict"; | ||
const dbConnection = yield this.driver.retrieveDatabaseConnection(); | ||
if (forceSync) | ||
if (!forceSync) | ||
yield this.driver.beginTransaction(dbConnection); | ||
@@ -172,7 +172,7 @@ try { | ||
yield this.driver.releaseDatabaseConnection(dbConnection); | ||
if (forceSync) | ||
if (!forceSync) | ||
yield this.driver.commitTransaction(dbConnection); | ||
} | ||
catch (error) { | ||
if (forceSync) | ||
if (!forceSync) | ||
yield this.driver.rollbackTransaction(dbConnection); | ||
@@ -179,0 +179,0 @@ throw error; |
@@ -0,1 +1,2 @@ | ||
/// <reference types="chai" /> | ||
import { ObjectType } from "../common/ObjectType"; | ||
@@ -2,0 +3,0 @@ /** |
@@ -0,1 +1,2 @@ | ||
/// <reference types="chai" /> | ||
export declare class AutoIncrementOnlyForPrimaryError extends Error { | ||
@@ -2,0 +3,0 @@ name: string; |
@@ -0,1 +1,2 @@ | ||
/// <reference types="chai" /> | ||
export declare class ColumnTypeUndefinedError extends Error { | ||
@@ -2,0 +3,0 @@ name: string; |
@@ -0,1 +1,2 @@ | ||
/// <reference types="chai" /> | ||
export declare class PrimaryColumnCannotBeNullableError extends Error { | ||
@@ -2,0 +3,0 @@ name: string; |
@@ -0,1 +1,2 @@ | ||
/// <reference types="chai" /> | ||
/** | ||
@@ -2,0 +3,0 @@ * Fields that needs to be indexed must be marked with this decorator. |
@@ -0,1 +1,2 @@ | ||
/// <reference types="chai" /> | ||
/** | ||
@@ -2,0 +3,0 @@ * Calls a method on which this decorator is applied after this entity insertion. |
@@ -0,1 +1,2 @@ | ||
/// <reference types="chai" /> | ||
/** | ||
@@ -2,0 +3,0 @@ * Calls a method on which this decorator is applied after entity is loaded. |
@@ -0,1 +1,2 @@ | ||
/// <reference types="chai" /> | ||
/** | ||
@@ -2,0 +3,0 @@ * Calls a method on which this decorator is applied after this entity removal. |
@@ -0,1 +1,2 @@ | ||
/// <reference types="chai" /> | ||
/** | ||
@@ -2,0 +3,0 @@ * Calls a method on which this decorator is applied after this entity update. |
@@ -0,1 +1,2 @@ | ||
/// <reference types="chai" /> | ||
/** | ||
@@ -2,0 +3,0 @@ * Calls a method on which this decorator is applied before this entity insertion. |
@@ -0,1 +1,2 @@ | ||
/// <reference types="chai" /> | ||
/** | ||
@@ -2,0 +3,0 @@ * Calls a method on which this decorator is applied before this entity removal. |
@@ -0,1 +1,2 @@ | ||
/// <reference types="chai" /> | ||
/** | ||
@@ -2,0 +3,0 @@ * Calls a method on which this decorator is applied before this entity update. |
@@ -0,1 +1,2 @@ | ||
/// <reference types="chai" /> | ||
import { DriverOptions } from "./DriverOptions"; | ||
@@ -2,0 +3,0 @@ import { ColumnMetadata } from "../metadata/ColumnMetadata"; |
@@ -5,2 +5,3 @@ export interface DatabaseConnection { | ||
isTransactionActive: boolean; | ||
releaseCallback?: Function; | ||
} |
@@ -0,1 +1,2 @@ | ||
/// <reference types="chai" /> | ||
import { SchemaBuilder } from "../schema-builder/SchemaBuilder"; | ||
@@ -10,2 +11,6 @@ import { ColumnMetadata } from "../metadata/ColumnMetadata"; | ||
export interface Driver { | ||
readonly keysEscapingCharacter?: string; | ||
escapeColumnName(columnName: string): string; | ||
escapeAliasName(aliasName: string): string; | ||
escapeTableName(tableName: string): string; | ||
/** | ||
@@ -38,6 +43,2 @@ * Retrieves a new database connection. | ||
/** | ||
* Indicates if returned results are in lowercase. | ||
*/ | ||
readonly isResultsLowercase: boolean; | ||
/** | ||
* Creates a schema builder which can be used to build database/table schemas. | ||
@@ -44,0 +45,0 @@ */ |
@@ -12,3 +12,2 @@ import { Driver } from "./Driver"; | ||
connectionOptions: DriverOptions; | ||
readonly isResultsLowercase: boolean; | ||
/** | ||
@@ -21,8 +20,14 @@ * Mysql library. | ||
*/ | ||
private mysqlConnection; | ||
private databaseConnection; | ||
/** | ||
* Connection to mysql database. | ||
* Mysql pool. | ||
*/ | ||
private mysqlPool; | ||
private pool; | ||
/** | ||
* Pool of database connections. | ||
*/ | ||
private databaseConnectionPool; | ||
escapeColumnName(columnName: string): string; | ||
escapeAliasName(aliasName: string): string; | ||
escapeTableName(tableName: string): string; | ||
retrieveDatabaseConnection(): Promise<DatabaseConnection>; | ||
@@ -35,3 +40,3 @@ releaseDatabaseConnection(dbConnection: DatabaseConnection): Promise<void>; | ||
driver: any; | ||
connection: DatabaseConnection | undefined; | ||
connection: any; | ||
pool: any; | ||
@@ -38,0 +43,0 @@ }; |
@@ -23,6 +23,5 @@ "use strict"; | ||
this.connectionOptions = connectionOptions; | ||
// ------------------------------------------------------------------------- | ||
// Public Properties | ||
// ------------------------------------------------------------------------- | ||
this.isResultsLowercase = false; | ||
/** | ||
* Pool of database connections. | ||
*/ | ||
this.databaseConnectionPool = []; | ||
@@ -46,6 +45,17 @@ // if driver dependency is not given explicitly, then try to load it via "require" | ||
// ------------------------------------------------------------------------- | ||
escapeColumnName(columnName) { | ||
return columnName; | ||
} | ||
escapeAliasName(aliasName) { | ||
return aliasName; | ||
// return "\"" + aliasName + "\""; | ||
} | ||
escapeTableName(tableName) { | ||
return tableName; | ||
// return "\"" + aliasName + "\""; | ||
} | ||
retrieveDatabaseConnection() { | ||
if (this.mysqlPool) { | ||
if (this.pool) { | ||
return new Promise((ok, fail) => { | ||
this.mysqlPool.getConnection((err, connection) => { | ||
this.pool.getConnection((err, connection) => { | ||
if (err) { | ||
@@ -68,8 +78,8 @@ fail(err); | ||
} | ||
if (this.mysqlConnection) | ||
return Promise.resolve(this.mysqlConnection); | ||
if (this.databaseConnection) | ||
return Promise.resolve(this.databaseConnection); | ||
throw new ConnectionIsNotSetError_1.ConnectionIsNotSetError("mysql"); | ||
} | ||
releaseDatabaseConnection(dbConnection) { | ||
if (this.mysqlPool) | ||
if (this.pool) | ||
dbConnection.connection.release(); | ||
@@ -84,4 +94,4 @@ return Promise.resolve(); | ||
driver: this.mysql, | ||
connection: this.mysqlConnection, | ||
pool: this.mysqlPool | ||
connection: this.databaseConnection ? this.databaseConnection.connection : undefined, | ||
pool: this.pool | ||
}; | ||
@@ -93,3 +103,3 @@ } | ||
get nativeConnection() { | ||
return this.mysqlConnection; | ||
return this.databaseConnection; | ||
} | ||
@@ -100,4 +110,4 @@ /** | ||
get db() { | ||
if (this.mysqlConnection && this.mysqlConnection.connection.config.database) | ||
return this.mysqlConnection.connection.config.database; | ||
if (this.databaseConnection && this.databaseConnection.connection.config.database) | ||
return this.databaseConnection.connection.config.database; | ||
if (this.connectionOptions.database) | ||
@@ -130,3 +140,3 @@ return this.connectionOptions.database; | ||
return new Promise((ok, fail) => { | ||
this.mysqlConnection = { | ||
this.databaseConnection = { | ||
id: 1, | ||
@@ -136,7 +146,7 @@ connection: this.mysql.createConnection(options), | ||
}; | ||
this.mysqlConnection.connection.connect((err) => err ? fail(err) : ok()); | ||
this.databaseConnection.connection.connect((err) => err ? fail(err) : ok()); | ||
}); | ||
} | ||
else { | ||
this.mysqlPool = this.mysql.createPool(options); | ||
this.pool = this.mysql.createPool(options); | ||
return Promise.resolve(); | ||
@@ -152,10 +162,10 @@ } | ||
const handler = (err) => err ? fail(err) : ok(); | ||
if (this.mysqlPool) { | ||
this.mysqlPool.end(handler); | ||
this.mysqlPool = undefined; | ||
if (this.pool) { | ||
this.pool.end(handler); | ||
this.pool = undefined; | ||
this.databaseConnectionPool = []; | ||
} | ||
if (this.mysqlConnection) { | ||
this.mysqlConnection.connection.end(handler); | ||
this.mysqlConnection = undefined; | ||
if (this.databaseConnection) { | ||
this.databaseConnection.connection.end(handler); | ||
this.databaseConnection = undefined; | ||
} | ||
@@ -239,20 +249,18 @@ }); | ||
buildParameters(sql, parameters) { | ||
if (!parameters || !Object.keys(parameters).length) | ||
return []; | ||
const builtParameters = []; | ||
Object.keys(parameters).forEach((key, index) => { | ||
// const value = this.parameters[key] !== null && this.parameters[key] !== undefined ? this.driver.escape(this.parameters[key]) : "NULL"; | ||
sql = sql.replace(new RegExp(":" + key, "g"), (str) => { | ||
builtParameters.push(parameters[key]); | ||
return "?"; | ||
}); // todo: make replace only in value statements, otherwise problems | ||
}); | ||
const keys = Object.keys(parameters).map(parameter => "(:" + parameter + ")").join("|"); | ||
sql.replace(new RegExp(keys, "g"), (key) => { | ||
const value = parameters[key.substr(1)]; | ||
builtParameters.push(value); | ||
return "?"; | ||
}); // todo: make replace only in value statements, otherwise problems | ||
return builtParameters; | ||
} | ||
replaceParameters(sql, parameters) { | ||
Object.keys(parameters).forEach((key, index) => { | ||
// const value = parameters[key] !== null && parameters[key] !== undefined ? this.driver.escape(parameters[key]) : "NULL"; | ||
sql = sql.replace(new RegExp(":" + key, "g"), (str) => { | ||
return "?"; | ||
}); // todo: make replace only in value statements, otherwise problems | ||
}); | ||
return sql; | ||
if (!parameters || !Object.keys(parameters).length) | ||
return sql; | ||
const keys = Object.keys(parameters).map(parameter => "(:" + parameter + ")").join("|"); | ||
return sql.replace(new RegExp(keys, "g"), "?"); | ||
} | ||
@@ -263,3 +271,3 @@ // ------------------------------------------------------------------------- | ||
checkIfConnectionSet() { | ||
if (!this.mysqlConnection && !this.mysqlPool) | ||
if (!this.databaseConnection && !this.pool) | ||
throw new ConnectionIsNotSetError_1.ConnectionIsNotSetError("mysql"); | ||
@@ -266,0 +274,0 @@ } |
@@ -12,3 +12,2 @@ import { Driver } from "./Driver"; | ||
connectionOptions: DriverOptions; | ||
readonly isResultsLowercase: boolean; | ||
/** | ||
@@ -21,7 +20,19 @@ * Postgres library. | ||
*/ | ||
private postgresConnection; | ||
private databaseConnection; | ||
/** | ||
* Postgres pool. | ||
*/ | ||
private pool; | ||
/** | ||
* Pool of database connections. | ||
*/ | ||
private databaseConnectionPool; | ||
/** | ||
* Access to the native implementation of the database. | ||
*/ | ||
readonly native: any; | ||
readonly native: { | ||
driver: any; | ||
connection: any; | ||
pool: any; | ||
}; | ||
/** | ||
@@ -36,2 +47,5 @@ * Access to the native connection to the database. | ||
constructor(connectionOptions: DriverOptions, postgres?: any); | ||
escapeColumnName(columnName: string): string; | ||
escapeAliasName(aliasName: string): string; | ||
escapeTableName(tableName: string): string; | ||
retrieveDatabaseConnection(): Promise<DatabaseConnection>; | ||
@@ -60,2 +74,14 @@ releaseDatabaseConnection(dbConnection: DatabaseConnection): Promise<void>; | ||
/** | ||
* Starts transaction. | ||
*/ | ||
beginTransaction(dbConnection: DatabaseConnection): Promise<void>; | ||
/** | ||
* Commits transaction. | ||
*/ | ||
commitTransaction(dbConnection: DatabaseConnection): Promise<void>; | ||
/** | ||
* Rollbacks transaction. | ||
*/ | ||
rollbackTransaction(dbConnection: DatabaseConnection): Promise<void>; | ||
/** | ||
* Clears all tables in the currently connected database. | ||
@@ -62,0 +88,0 @@ */ |
@@ -23,6 +23,6 @@ "use strict"; | ||
this.connectionOptions = connectionOptions; | ||
// ------------------------------------------------------------------------- | ||
// Public Properties | ||
// ------------------------------------------------------------------------- | ||
this.isResultsLowercase = true; | ||
/** | ||
* Pool of database connections. | ||
*/ | ||
this.databaseConnectionPool = []; | ||
// if driver dependency is not given explicitly, then try to load it via "require" | ||
@@ -49,3 +49,7 @@ if (!postgres && require) { | ||
get native() { | ||
return this.postgres; | ||
return { | ||
driver: this.postgres, | ||
connection: this.databaseConnection ? this.databaseConnection.connection : undefined, | ||
pool: this.pool | ||
}; | ||
} | ||
@@ -56,3 +60,3 @@ /** | ||
get nativeConnection() { | ||
return this.postgresConnection; | ||
return this.databaseConnection; | ||
} | ||
@@ -73,6 +77,15 @@ /** | ||
// ------------------------------------------------------------------------- | ||
escapeColumnName(columnName) { | ||
return "\"" + columnName + "\""; | ||
} | ||
escapeAliasName(aliasName) { | ||
return "\"" + aliasName + "\""; | ||
} | ||
escapeTableName(tableName) { | ||
return "\"" + tableName + "\""; | ||
} | ||
retrieveDatabaseConnection() { | ||
/*if (this.postgresPool) { // todo: rename to databaseConnectionPool | ||
if (this.pool) { | ||
return new Promise((ok, fail) => { | ||
this.postgresPool.getConnection((err: any, connection: any) => { | ||
this.pool.connect((err, connection, release) => { | ||
if (err) { | ||
@@ -82,15 +95,24 @@ fail(err); | ||
} | ||
ok(connection); | ||
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 = release; | ||
ok(dbConnection); | ||
}); | ||
}); | ||
}*/ | ||
if (this.postgresConnection) | ||
return Promise.resolve(this.postgresConnection); | ||
throw new ConnectionIsNotSetError_1.ConnectionIsNotSetError("mysql"); | ||
} | ||
if (this.databaseConnection) | ||
return Promise.resolve(this.databaseConnection); | ||
throw new ConnectionIsNotSetError_1.ConnectionIsNotSetError("postgres"); | ||
} | ||
releaseDatabaseConnection(dbConnection) { | ||
// if (this.mysqlPool) { | ||
// dbConnection.connection.release(); | ||
// } | ||
if (this.pool && dbConnection.releaseCallback) { | ||
dbConnection.releaseCallback(); | ||
} | ||
return Promise.resolve(); | ||
@@ -108,17 +130,23 @@ } | ||
connect() { | ||
return new Promise((ok, fail) => { | ||
const options = Object.assign({}, { | ||
host: this.connectionOptions.host, | ||
user: this.connectionOptions.username, | ||
password: this.connectionOptions.password, | ||
database: this.connectionOptions.database, | ||
port: this.connectionOptions.port | ||
}, this.connectionOptions.extra || {}); | ||
this.postgresConnection = { | ||
id: 1, | ||
connection: new this.postgres.Client(options), | ||
isTransactionActive: false | ||
}; | ||
this.postgresConnection.connection.connect((err) => err ? fail(err) : ok()); | ||
}); | ||
const options = Object.assign({}, { | ||
host: this.connectionOptions.host, | ||
user: this.connectionOptions.username, | ||
password: this.connectionOptions.password, | ||
database: this.connectionOptions.database, | ||
port: this.connectionOptions.port | ||
}, this.connectionOptions.extra || {}); | ||
if (this.connectionOptions.usePool === false) { | ||
return new Promise((ok, fail) => { | ||
this.databaseConnection = { | ||
id: 1, | ||
connection: new this.postgres.Client(options), | ||
isTransactionActive: false | ||
}; | ||
this.databaseConnection.connection.connect((err) => err ? fail(err) : ok()); | ||
}); | ||
} | ||
else { | ||
this.pool = new this.postgres.Pool(options); | ||
return Promise.resolve(); | ||
} | ||
} | ||
@@ -131,6 +159,15 @@ /** | ||
return new Promise((ok, fail) => { | ||
if (this.postgresConnection) { | ||
this.postgresConnection.connection.end(); // todo: check if it can emit errors | ||
this.postgresConnection = undefined; | ||
if (this.databaseConnection) { | ||
this.databaseConnection.connection.end(); // todo: check if it can emit errors | ||
this.databaseConnection = undefined; | ||
} | ||
if (this.databaseConnectionPool) { | ||
this.databaseConnectionPool.forEach(dbConnection => { | ||
if (dbConnection && dbConnection.releaseCallback) { | ||
dbConnection.releaseCallback(); | ||
} | ||
}); | ||
this.pool = undefined; | ||
this.databaseConnectionPool = []; | ||
} | ||
ok(); | ||
@@ -154,5 +191,3 @@ }); | ||
return new Promise((ok, fail) => { | ||
if (!this.postgresConnection) | ||
return fail(new ConnectionIsNotSetError_1.ConnectionIsNotSetError("postgres")); | ||
this.postgresConnection.connection.query(query, parameters, (err, result) => { | ||
dbConnection.connection.query(query, parameters, (err, result) => { | ||
if (err) { | ||
@@ -170,2 +205,35 @@ this.logFailedQuery(query); | ||
/** | ||
* Starts transaction. | ||
*/ | ||
beginTransaction(dbConnection) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
if (dbConnection.isTransactionActive) | ||
throw new Error(`Transaction already started for the given connection, commit current transaction before starting a new one.`); | ||
yield this.query(dbConnection, "START TRANSACTION"); | ||
dbConnection.isTransactionActive = true; | ||
}); | ||
} | ||
/** | ||
* Commits transaction. | ||
*/ | ||
commitTransaction(dbConnection) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
if (!dbConnection.isTransactionActive) | ||
throw new Error(`Transaction is not started yet, start transaction before committing it.`); | ||
yield this.query(dbConnection, "COMMIT"); | ||
dbConnection.isTransactionActive = false; | ||
}); | ||
} | ||
/** | ||
* Rollbacks transaction. | ||
*/ | ||
rollbackTransaction(dbConnection) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
if (!dbConnection.isTransactionActive) | ||
throw new Error(`Transaction is not started yet, start transaction before rolling it back.`); | ||
yield this.query(dbConnection, "ROLLBACK"); | ||
dbConnection.isTransactionActive = false; | ||
}); | ||
} | ||
/** | ||
* Clears all tables in the currently connected database. | ||
@@ -175,3 +243,3 @@ */ | ||
this.checkIfConnectionSet(); | ||
const dropTablesQuery = `SELECT 'DROP TABLE IF EXISTS "' || tablename || '" CASCADE;' as q FROM pg_tables WHERE schemaname = 'public';`; | ||
const dropTablesQuery = `SELECT 'DROP TABLE IF EXISTS "' || tablename || '" CASCADE;' as q FROM pg_tables WHERE schemaname = 'public'`; | ||
return this.query(dbConnection, dropTablesQuery) | ||
@@ -182,18 +250,37 @@ .then(results => Promise.all(results.map(q => this.query(dbConnection, q["q"])))) | ||
buildParameters(sql, parameters) { | ||
if (!parameters || !Object.keys(parameters).length) | ||
return []; | ||
const builtParameters = []; | ||
Object.keys(parameters).forEach((key, index) => { | ||
// const value = this.parameters[key] !== null && this.parameters[key] !== undefined ? this.driver.escape(this.parameters[key]) : "NULL"; | ||
sql = sql.replace(new RegExp(":" + key, "g"), (str) => { | ||
builtParameters.push(parameters[key]); | ||
return ""; | ||
}); // todo: make replace only in value statements, otherwise problems | ||
}); | ||
const keys = Object.keys(parameters).map(parameter => "(:" + parameter + ")").join("|"); | ||
sql.replace(new RegExp(keys, "g"), (key) => { | ||
const value = parameters[key.substr(1)]; | ||
if (value instanceof Array) { | ||
return value.map((v) => { | ||
builtParameters.push(v); | ||
}); | ||
} | ||
else { | ||
builtParameters.push(value); | ||
} | ||
return "?"; | ||
}); // todo: make replace only in value statements, otherwise problems | ||
return builtParameters; | ||
} | ||
replaceParameters(sql, parameters) { | ||
Object.keys(parameters).forEach((key, index) => { | ||
// const value = parameters[key] !== null && parameters[key] !== undefined ? this.driver.escape(parameters[key]) : "NULL"; | ||
sql = sql.replace(new RegExp(":" + key, "g"), (str) => { | ||
return "$" + (index + 1); | ||
}); // todo: make replace only in value statements, otherwise problems | ||
if (!parameters || !Object.keys(parameters).length) | ||
return sql; | ||
const builtParameters = []; | ||
const keys = Object.keys(parameters).map(parameter => "(:" + parameter + ")").join("|"); | ||
sql = sql.replace(new RegExp(keys, "g"), (key) => { | ||
const value = parameters[key.substr(1)]; | ||
if (value instanceof Array) { | ||
return value.map((v) => { | ||
builtParameters.push(v); | ||
return "$" + builtParameters.length; | ||
}); | ||
} | ||
else { | ||
builtParameters.push(value); | ||
} | ||
return "$" + builtParameters.length; | ||
}); | ||
@@ -207,6 +294,6 @@ return sql; | ||
this.checkIfConnectionSet(); | ||
const columns = Object.keys(keyValues).join(","); | ||
const columns = Object.keys(keyValues).join("\", \""); | ||
const values = Object.keys(keyValues).map((key, index) => "$" + (index + 1)).join(","); // todo: escape here | ||
const params = Object.keys(keyValues).map(key => keyValues[key]); | ||
let query = `INSERT INTO ${tableName}(${columns}) VALUES (${values})`; | ||
let query = `INSERT INTO "${tableName}"("${columns}") VALUES (${values})`; | ||
if (idColumnName) { | ||
@@ -227,7 +314,7 @@ query += " RETURNING " + idColumnName; | ||
this.checkIfConnectionSet(); | ||
const updateValues = this.parametrizeObjectMap(valuesMap).join(","); | ||
const updateValues = this.parametrizeObjectMap(valuesMap).join(", "); | ||
const conditionString = this.parametrizeObjectMap(conditions, Object.keys(valuesMap).length).join(" AND "); | ||
const updateParams = Object.keys(valuesMap).map(key => valuesMap[key]); | ||
const conditionParams = Object.keys(conditions).map(key => conditions[key]); | ||
const query = `UPDATE ${tableName} SET ${updateValues} ${conditionString ? (" WHERE " + conditionString) : ""}`; | ||
const query = `UPDATE "${tableName}" SET ${updateValues} ${conditionString ? (" WHERE " + conditionString) : ""}`; | ||
// console.log("executing update: ", query); | ||
@@ -245,3 +332,3 @@ yield this.query(dbConnection, query, updateParams.concat(conditionParams)); | ||
const params = Object.keys(conditions).map(key => conditions[key]); | ||
const query = `DELETE FROM ${tableName} WHERE ${conditionString}`; | ||
const query = `DELETE FROM "${tableName}" WHERE ${conditionString}`; | ||
yield this.query(dbConnection, query, params); | ||
@@ -259,3 +346,3 @@ }); | ||
// } else { | ||
return key + "=$" + (startIndex + index + 1); | ||
return "\"" + key + "\"=$" + (startIndex + index + 1); | ||
// } | ||
@@ -265,3 +352,3 @@ }); | ||
checkIfConnectionSet() { | ||
if (!this.postgresConnection) | ||
if (!this.databaseConnection && !this.pool) | ||
throw new ConnectionIsNotSetError_1.ConnectionIsNotSetError("postgres"); | ||
@@ -268,0 +355,0 @@ } |
@@ -0,1 +1,2 @@ | ||
/// <reference types="chai" /> | ||
import { Connection } from "../connection/Connection"; | ||
@@ -2,0 +3,0 @@ import { QueryBuilder } from "../query-builder/QueryBuilder"; |
@@ -0,1 +1,2 @@ | ||
/// <reference types="chai" /> | ||
import { Connection } from "../connection/Connection"; | ||
@@ -2,0 +3,0 @@ import { FindOptions } from "../repository/FindOptions"; |
@@ -0,1 +1,2 @@ | ||
/// <reference types="chai" /> | ||
import * as Rx from "rxjs/Rx"; | ||
@@ -2,0 +3,0 @@ import { Connection } from "../connection/Connection"; |
@@ -34,3 +34,3 @@ "use strict"; | ||
const propertiesMap = this.entityMetadata.createPropertiesMap(); | ||
return this._columns(propertiesMap).map((i) => String(i).toLowerCase()); | ||
return this._columns(propertiesMap).map((i) => String(i)); | ||
} | ||
@@ -37,0 +37,0 @@ } |
{ | ||
"name": "typeorm", | ||
"private": false, | ||
"version": "0.0.2-alpha.55", | ||
"version": "0.0.2-alpha.56", | ||
"description": "Data-mapper ORM for Typescript", | ||
@@ -6,0 +6,0 @@ "license": "Apache-2.0", |
@@ -0,1 +1,2 @@ | ||
/// <reference types="chai" /> | ||
import { Alias } from "./alias/Alias"; | ||
@@ -2,0 +3,0 @@ import { Broadcaster } from "../subscriber/Broadcaster"; |
@@ -327,7 +327,3 @@ "use strict"; | ||
let idsQuery = `SELECT DISTINCT(distinctAlias.${mainAliasName}_${metadata.primaryColumn.name}) as ids`; | ||
if (this.orderBys && this.orderBys.length > 0) | ||
idsQuery += ", " + this.orderBys.map(orderBy => orderBy.sort.replace(".", "_")).join(", "); | ||
idsQuery += ` FROM (${this.getSql()}) distinctAlias`; // TODO: WHAT TO DO WITH PARAMETERS HERE? DO THEY WORK? | ||
if (this.orderBys && this.orderBys.length > 0) | ||
idsQuery += " ORDER BY " + this.orderBys.map(order => "distinctAlias." + order.sort.replace(".", "_") + " " + order.order).join(", "); | ||
if (this.maxResults) | ||
@@ -340,10 +336,12 @@ idsQuery += " LIMIT " + this.maxResults; | ||
scalarResults = results; | ||
const ids = results.map(result => result["ids"]).join(", "); | ||
const ids = results.map(result => result["ids"]); | ||
if (ids.length === 0) | ||
return []; | ||
const queryWithIds = this.clone({ dbConnection: dbConnection }) | ||
.andWhere(mainAliasName + "." + metadata.primaryColumn.name + " IN (" + ids + ")"); | ||
.andWhere(mainAliasName + "." + metadata.primaryColumn.propertyName + " IN (:ids)", { ids: ids }); | ||
return this.driver.query(dbConnection, queryWithIds.getSql(), queryWithIds.getParameters()); | ||
}) | ||
.then(results => this.rawResultsToEntities(results)) | ||
.then(results => { | ||
return this.rawResultsToEntities(results); | ||
}) | ||
.then(results => this.broadcaster.broadcastLoadEventsForAll(this.aliasMap.mainAlias.target, results).then(() => results)) | ||
@@ -457,3 +455,5 @@ .then(results => { | ||
// relationCountMeta.alias.target; | ||
const ids = relationCountMeta.entities.map(entityWithMetadata => entityWithMetadata.entity[entityWithMetadata.metadata.primaryColumn.propertyName]); | ||
const ids = relationCountMeta.entities | ||
.map(entityWithMetadata => entityWithMetadata.entity[entityWithMetadata.metadata.primaryColumn.propertyName]) | ||
.filter(id => id !== undefined); | ||
if (!ids || !ids.length) | ||
@@ -463,3 +463,3 @@ throw new Error(`No ids found to load relation counters`); | ||
.select(`${parentMetadata.name + "." + parentMetadata.primaryColumn.propertyName} as id`) | ||
.addSelect(`COUNT(${relation.propertyName + "." + relation.inverseEntityMetadata.primaryColumn.propertyName}) as cnt`) | ||
.addSelect(`COUNT(${this.driver.escapeAliasName(relation.propertyName) + "." + this.driver.escapeColumnName(relation.inverseEntityMetadata.primaryColumn.name)}) as cnt`) | ||
.from(parentMetadata.target, parentMetadata.name) | ||
@@ -481,6 +481,6 @@ .leftJoin(parentMetadata.name + "." + relation.propertyName, relation.propertyName, relationCountMeta.conditionType, relationCountMeta.condition) | ||
// different properties are working. make different classes to work too | ||
entityWithMetadata.entity[propertyName] = entityResult.cnt; | ||
entityWithMetadata.entity[propertyName] = parseInt(entityResult.cnt); | ||
} | ||
else if (relation.countField) { | ||
entityWithMetadata.entity[relation.countField] = entityResult.cnt; | ||
entityWithMetadata.entity[relation.countField] = parseInt(entityResult.cnt); | ||
} | ||
@@ -606,6 +606,8 @@ } | ||
alias = this.fromEntity.alias.name; | ||
// console.log("ALIAS N:", this.fromEntity.alias); | ||
// console.log("ALIAS N:", alias); | ||
// add select from the main table | ||
if (this.selects.indexOf(alias) !== -1) { | ||
metadata.columns.forEach(column => { | ||
allSelects.push(alias + "." + column.name + " AS " + alias + "_" + column.name); | ||
allSelects.push(this.driver.escapeAliasName(alias) + "." + this.driver.escapeColumnName(column.name) + " AS " + this.driver.escapeAliasName(alias + "_" + column.name)); | ||
}); | ||
@@ -624,7 +626,7 @@ } | ||
joinMetadata.columns.forEach(column => { | ||
allSelects.push(join.alias.name + "." + column.name + " AS " + join.alias.name + "_" + column.name); | ||
allSelects.push(this.driver.escapeAliasName(join.alias.name) + "." + this.driver.escapeColumnName(column.name) + " AS " + this.driver.escapeAliasName(join.alias.name + "_" + column.name)); | ||
}); | ||
} | ||
else { | ||
allSelects.push(join.alias.name); | ||
allSelects.push(this.driver.escapeAliasName(join.alias.name)); | ||
} | ||
@@ -646,3 +648,3 @@ }); | ||
junctionMetadata.columns.forEach(column => { | ||
allSelects.push(join.alias.name + "." + column.name + " AS " + join.alias.name + "_" + column.name); | ||
allSelects.push(this.driver.escapeAliasName(join.alias.name) + "." + this.driver.escapeColumnName(column.name) + " AS " + this.driver.escapeAliasName(join.alias.name + "_" + column.name)); | ||
}); | ||
@@ -660,5 +662,5 @@ }); | ||
case "select": | ||
return "SELECT " + allSelects.join(", ") + " FROM " + tableName + " " + alias; | ||
return "SELECT " + allSelects.join(", ") + " FROM " + this.driver.escapeTableName(tableName) + " " + this.driver.escapeAliasName(alias); | ||
case "delete": | ||
return "DELETE " + (alias ? alias : "") + " FROM " + tableName + " " + (alias ? alias : ""); | ||
return "DELETE " + (alias ? this.driver.escapeAliasName(alias) : "") + " FROM " + this.driver.escapeTableName(tableName) + " " + (alias ? this.driver.escapeAliasName(alias) : ""); | ||
case "update": | ||
@@ -672,3 +674,3 @@ const updateSet = Object.keys(this.updateQuerySet).map(key => key + "=:updateQuerySet_" + key); | ||
this.addParameters(params); | ||
return "UPDATE " + tableName + " " + (alias ? alias : "") + " SET " + updateSet; | ||
return "UPDATE " + tableName + " " + (alias ? this.driver.escapeAliasName(alias) : "") + " SET " + updateSet; | ||
} | ||
@@ -702,3 +704,3 @@ throw new Error("No query builder type is specified."); | ||
const expression = alias.name + "." + embedded.propertyName + "." + column.propertyName + "([ =]|.{0}$)"; | ||
statement = statement.replace(new RegExp(expression, "gm"), alias.name + "." + column.name + "$1"); | ||
statement = statement.replace(new RegExp(expression, "gm"), this.driver.escapeAliasName(alias.name) + "." + this.driver.escapeColumnName(column.name) + "$1"); | ||
}); | ||
@@ -708,7 +710,7 @@ }); | ||
const expression = alias.name + "." + column.propertyName + "([ =]|.{0}$)"; | ||
statement = statement.replace(new RegExp(expression, "gm"), alias.name + "." + column.name + "$1"); | ||
statement = statement.replace(new RegExp(expression, "gm"), this.driver.escapeAliasName(alias.name) + "." + this.driver.escapeColumnName(column.name) + "$1"); | ||
}); | ||
metadata.relationsWithJoinColumns.forEach(relation => { | ||
const expression = alias.name + "." + relation.propertyName + "([ =]|.{0}$)"; | ||
statement = statement.replace(new RegExp(expression, "gm"), alias.name + "." + relation.name + "$1"); | ||
statement = statement.replace(new RegExp(expression, "gm"), this.driver.escapeAliasName(alias.name) + "." + this.driver.escapeColumnName(relation.name) + "$1"); | ||
}); | ||
@@ -735,8 +737,8 @@ }); | ||
if (relation.isOwning) { | ||
condition1 = junctionAlias + "." + junctionMetadata.columns[0].name + "=" + parentAlias + "." + joinTableColumn; | ||
condition1 = this.driver.escapeAliasName(junctionAlias) + "." + this.driver.escapeColumnName(junctionMetadata.columns[0].name) + "=" + this.driver.escapeAliasName(parentAlias) + "." + this.driver.escapeColumnName(joinTableColumn); | ||
} | ||
else { | ||
condition1 = junctionAlias + "." + junctionMetadata.columns[1].name + "=" + parentAlias + "." + joinTableColumn; | ||
condition1 = this.driver.escapeAliasName(junctionAlias) + "." + this.driver.escapeColumnName(junctionMetadata.columns[1].name) + "=" + this.driver.escapeAliasName(parentAlias) + "." + this.driver.escapeColumnName(joinTableColumn); | ||
} | ||
return " " + join.type + " JOIN " + junctionTable + " " + junctionAlias + " " + join.conditionType + " " + condition1; | ||
return " " + join.type + " JOIN " + junctionTable + " " + this.driver.escapeAliasName(junctionAlias) + " " + join.conditionType + " " + condition1; | ||
// " " + joinType + " JOIN " + joinTableName + " " + joinAlias + " " + join.conditionType + " " + condition2 + appendedCondition; | ||
@@ -759,3 +761,3 @@ // console.log(join); | ||
if (!parentAlias) { | ||
return " " + joinType + " JOIN " + joinTableName + " " + join.alias.name + " " + (join.condition ? (join.conditionType + " " + join.condition) : ""); | ||
return " " + joinType + " JOIN " + this.driver.escapeTableName(joinTableName) + " " + this.driver.escapeAliasName(join.alias.name) + " " + (join.condition ? (join.conditionType + " " + join.condition) : ""); | ||
} | ||
@@ -780,21 +782,21 @@ const foundAlias = this.aliasMap.findAliasByName(parentAlias); | ||
if (relation.isOwning) { | ||
condition1 = junctionAlias + "." + junctionMetadata.columns[0].name + "=" + parentAlias + "." + joinTableColumn; | ||
condition2 = joinAlias + "." + inverseJoinColumnName + "=" + junctionAlias + "." + junctionMetadata.columns[1].name; | ||
condition1 = this.driver.escapeAliasName(junctionAlias) + "." + this.driver.escapeColumnName(junctionMetadata.columns[0].name) + "=" + this.driver.escapeAliasName(parentAlias) + "." + this.driver.escapeColumnName(joinTableColumn); | ||
condition2 = this.driver.escapeAliasName(joinAlias) + "." + this.driver.escapeColumnName(inverseJoinColumnName) + "=" + this.driver.escapeAliasName(junctionAlias) + "." + this.driver.escapeColumnName(junctionMetadata.columns[1].name); | ||
} | ||
else { | ||
condition1 = junctionAlias + "." + junctionMetadata.columns[1].name + "=" + parentAlias + "." + joinTableColumn; | ||
condition2 = joinAlias + "." + inverseJoinColumnName + "=" + junctionAlias + "." + junctionMetadata.columns[0].name; | ||
condition1 = this.driver.escapeAliasName(junctionAlias) + "." + this.driver.escapeColumnName(junctionMetadata.columns[1].name) + "=" + this.driver.escapeAliasName(parentAlias) + "." + this.driver.escapeColumnName(joinTableColumn); | ||
condition2 = this.driver.escapeAliasName(joinAlias) + "." + this.driver.escapeColumnName(inverseJoinColumnName) + "=" + this.driver.escapeAliasName(junctionAlias) + "." + this.driver.escapeColumnName(junctionMetadata.columns[0].name); | ||
} | ||
return " " + joinType + " JOIN " + junctionTable + " " + junctionAlias + " " + join.conditionType + " " + condition1 + | ||
" " + joinType + " JOIN " + joinTableName + " " + joinAlias + " " + join.conditionType + " " + condition2 + appendedCondition; | ||
return " " + joinType + " JOIN " + this.driver.escapeTableName(junctionTable) + " " + this.driver.escapeAliasName(junctionAlias) + " " + join.conditionType + " " + condition1 + | ||
" " + joinType + " JOIN " + this.driver.escapeTableName(joinTableName) + " " + this.driver.escapeAliasName(joinAlias) + " " + join.conditionType + " " + condition2 + appendedCondition; | ||
} | ||
else if (relation.isManyToOne || (relation.isOneToOne && relation.isOwning)) { | ||
const joinTableColumn = relation.joinColumn.referencedColumn.name; | ||
const condition = join.alias.name + "." + joinTableColumn + "=" + parentAlias + "." + relation.name; | ||
return " " + joinType + " JOIN " + joinTableName + " " + join.alias.name + " " + join.conditionType + " " + condition + appendedCondition; | ||
const condition = this.driver.escapeAliasName(join.alias.name) + "." + this.driver.escapeColumnName(joinTableColumn) + "=" + this.driver.escapeAliasName(parentAlias) + "." + this.driver.escapeColumnName(relation.name); | ||
return " " + joinType + " JOIN " + this.driver.escapeTableName(joinTableName) + " " + this.driver.escapeAliasName(join.alias.name) + " " + join.conditionType + " " + condition + appendedCondition; | ||
} | ||
else if (relation.isOneToMany || (relation.isOneToOne && !relation.isOwning)) { | ||
const joinTableColumn = relation.inverseRelation.joinColumn.referencedColumn.name; | ||
const condition = join.alias.name + "." + relation.inverseRelation.name + "=" + parentAlias + "." + joinTableColumn; | ||
return " " + joinType + " JOIN " + joinTableName + " " + join.alias.name + " " + join.conditionType + " " + condition + appendedCondition; | ||
const condition = this.driver.escapeAliasName(join.alias.name) + "." + this.driver.escapeColumnName(relation.inverseRelation.name) + "=" + this.driver.escapeAliasName(parentAlias) + "." + this.driver.escapeColumnName(joinTableColumn); | ||
return " " + joinType + " JOIN " + this.driver.escapeTableName(joinTableName) + " " + this.driver.escapeAliasName(join.alias.name) + " " + join.conditionType + " " + condition + appendedCondition; | ||
} | ||
@@ -801,0 +803,0 @@ else { |
@@ -39,3 +39,3 @@ "use strict"; | ||
return; | ||
const columnName = this.driver.isResultsLowercase ? metadata.primaryColumn.name.toLowerCase() : metadata.primaryColumn.name; | ||
const columnName = metadata.primaryColumn.name; | ||
return result[alias.name + "_" + columnName]; | ||
@@ -70,3 +70,3 @@ }); | ||
metadata.columns.forEach(column => { | ||
const columnName = this.driver.isResultsLowercase ? column.name.toLowerCase() : column.name; | ||
const columnName = column.name; | ||
const valueInObject = rawSqlResults[0][alias.name + "_" + columnName]; // we use zero index since its grouped data | ||
@@ -130,3 +130,3 @@ if (valueInObject !== undefined && valueInObject !== null && column.propertyName && !column.isVirtual) { | ||
else if (relation.idField) { | ||
const relationName = this.driver.isResultsLowercase ? relation.name.toLowerCase() : relation.name; | ||
const relationName = relation.name; | ||
entity[relation.idField] = rawSqlResults[0][alias.name + "_" + relationName]; | ||
@@ -133,0 +133,0 @@ } |
@@ -0,1 +1,2 @@ | ||
/// <reference types="chai" /> | ||
import { QueryBuilder } from "../query-builder/QueryBuilder"; | ||
@@ -97,3 +98,3 @@ /** | ||
sort: string; | ||
order: "ASC" | "DESC"; | ||
order?: "ASC" | "DESC"; | ||
}[]; | ||
@@ -100,0 +101,0 @@ /** |
@@ -0,1 +1,2 @@ | ||
/// <reference types="chai" /> | ||
import { RelationMetadata } from "../metadata/RelationMetadata"; | ||
@@ -2,0 +3,0 @@ import { EntityMetadataCollection } from "../metadata-args/collection/EntityMetadataCollection"; |
@@ -80,3 +80,4 @@ "use strict"; | ||
} | ||
} | ||
}, | ||
configurable: true | ||
}); | ||
@@ -83,0 +84,0 @@ } |
@@ -0,1 +1,2 @@ | ||
/// <reference types="chai" /> | ||
import { QueryBuilder } from "../query-builder/QueryBuilder"; | ||
@@ -2,0 +3,0 @@ import { FindOptions } from "./FindOptions"; |
@@ -0,1 +1,2 @@ | ||
/// <reference types="chai" /> | ||
import { Connection } from "../connection/Connection"; | ||
@@ -2,0 +3,0 @@ import { EntityMetadata } from "../metadata/EntityMetadata"; |
@@ -271,3 +271,3 @@ "use strict"; | ||
const metadata = this.connection.entityMetadatas.findByTarget(entityWithId.entityTarget); | ||
const alias = entityWithId.entityTarget.constructor.name; | ||
const alias = entityWithId.entityTarget.name; | ||
const qb = new QueryBuilder_1.QueryBuilder(this.connection.driver, this.connection.entityMetadatas, this.connection.broadcaster, dbConnection) | ||
@@ -274,0 +274,0 @@ .select(alias) |
@@ -33,4 +33,3 @@ "use strict"; | ||
getChangedColumns(tableName, columns) { | ||
const sql = `SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_CATALOG = '${this.driver.db}'` + | ||
` AND TABLE_NAME = '${tableName}'`; | ||
const sql = `SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_CATALOG = '${this.driver.db}' AND TABLE_NAME = '${tableName}'`; | ||
return this.query(sql).then(results => { | ||
@@ -67,13 +66,13 @@ // console.log("changed columns: ", results); | ||
addColumnQuery(tableName, column) { | ||
const sql = `ALTER TABLE ${tableName} ADD ${this.buildCreateColumnSql(column, false)}`; | ||
const sql = `ALTER TABLE "${tableName}" ADD ${this.buildCreateColumnSql(column, false)}`; | ||
return this.query(sql).then(() => { }); | ||
} | ||
dropColumnQuery(tableName, columnName) { | ||
const sql = `ALTER TABLE ${tableName} DROP ${columnName}`; | ||
const sql = `ALTER TABLE "${tableName}" DROP "${columnName}"`; | ||
return this.query(sql).then(() => { }); | ||
} | ||
addForeignKeyQuery(foreignKey) { | ||
let sql = `ALTER TABLE ${foreignKey.tableName} ADD CONSTRAINT ${foreignKey.name} ` + | ||
`FOREIGN KEY (${foreignKey.columnNames.join(", ")}) ` + | ||
`REFERENCES ${foreignKey.referencedTable.name}(${foreignKey.referencedColumnNames.join(",")})`; | ||
let sql = `ALTER TABLE "${foreignKey.tableName}" ADD CONSTRAINT "${foreignKey.name}" ` + | ||
`FOREIGN KEY ("${foreignKey.columnNames.join("\", \"")}") ` + | ||
`REFERENCES "${foreignKey.referencedTable.name}"("${foreignKey.referencedColumnNames.join("\", \"")}")`; | ||
if (foreignKey.onDelete) | ||
@@ -89,3 +88,3 @@ sql += " ON DELETE " + foreignKey.onDelete; | ||
} | ||
const sql = `ALTER TABLE ${tableName} DROP FOREIGN KEY \`${foreignKeyName}\``; | ||
const sql = `ALTER TABLE "${tableName}" DROP CONSTRAINT "${foreignKeyName}"`; | ||
return this.query(sql).then(() => { }); | ||
@@ -95,3 +94,3 @@ } | ||
const sql = `SELECT tc.constraint_name FROM information_schema.table_constraints AS tc ` + | ||
`WHERE constraint_type = 'FOREIGN KEY' AND tc.table_catalog='${this.driver.db}' AND tc.table_name='${tableName}';`; | ||
`WHERE constraint_type = 'FOREIGN KEY' AND tc.table_catalog='${this.driver.db}' AND tc.table_name='${tableName}'`; | ||
// const sql = `SELECT * FROM INFORMATION_SCHEMA.table_constraints WHERE TABLE_CATALOG = '${this.driver.db}' ` | ||
@@ -102,3 +101,3 @@ // + `AND TABLE_NAME = '${tableName}' AND CONSTRAINT_TYPE='FOREIGN KEY'`; | ||
getTableUniqueKeysQuery(tableName) { | ||
const sql = `SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_CATALOG = '${this.driver.db}' ` + | ||
const sql = `SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_CATALOG='${this.driver.db}' ` + | ||
`AND TABLE_NAME = '${tableName}' AND CONSTRAINT_TYPE = 'UNIQUE'`; | ||
@@ -108,23 +107,5 @@ return this.query(sql).then(results => results.map(result => result.CONSTRAINT_NAME)); | ||
getTableIndicesQuery(tableName) { | ||
const sql = `select | ||
t.relname as table_name, | ||
i.relname as index_name, | ||
a.attname as column_name, | ||
ix.indisprimary as is_primary | ||
from | ||
pg_class t, | ||
pg_class i, | ||
pg_index ix, | ||
pg_attribute a | ||
where | ||
t.oid = ix.indrelid | ||
and i.oid = ix.indexrelid | ||
and a.attrelid = t.oid | ||
and a.attnum = ANY(ix.indkey) | ||
and t.relkind = 'r' | ||
and t.relname = '${tableName}' | ||
order by | ||
t.relname, | ||
i.relname; | ||
`; | ||
const sql = `select t.relname as table_name, i.relname as index_name, a.attname as column_name, ix.indisprimary as is_primary from pg_class t, pg_class i, pg_index ix, pg_attribute a | ||
where t.oid = ix.indrelid and i.oid = ix.indexrelid and a.attrelid = t.oid and a.attnum = ANY(ix.indkey) and t.relkind = 'r' and t.relname = '${tableName}' | ||
order by t.relname, i.relname`; | ||
return this.query(sql).then(results => { | ||
@@ -151,5 +132,5 @@ // exclude foreign keys | ||
if (isGenerated) { | ||
yield this.query(`ALTER SEQUENCE foo_id_seq OWNED BY NONE`); | ||
yield this.query(`ALTER SEQUENCE foo_id_seq OWNED BY NONE`); // todo: what is it? | ||
} | ||
const sql = `ALTER TABLE ${tableName} DROP CONSTRAINT ${indexName}`; | ||
const sql = `ALTER TABLE "${tableName}" DROP CONSTRAINT "${indexName}"`; | ||
yield this.query(sql); | ||
@@ -159,7 +140,7 @@ }); | ||
createIndex(tableName, index) { | ||
const sql = `CREATE ${index.isUnique ? "UNIQUE" : ""} INDEX \`${index.name}\` ON ${tableName}(${index.columns.join(", ")})`; | ||
const sql = `CREATE ${index.isUnique ? "UNIQUE" : ""} INDEX "${index.name}" ON "${tableName}"("${index.columns.join("\", \"")}")`; | ||
return this.query(sql).then(() => { }); | ||
} | ||
addUniqueKey(tableName, columnName, keyName) { | ||
const sql = `ALTER TABLE ${tableName} ADD CONSTRAINT ${keyName} UNIQUE (${columnName})`; | ||
const sql = `ALTER TABLE "${tableName}" ADD CONSTRAINT "${keyName}" UNIQUE ("${columnName}")`; | ||
return this.query(sql).then(() => { }); | ||
@@ -173,3 +154,3 @@ } | ||
changeColumnQuery(tableName, columnName, newColumn, skipPrimary = false) { | ||
const sql = `ALTER TABLE ${tableName} CHANGE ${columnName} ${this.buildCreateColumnSql(newColumn, skipPrimary)}`; | ||
const sql = `ALTER TABLE "${tableName}" CHANGE "${columnName}" ${this.buildCreateColumnSql(newColumn, skipPrimary)}`; | ||
return this.query(sql).then(() => { }); | ||
@@ -189,3 +170,3 @@ } | ||
buildCreateColumnSql(column, skipPrimary) { | ||
let c = column.name; | ||
let c = "\"" + column.name + "\""; | ||
if (column.isGenerated === true) | ||
@@ -192,0 +173,0 @@ c += " SERIAL"; |
@@ -111,6 +111,6 @@ "use strict"; | ||
const updates = columns | ||
.filter(column => !!column.oldColumnName && column.name.toLowerCase() !== column.oldColumnName.toLowerCase()) | ||
.filter(column => !!column.oldColumnName && column.name !== column.oldColumnName) | ||
.filter(column => dbColumns.indexOf(column.oldColumnName) !== -1) | ||
.map((column) => __awaiter(this, void 0, void 0, function* () { | ||
yield this.dropColumnForeignKeys(table.name, column.name.toLowerCase(), foreignKeys); | ||
yield this.dropColumnForeignKeys(table.name, column.name, foreignKeys); | ||
return this.schemaBuilder.changeColumnQuery(table.name, column.oldColumnName, column); | ||
@@ -128,3 +128,3 @@ })); | ||
const dropColumnQueries = dbColumns | ||
.filter(dbColumn => !columns.find(column => column.name.toLowerCase() === dbColumn.toLowerCase())) | ||
.filter(dbColumn => !columns.find(column => column.name === dbColumn)) | ||
.map((dbColumn) => __awaiter(this, void 0, void 0, function* () { | ||
@@ -142,5 +142,4 @@ yield this.dropColumnForeignKeys(table.name, dbColumn, foreignKeys); | ||
return this.schemaBuilder.getTableColumns(table.name).then(dbColumns => { | ||
dbColumns = dbColumns.map(dbColumn => dbColumn.toLowerCase()); | ||
const newColumnQueries = columns | ||
.filter(column => dbColumns.indexOf(column.name.toLowerCase()) === -1) | ||
.filter(column => dbColumns.indexOf(column.name) === -1) | ||
.map(column => this.schemaBuilder.addColumnQuery(table.name, column)); | ||
@@ -157,7 +156,7 @@ return Promise.all(newColumnQueries); | ||
const updateQueries = changedColumns.map((changedColumn) => __awaiter(this, void 0, void 0, function* () { | ||
const column = columns.find(column => column.name.toLowerCase() === changedColumn.columnName.toLowerCase()); | ||
const column = columns.find(column => column.name === changedColumn.columnName); | ||
if (!column) | ||
throw new Error(`Column ${changedColumn.columnName} was not found in the given columns`); | ||
yield this.dropColumnForeignKeys(table.name, column.name.toLowerCase(), foreignKeys); | ||
return this.schemaBuilder.changeColumnQuery(table.name, column.name.toLowerCase(), column, changedColumn.hasPrimaryKey); | ||
yield this.dropColumnForeignKeys(table.name, column.name, foreignKeys); | ||
return this.schemaBuilder.changeColumnQuery(table.name, column.name, column, changedColumn.hasPrimaryKey); | ||
})); | ||
@@ -184,13 +183,13 @@ return Promise.all(updateQueries); | ||
return this.schemaBuilder.getTableUniqueKeysQuery(table.name).then(dbKeys => { | ||
dbKeys = dbKeys.map(dbKey => dbKey.toLowerCase()); | ||
dbKeys = dbKeys.map(dbKey => dbKey); | ||
// first find metadata columns that should be unique and update them if they are not unique in db | ||
const addQueries = columns | ||
.filter(column => column.isUnique) | ||
.filter(column => dbKeys.indexOf("uk_" + column.name.toLowerCase()) === -1) | ||
.map(column => this.schemaBuilder.addUniqueKey(table.name, column.name.toLowerCase(), "uk_" + column.name.toLowerCase())); | ||
.filter(column => dbKeys.indexOf("uk_" + column.name) === -1) | ||
.map(column => this.schemaBuilder.addUniqueKey(table.name, column.name, "uk_" + column.name)); | ||
// second find columns in db that are unique, however in metadata columns they are not unique | ||
const dropQueries = columns | ||
.filter(column => !column.isUnique) | ||
.filter(column => dbKeys.indexOf("uk_" + column.name.toLowerCase()) !== -1) | ||
.map(column => this.schemaBuilder.dropIndex(table.name, "uk_" + column.name.toLowerCase())); | ||
.filter(column => dbKeys.indexOf("uk_" + column.name) !== -1) | ||
.map(column => this.schemaBuilder.dropIndex(table.name, "uk_" + column.name)); | ||
return Promise.all([addQueries, dropQueries]); | ||
@@ -197,0 +196,0 @@ }); |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
1535869
14255