Merge pull request #2152 from appwrite/revert-2143-1.8.x

Revert "1.8.x"
This commit is contained in:
Jake Barnby authored and GitHub committed 2025-07-24 23:41:49 +12:00
commit 297d732f9a
128 files changed
+1561 -1640

No files matched your search

+1 -1
View File
@@ -22,7 +22,7 @@
},
"dependencies": {
"@ai-sdk/svelte": "^1.1.24",
"@appwrite.io/console": "https://pkg.pr.new/appwrite-labs/cloud/@appwrite.io/console@935b30f",
"@appwrite.io/console": "https://pkg.pr.new/appwrite-labs/cloud/@appwrite.io/console@8836b0c",
"@appwrite.io/pink-icons": "0.25.0",
"@appwrite.io/pink-icons-svelte": "^2.0.0-RC.1",
"@appwrite.io/pink-legacy": "^1.0.3",
+9 -9
View File
@@ -12,8 +12,8 @@ importers:
specifier: ^1.1.24
version: 1.1.24(svelte@5.25.3)(zod@3.24.3)
'@appwrite.io/console':
specifier: https://pkg.pr.new/appwrite-labs/cloud/@appwrite.io/console@935b30f
version: https://pkg.pr.new/appwrite-labs/cloud/@appwrite.io/console@935b30f
specifier: https://pkg.pr.new/appwrite-labs/cloud/@appwrite.io/console@8836b0c
version: https://pkg.pr.new/appwrite-labs/cloud/@appwrite.io/console@8836b0c
'@appwrite.io/pink-icons':
specifier: 0.25.0
version: 0.25.0
@@ -257,8 +257,8 @@ packages:
'@analytics/type-utils@0.6.2':
resolution: {integrity: sha512-TD+xbmsBLyYy/IxFimW/YL/9L2IEnM7/EoV9Aeh56U64Ify8o27HJcKjo38XY9Tcn0uOq1AX3thkKgvtWvwFQg==}
'@appwrite.io/console@https://pkg.pr.new/appwrite-labs/cloud/@appwrite.io/console@935b30f':
resolution: {tarball: https://pkg.pr.new/appwrite-labs/cloud/@appwrite.io/console@935b30f}
'@appwrite.io/console@https://pkg.pr.new/appwrite-labs/cloud/@appwrite.io/console@8836b0c':
resolution: {tarball: https://pkg.pr.new/appwrite-labs/cloud/@appwrite.io/console@8836b0c}
version: 1.9.0
'@appwrite.io/pink-icons-svelte@2.0.0-RC.1':
@@ -2544,8 +2544,8 @@ packages:
loupe@3.1.3:
resolution: {integrity: sha512-kkIp7XSkP78ZxJEsSxW3712C6teJVoeHHwgo9zJ380de7IYyJ2ISlxojcH2pC5OFLewESmnRi/+XCDIEEVyoug==}
loupe@3.1.4:
resolution: {integrity: sha512-wJzkKwJrheKtknCOKNEtDK4iqg/MxmZheEMtSTYvnzRdEYaZzmgH976nenp8WdJRdx5Vc1X/9MO0Oszl6ezeXg==}
loupe@3.2.0:
resolution: {integrity: sha512-2NCfZcT5VGVNX9mSZIxLRkEAegDGBpuQZBy13desuHeVORmBDyAET4TkJr4SjqQy3A8JDofMN6LpkK8Xcm/dlw==}
lru-cache@10.4.3:
resolution: {integrity: sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==}
@@ -3646,7 +3646,7 @@ snapshots:
'@analytics/type-utils@0.6.2': {}
'@appwrite.io/console@https://pkg.pr.new/appwrite-labs/cloud/@appwrite.io/console@935b30f': {}
'@appwrite.io/console@https://pkg.pr.new/appwrite-labs/cloud/@appwrite.io/console@8836b0c': {}
'@appwrite.io/pink-icons-svelte@2.0.0-RC.1(svelte@5.25.3)':
dependencies:
@@ -5037,7 +5037,7 @@ snapshots:
'@vitest/utils@3.2.4':
dependencies:
'@vitest/pretty-format': 3.2.4
loupe: 3.1.4
loupe: 3.2.0
tinyrainbow: 2.0.0
'@vue/compiler-core@3.5.13':
@@ -6177,7 +6177,7 @@ snapshots:
loupe@3.1.3: {}
loupe@3.1.4: {}
loupe@3.2.0: {}
lru-cache@10.4.3: {}
+16 -16
View File
@@ -148,9 +148,9 @@ export enum Click {
ConnectRepositoryClick = 'click_connect_repository',
CreditsRedeemClick = 'click_credits_redeem',
CloudSignupClick = 'click_cloud_signup',
DatabaseColumnDelete = 'click_column_delete',
DatabaseAttributeDelete = 'click_attribute_delete',
DatabaseIndexDelete = 'click_index_delete',
DatabaseTableDelete = 'click_table_delete',
DatabaseCollectionDelete = 'click_collection_delete',
DatabaseDatabaseDelete = 'click_database_delete',
DatabaseImportCsv = 'click_database_import_csv',
DomainCreateClick = 'click_domain_create',
@@ -273,22 +273,22 @@ export enum Submit {
DatabaseDelete = 'submit_database_delete',
DatabaseUpdateName = 'submit_database_update_name',
DatabaseImportCsv = 'submit_database_import_csv',
ColumnCreate = 'submit_column_create',
ColumnUpdate = 'submit_column_update',
ColumnDelete = 'submit_column_delete',
RowCreate = 'submit_row_create',
RowDelete = 'submit_row_delete',
RowUpdate = 'submit_row_update',
RowUpdatePermissions = 'submit_row_update_permissions',
AttributeCreate = 'submit_attribute_create',
AttributeUpdate = 'submit_attribute_update',
AttributeDelete = 'submit_attribute_delete',
DocumentCreate = 'submit_document_create',
DocumentDelete = 'submit_document_delete',
DocumentUpdate = 'submit_document_update',
DocumentUpdatePermissions = 'submit_document_update_permissions',
IndexCreate = 'submit_index_create',
IndexDelete = 'submit_index_delete',
TableCreate = 'submit_row_create',
TableDelete = 'submit_row_delete',
TableUpdateName = 'submit_row_update_name',
TableUpdatePermissions = 'submit_row_update_permissions',
TableUpdateSecurity = 'submit_row_update_security',
TableUpdateEnabled = 'submit_row_update_enabled',
TableUpdateDisplayNames = 'submit_row_update_display_names',
CollectionCreate = 'submit_collection_create',
CollectionDelete = 'submit_collection_delete',
CollectionUpdateName = 'submit_collection_update_name',
CollectionUpdatePermissions = 'submit_collection_update_permissions',
CollectionUpdateSecurity = 'submit_collection_update_security',
CollectionUpdateEnabled = 'submit_collection_update_enabled',
CollectionUpdateDisplayNames = 'submit_collection_update_display_names',
FunctionCreate = 'submit_function_create',
FunctionDelete = 'submit_function_delete',
FunctionUpdateName = 'submit_function_update_name',
+3 -3
View File
@@ -28,10 +28,10 @@ const groups = [
'integrations',
'migrations',
'users',
'tables',
'columns',
'collections',
'attributes',
'indexes',
'rows',
'documents',
'teams',
'security',
'buckets',
+1 -1
View File
@@ -27,7 +27,7 @@
const examples = [
'How to add platform in the console?',
'How can I manage users, permissions, and access control in Appwrite?',
'How can I set up database tables and rows in Appwrite?',
'How can I set up database collections and documents in Appwrite?',
'How do I configure and manage server-side functions in Appwrite?',
'How to add custom domain in the console?'
];
@@ -1,9 +1,9 @@
<script lang="ts">
import { initSearcher } from '../commands';
import { tablesSearcher } from '../searchers';
import { collectionsSearcher } from '../searchers';
import Template from './template.svelte';
const { search, results } = initSearcher(tablesSearcher);
const { search, results } = initSearcher(collectionsSearcher);
</script>
<Template options={$results} bind:search={$search} />
@@ -1,16 +1,16 @@
<script lang="ts">
import { initCreateColumn } from '$routes/(console)/project-[region]-[project]/databases/database-[database]/table-[table]/+layout.svelte';
import { columnOptions } from '$routes/(console)/project-[region]-[project]/databases/database-[database]/table-[table]/columns/store';
import { initCreateAttribute } from '$routes/(console)/project-[region]-[project]/databases/database-[database]/collection-[collection]/+layout.svelte';
import { attributeOptions } from '$routes/(console)/project-[region]-[project]/databases/database-[database]/collection-[collection]/attributes/store';
import Template from './template.svelte';
let search = '';
let options = columnOptions.map((option) => {
let options = attributeOptions.map((option) => {
return {
label: option.name,
icon: option.icon,
callback() {
initCreateColumn(option.name);
initCreateAttribute(option.name);
}
};
});
+8 -8
View File
@@ -37,16 +37,16 @@ export const DatabasesPanel: SubPanel = {
component: Databases
};
import Tables from './tables.svelte';
export const TablesPanel: SubPanel = {
name: 'Tables',
component: Tables
import Collections from './collections.svelte';
export const CollectionsPanel: SubPanel = {
name: 'Collections',
component: Collections
};
import CreateColumn from './createColumn.svelte';
export const CreateColumnPanel: SubPanel = {
name: 'Create Column',
component: CreateColumn
import CreateAttribute from './createAttribute.svelte';
export const CreateAttributePanel: SubPanel = {
name: 'Create Attribute',
component: CreateAttribute
};
import Users from './users.svelte';
@@ -0,0 +1,29 @@
import { goto } from '$app/navigation';
import { database } from '$routes/(console)/project-[region]-[project]/databases/database-[database]/store';
import { get } from 'svelte/store';
import type { Searcher } from '../commands';
import { sdk } from '$lib/stores/sdk';
import { base } from '$app/paths';
import { page } from '$app/state';
export const collectionsSearcher = (async (query: string) => {
const databaseId = get(database).$id;
const { collections } = await sdk
.forProject(page.params.region, page.params.project)
.databases.listCollections(databaseId);
return collections
.filter((col) => col.name.toLowerCase().includes(query.toLowerCase()))
.map(
(col) =>
({
group: 'collections',
label: col.name,
callback: () => {
goto(
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${databaseId}/collection-${col.$id}`
);
}
}) as const
);
}) satisfies Searcher;
+1 -1
View File
@@ -1,7 +1,7 @@
export * from './databases';
export * from './users';
export * from './organizations';
export * from './tables';
export * from './collections';
export * from './projects';
export * from './teams';
export * from './functions';
-27
View File
@@ -1,27 +0,0 @@
import { goto } from '$app/navigation';
import type { Searcher } from '../commands';
import { sdk } from '$lib/stores/sdk';
import { base } from '$app/paths';
import { page } from '$app/state';
export const tablesSearcher = (async (query: string) => {
const databaseId = page.params.database;
const { tables } = await sdk
.forProject(page.params.region, page.params.project)
.tables.list(databaseId);
return tables
.filter((table) => table.name.toLowerCase().includes(query.toLowerCase()))
.map(
(table) =>
({
group: 'tables',
label: table.name,
callback: () => {
goto(
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${databaseId}/table-${table.$id}`
);
}
}) as const
);
}) satisfies Searcher;
+2 -3
View File
@@ -57,7 +57,6 @@
}
function updateOrAddItem(payload: Payload) {
// todo: @itznotabug - might need a change to $table?
const { $id, status, $collection, policyId } = payload;
if ($collection === 'archives' && policyId !== null) {
return;
@@ -118,9 +117,9 @@
}
function backupName(item: BackupArchive | BackupRestoration, key: string) {
const column = key === 'archives' ? '$createdAt' : 'startedAt';
const attribute = key === 'archives' ? '$createdAt' : 'startedAt';
return toLocaleDate(item[column]);
return toLocaleDate(item[attribute]);
}
onMount(() => {
+7 -6
View File
@@ -8,18 +8,19 @@
let {
columns,
isCustomTable = false,
isCustomCollection = false,
allowNoColumns = false,
children
}: {
columns: Writable<Column[]>;
isCustomTable?: boolean;
isCustomCollection?: boolean;
allowNoColumns?: boolean;
children: Snippet<[toggle: () => void, selectedColumnsNumber: number]>;
} = $props();
let maxHeight = $state('none');
let containerRef = $state<HTMLElement>(null);
const collectionId = $derived(page.params.collection);
const calcMaxHeight = () => {
if (containerRef) {
@@ -34,16 +35,16 @@
const saveColumnPreferences = () => {
const shownColumns = $columns.filter((n) => n.hide === true).map((n) => n.id);
if (isCustomTable) {
preferences.setCustomTableColumns(page.params.table, shownColumns);
if (isCustomCollection) {
preferences.setCustomCollectionColumns(collectionId, shownColumns);
} else {
preferences.setColumns(shownColumns);
}
};
onMount(() => {
if (isCustomTable) {
const shownColumns = preferences.getCustomTableColumns(page.params.table);
if (isCustomCollection) {
const shownColumns = preferences.getCustomCollectionColumns(collectionId);
columns.update((n) =>
n.map((column) => {
+22 -18
View File
@@ -13,7 +13,7 @@
type ImportItem = {
status: string;
table?: string;
collection?: string;
};
type ImportItemsMap = Map<string, ImportItem>;
@@ -22,11 +22,15 @@
* Keeps a track of the active and ongoing csv migrations.
*
* The structure is as follows -
* `{ migrationId: { status: status, table: table } }`
* `{ migrationId: { status: status, collection: collection } }`
*/
const importItems: Writable<ImportItemsMap> = writable(new Map());
async function showCompletionNotification(database: string, table: string, payload: Payload) {
async function showCompletionNotification(
database: string,
collection: string,
payload: Payload
) {
const isSuccess = payload.status === 'completed';
const isError = !isSuccess && !!payload.errors;
@@ -44,20 +48,20 @@
const type = isSuccess ? 'success' : 'error';
const message = isError ? errorMessage : 'CSV import finished successfully.';
const url = `${base}/project-${page.params.region}-${page.params.project}/databases/database-${database}/table-${table}`;
const url = `${base}/project-${page.params.region}-${page.params.project}/databases/database-${database}/collection-${collection}`;
addNotification({
type,
message,
isHtml: true,
buttons:
isSuccess && table !== page.params.table
? [{ name: 'View rows', method: () => goto(url) }]
isSuccess && collection !== page.params.collection
? [{ name: 'View documents', method: () => goto(url) }]
: undefined
});
if (isSuccess) {
await invalidate(Dependencies.ROWS);
await invalidate(Dependencies.DOCUMENTS);
}
}
@@ -66,19 +70,19 @@
const status = importData.status;
const resourceId = importData.resourceId ?? '';
const [databaseId, tableId] = resourceId.split(':') ?? [];
const [databaseId, collectionId] = resourceId.split(':') ?? [];
const current = $importItems.get(importData.$id);
let tableName = current?.table ?? null;
let collectionName = current?.collection ?? null;
if (!tableName && tableId) {
if (!collectionName && collectionId) {
try {
const table = await sdk
const collection = await sdk
.forProject(page.params.region, page.params.project)
.tables.get(databaseId, tableId);
tableName = table.name;
.databases.getCollection(databaseId, collectionId);
collectionName = collection.name;
} catch {
tableName = null;
collectionName = null;
}
}
@@ -95,12 +99,12 @@
if (shouldSkip) return items;
const next = new Map(items);
next.set(importData.$id, { status, table: tableName ?? undefined });
next.set(importData.$id, { status, collection: collectionName ?? undefined });
return next;
});
if (status === 'completed' || status === 'failed') {
await showCompletionNotification(databaseId, tableId, importData);
await showCompletionNotification(databaseId, collectionId, importData);
}
}
@@ -168,7 +172,7 @@
<header class="upload-box-header">
<h4 class="upload-box-title">
<Typography.Text variant="m-500">
Importing rows ({$importItems.size})
Importing documents ({$importItems.size})
</Typography.Text>
</h4>
<button
@@ -194,7 +198,7 @@
<div
class="progress-bar-top-line u-flex u-gap-8 u-main-space-between">
<Typography.Text>
{@html text(value.status, value.table)}
{@html text(value.status, value.collection)}
</Typography.Text>
</div>
<div
+27 -24
View File
@@ -26,10 +26,10 @@
...services.flatMap((s) => s.actions.map((a) => a.name)),
...services.flatMap((s) => s.resources.flatMap((r) => r.actions.map((a) => a.name)))
];
const columnNames = [
...services.flatMap((s) => s.actions.flatMap((a) => a.columns ?? [])),
const attributeNames = [
...services.flatMap((s) => s.actions.flatMap((a) => a.attributes ?? [])),
...services.flatMap((s) =>
s.resources.flatMap((r) => r.actions.flatMap((a) => a.columns ?? []))
s.resources.flatMap((r) => r.actions.flatMap((a) => a.attributes ?? []))
)
];
@@ -37,7 +37,7 @@
const isService = (s: string) => serviceNames.includes(s);
const isResource = (s: string) => resourceNames.includes(s);
const isAction = (s: string) => actionNames.includes(s);
const isColumn = (s: string) => columnNames.includes(s);
const isAttribute = (s: string) => attributeNames.includes(s);
const dispatch = createEventDispatcher();
@@ -69,7 +69,7 @@
case 'service': {
selected.resource = null;
selected.action = null;
selected.column = null;
selected.attribute = null;
break;
}
case 'resource': {
@@ -79,25 +79,25 @@
// We need to check if the selected action name is still
// on the available list, and if so, change the action to the
// appropriate one, as it may contain different attributes/columns.
// appropriate one, as it may contain different attributes
const availableAction = availableActions.find(
(a) => a.name === selected.action?.name
);
if (!availableAction) {
selected.action = null;
selected.column = null;
selected.attribute = null;
} else {
selected.action = availableAction;
if (!selected?.action?.columns?.includes(selected.column)) {
selected.column = null;
if (!selected?.action?.attributes?.includes(selected.attribute)) {
selected.attribute = null;
}
}
break;
}
case 'action': {
selected.column = null;
selected.attribute = null;
break;
}
}
@@ -113,13 +113,16 @@
if (isService(field)) {
selected.service = services.find((s) => s.name === field);
} else if (isResource(field)) {
selected.resource = selected.service?.resources.find((r) => r.name === field);
const resource = selected.service?.resources.find((r) => r.name === field);
selected.resource = resource;
} else if (isAction(field)) {
selected.action =
const action =
selected.resource?.actions.find((a) => a.name === field) ||
selected.service?.actions.find((a) => a.name === field);
} else if (isColumn(field)) {
selected.column = selected.action?.columns?.find((a) => a === field);
selected.action = action;
} else if (isAttribute(field)) {
const attribute = selected.action?.attributes?.find((a) => a === field);
selected.attribute = attribute;
}
}
}
@@ -140,7 +143,7 @@
const secondToLastField = at(fields, index - 2);
if (index === 0 || isService(currField)) return 'service';
if (isColumn(currField) || isAction(prevField)) return 'attribute';
if (isAttribute(currField) || isAction(prevField)) return 'attribute';
if (isAction(currField)) return 'action';
if (isResource(currField)) return 'resource';
if (isService(prevField) || isResource(prevField) || index === 1) {
@@ -179,7 +182,7 @@
service: null as EventService | null,
resource: null as EventResource | null,
action: null as EventAction | null,
column: null as string | null
attribute: null as string | null
};
let helper: string = null;
let customInput: string = null;
@@ -195,7 +198,7 @@
services: services,
resources: selected.service?.resources || [],
actions: (selected.resource ? selected.resource?.actions : selected.service?.actions) || [],
columns: selected.action?.columns || []
attributes: selected.action?.attributes || []
};
$: eventString = (function createEventString(): Array<{ value: string; description: string }> {
@@ -209,8 +212,8 @@
if (selected.service) {
fields.push(selected.service.name, '*');
}
if (selected.resource?.name === 'rows') {
fields.push('tables', '*');
if (selected.resource?.name === 'documents') {
fields.push('collections', '*');
}
if (selected.resource) {
fields.push(selected.resource.name, '*');
@@ -218,8 +221,8 @@
if (selected.action) {
fields.push(selected.action.name);
}
if (selected.column) {
fields.push(selected.column);
if (selected.attribute) {
fields.push(selected.attribute);
}
}
@@ -287,14 +290,14 @@
</Layout.Stack>
{/if}
{#if !empty(available.columns)}
{#if !empty(available.attributes)}
<Layout.Stack gap="s">
<Typography.Text variant="m-500">Choose an attribute (optional)</Typography.Text>
<Layout.Stack gap="s" wrap="wrap" direction="row">
{#each available.columns as attribute}
{#each available.attributes as attribute}
<Pill
disabled={showInput}
selected={selected.column === attribute}
selected={selected.attribute === attribute}
button
on:click={() => select('attribute', attribute)}>
{attribute}
+2 -2
View File
@@ -499,7 +499,7 @@
size="s"
event="empty_documentation"
href="https://appwrite.io/docs/products/storage/upload-download"
ariaLabel="upload download"
ariaLabel="create document"
>Documentation</Button>
<Button
secondary
@@ -526,7 +526,7 @@
size="s"
event="empty_documentation"
href="https://appwrite.io/docs/products/storage/buckets"
ariaLabel="create buckets">Documentation</Button>
ariaLabel="create document">Documentation</Button>
<Button
secondary
+10 -10
View File
@@ -12,8 +12,8 @@ export type TagValue = {
};
export type Operator = {
toTag: (column: string, input?: string | number | string[], type?: string) => TagValue;
toQuery: (column: string, input?: string | number | string[]) => string;
toTag: (attribute: string, input?: string | number | string[], type?: string) => TagValue;
toQuery: (attribute: string, input?: string | number | string[]) => string;
types: ColumnType[];
hideInput?: boolean;
};
@@ -134,7 +134,7 @@ export enum ValidTypes {
const operatorsDefault = new Map<
ValidOperators,
{
query: (col: string, input: string | number | string[]) => string;
query: (attr: string, input: string | number | string[]) => string;
types: ColumnType[];
hideInput?: boolean;
}
@@ -249,8 +249,8 @@ export function generateDefaultOperators() {
operatorsDefault.forEach((operator, operatorName) => {
operators[operatorName] = {
toQuery: operator.query,
toTag: (column, input = null, type = null) => {
return generateTag(column, operatorName, input, type);
toTag: (attribute, input = null, type = null) => {
return generateTag(attribute, operatorName, input, type);
},
types: operator.types,
hideInput: operator.hideInput
@@ -259,24 +259,24 @@ export function generateDefaultOperators() {
return operators;
}
export function generateTag(column: string, operatorName: string, input = null, type = null) {
export function generateTag(attribute: string, operatorName: string, input = null, type = null) {
if (input === null) {
return {
value: '',
tag: `**${column}** ${operatorName}`
tag: `**${attribute}** ${operatorName}`
};
} else if (Array.isArray(input) && input.length > 2) {
return {
value: input,
tag: `**${column}** ${operatorName} **${formatArray(input)}** `
tag: `**${attribute}** ${operatorName} **${formatArray(input)}** `
};
} else if (type === ValidTypes.Datetime) {
return {
value: input,
tag: `**${column}** ${operatorName} **${toLocaleDateTime(input.toString())}**`
tag: `**${attribute}** ${operatorName} **${toLocaleDateTime(input.toString())}**`
};
} else {
return { value: input, tag: `**${column}** ${operatorName} **${input}**` };
return { value: input, tag: `**${attribute}** ${operatorName} **${input}**` };
}
}
+2 -2
View File
@@ -9,14 +9,14 @@
export let columns: Writable<Column[]>;
export let view: View;
export let isCustomTable = false;
export let isCustomCollection = false;
export let hideView = false;
export let hideColumns = false;
export let allowNoColumns = false;
</script>
{#if !hideColumns && view === View.Table}
<ColumnSelector {columns} {isCustomTable} {allowNoColumns}>
<ColumnSelector {columns} {isCustomCollection} {allowNoColumns}>
{#snippet children(toggle, selectedColumnsNumber)}
<Button.Button
size="s"
+9 -52
View File
@@ -38,9 +38,9 @@ export enum Dependencies {
MEMBERSHIPS = 'dependency:memberships',
DATABASE = 'dependency:database',
DATABASES = 'dependency:databases',
TABLE = 'dependency:table',
ROW = 'dependency:row',
ROWS = 'dependency:rows',
COLLECTION = 'dependency:collection',
DOCUMENT = 'dependency:document',
DOCUMENTS = 'dependency:documents',
BUCKET = 'dependency:bucket',
FILE = 'dependency:file',
FILE_TOKENS = 'dependency:file_tokens',
@@ -64,7 +64,7 @@ export enum Dependencies {
WEBHOOK = 'dependency:webhook',
WEBHOOKS = 'dependency:webhooks',
MIGRATIONS = 'dependency:migrations',
TABLES = 'dependency:tables',
COLLECTIONS = 'dependency:collections',
BACKUPS = 'dependency:backups',
RUNTIMES = 'dependency:runtimes',
CONSOLE_VARIABLES = 'dependency:console_variables',
@@ -92,8 +92,6 @@ export const defaultScopes: string[] = [
'teams.write',
'documents.read',
'documents.write',
'rows.read',
'rows.write',
'files.read',
'files.write',
'projects.read',
@@ -113,8 +111,6 @@ export const defaultScopes: string[] = [
'databases.write',
'collections.read',
'collections.write',
'tables.read',
'tables.write',
'buckets.read',
'buckets.write',
'functions.read',
@@ -145,9 +141,6 @@ export const defaultScopes: string[] = [
export const defaultRoles: string[] = ['owner'];
// TODO: remove old terminology scopes.
// these are kept for backwards compatibility with keys and events that already exists.
// for the new ones, we use the new terminology.
export const scopes: {
scope: string;
description: string;
@@ -208,18 +201,6 @@ export const scopes: {
category: 'Database',
icon: 'database'
},
{
scope: 'tables.read',
description: "Access to read your project's database tables",
category: 'Database',
icon: 'database'
},
{
scope: 'tables.write',
description: "Access to create, update, and delete your project's database tables",
category: 'Database',
icon: 'database'
},
{
scope: 'attributes.read',
description: "Access to read your project's database collection's attributes",
@@ -233,18 +214,6 @@ export const scopes: {
category: 'Database',
icon: 'database'
},
{
scope: 'columns.read',
description: "Access to read your project's database table's columns",
category: 'Database',
icon: 'database'
},
{
scope: 'columns.write',
description: "Access to create, update, and delete your project's database table's columns",
category: 'Database',
icon: 'database'
},
{
scope: 'indexes.read',
description: "Access to read your project's database collection's indexes",
@@ -270,18 +239,6 @@ export const scopes: {
category: 'Database',
icon: 'database'
},
{
scope: 'rows.read',
description: "Access to read your project's database rows",
category: 'Database',
icon: 'database'
},
{
scope: 'rows.write',
description: "Access to create, update, and delete your project's database rows",
category: 'Database',
icon: 'database'
},
{
scope: 'files.read',
description: "Access to read your project's storage files and preview images",
@@ -473,7 +430,7 @@ export type EventResource = {
export type EventAction = {
name: string;
columns?: string[];
attributes?: string[];
};
export const eventServices: Array<EventService> = [
@@ -491,11 +448,11 @@ export const eventServices: Array<EventService> = [
name: 'databases',
resources: [
{
name: 'tables',
name: 'collections',
actions: [{ name: 'create' }, { name: 'update' }, { name: 'delete' }]
},
{
name: 'rows',
name: 'documents',
actions: [{ name: 'create' }, { name: 'update' }, { name: 'delete' }]
}
],
@@ -522,7 +479,7 @@ export const eventServices: Array<EventService> = [
name: 'memberships',
actions: [
{ name: 'create' },
{ name: 'update', columns: ['status'] },
{ name: 'update', attributes: ['status'] },
{ name: 'delete' }
]
}
@@ -538,7 +495,7 @@ export const eventServices: Array<EventService> = [
],
actions: [
{ name: 'create' },
{ name: 'update', columns: ['email', 'name', 'password', 'status', 'prefs'] },
{ name: 'update', attributes: ['email', 'name', 'password', 'status', 'prefs'] },
{ name: 'delete' }
]
},
-3
View File
@@ -35,7 +35,6 @@
let showDropdown = false;
// TODO: remove the default billing limits when backend is updated with billing code
// TODO: @itznotabug - check with @abnegate, what do we do here? this is billing!
const { bandwidth, documents, storage, users, executions } = $organization?.billingLimits ?? {
bandwidth: 1,
documents: 1,
@@ -43,8 +42,6 @@
users: 1,
executions: 1
};
// TODO: @itznotabug - check with @abnegate, what do we do here? this is billing!
const limitedServices = [
{ name: 'bandwidth', value: bandwidth },
{ name: 'documents', value: documents },
+3 -3
View File
@@ -13,14 +13,14 @@
view = $bindable(),
columns,
hideColumns = false,
isCustomTable = false
isCustomCollection = false
}: {
show?: boolean;
hideView?: boolean;
view?: View;
columns?: Writable<Column[]>;
hideColumns?: boolean;
isCustomTable?: boolean;
isCustomCollection?: boolean;
} = $props();
</script>
@@ -35,7 +35,7 @@
{#if !hideColumns && $columns?.length}
<Layout.Stack gap="xs">
<Typography.Text>Columns</Typography.Text>
<ColumnSelector {columns} {isCustomTable}>
<ColumnSelector {columns} {isCustomCollection}>
{#snippet children(toggle, selectedColumnsNumber)}
<Button.Button
size="s"
+8 -2
View File
@@ -8,7 +8,7 @@
export let title: string;
export let columns: Writable<Column[]>;
export let view: View;
export let isCustomTable = false;
export let isCustomCollection = false;
export let hideView = false;
export let hideColumns = false;
export let allowNoColumns = false;
@@ -17,7 +17,13 @@
<header class="grid-header">
<Typography.Title size="m">{title}</Typography.Title>
<div class="u-flex u-gap-16 u-contents-mobile">
<ViewSelector {view} {columns} {isCustomTable} {hideView} {hideColumns} {allowNoColumns} />
<ViewSelector
{view}
{columns}
{isCustomCollection}
{hideView}
{hideColumns}
{allowNoColumns} />
<div class="grid-header-col-2">
<slot />
</div>
-3
View File
@@ -366,8 +366,6 @@ export async function checkForUsageLimit(org: Organization) {
return;
}
}
// TODO: @itznotabug - check with @abnegate, what do we do here? this is billing!
const { bandwidth, documents, executions, storage, users } = org?.billingLimits ?? {};
const resources = [
{ value: bandwidth, name: 'bandwidth' },
@@ -380,7 +378,6 @@ export async function checkForUsageLimit(org: Organization) {
const members = org.total;
const plan = get(currentPlan);
const membersOverflow =
// `plan` can be null on `onboarding/create-organization` route.
// nested null checks needed: GitHub Education plan have empty addons.
members > plan?.addons?.seats?.limit
? members - (plan?.addons?.seats?.limit || members)
+12 -13
View File
@@ -9,7 +9,7 @@ const initialFormData = {
},
databases: {
root: false,
rows: false
documents: false
},
functions: {
root: false,
@@ -45,19 +45,18 @@ export const ResourcesFriendly = {
'environment-variable': { singular: 'Environment Variable', plural: 'Environment Variables' },
deployment: { singular: 'Deployment', plural: 'Deployments' },
database: { singular: 'Database', plural: 'Databases' },
table: { singular: 'Table', plural: 'Tables' },
collection: { singular: 'Collection', plural: 'Collections' },
index: { singular: 'Index', plural: 'Indexes' },
column: { singular: 'Column', plural: 'Columns' },
row: { singular: 'Row', plural: 'Rows' }
attribute: { singular: 'Attribute', plural: 'Attributes' },
document: { singular: 'Document', plural: 'Documents' }
};
const resources = Object.keys(ResourcesFriendly);
type Resource = (typeof resources)[number];
// @todo: @itznotabug - check if other resources are correct and work fine!
export const providerResources: Record<Provider, Resource[]> = {
appwrite: [...resources], // new terminology, others are ok?
appwrite: [...resources],
supabase: [
'user',
'database',
@@ -92,12 +91,12 @@ export const migrationFormToResources = (
}
if (formData.databases.root) {
addResource('database');
addResource('table');
addResource('column');
addResource('columnIndex');
addResource('collection');
addResource('attribute');
addResource('index');
}
if (formData.databases.rows) {
addResource('row');
if (formData.databases.documents) {
addResource('document');
}
if (formData.functions.root) {
addResource('function');
@@ -151,8 +150,8 @@ export const resourcesToMigrationForm = (
if (resources.includes('database')) {
formData.databases.root = true;
}
if (includesAll(resources, ['table', 'column', 'row'])) {
formData.databases.rows = true;
if (includesAll(resources, ['collection', 'attribute', 'document'])) {
formData.databases.documents = true;
}
if (resources.includes('function') && isVersionAtLeast(version, '1.4.0')) {
formData.functions.root = true;
-1
View File
@@ -42,7 +42,6 @@ export type OrganizationList = {
total: number;
};
// TODO: @itznotabug - check with @abnegate, what do we do here? this is billing!
export type BillingLimits = {
bandwidth: number;
documents: number;
+10 -15
View File
@@ -20,13 +20,9 @@ type TeamPreferences = {
type PreferencesStore = {
[key: string]: Preferences;
// kept for backwards compatibility
collections?: {
[key: string]: Preferences['columns'];
};
tables?: {
[key: string]: Preferences['columns'];
};
displayNames?: {
[key: string]: TeamPreferences['names'];
};
@@ -110,8 +106,8 @@ function createPreferences() {
}
);
},
getCustomTableColumns: (tableId: string): Preferences['columns'] => {
return preferences?.tables?.[tableId] ?? preferences?.collections?.[tableId] ?? [];
getCustomCollectionColumns: (collectionId: string): Preferences['columns'] => {
return preferences?.collections?.[collectionId] ?? [];
},
setLimit: (limit: Preferences['limit']) =>
updateAndSync((n) => {
@@ -152,15 +148,14 @@ function createPreferences() {
return n;
}),
setCustomTableColumns: (tableId: string, columns: Preferences['columns']) =>
setCustomCollectionColumns: (collectionId: string, columns: Preferences['columns']) =>
updateAndSync((n) => {
n ??= {};
n.collections ??= {};
n.tables ??= {};
if (!n?.collections?.[collectionId]) {
n ??= {};
n.collections ??= {};
}
n.tables[tableId] = Array.from(new Set(columns));
// let's not double save
// n.collections[tableId] = Array.from(new Set(columns));
n.collections[collectionId] = Array.from(new Set(columns));
return n;
}),
loadTeamPrefs: async (id: string) => {
@@ -177,7 +172,7 @@ function createPreferences() {
},
setDisplayNames: async (
orgId: string,
tableId: string,
collectionId: string,
names: TeamPreferences['names']
) => {
let teamPrefs: Models.Preferences;
@@ -188,7 +183,7 @@ function createPreferences() {
}
teamPrefs = n;
n.displayNames[tableId] = names;
n.displayNames[collectionId] = names;
return n;
});
+4 -6
View File
@@ -19,15 +19,13 @@ export const canWritePlatforms = derived(scopes, ($scopes) => $scopes.includes('
export const canWriteTargets = derived(scopes, ($scopes) => $scopes.includes('targets.write'));
export const canWriteUsers = derived(scopes, ($scopes) => $scopes.includes('users.write'));
export const canWriteTeams = derived(scopes, ($scopes) => $scopes.includes('teams.write'));
export const canWriteTables = derived(scopes, ($scopes) => {
return $scopes.includes('collections.write') || $scopes.includes('tables.write');
});
export const canWriteCollections = derived(scopes, ($scopes) =>
$scopes.includes('collections.write')
);
export const canWriteSites = derived(scopes, ($scopes) => $scopes.includes('sites.write'));
export const canWriteDomains = derived(scopes, ($scopes) => $scopes.includes('domains.write')); //TODO: check if correct
export const canWriteRows = derived(scopes, ($scopes) => {
return $scopes.includes('documents.write') || $scopes.includes('rows.write');
});
export const canWriteDocuments = derived(scopes, ($scopes) => $scopes.includes('documents.write'));
export const canWriteExecutions = derived(scopes, ($scopes) =>
$scopes.includes('executions.write')
);
+1 -3
View File
@@ -21,7 +21,6 @@ import {
Vcs,
Sites,
Tokens,
Tables,
Domains
} from '@appwrite.io/console';
import { Billing } from '../sdk/billing';
@@ -123,8 +122,7 @@ const sdkForProject = {
vcs: new Vcs(clientProject),
proxy: new Proxy(clientProject),
migrations: new Migrations(clientProject),
sites: new Sites(clientProject),
tables: new Tables(clientProject)
sites: new Sites(clientProject)
};
export const realtime = {
@@ -7,7 +7,6 @@ import type { PageLoad } from './$types';
export const load: PageLoad = async ({ url, params, route, depends }) => {
depends(Dependencies.ORGANIZATION);
depends(Dependencies.MEMBERS);
const page = getPage(url);
const search = getSearch(url);
const limit = getLimit(url, route, PAGE_LIMIT);
@@ -6,7 +6,6 @@
import { capitalize } from '$lib/helpers/string';
import { currentPlan } from '$lib/stores/organization';
import { wizard } from '$lib/stores/wizard';
function getResource(id: string) {
id = id.replace('/(console)/project-[region]-[project]/', '');
let parts = id.split('/');
@@ -40,7 +39,6 @@
>{'status' in page.error
? page.error.status || 'Invalid Argument'
: 'Invalid Argument'}</Typography.Title>
<Typography.Title>{page.error.message}</Typography.Title>
<p class="body-text-2 u-bold u-margin-block-start-4">{page.error.message}</p>
{/if}
</Container>
@@ -82,7 +82,6 @@
const database = await sdk
.forProject(page.params.region, page.params.project)
.databases.create(databaseId, name);
await createPolicies(databaseId);
showCreate = false;
@@ -8,13 +8,13 @@
registerSearchers,
updateCommandGroupRanks
} from '$lib/commandCenter';
import { tablesSearcher } from '$lib/commandCenter/searchers';
import { collectionsSearcher } from '$lib/commandCenter/searchers';
import { Dependencies } from '$lib/constants';
import type { Models } from '@appwrite.io/console';
import CreateTable from './createTable.svelte';
import CreateCollection from './createCollection.svelte';
import { showCreate } from './store';
import { TablesPanel } from '$lib/commandCenter/panels';
import { canWriteTables, canWriteDatabases } from '$lib/stores/roles';
import { CollectionsPanel } from '$lib/commandCenter/panels';
import { canWriteCollections, canWriteDatabases } from '$lib/stores/roles';
import { showCreateBackup, showCreatePolicy } from './backups/store';
import { IconPlus } from '@appwrite.io/pink-icons-svelte';
import { currentPlan } from '$lib/stores/organization';
@@ -23,17 +23,17 @@
const project = page.params.project;
const databaseId = page.params.database;
async function handleCreate(event: CustomEvent<Models.Table>) {
async function handleCreate(event: CustomEvent<Models.Collection>) {
$showCreate = false;
await invalidate(Dependencies.DATABASE);
await goto(
`${base}/project-${page.params.region}-${project}/databases/database-${databaseId}/table-${event.detail.$id}`
`${base}/project-${page.params.region}-${project}/databases/database-${databaseId}/collection-${event.detail.$id}`
);
}
$: $registerCommands([
{
label: 'Create table',
label: 'Create collection',
callback() {
$showCreate = true;
if (!page.url.pathname.endsWith(databaseId)) {
@@ -43,7 +43,7 @@
}
},
keys: page.url.pathname.endsWith(databaseId) ? ['c'] : ['c', 'c'],
disabled: page.url.pathname.includes('table-') || !$canWriteTables,
disabled: page.url.pathname.includes('collection-') || !$canWriteCollections,
group: 'databases',
icon: IconPlus
},
@@ -80,14 +80,14 @@
disabled: !isCloud || !$currentPlan.backupsEnabled
},
{
label: 'Go to tables',
label: 'Go to collections',
callback() {
goto(
`${base}/project-${page.params.region}-${project}/databases/database-${databaseId}`
);
},
disabled:
page.url.pathname.endsWith(databaseId) || page.url.pathname.includes('table-'),
page.url.pathname.endsWith(databaseId) || page.url.pathname.includes('collection-'),
keys: ['g', 'c'],
group: 'databases'
},
@@ -98,7 +98,8 @@
`${base}/project-${page.params.region}-${project}/databases/database-${databaseId}/usage`
);
},
disabled: page.url.pathname.includes('/usage') || page.url.pathname.includes('table-'),
disabled:
page.url.pathname.includes('/usage') || page.url.pathname.includes('collection-'),
keys: ['g', 'u'],
group: 'databases'
},
@@ -110,7 +111,7 @@
);
},
disabled:
page.url.pathname.includes('/backups') || page.url.pathname.includes('table-'),
page.url.pathname.includes('/backups') || page.url.pathname.includes('collection-'),
keys: ['g', 'b'],
group: 'databases'
},
@@ -123,24 +124,24 @@
},
disabled:
page.url.pathname.includes('/settings') ||
page.url.pathname.includes('table-') ||
page.url.pathname.includes('collection-') ||
!$canWriteDatabases,
keys: ['g', 's'],
group: 'databases'
},
{
label: 'Find tables',
label: 'Find collections',
callback: () => {
addSubPanel(TablesPanel);
addSubPanel(CollectionsPanel);
},
group: 'databases',
rank: -1
}
]);
$registerSearchers(tablesSearcher);
$registerSearchers(collectionsSearcher);
$: $updateCommandGroupRanks({ tables: 10 });
$: $updateCommandGroupRanks({ collections: 10 });
</script>
<svelte:head>
@@ -149,4 +150,4 @@
<slot />
<CreateTable bind:showCreate={$showCreate} on:created={handleCreate} />
<CreateCollection bind:showCreate={$showCreate} on:created={handleCreate} />
@@ -2,11 +2,11 @@
import { Empty, PaginationWithLimit } from '$lib/components';
import { Button } from '$lib/elements/forms';
import { Container, ResponsiveContainerHeader } from '$lib/layout';
import { tableViewColumns, showCreate } from './store';
import { columns, showCreate } from './store';
import Table from './table.svelte';
import Grid from './grid.svelte';
import type { PageData } from './$types';
import { canWriteTables } from '$lib/stores/roles';
import { canWriteCollections } from '$lib/stores/roles';
import { Icon } from '@appwrite.io/pink-svelte';
import { IconPlus } from '@appwrite.io/pink-icons-svelte';
@@ -16,18 +16,18 @@
<Container>
<ResponsiveContainerHeader
bind:view={data.view}
columns={tableViewColumns}
{columns}
hasSearch
searchPlaceholder="Search by name or ID">
{#if $canWriteTables}
<Button on:click={() => ($showCreate = true)} event="create_table">
{#if $canWriteCollections}
<Button on:click={() => ($showCreate = true)} event="create_collection">
<Icon icon={IconPlus} slot="start" size="s" />
Create table
Create collection
</Button>
{/if}
</ResponsiveContainerHeader>
{#if data.tables.total}
{#if data.collections.total}
{#if data.view === 'grid'}
<Grid {data} bind:showCreate={$showCreate} />
{:else}
@@ -35,16 +35,16 @@
{/if}
<PaginationWithLimit
name="Tables"
name="Collections"
limit={data.limit}
offset={data.offset}
total={data.tables.total} />
total={data.collections.total} />
{:else}
<Empty
single
allowCreate={$canWriteTables}
href="https://appwrite.io/docs/products/databases/tables"
target="table"
allowCreate={$canWriteCollections}
href="https://appwrite.io/docs/products/databases/collections"
target="collection"
on:click={() => ($showCreate = true)} />
{/if}
</Container>
@@ -5,16 +5,15 @@ import type { PageLoad } from './$types';
import { CARD_LIMIT, Dependencies } from '$lib/constants';
export const load: PageLoad = async ({ params, url, route, depends }) => {
depends(Dependencies.TABLES);
depends(Dependencies.COLLECTIONS);
const page = getPage(url);
const search = getSearch(url);
const limit = getLimit(url, route, CARD_LIMIT);
const view = getView(url, route, View.Grid);
const offset = pageToOffset(page, limit);
const tables = await sdk
const collections = await sdk
.forProject(params.region, params.project)
.tables.list(
.databases.listCollections(
params.database,
[Query.limit(limit), Query.offset(offset), Query.orderDesc('')],
search || undefined
@@ -25,6 +24,6 @@ export const load: PageLoad = async ({ params, url, route, depends }) => {
limit,
search,
view,
tables
collections
};
};
@@ -1,41 +0,0 @@
import { base } from '$app/paths';
import type { PageLoad } from './$types';
import { redirect } from '@sveltejs/kit';
import { AppwriteException } from '@appwrite.io/console';
const LEGACY_ROUTE_MAPPINGS = [
{ pattern: /^collection-([^/]+)/, replacement: 'table-$1' },
{ pattern: /^document-([^/]+)/, replacement: 'row-$1' },
{ pattern: /^attribute-([^/]+)/, replacement: 'column-$1' }
] as const;
function isLegacyRoute(segments: string[]): boolean {
return segments.some((segment) =>
LEGACY_ROUTE_MAPPINGS.some((mapping) => mapping.pattern.test(segment))
);
}
function rewriteLegacySegments(segments: string[]): string[] {
return segments.map((segment) => {
for (const mapping of LEGACY_ROUTE_MAPPINGS) {
if (mapping.pattern.test(segment)) {
return segment.replace(mapping.pattern, mapping.replacement);
}
}
return segment;
});
}
export const load: PageLoad = async ({ params, url }) => {
const restSegments = params.rest ? params.rest.split('/').filter(Boolean) : [];
const baseUrl = `${base}/project-${params.region}-${params.project}/databases/database-${params.database}`;
if (isLegacyRoute(restSegments)) {
const rewrittenSegments = rewriteLegacySegments(restSegments);
const newPath = `${baseUrl}/${rewrittenSegments.join('/')}`;
redirect(308, newPath + url.search);
}
throw new AppwriteException('Not Found', 404);
};
@@ -1,13 +1,10 @@
<script lang="ts" context="module">
import { writable } from 'svelte/store';
import type { Option } from './columns/store';
const createAttributeArgs = writable({
showCreate: false,
selectedOption: null as Option['name'] | null
});
export const initCreateColumn = (option: Option['name']) => {
export const initCreateAttribute = (option: Option['name']) => {
createAttributeArgs.set({ showCreate: true, selectedOption: option });
};
@@ -22,16 +19,18 @@
import { Dependencies } from '$lib/constants';
import { realtime } from '$lib/stores/sdk';
import { onMount } from 'svelte';
import { table } from './store';
import { collection } from './store';
import { addSubPanel, registerCommands, updateCommandGroupRanks } from '$lib/commandCenter';
import CreateAttribute from './createColumn.svelte';
import { CreateColumnPanel } from '$lib/commandCenter/panels';
import CreateAttribute from './createAttribute.svelte';
import { writable } from 'svelte/store';
import type { Option } from './attributes/store';
import { CreateAttributePanel } from '$lib/commandCenter/panels';
import { database } from '../store';
import { project } from '$routes/(console)/project-[region]-[project]/store';
import { page } from '$app/state';
import CreateIndex from './indexes/createIndex.svelte';
import { base } from '$app/paths';
import { canWriteTables } from '$lib/stores/roles';
import { canWriteCollections } from '$lib/stores/roles';
import { IconEye, IconLockClosed, IconPlus, IconPuzzle } from '@appwrite.io/pink-icons-svelte';
onMount(() => {
@@ -39,143 +38,142 @@
.forProject(page.params.region, page.params.project)
.subscribe(['project', 'console'], (response) => {
if (
response.events.includes('databases.*.tables.*.columns.*') ||
response.events.includes('databases.*.tables.*.indexes.*')
response.events.includes('databases.*.collections.*.attributes.*') ||
response.events.includes('databases.*.collections.*.indexes.*')
) {
invalidate(Dependencies.TABLE);
invalidate(Dependencies.COLLECTION);
}
});
});
// TODO: use route ids instead of pathname
$: $registerCommands([
{
label: 'Create row',
keys: page.url.pathname.endsWith($table.$id) ? ['t'] : ['t', 'd'],
label: 'Create document',
keys: page.url.pathname.endsWith($collection.$id) ? ['c'] : ['c', 'd'],
callback() {
goto(
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${$database?.$id}/table-${$table?.$id}/create`
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${$database?.$id}/collection-${$collection?.$id}/create`
);
},
icon: IconPlus,
group: 'rows'
group: 'documents'
},
{
label: 'Create column',
keys: page.url.pathname.endsWith('columns') ? ['t'] : ['t', 'a'],
label: 'Create attribute',
keys: page.url.pathname.endsWith('attributes') ? ['c'] : ['c', 'a'],
callback() {
addSubPanel(CreateColumnPanel);
addSubPanel(CreateAttributePanel);
},
icon: IconPlus,
group: 'columns',
disabled: !$canWriteTables
group: 'attributes',
disabled: !$canWriteCollections
},
{
label: 'Go to rows',
label: 'Go to documents',
keys: ['g', 'd'],
callback() {
goto(
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${$database?.$id}/table-${$table?.$id}`
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${$database?.$id}/collection-${$collection?.$id}`
);
},
disabled: page.url.pathname.endsWith($table.$id),
group: 'tables'
disabled: page.url.pathname.endsWith($collection.$id),
group: 'collections'
},
{
label: 'Go to columns',
label: 'Go to attributes',
keys: ['g', 'a'],
callback() {
goto(
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${$database?.$id}/table-${$table?.$id}/columns`
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${$database?.$id}/collection-${$collection?.$id}/attributes`
);
},
disabled: page.url.pathname.endsWith('columns'),
group: 'tables'
disabled: page.url.pathname.endsWith('attributes'),
group: 'collections'
},
{
label: 'Go to indexes',
keys: ['g', 'i'],
callback() {
goto(
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${$database?.$id}/table-${$table?.$id}/indexes`
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${$database?.$id}/collection-${$collection?.$id}/indexes`
);
},
disabled: page.url.pathname.endsWith('indexes'),
group: 'tables'
group: 'collections'
},
{
label: 'Go to activity',
keys: ['g', 'c'],
callback() {
goto(
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${$database?.$id}/table-${$table?.$id}/activity`
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${$database?.$id}/collection-${$collection?.$id}/activity`
);
},
disabled: page.url.pathname.endsWith('activity'),
group: 'tables'
group: 'collections'
},
{
label: 'Go to usage',
keys: ['g', 'u'],
callback() {
goto(
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${$database?.$id}/table-${$table?.$id}/usage`
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${$database?.$id}/collection-${$collection?.$id}/usage`
);
},
disabled: page.url.pathname.endsWith('usage'),
group: 'tables'
group: 'collections'
},
{
label: 'Go to settings',
keys: ['g', 's'],
callback() {
goto(
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${$database?.$id}/table-${$table?.$id}/settings`
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${$database?.$id}/collection-${$collection?.$id}/settings`
);
},
disabled: page.url.pathname.endsWith('settings') || !$canWriteTables,
group: 'tables'
disabled: page.url.pathname.endsWith('settings') || !$canWriteCollections,
group: 'collections'
},
{
label: 'Display Name',
async callback() {
await goto(
`${base}/project-${$project.region}-${$project.$id}/databases/database-${$database.$id}/table-${$table.$id}/settings#display-name`
`${base}/project-${$project.region}-${$project.$id}/databases/database-${$database.$id}/collection-${$collection.$id}/settings#display-name`
);
},
group: 'tables',
group: 'collections',
disabled:
page.url.pathname.endsWith('display-name') ||
page.url.pathname.endsWith('settings') ||
!$canWriteTables,
!$canWriteCollections,
icon: IconEye
},
{
label: 'Permissions',
async callback() {
await goto(
`${base}/project-${$project.region}-${$project.$id}/databases/database-${$database.$id}/table-${$table.$id}/settings#permissions`
`${base}/project-${$project.region}-${$project.$id}/databases/database-${$database.$id}/collection-${$collection.$id}/settings#permissions`
);
},
group: 'tables',
group: 'collections',
disabled:
page.url.pathname.endsWith('permissions') ||
page.url.pathname.endsWith('settings') ||
!$canWriteTables,
!$canWriteCollections,
icon: IconPuzzle
},
{
label: 'Row security',
label: 'Document security',
async callback() {
await goto(
`${base}/project-${$project.region}-${$project.$id}/databases/database-${$database.$id}/table-${$table.$id}/settings#row-security`
`${base}/project-${$project.region}-${$project.$id}/databases/database-${$database.$id}/collection-${$collection.$id}/settings#document-security`
);
},
group: 'tables',
group: 'collections',
disabled:
page.url.pathname.endsWith('row-security') ||
page.url.pathname.endsWith('document-security') ||
page.url.pathname.endsWith('settings') ||
!$canWriteTables,
!$canWriteCollections,
icon: IconLockClosed
},
{
@@ -186,20 +184,20 @@
},
icon: IconPlus,
group: 'indexes',
disabled: !$canWriteTables
disabled: !$canWriteCollections
}
]);
$updateCommandGroupRanks({
columns: 1000,
rows: 900,
tables: 800,
attributes: 1000,
documents: 900,
collections: 800,
indexes: 700
});
</script>
<svelte:head>
<title>{$table?.name ?? 'Table'} - Appwrite</title>
<title>{$collection?.name ?? 'Collection'} - Appwrite</title>
</svelte:head>
<slot />
@@ -7,21 +7,22 @@ import SubNavigation from './subNavigation.svelte';
import { Query } from '@appwrite.io/console';
export const load: LayoutLoad = async ({ params, depends }) => {
depends(Dependencies.TABLE);
const [table, allTables] = await Promise.all([
sdk.forProject(params.region, params.project).tables.get(params.database, params.table),
depends(Dependencies.COLLECTION);
const [collection, allCollections] = await Promise.all([
sdk
.forProject(params.region, params.project)
.tables.list(params.database, [Query.orderDesc(''), Query.limit(100)])
.databases.getCollection(params.database, params.collection),
sdk
.forProject(params.region, params.project)
.databases.listCollections(params.database, [Query.orderDesc(''), Query.limit(100)])
]);
return {
header: Header,
breadcrumbs: Breadcrumbs,
subNavigation: SubNavigation,
table,
allTables
collection,
allCollections
};
};
@@ -6,13 +6,13 @@
import type { Column, ColumnType } from '$lib/helpers/types';
import { Container } from '$lib/layout';
import { preferences } from '$lib/stores/preferences';
import { canWriteTables, canWriteRows } from '$lib/stores/roles';
import { canWriteCollections, canWriteDocuments } from '$lib/stores/roles';
import { Card, Icon, Layout, Empty as PinkEmpty } from '@appwrite.io/pink-svelte';
import type { PageData } from './$types';
import CreateColumnDropdown from './columns/createColumnDropdown.svelte';
import type { Option } from './columns/store';
import CreateColumn from './createColumn.svelte';
import { table, tableColumns, isCsvImportInProgress } from './store';
import CreateAttributeDropdown from './attributes/createAttributeDropdown.svelte';
import type { Option } from './attributes/store';
import CreateAttribute from './createAttribute.svelte';
import { collection, columns, isCsvImportInProgress } from './store';
import Table from './table.svelte';
import { writable } from 'svelte/store';
import FilePicker from '$lib/components/filePicker.svelte';
@@ -28,26 +28,26 @@
export let data: PageData;
let showImportCSV = false;
let showCreateColumn = false;
let selectedColumn: Option['name'] = null;
let showCreateAttribute = false;
let selectedAttribute: Option['name'] = null;
const filterColumns = writable<Column[]>([]);
$: selected = preferences.getCustomTableColumns(page.params.table);
$: selected = preferences.getCustomCollectionColumns(page.params.collection);
$: tableColumns.set(
$table.columns.map((column) => ({
id: column.key,
title: column.key,
type: column.type as ColumnType,
hide: !!selected?.includes(column.key),
array: column?.array,
format: 'format' in column && column?.format === 'enum' ? column.format : null,
elements: 'elements' in column ? column.elements : null
$: columns.set(
$collection.attributes.map((attribute) => ({
id: attribute.key,
title: attribute.key,
type: attribute.type as ColumnType,
hide: !!selected?.includes(attribute.key),
array: attribute?.array,
format: 'format' in attribute && attribute?.format === 'enum' ? attribute.format : null,
elements: 'elements' in attribute ? attribute.elements : null
}))
);
$: filterColumns.set([
...$tableColumns,
...$columns,
...['$id', '$createdAt', '$updatedAt'].map((id) => ({
id,
title: id,
@@ -56,8 +56,8 @@
}))
]);
$: hasColumns = !!$table.columns.length;
$: hasValidColumns = $table?.columns?.some((col) => col.status === 'available');
$: hasAttributes = !!$collection.attributes.length;
$: hasValidAttributes = $collection?.attributes?.some((attr) => attr.status === 'available');
async function onSelect(file: Models.File) {
$isCsvImportInProgress = true;
@@ -68,12 +68,12 @@
.migrations.createCsvMigration(
file.bucketId,
file.$id,
`${page.params.database}:${page.params.table}`
`${page.params.database}:${page.params.collection}`
);
addNotification({
type: 'success',
message: 'Rows import from csv has started'
message: 'Documents import from csv has started'
});
trackEvent(Submit.DatabaseImportCsv);
@@ -89,61 +89,61 @@
}
</script>
{#key page.params.table}
{#key page.params.collection}
<Container>
<Layout.Stack direction="column" gap="xl">
<Layout.Stack direction="row" justifyContent="space-between">
<Filters
query={data.query}
columns={filterColumns}
disabled={!(hasColumns && hasValidColumns)}
analyticsSource="database_rows" />
disabled={!(hasAttributes && hasValidAttributes)}
analyticsSource="database_documents" />
<Layout.Stack direction="row" alignItems="center" justifyContent="flex-end">
<ViewSelector view={data.view} columns={tableColumns} hideView isCustomTable />
<ViewSelector view={data.view} {columns} hideView isCustomCollection />
<Button
secondary
event={Click.DatabaseImportCsv}
disabled={!(hasColumns && hasValidColumns)}
disabled={!(hasAttributes && hasValidAttributes)}
on:click={() => (showImportCSV = true)}>
Import CSV
</Button>
{#if !$isSmallViewport}
<Button
disabled={!(hasColumns && hasValidColumns)}
href={`${base}/project-${page.params.region}-${page.params.project}/databases/database-${page.params.database}/table-${page.params.table}/create`}
event="create_row">
disabled={!(hasAttributes && hasValidAttributes)}
href={`${base}/project-${page.params.region}-${page.params.project}/databases/database-${page.params.database}/collection-${page.params.collection}/create`}
event="create_document">
<Icon icon={IconPlus} slot="start" size="s" />
Create row
Create document
</Button>
{/if}
</Layout.Stack>
</Layout.Stack>
{#if $isSmallViewport}
<Button
disabled={!(hasColumns && hasValidColumns)}
href={`${base}/project-${page.params.region}-${page.params.project}/databases/database-${page.params.database}/table-${page.params.table}/create`}
event="create_row">
disabled={!(hasAttributes && hasValidAttributes)}
href={`${base}/project-${page.params.region}-${page.params.project}/databases/database-${page.params.database}/collection-${page.params.collection}/create`}
event="create_document">
<Icon icon={IconPlus} slot="start" size="s" />
Create row
Create document
</Button>
{/if}
</Layout.Stack>
{#if hasColumns && hasValidColumns}
{#if data.rows.total}
{#if hasAttributes && hasValidAttributes}
{#if data.documents.total}
<Table {data} />
<PaginationWithLimit
name="Rows"
name="Documents"
limit={data.limit}
offset={data.offset}
total={data.rows.total} />
total={data.documents.total} />
{:else if $hasPageQueries}
<EmptySearch hidePages>
<div class="common-section">
<div class="u-text-center common-section">
<b class="body-text-2 u-bold">Sorry, we couldn't find any rows.</b>
<p>There are no rows that match your filters.</p>
<b class="body-text-2 u-bold">Sorry, we couldn't find any documents.</b>
<p>There are no documents that match your filters.</p>
</div>
<div class="u-flex common-section u-main-center">
<Button
@@ -152,7 +152,7 @@
queries.clearAll();
queries.apply();
trackEvent(Submit.FilterClear, {
source: 'database_rows'
source: 'database_documents'
});
}}>
Clear filters
@@ -162,24 +162,24 @@
</EmptySearch>
{:else}
<Empty
allowCreate={$canWriteRows}
allowCreate={$canWriteDocuments}
single
href="https://appwrite.io/docs/products/databases/rows"
target="row">
href="https://appwrite.io/docs/products/databases/documents"
target="document">
<svelte:fragment slot="actions">
<Button
external
href="https://appwrite.io/docs/products/databases/rows"
href="https://appwrite.io/docs/products/databases/documents"
text
event="empty_documentation"
size="s"
ariaLabel="create row">Documentation</Button>
ariaLabel="create document">Documentation</Button>
<Button
href={`${base}/project-${page.params.region}-${page.params.project}/databases/database-${page.params.database}/table-${page.params.table}/create`}
href={`${base}/project-${page.params.region}-${page.params.project}/databases/database-${page.params.database}/collection-${page.params.collection}/create`}
secondary
disabled={!$canWriteRows}
disabled={!$canWriteDocuments}
size="s">
Create row
Create document
</Button>
</svelte:fragment>
</Empty>
@@ -187,24 +187,24 @@
{:else}
<Card.Base padding="none">
<PinkEmpty
title="Create a column to get started."
title="Create an attribute to get started."
description="Need a hand? Learn more in our documentation.">
<slot name="actions" slot="actions">
<Button
external
href="https://appwrite.io/docs/products/databases/tables#columns"
href="https://appwrite.io/docs/products/databases/collections#attributes"
text
event="empty_documentation"
size="s">Documentation</Button>
{#if $canWriteTables}
<CreateColumnDropdown
bind:selectedOption={selectedColumn}
bind:showCreate={showCreateColumn}
{#if $canWriteCollections}
<CreateAttributeDropdown
bind:selectedOption={selectedAttribute}
bind:showCreate={showCreateAttribute}
let:toggle>
<Button secondary event="create_column" on:click={toggle}>
Create column
<Button secondary event="create_attribute" on:click={toggle}>
Create attribute
</Button>
</CreateColumnDropdown>
</CreateAttributeDropdown>
{/if}
</slot>
</PinkEmpty>
@@ -213,8 +213,10 @@
</Container>
{/key}
{#if showCreateColumn}
<CreateColumn bind:showCreate={showCreateColumn} bind:selectedOption={selectedColumn} />
{#if showCreateAttribute}
<CreateAttribute
bind:showCreate={showCreateAttribute}
bind:selectedOption={selectedAttribute} />
{/if}
{#if showImportCSV}
@@ -4,11 +4,11 @@ import { sdk } from '$lib/stores/sdk';
import { Query } from '@appwrite.io/console';
import type { PageLoad } from './$types';
import { queries, queryParamToMap } from '$lib/components/filters';
import { buildWildcardColumnsQuery } from './row-[row]/columns/store';
import { buildWildcardAttributesQuery } from './document-[document]/attributes/store';
export const load: PageLoad = async ({ params, depends, url, route, parent }) => {
const { table } = await parent();
depends(Dependencies.ROWS);
const { collection } = await parent();
depends(Dependencies.DOCUMENTS);
const page = getPage(url);
const limit = getLimit(url, route, PAGE_LIMIT);
@@ -18,6 +18,7 @@ export const load: PageLoad = async ({ params, depends, url, route, parent }) =>
const paramQueries = url.searchParams.get('query');
const parsedQueries = queryParamToMap(paramQueries || '[]');
queries.set(parsedQueries);
return {
@@ -25,14 +26,14 @@ export const load: PageLoad = async ({ params, depends, url, route, parent }) =>
limit,
view,
query,
rows: await sdk
documents: await sdk
.forProject(params.region, params.project)
.tables.listRows(params.database, params.table, [
.databases.listDocuments(params.database, params.collection, [
Query.limit(limit),
Query.offset(offset),
Query.orderDesc(''),
...parsedQueries.values(),
...buildWildcardColumnsQuery(table)
...buildWildcardAttributesQuery(collection)
])
};
};
@@ -14,7 +14,7 @@ export const load: PageLoad = async ({ params, url, route }) => {
limit,
logs: await sdk
.forProject(params.region, params.project)
.tables.listLogs(params.database, params.table, [
.databases.listCollectionLogs(params.database, params.collection, [
Query.limit(limit),
Query.offset(offset)
])
@@ -4,7 +4,7 @@
import { Empty } from '$lib/components';
import { Button } from '$lib/elements/forms';
import { Container } from '$lib/layout';
import { canWriteTables } from '$lib/stores/roles';
import { canWriteCollections } from '$lib/stores/roles';
import {
ActionMenu,
Badge,
@@ -16,15 +16,15 @@
Tooltip,
Typography
} from '@appwrite.io/pink-svelte';
import Create from '../createColumn.svelte';
import { isRelationship, isString } from '../row-[row]/columns/store';
import Create from '../createAttribute.svelte';
import { isRelationship, isString } from '../document-[document]/attributes/store';
import FailedModal from '../failedModal.svelte';
import CreateIndex from '../indexes/createIndex.svelte';
import { columns, type Columns, isCsvImportInProgress } from '../store';
import CreateColumnDropdown from './createColumnDropdown.svelte';
import Delete from './deleteColumn.svelte';
import { attributes, type Attributes, isCsvImportInProgress } from '../store';
import CreateAttributeDropdown from './createAttributeDropdown.svelte';
import Delete from './deleteAttribute.svelte';
import Edit from './edit.svelte';
import { columnOptions, type Option } from './store';
import { attributeOptions, type Option } from './store';
import {
IconArrowSmRight,
IconDotsHorizontal,
@@ -45,7 +45,7 @@
let showDropdown = [];
let selectedOption: Option['name'] = null;
let selectedColumn: Columns = null;
let selectedAttribute: Attributes = null;
let showCreate = false;
let showDelete = false;
let showEdit = false;
@@ -53,14 +53,14 @@
let showFailed = false;
let error = '';
const columnFormatIcon = {
const attributeFormatIcon = {
ip: IconLocationMarker,
url: IconLink,
email: IconLink,
enum: IconViewList
};
function getColumnStatusBadge(status: string): ComponentProps<Badge>['type'] {
function getAttributeStatusBadge(status: string): ComponentProps<Badge>['type'] {
switch (status) {
case 'processing':
return 'warning';
@@ -76,13 +76,13 @@
<Container>
<Layout.Stack direction="row" justifyContent="space-between">
<Typography.Title>Columns</Typography.Title>
{#if $canWriteTables}
<CreateColumnDropdown bind:selectedOption bind:showCreate />
<Typography.Title>Attributes</Typography.Title>
{#if $canWriteCollections}
<CreateAttributeDropdown bind:selectedOption bind:showCreate />
{/if}
</Layout.Stack>
{#if $columns.length}
{#if $attributes.length}
<Table.Root
let:root
columns={[
@@ -97,27 +97,27 @@
<Table.Header.Cell column="default" {root}>Default value</Table.Header.Cell>
<Table.Header.Cell column="actions" {root} />
</svelte:fragment>
{#each $columns as column, index}
{@const option = columnOptions.find((option) => option.type === column.type)}
{#each $attributes as attribute, index}
{@const option = attributeOptions.find((option) => option.type === attribute.type)}
<Table.Row.Base {root}>
<Table.Cell column="key" {root}>
<Layout.Stack direction="row" alignItems="center">
{#if isRelationship(column)}
{#if isRelationship(attribute)}
<Icon
size="s"
icon={column?.twoWay
icon={attribute?.twoWay
? IconSwitchHorizontal
: IconArrowSmRight} />
{:else if 'format' in column && column.format}
{@const icon = columnFormatIcon[column?.format]}
{:else if 'format' in attribute && attribute.format}
{@const icon = attributeFormatIcon[attribute?.format]}
<Icon {icon} size="s" />
{:else}
<Icon icon={option.icon} size="s" />
{/if}
<Layout.Stack direction="row" alignItems="center" gap="s">
<Layout.Stack inline direction="row" alignItems="center" gap="xxs">
<span class="text u-trim-1" data-private>{column.key}</span>
{#if isString(column) && column.encrypt}
<span class="text u-trim-1" data-private>{attribute.key}</span>
{#if isString(attribute) && attribute.encrypt}
<Tooltip>
<Icon
size="s"
@@ -127,49 +127,49 @@
</Tooltip>
{/if}
</Layout.Stack>
{#if column.status !== 'available'}
{#if attribute.status !== 'available'}
<Badge
size="s"
variant="secondary"
content={column.status}
type={getColumnStatusBadge(column.status)} />
{#if column.error}
content={attribute.status}
type={getAttributeStatusBadge(attribute.status)} />
{#if attribute.error}
<Link.Button
variant="muted"
on:click={(e) => {
e.preventDefault();
error = column.error;
error = attribute.error;
showFailed = true;
}}>Details</Link.Button>
{/if}
{:else if column.required}
{:else if attribute.required}
<Badge size="xs" variant="secondary" content="required" />
{/if}
</Layout.Stack>
</Layout.Stack>
</Table.Cell>
<Table.Cell column="type" {root}>
{#if 'format' in column && column.format}
<span class="u-capitalize">{column.format}</span>
{#if 'format' in attribute && attribute.format}
<span class="u-capitalize">{attribute.format}</span>
{:else}
<p>
<span class="u-capitalize">{column.type}</span>
{#if isRelationship(column)}
<span class="u-capitalize">{attribute.type}</span>
{#if isRelationship(attribute)}
<span>
with <a
href={`${base}/project-${page.params.region}-${page.params.project}/databases/database-${databaseId}/table-${column?.relatedTable}`}
><b data-private>{column?.key}</b></a>
href={`${base}/project-${page.params.region}-${page.params.project}/databases/database-${databaseId}/collection-${attribute?.relatedCollection}`}
><b data-private>{attribute?.key}</b></a>
</span>
{/if}
</p>
{/if}
<span>
{column.array ? '[]' : ''}
{attribute.array ? '[]' : ''}
</span>
</Table.Cell>
<Table.Cell column="default" {root}>
{column?.default !== null && column?.default !== undefined
? column?.default
{attribute?.default !== null && attribute?.default !== undefined
? attribute?.default
: '-'}
</Table.Cell>
<Table.Cell column="actions" {root}>
@@ -190,32 +190,32 @@
on:click={(event) => {
toggle(event);
showEdit = true;
selectedColumn = column;
selectedAttribute = attribute;
showDropdown[index] = false;
}}>
Update
</ActionMenu.Item.Button>
{#if !isRelationship(column)}
{#if !isRelationship(attribute)}
<ActionMenu.Item.Button
leadingIcon={IconPlus}
on:click={(event) => {
toggle(event);
selectedColumn = column;
selectedAttribute = attribute;
showCreateIndex = true;
showDropdown[index] = false;
}}>
Create index
</ActionMenu.Item.Button>
{/if}
{#if column.status !== 'processing'}
{#if attribute.status !== 'processing'}
<ActionMenu.Item.Button
leadingIcon={IconTrash}
on:click={(event) => {
toggle(event);
showDelete = true;
showDropdown[index] = false;
selectedColumn = column;
trackEvent(Click.DatabaseColumnDelete);
selectedAttribute = attribute;
trackEvent(Click.DatabaseAttributeDelete);
}}>
Delete
</ActionMenu.Item.Button>
@@ -228,20 +228,20 @@
{/each}
</Table.Root>
{:else}
<Empty single target="column">
<Empty single target="attribute">
<svelte:fragment slot="actions">
<Button
external
href="https://appwrite.io/docs/products/databases/tables#columns"
href="https://appwrite.io/docs/products/databases/collections#attributes"
text
event="empty_documentation"
ariaLabel={'create column'}>Documentation</Button>
{#if $canWriteTables}
<CreateColumnDropdown bind:selectedOption bind:showCreate let:toggle>
<Button secondary event="create_column" on:click={toggle}>
Create column
ariaLabel={`create {target}`}>Documentation</Button>
{#if $canWriteCollections}
<CreateAttributeDropdown bind:selectedOption bind:showCreate let:toggle>
<Button secondary event="create_attribute" on:click={toggle}>
Create attribute
</Button>
</CreateColumnDropdown>
</CreateAttributeDropdown>
{/if}
</svelte:fragment>
</Empty>
@@ -252,14 +252,14 @@
<Create bind:showCreate bind:selectedOption />
{/if}
{#if showDelete}
<Delete bind:showDelete {selectedColumn} />
<Delete bind:showDelete {selectedAttribute} />
{/if}
{#if showEdit}
<Edit bind:showEdit {selectedColumn} />
<Edit bind:showEdit {selectedAttribute} />
{/if}
{#if showCreateIndex}
<CreateIndex bind:showCreateIndex externalColumn={selectedColumn} />
<CreateIndex bind:showCreateIndex externalAttribute={selectedAttribute} />
{/if}
{#if showFailed}
<FailedModal bind:show={showFailed} title="Create column" header="Creation failed" {error} />
<FailedModal bind:show={showFailed} title="Create attribute" header="Creation failed" {error} />
{/if}
@@ -5,15 +5,15 @@
export async function submitBoolean(
databaseId: string,
tableId: string,
collectionId: string,
key: string,
data: Partial<Models.ColumnBoolean>
data: Partial<Models.AttributeBoolean>
) {
await sdk
.forProject(page.params.region, page.params.project)
.tables.createBooleanColumn(
.databases.createBooleanAttribute(
databaseId,
tableId,
collectionId,
key,
data.required,
data.default,
@@ -22,15 +22,15 @@
}
export async function updateBoolean(
databaseId: string,
tableId: string,
data: Partial<Models.ColumnBoolean>,
collectionId: string,
data: Partial<Models.AttributeBoolean>,
originalKey?: string
) {
await sdk
.forProject(page.params.region, page.params.project)
.tables.updateBooleanColumn(
.databases.updateBooleanAttribute(
databaseId,
tableId,
collectionId,
originalKey,
data.required,
data.default,
@@ -43,7 +43,7 @@
import { InputSelect } from '$lib/elements/forms';
export let editing = false;
export let data: Partial<Models.ColumnBoolean> = {
export let data: Partial<Models.AttributeBoolean> = {
required: false,
array: false,
default: null
@@ -66,7 +66,7 @@
const {
stores: { required, array },
listen
} = createConservative<Partial<Models.ColumnBoolean>>({
} = createConservative<Partial<Models.AttributeBoolean>>({
required: false,
array: false,
...data
@@ -1,13 +1,13 @@
<script lang="ts">
import { Button } from '$lib/elements/forms';
import { ActionMenu, Icon, Popover } from '@appwrite.io/pink-svelte';
import { columnOptions, type Option } from './store';
import { attributeOptions, type Option } from './store';
import { IconPlus } from '@appwrite.io/pink-icons-svelte';
import CsvDisabled from '../csvDisabled.svelte';
import { isCsvImportInProgress } from '../store';
export let showCreate = false;
export let selectedOption: Option['name'] = null;
export let showCreate = false;
</script>
{#if $isCsvImportInProgress}
@@ -22,11 +22,11 @@
<slot {toggle}>
<Button on:click={toggle} event="create_attribute">
<Icon icon={IconPlus} slot="start" size="s" />
Create column
Create attribute
</Button>
</slot>
<ActionMenu.Root slot="tooltip">
{#each columnOptions as attribute}
{#each attributeOptions as attribute}
<ActionMenu.Item.Button
leadingIcon={attribute.icon}
on:click={() => {
@@ -5,15 +5,15 @@
export async function submitDatetime(
databaseId: string,
tableId: string,
collectionId: string,
key: string,
data: Partial<Models.ColumnDatetime>
data: Partial<Models.AttributeDatetime>
) {
await sdk
.forProject(page.params.region, page.params.project)
.tables.createDatetimeColumn(
.databases.createDatetimeAttribute(
databaseId,
tableId,
collectionId,
key,
data.required,
data.default,
@@ -23,15 +23,15 @@
export async function updateDatetime(
databaseId: string,
tableId: string,
data: Partial<Models.ColumnDatetime>,
collectionId: string,
data: Partial<Models.AttributeDatetime>,
originalKey?: string
) {
await sdk
.forProject(page.params.region, page.params.project)
.tables.updateDatetimeColumn(
.databases.updateDatetimeAttribute(
databaseId,
tableId,
collectionId,
originalKey,
data.required,
data.default,
@@ -44,7 +44,7 @@
import { InputDateTime } from '$lib/elements/forms';
export let editing = false;
export let data: Partial<Models.ColumnDatetime>;
export let data: Partial<Models.AttributeDatetime>;
import { createConservative } from '$lib/helpers/stores';
import { Selector } from '@appwrite.io/pink-svelte';
@@ -63,7 +63,7 @@
const {
stores: { required, array },
listen
} = createConservative<Partial<Models.ColumnDatetime>>({
} = createConservative<Partial<Models.AttributeDatetime>>({
required: false,
array: false,
...data
@@ -4,16 +4,15 @@
import { page } from '$app/state';
import { InputChoice } from '$lib/elements/forms';
import { addNotification } from '$lib/stores/notifications';
import { table } from '../store';
import type { Columns } from '../store';
import { collection } from '../store';
import type { Attributes } from '../store';
import { sdk } from '$lib/stores/sdk';
import { Submit, trackEvent, trackError } from '$lib/actions/analytics';
import { isRelationship } from '../row-[row]/columns/store';
import { isRelationship } from '../document-[document]/attributes/store';
import Confirm from '$lib/components/confirm.svelte';
export let showDelete = false;
export let selectedColumn: Columns;
export let selectedAttribute: Attributes;
const databaseId = page.params.database;
let error: string;
@@ -23,37 +22,38 @@
try {
await sdk
.forProject(page.params.region, page.params.project)
.tables.deleteColumn(databaseId, $table.$id, selectedColumn.key);
.databases.deleteAttribute(databaseId, $collection.$id, selectedAttribute.key);
showDelete = false;
addNotification({
type: 'success',
message: `Column has been deleted`
message: `Attribute has been deleted`
});
trackEvent(Submit.ColumnDelete);
trackEvent(Submit.AttributeDelete);
await goto(
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${databaseId}/table-${page.params.table}/columns`
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${databaseId}/collection-${page.params.collection}/attributes`
);
} catch (e) {
error = e.message;
trackError(e, Submit.ColumnDelete);
trackError(e, Submit.AttributeDelete);
}
}
$: isDeleteBtnDisabled = isRelationship(selectedColumn) && selectedColumn?.twoWay && !checked;
$: isDeleteBtnDisabled =
isRelationship(selectedAttribute) && selectedAttribute?.twoWay && !checked;
</script>
<Confirm
bind:open={showDelete}
onSubmit={handleDelete}
title="Delete column"
title="Delete attribute"
bind:error
disabled={isDeleteBtnDisabled}>
<p>
Are you sure you want to delete <b data-private>{selectedColumn?.key}</b> from
<b data-private>{$table?.name}</b>?
Are you sure you want to delete <b data-private>{selectedAttribute?.key}</b> from
<b data-private>{$collection?.name}</b>?
</p>
{#if isRelationship(selectedColumn) && selectedColumn?.twoWay}
{#if isRelationship(selectedAttribute) && selectedAttribute?.twoWay}
<div class="u-flex u-flex-vertical u-gap-24">
<p>
This is a two way relationship and the corresponding relationship will also be
@@ -62,8 +62,8 @@
<p><b>This action is irreversible.</b></p>
<ul>
<InputChoice id="delete" label="Delete" showLabel={false} bind:value={checked}>
Delete relationship between <b data-private>{selectedColumn.key}</b> to
<b data-private>{selectedColumn.twoWayKey}</b>
Delete relationship between <b data-private>{selectedAttribute.key}</b> to
<b data-private>{selectedAttribute.twoWayKey}</b>
</InputChoice>
</ul>
</div>
@@ -8,60 +8,60 @@
import { Button, InputText } from '$lib/elements/forms';
import deepEqual from 'deep-equal';
import { addNotification } from '$lib/stores/notifications';
import type { Columns } from '../store';
import { columnOptions, type Option } from './store';
import type { Attributes } from '../store';
import { attributeOptions, type Option } from './store';
export let showEdit = false;
export let selectedColumn: Columns;
export let selectedAttribute: Attributes;
const databaseId = page.params.database;
const tableId = page.params.table;
const collectionId = page.params.collection;
let originalKey = '';
let error: string;
let currentColumn: Columns;
let currentAttr: Attributes;
$: option = columnOptions.find((option) => {
if (selectedColumn) {
if ('format' in selectedColumn && selectedColumn.format) {
return option?.format === selectedColumn?.format;
$: option = attributeOptions.find((option) => {
if (selectedAttribute) {
if ('format' in selectedAttribute && selectedAttribute.format) {
return option?.format === selectedAttribute?.format;
} else {
return option?.type === selectedColumn?.type;
return option?.type === selectedAttribute?.type;
}
}
}) as Option;
async function submit() {
try {
await option.update(databaseId, tableId, selectedColumn, originalKey);
await invalidate(Dependencies.TABLE);
if (!page.url.pathname.includes('columns')) {
await option.update(databaseId, collectionId, selectedAttribute, originalKey);
await invalidate(Dependencies.COLLECTION);
if (!page.url.pathname.includes('attributes')) {
await goto(
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${databaseId}/table-${tableId}/columns`
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${databaseId}/collection-${collectionId}/attributes`
);
}
addNotification({
type: 'success',
message: `Column ${selectedColumn.key} has been updated`
message: `Attribute ${selectedAttribute.key} has been updated`
});
showEdit = false;
trackEvent(Submit.ColumnUpdate);
trackEvent(Submit.AttributeUpdate);
} catch (e) {
error = e.message;
trackError(e, Submit.ColumnUpdate);
trackError(e, Submit.AttributeUpdate);
}
}
$: onShow(showEdit);
$: title = `Update ${columnOptions.find((v) => v.name === option.name)?.sentenceName ?? ''} attribute`;
$: title = `Update ${attributeOptions.find((v) => v.name === option.name)?.sentenceName ?? ''} attribute`;
function onShow(show: boolean) {
if (show) {
currentColumn ??= { ...selectedColumn };
originalKey = currentColumn.key;
currentAttr ??= { ...selectedAttribute };
originalKey = currentAttr.key;
error = null;
} else {
currentColumn = null;
currentAttr = null;
}
}
</script>
@@ -78,26 +78,26 @@
</div>
</svelte:fragment>
{#if selectedColumn}
{#if selectedColumn?.type !== 'relationship'}
{#if selectedAttribute}
{#if selectedAttribute?.type !== 'relationship'}
<InputText
id="key"
label="Column Key"
label="Attribute Key"
placeholder="Enter Key"
bind:value={selectedColumn.key}
bind:value={selectedAttribute.key}
autofocus />
{/if}
{#if option}
<svelte:component
this={option.component}
editing
bind:data={selectedColumn}
bind:data={selectedAttribute}
onclose={() => (option = null)} />
{/if}
{/if}
<svelte:fragment slot="footer">
<Button secondary on:click={() => (showEdit = false)}>Cancel</Button>
<Button submit disabled={deepEqual(currentColumn, selectedColumn)}>Update</Button>
<Button submit disabled={deepEqual(currentAttr, selectedAttribute)}>Update</Button>
</svelte:fragment>
</Modal>
@@ -5,15 +5,15 @@
export async function submitEmail(
databaseId: string,
tableId: string,
collectionId: string,
key: string,
data: Partial<Models.ColumnEmail>
data: Partial<Models.AttributeEmail>
) {
await sdk
.forProject(page.params.region, page.params.project)
.tables.createEmailColumn(
.databases.createEmailAttribute(
databaseId,
tableId,
collectionId,
key,
data.required,
data.default,
@@ -23,15 +23,15 @@
export async function updateEmail(
databaseId: string,
tableId: string,
data: Partial<Models.ColumnEmail>,
collectionId: string,
data: Partial<Models.AttributeEmail>,
originalKey?: string
) {
await sdk
.forProject(page.params.region, page.params.project)
.tables.updateEmailColumn(
.databases.updateEmailAttribute(
databaseId,
tableId,
collectionId,
originalKey,
data.required,
data.default,
@@ -44,7 +44,7 @@
import { InputEmail } from '$lib/elements/forms';
export let editing = false;
export let data: Partial<Models.ColumnEmail>;
export let data: Partial<Models.AttributeEmail>;
import { createConservative } from '$lib/helpers/stores';
import { Selector } from '@appwrite.io/pink-svelte';
@@ -63,7 +63,7 @@
const {
stores: { required, array },
listen
} = createConservative<Partial<Models.ColumnEmail>>({
} = createConservative<Partial<Models.AttributeEmail>>({
required: false,
array: false,
...data
@@ -5,15 +5,15 @@
export async function submitEnum(
databaseId: string,
tableId: string,
collectionId: string,
key: string,
data: Partial<Models.ColumnEnum>
data: Partial<Models.AttributeEnum>
) {
await sdk
.forProject(page.params.region, page.params.project)
.tables.createEnumColumn(
.databases.createEnumAttribute(
databaseId,
tableId,
collectionId,
key,
data.elements,
data.required,
@@ -24,15 +24,15 @@
export async function updateEnum(
databaseId: string,
tableId: string,
data: Partial<Models.ColumnEnum>,
collectionId: string,
data: Partial<Models.AttributeEnum>,
originalKey?: string
) {
await sdk
.forProject(page.params.region, page.params.project)
.tables.updateEnumColumn(
.databases.updateEnumAttribute(
databaseId,
tableId,
collectionId,
originalKey,
data.elements,
data.required,
@@ -46,7 +46,7 @@
import { InputSelect, InputTags } from '$lib/elements/forms';
export let editing = false;
export let data: Partial<Models.ColumnEnum>;
export let data: Partial<Models.AttributeEnum>;
import { createConservative } from '$lib/helpers/stores';
import { Icon, Selector, Tooltip, Typography } from '@appwrite.io/pink-svelte';
@@ -66,7 +66,7 @@
const {
stores: { required, array },
listen
} = createConservative<Partial<Models.ColumnEnum>>({
} = createConservative<Partial<Models.AttributeEnum>>({
required: false,
array: false,
...data
@@ -5,15 +5,15 @@
export async function submitFloat(
databaseId: string,
tableId: string,
collectionId: string,
key: string,
data: Partial<Models.ColumnFloat>
data: Partial<Models.AttributeFloat>
) {
await sdk
.forProject(page.params.region, page.params.project)
.tables.createFloatColumn(
.databases.createFloatAttribute(
databaseId,
tableId,
collectionId,
key,
data.required,
data.min,
@@ -25,15 +25,15 @@
export async function updateFloat(
databaseId: string,
tableId: string,
data: Partial<Models.ColumnFloat>,
collectionId: string,
data: Partial<Models.AttributeFloat>,
originalKey?: string
) {
await sdk
.forProject(page.params.region, page.params.project)
.tables.updateFloatColumn(
.databases.updateFloatAttribute(
databaseId,
tableId,
collectionId,
originalKey,
data.required,
data.default,
@@ -48,7 +48,7 @@
import { InputNumber } from '$lib/elements/forms';
export let editing = false;
export let data: Partial<Models.ColumnFloat> = {
export let data: Partial<Models.AttributeFloat> = {
required: false,
min: 0,
max: 0,
@@ -73,7 +73,7 @@
const {
stores: { required, array },
listen
} = createConservative<Partial<Models.ColumnFloat>>({
} = createConservative<Partial<Models.AttributeFloat>>({
required: false,
array: false,
...data
@@ -5,15 +5,15 @@
export async function submitInteger(
databaseId: string,
tableId: string,
collectionId: string,
key: string,
data: Partial<Models.ColumnInteger>
data: Partial<Models.AttributeInteger>
) {
await sdk
.forProject(page.params.region, page.params.project)
.tables.createIntegerColumn(
.databases.createIntegerAttribute(
databaseId,
tableId,
collectionId,
key,
data.required,
data.min,
@@ -25,15 +25,15 @@
export async function updateInteger(
databaseId: string,
tableId: string,
data: Partial<Models.ColumnInteger>,
collectionId: string,
data: Partial<Models.AttributeInteger>,
originalKey?: string
) {
await sdk
.forProject(page.params.region, page.params.project)
.tables.updateIntegerColumn(
.databases.updateIntegerAttribute(
databaseId,
tableId,
collectionId,
originalKey,
data.required,
data.default,
@@ -49,7 +49,7 @@
export let editing = false;
export let data: Partial<Models.ColumnInteger> = {
export let data: Partial<Models.AttributeInteger> = {
required: false,
min: 0,
max: 0,
@@ -74,7 +74,7 @@
const {
stores: { required, array },
listen
} = createConservative<Partial<Models.ColumnInteger>>({
} = createConservative<Partial<Models.AttributeInteger>>({
required: false,
array: false,
...data
@@ -5,15 +5,15 @@
export async function submitIp(
databaseId: string,
tableId: string,
collectionId: string,
key: string,
data: Partial<Models.ColumnIp>
data: Partial<Models.AttributeIp>
) {
await sdk
.forProject(page.params.region, page.params.project)
.tables.createIpColumn(
.databases.createIpAttribute(
databaseId,
tableId,
collectionId,
key,
data.required,
data.default,
@@ -22,15 +22,15 @@
}
export async function updateIp(
databaseId: string,
tableId: string,
data: Partial<Models.ColumnIp>,
collectionId: string,
data: Partial<Models.AttributeIp>,
originalKey?: string
) {
await sdk
.forProject(page.params.region, page.params.project)
.tables.updateIpColumn(
.databases.updateIpAttribute(
databaseId,
tableId,
collectionId,
originalKey,
data.required,
data.default,
@@ -43,7 +43,7 @@
import { InputText } from '$lib/elements/forms';
export let editing = false;
export let data: Partial<Models.ColumnIp>;
export let data: Partial<Models.AttributeIp>;
import { createConservative } from '$lib/helpers/stores';
import { Selector } from '@appwrite.io/pink-svelte';
@@ -62,7 +62,7 @@
const {
stores: { required, array },
listen
} = createConservative<Partial<Models.ColumnIp>>({
} = createConservative<Partial<Models.AttributeIp>>({
required: false,
array: false,
...data
@@ -6,9 +6,9 @@
export async function submitRelationship(
databaseId: string,
tableId: string,
collectionId: string,
_key: string,
data: Partial<Models.ColumnRelationship>
data: Partial<Models.AttributeRelationship>
) {
if (!isValueOfStringEnum(RelationshipType, data.relationType)) {
throw new Error(
@@ -21,10 +21,10 @@
await sdk
.forProject(page.params.region, page.params.project)
.tables.createRelationshipColumn(
.databases.createRelationshipAttribute(
databaseId,
tableId,
data.relatedTable,
collectionId,
data.relatedCollection,
data.relationType,
data.twoWay,
data.key,
@@ -35,8 +35,8 @@
export async function updateRelationship(
databaseId: string,
tableId: string,
data: Partial<Models.ColumnRelationship>,
collectionId: string,
data: Partial<Models.AttributeRelationship>,
originalKey?: string
) {
if (!isValueOfStringEnum(RelationMutate, data.onDelete)) {
@@ -45,9 +45,9 @@
await sdk
.forProject(page.params.region, page.params.project)
.tables.updateRelationshipColumn(
.databases.updateRelationshipAttribute(
databaseId,
tableId,
collectionId,
originalKey,
data.onDelete,
data.key !== originalKey ? data.key : undefined
@@ -59,7 +59,7 @@
import { InputText, InputSelect } from '$lib/elements/forms';
import { onMount } from 'svelte';
import { Box } from '$lib/components';
import { table } from '../store';
import { collection } from '../store';
import arrowOne from './arrow-one.svg';
import arrowTwo from './arrow-two.svg';
import { camelize } from '$lib/helpers/string';
@@ -69,7 +69,7 @@
// Props
export let editing = false;
export let data: Models.ColumnRelationship;
export let data: Models.AttributeRelationship;
// Constants
const databaseId = page.params.database;
@@ -81,45 +81,47 @@
];
const deleteOptions = [
{ value: 'setNull', label: 'Set NULL - set row ID as NULL in all related rows' },
{ value: 'cascade', label: 'Cascade - delete all related rows' },
{ value: 'restrict', label: 'Restrict - row can not be deleted' }
{ value: 'setNull', label: 'Set NULL - set document ID as NULL in all related documents' },
{ value: 'cascade', label: 'Cascade - delete all related documents' },
{ value: 'restrict', label: 'Restrict - document can not be deleted' }
];
// Variables
let way = 'one';
let search = undefined;
let tableList: Models.TableList;
let originalTableList: Models.TableList;
let collectionList: Models.CollectionList;
let originalCollectionList: Models.CollectionList;
// Lifecycle hooks
async function getTables() {
async function getCollections() {
const queries = [Query.limit(100)];
return sdk
.forProject(page.params.region, page.params.project)
.tables.list(databaseId, queries, search);
.databases.listCollections(databaseId, queries, search);
}
const debouncedFetchTables = debounce(async () => {
tableList = await getTables();
const debouncedFetchCollections = debounce(async () => {
collectionList = await getCollections();
// reset search
search = undefined;
}, 500);
function updateKeyName() {
if (!editing) {
const collection = tableList.tables.find((n) => n.$id === data.relatedTable);
const collection = collectionList.collections.find(
(n) => n.$id === data.relatedCollection
);
data.key = camelize(collection.name);
}
}
onMount(async () => {
tableList = await getTables();
originalTableList = tableList;
collectionList = await getCollections();
originalCollectionList = collectionList;
});
// Reactive statements
$: tables = tableList?.tables?.filter((n) => n.$id !== $table.$id) ?? [];
$: collections = collectionList?.collections?.filter((n) => n.$id !== $collection.$id) ?? [];
$: if (editing) {
way = data.twoWay ? 'two' : 'one';
@@ -127,26 +129,26 @@
if (way === 'two') {
data.twoWay = true;
if (!data.twoWayKey) {
data.twoWayKey = camelize($table.name);
data.twoWayKey = camelize($collection.name);
}
} else {
data.twoWay = false;
}
}
$: search = data.relatedTable || undefined;
$: search = data.relatedCollection || undefined;
$: if (search) {
const exists = tableList?.tables?.some((c) =>
const exists = collectionList?.collections?.some((c) =>
c.$id.toLocaleLowerCase().includes(search.toLocaleLowerCase())
);
if (!exists) {
debouncedFetchTables();
debouncedFetchCollections();
}
} else if (!tableList?.total) {
} else if (!collectionList?.total) {
// reset to original list!
tableList = originalTableList;
collectionList = originalCollectionList;
}
</script>
@@ -157,7 +159,7 @@
name="one"
value="one"
icon={IconArrowSmRight}>
One Relation column within this table
One Relation attribute within this collection
</Card.Selector>
<Card.Selector
title="Two-way relationship"
@@ -165,23 +167,23 @@
name="two"
value="two"
icon={IconSwitchHorizontal}>
One Relation column within this table and another within the related table
One Relation attribute within this collection and another within the related collection
</Card.Selector>
</Layout.Stack>
<Input.ComboBox
required
id="related"
label="Related table"
placeholder="Select a table"
bind:value={data.relatedTable}
label="Related collection"
placeholder="Select a collection"
bind:value={data.relatedCollection}
on:change={updateKeyName}
options={tables?.map((n) => ({ value: n.$id, label: `${n.name} (${n.$id})` })) ?? []} />
options={collections?.map((n) => ({ value: n.$id, label: `${n.name} (${n.$id})` })) ?? []} />
{#if data?.relatedTable}
{#if data?.relatedCollection}
<InputText
id="key"
label="Column key"
label="Attribute key"
placeholder="Enter key"
bind:value={data.key}
helper="Allowed characters: a-z, A-Z, 0-9, -, ."
@@ -189,11 +191,11 @@
{#if way === 'two'}
<InputText
id="keyRelated"
label="Column key (related table)"
label="Attribute key (related collection)"
placeholder="Enter key"
bind:value={data.twoWayKey}
required
helper="Allowed characters: a-z, A-Z, 0-9, -, . Once created, column key cannot be
helper="Allowed characters: a-z, A-Z, 0-9, -, . Once created, attribute key cannot be
adjusted to maintain data integrity."
readonly={editing} />
{/if}
@@ -210,7 +212,7 @@
<div class="u-flex u-flex-vertical u-gap-16">
<Box>
<div class="u-flex u-align u-cross-center u-main-center u-gap-32">
<span data-private>{camelize($table.name)}</span>
<span data-private>{camelize($collection.name)}</span>
{#if data.twoWay}
<img src={arrowTwo} alt={'Two way relationship'} />
{:else}
@@ -222,7 +224,7 @@
{#if data.relationType}
<div>
<p class="u-text-center">
<b data-private>{camelize($table.name)}</b> can contain {[
<b data-private>{camelize($collection.name)}</b> can contain {[
'oneToOne',
'manyToOne'
].includes(data.relationType)
@@ -235,14 +237,14 @@
can belong to {['oneToOne', 'oneToMany'].includes(data.relationType)
? 'one'
: 'many'}
<b data-private>{camelize($table.name)}</b>
<b data-private>{camelize($collection.name)}</b>
</p>
</div>
{/if}
</div>
<InputSelect
id="deleting"
label="On deleting a row"
label="On deleting a document"
bind:value={data.onDelete}
required
placeholder="Select a deletion method"
@@ -9,7 +9,7 @@ import Ip, { submitIp, updateIp } from './ip.svelte';
import String, { submitString, updateString } from './string.svelte';
import Url, { submitUrl, updateUrl } from './url.svelte';
import Datetime, { submitDatetime, updateDatetime } from './datetime.svelte';
import type { Columns } from '../store';
import type { Attributes } from '../store';
import Relationship, { submitRelationship, updateRelationship } from './relationship.svelte';
import {
IconCalendar,
@@ -41,21 +41,21 @@ export type Option = {
type: 'string' | 'integer' | 'double' | 'boolean' | 'datetime' | 'relationship';
create: (
databaseId: string,
tableId: string,
collectionId: string,
key: string,
data: Partial<Columns>
data: Partial<Attributes>
) => Promise<void>;
update: (
databaseId: string,
tableId: string,
data: Partial<Columns>,
collectionId: string,
data: Partial<Attributes>,
originalKey: string
) => Promise<void>;
format?: 'email' | 'ip' | 'url' | 'enum';
icon: ComponentType;
};
export const columnOptions: Option[] = [
export const attributeOptions: Option[] = [
{
name: 'String',
sentenceName: 'string',
@@ -5,15 +5,15 @@
export async function submitString(
databaseId: string,
tableId: string,
collectionId: string,
key: string,
data: Partial<Models.ColumnString>
data: Partial<Models.AttributeString>
) {
await sdk
.forProject(page.params.region, page.params.project)
.tables.createStringColumn(
.databases.createStringAttribute(
databaseId,
tableId,
collectionId,
key,
data.size,
data.required,
@@ -24,15 +24,15 @@
}
export async function updateString(
databaseId: string,
tableId: string,
data: Partial<Models.ColumnString>,
collectionId: string,
data: Partial<Models.AttributeString>,
originalKey?: string
) {
await sdk
.forProject(page.params.region, page.params.project)
.tables.updateStringColumn(
.databases.updateStringAttribute(
databaseId,
tableId,
collectionId,
originalKey,
data.required,
data.default,
@@ -51,7 +51,7 @@
import { InputNumber, InputText, InputTextarea } from '$lib/elements/forms';
import { Popover, Layout, Tag, Typography, Link } from '@appwrite.io/pink-svelte';
export let data: Partial<Models.ColumnString> = {
export let data: Partial<Models.AttributeString> = {
required: false,
size: 0,
array: false,
@@ -74,7 +74,7 @@
const {
stores: { required, array },
listen
} = createConservative<Partial<Models.ColumnString>>({
} = createConservative<Partial<Models.AttributeString>>({
required: false,
array: false,
...data
@@ -96,7 +96,7 @@
bind:value={data.size}
min={supportsStringEncryption && data.encrypt ? 150 : undefined}
helper={supportsStringEncryption && data.encrypt
? 'Encrypted string columns require a minimum size of 150.'
? 'Encrypted string attributes require a minimum size of 150.'
: undefined} />
<svelte:component
@@ -115,7 +115,7 @@
label="Required"
bind:checked={data.required}
disabled={data.array}
description="Indicate whether this column is required." />
description="Indicate whether this attribute is required." />
<Selector.Checkbox
size="s"
@@ -123,7 +123,7 @@
label="Array"
bind:checked={data.array}
disabled={data.required || editing}
description="Indicate whether this column is an array. Defaults to an empty array." />
description="Indicate whether this attribute is an array. Defaults to an empty array." />
<Layout.Stack gap="xs" direction="column">
<div
@@ -167,7 +167,7 @@
<ActionMenu.Root width="180px" slot="tooltip">
<Typography.Text variant="m-500">
Available on Pro plan. <Link.Anchor href={$upgradeURL}>Upgrade</Link.Anchor>
to enable encrypted columns.
to enable encrypted attributes.
</Typography.Text>
</ActionMenu.Root>
</Popover>
@@ -5,15 +5,15 @@
export async function submitUrl(
databaseId: string,
tableId: string,
collectionId: string,
key: string,
data: Partial<Models.ColumnUrl>
data: Partial<Models.AttributeUrl>
) {
await sdk
.forProject(page.params.region, page.params.project)
.tables.createUrlColumn(
.databases.createUrlAttribute(
databaseId,
tableId,
collectionId,
key,
data.required,
data.default,
@@ -23,15 +23,15 @@
export async function updateUrl(
databaseId: string,
tableId: string,
data: Partial<Models.ColumnUrl>,
collectionId: string,
data: Partial<Models.AttributeUrl>,
originalKey?: string
) {
await sdk
.forProject(page.params.region, page.params.project)
.tables.updateUrlColumn(
.databases.updateUrlAttribute(
databaseId,
tableId,
collectionId,
originalKey,
data.required,
data.default,
@@ -43,7 +43,7 @@
<script lang="ts">
import { InputURL } from '$lib/elements/forms';
export let data: Partial<Models.ColumnUrl>;
export let data: Partial<Models.AttributeUrl>;
export let editing = false;
import { createConservative } from '$lib/helpers/stores';
@@ -63,7 +63,7 @@
const {
stores: { required, array },
listen
} = createConservative<Partial<Models.ColumnUrl>>({
} = createConservative<Partial<Models.AttributeUrl>>({
required: false,
array: false,
...data
@@ -3,7 +3,7 @@
import { page } from '$app/state';
import { Breadcrumbs } from '$lib/layout';
import { database } from '../store';
import { table } from './store';
import { collection } from './store';
$: breadcrumbs = [
{
@@ -18,8 +18,8 @@
title: $database?.name
},
{
href: `${base}/project-${page.params.region}-${page.params.project}/databases/database-${$database?.$id}/table-${$table?.$id}`,
title: $table?.name
href: `${base}/project-${page.params.region}-${page.params.project}/databases/database-${$database?.$id}/collection-${$collection?.$id}`,
title: $collection?.name
}
];
</script>
@@ -10,10 +10,10 @@
import { Submit, trackError, trackEvent } from '$lib/actions/analytics';
import { addNotification } from '$lib/stores/notifications';
import { writable } from 'svelte/store';
import ColumnForm from '../row-[row]/columnForm.svelte';
import AttributeForm from '../document-[document]/attributeForm.svelte';
import { Permissions } from '$lib/components/permissions';
import type { PageData } from './$types';
import type { Columns } from '../store';
import type { Attributes } from '../store';
import { ID } from '@appwrite.io/console';
export let data: PageData;
@@ -24,66 +24,68 @@
type CreateDocument = {
id?: string;
row: object;
document: object;
permissions: string[];
columns: Columns[];
attributes: Attributes[];
};
function createRowWritable() {
const availableColumns = (data.table.columns as unknown as Columns[]).filter(
function createDocumentWritable() {
const availableAttributes = (data.collection.attributes as unknown as Attributes[]).filter(
(a) => a.status === 'available'
);
const initial = {
id: null,
row: availableColumns.reduce((acc, attr) => {
document: availableAttributes.reduce((acc, attr) => {
acc[attr.key] = attr.array ? [] : null;
return acc;
}, {}),
permissions: [],
columns: availableColumns
attributes: availableAttributes
};
return writable<CreateDocument>({ ...initial });
const store = writable<CreateDocument>({ ...initial });
return store;
}
const createRow = createRowWritable();
const createDocument = createDocumentWritable();
async function create() {
try {
const { $id } = await sdk
.forProject(page.params.region, page.params.project)
.tables.createRow(
.databases.createDocument(
page.params.database,
page.params.table,
$createRow.id ?? ID.unique(),
$createRow.row,
$createRow.permissions
page.params.collection,
$createDocument.id ?? ID.unique(),
$createDocument.document,
$createDocument.permissions
);
addNotification({
message: 'Row has been created',
message: 'Document has been created',
type: 'success'
});
trackEvent(Submit.RowCreate, {
customId: !!$createRow.id // todo: @itznotabug - change store name
trackEvent(Submit.DocumentCreate, {
customId: !!$createDocument.id
});
goto(
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${page.params.database}/table-${page.params.table}/row-${$id}`
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${page.params.database}/collection-${page.params.collection}/document-${$id}`
);
} catch (error) {
addNotification({
message: error.message,
type: 'error'
});
trackError(error, Submit.RowCreate);
trackError(error, Submit.DocumentCreate);
}
}
</script>
<Wizard
title="Create row"
href={`${base}/project-${page.params.region}-${page.params.project}/databases/database-${page.params.database}/table-${page.params.table}`}
title="Create document"
href={`${base}/project-${page.params.region}-${page.params.project}/databases/database-${page.params.database}/collection-${page.params.collection}/`}
bind:showExitModal
column
columnSize="s"
@@ -91,10 +93,10 @@
<Form bind:this={formComponent} onSubmit={create} bind:isSubmitting>
<Layout.Stack gap="xxl">
<Fieldset legend="Data">
<ColumnForm
bind:formValues={$createRow.row}
columns={$createRow.columns}
bind:customId={$createRow.id} />
<AttributeForm
bind:formValues={$createDocument.document}
attributes={$createDocument.attributes}
bind:customId={$createDocument.id} />
</Fieldset>
<Fieldset legend="Permissions">
@@ -103,18 +105,21 @@
Choose which permission scopes to grant your application. It is best
practice to allow only the permissions you need to meet your project goals.
</Typography.Text>
{#if data.table.rowSecurity}
{#if data.collection.documentSecurity}
<Alert.Inline status="info">
<svelte:fragment slot="title">Row security is enabled</svelte:fragment>
Users will be able to access this row if they have been granted
<b>either row or table permissions</b>.
<svelte:fragment slot="title"
>Document security is enabled</svelte:fragment>
Users will be able to access this document if they have been granted
<b>either document or collection permissions</b>.
</Alert.Inline>
<Permissions bind:permissions={$createRow.permissions} />
<Permissions bind:permissions={$createDocument.permissions} />
{:else}
<Alert.Inline status="info">
<svelte:fragment slot="title">Row security is disabled</svelte:fragment>
If you want to assign row permissions, navigate to Table settings and enable
row security. Otherwise, only table permissions will be used.
<svelte:fragment slot="title"
>Document security is disabled</svelte:fragment>
If you want to assign document permissions, navigate to Collection settings
and enable document security. Otherwise, only collection permissions will
be used.
</Alert.Inline>
{/if}
</Layout.Stack>
@@ -1,27 +1,22 @@
<script lang="ts">
import { Modal } from '$lib/components';
import {
option,
columnOptions,
type Option
} from '$routes/(console)/project-[region]-[project]/databases/database-[database]/table-[table]/columns/store';
import { option, attributeOptions, type Option } from './attributes/store';
import { Button, InputText } from '$lib/elements/forms';
import { goto, invalidate } from '$app/navigation';
import { Dependencies } from '$lib/constants';
import { page } from '$app/state';
import { addNotification } from '$lib/stores/notifications';
import { base } from '$app/paths';
import type { Columns } from './store';
import type { Attributes } from './store';
import { Submit, trackEvent, trackError } from '$lib/actions/analytics';
export let showCreate = false;
export let selectedOption: Option['name'] = null;
$: tableId = page.params.table;
const databaseId = page.params.database;
$: collectionId = page.params.collection;
let key: string = null;
let data: Partial<Columns> = {
let data: Partial<Attributes> = {
required: false,
array: false,
default: null
@@ -30,28 +25,28 @@
async function submit() {
try {
await $option.create(databaseId, tableId, key, data);
await invalidate(Dependencies.TABLE);
await $option.create(databaseId, collectionId, key, data);
await invalidate(Dependencies.COLLECTION);
if (!page.url.pathname.includes('columns')) {
if (!page.url.pathname.includes('attributes')) {
await goto(
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${databaseId}/table-${tableId}/columns`
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${databaseId}/collection-${collectionId}/attributes`
);
}
addNotification({
type: 'success',
message: `Column ${key ?? data?.key} has been created`
message: `Attribute ${key ?? data?.key} has been created`
});
showCreate = false;
trackEvent(Submit.ColumnCreate);
trackEvent(Submit.AttributeCreate);
} catch (e) {
error = e.message;
trackError(e, Submit.ColumnCreate);
trackError(e, Submit.AttributeCreate);
}
}
$: if (selectedOption) {
$option = columnOptions.find((option) => option.name === selectedOption);
$option = attributeOptions.find((option) => option.name === selectedOption);
}
$: if (!showCreate) {
@@ -66,14 +61,14 @@
};
}
$: title = `Create ${columnOptions.find((option) => option.name === selectedOption)?.sentenceName ?? ''} column`;
$: title = `Create ${attributeOptions.find((option) => option.name === selectedOption)?.sentenceName ?? ''} attribute`;
</script>
<Modal {error} bind:show={showCreate} onSubmit={submit} {title}>
{#if selectedOption !== 'Relationship'}
<InputText
id="key"
label="Column key"
label="Attribute key"
placeholder="Enter key"
bind:value={key}
autofocus
@@ -3,35 +3,40 @@ import { Dependencies } from '$lib/constants';
import type { LayoutLoad } from './$types';
import Breadcrumbs from './breadcrumbs.svelte';
import Header from './header.svelte';
import type { Columns } from '../store';
import { buildWildcardColumnsQuery } from './columns/store';
import type { Attributes } from '../store';
import { buildWildcardAttributesQuery } from './attributes/store';
export const load: LayoutLoad = async ({ params, parent, depends }) => {
depends(Dependencies.ROW);
const { table } = await parent();
const { collection } = await parent();
depends(Dependencies.DOCUMENT);
const row = await sdk
const document = await sdk
.forProject(params.region, params.project)
.tables.getRow(params.database, params.table, params.row, buildWildcardColumnsQuery(table));
.databases.getDocument(
params.database,
params.collection,
params.document,
buildWildcardAttributesQuery(collection)
);
/**
* Sanitize DateTime to remove UTC Timezone section.
*/
table.columns.forEach((column) => {
const { type, key, array } = column as unknown as Columns;
collection.attributes.forEach((attribute) => {
const { type, key, array } = attribute as unknown as Attributes;
if (type === 'datetime') {
if (array) {
row[key] = row[key].map((n: string) => {
document[key] = document[key].map((n: string) => {
if (!n) {
return null;
}
return new Date(n).toISOString().slice(0, 23);
});
} else {
if (row[key]) {
row[key] = new Date(row[key]).toISOString().slice(0, 23);
if (document[key]) {
document[key] = new Date(document[key]).toISOString().slice(0, 23);
} else {
row[key] = null;
document[key] = null;
}
}
}
@@ -40,6 +45,6 @@ export const load: LayoutLoad = async ({ params, parent, depends }) => {
return {
header: Header,
breadcrumbs: Breadcrumbs,
row
document
};
};
@@ -11,38 +11,36 @@
import type { Models } from '@appwrite.io/console';
import { Dependencies } from '$lib/constants';
import { invalidate } from '$app/navigation';
import { table, type Columns } from '../store';
import ColumnItem from './columnItem.svelte';
import { isRelationship, isRelationshipToMany } from './columns/store';
import { doc } from './store';
import { collection, type Attributes } from '../store';
import AttributeItem from './attributeItem.svelte';
import { isRelationship, isRelationshipToMany } from './attributes/store';
import { deepClone } from '$lib/helpers/object';
export let data;
const row = data.row;
const databaseId = page.params.database;
const tableId = page.params.table;
const rowId = page.params.row;
const collectionId = page.params.collection;
const documentId = page.params.document;
function initWork() {
const prohibitedKeys = [
'$id',
'$collection',
'$tableId',
'$collectionId',
'$databaseId',
'$createdAt',
'$updatedAt'
];
const filteredKeys = Object.keys(row).filter((key) => {
const filteredKeys = Object.keys($doc).filter((key) => {
return !prohibitedKeys.includes(key);
});
const result = filteredKeys.reduce((obj, key) => {
obj[key] = row[key];
obj[key] = $doc[key];
return obj;
}, {});
return writable(deepClone(result as Models.Row));
return writable(deepClone(result as Models.Document));
}
const work = initWork();
@@ -51,12 +49,18 @@
try {
await sdk
.forProject(page.params.region, page.params.project)
.tables.updateRow(databaseId, tableId, rowId, $work, $work.$permissions);
.databases.updateDocument(
databaseId,
collectionId,
documentId,
$work,
$work.$permissions
);
invalidate(Dependencies.ROW);
trackEvent(Submit.RowUpdate);
invalidate(Dependencies.DOCUMENT);
trackEvent(Submit.DocumentUpdate);
addNotification({
message: 'Row has been updated',
message: 'Document has been updated',
type: 'success'
});
} catch (error) {
@@ -64,46 +68,46 @@
message: error.message,
type: 'error'
});
trackError(error, Submit.RowUpdate);
trackError(error, Submit.DocumentUpdate);
}
}
function compareColumns(column: Columns, related: Models.Row, row: Models.Row) {
if (!column) {
function compareAttributes(
attribute: Attributes,
$work: Models.Document,
$doc: Models.Document
) {
if (!attribute) {
return false;
}
const rowColumn = row?.[column.key];
const relatedColumn = related?.[column.key];
const workAttribute = $work?.[attribute.key];
const docAttribute = $doc?.[attribute.key];
// undefined for a second, not sure why!
if (rowColumn === undefined || relatedColumn === undefined) {
return false;
if (attribute.array) {
return !symmetricDifference(Array.from(workAttribute), Array.from(docAttribute)).length;
}
if (column.array) {
return !symmetricDifference(Array.from(relatedColumn), Array.from(rowColumn)).length;
}
if (isRelationship(column)) {
if (isRelationshipToMany(column as Models.ColumnRelationship)) {
const workIds = relatedColumn.map((doc: string | Record<string, unknown>) =>
if (isRelationship(attribute)) {
if (isRelationshipToMany(attribute as Models.AttributeRelationship)) {
const workIds = workAttribute.map((doc: string | Record<string, unknown>) =>
typeof doc === 'string' ? doc : doc.$id
);
const relatedIds = rowColumn.map((doc: string | Record<string, unknown>) =>
const relatedIds = docAttribute.map((doc: string | Record<string, unknown>) =>
typeof doc === 'string' ? doc : doc.$id
);
return !symmetricDifference(workIds, relatedIds).length;
} else {
const workId =
typeof relatedColumn === 'string' ? relatedColumn : relatedColumn?.$id;
const relatedId = typeof rowColumn === 'string' ? rowColumn : rowColumn?.$id;
typeof workAttribute === 'string' ? workAttribute : workAttribute?.$id;
const relatedId =
typeof docAttribute === 'string' ? docAttribute : docAttribute?.$id;
return workId === relatedId;
}
}
return relatedColumn === rowColumn;
return workAttribute === docAttribute;
}
</script>
@@ -112,19 +116,19 @@
</svelte:head>
<Container>
{#if $table?.columns?.length}
{#each $table.columns as column}
{@const label = column.key}
{#if $collection?.attributes?.length}
{#each $collection.attributes as attribute}
{@const label = attribute.key}
<CardGrid>
<svelte:fragment slot="title">{label}</svelte:fragment>
<svelte:fragment slot="aside">
<ColumnItem {column} bind:formValues={$work} {label} editing />
<AttributeItem {attribute} bind:formValues={$work} {label} editing />
</svelte:fragment>
<svelte:fragment slot="actions">
<Button
disabled={compareColumns(column, $work, row)}
disabled={compareAttributes(attribute, $work, $doc)}
on:click={() => updateData()}>Update</Button>
</svelte:fragment>
</CardGrid>
@@ -14,7 +14,7 @@ export const load: PageLoad = async ({ params, url, route }) => {
limit,
logs: await sdk
.forProject(params.region, params.project)
.tables.listRowLogs(params.database, params.table, params.row, [
.databases.listDocumentLogs(params.database, params.collection, params.document, [
Query.limit(limit),
Query.offset(offset)
])
@@ -0,0 +1,63 @@
<script lang="ts">
import type { Models } from '@appwrite.io/console';
import Boolean from './attributes/boolean.svelte';
import Datetime from './attributes/datetime.svelte';
import Enum from './attributes/enum.svelte';
import Integer from './attributes/integer.svelte';
import Relationship from './attributes/relationship.svelte';
import String from './attributes/string.svelte';
import Url from './attributes/url.svelte';
export let id: string;
export let label: string;
export let optionalText: string | undefined = undefined;
export let value: string | number | boolean | null | string[];
export let editing = false;
export let attribute:
| Models.AttributeBoolean
| Models.AttributeEmail
| Models.AttributeEnum
| Models.AttributeFloat
| Models.AttributeInteger
| Models.AttributeIp
| Models.AttributeString
| Models.AttributeDatetime
| Models.AttributeUrl;
const attributesTypeMap = {
string: String,
integer: Integer,
double: Integer,
boolean: Boolean,
datetime: Datetime,
relationship: Relationship
};
const attributesFormatMap = {
ip: String,
url: Url,
email: String,
enum: Enum
};
</script>
{#if attribute.type in attributesTypeMap}
{#if 'format' in attribute && attribute.format}
<svelte:component
this={attributesFormatMap[attribute.format]}
{id}
{label}
{attribute}
{optionalText}
bind:value />
{:else}
<svelte:component
this={attributesTypeMap[attribute.type]}
{id}
{editing}
{label}
{attribute}
{optionalText}
bind:value />
{/if}
{/if}
@@ -1,22 +1,22 @@
<script lang="ts">
import CustomId from '$lib/components/customId.svelte';
import { Icon, Layout, Tag } from '@appwrite.io/pink-svelte';
import type { Columns } from '../store';
import ColumnItem from './columnItem.svelte';
import type { Attributes } from '../store';
import AttributeItem from './attributeItem.svelte';
import { IconPencil } from '@appwrite.io/pink-icons-svelte';
export let columns: Columns[] = [];
export let attributes: Attributes[] = [];
export let formValues: object = {};
export let customId: string | null | undefined = undefined;
let showCustomId = false;
</script>
{#if columns.length}
{#if attributes.length}
<Layout.Stack>
{#each columns as column}
{@const label = column.key}
<ColumnItem {column} bind:formValues {label} />
{#each attributes as attribute}
{@const label = attribute.key}
<AttributeItem {attribute} bind:formValues {label} />
{/each}
{#if customId !== undefined}
@@ -24,11 +24,11 @@
<span>
<Tag size="s" on:click={() => (showCustomId = !showCustomId)}>
<Icon icon={IconPencil} slot="start" size="s" />
Row ID
Document ID
</Tag>
</span>
{:else}
<CustomId autofocus bind:show={showCustomId} name="Row" bind:id={customId} />
<CustomId autofocus bind:show={showCustomId} name="Document" bind:id={customId} />
{/if}
{/if}
</Layout.Stack>
@@ -3,10 +3,10 @@
import { capitalize } from '$lib/helpers/string';
import { Icon, Layout, Typography } from '@appwrite.io/pink-svelte';
import { IconPlus } from '@appwrite.io/pink-icons-svelte';
import Column from './column.svelte';
import type { Columns } from '../store';
import Attribute from './attribute.svelte';
import type { Attributes } from '../store';
export let column: Columns;
export let attribute: Attributes;
export let formValues: object = {};
export let label: string;
export let editing = false;
@@ -25,9 +25,9 @@
};
}
function getColumnType(column: Columns) {
if ('format' in column) {
switch (column.format) {
function getAttributeType(attribute: Attributes) {
if ('format' in attribute) {
switch (attribute.format) {
case 'ip':
return 'IP';
case 'email':
@@ -41,41 +41,41 @@
break;
}
}
return `${capitalize(column.type)}${column.array ? '[]' : ''}`;
return `${capitalize(attribute.type)}${attribute.array ? '[]' : ''}`;
}
</script>
{#if column.array}
{#if formValues[column.key]?.length === 0}
{#if attribute.array}
{#if formValues[attribute.key]?.length === 0}
<Layout.Stack direction="row" alignContent="space-between">
<Layout.Stack gap="xxs" direction="row" alignItems="center">
<Typography.Text variant="m-500">{label}</Typography.Text>
<Typography.Text variant="m-400" color="--fgcolor-neutral-tertiary">
{getColumnType(column)}
{getAttributeType(attribute)}
</Typography.Text>
</Layout.Stack>
<Button secondary on:click={() => addArrayItem(column.key)}>
<Button secondary on:click={() => addArrayItem(attribute.key)}>
<Icon icon={IconPlus} slot="start" size="s" />
Add item
</Button>
</Layout.Stack>
{:else}
<Layout.Stack>
{#each [...(formValues[column.key]?.keys() ?? [])] as index}
{#each [...formValues[attribute.key].keys()] as index}
<Layout.Stack direction="row" alignItems="flex-end" gap="xs">
<Column
{column}
id={`${column.key}-${index}`}
optionalText={index === 0 ? getColumnType(column) : undefined}
<Attribute
{attribute}
id={`${attribute.key}-${index}`}
optionalText={index === 0 ? getAttributeType(attribute) : undefined}
label={index === 0 ? label : ''}
bind:value={formValues[column.key][index]} />
<Button text icon on:click={() => removeArrayItem(column.key, index)}>
bind:value={formValues[attribute.key][index]} />
<Button text icon on:click={() => removeArrayItem(attribute.key, index)}>
<span class="icon-x" aria-hidden="true"></span>
</Button>
</Layout.Stack>
{/each}
<div>
<Button secondary on:click={() => addArrayItem(column.key)}>
<Button secondary on:click={() => addArrayItem(attribute.key)}>
<Icon icon={IconPlus} slot="start" size="s" />
Add item
</Button>
@@ -83,11 +83,11 @@
</Layout.Stack>
{/if}
{:else}
<Column
{label}
<Attribute
{editing}
{column}
id={column.key}
optionalText={getColumnType(column)}
bind:value={formValues[column.key]} />
{attribute}
{label}
optionalText={getAttributeType(attribute)}
id={attribute.key}
bind:value={formValues[attribute.key]} />
{/if}
@@ -5,7 +5,7 @@
export let id: string;
export let label: string;
export let value: boolean;
export let column: Models.ColumnBoolean;
export let attribute: Models.AttributeBoolean;
export let optionalText: string | undefined = undefined;
</script>
@@ -15,9 +15,9 @@
bind:value
{optionalText}
placeholder="Select a value"
required={column.required}
required={attribute.required}
options={[
!column.required && { label: 'NULL', value: null },
!attribute.required && { label: 'NULL', value: null },
{ label: 'True', value: true },
{ label: 'False', value: false }
].filter(Boolean)} />
@@ -5,7 +5,7 @@
export let id: string;
export let label: string;
export let value: string;
export let column: Models.ColumnDatetime;
export let attribute: Models.AttributeDatetime;
export let type: 'date' | 'time' | 'datetime-local' = 'datetime-local';
</script>
@@ -14,5 +14,5 @@
{label}
{type}
bind:value
required={column.required}
nullable={!column.required} />
required={attribute.required}
nullable={!attribute.required} />
@@ -5,7 +5,7 @@
export let id: string;
export let label: string;
export let value: string | null;
export let column: Models.ColumnEmail;
export let attribute: Models.AttributeUrl;
</script>
<InputEmail
@@ -13,5 +13,5 @@
{label}
bind:value
placeholder="Enter URL"
required={column.required}
nullable={!column.required} />
required={attribute.required}
nullable={!attribute.required} />
@@ -5,17 +5,17 @@
export let id: string;
export let label: string;
export let value: string;
export let column: Models.ColumnEnum;
export let attribute: Models.AttributeEnum;
export let optionalText: string | undefined = undefined;
$: options = [
...column.elements.map((element) => {
...attribute.elements.map((element) => {
return {
label: element,
value: element
};
}),
!column.required && {
!attribute.required && {
label: 'NULL',
value: null
}
@@ -28,5 +28,5 @@
{id}
{label}
{optionalText}
required={column.required}
required={attribute.required}
placeholder="Select a value" />
@@ -5,15 +5,15 @@
export let id: string;
export let label: string;
export let value: number;
export let column: Models.ColumnInteger;
export let attribute: Models.AttributeInteger;
</script>
<InputNumber
{id}
{label}
bind:value
min={column.min}
max={column.max}
required={column.required}
nullable={!column.required}
step={column.type === 'double' ? 'any' : 1} />
min={attribute.min}
max={attribute.max}
required={attribute.required}
nullable={!attribute.required}
step={attribute.type === 'double' ? 'any' : 1} />
@@ -5,7 +5,7 @@
import { sdk } from '$lib/stores/sdk';
import { Query, type Models } from '@appwrite.io/console';
import { onMount } from 'svelte';
import { row } from '../store';
import { doc } from '../store';
import { isRelationshipToMany } from './store';
import { IconPlus, IconX } from '@appwrite.io/pink-icons-svelte';
import { Icon, Layout, Typography } from '@appwrite.io/pink-svelte';
@@ -15,12 +15,12 @@
export let editing = false;
export let value: string | string[];
export let column: Models.ColumnRelationship;
export let attribute: Models.AttributeRelationship;
export let optionalText: string | undefined = undefined;
const databaseId = page.params.database;
let rowList: Models.RowList<Models.Row>;
let documentList: Models.DocumentList<Models.Document>;
let search: string = null;
let displayNames = ['$id'];
let relatedList: string[] = [];
@@ -32,38 +32,38 @@
onMount(async () => {
if (value) {
if (isRelationshipToMany(column)) {
if (isRelationshipToMany(attribute)) {
relatedList = (value as string[]).slice();
} else {
singleRel = value as string;
}
}
if (editing && $row?.[column.key]) {
if ($row[column.key]?.length) {
if (editing && $doc?.[attribute.key]) {
if ($doc[attribute.key]?.length) {
relatedList =
$row[column.key]?.map((d: Record<string, unknown>) => {
$doc[attribute.key]?.map((d: Record<string, unknown>) => {
return d?.$id;
}) ?? [];
} else {
singleRel = $row[column.key]?.$id;
singleRel = $doc[attribute.key]?.$id;
}
}
displayNames = preferences.getDisplayNames()?.[column?.relatedTable] ?? ['$id'];
displayNames = preferences.getDisplayNames()?.[attribute?.relatedCollection] ?? ['$id'];
if (!displayNames?.includes('$id')) {
displayNames.unshift('$id');
}
});
async function getRows(search: string = null) {
async function getDocuments(search: string = null) {
const queries = search
? [Query.select(['$id']), Query.startsWith('$id', search), Query.orderDesc('')]
: [Query.select(['$id'])];
return await sdk
.forProject(page.params.region, page.params.project)
.tables.listRows(databaseId, column.relatedTable, queries);
.databases.listDocuments(databaseId, attribute.relatedCollection, queries);
}
function getAvailableOptions(excludeIndex?: number) {
@@ -105,7 +105,7 @@
}
// Reactive statements
$: getRows(search).then((res) => (rowList = res));
$: getDocuments(search).then((res) => (documentList = res));
$: paginatedItems = editing
? relatedList
@@ -117,10 +117,10 @@
$: totalCount = relatedList?.length ?? 0;
$: options =
rowList?.rows?.map((row) => {
documentList?.documents?.map((document) => {
const names = displayNames.filter((name) => name !== '$id');
const values = names
.map((name) => row?.[name])
.map((name) => document?.[name])
// always supposed to be a string but just being a bit safe here
.filter((value) => value != null && typeof value === 'string' && value !== '');
@@ -130,15 +130,15 @@
values.map((value) => (value.length > 5 ? value.slice(0, 5) + '...' : value));
const label = !values.length
? row.$id
? document.$id
: // values are in `$id (a | b)` format
// previously used to have a `$id a | b`.
`${row.$id} (${displayValues.join(' | ')})`;
`${document.$id} (${displayValues.join(' | ')})`;
return {
label,
value: row.$id,
data: names.map((name) => row?.[name])
value: document.$id,
data: names.map((name) => document?.[name])
};
}) ?? [];
@@ -150,7 +150,7 @@
$: showEmptyInput = editing && totalCount === 0 && !showInput;
</script>
{#if isRelationshipToMany(column)}
{#if isRelationshipToMany(attribute)}
<Layout.Stack gap="xxl">
<Layout.Stack gap="m">
<Layout.Stack direction="row" alignContent="space-between">
@@ -178,7 +178,7 @@
required
{options}
bind:value={relatedList[0]}
placeholder={`Select ${column.key}`}
placeholder={`Select ${attribute.key}`}
on:change={() => {
if (!relatedList[0]) relatedList = [''];
updateRelatedList();
@@ -196,7 +196,7 @@
required
options={getAvailableOptions(actualIndex)}
bind:value={relatedList[actualIndex]}
placeholder={`Select ${column.key}`}
placeholder={`Select ${attribute.key}`}
on:change={updateRelatedList} />
{#if relatedList[actualIndex]}
<div style:padding-block-start="0.5rem">
@@ -244,7 +244,7 @@
<InputSelect
{id}
required
placeholder={`Select ${column.key}`}
placeholder={`Select ${attribute.key}`}
bind:value={newItemValue}
options={getAvailableOptions()}
on:change={addNewItem} />
@@ -272,8 +272,8 @@
{id}
{label}
{options}
required={column.required}
placeholder={`Select ${column.key}`}
required={attribute.required}
placeholder={`Select ${attribute.key}`}
bind:value={singleRel}
on:change={() => (value = singleRel)} />
{/if}
@@ -0,0 +1,37 @@
import { type Models, Query } from '@appwrite.io/console';
import type { Attributes } from '../../store';
export function isRelationshipToMany(attribute: Models.AttributeRelationship) {
if (!attribute) return false;
if (!attribute?.relationType) return false;
if (attribute?.side === 'child') {
return !['oneToOne', 'oneToMany'].includes(attribute?.relationType);
} else {
return !['oneToOne', 'manyToOne'].includes(attribute?.relationType);
}
}
export function isRelationship(attribute: Attributes): attribute is Models.AttributeRelationship {
if (!attribute) return false;
return attribute?.type === 'relationship';
}
export function isString(attribute: Attributes): attribute is Models.AttributeString {
if (!attribute) return false;
return attribute?.type === 'string';
}
/**
* Returns select queries for all main and related fields in a collection.
*/
export function buildWildcardAttributesQuery(
collection: Models.Collection | null = null
): string[] {
return [
...(collection?.attributes
?.filter((attr) => isRelationship(attr))
?.map((attr) => Query.select([`${attr.key}.*`])) ?? []),
Query.select(['*'])
];
}
@@ -5,25 +5,25 @@
export let id: string;
export let label: string;
export let value: string;
export let column: Models.ColumnString;
export let attribute: Models.AttributeString;
</script>
{#if column.size >= 50}
{#if attribute.size >= 50}
<InputTextarea
{id}
{label}
bind:value
placeholder="Enter string"
maxlength={column.size}
required={column.required}
nullable={!column.required} />
maxlength={attribute.size}
required={attribute.required}
nullable={!attribute.required} />
{:else}
<InputText
{id}
{label}
bind:value
placeholder="Enter string"
maxlength={column.size}
required={column.required}
nullable={!column.required} />
maxlength={attribute.size}
required={attribute.required}
nullable={!attribute.required} />
{/if}
@@ -5,7 +5,7 @@
export let id: string;
export let label: string;
export let value: string | null;
export let column: Models.ColumnUrl;
export let attribute: Models.AttributeUrl;
</script>
<InputURL
@@ -13,5 +13,5 @@
{label}
bind:value
placeholder="Enter URL"
required={column.required}
nullable={!column.required} />
required={attribute.required}
nullable={!attribute.required} />
@@ -3,8 +3,8 @@
import { page } from '$app/state';
import { Breadcrumbs } from '$lib/layout';
import { database } from '../../store';
import { table } from '../store';
import { row } from './store';
import { collection } from '../store';
import { doc } from './store';
$: breadcrumbs = [
{
@@ -15,12 +15,12 @@
title: $database?.name
},
{
href: `${base}/project-${page.params.region}-${page.params.project}/databases/database-${$database?.$id}/table-${$table?.$id}`,
title: $table?.name
href: `${base}/project-${page.params.region}-${page.params.project}/databases/database-${$database?.$id}/collection-${$collection?.$id}`,
title: $collection?.name
},
{
href: `${base}/project-${page.params.region}-${page.params.project}/databases/database-${$database?.$id}/table-${$table?.$id}/row-${$row?.$id}`,
title: $row?.$id
href: `${base}/project-${page.params.region}-${page.params.project}/databases/database-${$database?.$id}/collection-${$collection?.$id}/document-${$doc?.$id}`,
title: $doc?.$id
}
];
</script>
@@ -7,9 +7,9 @@
import { Button } from '$lib/elements/forms';
import { addNotification } from '$lib/stores/notifications';
import { sdk } from '$lib/stores/sdk';
import { Alert, Layout, Selector, Table } from '@appwrite.io/pink-svelte';
import { columns, table } from '../store';
import { isRelationship, isRelationshipToMany } from './columns/store';
import { Alert, Selector, Table } from '@appwrite.io/pink-svelte';
import { attributes, collection } from '../store';
import { isRelationship, isRelationshipToMany } from './attributes/store';
import type { Models } from '@appwrite.io/console';
export let showDelete = false;
@@ -20,32 +20,32 @@
try {
await sdk
.forProject(page.params.region, page.params.project)
.tables.deleteRow(databaseId, page.params.table, page.params.row);
.databases.deleteDocument(databaseId, page.params.collection, page.params.document);
showDelete = false;
addNotification({
type: 'success',
message: `Row has been deleted`
message: `Document has been deleted`
});
trackEvent(Submit.RowDelete);
trackEvent(Submit.DocumentDelete);
await goto(
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${page.params.database}/table-${page.params.table}`
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${page.params.database}/collection-${page.params.collection}`
);
} catch (error) {
addNotification({
type: 'error',
message: error.message
});
trackError(error, Submit.RowDelete);
trackError(error, Submit.DocumentDelete);
}
};
enum Deletion {
'setNull' = 'Set row ID as NULL in all related rows',
'cascade' = 'All related rows will be deleted',
'restrict' = 'Row cannot be deleted'
'setNull' = 'Set document ID as NULL in all related documents',
'cascade' = 'All related documents will be deleted',
'restrict' = 'Document cannot be deleted'
}
$: relColumns = $columns?.filter(
$: relAttributes = $attributes?.filter(
(attribute) =>
isRelationship(attribute) &&
// One-to-One are always included
@@ -56,16 +56,18 @@
(attribute.relationType === 'manyToOne' && attribute.side === 'child') ||
// Many-to-Many: Only include if the parent is being deleted
(isRelationshipToMany(attribute) && attribute.side === 'parent'))
) as Models.ColumnRelationship[];
) as Models.AttributeRelationship[];
</script>
<Confirm title="Delete row" onSubmit={handleDelete} bind:open={showDelete}>
<Confirm title="Delete document" onSubmit={handleDelete} bind:open={showDelete}>
<p data-private>
Are you sure you want to delete <b>the row from <span data-private>{$table.name}</span></b>?
Are you sure you want to delete <b
>the document from <span data-private>{$collection.name}</span></b
>?
</p>
{#if relColumns?.length}
<p class="text">This row contains the following relationships:</p>
{#if relAttributes?.length}
<p class="text">This document contains the following relationships:</p>
<Table.Root
let:root
columns={[
@@ -78,7 +80,7 @@
<Table.Header.Cell column="setting" {root}>Setting</Table.Header.Cell>
<Table.Header.Cell column="desc" {root} />
</svelte:fragment>
{#each relColumns as attr}
{#each relAttributes as attr}
<Table.Row.Base {root}>
<Table.Cell column="relations" {root}>
<span class="u-flex u-cross-center u-gap-8">
@@ -99,16 +101,18 @@
</Table.Row.Base>
{/each}
</Table.Root>
<Layout.Stack gap="l">
<div class="u-flex u-flex-vertical u-gap-16">
<Alert.Inline
title="To change these deletion behaviors edit the relationship settings." />
<Selector.Checkbox id="delete" label="Delete row from ${$table.name}" bind:checked />
</Layout.Stack>
<Selector.Checkbox
id="delete"
label={`Delete document from ${$collection.name}`}
bind:checked />
</div>
{/if}
<svelte:fragment slot="footer">
<Button text on:click={() => (showDelete = false)}>Cancel</Button>
<Button danger submit disabled={relColumns?.length && !checked}>Delete</Button>
<Button danger submit disabled={relAttributes?.length && !checked}>Delete</Button>
</svelte:fragment>
</Confirm>
@@ -1,8 +1,8 @@
<script lang="ts">
import { Button } from '$lib/elements/forms';
import { CardGrid } from '$lib/components';
import { table } from '../store';
import { row } from './store';
import { collection } from '../store';
import { doc } from './store';
import { onMount } from 'svelte';
import { page } from '$app/state';
import { sdk } from '$lib/stores/sdk';
@@ -12,52 +12,62 @@
import { Dependencies } from '$lib/constants';
import { invalidate } from '$app/navigation';
import { Submit, trackEvent, trackError } from '$lib/actions/analytics';
import ColumnForm from './columnForm.svelte';
import AttributeForm from './attributeForm.svelte';
let disableUpdate = true;
let currentRow: string;
let currentDoc: string;
const databaseId = page.params.database;
const tableId = page.params.table;
const rowId = page.params.row;
const collectionId = page.params.collection;
const documentId = page.params.document;
const work = writable(
Object.keys($row)
Object.keys($doc)
.filter((key) => {
return ![
'$id',
'$collection',
'$tableId',
'$collectionId',
'$databaseId',
'$createdAt',
'$updatedAt'
].includes(key);
})
.reduce((obj, key) => {
obj[key] = $row[key];
obj[key] = $doc[key];
return obj;
}, {}) as Models.Row
}, {}) as Models.Document
);
onMount(async () => {
currentRow = JSON.stringify($work);
currentDoc = JSON.stringify($work);
});
$: {
disableUpdate = currentRow === JSON.stringify($work);
if (currentDoc !== JSON.stringify($work)) {
disableUpdate = false;
} else {
disableUpdate = true;
}
}
async function updateData() {
try {
await sdk
.forProject(page.params.region, page.params.project)
.tables.updateRow(databaseId, tableId, rowId, $work, $work.$permissions);
await invalidate(Dependencies.ROW);
.databases.updateDocument(
databaseId,
collectionId,
documentId,
$work,
$work.$permissions
);
await invalidate(Dependencies.DOCUMENT);
currentRow = JSON.stringify($work);
trackEvent(Submit.RowUpdate);
currentDoc = JSON.stringify($work);
trackEvent(Submit.DocumentUpdate);
disableUpdate = true;
addNotification({
message: 'Row has been updated',
message: 'Document has been updated',
type: 'success'
});
} catch (error) {
@@ -65,16 +75,16 @@
message: error.message,
type: 'error'
});
trackError(error, Submit.RowUpdate);
trackError(error, Submit.DocumentUpdate);
}
}
</script>
<CardGrid>
<svelte:fragment slot="title">Data</svelte:fragment>
Update row data based on the columns created earlier.
Update document data based on the attributes created earlier.
<svelte:fragment slot="aside">
<ColumnForm columns={$table.columns} bind:formValues={$work} />
<AttributeForm attributes={$collection.attributes} bind:formValues={$work} />
</svelte:fragment>
<svelte:fragment slot="actions">
@@ -4,14 +4,13 @@
import { Id, Tab, Tabs } from '$lib/components';
import { isTabSelected } from '$lib/helpers/load';
import { Cover, CoverTitle } from '$lib/layout';
import { row } from './store';
import { doc } from './store';
const projectId = page.params.project;
const databaseId = page.params.database;
const tableId = page.params.table;
const rowId = page.params.row;
const path = `${base}/project-${page.params.region}-${page.params.project}/databases/database-${databaseId}/table-${tableId}/row-${rowId}`;
const collectionId = page.params.collection;
const documentId = page.params.document;
const path = `${base}/project-${page.params.region}-${page.params.project}/databases/database-${databaseId}/collection-${collectionId}/document-${documentId}`;
const tabs = [
{
href: path,
@@ -36,10 +35,10 @@
<Cover>
<svelte:fragment slot="header">
<CoverTitle
href={`${base}/project-${page.params.region}-${projectId}/databases/database-${databaseId}/table-${tableId}`}>
{$row?.$id}
href={`${base}/project-${page.params.region}-${projectId}/databases/database-${databaseId}/collection-${collectionId}`}>
{$doc?.$id}
</CoverTitle>
<Id value={$row?.$id} event="row">Row ID</Id>
<Id value={$doc?.$id} event="document">Document ID</Id>
</svelte:fragment>
<Tabs>
@@ -3,7 +3,7 @@
import { Container } from '$lib/layout';
import { Button } from '$lib/elements/forms';
import { sdk } from '$lib/stores/sdk';
import { row } from '../store';
import { doc } from '../store';
import { addNotification } from '$lib/stores/notifications';
import { toLocaleDateTime } from '$lib/helpers/date';
import Delete from '../delete.svelte';
@@ -12,49 +12,48 @@
import { invalidate } from '$app/navigation';
import { Dependencies } from '$lib/constants';
import { Submit, trackEvent, trackError } from '$lib/actions/analytics';
import { table } from '../../store';
import { page } from '$app/state';
import { collection } from '../../store';
import { page } from '$app/stores';
let showDelete = false;
let permissions = $row?.$permissions;
let permissions = $doc?.$permissions;
let arePermsDisabled = true;
let showPermissionAlert = true;
async function updatePermissions() {
try {
await sdk
.forProject(page.params.region, page.params.project)
.tables.updateRow(
$row.$databaseId,
$row.$tableId,
$row.$id,
$row.data,
.forProject($page.params.region, $page.params.project)
.databases.updateDocument(
$doc.$databaseId,
$doc.$collectionId,
$doc.$id,
$doc.data,
permissions
);
await invalidate(Dependencies.ROW);
await invalidate(Dependencies.DOCUMENT);
arePermsDisabled = true;
addNotification({
message: 'Permissions have been updated',
type: 'success'
});
trackEvent(Submit.RowUpdatePermissions);
trackEvent(Submit.DocumentUpdatePermissions);
} catch (error) {
addNotification({
message: error.message,
type: 'error'
});
trackError(error, Submit.RowUpdatePermissions);
trackError(error, Submit.DocumentUpdatePermissions);
}
}
$: if (permissions) {
arePermsDisabled = !symmetricDifference(permissions, $row.$permissions).length;
arePermsDisabled = !symmetricDifference(permissions, $doc.$permissions).length;
}
</script>
<svelte:head>
<title>Row - Appwrite</title>
<title>Document - Appwrite</title>
</svelte:head>
<Container>
@@ -63,8 +62,8 @@
<svelte:fragment slot="aside">
<div>
<p>Created: {toLocaleDateTime($row.$createdAt)}</p>
<p>Last updated: {toLocaleDateTime($row.$updatedAt)}</p>
<p>Created: {toLocaleDateTime($doc.$createdAt)}</p>
<p>Last updated: {toLocaleDateTime($doc.$updatedAt)}</p>
</div>
</svelte:fragment>
</CardGrid>
@@ -72,9 +71,9 @@
<svelte:fragment slot="title">Permissions</svelte:fragment>
<p>
A user requires appropriate permissions at either the <b>table level</b> or
<b>row level</b> to access a row. If no permissions are configured, no user can access
the row
A user requires appropriate permissions at either the <b>collection level</b> or
<b>document level</b> to access a document. If no permissions are configured, no user
can access the document
<a
href="https://appwrite.io/docs/products/databases/permissions"
target="_blank"
@@ -84,13 +83,13 @@
</p>
<svelte:fragment slot="aside">
{#if $table.rowSecurity}
{#if $collection.documentSecurity}
{#if showPermissionAlert}
<Alert type="info" dismissible on:dismiss={() => (showPermissionAlert = false)}>
<svelte:fragment slot="title">Row security is enabled</svelte:fragment>
<svelte:fragment slot="title">Document security is enabled</svelte:fragment>
<p class="text">
Users will be able to access this row if they have been granted <b
>either row or table permissions.
Users will be able to access this document if they have been granted <b
>either document or collection permissions.
</b>
</p>
</Alert>
@@ -100,33 +99,38 @@
{/if}
{:else}
<Alert type="info">
<svelte:fragment slot="title">Row security is disabled</svelte:fragment>
<svelte:fragment slot="title">Document security is disabled</svelte:fragment>
<p class="text">
If you want to assign row permissions. Go to Table settings and enable row
security. Otherwise, only table permissions will be used.
If you want to assign document permissions. Go to Collection settings and
enable document security. Otherwise, only collection permissions will be
used.
</p>
</Alert>
{/if}
</svelte:fragment>
<svelte:fragment slot="actions">
<Button disabled={arePermsDisabled} on:click={updatePermissions}>Update</Button>
<Button
disabled={arePermsDisabled}
on:click={() => {
updatePermissions();
}}>Update</Button>
</svelte:fragment>
</CardGrid>
<CardGrid>
<svelte:fragment slot="title">Delete row</svelte:fragment>
<svelte:fragment slot="title">Delete document</svelte:fragment>
<p>
The row will be permanently deleted, including all the data within it. This action is
irreversible.
The document will be permanently deleted, including all the data within it. This action
is irreversible.
</p>
<svelte:fragment slot="aside">
<BoxAvatar>
<svelte:fragment slot="title">
<h6 class="u-bold u-trim-1">{$row.$id}</h6>
<h6 class="u-bold u-trim-1">{$doc.$id}</h6>
</svelte:fragment>
<p>
Last updated: {toLocaleDateTime($row.$updatedAt)}
Last updated: {toLocaleDateTime($doc.$updatedAt)}
</p>
</BoxAvatar>
</svelte:fragment>
@@ -2,4 +2,4 @@ import { page } from '$app/stores';
import { derived } from 'svelte/store';
import type { Models } from '@appwrite.io/console';
export const row = derived(page, ($page) => $page.data.row as Models.Row);
export const doc = derived(page, ($page) => $page.data.document as Models.Document);
@@ -4,30 +4,33 @@
import { Id, Tab, Tabs } from '$lib/components';
import { isTabSelected } from '$lib/helpers/load';
import { Cover, CoverTitle } from '$lib/layout';
import { canWriteTables } from '$lib/stores/roles';
import { table } from './store';
import { canWriteCollections } from '$lib/stores/roles';
import { collection } from './store';
import { isTabletViewport } from '$lib/stores/viewport';
const databaseId = $derived(page.params.database);
let databaseId = $derived.by(() => {
return page.params.database;
});
let collectionId = $derived.by(() => {
return page.params.collection;
});
const tableId = $derived(page.params.table);
let path = $derived.by(() => {
return `${base}/project-${page.params.region}-${page.params.project}/databases/database-${databaseId}/collection-${collectionId}`;
});
const path = $derived(
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${databaseId}/table-${tableId}`
);
const tabs = $derived(
[
let tabs = $derived.by(() => {
return [
{
href: path,
title: 'Rows',
event: 'rows',
title: 'Documents',
event: 'documents',
hasChildren: true
},
{
href: `${path}/columns`,
title: 'Columns',
event: 'columns'
href: `${path}/attributes`,
title: 'Attributes',
event: 'attributes'
},
{
href: `${path}/indexes`,
@@ -50,10 +53,10 @@
href: `${path}/settings`,
title: 'Settings',
event: 'settings',
disabled: !$canWriteTables
disabled: !$canWriteCollections
}
].filter((tab) => !tab.disabled)
);
].filter((tab) => !tab.disabled);
});
</script>
<div style:margin-top={$isTabletViewport ? '48px' : 0}>
@@ -61,10 +64,10 @@
<svelte:fragment slot="header">
<CoverTitle
href={`${base}/project-${page.params.region}-${page.params.project}/databases/database-${databaseId}`}>
{$table?.name}
{$collection?.name}
</CoverTitle>
{#key $table?.$id}
<Id value={$table?.$id}>{$table?.$id}</Id>
{#key $collection?.$id}
<Id value={$collection?.$id}>{$collection?.$id}</Id>
{/key}
</svelte:fragment>
@@ -1,17 +1,17 @@
<script lang="ts">
import { Empty } from '$lib/components';
import { Container } from '$lib/layout';
import { table } from '../store';
import { collection } from '../store';
import Delete from './deleteIndex.svelte';
import Create from './createIndex.svelte';
import Overview from './overviewIndex.svelte';
import CreateColumn from '../createColumn.svelte';
import CreateAttribute from '../createAttribute.svelte';
import type { Models } from '@appwrite.io/console';
import { Button } from '$lib/elements/forms';
import CreateColumnDropdown from '../columns/createColumnDropdown.svelte';
import type { Option } from '../columns/store';
import CreateAttributeDropdown from '../attributes/createAttributeDropdown.svelte';
import type { Option } from '../attributes/store';
import FailedModal from '../failedModal.svelte';
import { canWriteTables } from '$lib/stores/roles';
import { canWriteCollections } from '$lib/stores/roles';
import {
ActionMenu,
Badge,
@@ -33,16 +33,16 @@
export let data;
let error = '';
let showFailed = false;
let showDelete = false;
let showOverview = false;
let selectedIndex: Models.Index = null;
let showCreateIndex = false;
let showCreateColumn = false;
let selectedColumn: Option['name'] = null;
let selectedIndex: Models.ColumnIndex = null;
let showOverview = false;
let showDelete = false;
let showCreateAttribute = false;
let selectedAttribute: Option['name'] = null;
let showFailed = false;
let error = '';
function getColumnStatusBadge(status: string): ComponentProps<Badge>['type'] {
function getAttributeStatusBadge(status: string): ComponentProps<Badge>['type'] {
switch (status) {
case 'processing':
return 'warning';
@@ -59,10 +59,10 @@
<Container>
<Layout.Stack direction="row" justifyContent="space-between">
<Typography.Title>Indexes</Typography.Title>
{#if $canWriteTables}
{#if $canWriteCollections}
<Button
event="create_index"
disabled={!$table?.columns?.length}
disabled={!$collection?.attributes?.length}
on:click={() => (showCreateIndex = true)}>
<Icon icon={IconPlus} slot="start" size="s" />
Create index
@@ -70,14 +70,14 @@
{/if}
</Layout.Stack>
{#if data.table?.columns?.length}
{#if data.table.indexes.length}
{#if data.collection?.attributes?.length}
{#if data.collection.indexes.length}
<Table.Root
let:root
columns={[
{ id: 'key' },
{ id: 'type' },
{ id: 'columns' },
{ id: 'attributes' },
{ id: 'orders' },
{ id: 'lengths' },
{ id: 'actions', width: 40 }
@@ -85,12 +85,12 @@
<svelte:fragment slot="header" let:root>
<Table.Header.Cell column="key" {root}>Key</Table.Header.Cell>
<Table.Header.Cell column="type" {root}>Type</Table.Header.Cell>
<Table.Header.Cell column="columns" {root}>Columns</Table.Header.Cell>
<Table.Header.Cell column="attributes" {root}>Attributes</Table.Header.Cell>
<Table.Header.Cell column="orders" {root}>Orders</Table.Header.Cell>
<Table.Header.Cell column="lengths" {root}>Lengths</Table.Header.Cell>
<Table.Header.Cell column="actions" {root} />
</svelte:fragment>
{#each data.table.indexes as index}
{#each data.collection.indexes as index}
<Table.Row.Base {root}>
<Table.Cell column="key" {root}>
<Layout.Stack direction="row" alignItems="center">
@@ -100,7 +100,7 @@
size="s"
variant="secondary"
content={index.status}
type={getColumnStatusBadge(index.status)} />
type={getAttributeStatusBadge(index.status)} />
{#if index.error}
<Link.Button
variant="muted"
@@ -114,8 +114,8 @@
</Layout.Stack>
</Table.Cell>
<Table.Cell column="type" {root}>{index.type}</Table.Cell>
<Table.Cell column="columns" {root}>
{index.columns}
<Table.Cell column="attributes" {root}>
{index.attributes}
</Table.Cell>
<Table.Cell column="orders" {root}>
{index.orders}
@@ -150,30 +150,30 @@
</Table.Root>
{:else}
<Empty
allowCreate={$canWriteTables}
allowCreate={$canWriteCollections}
single
href="https://appwrite.io/docs/products/databases/tables#indexes"
href="https://appwrite.io/docs/products/databases/collections#indexes"
target="index"
on:click={() => (showCreateIndex = true)} />
{/if}
{:else}
<Empty single target="index">
<Empty single target="attribute">
<svelte:fragment slot="actions">
<Button
external
href="https://appwrite.io/docs/products/databases/tables#columns"
href="https://appwrite.io/docs/products/databases/collections#attributes"
text
event="empty_documentation"
ariaLabel="create index">Documentation</Button>
{#if $canWriteTables}
<CreateColumnDropdown
bind:selectedOption={selectedColumn}
bind:showCreate={showCreateColumn}
ariaLabel={`create {target}`}>Documentation</Button>
{#if $canWriteCollections}
<CreateAttributeDropdown
bind:selectedOption={selectedAttribute}
bind:showCreate={showCreateAttribute}
let:toggle>
<Button secondary event="create_column" on:click={toggle}>
Create column
<Button secondary event="create_attribute" on:click={toggle}>
Create attribute
</Button>
</CreateColumnDropdown>
</CreateAttributeDropdown>
{/if}
</svelte:fragment>
</Empty>
@@ -187,8 +187,10 @@
<Overview bind:showOverview {selectedIndex} />
{/if}
{#if showCreateColumn}
<CreateColumn bind:showCreate={showCreateColumn} bind:selectedOption={selectedColumn} />
{#if showCreateAttribute}
<CreateAttribute
bind:showCreate={showCreateAttribute}
bind:selectedOption={selectedAttribute} />
{/if}
<FailedModal bind:show={showFailed} title="Create index" header="Creation failed" {error} />
@@ -10,14 +10,14 @@
import { addNotification } from '$lib/stores/notifications';
import { sdk } from '$lib/stores/sdk';
import { IndexType } from '@appwrite.io/console';
import { isRelationship } from '../row-[row]/columns/store';
import { type Columns, table, indexes } from '../store';
import { isRelationship } from '../document-[document]/attributes/store';
import { type Attributes, collection, indexes } from '../store';
import { Icon, Layout } from '@appwrite.io/pink-svelte';
import { IconPlus } from '@appwrite.io/pink-icons-svelte';
import { flags } from '$lib/flags';
export let showCreateIndex = false;
export let externalColumn: Columns = null;
export let externalAttribute: Attributes = null;
const databaseId = page.params.database;
@@ -30,14 +30,14 @@
];
let selectedType = IndexType.Key;
let columnOptions = $table.columns
.filter((column) => !isRelationship(column))
.map((column) => ({
value: column.key,
label: column.key
let attributeOptions = $collection.attributes
.filter((attribute) => !isRelationship(attribute))
.map((attribute) => ({
value: attribute.key,
label: attribute.key
}));
let columnList = [{ value: '', order: '', length: null }];
let attributeList = [{ value: '', order: '', length: null }];
const showLengths = flags.showIndexLengths(page.data);
@@ -53,8 +53,8 @@
}
function initialize() {
columnList = externalColumn
? [{ value: externalColumn.key, order: 'ASC', length: null }]
attributeList = externalAttribute
? [{ value: externalAttribute.key, order: 'ASC', length: null }]
: [{ value: '', order: 'ASC', length: null }];
selectedType = IndexType.Key;
key = `index_${$indexes.length + 1}`;
@@ -66,32 +66,32 @@
key = generateIndexKey();
}
$: addColumnDisabled = !columnList.at(-1)?.value || !columnList.at(-1)?.order;
$: addAttributeDisabled = !attributeList.at(-1)?.value || !attributeList.at(-1)?.order;
async function create() {
if (!(key && selectedType && !addColumnDisabled)) {
if (!(key && selectedType && !addAttributeDisabled)) {
error = 'All fields are required';
return;
}
try {
await sdk.forProject(page.params.region, page.params.project).tables.createIndex(
await sdk.forProject(page.params.region, page.params.project).databases.createIndex(
databaseId,
$table.$id,
$collection.$id,
key,
selectedType,
columnList.map((a) => a.value),
columnList.map((a) => a.order),
columnList.map((a) => (a.length ? Number(a.length) : null))
attributeList.map((a) => a.value),
attributeList.map((a) => a.order),
attributeList.map((a) => (a.length ? Number(a.length) : null))
);
await Promise.allSettled([
invalidate(Dependencies.TABLE),
invalidate(Dependencies.COLLECTION),
invalidate(Dependencies.DATABASE)
]);
goto(
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${databaseId}/table-${$table.$id}/indexes`
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${databaseId}/collection-${$collection.$id}/indexes`
);
addNotification({
@@ -106,11 +106,11 @@
}
}
function addColumn() {
if (addColumnDisabled) return;
function addAttribute() {
if (addAttributeDisabled) return;
// We assign instead of pushing to trigger Svelte's reactivity
columnList = [...columnList, { value: '', order: '', length: null }];
attributeList = [...attributeList, { value: '', order: '', length: null }];
}
</script>
@@ -125,7 +125,7 @@
<InputSelect required options={types} id="type" label="Index type" bind:value={selectedType} />
<Layout.Stack gap="s">
{#each columnList as column, index}
{#each attributeList as attribute, i}
<Layout.Stack direction="row">
<InputSelect
required
@@ -133,12 +133,12 @@
{ value: '$id', label: '$id' },
{ value: '$createdAt', label: '$createdAt' },
{ value: '$updatedAt', label: '$updatedAt' },
...columnOptions
...attributeOptions
]}
id={`column-${index}`}
label={index === 0 ? 'Column' : undefined}
placeholder="Select column"
bind:value={column.value} />
id={`attribute-${i}`}
label={i === 0 ? 'Attribute' : undefined}
placeholder="Select Attribute"
bind:value={attribute.value} />
<InputSelect
options={[
@@ -146,25 +146,25 @@
{ value: 'DESC', label: 'DESC' }
]}
required
id={`order-${index}`}
label={index === 0 ? 'Order' : undefined}
bind:value={column.order}
placeholder="Select order" />
id={`order-${i}`}
label={i === 0 ? 'Order' : undefined}
bind:value={attribute.order}
placeholder="Select Order" />
<Layout.Stack direction="row" alignItems="flex-end" gap="xs">
{#if selectedType === IndexType.Key && showLengths}
<InputNumber
id={`length-${index}`}
label={index === 0 ? 'Length' : undefined}
placeholder="Enter length"
bind:value={column.length} />
id={`length-${i}`}
label={i === 0 ? 'Length' : undefined}
placeholder="Enter Length"
bind:value={attribute.length} />
{/if}
<Button
icon
compact
disabled={columnList.length <= 1}
disabled={attributeList.length <= 1}
on:click={() => {
columnList = remove(columnList, index);
attributeList = remove(attributeList, i);
}}>
<span class="icon-x" aria-hidden="true"></span>
</Button>
@@ -172,9 +172,9 @@
</Layout.Stack>
{/each}
<div>
<Button compact on:click={addColumn} disabled={addColumnDisabled}>
<Button compact on:click={addAttribute} disabled={addAttributeDisabled}>
<Icon icon={IconPlus} slot="start" size="s" />
Add column
Add attribute
</Button>
</div>
</Layout.Stack>
@@ -1,6 +1,6 @@
<script lang="ts">
import { addNotification } from '$lib/stores/notifications';
import { table } from '../store';
import { collection } from '../store';
import { sdk } from '$lib/stores/sdk';
import type { Models } from '@appwrite.io/console';
import { page } from '$app/state';
@@ -11,17 +11,17 @@
import { Typography } from '@appwrite.io/pink-svelte';
export let showDelete = false;
export let selectedIndex: Models.ColumnIndex;
export let selectedIndex: Models.Index;
let error: string;
const databaseId = page.params.database;
let error: string;
async function handleDelete() {
try {
await sdk
.forProject(page.params.region, page.params.project)
.tables.deleteIndex(databaseId, $table.$id, selectedIndex.key);
await invalidate(Dependencies.TABLE);
.databases.deleteIndex(databaseId, $collection.$id, selectedIndex.key);
await invalidate(Dependencies.COLLECTION);
showDelete = false;
addNotification({
type: 'success',
@@ -37,6 +37,6 @@
<Confirm onSubmit={handleDelete} title="Delete index" bind:open={showDelete} bind:error>
<Typography.Text>
Are you sure you want to delete <b>{selectedIndex.key}</b> from <b>{$table.name}</b>?
Are you sure you want to delete <b>{selectedIndex.key}</b> from <b>{$collection.name}</b>?
</Typography.Text>
</Confirm>
@@ -7,7 +7,7 @@
import { flags } from '$lib/flags';
export let showOverview = false;
export let selectedIndex: Models.ColumnIndex = null;
export let selectedIndex: Models.Index = null;
const showLengths = flags.showIndexLengths(page.data);
</script>
@@ -16,8 +16,8 @@
<InputText
required
id="key"
label="Index key"
placeholder="Enter key"
label="Index Key"
placeholder="Enter Key"
value={selectedIndex.key}
readonly />
<InputText
@@ -28,14 +28,14 @@
value={selectedIndex.type}
readonly />
{#if selectedIndex?.columns?.length}
{#each selectedIndex.columns as column, i}
{#if selectedIndex?.attributes?.length}
{#each selectedIndex.attributes as attribute, i}
<Layout.Stack direction="row">
<InputText
required
label={i === 0 ? 'Column' : ''}
id={`value-${column}`}
value={column}
label={i === 0 ? 'Attribute' : ''}
id={`value-${attribute}`}
value={attribute}
readonly />
<InputText
required
@@ -1,7 +1,5 @@
<script lang="ts">
import Helper from '$lib/elements/forms/helper.svelte';
import { Icon } from '@appwrite.io/pink-svelte';
import { IconChevronDown } from '@appwrite.io/pink-icons-svelte';
export let value: string;
export let id: string;
@@ -32,7 +30,7 @@
<select bind:this={element} {id} bind:value {required} on:invalid={handleInvalid}>
<slot />
</select>
<Icon icon={IconChevronDown} size="s" />
<span class="icon-cheveron-down" aria-hidden="true"></span>
</div>
{#if error}
<Helper type="warning">{error}</Helper>
@@ -9,14 +9,14 @@
export let show = false;
export let data: Partial<Models.Document>[];
export let selectedRelationship: Models.ColumnRelationship = null;
export let selectedRelationship: Models.AttributeRelationship = null;
const databaseId = page.params.database;
const limit = 10;
$: args =
preferences
.getDisplayNames()
?.[selectedRelationship?.relatedTable]?.filter((p) => p !== '$id') ?? [];
?.[selectedRelationship?.relatedCollection]?.filter((p) => p !== '$id') ?? [];
$: if (!show) {
data = null;
@@ -36,7 +36,7 @@
{#snippet children(paginatedItems: typeof data)}
<Table.Root let:root columns={tableColumns}>
<svelte:fragment slot="header" let:root>
<Table.Header.Cell column="$id" {root}>Row ID</Table.Header.Cell>
<Table.Header.Cell column="$id" {root}>Document ID</Table.Header.Cell>
{#if args.length}
{#each args as arg}
<Table.Header.Cell column={arg} {root}>{arg}</Table.Header.Cell>
@@ -46,7 +46,7 @@
{#each paginatedItems as doc}
<Table.Row.Link
{root}
href={`${base}/project-${page.params.region}-${page.params.project}/databases/database-${databaseId}/table-${selectedRelationship.relatedTable}/row-${doc.$id}`}
href={`${base}/project-${page.params.region}-${page.params.project}/databases/database-${databaseId}/collection-${selectedRelationship.relatedCollection}/document-${doc.$id}`}
on:click={() => (show = false)}>
<Table.Cell column="$id" {root}>
<Id value={doc.$id}>{doc.$id}</Id>
@@ -1,6 +1,6 @@
<script lang="ts">
import { Container } from '$lib/layout';
import { table } from '../store';
import { collection } from '../store';
import DangerZone from './dangerZone.svelte';
import DisplayName from './displayName.svelte';
import UpdateName from './updateName.svelte';
@@ -10,7 +10,7 @@
</script>
<Container>
{#if $table}
{#if $collection}
<UpdateStatus />
<UpdateName />
<DisplayName />
@@ -2,22 +2,23 @@
import { BoxAvatar, CardGrid } from '$lib/components';
import { Button } from '$lib/elements/forms';
import { toLocaleDateTime } from '$lib/helpers/date';
import { table } from '../store';
import Delete from './deleteTable.svelte';
import { collection } from '../store';
import Delete from './deleteCollection.svelte';
import { Click, trackEvent } from '$lib/actions/analytics';
let showDelete = false;
</script>
<CardGrid>
<svelte:fragment slot="title">Delete table</svelte:fragment>
The table will be permanently deleted, including all the rows within it. This action is irreversible.
<svelte:fragment slot="title">Delete collection</svelte:fragment>
The collection will be permanently deleted, including all the documents within it. This action is
irreversible.
<svelte:fragment slot="aside">
<BoxAvatar>
<svelte:fragment slot="title">
<h6 class="u-bold u-trim-1">{$table.name}</h6>
<h6 class="u-bold u-trim-1">{$collection.name}</h6>
</svelte:fragment>
<p>Last updated: {toLocaleDateTime($table.$updatedAt)}</p>
<p>Last updated: {toLocaleDateTime($collection.$updatedAt)}</p>
</BoxAvatar>
</svelte:fragment>
@@ -25,7 +26,7 @@
<Button
secondary
on:click={() => {
trackEvent(Click.DatabaseTableDelete);
trackEvent(Click.DatabaseCollectionDelete);
showDelete = true;
}}>Delete</Button>
</svelte:fragment>
@@ -8,7 +8,7 @@
import { addNotification } from '$lib/stores/notifications';
import { sdk } from '$lib/stores/sdk';
import { Typography } from '@appwrite.io/pink-svelte';
import { table } from '../store';
import { collection } from '../store';
export let showDelete = false;
@@ -19,26 +19,26 @@
try {
await sdk
.forProject(page.params.region, page.params.project)
.tables.delete(databaseId, $table.$id);
.databases.deleteCollection(databaseId, $collection.$id);
await invalidate(Dependencies.DATABASE);
showDelete = false;
addNotification({
type: 'success',
message: `${$table.name} has been deleted`
message: `${$collection.name} has been deleted`
});
trackEvent(Submit.TableDelete);
trackEvent(Submit.CollectionDelete);
await goto(
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${page.params.database}`
);
} catch (e) {
error = e.message;
trackError(e, Submit.TableDelete);
trackError(e, Submit.CollectionDelete);
}
}
</script>
<Confirm onSubmit={handleDelete} title="Delete table" bind:open={showDelete} bind:error>
<Confirm onSubmit={handleDelete} title="Delete collection" bind:open={showDelete} bind:error>
<Typography.Text>
Are you sure you want to delete <b>{$table.name}</b>?
Are you sure you want to delete <b>{$collection.name}</b>?
</Typography.Text>
</Confirm>
@@ -7,17 +7,17 @@
import { last, symmetricDifference } from '$lib/helpers/array';
import { addNotification } from '$lib/stores/notifications';
import type { Models } from '@appwrite.io/console';
import { columns } from '../store';
import { attributes } from '../store';
import { preferences } from '$lib/stores/preferences';
import { page } from '$app/state';
import { Icon, Layout } from '@appwrite.io/pink-svelte';
import { IconPlus, IconX } from '@appwrite.io/pink-icons-svelte';
import { organization } from '$lib/stores/organization';
const tableId = page.params.table;
const collectionId = page.params.collection;
function getDisplayNames() {
return [...(preferences.getDisplayNames()?.[tableId] ?? [])].filter(
return [...(preferences.getDisplayNames()?.[collectionId] ?? [])].filter(
(name) => name !== '$id'
); // edge case with `$id`? got saved during tests!
}
@@ -30,33 +30,33 @@
// structuredClone doesn't work
const regularArray = [...names];
await preferences.setDisplayNames($organization.$id, tableId, regularArray);
await preferences.setDisplayNames($organization.$id, collectionId, regularArray);
names = getDisplayNames();
await invalidate(Dependencies.TEAM);
addNotification({
message: 'Display names have been updated',
message: 'Display names has been updated',
type: 'success'
});
trackEvent(Submit.TableUpdateDisplayNames);
trackEvent(Submit.CollectionUpdateDisplayNames);
} catch (error) {
addNotification({
message: error.message,
type: 'error'
});
trackError(error, Submit.TableUpdateDisplayNames);
trackError(error, Submit.CollectionUpdateDisplayNames);
}
}
function getValidColumns() {
return ($columns as Models.ColumnString[]).filter(
function getValidAttributes() {
return ($attributes as Models.AttributeString[]).filter(
(attr) => attr.type === 'string' && !attr?.array
);
}
function getOptions(index: number) {
const current = names?.[index];
return getValidColumns()
return getValidAttributes()
.filter((attr) => !names?.includes(attr.key) || attr.key === current)
.map((attr) => ({
value: attr.key,
@@ -69,23 +69,25 @@
);
const updateBtnDisabled = $derived(
!symmetricDifference(names, preferences.getDisplayNames()?.[tableId] ?? [])?.length ||
!symmetricDifference(names, preferences.getDisplayNames()?.[collectionId] ?? [])?.length ||
(names?.length && !last(names))
);
const hasExhaustedOptions = $derived(getValidColumns().length === names.filter(Boolean).length);
const hasExhaustedOptions = $derived(
getValidAttributes().length === names.filter(Boolean).length
);
</script>
<Form onSubmit={updateDisplayName}>
<CardGrid>
<svelte:fragment slot="title">Display name</svelte:fragment>
Select up to 5 string columns to display as row names in the Appwrite console. These help identify
rows in places like relationships.
Select up to 5 string attributes to display as document names in the Appwrite console. These
help identify documents in places like relationships.
<svelte:fragment slot="aside">
<Layout.Stack gap="s">
<Layout.Stack direction="row" gap="xxs">
<InputText id="id" value="Row ID" readonly />
<InputText id="id" value="Document ID" readonly />
<span style:visibility="hidden">
<Button icon extraCompact>
<Icon icon={IconX} />
@@ -103,7 +105,7 @@
{options}
{disabled}
bind:value={names[index]}
placeholder="Select column" />
placeholder="Select attribute" />
<Button
icon
extraCompact
@@ -128,7 +130,7 @@
names = names;
}}>
<Icon icon={IconPlus} slot="start" size="s" />
Add column
Add attribute
</Button>
</div>
{/if}
@@ -8,40 +8,40 @@
import { addNotification } from '$lib/stores/notifications';
import { sdk } from '$lib/stores/sdk';
import { onMount } from 'svelte';
import { table } from '../store';
import { collection } from '../store';
const databaseId = page.params.database;
let tableName: string = null;
let collectionName: string = null;
onMount(() => {
tableName ??= $table.name;
collectionName ??= $collection.name;
});
async function updateName() {
try {
await sdk
.forProject(page.params.region, page.params.project)
.tables.update(
.databases.updateCollection(
databaseId,
$table.$id,
tableName,
$table.$permissions,
$table.rowSecurity,
$table.enabled
$collection.$id,
collectionName,
$collection.$permissions,
$collection.documentSecurity,
$collection.enabled
);
await invalidate(Dependencies.TABLE);
await invalidate(Dependencies.COLLECTION);
addNotification({
message: 'Name has been updated',
type: 'success'
});
trackEvent(Submit.TableUpdateName);
trackEvent(Submit.CollectionUpdateName);
} catch (error) {
addNotification({
message: error.message,
type: 'error'
});
trackError(error, Submit.TableUpdateName);
trackError(error, Submit.CollectionUpdateName);
}
}
</script>
@@ -56,11 +56,12 @@
label="Name"
placeholder="Enter name"
autocomplete={false}
bind:value={tableName} />
bind:value={collectionName} />
</svelte:fragment>
<svelte:fragment slot="actions">
<Button disabled={tableName === $table.name || !tableName} submit>Update</Button>
<Button disabled={collectionName === $collection.name || !collectionName} submit
>Update</Button>
</svelte:fragment>
</CardGrid>
</Form>
@@ -10,62 +10,63 @@
import { addNotification } from '$lib/stores/notifications';
import { sdk } from '$lib/stores/sdk';
import { onMount } from 'svelte';
import { table } from '../store';
import { collection } from '../store';
import { Link } from '@appwrite.io/pink-svelte';
const databaseId = page.params.database;
let arePermsDisabled = true;
let tablePermissions: string[] = null;
let collectionPermissions: string[] = null;
onMount(() => {
tablePermissions ??= $table.$permissions;
collectionPermissions ??= $collection.$permissions;
});
async function updatePermissions() {
try {
await sdk
.forProject(page.params.region, page.params.project)
.tables.update(
.databases.updateCollection(
databaseId,
$table.$id,
$table.name,
tablePermissions,
$table.rowSecurity,
$table.enabled
$collection.$id,
$collection.name,
collectionPermissions,
$collection.documentSecurity,
$collection.enabled
);
await invalidate(Dependencies.TABLE);
await invalidate(Dependencies.COLLECTION);
addNotification({
message: 'Permissions have been updated',
type: 'success'
});
trackEvent(Submit.TableUpdatePermissions);
trackEvent(Submit.CollectionUpdatePermissions);
} catch (error) {
addNotification({
message: error.message,
type: 'error'
});
trackError(error, Submit.TableUpdatePermissions);
trackError(error, Submit.CollectionUpdatePermissions);
}
}
$: arePermsDisabled = !(
tablePermissions && symmetricDifference(tablePermissions, $table.$permissions).length
collectionPermissions &&
symmetricDifference(collectionPermissions, $collection.$permissions).length
);
</script>
<CardGrid>
<svelte:fragment slot="title">Permissions</svelte:fragment>
Choose who can access your tables and rows. <Link.Anchor
Choose who can access your collection and documents. <Link.Anchor
href="https://appwrite.io/docs/products/databases/permissions"
target="_blank"
rel="noopener noreferrer">
Learn more
</Link.Anchor>.
<svelte:fragment slot="aside">
{#if tablePermissions}
<Permissions bind:permissions={tablePermissions} withCreate />
{#if collectionPermissions}
<Permissions bind:permissions={collectionPermissions} withCreate />
{/if}
</svelte:fragment>
<svelte:fragment slot="actions">
@@ -0,0 +1,72 @@
<script lang="ts">
import { invalidate } from '$app/navigation';
import { page } from '$app/state';
import { Submit, trackEvent, trackError } from '$lib/actions/analytics';
import { CardGrid } from '$lib/components';
import { Dependencies } from '$lib/constants';
import { Button, InputSwitch } from '$lib/elements/forms';
import { addNotification } from '$lib/stores/notifications';
import { sdk } from '$lib/stores/sdk';
import { onMount } from 'svelte';
import { collection } from '../store';
const databaseId = page.params.database;
let collectionDocumentSecurity: boolean = null;
onMount(() => {
collectionDocumentSecurity ??= $collection.documentSecurity;
});
async function updateSecurity() {
try {
await sdk
.forProject(page.params.region, page.params.project)
.databases.updateCollection(
databaseId,
$collection.$id,
$collection.name,
$collection.$permissions,
collectionDocumentSecurity,
$collection.enabled
);
await invalidate(Dependencies.COLLECTION);
addNotification({
message: 'Security has been updated',
type: 'success'
});
trackEvent(Submit.CollectionUpdateSecurity);
} catch (error) {
addNotification({
message: error.message,
type: 'error'
});
trackError(error, Submit.CollectionUpdateSecurity);
}
}
</script>
<CardGrid>
<svelte:fragment slot="title">Document security</svelte:fragment>
<svelte:fragment slot="aside">
<InputSwitch
bind:value={collectionDocumentSecurity}
id="security"
label="Document security" />
<p class="text">
When document security is enabled, users will be able to access documents for which they
have been granted <b>either document or collection permissions</b>.
</p>
<p class="text">
If document security is disabled, users can access documents <b
>only if they have collection permissions</b
>. Document permissions will be ignored.
</p>
</svelte:fragment>
<svelte:fragment slot="actions">
<Button
disabled={collectionDocumentSecurity === $collection.documentSecurity}
on:click={updateSecurity}>Update</Button>
</svelte:fragment>
</CardGrid>
Loaded 100 of 128 files, more files were not shown because too many files have changed in this diff. Show more