import type { CursorFilter } from '@resolve-js/eventstore-base' ; import { cursorToThreadArray } from '@resolve-js/eventstore-base' ; import type { AdapterPool } from './types' ; import { INT8_SQL_TYPE } from './constants' ; type LoadFilter = Omit < CursorFilter , 'limit' > & { limit ? : CursorFilter [ 'limit' ] ; } ; const createLoadQuery = ( { escapeId , escape , eventsTableName , databaseName } , { eventTypes , aggregateIds , cursor , limit } ) => { const vectorConditions = cursorToThreadArray ( cursor ) ; const injectString = ( value ) : string => `${ escape ( value ) }` ; const injectNumber = ( value ) : string => `${ + value }` ; const queryConditions = [ '1 = 1' ] ; if ( eventTypes != null ) { if ( eventTypes . length === 0 ) { return null ; } queryConditions . push ( `"type" IN (${ eventTypes . map ( injectString ) })` ) ; } if ( aggregateIds != null ) { if ( aggregateIds . length === 0 ) { return null ; } queryConditions . push ( `"aggregateId" IN (${ aggregateIds . map ( injectString ) })` ) ; } const resultQueryCondition = queryConditions . join ( ' AND ' ) ; const databaseNameAsId = escapeId ( databaseName ) ; const eventsTableAsId = escapeId ( eventsTableName ) ; if ( limit !== undefined ) { return [ `SELECT "unitedEvents".* FROM (
        ${ vectorConditions . map ( ( threadCounter , threadId ) => `(${ [ `SELECT * FROM ${ databaseNameAsId }.${ eventsTableAsId }` , `WHERE (${ resultQueryCondition }) AND "threadId" = ${ threadId } AND "threadCounter" >= ${ threadCounter }::${ INT8_SQL_TYPE }` , `LIMIT ${ limit }` , ] . join ( ' ' ) })` ) . join ( ' UNION ALL \n' ) }
        ) "unitedEvents"` , `ORDER BY "unitedEvents"."timestamp" ASC, "unitedEvents"."threadCounter" ASC, "unitedEvents"."threadId" ASC` , `LIMIT ${ + limit }` , ] . join ( '\n' ) ; } else { const resultVectorConditions = `${ vectorConditions . map ( ( threadCounter , threadId ) => `"threadId" = ${ injectNumber ( threadId ) } AND "threadCounter" >= ${ threadCounter }::${ INT8_SQL_TYPE } ` ) . join ( ' OR ' ) }` ; return [ `SELECT * FROM ${ databaseNameAsId }.${ eventsTableAsId }` , `WHERE (${ resultVectorConditions }) AND (${ resultQueryCondition })` , `ORDER BY "timestamp" ASC, "threadCounter" ASC, "threadId" ASC` , ] . join ( '\n' ) ; } } ; export default createLoadQuery ;