Models
An example of creating a more complex model of my ORM system
In this section, we will create a more complex model for Tasks
that demonstrates the use of various decorators to define the table structure and field characteristics.
Model Description
The Tasks
model includes the following fields:
task_id: A unique identifier for the task.
title: The title of the task.
description: A description of the task.
is_completed: The completion status of the task.
due_date: The due date of the task.
status: A computed field for displaying the status of the task.
created_at: The date and time when the task was created.
updated_at: The date and time of the last update to the task.
price: The price of the task.
Code Example
import {
Boolean,
Column,
ComputedColumn,
Numeric,
PrimaryGeneratedColumn,
String,
Table
} from "@myroslavshymon/orm";
@Table({ name: 'tasks' })
export class Tasks {
@PrimaryGeneratedColumn({ type: 'BIGINT' })
task_id: number;
@String({ type: "VARCHAR", length: 255 })
@Column({ options: { nullable: false } })
title: string;
@String({ type: "TEXT" })
@Column({ options: { nullable: true } })
description: string;
@Boolean()
@Column({ options: { nullable: false, defaultValue: false } })
is_completed: boolean;
@Column({ options: { dataType: 'DATE', nullable: true } })
due_date: Date;
@ComputedColumn({ dataType: 'VARCHAR', calculate: "title || ' - ' || CASE WHEN is_completed THEN 'Completed' ELSE 'Pending' END" })
status: string;
@Column({ options: { dataType: 'TIMESTAMP', defaultValue: 'CURRENT_TIMESTAMP' } })
created_at: Date;
@Column({ options: { dataType: 'TIMESTAMP', defaultValue: 'CURRENT_TIMESTAMP' } })
updated_at: Date;
@Numeric({ type: 'NUMERIC', precision: 10, scale: 2 })
@Column({ options: { check: 'price >= 0', nameOfCheckConstraint: 'check_price' } })
price: number;
}
Decorator Explanations
@PrimaryGeneratedColumn: Used to define the primary key of the table. It specifies the data type as BIGINT for
task_id
.@String: A decorator for text fields. It specifies the data type as VARCHAR for
title
and TEXT fordescription
.@Boolean: A decorator for boolean fields. Used for
is_completed
, with a default value offalse
.@Column: A general decorator for columns. For
due_date
, the data type used is DATE. Forcreated_at
andupdated_at
, the data type is TIMESTAMP with a default value of 'CURRENT_TIMESTAMP'.@ComputedColumn: Creates a computed field. For
status
, it uses an expression that combines the title and the status of the task.@Numeric: Used for numeric fields with floating-point precision. For
price
, it sets the precision to 10 digits with 2 decimal places, and includes a constraint that the value must be greater than or equal to 0.
This approach allows for the creation of a table with various data types and parameters using all available decorators for PostgreSQL, making the model flexible and comprehensive.
Last updated