$size query (#9591)

Signed-off-by: Denis Bykhov <bykhov.denis@gmail.com>
This commit is contained in:
Denis Bykhov
2025-07-23 18:15:34 +05:00
committed by GitHub
parent 679a3df09f
commit 3ff80a095c
17 changed files with 274 additions and 47 deletions
-2
View File
@@ -61,8 +61,6 @@ export default mergeIds(viewId, view, {
HyperlinkEditorPopup: '' as AnyComponent,
IntlStringPresenter: '' as AnyComponent,
FileSizePresenter: '' as AnyComponent,
NumberEditor: '' as AnyComponent,
NumberPresenter: '' as AnyComponent,
MarkupDiffPresenter: '' as AnyComponent,
MarkupPresenter: '' as AnyComponent,
BooleanPresenter: '' as AnyComponent,
+24
View File
@@ -110,6 +110,30 @@ const predicates: Record<string, PredicateFactory> = {
$ne: (o, propertyKey) => {
// eslint-disable-next-line eqeqeq
return (docs) => execPredicate(docs, propertyKey, (value) => (o != null ? !deepEqual(o, value) : value != null))
},
$size: (o, propertyKey) => {
return (docs) =>
execPredicate(docs, propertyKey, (value) => {
if (!Array.isArray(value)) {
throw new Error('$size predicate requires array')
}
if (typeof o === 'number') {
return value.length === o
}
if (typeof o === 'object' && o.$gt !== undefined) {
return value.length > o.$gt
}
if (typeof o === 'object' && o.$gte !== undefined) {
return value.length >= o.$gte
}
if (typeof o === 'object' && o.$lt !== undefined) {
return value.length < o.$lt
}
if (typeof o === 'object' && o.$lte !== undefined) {
return value.length <= o.$lte
}
return false
})
}
}
+15
View File
@@ -19,6 +19,20 @@ import type { KeysByType } from 'simplytyped'
import type { Association, AttachedDoc, Class, Doc, Domain, Ref, Space } from './classes'
import type { Tx } from './tx'
export type ArraySizeSelector =
| {
$gt: number
}
| {
$lt: number
}
| {
$gte: number
}
| {
$lte: number
}
/**
* @public
*/
@@ -36,6 +50,7 @@ export type QuerySelector<T> = {
$like?: string
$regex?: string
$options?: string
$size?: T extends Array<any> ? number | ArraySizeSelector : never
}
/**
+6 -1
View File
@@ -91,7 +91,12 @@
"Started": "Started",
"Each": "Each",
"CreateCard": "Create card",
"OnCardUpdate": "On card update"
"OnCardUpdate": "On card update",
"ArraySizeEquals": "Size equals",
"ArraySizeGt": "Size greater than",
"ArraySizeGte": "Size greater than or equal",
"ArraySizeLt": "Size less than",
"ArraySizeLte": "Size less than or equal"
},
"error": {
"MethodNotFound": "Method not found: {methodId}",
+6 -1
View File
@@ -91,7 +91,12 @@
"Started": "Iniciado",
"Each": "Cada",
"CreateCard": "Crear tarjeta",
"OnCardUpdate": "Al actualizar la tarjeta"
"OnCardUpdate": "Al actualizar la tarjeta",
"ArraySizeEquals": "Tamaño igual a",
"ArraySizeGt": "Tamaño mayor que",
"ArraySizeGte": "Tamaño mayor o igual que",
"ArraySizeLt": "Tamaño menor que",
"ArraySizeLte": "Tamaño menor o igual que"
},
"error": {
"MethodNotFound": "Método no encontrado: {methodId}",
+6 -1
View File
@@ -91,7 +91,12 @@
"Started": "Démarré",
"Each": "Chaque",
"CreateCard": "Créer une carte",
"OnCardUpdate": "Lors de la mise à jour de la carte"
"OnCardUpdate": "À la modification de la carte",
"ArraySizeEquals": "Taille égale à",
"ArraySizeGt": "Taille supérieure à",
"ArraySizeGte": "Taille supérieure ou égale à",
"ArraySizeLt": "Taille inférieure à",
"ArraySizeLte": "Taille inférieure ou égale à"
},
"error": {
"MethodNotFound": "Méthode introuvable : {methodId}",
+6 -1
View File
@@ -91,7 +91,12 @@
"Started": "Avviato",
"Each": "Ogni",
"CreateCard": "Crea scheda",
"OnCardUpdate": "Alla modifica della scheda"
"OnCardUpdate": "Alla modifica della scheda",
"ArraySizeEquals": "Dimensione uguale a",
"ArraySizeGt": "Dimensione maggiore di",
"ArraySizeGte": "Dimensione maggiore o uguale a",
"ArraySizeLt": "Dimensione minore di",
"ArraySizeLte": "Dimensione minore o uguale a"
},
"error": {
"MethodNotFound": "Metodo non trovato: {methodId}",
+6 -1
View File
@@ -90,7 +90,12 @@
"Started": "開始",
"Each": "各",
"CreateCard": "カードを作成",
"OnCardUpdate": "カード更新時"
"OnCardUpdate": "カード更新時",
"ArraySizeEquals": "サイズが等しい",
"ArraySizeGt": "サイズがより大きい",
"ArraySizeGte": "サイズが以上",
"ArraySizeLt": "サイズがより小さい",
"ArraySizeLte": "サイズが以下"
},
"error": {
"MethodNotFound": "メソッドが見つかりません: {methodId}",
+6 -1
View File
@@ -91,7 +91,12 @@
"Started": "Iniciado",
"Each": "Cada",
"CreateCard": "Criar Cartão",
"OnCardUpdate": "Ao atualizar o cartão"
"OnCardUpdate": "Ao atualizar o cartão",
"ArraySizeEquals": "Tamanho igual a",
"ArraySizeGt": "Tamanho maior que",
"ArraySizeGte": "Tamanho maior ou igual a",
"ArraySizeLt": "Tamanho menor que",
"ArraySizeLte": "Tamanho menor ou igual a"
},
"error": {
"MethodNotFound": "Método não encontrado: {methodId}",
+6 -1
View File
@@ -91,7 +91,12 @@
"Started": "Начат",
"Each": "Каждый",
"CreateCard": "Создать карточку",
"OnCardUpdate": "При обновлении карточки"
"OnCardUpdate": "При обновлении карточки",
"ArraySizeEquals": "Размер равен",
"ArraySizeGt": "Размер больше чем",
"ArraySizeGte": "Размер больше или равен",
"ArraySizeLt": "Размер меньше чем",
"ArraySizeLte": "Размер меньше или равен"
},
"error": {
"MethodNotFound": "Метод не найден: {methodId}",
+6 -1
View File
@@ -91,7 +91,12 @@
"Started": "已启动",
"Each": "每个",
"CreateCard": "创建卡片",
"OnCardUpdate": "在卡片更新时"
"OnCardUpdate": "在卡片更新时",
"ArraySizeEquals": "大小等于",
"ArraySizeGt": "大小大于",
"ArraySizeGte": "大小大于等于",
"ArraySizeLt": "大小小于",
"ArraySizeLte": "大小小于等于"
},
"error": {
"MethodNotFound": "找不到方法:{methodId}",
@@ -15,6 +15,7 @@
<script lang="ts">
import core, { AnyAttribute } from '@hcengineering/core'
import { getClient } from '@hcengineering/presentation'
import { Context, parseContext, Process, SelectedContext } from '@hcengineering/process'
import {
AnyComponent,
@@ -29,6 +30,7 @@
} from '@hcengineering/ui'
import view from '@hcengineering/view-resources/src/plugin'
import { createEventDispatcher } from 'svelte'
import { getContext } from '../../utils'
import ContextSelectorPopup from '../attributeEditors/ContextSelectorPopup.svelte'
import ContextValue from '../attributeEditors/ContextValue.svelte'
@@ -39,13 +41,41 @@
export let attribute: AnyAttribute
export let baseEditor: AnyComponent | undefined
const client = getClient()
$: numberContext = getContext(client, process, core.class.TypeNumber, 'attribute')
const modes: DropdownIntlItem[] = [
{ id: 'all', label: view.string.FilterArrayAll },
{ id: 'any', label: view.string.FilterArrayAny },
{ id: 'notall', label: view.string.NotContains }
{ id: 'notall', label: view.string.NotContains },
{ id: 'size', label: view.string.ArraySizeEquals },
{ id: 'sizeGt', label: view.string.ArraySizeGt },
{ id: 'sizeGte', label: view.string.ArraySizeGte },
{ id: 'sizeLt', label: view.string.ArraySizeLt },
{ id: 'sizeLte', label: view.string.ArraySizeLte }
]
let mode = value == null ? 'all' : value.$all !== undefined ? 'all' : value.$in !== undefined ? 'any' : 'notIncludes'
let mode =
value == null
? 'all'
: value.$all !== undefined
? 'all'
: value.$in !== undefined
? 'any'
: value.$nin !== undefined
? 'notIncludes'
: value.$size !== undefined
? typeof value.$size === 'object'
? Object.keys(value.$size)[0] === '$gt'
? 'sizeGt'
: Object.keys(value.$size)[0] === '$gte'
? 'sizeGte'
: Object.keys(value.$size)[0] === '$lt'
? 'sizeLt'
: 'sizeLte'
: 'size'
: 'all'
const dispatch = createEventDispatcher()
@@ -58,7 +88,7 @@
{
process,
masterTag: process.masterTag,
context,
context: isSize(mode) ? numberContext : context,
attribute,
onSelect
},
@@ -78,6 +108,16 @@
} else if (value?.$nin !== undefined) {
mode = 'notIncludes'
val = value.$nin
} else if (value?.$size !== undefined) {
if (typeof value.$size === 'object') {
const operator = Object.keys(value.$size)[0]
val = value.$size[operator]
mode =
operator === '$gt' ? 'sizeGt' : operator === '$gte' ? 'sizeGte' : operator === '$lt' ? 'sizeLt' : 'sizeLte'
} else {
mode = 'size'
val = value.$size
}
} else {
mode = 'all'
val = undefined
@@ -86,16 +126,14 @@
}
function onSelect (res: SelectedContext | null): void {
val = res === null ? undefined : '$' + JSON.stringify(res)
buildResult()
buildResult(res === null ? undefined : '$' + JSON.stringify(res))
}
function onChange (value: any | undefined): void {
val = value
buildResult()
buildResult(value)
}
function buildResult () {
function buildResult (val: any | undefined) {
if (val === undefined || val === '') {
dispatch('change', null)
return
@@ -106,12 +144,21 @@
result = { $all: val }
} else if (mode === 'any') {
result = { $in: val }
} else {
} else if (mode === 'notIncludes') {
result = { $nin: val }
} else if (mode === 'size') {
result = { $size: val }
} else if (mode.startsWith('size')) {
const operator = mode === 'sizeGt' ? '$gt' : mode === 'sizeGte' ? '$gte' : mode === 'sizeLt' ? '$lt' : '$lte'
result = { $size: { [operator]: val } }
}
value = result
dispatch('change', result)
}
function isSize (mode: string): boolean {
return mode.startsWith('size')
}
</script>
<div class="flex-row-center flex-gap-4">
@@ -124,44 +171,78 @@
width={'100%'}
on:selected={(e) => {
mode = e.detail
buildResult()
buildResult(val)
}}
/>
<div class="text-input" class:context={contextValue}>
{#if contextValue}
{#if !isSize(mode)}
{#if contextValue}
<ContextValue
{process}
masterTag={process.masterTag}
{contextValue}
{context}
{attribute}
category={'attribute'}
attrClass={core.class.ArrOf}
on:update={(e) => {
onSelect(e.detail)
}}
/>
{:else}
<div class="w-full">
{#if baseEditor}
<Component
is={baseEditor}
props={{
label: attribute?.label,
placeholder: attribute?.label,
kind: 'ghost',
size: 'large',
width: '100%',
justify: 'left',
readonly,
type: attribute?.type,
value: val,
onChange,
focus
}}
/>
{/if}
</div>
{/if}
{:else if contextValue}
<ContextValue
{process}
masterTag={process.masterTag}
{contextValue}
{context}
context={numberContext}
{attribute}
category={'attribute'}
attrClass={core.class.ArrOf}
attrClass={core.class.TypeNumber}
on:update={(e) => {
onSelect(e.detail)
}}
/>
{:else}
{:else if !Number.isNaN(val)}
<div class="w-full">
{#if baseEditor}
<Component
is={baseEditor}
props={{
label: attribute?.label,
placeholder: attribute?.label,
kind: 'ghost',
size: 'large',
width: '100%',
justify: 'left',
readonly,
type: attribute?.type,
value: val,
onChange,
focus
}}
/>
{/if}
<Component
is={view.component.NumberEditor}
props={{
label: attribute?.label,
placeholder: attribute?.label,
kind: 'ghost',
size: 'large',
width: '100%',
justify: 'left',
readonly,
type: core.class.TypeNumber,
value: val,
onChange,
focus
}}
/>
</div>
{/if}
<div class="button flex-row-center">
+8 -1
View File
@@ -31,7 +31,9 @@ export default mergeIds(viewId, view, {
ProxyPresenter: '' as AnyComponent,
ArrayEditor: '' as AnyComponent,
SpaceTypeSelector: '' as AnyComponent,
MasterDetailBrowser: '' as AnyComponent
MasterDetailBrowser: '' as AnyComponent,
NumberEditor: '' as AnyComponent,
NumberPresenter: '' as AnyComponent
},
string: {
Contains: '' as IntlString,
@@ -62,6 +64,11 @@ export default mergeIds(viewId, view, {
FilterUpdated: '' as IntlString,
FilterLessThan: '' as IntlString,
FilterGreaterThan: '' as IntlString,
ArraySizeEquals: '' as IntlString,
ArraySizeGt: '' as IntlString,
ArraySizeGte: '' as IntlString,
ArraySizeLt: '' as IntlString,
ArraySizeLte: '' as IntlString,
Before: '' as IntlString,
After: '' as IntlString,
Apply: '' as IntlString,
+12
View File
@@ -15,6 +15,7 @@
import core, {
type AccountUuid,
type AnyAttribute,
type Arr,
type AttachedDoc,
type Class,
@@ -43,6 +44,10 @@ export function createClass (_class: Ref<Class<Obj>>, attributes: Data<Class<Obj
return txFactory.createTxCreateDoc(core.class.Class, core.space.Model, attributes, _class)
}
export function createAttribute (attribute: Data<AnyAttribute>): TxCreateDoc<Doc> {
return txFactory.createTxCreateDoc(core.class.Attribute, core.space.Model, attribute)
}
/**
* @public
*/
@@ -115,6 +120,13 @@ export function genMinModel (): TxCUD<Doc>[] {
txes.push(
createClass(core.class.Doc, { label: 'Doc' as IntlString, extends: core.class.Obj, kind: ClassifierKind.CLASS })
)
txes.push(
createClass(core.class.Attribute, {
label: 'Attribute' as IntlString,
extends: core.class.Doc,
kind: ClassifierKind.CLASS
})
)
txes.push(
createClass(core.class.Relation, {
label: 'Relation' as IntlString,
+17 -1
View File
@@ -154,7 +154,8 @@ describe('postgres operations', () => {
await operations.createDoc(taskPlugin.class.Task, '' as Ref<Space>, {
name: `my-task-${i}`,
description: `${i * i}`,
rate: 20 + i
rate: 20 + i,
arr: new Array(i).fill(i)
})
}
@@ -169,6 +170,21 @@ describe('postgres operations', () => {
const third = await client.findAll<Task>(taskPlugin.class.Task, { rate: { $in: [25, 26, 27, 28] } })
expect(third.length).toEqual(4)
const size = await client.findAll<Task>(taskPlugin.class.Task, { arr: { $size: 5 } })
expect(size.length).toEqual(1)
const sizeGt = await client.findAll<Task>(taskPlugin.class.Task, { arr: { $size: { $gt: 45 } } })
expect(sizeGt.length).toEqual(4)
const sizeGte = await client.findAll<Task>(taskPlugin.class.Task, { arr: { $size: { $gte: 45 } } })
expect(sizeGte.length).toEqual(5)
const sizeLt = await client.findAll<Task>(taskPlugin.class.Task, { arr: { $size: { $lt: 45 } } })
expect(sizeLt.length).toEqual(45)
const sizeLte = await client.findAll<Task>(taskPlugin.class.Task, { arr: { $size: { $lte: 45 } } })
expect(sizeLte.length).toEqual(46)
})
it('check update', async () => {
+11 -2
View File
@@ -1,4 +1,4 @@
import {
import core, {
type AttachedDoc,
type Class,
ClassifierKind,
@@ -11,7 +11,7 @@ import {
type Tx
} from '@hcengineering/core'
import { type IntlString, plugin, type Plugin } from '@hcengineering/platform'
import { createClass } from './minmodel'
import { createAttribute, createClass } from './minmodel'
export interface TaskComment extends AttachedDoc {
message: string
@@ -107,6 +107,15 @@ export function createTaskModel (txes: Tx[]): void {
kind: ClassifierKind.CLASS,
label: 'Comment' as IntlString,
domain: 'test-task' as Domain
}),
createAttribute({
attributeOf: taskPlugin.class.Task,
name: 'arr',
type: {
_class: core.class.ArrOf,
label: 'arr' as IntlString,
type: core.class.TypeNumber
}
})
)
}
+25
View File
@@ -1263,6 +1263,31 @@ abstract class PostgresAdapterBase implements DbAdapter {
res.push(`${tkey} @> ${vars.addArray(val, valType)}`)
}
break
case '$size': {
let v = val
let op = '='
if (typeof val === 'object') {
if (val.$gt !== undefined) {
v = val.$gt
op = '>'
} else if (val.$gte !== undefined) {
v = val.$gte
op = '>='
} else if (val.$lt !== undefined) {
v = val.$lt
op = '<'
} else if (val.$lte !== undefined) {
v = val.$lte
op = '<='
}
}
if (type === 'dataArray') {
res.push(`coalesce(jsonb_array_length(${tkey}), 0) ${op} ${vars.add(v, '::integer')}`)
} else {
res.push(`array_length(${tkey}, 1) ${op} ${vars.add(v, '::integer')}`)
}
break
}
default:
nonOperator[operator] = value[operator]
break