1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
|
import { isEmpty, isNotEmpty } from "@/db/utils"
import type { Filter, JoinOperator } from "@/types/table"
import { addDays, endOfDay, startOfDay } from "date-fns"
import {
and,
eq,
gt,
gte,
ilike,
inArray,
lt,
lte,
ne,
notIlike,
notInArray,
or,
type AnyColumn,
type SQL,
type Table,
} from "drizzle-orm"
import type { PgTable, PgView } from "drizzle-orm/pg-core"
type TableOrView = PgTable | PgView<any>
// 조인된 테이블들의 타입 정의
export interface JoinedTables {
[key: string]: TableOrView
}
// 커스텀 컬럼 매핑 타입 정의
export interface CustomColumnMapping {
[filterId: string]: {
table: TableOrView
column: string
} | AnyColumn
}
/**
* Enhanced filterColumns function that supports joined tables and custom column mapping.
*
* This function can handle filters that reference columns from different tables
* in a joined query, and allows for custom mapping of filter IDs to actual table columns.
*/
export function filterColumns<T extends TableOrView>({
table,
filters,
joinOperator,
joinedTables,
customColumnMapping,
}: {
table: T
filters: Filter<T>[]
joinOperator: JoinOperator
joinedTables?: JoinedTables
customColumnMapping?: CustomColumnMapping
}): SQL | undefined {
const joinFn = joinOperator === "and" ? and : or
const conditions = filters.map((filter) => {
const column = getColumnWithMapping(table, filter.id, joinedTables, customColumnMapping)
if (!column) {
console.warn(`Column not found for filter ID: ${filter.id}`)
return undefined
}
switch (filter.operator) {
case "eq":
if (Array.isArray(filter.value)) {
return inArray(column, filter.value)
} else if (
column.dataType === "boolean" &&
typeof filter.value === "string"
) {
return eq(column, filter.value === "true")
} else if (filter.type === "date") {
const date = new Date(filter.value)
const start = startOfDay(date)
const end = endOfDay(date)
return and(gte(column, start), lte(column, end))
} else {
return eq(column, filter.value)
}
case "ne":
if (Array.isArray(filter.value)) {
return notInArray(column, filter.value)
} else if (column.dataType === "boolean") {
return ne(column, filter.value === "true")
} else if (filter.type === "date") {
const date = new Date(filter.value)
const start = startOfDay(date)
const end = endOfDay(date)
return or(lt(column, start), gt(column, end))
} else {
return ne(column, filter.value)
}
case "iLike":
return filter.type === "text" && typeof filter.value === "string"
? ilike(column, `%${filter.value}%`)
: undefined
case "notILike":
return filter.type === "text" && typeof filter.value === "string"
? notIlike(column, `%${filter.value}%`)
: undefined
case "lt":
return filter.type === "number"
? lt(column, filter.value)
: filter.type === "date" && typeof filter.value === "string"
? lt(column, endOfDay(new Date(filter.value)))
: undefined
case "lte":
return filter.type === "number"
? lte(column, filter.value)
: filter.type === "date" && typeof filter.value === "string"
? lte(column, endOfDay(new Date(filter.value)))
: undefined
case "gt":
return filter.type === "number"
? gt(column, filter.value)
: filter.type === "date" && typeof filter.value === "string"
? gt(column, startOfDay(new Date(filter.value)))
: undefined
case "gte":
return filter.type === "number"
? gte(column, filter.value)
: filter.type === "date" && typeof filter.value === "string"
? gte(column, startOfDay(new Date(filter.value)))
: undefined
case "isBetween":
return filter.type === "date" &&
Array.isArray(filter.value) &&
filter.value.length === 2
? and(
filter.value[0]
? gte(column, startOfDay(new Date(filter.value[0])))
: undefined,
filter.value[1]
? lte(column, endOfDay(new Date(filter.value[1])))
: undefined
)
: undefined
case "isRelativeToToday":
if (filter.type === "date" && typeof filter.value === "string") {
const today = new Date()
const [amount, unit] = filter.value.split(" ") ?? []
let startDate: Date
let endDate: Date
if (!amount || !unit) return undefined
switch (unit) {
case "days":
startDate = startOfDay(addDays(today, parseInt(amount)))
endDate = endOfDay(startDate)
break
case "weeks":
startDate = startOfDay(addDays(today, parseInt(amount) * 7))
endDate = endOfDay(addDays(startDate, 6))
break
case "months":
startDate = startOfDay(addDays(today, parseInt(amount) * 30))
endDate = endOfDay(addDays(startDate, 29))
break
default:
return undefined
}
return and(gte(column, startDate), lte(column, endDate))
}
return undefined
case "isEmpty":
return isEmpty(column)
case "isNotEmpty":
return isNotEmpty(column)
default:
throw new Error(`Unsupported operator: ${filter.operator}`)
}
})
const validConditions = conditions.filter(
(condition) => condition !== undefined
)
return validConditions.length > 0 ? joinFn(...validConditions) : undefined
}
/**
* Enhanced column getter - 간단한 수정 버전
*/
function getColumnWithMapping<T extends TableOrView>(
table: T,
columnKey: keyof T | string,
joinedTables?: JoinedTables,
customColumnMapping?: CustomColumnMapping
): AnyColumn | undefined {
// 1. 커스텀 매핑이 있는 경우 우선 확인
if (customColumnMapping && columnKey in customColumnMapping) {
const mapping = customColumnMapping[columnKey as string]
if (typeof mapping === 'object' && 'dataType' in mapping) {
return mapping as AnyColumn
}
if (typeof mapping === 'object' && 'table' in mapping && 'column' in mapping) {
try {
if (mapping.table && typeof mapping.column === 'string') {
const column = (mapping.table as any)[mapping.column];
if (column !== undefined) {
return column as AnyColumn;
}
}
} catch (error) {
console.warn(`Failed to get column ${mapping.column} from table:`, error)
}
}
}
// 2. 메인 테이블에서 컬럼 찾기 - 수정된 부분
if (typeof columnKey === 'string') {
// ✅ in 연산자 대신 직접 접근해서 undefined 체크
try {
const column = (table as any)[columnKey];
if (column !== undefined && column !== null) {
return column as AnyColumn;
}
} catch (error) {
// 직접 접근 실패 시 조용히 넘어감
}
} else {
// keyof T 타입인 경우 기존 함수 사용
try {
return getColumn(table, columnKey);
} catch (error) {
// getColumn 실패 시 조용히 넘어감
}
}
// 3. 조인된 테이블들에서 컬럼 찾기
if (joinedTables && typeof columnKey === 'string') {
for (const [tableName, joinedTable] of Object.entries(joinedTables)) {
try {
const column = (joinedTable as any)[columnKey];
if (column !== undefined && column !== null) {
return column as AnyColumn;
}
} catch (error) {
// 조용히 넘어감
}
}
}
// 4. 컬럼을 찾지 못한 경우
return undefined;
}
/**
* Get table column (기존 함수 유지).
*/
export function getColumn<T extends TableOrView>(
table: T,
columnKey: keyof T
): AnyColumn {
return table[columnKey] as AnyColumn
}
/**
* Safe helper to get column from any table with string key
*/
export function getColumnSafe(table: TableOrView, columnKey: string): AnyColumn | undefined {
try {
if (columnKey in table) {
return (table as any)[columnKey] as AnyColumn
}
} catch (error) {
console.warn(`Failed to get column ${columnKey} from table:`, error)
}
return undefined
}
// 사용 예시를 위한 타입 정의
export type FilterColumnsParams<T extends TableOrView> = Parameters<typeof filterColumns<T>>[0]
|