I am using PostgreSQL with TypeORM. My Student
entity has a jsonb
field, defined like this:
@Entity('students')
export class Student {
...
@Column('jsonb', { name: 'other_data', nullable: true })
otherData: { nr?: string; hometown?: string } | null;
}
The students
table was initially created without the column other_data
but added later via the following migration:
await queryRunner.addColumns('students', [
new TableColumn({
name: 'other_data',
type: 'jsonb',
isNullable: true,
}),
]);
The column adding was successful, I can see on psql console that \d students
has the field with type jsonb
.
The content of otherData
is expected to be a json contains nr
and hometown
optional fields.
After database table is created, I try to run a migration to add index to the nr
field of otherData
(please bear in mind otherData
is a jsonb
type).
This is what I tried in TypeORM migration file:
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`CREATE INDEX "student_nr" ON "students" USING gin (other_data -> 'nr')`
);
When I run the migration, I get error:
Migration "AddIndexOnOtherDataColumn1647948281597" has been failed, error: syntax error at or near "->"
query: ROLLBACK
Error during migration run:
QueryFailedError: syntax error at or near "->"
at QueryFailedError.TypeORMError [as constructor] (/Users/john/myproj/src/error/TypeORMError.ts:7:9)
at new QueryFailedError (/Users/john/myproj/src/error/QueryFailedError.ts:9:9)
at PostgresQueryRunner.<anonymous> (/Users/john/myproj/src/driver/postgres/PostgresQueryRunner.ts:247:19)
at step (/Users/john/myproj/node_modules/tslib/tslib.js:143:27)
at Object.throw (/Users/john/myproj/node_modules/tslib/tslib.js:124:57)
at rejected (/Users/john/myproj/node_modules/tslib/tslib.js:115:69)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
query: `CREATE INDEX "student_nr" ON "students" USING gin (other_data -> 'nr')`,
parameters: undefined,
driverError: error: syntax error at or near "->"
The noticeable part of the error message is parameters: undefined
and error near "->"
. But I get stuck on why this error, where am I wrong?
I eventually solved the problem by adding one more ()
around other_data->'nr'
:
await queryRunner.query(
`CREATE INDEX "student_nr" ON "students" USING gin ((other_data -> 'nr'))`
);
But it would be nice if someone is experienced with it could verify whether I am right in fixing the issue & also would be nice to explain more on it. Thanks!