[EntitySchema] Extend BaseSchema
Issue type:
[x] question [ ] bug report [ ] feature request [x] documentation issue
Database system/driver:
[ ] cordova
[ ] mongodb
[ ] mssql
[ ] mysql / mariadb
[ ] oracle
[x] postgres
[ ] sqlite
[ ] sqljs
[ ] react-native
[ ] expo
TypeORM version:
[x] latest
[ ] @next
[ ] 0.x.x (or put your version here)
Steps to reproduce or a small repository showing the problem:
Dear TypeORM maintainers and community,
first of all, i would like to thank you for this awesome project - i really like using TypeORM.. Recently, I stumbled upon EntitySchema for decoupling the "database structure" from the actual models - and i like this approach very much!
Before, when using the normal Entity Decorators, i did something like this in order to DRY up my boilerplate code for my entities:
export abstract class AbstractEntity {
@PrimaryGeneratedColumn('uuid') id: string;
@CreateDateColumn() createdAt: Date;
@UpdateDateColumn() updatedAt: Date;
}
export class Category extends AbstractEntity {
@Column() slug: string;
// ...
}
When switching to EntitySchema, i found, that there is some kind of extends param, which can be used to extend an existing Schema (see code here)
https://github.com/typeorm/typeorm/blob/b9d2756c1726728da85c36aeedd924230dc601e6/src/entity-schema/EntitySchemaOptions.ts#L13-L18
However, I did not find any real documentation about this feature so far - not even in the sample.
Basically, what i would like to do, is something like this:
export const BaseSchema = new EntitySchema({
name: 'BaseSchema',
columns: {
id: {
type: 'uuid',
generated: 'uuid',
primary: 'true',
},
// ... more default column descriptions here
},
// maybe some other "default" descriptions here
});
and then "use" this schema as blueprint for other schemas, like so:
export const CategorySchema = new EntitySchema<Category>({
name: 'Category',
tablename: 'categories',
extends: 'BaseSchema',
columns: {
slug: {
type: 'varchar',
length: 50,
unique: true,
}
}
});
so that the CategorySchema inherits all columns that are described in the BaseSchema. However, this does not work - if i run the dev server (synchronize: true to automatically migrate everything), this does not work..
Maybe you can point me to the right direction? That would be awesome :+1:
In order to give something back, i would then update the documentation for the EntitySchema, because this lacks documentation..
All the best and thanks a lot for your time and effort!
Oh, and i did not find any test for the extends feature...
Do not know this feature well but it seems like this is not implemented. It is just presented as option. @pleerock could you please confirm?
haha, that would explain, why it did not work :rofl: .. maybe you can point me into the right direction where i can double-check that? any idea how to implement this feature? maybe i can PR it?!
we don't need extends in there. Just use object spread/rest syntax and you'll get more than just extension, e.g.
columns: {
id: {
type: 'uuid',
generated: 'uuid',
primary: 'true',
},
...commonColumns,
...etc
}
haha, yeah, i used this approach in order to get it to work (for now).. But i was wondering if this extends would be the better option / approach..
Thanks for pointing it out @pleerock :+1:
Will the extends be removed from the options? i would like to write down some of the insights i gathered when working with the EntitySchema and add it to the docs..
Ok, just an information for anyone, who may be stumbling upon the same issue here:
In order to "include" some kind of BaseColumns to an EntitySchema, you may need to define them as follows:
import { EntitySchemaColumnOptions } from 'typeorm';
export const BaseColumnsSchemaPart = {
id: {
type: 'uuid',
primary: true,
generated: 'uuid',
} as EntitySchemaColumnOptions,
createdAt: {
name: 'created_at',
type: 'timestamp with time zone',
createDate: true,
} as EntitySchemaColumnOptions,
updatedAt: {
name: 'updated_at',
type: 'timestamp with time zone',
updateDate: true,
} as EntitySchemaColumnOptions,
};
Then, in your "regular" schema file, include it like this:
export const UserSchema = new EntitySchema<User>({
name: 'UserSchema',
tableName: 'users',
columns: {
...BaseColumnsSchemaPart,
email: {
type: 'varchar',
length: 150,
unique: true,
},
// ... more columns may be defined here...
},
// other options like relations, ...
});
Nice @johannesschobel. Good to see you have a solution. If you want contribute we need some improvement in https://typeorm.io/#/separating-entity-definition section (at least note about extending + some info about target).
You are tagging the wrong Johannes here :ROFL: but I will update the docs for sure.. I will try to read the contributing guide during the next days and submit a PR
🤣 pardon
I will close this issue if I have updated the docs.. is this ok for you? As some kind of reminder for me, haha..
All the best and thanks for your time and help!
Hey, buddy, I have a problem. It can't generate uuid automatically.
query: SELECT * FROM current_schema()
query: CREATE EXTENSION IF NOT EXISTS "uuid-ossp"
query: SELECT version();
Data Source has been initialized!
query: START TRANSACTION
.....
error: error: null value in column "id" of relation "users" violates not-null constraint
import { EntitySchemaColumnOptions } from "typeorm";
export const _BaseColumns = {
id: {
type: "uuid",
primary: true,
generated: "uuid",
} as EntitySchemaColumnOptions,
createdAt: {
name: "created_at",
type: "timestamp with time zone",
createDate: true,
} as EntitySchemaColumnOptions,
updatedAt: {
name: "updated_at",
type: "timestamp with time zone",
updateDate: true,
} as EntitySchemaColumnOptions,
deletedAt: {
name: "deleted_at",
type: "timestamp with time zone",
deleteDate: true,
nullable: true,
} as EntitySchemaColumnOptions,
};
// userchema
export const UserSchema = new EntitySchema<IUser>({
name: "UserSchema",
tableName: "users",
columns: {
..._BaseColumns,
email: {
type: "varchar",
length: 50,
},
},
});
// datasource
const db = new DataSource({
type: "postgres",
host: "localhost",
port: 5432,
username: "postgres",
password: "123456",
database: "test",
logging: true,
entities: [UserSchema],
});
try {
await db.initialize();
console.log("Data Source has been initialized!");
await db.manager.save(UserSchema, { email: "[email protected]" });
} catch (error) {
console.error("Error during Data Source initialization:", error);
}