-
Notifications
You must be signed in to change notification settings - Fork 220
Expand file tree
/
Copy pathcreateIndex.svelte
More file actions
313 lines (282 loc) · 11.4 KB
/
createIndex.svelte
File metadata and controls
313 lines (282 loc) · 11.4 KB
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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
<script lang="ts">
import { base } from '$app/paths';
import { page } from '$app/state';
import { goto, invalidate } from '$app/navigation';
import { Submit, trackError, trackEvent } from '$lib/actions/analytics';
import { Dependencies } from '$lib/constants';
import { Button, InputNumber, InputSelect, InputText } from '$lib/elements/forms';
import { remove } from '$lib/helpers/array';
import { addNotification } from '$lib/stores/notifications';
import { sdk } from '$lib/stores/sdk';
import { IndexType } from '@appwrite.io/console';
import { isRelationship, isSpatialType } from '../rows/store';
import { table, indexes } from '../store';
import { Icon, Layout } from '@appwrite.io/pink-svelte';
import { IconCalendar, IconFingerPrint, IconPlus, IconX } from '@appwrite.io/pink-icons-svelte';
import { isSmallViewport } from '$lib/stores/viewport';
import { columnOptions as baseColumnOptions } from '../columns/store';
let {
showCreateIndex = $bindable(false),
externalColumnKey = null
}: {
showCreateIndex: boolean;
externalColumnKey?: string;
} = $props();
const databaseId = page.params.database;
let key = $state('');
let selectedType = $state<IndexType>(IndexType.Key);
let columnOptions = $derived(
$table.columns
.filter((column) => {
if (selectedType === IndexType.Spatial) {
return isSpatialType(column); // keep only spatial
}
return !isRelationship(column) && !isSpatialType(column); // keep non-relationship and non-spatial
})
.map((column) => ({
value: column.key,
label: column.key,
leadingIcon: baseColumnOptions.find((option) => option.type === column.type)?.icon
}))
);
let columnList = $state([{ value: '', order: '', length: null }]);
const types = [
{ value: IndexType.Key, label: 'Key' },
{ value: IndexType.Unique, label: 'Unique' },
{ value: IndexType.Fulltext, label: 'Fulltext' },
{ value: IndexType.Spatial, label: 'Spatial' }
];
// order options derived from selected type
let orderOptions = $derived.by(() =>
selectedType === IndexType.Spatial
? [
{ value: 'ASC', label: 'ASC' },
{ value: 'DESC', label: 'DESC' },
{ value: null, label: 'NONE' }
]
: [
{ value: 'ASC', label: 'ASC' },
{ value: 'DESC', label: 'DESC' }
]
);
// Handle index type changes and reset incompatible columns
$effect(() => {
if (selectedType === IndexType.Spatial) {
// When switching to spatial, reset to single empty column with null order
// or clear any non-spatial columns that were previously selected
const currentColumn = columnList.at(0)?.value;
const currentColumnObj = $table.columns.find(col => col.key === currentColumn);
if (!currentColumn || !currentColumnObj || !isSpatialType(currentColumnObj)) {
columnList = [{ value: '', order: null, length: null }];
} else {
// Keep the spatial column but ensure order is null
columnList = [{ value: currentColumn, order: null, length: null }];
}
} else {
// When switching away from spatial, ensure non-spatial columns have proper order
const currentColumn = columnList.at(0)?.value;
if (currentColumn && columnList.at(0)?.order === null) {
columnList = [{ value: currentColumn, order: 'ASC', length: null }];
}
}
});
function generateIndexKey() {
let indexKeys = $indexes.map((index) => index.key);
let highestIndex = indexKeys.reduce((max, key) => {
const match = key.match(/^index_(\d+)$/);
return match ? Math.max(max, parseInt(match[1], 10)) : max;
}, indexKeys.length);
return `index_${highestIndex + 1}`;
}
function initialize() {
const column = $table.columns.filter((column) => externalColumnKey === column.key);
const isSpatial = column.length && isSpatialType(column[0]);
const order = isSpatial ? null : 'ASC';
selectedType = isSpatial ? IndexType.Spatial : IndexType.Key;
columnList = externalColumnKey
? [{ value: externalColumnKey, order, length: null }]
: [{ value: '', order, length: null }];
key = `index_${$indexes.length + 1}`;
}
const addColumnDisabled = $derived(
selectedType === IndexType.Spatial ||
!columnList.at(-1)?.value ||
(!columnList.at(-1)?.order && columnList.at(-1)?.order !== null)
);
const isOnIndexesPage = $derived(page.route.id?.endsWith('/indexes'));
const navigatorPathToIndexes = $derived(
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${databaseId}/table-${$table?.$id}/indexes`
);
let initializedForOpen = $state(false);
$effect(() => {
if (showCreateIndex && !initializedForOpen) {
initialize();
key = generateIndexKey();
initializedForOpen = true;
}
if (!showCreateIndex && initializedForOpen) {
initializedForOpen = false;
}
});
export async function create() {
// Validate basic requirements
if (!key || !selectedType) {
addNotification({
type: 'error',
message: 'Index key and type are required'
});
throw new Error('Index key and type are required');
}
// Validate column selection for spatial indexes
if (selectedType === IndexType.Spatial) {
if (!columnList.at(0)?.value) {
addNotification({
type: 'error',
message: 'Please select a spatial column for the spatial index'
});
throw new Error('Please select a spatial column for the spatial index');
}
} else if (addColumnDisabled) {
addNotification({
type: 'error',
message: 'Selected column key or type invalid'
});
throw new Error('Selected column key or type invalid');
}
try {
const orders = columnList.map((a) => a.order).filter((order) => order !== null);
await sdk.forProject(page.params.region, page.params.project).tablesDB.createIndex({
databaseId,
tableId: $table.$id,
key,
type: selectedType,
columns: columnList.map((a) => a.value),
lengths: columnList.map((a) => (a.length ? Number(a.length) : null)),
...(orders.length ? { orders } : {})
});
await Promise.allSettled([
invalidate(Dependencies.TABLE),
invalidate(Dependencies.DATABASE)
]);
addNotification({
message: 'Index is being created',
type: 'success',
buttons: !isOnIndexesPage
? [
{
name: 'View indexes',
method: () => goto(navigatorPathToIndexes)
}
]
: undefined
});
trackEvent(Submit.IndexCreate, { type: 'manual' });
showCreateIndex = false;
} catch (err) {
addNotification({
type: 'error',
message: err.message
});
trackError(err, Submit.IndexCreate);
throw err;
}
}
function addColumn() {
if (addColumnDisabled) return;
// We assign instead of pushing to trigger Svelte's reactivity
columnList = [...columnList, { value: '', order: '', length: null }];
}
</script>
<InputText
required
id="key"
label="Index Key"
pattern="^[A-Za-z0-9][A-Za-z0-9._\-]*$"
placeholder="Enter Key"
bind:value={key}
autofocus />
<InputSelect required options={types} id="type" label="Index type" bind:value={selectedType} />
<Layout.Stack gap="s">
{#each columnList as column, index}
{@const direction = $isSmallViewport ? 'column' : 'row'}
<Layout.Stack {direction}>
<InputSelect
required
options={[
// allow system fields only for non-spatial index types
...(selectedType === IndexType.Spatial
? []
: [
{ value: '$id', label: '$id', leadingIcon: IconFingerPrint },
{
value: '$createdAt',
label: '$createdAt',
leadingIcon: IconCalendar
},
{
value: '$updatedAt',
label: '$updatedAt',
leadingIcon: IconCalendar
}
]),
...columnOptions
]}
id={`column-${index}`}
label={index === 0 ? 'Column' : undefined}
placeholder="Select column"
bind:value={column.value} />
<InputSelect
options={orderOptions}
required
id={`order-${index}`}
label={index === 0 ? 'Order' : undefined}
bind:value={column.order}
placeholder="Select order" />
{#if selectedType === IndexType.Key}
<InputNumber
id={`length-${index}`}
label={index === 0 ? 'Length' : undefined}
placeholder="Enter length"
bind:value={column.length} />
{/if}
{#if $isSmallViewport}
<div style:margin-top="0.25rem">
<Button
text
secondary
disabled={columnList.length <= 1}
on:click={() => {
columnList = remove(columnList, index);
}}>
Remove
</Button>
</div>
{:else}
<div style:margin-top="27.6px" class="x-button-holder">
<Button
icon
size="s"
secondary
disabled={columnList.length <= 1}
on:click={() => {
columnList = remove(columnList, index);
}}>
<Icon icon={IconX} size="s" />
</Button>
</div>
{/if}
</Layout.Stack>
{/each}
<div>
<Button compact on:click={addColumn} disabled={addColumnDisabled}>
<Icon icon={IconPlus} slot="start" size="s" />
Add column
</Button>
</div>
</Layout.Stack>
<style lang="scss">
.x-button-holder :global(button) {
width: 34px;
height: 34px;
}
</style>