Skip to content

Commit

Permalink
refactored entity schemas
Browse files Browse the repository at this point in the history
  • Loading branch information
Umed Khudoiberdiev committed Feb 27, 2018
1 parent ba90fd9 commit 1606ab8
Show file tree
Hide file tree
Showing 43 changed files with 427 additions and 271 deletions.
3 changes: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ If you want to disable this behavior use `queryBuilder.updateEntity(false)` meth
This feature is convenient for users who have uuid, create/update date, version columns or columns with DEFAULT value set.
* now `InsertQueryBuilder`, `UpdateQueryBuilder` and `DeleteQueryBuilder` call subscribers and listeners.
You can disable this behavior by setting `queryBuilder.callListeners(false)` method.
* `Repository` and `EntityManager` method `.findOne` is deprecated and will be removed in next 0.3.0 version.
* `Repository` and `EntityManager` method `.findOneById` is deprecated and will be removed in next 0.3.0 version.
Use `findOne(id)` method instead now.
* `InsertQueryBuilder` now returns `InsertResult` which contains extended information and metadata about runned query
* `UpdateQueryBuilder` now returns `UpdateResult` which contains extended information and metadata about runned query
Expand All @@ -56,6 +56,7 @@ By default its true.
* added support for nested set and materialized path tree hierarchy patterns
* breaking change on how array parameters work in queries - now instead of (:param) new syntax must be used (:...param).
This fixed various issues on how real arrays must work
* changed the way how entity schemas are created (now more type-safe), now interface EntitySchema is a class

## 0.1.13

Expand Down
20 changes: 14 additions & 6 deletions sample/sample24-schemas/app.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,17 @@
import "reflect-metadata";
import {ConnectionOptions, createConnection} from "../../src/index";
import {ConnectionOptions, createConnection, EntitySchema} from "../../src";
import {Post} from "./entity/Post";
import {PostDetails} from "./entity/PostDetails";
import {Category} from "./entity/Category";
import {Image} from "./entity/Image";

// NOTE: this example is not working yet, only concepts of how this feature must work described here

const PostEntity = new EntitySchema<Post>(require(__dirname + "/../../../../sample/sample24-schemas/schemas/post.json"));
const PostDetailsEntity = new EntitySchema<PostDetails>(require(__dirname + "/../../../../sample/sample24-schemas/schemas/post-details.json"));
const CategoryEntity = new EntitySchema<Category>(require(__dirname + "/../../../../sample/sample24-schemas/schemas/category.json"));
const ImageEntity = new EntitySchema<Image>(require(__dirname + "/../../../../sample/sample24-schemas/schemas/image.json"));

const options: ConnectionOptions = {
type: "mysql",
host: "localhost",
Expand All @@ -13,11 +21,11 @@ const options: ConnectionOptions = {
database: "test",
synchronize: true,
// entitySchemaDirectories: [__dirname + "/schemas"],
entitySchemas: [
require(__dirname + "/../../../../sample/sample24-schemas/schemas/post.json"),
require(__dirname + "/../../../../sample/sample24-schemas/schemas/post-details.json"),
require(__dirname + "/../../../../sample/sample24-schemas/schemas/category.json"),
require(__dirname + "/../../../../sample/sample24-schemas/schemas/image.json")
entities: [
PostEntity,
PostDetailsEntity,
CategoryEntity,
ImageEntity,
]
};

Expand Down
9 changes: 1 addition & 8 deletions src/connection/BaseConnectionOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export interface BaseConnectionOptions {
* Accepts both entity classes and directories where from entities need to be loaded.
* Directories support glob patterns.
*/
readonly entities?: (Function|string)[];
readonly entities?: ((Function|string|EntitySchema<any>))[];

/**
* Subscribers to be loaded for this connection.
Expand All @@ -34,13 +34,6 @@ export interface BaseConnectionOptions {
*/
readonly subscribers?: Function[]|string[];

/**
* Entity schemas to be loaded for this connection.
* Accepts both entity schema classes and directories where from entity schemas need to be loaded.
* Directories support glob patterns.
*/
readonly entitySchemas?: EntitySchema[]|string[];

/**
* Migrations to be loaded for this connection.
* Accepts both migration classes and directories where from migrations need to be loaded.
Expand Down
24 changes: 14 additions & 10 deletions src/connection/Connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import {PromiseUtils} from "../util/PromiseUtils";
import {SqljsEntityManager} from "../entity-manager/SqljsEntityManager";
import {RelationLoader} from "../query-builder/RelationLoader";
import {RelationIdLoader} from "../query-builder/RelationIdLoader";
import {EntitySchema} from "../";

/**
* Connection is a single database ORM connection to a specific database.
Expand Down Expand Up @@ -298,14 +299,14 @@ export class Connection {
/**
* Checks if entity metadata exist for the given entity class, target name or table name.
*/
hasMetadata(target: Function|string): boolean {
hasMetadata(target: Function|EntitySchema<any>|string): boolean {
return !!this.findMetadata(target);
}

/**
* Gets entity metadata for the given entity class or schema name.
*/
getMetadata(target: Function|string): EntityMetadata {
getMetadata(target: Function|EntitySchema<any>|string): EntityMetadata {
const metadata = this.findMetadata(target);
if (!metadata)
throw new EntityMetadataNotFound(target);
Expand All @@ -316,23 +317,23 @@ export class Connection {
/**
* Gets repository for the given entity.
*/
getRepository<Entity>(target: ObjectType<Entity>|string): Repository<Entity> {
getRepository<Entity>(target: ObjectType<Entity>|EntitySchema<Entity>|string): Repository<Entity> {
return this.manager.getRepository(target);
}

/**
* Gets tree repository for the given entity class or name.
* Only tree-type entities can have a TreeRepository, like ones decorated with @Tree decorator.
*/
getTreeRepository<Entity>(target: ObjectType<Entity>|string): TreeRepository<Entity> {
getTreeRepository<Entity>(target: ObjectType<Entity>|EntitySchema<Entity>|string): TreeRepository<Entity> {
return this.manager.getTreeRepository(target);
}

/**
* Gets mongodb-specific repository for the given entity class or name.
* Works only if connection is mongodb-specific.
*/
getMongoRepository<Entity>(target: ObjectType<Entity>|string): MongoRepository<Entity> {
getMongoRepository<Entity>(target: ObjectType<Entity>|EntitySchema<Entity>|string): MongoRepository<Entity> {
if (!(this.driver instanceof MongoDriver))
throw new Error(`You can use getMongoRepository only for MongoDB connections.`);

Expand Down Expand Up @@ -378,7 +379,7 @@ export class Connection {
/**
* Creates a new query builder that can be used to build a sql query.
*/
createQueryBuilder<Entity>(entityClass: ObjectType<Entity>|Function|string, alias: string, queryRunner?: QueryRunner): SelectQueryBuilder<Entity>;
createQueryBuilder<Entity>(entityClass: ObjectType<Entity>|EntitySchema<Entity>|Function|string, alias: string, queryRunner?: QueryRunner): SelectQueryBuilder<Entity>;

/**
* Creates a new query builder that can be used to build a sql query.
Expand All @@ -388,12 +389,12 @@ export class Connection {
/**
* Creates a new query builder that can be used to build a sql query.
*/
createQueryBuilder<Entity>(entityOrRunner?: ObjectType<Entity>|Function|string|QueryRunner, alias?: string, queryRunner?: QueryRunner): SelectQueryBuilder<Entity> {
createQueryBuilder<Entity>(entityOrRunner?: ObjectType<Entity>|EntitySchema<Entity>|Function|string|QueryRunner, alias?: string, queryRunner?: QueryRunner): SelectQueryBuilder<Entity> {
if (this instanceof MongoEntityManager)
throw new Error(`Query Builder is not supported by MongoDB.`);

if (alias) {
const metadata = this.getMetadata(entityOrRunner as Function|string);
const metadata = this.getMetadata(entityOrRunner as Function|EntitySchema<Entity>|string);
return new SelectQueryBuilder(this, queryRunner)
.select(alias)
.from(metadata.target, alias);
Expand Down Expand Up @@ -448,10 +449,13 @@ export class Connection {
/**
* Finds exist entity metadata by the given entity class, target name or table name.
*/
protected findMetadata(target: Function|string): EntityMetadata|undefined {
protected findMetadata(target: Function|EntitySchema<any>|string): EntityMetadata|undefined {
return this.entityMetadatas.find(metadata => {
if (metadata.target === target)
return true;
if (target instanceof EntitySchema) {
return metadata.name === target.options.name;
}
if (typeof target === "string") {
if (target.indexOf(".") !== -1) {
return metadata.tablePath === target;
Expand All @@ -477,7 +481,7 @@ export class Connection {
Object.assign(this, { subscribers: subscribers });

// build entity metadatas
const entityMetadatas = connectionMetadataBuilder.buildEntityMetadatas(this.options.entities || [], this.options.entitySchemas || []);
const entityMetadatas = connectionMetadataBuilder.buildEntityMetadatas(this.options.entities || []);
Object.assign(this, { entityMetadatas: entityMetadatas });

// create migration instances
Expand Down
15 changes: 9 additions & 6 deletions src/connection/ConnectionMetadataBuilder.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {importClassesFromDirectories, importJsonsFromDirectories} from "../util/DirectoryExportedClassesLoader";
import {importClassesFromDirectories} from "../util/DirectoryExportedClassesLoader";
import {OrmUtils} from "../util/OrmUtils";
import {getFromContainer} from "../container";
import {MigrationInterface} from "../migration/MigrationInterface";
Expand Down Expand Up @@ -49,14 +49,17 @@ export class ConnectionMetadataBuilder {
/**
* Builds entity metadatas for the given classes or directories.
*/
buildEntityMetadatas(entities: (Function|string)[], schemas: (EntitySchema|string)[]): EntityMetadata[] {
const [entityClasses, entityDirectories] = OrmUtils.splitClassesAndStrings(entities || []);
buildEntityMetadatas(entities: (Function|EntitySchema<any>|string)[]): EntityMetadata[] {
// todo: instead we need to merge multiple metadata args storages

const [entityClassesOrSchemas, entityDirectories] = OrmUtils.splitClassesAndStrings(entities || []);
const entityClasses: Function[] = entityClassesOrSchemas.filter(entityClass => (entityClass instanceof EntitySchema) === false) as any;
const entitySchemas: EntitySchema<any>[] = entityClassesOrSchemas.filter(entityClass => entityClass instanceof EntitySchema) as any;

const allEntityClasses = [...entityClasses, ...importClassesFromDirectories(entityDirectories)];
const decoratorEntityMetadatas = new EntityMetadataBuilder(this.connection, getMetadataArgsStorage()).build(allEntityClasses);

const [entitySchemaClasses, entitySchemaDirectories] = OrmUtils.splitClassesAndStrings(schemas || []);
const allEntitySchemaClasses = [...entitySchemaClasses, ...importJsonsFromDirectories(entitySchemaDirectories)];
const metadataArgsStorageFromSchema = new EntitySchemaTransformer().transform(allEntitySchemaClasses);
const metadataArgsStorageFromSchema = new EntitySchemaTransformer().transform(entitySchemas);
const schemaEntityMetadatas = new EntityMetadataBuilder(this.connection, metadataArgsStorageFromSchema).build();

return [...decoratorEntityMetadatas, ...schemaEntityMetadatas];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ export class ConnectionOptionsEnvReader {
entities: this.stringToArray(PlatformTools.getEnvVariable("TYPEORM_ENTITIES")),
migrations: this.stringToArray(PlatformTools.getEnvVariable("TYPEORM_MIGRATIONS")),
subscribers: this.stringToArray(PlatformTools.getEnvVariable("TYPEORM_SUBSCRIBERS")),
entitySchemas: this.stringToArray(PlatformTools.getEnvVariable("TYPEORM_ENTITY_SCHEMAS")),
logging: this.transformLogging(PlatformTools.getEnvVariable("TYPEORM_LOGGING")),
logger: PlatformTools.getEnvVariable("TYPEORM_LOGGER"),
entityPrefix: PlatformTools.getEnvVariable("TYPEORM_ENTITY_PREFIX"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ export class ConnectionOptionsXmlReader {
synchronize: connection.synchronize ? connection.synchronize[0] : undefined,
entities: connection.entities ? connection.entities[0].entity : [],
subscribers: connection.subscribers ? connection.subscribers[0].entity : [],
entitySchemas: connection.entitySchemas ? connection.entitySchemas[0].entity : [],
logging: connection.logging[0] ? connection.logging[0].split(",") : undefined,
};
});
Expand Down
Loading

0 comments on commit 1606ab8

Please sign in to comment.