-
Notifications
You must be signed in to change notification settings - Fork 173
Fix cursor pagination with optional tie-breaker #2080
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ravikiranvm
wants to merge
8
commits into
main
Choose a base branch
from
ops-3810
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+382
−70
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
1635750
Fix cursor pagination with optional tie-breaker
ravikiranvm 0e1098e
Remove some unnecessary changes
ravikiranvm 76010d0
Use better names
ravikiranvm 758ff11
Add integration test cases
ravikiranvm 7bd00f4
Guard secondary column to be used only with primary column
ravikiranvm 4e1d6f3
Fix sonar comments
ravikiranvm 8fc7a8c
Fix sonar
ravikiranvm 38489e8
Extract a func to be used in multiple test cases
ravikiranvm File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -31,8 +31,16 @@ export type PagingResult<Entity> = { | |
| cursor: CursorResult; | ||
| }; | ||
|
|
||
| type CursorContext = { | ||
| primaryColumnName: string; | ||
| primaryParamName: string; | ||
| secondaryColumnName: string | null; | ||
| secondaryParamName: string | null; | ||
| }; | ||
|
|
||
| const PAGINATION_KEY = 'created'; | ||
| const CUSTOM_PAGINATION_KEY = 'custom_pagination'; | ||
| const CUSTOM_PAGINATION_SECONDARY_KEY = 'custom_pagination_tie_breaker'; | ||
| const DEFAULT_TIMESTAMP_TYPE = 'timestamp with time zone'; | ||
|
|
||
| export default class Paginator<Entity extends ObjectLiteral> { | ||
|
|
@@ -56,6 +64,12 @@ export default class Paginator<Entity extends ObjectLiteral> { | |
|
|
||
| private paginationColumnType: string | null = null; | ||
|
|
||
| private paginationSecondaryColumnPath: string | null = null; | ||
|
|
||
| private paginationSecondaryColumnName: string | null = null; | ||
|
|
||
| private paginationSecondaryColumnType: string | null = null; | ||
|
|
||
| public constructor(private readonly entity: EntitySchema) {} | ||
|
|
||
| public setPaginationColumn( | ||
|
|
@@ -72,6 +86,16 @@ export default class Paginator<Entity extends ObjectLiteral> { | |
| this.alias = alias; | ||
| } | ||
|
|
||
| public setPaginationSecondaryColumn( | ||
| columnPath: string, | ||
| columnName: string, | ||
| columnType = 'string', | ||
| ): void { | ||
| this.paginationSecondaryColumnPath = columnPath; | ||
| this.paginationSecondaryColumnName = columnName; | ||
| this.paginationSecondaryColumnType = columnType; | ||
| } | ||
|
|
||
| public setAfterCursor(cursor: string): void { | ||
| this.afterCursor = cursor; | ||
| } | ||
|
|
@@ -169,30 +193,28 @@ export default class Paginator<Entity extends ObjectLiteral> { | |
| where: WhereExpressionBuilder, | ||
| cursors: CursorParam, | ||
| ): void { | ||
| const dbType = system.get(AppSystemProp.DB_TYPE); | ||
| const dbType = this.getSupportedDbType(); | ||
| const operator = this.getOperator(); | ||
| let queryString: string; | ||
|
|
||
| const isCustomColumn = | ||
| this.paginationColumnName && cursors[CUSTOM_PAGINATION_KEY]; | ||
| const columnName = isCustomColumn | ||
| ? this.paginationColumnName | ||
| : `${this.alias}.${PAGINATION_KEY}`; | ||
| const paramName = isCustomColumn ? CUSTOM_PAGINATION_KEY : PAGINATION_KEY; | ||
|
|
||
| if (dbType === DatabaseType.SQLITE3) { | ||
| queryString = `${columnName} ${operator} :${paramName}`; | ||
| } else if (dbType === DatabaseType.POSTGRES) { | ||
| if (this.hasBeforeCursor() && !this.hasAfterCursor()) { | ||
| queryString = `${columnName} ${operator} (:${paramName}::timestamp + INTERVAL '1 millisecond')`; | ||
| } else { | ||
| queryString = `${columnName} ${operator} :${paramName}::timestamp`; | ||
| } | ||
| } else { | ||
| throw new Error('Unsupported database type'); | ||
| const context = this.resolveCursorContext(cursors); | ||
|
|
||
| if (context.secondaryColumnName && context.secondaryParamName) { | ||
| this.applyCompositeCursorFilter( | ||
| where, | ||
| cursors, | ||
| dbType, | ||
| operator, | ||
| context, | ||
| ); | ||
| return; | ||
| } | ||
|
|
||
| where.orWhere(queryString, cursors); | ||
| this.applySingleColumnCursorFilter( | ||
| where, | ||
| cursors, | ||
| dbType, | ||
| operator, | ||
| context, | ||
| ); | ||
| } | ||
|
|
||
| private getOperator(): string { | ||
|
|
@@ -222,6 +244,10 @@ export default class Paginator<Entity extends ObjectLiteral> { | |
| orderByCondition[`${this.alias}.${PAGINATION_KEY}`] = order; | ||
| } | ||
|
|
||
| if (this.paginationColumnName && this.paginationSecondaryColumnName) { | ||
| orderByCondition[this.paginationSecondaryColumnName] = order; | ||
| } | ||
|
|
||
| return orderByCondition; | ||
| } | ||
|
|
||
|
|
@@ -257,9 +283,31 @@ export default class Paginator<Entity extends ObjectLiteral> { | |
| this.paginationColumnType || DEFAULT_TIMESTAMP_TYPE, | ||
| value, | ||
| ); | ||
| const payload = `${CUSTOM_PAGINATION_KEY}:${encodedValue}`; | ||
| const payload = [`${CUSTOM_PAGINATION_KEY}:${encodedValue}`]; | ||
|
|
||
| return btoa(payload); | ||
| if ( | ||
| this.paginationSecondaryColumnPath && | ||
| this.paginationSecondaryColumnName | ||
| ) { | ||
| const secondaryValue = getValueByPath( | ||
| entity, | ||
| this.paginationSecondaryColumnPath, | ||
| ); | ||
| if (secondaryValue === null || secondaryValue === undefined) { | ||
| throw new Error( | ||
| `Pagination secondary column not found at path: ${this.paginationSecondaryColumnPath}`, | ||
| ); | ||
| } | ||
| const encodedSecondaryValue = encodeByType( | ||
| this.paginationSecondaryColumnType || 'string', | ||
| secondaryValue, | ||
| ); | ||
| payload.push( | ||
| `${CUSTOM_PAGINATION_SECONDARY_KEY}:${encodedSecondaryValue}`, | ||
| ); | ||
| } | ||
|
|
||
| return btoa(payload.join(',')); | ||
| } | ||
|
|
||
| private decode(cursor: string): CursorParam { | ||
|
|
@@ -279,6 +327,9 @@ export default class Paginator<Entity extends ObjectLiteral> { | |
| if (key === CUSTOM_PAGINATION_KEY) { | ||
| return this.paginationColumnType || DEFAULT_TIMESTAMP_TYPE; | ||
| } | ||
| if (key === CUSTOM_PAGINATION_SECONDARY_KEY) { | ||
| return this.paginationSecondaryColumnType || 'string'; | ||
| } | ||
|
|
||
| const col = this.entity.options.columns[key]; | ||
| if (col === undefined) { | ||
|
|
@@ -291,6 +342,162 @@ export default class Paginator<Entity extends ObjectLiteral> { | |
| return order === Order.ASC ? Order.DESC : Order.ASC; | ||
| } | ||
|
|
||
| private buildComparisonClause({ | ||
| dbType, | ||
| columnName, | ||
| paramName, | ||
| operator, | ||
| }: { | ||
| dbType: DatabaseType; | ||
| columnName: string; | ||
| paramName: string; | ||
| operator: string; | ||
| }): string { | ||
| if (dbType === DatabaseType.SQLITE3) { | ||
| return `${columnName} ${operator} :${paramName}`; | ||
| } | ||
|
|
||
| if (dbType === DatabaseType.POSTGRES) { | ||
| const type = this.getEntityPropertyType(paramName); | ||
| if (this.isTimestampType(type)) { | ||
| if (operator === '<') { | ||
| return `${columnName} < :${paramName}::timestamptz`; | ||
| } | ||
| if (operator === '>') { | ||
| return `${columnName} >= (:${paramName}::timestamptz + INTERVAL '1 millisecond')`; | ||
| } | ||
| if (operator === '=') { | ||
| return `(${columnName} >= :${paramName}::timestamptz AND ${columnName} < (:${paramName}::timestamptz + INTERVAL '1 millisecond'))`; | ||
| } | ||
| return `${columnName} ${operator} :${paramName}::timestamptz`; | ||
| } | ||
| return `${columnName} ${operator} :${paramName}`; | ||
| } | ||
|
|
||
| throw new Error('Unsupported database type'); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. you already check with this.getSupportedDbType(); |
||
| } | ||
|
|
||
| private isTimestampType(type: string): boolean { | ||
| return ( | ||
| type === 'timestamp with time zone' || | ||
| type === 'datetime' || | ||
| type === 'date' | ||
| ); | ||
| } | ||
|
|
||
| private getSupportedDbType(): DatabaseType { | ||
| const dbType = system.get(AppSystemProp.DB_TYPE); | ||
| if (dbType === DatabaseType.SQLITE3 || dbType === DatabaseType.POSTGRES) { | ||
| return dbType; | ||
| } | ||
| throw new Error('Unsupported database type'); | ||
| } | ||
|
|
||
| private resolveCursorContext(cursors: CursorParam): CursorContext { | ||
| const customPaginationColumnName = this.paginationColumnName; | ||
| const hasCustomPaginationCursor = | ||
| customPaginationColumnName !== null && | ||
| cursors[CUSTOM_PAGINATION_KEY] !== undefined; | ||
|
|
||
| const primaryColumnName = | ||
| hasCustomPaginationCursor && customPaginationColumnName | ||
| ? customPaginationColumnName | ||
| : `${this.alias}.${PAGINATION_KEY}`; | ||
| const primaryParamName = hasCustomPaginationCursor | ||
| ? CUSTOM_PAGINATION_KEY | ||
| : PAGINATION_KEY; | ||
|
|
||
| const hasCustomSecondaryCursor = | ||
| this.paginationSecondaryColumnName !== null && | ||
| cursors[CUSTOM_PAGINATION_SECONDARY_KEY] !== undefined; | ||
|
|
||
| if (hasCustomPaginationCursor && hasCustomSecondaryCursor) { | ||
| return { | ||
| primaryColumnName, | ||
| primaryParamName, | ||
| secondaryColumnName: this.paginationSecondaryColumnName, | ||
| secondaryParamName: CUSTOM_PAGINATION_SECONDARY_KEY, | ||
| }; | ||
| } | ||
ravikiranvm marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| return { | ||
| primaryColumnName, | ||
| primaryParamName, | ||
| secondaryColumnName: null, | ||
| secondaryParamName: null, | ||
| }; | ||
| } | ||
|
|
||
| private applySingleColumnCursorFilter( | ||
| where: WhereExpressionBuilder, | ||
| cursors: CursorParam, | ||
| dbType: DatabaseType, | ||
| operator: string, | ||
| context: CursorContext, | ||
| ): void { | ||
| where.orWhere( | ||
| this.buildComparisonClause({ | ||
| dbType, | ||
| columnName: context.primaryColumnName, | ||
| paramName: context.primaryParamName, | ||
| operator, | ||
| }), | ||
| cursors, | ||
| ); | ||
| } | ||
|
|
||
| private applyCompositeCursorFilter( | ||
| where: WhereExpressionBuilder, | ||
| cursors: CursorParam, | ||
| dbType: DatabaseType, | ||
| operator: string, | ||
| context: CursorContext, | ||
| ): void { | ||
| const { | ||
| primaryColumnName, | ||
| primaryParamName, | ||
| secondaryColumnName, | ||
| secondaryParamName, | ||
| } = context; | ||
| if (!secondaryColumnName || !secondaryParamName) { | ||
| throw new Error('Pagination secondary context is not configured'); | ||
| } | ||
|
|
||
| where.orWhere( | ||
| this.buildComparisonClause({ | ||
| dbType, | ||
| columnName: primaryColumnName, | ||
| paramName: primaryParamName, | ||
| operator, | ||
| }), | ||
| cursors, | ||
| ); | ||
|
|
||
| // Lexicographic cursor compare: primary equals, then compare secondary key. | ||
| where.orWhere( | ||
| new Brackets((nestedWhere) => { | ||
| nestedWhere.where( | ||
| this.buildComparisonClause({ | ||
| dbType, | ||
| columnName: primaryColumnName, | ||
| paramName: primaryParamName, | ||
| operator: '=', | ||
| }), | ||
| cursors, | ||
| ); | ||
| nestedWhere.andWhere( | ||
| this.buildComparisonClause({ | ||
| dbType, | ||
| columnName: secondaryColumnName, | ||
| paramName: secondaryParamName, | ||
| operator, | ||
| }), | ||
| cursors, | ||
| ); | ||
| }), | ||
| ); | ||
| } | ||
|
|
||
| private toPagingResult<Entity>(entities: Entity[]): PagingResult<Entity> { | ||
| return { | ||
| data: entities, | ||
|
|
||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
why did you add this?