update: refactor to use the Tables API.

This commit is contained in:
Darshan committed 2025-06-26 18:15:17 +05:30
1 parent 407d923544
commit bee0a590d0
96 files changed
+961 -948

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@56743f5",
"@appwrite.io/console": "https://pkg.pr.new/appwrite-labs/cloud/@appwrite.io/console@4ca420f",
"@appwrite.io/pink-icons": "0.25.0",
"@appwrite.io/pink-icons-svelte": "^2.0.0-RC.1",
"@appwrite.io/pink-legacy": "^1.0.3",
+5 -5
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@56743f5
version: https://pkg.pr.new/appwrite-labs/cloud/@appwrite.io/console@56743f5
specifier: https://pkg.pr.new/appwrite-labs/cloud/@appwrite.io/console@4ca420f
version: https://pkg.pr.new/appwrite-labs/cloud/@appwrite.io/console@4ca420f
'@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@56743f5':
resolution: {tarball: https://pkg.pr.new/appwrite-labs/cloud/@appwrite.io/console@56743f5}
'@appwrite.io/console@https://pkg.pr.new/appwrite-labs/cloud/@appwrite.io/console@4ca420f':
resolution: {tarball: https://pkg.pr.new/appwrite-labs/cloud/@appwrite.io/console@4ca420f}
version: 1.9.0
'@appwrite.io/pink-icons-svelte@https://pkg.pr.new/appwrite/pink/@appwrite.io/pink-icons-svelte@d521606fc63e0800b996f0fbb1a8d1f6907480ed':
@@ -3636,7 +3636,7 @@ snapshots:
'@analytics/type-utils@0.6.2': {}
'@appwrite.io/console@https://pkg.pr.new/appwrite-labs/cloud/@appwrite.io/console@56743f5': {}
'@appwrite.io/console@https://pkg.pr.new/appwrite-labs/cloud/@appwrite.io/console@4ca420f': {}
'@appwrite.io/pink-icons-svelte@https://pkg.pr.new/appwrite/pink/@appwrite.io/pink-icons-svelte@d521606fc63e0800b996f0fbb1a8d1f6907480ed(svelte@5.25.3)':
dependencies:
+1 -2
View File
@@ -24,11 +24,10 @@
streamProtocol: 'text'
});
// TODO: change collections to tables after docs are updated!
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 collections and documents in Appwrite?',
'How can I set up database tables and rows in Appwrite?',
'How do I configure and manage server-side functions in Appwrite?',
'How to add custom domain in the console?'
];
+8 -10
View File
@@ -1,27 +1,25 @@
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 tablesSearcher = (async (query: string) => {
const databaseId = get(database).$id;
const { collections } = await sdk
const databaseId = page.params.database;
const { tables } = await sdk
.forProject(page.params.region, page.params.project)
.databases.listCollections(databaseId);
.tables.list(databaseId);
return collections
.filter((col) => col.name.toLowerCase().includes(query.toLowerCase()))
return tables
.filter((table) => table.name.toLowerCase().includes(query.toLowerCase()))
.map(
(col) =>
(table) =>
({
group: 'tables',
label: col.name,
label: table.name,
callback: () => {
goto(
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${databaseId}/table-${col.$id}`
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${databaseId}/table-${table.$id}`
);
}
}) as const
+1 -1
View File
@@ -33,7 +33,7 @@
onMount(async () => {
if (isCustomCollection) {
const prefs = preferences.getCustomCollectionColumns(page.params.table);
const prefs = preferences.getCustomTableColumns(page.params.table);
columns.set(
$columns.map((column) => {
column.hide = prefs?.includes(column.id) ?? false;
+17 -21
View File
@@ -13,7 +13,7 @@
type ImportItem = {
status: string;
collection?: string;
table?: string;
};
type ImportItemsMap = Map<string, ImportItem>;
@@ -22,15 +22,11 @@
* Keeps a track of the active and ongoing csv migrations.
*
* The structure is as follows -
* `{ migrationId: { status: status, collection: collection } }`
* `{ migrationId: { status: status, table: table } }`
*/
const importItems: Writable<ImportItemsMap> = writable(new Map());
async function showCompletionNotification(
database: string,
collection: string,
payload: Payload
) {
async function showCompletionNotification(database: string, table: string, payload: Payload) {
const isSuccess = payload.status === 'completed';
const isError = !isSuccess && !!payload.errors;
@@ -48,15 +44,15 @@
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-${collection}`;
const url = `${base}/project-${page.params.region}-${page.params.project}/databases/database-${database}/table-${table}`;
addNotification({
type,
message,
isHtml: true,
buttons:
isSuccess && collection !== page.params.collection
? [{ name: 'View documents', method: () => goto(url) }]
isSuccess && table !== page.params.table
? [{ name: 'View rows', method: () => goto(url) }]
: undefined
});
@@ -70,19 +66,19 @@
const status = importData.status;
const resourceId = importData.resourceId ?? '';
const [databaseId, collectionId] = resourceId.split(':') ?? [];
const [databaseId, tableId] = resourceId.split(':') ?? [];
const current = $importItems.get(importData.$id);
let collectionName = current?.collection ?? null;
let tableName = current?.table ?? null;
if (!collectionName && collectionId) {
if (!tableName && tableId) {
try {
const collection = await sdk
const table = await sdk
.forProject(page.params.region, page.params.project)
.databases.getCollection(databaseId, collectionId);
collectionName = collection.name;
.tables.get(databaseId, tableId);
tableName = table.name;
} catch {
collectionName = null;
tableName = null;
}
}
@@ -99,12 +95,12 @@
if (shouldSkip) return items;
const next = new Map(items);
next.set(importData.$id, { status, collection: collectionName ?? undefined });
next.set(importData.$id, { status, table: tableName ?? undefined });
return next;
});
if (status === 'completed' || status === 'failed') {
await showCompletionNotification(databaseId, collectionId, importData);
await showCompletionNotification(databaseId, tableId, importData);
}
}
@@ -172,7 +168,7 @@
<header class="upload-box-header">
<h4 class="upload-box-title">
<Typography.Text variant="m-500">
Importing documents ({$importItems.size})
Importing rows ({$importItems.size})
</Typography.Text>
</h4>
<button
@@ -198,7 +194,7 @@
<div
class="progress-bar-top-line u-flex u-gap-8 u-main-space-between">
<Typography.Text>
{@html text(value.status, value.collection)}
{@html text(value.status, value.table)}
</Typography.Text>
</div>
<div
+24 -28
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 attributeNames = [
...services.flatMap((s) => s.actions.flatMap((a) => a.attributes ?? [])),
const columnNames = [
...services.flatMap((s) => s.actions.flatMap((a) => a.columns ?? [])),
...services.flatMap((s) =>
s.resources.flatMap((r) => r.actions.flatMap((a) => a.attributes ?? []))
s.resources.flatMap((r) => r.actions.flatMap((a) => a.columns ?? []))
)
];
@@ -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 isAttribute = (s: string) => attributeNames.includes(s);
const isColumn = (s: string) => columnNames.includes(s);
const dispatch = createEventDispatcher();
@@ -69,7 +69,7 @@
case 'service': {
selected.resource = null;
selected.action = null;
selected.attribute = null;
selected.column = 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
// appropriate one, as it may contain different attributes/columns.
const availableAction = availableActions.find(
(a) => a.name === selected.action?.name
);
if (!availableAction) {
selected.action = null;
selected.attribute = null;
selected.column = null;
} else {
selected.action = availableAction;
if (!selected?.action?.attributes?.includes(selected.attribute)) {
selected.attribute = null;
if (!selected?.action?.columns?.includes(selected.column)) {
selected.column = null;
}
}
break;
}
case 'action': {
selected.attribute = null;
selected.column = null;
break;
}
}
@@ -113,16 +113,13 @@
if (isService(field)) {
selected.service = services.find((s) => s.name === field);
} else if (isResource(field)) {
const resource = selected.service?.resources.find((r) => r.name === field);
selected.resource = resource;
selected.resource = selected.service?.resources.find((r) => r.name === field);
} else if (isAction(field)) {
const action =
selected.action =
selected.resource?.actions.find((a) => a.name === field) ||
selected.service?.actions.find((a) => a.name === field);
selected.action = action;
} else if (isAttribute(field)) {
const attribute = selected.action?.attributes?.find((a) => a === field);
selected.attribute = attribute;
} else if (isColumn(field)) {
selected.column = selected.action?.columns?.find((a) => a === field);
}
}
}
@@ -143,7 +140,7 @@
const secondToLastField = at(fields, index - 2);
if (index === 0 || isService(currField)) return 'service';
if (isAttribute(currField) || isAction(prevField)) return 'attribute';
if (isColumn(currField) || isAction(prevField)) return 'attribute';
if (isAction(currField)) return 'action';
if (isResource(currField)) return 'resource';
if (isService(prevField) || isResource(prevField) || index === 1) {
@@ -182,7 +179,7 @@
service: null as EventService | null,
resource: null as EventResource | null,
action: null as EventAction | null,
attribute: null as string | null
column: null as string | null
};
let helper: string = null;
let customInput: string = null;
@@ -198,7 +195,7 @@
services: services,
resources: selected.service?.resources || [],
actions: (selected.resource ? selected.resource?.actions : selected.service?.actions) || [],
attributes: selected.action?.attributes || []
columns: selected.action?.columns || []
};
$: eventString = (function createEventString(): Array<{ value: string; description: string }> {
@@ -212,9 +209,8 @@
if (selected.service) {
fields.push(selected.service.name, '*');
}
// TODO: change collections and documents terminology later
if (selected.resource?.name === 'documents') {
fields.push('collections', '*');
if (selected.resource?.name === 'rows') {
fields.push('tables', '*');
}
if (selected.resource) {
fields.push(selected.resource.name, '*');
@@ -222,8 +218,8 @@
if (selected.action) {
fields.push(selected.action.name);
}
if (selected.attribute) {
fields.push(selected.attribute);
if (selected.column) {
fields.push(selected.column);
}
}
@@ -291,14 +287,14 @@
</Layout.Stack>
{/if}
{#if !empty(available.attributes)}
{#if !empty(available.columns)}
<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.attributes as attribute}
{#each available.columns as attribute}
<Pill
disabled={showInput}
selected={selected.attribute === attribute}
selected={selected.column === 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="create document"
ariaLabel="upload download"
>Documentation</Button>
<Button
secondary
@@ -526,7 +526,7 @@
size="s"
event="empty_documentation"
href="https://appwrite.io/docs/products/storage/buckets"
ariaLabel="create document">Documentation</Button>
ariaLabel="create buckets">Documentation</Button>
<Button
secondary
+47 -4
View File
@@ -64,7 +64,7 @@ export enum Dependencies {
WEBHOOK = 'dependency:webhook',
WEBHOOKS = 'dependency:webhooks',
MIGRATIONS = 'dependency:migrations',
COLLECTIONS = 'dependency:collections',
TABLES = 'dependency:tables',
BACKUPS = 'dependency:backups',
RUNTIMES = 'dependency:runtimes',
CONSOLE_VARIABLES = 'dependency:console_variables',
@@ -92,6 +92,8 @@ export const defaultScopes: string[] = [
'teams.write',
'documents.read',
'documents.write',
'rows.read',
'rows.write',
'files.read',
'files.write',
'projects.read',
@@ -111,6 +113,8 @@ export const defaultScopes: string[] = [
'databases.write',
'collections.read',
'collections.write',
'tables.read',
'tables.write',
'buckets.read',
'buckets.write',
'functions.read',
@@ -141,6 +145,9 @@ 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;
@@ -201,6 +208,18 @@ 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",
@@ -214,6 +233,18 @@ 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",
@@ -239,6 +270,18 @@ 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",
@@ -430,7 +473,7 @@ export type EventResource = {
export type EventAction = {
name: string;
attributes?: string[];
columns?: string[];
};
export const eventServices: Array<EventService> = [
@@ -479,7 +522,7 @@ export const eventServices: Array<EventService> = [
name: 'memberships',
actions: [
{ name: 'create' },
{ name: 'update', attributes: ['status'] },
{ name: 'update', columns: ['status'] },
{ name: 'delete' }
]
}
@@ -495,7 +538,7 @@ export const eventServices: Array<EventService> = [
],
actions: [
{ name: 'create' },
{ name: 'update', attributes: ['email', 'name', 'password', 'status', 'prefs'] },
{ name: 'update', columns: ['email', 'name', 'password', 'status', 'prefs'] },
{ name: 'delete' }
]
},
+3
View File
@@ -35,6 +35,7 @@
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,
@@ -42,6 +43,8 @@
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 },
+6 -1
View File
@@ -345,6 +345,8 @@ 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' },
@@ -357,8 +359,11 @@ 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) : 0;
members > plan?.addons?.seats?.limit
? members - (plan?.addons?.seats?.limit || members)
: 0;
if (resources.some((r) => r.value >= 100) || membersOverflow > 0) {
readOnly.set(true);
+13 -12
View File
@@ -9,7 +9,7 @@ const initialFormData = {
},
databases: {
root: false,
documents: false
rows: false
},
functions: {
root: false,
@@ -45,18 +45,19 @@ export const ResourcesFriendly = {
'environment-variable': { singular: 'Environment Variable', plural: 'Environment Variables' },
deployment: { singular: 'Deployment', plural: 'Deployments' },
database: { singular: 'Database', plural: 'Databases' },
collection: { singular: 'Table', plural: 'Tables' },
table: { singular: 'Table', plural: 'Tables' },
index: { singular: 'Index', plural: 'Indexes' },
attribute: { singular: 'Column', plural: 'Columns' },
document: { singular: 'Row', plural: 'Rows' }
column: { singular: 'Column', plural: 'Columns' },
row: { singular: 'Row', plural: 'Rows' }
};
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],
appwrite: [...resources], // new terminology, others are ok?
supabase: [
'user',
'database',
@@ -91,12 +92,12 @@ export const migrationFormToResources = (
}
if (formData.databases.root) {
addResource('database');
addResource('collection');
addResource('attribute');
addResource('index');
addResource('table');
addResource('column');
addResource('columnIndex');
}
if (formData.databases.documents) {
addResource('document');
if (formData.databases.rows) {
addResource('row');
}
if (formData.functions.root) {
addResource('function');
@@ -150,8 +151,8 @@ export const resourcesToMigrationForm = (
if (resources.includes('database')) {
formData.databases.root = true;
}
if (includesAll(resources, ['collection', 'attribute', 'document'])) {
formData.databases.documents = true;
if (includesAll(resources, ['table', 'column', 'row'])) {
formData.databases.rows = true;
}
if (resources.includes('function') && isVersionAtLeast(version, '1.4.0')) {
formData.functions.root = true;
+1
View File
@@ -41,6 +41,7 @@ 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;
+14 -12
View File
@@ -4,7 +4,6 @@ import type { Page } from '@sveltejs/kit';
import { get, writable } from 'svelte/store';
import { sdk } from './sdk';
import type { Models } from '@appwrite.io/console';
import { organization } from './organization';
import { page } from '$app/state';
import { user } from '$lib/stores/user';
import deepEqual from 'deep-equal';
@@ -21,7 +20,7 @@ type TeamPreferences = {
type PreferencesStore = {
[key: string]: Preferences;
collections?: {
tables?: {
[key: string]: Preferences['columns'];
};
displayNames?: {
@@ -107,8 +106,8 @@ function createPreferences() {
}
);
},
getCustomCollectionColumns: (collectionId: string): Preferences['columns'] => {
return preferences?.collections?.[collectionId] ?? [];
getCustomTableColumns: (tableId: string): Preferences['columns'] => {
return preferences?.tables?.[tableId] ?? [];
},
setLimit: (limit: Preferences['limit']) =>
updateAndSync((n) => {
@@ -151,13 +150,13 @@ function createPreferences() {
}),
setCustomCollectionColumns: (columns: Preferences['columns']) =>
updateAndSync((n) => {
const collection = page.params.table;
if (!n?.collections?.[collection]) {
const table = page.params.table;
if (!n?.tables?.[table]) {
n ??= {};
n.collections ??= {};
n.tables ??= {};
}
n.collections[collection] = columns;
n.tables[table] = columns;
return n;
}),
@@ -173,8 +172,11 @@ function createPreferences() {
getDisplayNames: () => {
return preferences?.displayNames ?? {};
},
setDisplayNames: async (collectionId: string, names: TeamPreferences['names']) => {
const id = get(organization).$id;
setDisplayNames: async (
orgId: string,
tableId: string,
names: TeamPreferences['names']
) => {
let teamPrefs: Models.Preferences;
update((n) => {
if (!n?.displayNames) {
@@ -183,11 +185,11 @@ function createPreferences() {
}
teamPrefs = n;
n.displayNames[collectionId] = names;
n.displayNames[tableId] = names;
return n;
});
await sdk.forConsole.teams.updatePrefs(id, teamPrefs);
await sdk.forConsole.teams.updatePrefs(orgId, teamPrefs);
}
};
}
+1
View File
@@ -25,6 +25,7 @@ export const canWriteCollections = derived(scopes, ($scopes) =>
export const canWriteSites = derived(scopes, ($scopes) => $scopes.includes('sites.write'));
export const canWriteDomains = derived(scopes, ($scopes) => $scopes.includes('domains.write')); //TODO: check if correct
// TODO: @itznotabug - add new scopes as well, don't replace completely!
export const canWriteDocuments = derived(scopes, ($scopes) => $scopes.includes('documents.write'));
export const canWriteExecutions = derived(scopes, ($scopes) =>
$scopes.includes('executions.write')
+3 -1
View File
@@ -21,6 +21,7 @@ import {
Vcs,
Sites,
Tokens,
Tables,
Domains
} from '@appwrite.io/console';
import { Billing } from '../sdk/billing';
@@ -122,7 +123,8 @@ const sdkForProject = {
vcs: new Vcs(clientProject),
proxy: new Proxy(clientProject),
migrations: new Migrations(clientProject),
sites: new Sites(clientProject)
sites: new Sites(clientProject),
tables: new Tables(clientProject)
};
export const realtime = {
@@ -83,6 +83,7 @@
const database = await sdk
.forProject(page.params.region, page.params.project)
.databases.create(databaseId, name);
await createPolicies(databaseId);
showCreate = false;
@@ -11,7 +11,7 @@
import { tablesSearcher } from '$lib/commandCenter/searchers';
import { Dependencies } from '$lib/constants';
import type { Models } from '@appwrite.io/console';
import CreateCollection from './createTable.svelte';
import CreateTable from './createTable.svelte';
import { showCreate } from './store';
import { TablesPanel } from '$lib/commandCenter/panels';
import { canWriteCollections, canWriteDatabases } from '$lib/stores/roles';
@@ -23,7 +23,7 @@
const project = page.params.project;
const databaseId = page.params.database;
async function handleCreate(event: CustomEvent<Models.Collection>) {
async function handleCreate(event: CustomEvent<Models.Table>) {
$showCreate = false;
await invalidate(Dependencies.DATABASE);
await goto(
@@ -149,4 +149,4 @@
<slot />
<CreateCollection bind:showCreate={$showCreate} on:created={handleCreate} />
<CreateTable bind:showCreate={$showCreate} on:created={handleCreate} />
@@ -2,7 +2,7 @@
import { Empty, PaginationWithLimit } from '$lib/components';
import { Button } from '$lib/elements/forms';
import { Container, ResponsiveContainerHeader } from '$lib/layout';
import { columns, showCreate } from './store';
import { tableViewColumns, showCreate } from './store';
import Table from './table.svelte';
import Grid from './grid.svelte';
import type { PageData } from './$types';
@@ -16,7 +16,7 @@
<Container>
<ResponsiveContainerHeader
bind:view={data.view}
{columns}
columns={tableViewColumns}
hasSearch
searchPlaceholder="Search by name or ID">
{#if $canWriteCollections}
@@ -27,7 +27,7 @@
{/if}
</ResponsiveContainerHeader>
{#if data.collections.total}
{#if data.tables.total}
{#if data.view === 'grid'}
<Grid {data} bind:showCreate={$showCreate} />
{:else}
@@ -38,13 +38,12 @@
name="Tables"
limit={data.limit}
offset={data.offset}
total={data.collections.total} />
total={data.tables.total} />
{:else}
<!-- TODO: update collections docs url and content later -->
<Empty
single
allowCreate={$canWriteCollections}
href="https://appwrite.io/docs/products/databases/collections"
href="https://appwrite.io/docs/products/databases/tables"
target="table"
on:click={() => ($showCreate = true)} />
{/if}
@@ -5,15 +5,16 @@ import type { PageLoad } from './$types';
import { CARD_LIMIT, Dependencies } from '$lib/constants';
export const load: PageLoad = async ({ params, url, route, depends }) => {
depends(Dependencies.COLLECTIONS);
depends(Dependencies.TABLES);
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 collections = await sdk
const tables = await sdk
.forProject(params.region, params.project)
.databases.listCollections(
.tables.list(
params.database,
[Query.limit(limit), Query.offset(offset), Query.orderDesc('')],
search || undefined
@@ -24,6 +25,6 @@ export const load: PageLoad = async ({ params, url, route, depends }) => {
limit,
search,
view,
collections
tables
};
};
@@ -24,11 +24,13 @@
const create = async () => {
error = null;
try {
const collection = await sdk
const table = await sdk
.forProject(page.params.region, page.params.project)
.databases.createCollection(databaseId, id ? id : ID.unique(), name);
.tables.create(databaseId, id ? id : ID.unique(), name);
showCreate = false;
dispatch('created', collection);
dispatch('created', table);
addNotification({
type: 'success',
message: `${name} has been created`
@@ -18,17 +18,17 @@
let confirmedDeletion = false;
let error = null;
let isLoadingDocumentsCount = false;
let isLoadingRowsCount = false;
$: collectionItems = [];
let collections: Models.CollectionList = null;
$: tableItems = [];
let tables: Models.TableList = null;
function buildQueries(): string[] {
const queries = [Query.orderDesc('$updatedAt')];
if (collectionItems.length > 0) {
if (tableItems.length > 0) {
queries.push(Query.limit(25));
queries.push(Query.offset(collectionItems.length));
queries.push(Query.offset(tableItems.length));
} else {
queries.push(Query.limit(3));
}
@@ -36,32 +36,32 @@
return queries;
}
async function listCollections() {
async function listTables() {
// let's just wait...
if (isLoadingDocumentsCount) return;
if (isLoadingRowsCount) return;
isLoadingDocumentsCount = true;
isLoadingRowsCount = true;
try {
const queries = buildQueries();
collections = await sdk
tables = await sdk
.forProject(page.params.region, page.params.project)
.databases.listCollections(databaseId, queries);
.tables.list(databaseId, queries);
const collectionPromises = collections.collections.map(async (collection) => {
const tablePromises = tables.tables.map(async (table) => {
return {
id: collection.$id,
name: collection.name,
updatedAt: collection.$updatedAt
id: table.$id,
name: table.name,
updatedAt: table.$updatedAt
};
});
collectionItems = [...collectionItems, ...(await Promise.all(collectionPromises))];
tableItems = [...tableItems, ...(await Promise.all(tablePromises))];
} catch (err) {
error = true;
} finally {
isLoadingDocumentsCount = false;
isLoadingRowsCount = false;
}
}
@@ -88,24 +88,24 @@
/* reset data on modal close */
$: if (!showDelete) {
collections = null;
collectionItems = [];
tables = null;
tableItems = [];
} else {
listCollections();
listTables();
}
</script>
<Modal title="Delete database" bind:show={showDelete} onSubmit={handleDelete}>
<p class="text" slot="description">
{#if collectionItems.length > 0}
The following collections and all data associated with <b>{$database.name}</b>, will be
{#if tableItems.length > 0}
The following tables and all data associated with <b>{$database.name}</b>, will be
permanently deleted.
{:else}
Are you sure you want to delete <b>{$database.name}</b>?
{/if}
</p>
{#if isLoadingDocumentsCount}
{#if isLoadingRowsCount}
<div class="u-flex u-main-center">
<Spinner />
</div>
@@ -113,36 +113,36 @@
<p class="text">
Are you sure you want to delete <b>{$database.name}</b>?
</p>
{:else if collectionItems.length > 0}
{:else if tableItems.length > 0}
<div class="u-flex-vertical u-gap-16">
<Table.Root columns={2} let:root>
<svelte:fragment slot="header" let:root>
<Table.Header.Cell {root}>Collection</Table.Header.Cell>
<Table.Header.Cell {root}>Table</Table.Header.Cell>
<Table.Header.Cell {root}>Last Updated</Table.Header.Cell>
</svelte:fragment>
{#each collectionItems as collection}
{#each tableItems as table}
<Table.Row.Base {root}>
<Table.Cell {root}>{collection.name}</Table.Cell>
<Table.Cell {root}>{toLocaleDate(collection.updatedAt)}</Table.Cell>
<Table.Cell {root}>{table.name}</Table.Cell>
<Table.Cell {root}>{toLocaleDate(table.updatedAt)}</Table.Cell>
</Table.Row.Base>
{/each}
</Table.Root>
{#if collectionItems.length < collections.total}
{#if tableItems.length < tables.total}
<div class="u-flex u-gap-16 u-cross-center">
<button class="u-underline" on:click={listCollections} type="button">
<button class="u-underline" on:click={listTables} type="button">
Show more
</button>
{#if isLoadingDocumentsCount}
{#if isLoadingRowsCount}
<div class="loader is-small"></div>
{/if}
</div>
{:else if collectionItems.length > 25}
{:else if tableItems.length > 25}
<button
class="u-underline"
on:click={() => {
collectionItems = collectionItems.slice(0, 3);
tableItems = tableItems.slice(0, 3);
}}
type="button">
Show less
@@ -151,7 +151,7 @@
</div>
{/if}
{#if !isLoadingDocumentsCount}
{#if !isLoadingRowsCount}
<p class="text" data-private>
<b>
Once deleted, this database and its backups cannot be restored. This action is
@@ -162,7 +162,7 @@
<div class="input-check-box-friction">
<InputCheckbox
required
id="delete_policy"
id="delete_database"
bind:checked={confirmedDeletion}
label="I understand and confirm" />
</div>
@@ -2,9 +2,9 @@
import { base } from '$app/paths';
import { page } from '$app/state';
import { CardContainer, GridItem1, Id } from '$lib/components';
import { Pill } from '$lib/elements';
import { canWriteCollections } from '$lib/stores/roles';
import type { PageData } from './$types';
import { Badge } from '@appwrite.io/pink-svelte';
export let data: PageData;
export let showCreate = false;
const projectId = page.params.project;
@@ -13,19 +13,19 @@
<CardContainer
disableEmpty={!$canWriteCollections}
total={data.collections.total}
total={data.tables.total}
on:click={() => (showCreate = true)}
event="table">
{#each data.collections.collections as collection}
{#each data.tables.tables as table}
<GridItem1
href={`${base}/project-${page.params.region}-${projectId}/databases/database-${databaseId}/table-${collection.$id}`}>
<svelte:fragment slot="title">{collection.name}</svelte:fragment>
href={`${base}/project-${page.params.region}-${projectId}/databases/database-${databaseId}/table-${table.$id}`}>
<svelte:fragment slot="title">{table.name}</svelte:fragment>
<svelte:fragment slot="status">
{#if !collection.enabled}
<Pill>disabled</Pill>
{#if !table.enabled}
<Badge variant="secondary" content="disabled" />
{/if}</svelte:fragment>
<Id value={collection.$id}>{collection.$id}</Id>
<Id value={table.$id}>{table.$id}</Id>
</GridItem1>
{/each}
</CardContainer>
@@ -25,10 +25,10 @@
databaseName ??= $database.name;
});
async function loadCollectionCount() {
async function loadTableCount() {
const { total } = await sdk
.forProject(page.params.region, page.params.project)
.databases.listCollections($database.$id, [Query.limit(1)]);
.tables.list($database.$id, [Query.limit(1)]);
return total;
}
@@ -104,7 +104,7 @@
<Layout.Stack direction="column" gap="xxs">
<h6 class="u-bold u-trim-1">{$database.name}</h6>
<Layout.Stack direction="row" gap="s">
{#await loadCollectionCount()}
{#await loadTableCount()}
<Skeleton variant="line" width="100%" height={19.5} />
{:then count}
{count} {count === 1 ? 'Table' : 'Tables'}
@@ -6,8 +6,8 @@ import { derived, writable } from 'svelte/store';
export const database = derived(page, ($page) => $page.data.database as Models.Database);
export const showCreate = writable(false);
export const columns = writable<Column[]>([
{ id: '$id', title: 'Collection ID', type: 'string', width: 200 },
export const tableViewColumns = writable<Column[]>([
{ id: '$id', title: 'Table ID', type: 'string', width: 200 },
{ id: 'name', title: 'Name', type: 'string', width: { min: 120 } },
{ id: '$createdAt', title: 'Created', type: 'datetime', width: { min: 120 } },
{ id: '$updatedAt', title: 'Updated', type: 'datetime', width: { min: 120 } }
@@ -5,15 +5,15 @@
export async function submitString(
databaseId: string,
collectionId: string,
tableId: string,
key: string,
data: Partial<Models.AttributeString>
data: Partial<Models.ColumnString>
) {
await sdk
.forProject(page.params.region, page.params.project)
.databases.createStringAttribute(
.tables.createStringColumn(
databaseId,
collectionId,
tableId,
key,
data.size,
data.required,
@@ -23,15 +23,15 @@
}
export async function updateString(
databaseId: string,
collectionId: string,
data: Partial<Models.AttributeString>,
tableId: string,
data: Partial<Models.ColumnString>,
originalKey?: string
) {
await sdk
.forProject(page.params.region, page.params.project)
.databases.updateStringAttribute(
.tables.updateStringColumn(
databaseId,
collectionId,
tableId,
originalKey,
data.required,
data.default,
@@ -42,10 +42,10 @@
</script>
<script lang="ts">
import { InputChoice, InputNumber, InputText, InputTextarea } from '$lib/elements/forms';
import { createConservative } from '$lib/helpers/stores';
import { InputChoice, InputNumber, InputText, InputTextarea } from '$lib/elements/forms';
export let data: Partial<Models.AttributeString> = {
export let data: Partial<Models.ColumnString> = {
required: false,
size: 0,
default: null,
@@ -67,7 +67,7 @@
const {
stores: { required, array },
listen
} = createConservative<Partial<Models.AttributeString>>({
} = createConservative<Partial<Models.ColumnString>>({
required: false,
array: false,
...data
@@ -22,7 +22,7 @@
import { Dependencies } from '$lib/constants';
import { realtime } from '$lib/stores/sdk';
import { onMount } from 'svelte';
import { collection } from './store';
import { table } from './store';
import { addSubPanel, registerCommands, updateCommandGroupRanks } from '$lib/commandCenter';
import CreateAttribute from './createColumn.svelte';
import { CreateColumnPanel } from '$lib/commandCenter/panels';
@@ -35,26 +35,26 @@
import { IconEye, IconLockClosed, IconPlus, IconPuzzle } from '@appwrite.io/pink-icons-svelte';
onMount(() => {
// TODO: change the events once terminologies are changed on the backend
return realtime
.forProject(page.params.region, page.params.project)
.subscribe(['project', 'console'], (response) => {
if (
response.events.includes('databases.*.collections.*.attributes.*') ||
response.events.includes('databases.*.collections.*.indexes.*')
response.events.includes('databases.*.tables.*.columns.*') ||
response.events.includes('databases.*.tables.*.indexes.*')
) {
invalidate(Dependencies.TABLE);
}
});
});
// TODO: use route ids instead of pathname
$: $registerCommands([
{
label: 'Create row',
keys: page.url.pathname.endsWith($collection.$id) ? ['c'] : ['c', 'd'],
keys: page.url.pathname.endsWith($table.$id) ? ['t'] : ['t', 'd'],
callback() {
goto(
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${$database?.$id}/table-${$collection?.$id}/create`
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${$database?.$id}/table-${$table?.$id}/create`
);
},
icon: IconPlus,
@@ -62,7 +62,7 @@
},
{
label: 'Create column',
keys: page.url.pathname.endsWith('attributes') ? ['c'] : ['c', 'a'],
keys: page.url.pathname.endsWith('columns') ? ['t'] : ['t', 'a'],
callback() {
addSubPanel(CreateColumnPanel);
},
@@ -75,10 +75,10 @@
keys: ['g', 'd'],
callback() {
goto(
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${$database?.$id}/table-${$collection?.$id}`
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${$database?.$id}/table-${$table?.$id}`
);
},
disabled: page.url.pathname.endsWith($collection.$id),
disabled: page.url.pathname.endsWith($table.$id),
group: 'tables'
},
{
@@ -86,7 +86,7 @@
keys: ['g', 'a'],
callback() {
goto(
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${$database?.$id}/table-${$collection?.$id}/attributes`
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${$database?.$id}/table-${$table?.$id}/columns`
);
},
disabled: page.url.pathname.endsWith('columns'),
@@ -97,7 +97,7 @@
keys: ['g', 'i'],
callback() {
goto(
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${$database?.$id}/table-${$collection?.$id}/indexes`
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${$database?.$id}/table-${$table?.$id}/indexes`
);
},
disabled: page.url.pathname.endsWith('indexes'),
@@ -108,7 +108,7 @@
keys: ['g', 'c'],
callback() {
goto(
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${$database?.$id}/table-${$collection?.$id}/activity`
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${$database?.$id}/table-${$table?.$id}/activity`
);
},
disabled: page.url.pathname.endsWith('activity'),
@@ -119,7 +119,7 @@
keys: ['g', 'u'],
callback() {
goto(
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${$database?.$id}/table-${$collection?.$id}/usage`
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${$database?.$id}/table-${$table?.$id}/usage`
);
},
disabled: page.url.pathname.endsWith('usage'),
@@ -130,7 +130,7 @@
keys: ['g', 's'],
callback() {
goto(
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${$database?.$id}/table-${$collection?.$id}/settings`
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${$database?.$id}/table-${$table?.$id}/settings`
);
},
disabled: page.url.pathname.endsWith('settings') || !$canWriteCollections,
@@ -140,7 +140,7 @@
label: 'Display Name',
async callback() {
await goto(
`${base}/project-${$project.region}-${$project.$id}/databases/database-${$database.$id}/table-${$collection.$id}/settings#display-name`
`${base}/project-${$project.region}-${$project.$id}/databases/database-${$database.$id}/table-${$table.$id}/settings#display-name`
);
},
group: 'tables',
@@ -154,7 +154,7 @@
label: 'Permissions',
async callback() {
await goto(
`${base}/project-${$project.region}-${$project.$id}/databases/database-${$database.$id}/table-${$collection.$id}/settings#permissions`
`${base}/project-${$project.region}-${$project.$id}/databases/database-${$database.$id}/table-${$table.$id}/settings#permissions`
);
},
group: 'tables',
@@ -168,7 +168,7 @@
label: 'Row security',
async callback() {
await goto(
`${base}/project-${$project.region}-${$project.$id}/databases/database-${$database.$id}/table-${$collection.$id}/settings#row-security`
`${base}/project-${$project.region}-${$project.$id}/databases/database-${$database.$id}/table-${$table.$id}/settings#row-security`
);
},
group: 'tables',
@@ -199,7 +199,7 @@
</script>
<svelte:head>
<title>{$collection?.name ?? 'Table'} - Appwrite</title>
<title>{$table?.name ?? 'Table'} - Appwrite</title>
</svelte:head>
<slot />
@@ -9,21 +9,19 @@ import { Query } from '@appwrite.io/console';
export const load: LayoutLoad = async ({ params, depends }) => {
depends(Dependencies.TABLE);
const [collection, allCollections] = await Promise.all([
sdk
.forProject(params.region, params.project)
.databases.getCollection(params.database, params.table),
const [table, allTables] = await Promise.all([
sdk.forProject(params.region, params.project).tables.get(params.database, params.table),
sdk
.forProject(params.region, params.project)
.databases.listCollections(params.database, [Query.orderDesc(''), Query.limit(100)])
.tables.list(params.database, [Query.orderDesc(''), Query.limit(100)])
]);
return {
header: Header,
breadcrumbs: Breadcrumbs,
subNavigation: SubNavigation,
collection,
allCollections
table,
allTables
};
};
@@ -12,7 +12,7 @@
import CreateColumnDropdown from './columns/createColumnDropdown.svelte';
import type { Option } from './columns/store';
import CreateColumn from './createColumn.svelte';
import { collection, tableColumns, isCsvImportInProgress } from './store';
import { table, tableColumns, isCsvImportInProgress } from './store';
import Table from './table.svelte';
import { writable } from 'svelte/store';
import FilePicker from '$lib/components/filePicker.svelte';
@@ -29,21 +29,21 @@
export let data: PageData;
let showImportCSV = false;
let showCreateAttribute = false;
let selectedAttribute: Option['name'] = null;
let showCreateColumn = false;
let selectedColumn: Option['name'] = null;
const filterColumns = writable<Column[]>([]);
$: selected = preferences.getCustomCollectionColumns(page.params.table);
$: selected = preferences.getCustomTableColumns(page.params.table);
$: tableColumns.set(
$collection.attributes.map((attribute) => ({
id: attribute.key,
title: attribute.key,
type: attribute.type as ColumnType,
show: selected?.includes(attribute.key) ?? true,
array: attribute?.array,
format: 'format' in attribute && attribute?.format === 'enum' ? attribute.format : null,
elements: 'elements' in attribute ? attribute.elements : null
$table.columns.map((column) => ({
id: column.key,
title: column.key,
type: column.type as ColumnType,
show: selected?.includes(column.key) ?? true,
array: column?.array,
format: 'format' in column && column?.format === 'enum' ? column.format : null,
elements: 'elements' in column ? column.elements : null
}))
);
$: filterColumns.set([
@@ -56,8 +56,8 @@
}))
]);
$: hasAttributes = !!$collection.attributes.length;
$: hasValidAttributes = $collection?.attributes?.some((attr) => attr.status === 'available');
$: hasColumns = !!$table.columns.length;
$: hasValidColumns = $table?.columns?.some((attr) => attr.status === 'available');
async function onSelect(file: Models.File) {
$isCsvImportInProgress = true;
@@ -96,7 +96,7 @@
<Filters
query={data.query}
columns={tableColumns}
disabled={!(hasAttributes && hasValidAttributes)}
disabled={!(hasColumns && hasValidColumns)}
analyticsSource="database_rows" />
<Layout.Stack direction="row" alignItems="center" justifyContent="flex-end">
<ViewSelector view={data.view} columns={tableColumns} hideView />
@@ -104,14 +104,14 @@
<Button
secondary
event={Click.DatabaseImportCsv}
disabled={!(hasAttributes && hasValidAttributes)}
disabled={!(hasColumns && hasValidColumns)}
on:click={() => (showImportCSV = true)}>
Import CSV
</Button>
{/if}
{#if !$isSmallViewport}
<Button
disabled={!(hasAttributes && hasValidAttributes)}
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">
<Icon icon={IconPlus} slot="start" size="s" />
@@ -122,7 +122,7 @@
</Layout.Stack>
{#if $isSmallViewport}
<Button
disabled={!(hasAttributes && hasValidAttributes)}
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">
<Icon icon={IconPlus} slot="start" size="s" />
@@ -131,15 +131,15 @@
{/if}
</Layout.Stack>
{#if hasAttributes && hasValidAttributes}
{#if data.documents.total}
{#if hasColumns && hasValidColumns}
{#if data.rows.total}
<Table {data} />
<PaginationWithLimit
name="Rows"
limit={data.limit}
offset={data.offset}
total={data.documents.total} />
total={data.rows.total} />
{:else if $hasPageQueries}
<EmptySearch hidePages>
<div class="common-section">
@@ -166,12 +166,12 @@
<Empty
allowCreate={$canWriteDocuments}
single
href="https://appwrite.io/docs/products/databases/documents"
href="https://appwrite.io/docs/products/databases/rows"
target="row">
<svelte:fragment slot="actions">
<Button
external
href="https://appwrite.io/docs/products/databases/documents"
href="https://appwrite.io/docs/products/databases/rows"
text
event="empty_documentation"
size="s"
@@ -194,14 +194,14 @@
<slot name="actions" slot="actions">
<Button
external
href="https://appwrite.io/docs/products/databases/collections#attributes"
href="https://appwrite.io/docs/products/databases/tables#columns"
text
event="empty_documentation"
size="s">Documentation</Button>
{#if $canWriteCollections}
<CreateColumnDropdown
bind:selectedOption={selectedAttribute}
bind:showCreate={showCreateAttribute}
bind:selectedOption={selectedColumn}
bind:showCreate={showCreateColumn}
let:toggle>
<Button secondary event="create_column" on:click={toggle}>
Create column
@@ -215,11 +215,8 @@
</Container>
{/key}
<!-- TODO: @itznotabug - change variable name -->
{#if showCreateAttribute}
<CreateColumn
bind:showCreate={showCreateAttribute}
bind:selectedOption={selectedAttribute} />
{#if showCreateColumn}
<CreateColumn bind:showCreate={showCreateColumn} bind:selectedOption={selectedColumn} />
{/if}
{#if showImportCSV}
@@ -22,9 +22,9 @@ export const load: PageLoad = async ({ params, depends, url, route }) => {
limit,
view,
query,
documents: await sdk
rows: await sdk
.forProject(params.region, params.project)
.databases.listDocuments(params.database, params.table, [
.tables.listRows(params.database, params.table, [
Query.limit(limit),
Query.offset(offset),
Query.orderDesc(''),
@@ -14,7 +14,7 @@ export const load: PageLoad = async ({ params, url, route }) => {
limit,
logs: await sdk
.forProject(params.region, params.project)
.databases.listCollectionLogs(params.database, params.table, [
.tables.listLogs(params.database, params.table, [
Query.limit(limit),
Query.offset(offset)
])
@@ -3,7 +3,7 @@
import { page } from '$app/state';
import { Breadcrumbs } from '$lib/layout';
import { database } from '../store';
import { collection } from './store';
import { table } from './store';
$: breadcrumbs = [
{
@@ -18,8 +18,8 @@
title: $database?.name
},
{
href: `${base}/project-${page.params.region}-${page.params.project}/databases/database-${$database?.$id}/table-${$collection?.$id}`,
title: $collection?.name
href: `${base}/project-${page.params.region}-${page.params.project}/databases/database-${$database?.$id}/table-${$table?.$id}`,
title: $table?.name
}
];
</script>
@@ -20,7 +20,7 @@
import { isRelationship, isString } from '../row-[row]/columns/store';
import FailedModal from '../failedModal.svelte';
import CreateIndex from '../indexes/createIndex.svelte';
import { columns, type Attributes, isCsvImportInProgress } from '../store';
import { columns, type Columns, isCsvImportInProgress } from '../store';
import CreateColumnDropdown from './createColumnDropdown.svelte';
import Delete from './deleteColumn.svelte';
import Edit from './edit.svelte';
@@ -45,7 +45,7 @@
let showDropdown = [];
let selectedOption: Option['name'] = null;
let selectedAttribute: Attributes = null;
let selectedColumn: Columns = null;
let showCreate = false;
let showDelete = false;
let showEdit = false;
@@ -53,14 +53,14 @@
let showFailed = false;
let error = '';
const attributeFormatIcon = {
const columnFormatIcon = {
ip: IconLocationMarker,
url: IconLink,
email: IconLink,
enum: IconViewList
};
function getAttributeStatusBadge(status: string): ComponentProps<Badge>['type'] {
function getColumnStatusBadge(status: string): ComponentProps<Badge>['type'] {
switch (status) {
case 'processing':
return 'warning';
@@ -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 attribute, index}
{@const option = columnOptions.find((option) => option.type === attribute.type)}
{#each $columns as column, index}
{@const option = columnOptions.find((option) => option.type === column.type)}
<Table.Row.Base {root}>
<Table.Cell column="key" {root}>
<Layout.Stack direction="row" alignItems="center">
{#if isRelationship(attribute)}
{#if isRelationship(column)}
<Icon
size="s"
icon={attribute?.twoWay
icon={column?.twoWay
? IconSwitchHorizontal
: IconArrowSmRight} />
{:else if 'format' in attribute && attribute.format}
{@const icon = attributeFormatIcon[attribute?.format]}
{:else if 'format' in column && column.format}
{@const icon = columnFormatIcon[column?.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>{attribute.key}</span>
{#if isString(attribute) && attribute.encrypt}
<span class="text u-trim-1" data-private>{column.key}</span>
{#if isString(column) && column.encrypt}
<Tooltip>
<Icon
size="s"
@@ -127,49 +127,49 @@
</Tooltip>
{/if}
</Layout.Stack>
{#if attribute.status !== 'available'}
{#if column.status !== 'available'}
<Badge
size="s"
variant="secondary"
content={attribute.status}
type={getAttributeStatusBadge(attribute.status)} />
{#if attribute.error}
content={column.status}
type={getColumnStatusBadge(column.status)} />
{#if column.error}
<Link.Button
variant="muted"
on:click={(e) => {
e.preventDefault();
error = attribute.error;
error = column.error;
showFailed = true;
}}>Details</Link.Button>
{/if}
{:else if attribute.required}
{:else if column.required}
<Badge size="xs" variant="secondary" content="required" />
{/if}
</Layout.Stack>
</Layout.Stack>
</Table.Cell>
<Table.Cell column="type" {root}>
{#if 'format' in attribute && attribute.format}
<span class="u-capitalize">{attribute.format}</span>
{#if 'format' in column && column.format}
<span class="u-capitalize">{column.format}</span>
{:else}
<p>
<span class="u-capitalize">{attribute.type}</span>
{#if isRelationship(attribute)}
<span class="u-capitalize">{column.type}</span>
{#if isRelationship(column)}
<span>
with <a
href={`${base}/project-${page.params.region}-${page.params.project}/databases/database-${databaseId}/table-${attribute?.relatedCollection}`}
><b data-private>{attribute?.key}</b></a>
href={`${base}/project-${page.params.region}-${page.params.project}/databases/database-${databaseId}/table-${column?.relatedTable}`}
><b data-private>{column?.key}</b></a>
</span>
{/if}
</p>
{/if}
<span>
{attribute.array ? '[]' : ''}
{column.array ? '[]' : ''}
</span>
</Table.Cell>
<Table.Cell column="default" {root}>
{attribute?.default !== null && attribute?.default !== undefined
? attribute?.default
{column?.default !== null && column?.default !== undefined
? column?.default
: '-'}
</Table.Cell>
<Table.Cell column="actions" {root}>
@@ -190,31 +190,31 @@
on:click={(event) => {
toggle(event);
showEdit = true;
selectedAttribute = attribute;
selectedColumn = column;
showDropdown[index] = false;
}}>
Update
</ActionMenu.Item.Button>
{#if !isRelationship(attribute)}
{#if !isRelationship(column)}
<ActionMenu.Item.Button
leadingIcon={IconPlus}
on:click={(event) => {
toggle(event);
selectedAttribute = attribute;
selectedColumn = column;
showCreateIndex = true;
showDropdown[index] = false;
}}>
Create index
</ActionMenu.Item.Button>
{/if}
{#if attribute.status !== 'processing'}
{#if column.status !== 'processing'}
<ActionMenu.Item.Button
leadingIcon={IconTrash}
on:click={(event) => {
toggle(event);
showDelete = true;
showDropdown[index] = false;
selectedAttribute = attribute;
selectedColumn = column;
trackEvent(Click.DatabaseColumnDelete);
}}>
Delete
@@ -232,7 +232,7 @@
<svelte:fragment slot="actions">
<Button
external
href="https://appwrite.io/docs/products/databases/collections#attributes"
href="https://appwrite.io/docs/products/databases/tables#columns"
text
event="empty_documentation"
ariaLabel={'create column'}>Documentation</Button>
@@ -252,13 +252,13 @@
<Create bind:showCreate bind:selectedOption />
{/if}
{#if showDelete}
<Delete bind:showDelete {selectedAttribute} />
<Delete bind:showDelete {selectedColumn} />
{/if}
{#if showEdit}
<Edit bind:showEdit {selectedAttribute} />
<Edit bind:showEdit {selectedColumn} />
{/if}
{#if showCreateIndex}
<CreateIndex bind:showCreateIndex externalAttribute={selectedAttribute} />
<CreateIndex bind:showCreateIndex externalColumn={selectedColumn} />
{/if}
{#if showFailed}
<FailedModal bind:show={showFailed} title="Create column" header="Creation failed" {error} />
@@ -5,15 +5,15 @@
export async function submitBoolean(
databaseId: string,
collectionId: string,
tableId: string,
key: string,
data: Partial<Models.AttributeBoolean>
data: Partial<Models.ColumnBoolean>
) {
await sdk
.forProject(page.params.region, page.params.project)
.databases.createBooleanAttribute(
.tables.createBooleanColumn(
databaseId,
collectionId,
tableId,
key,
data.required,
data.default,
@@ -22,15 +22,15 @@
}
export async function updateBoolean(
databaseId: string,
collectionId: string,
data: Partial<Models.AttributeBoolean>,
tableId: string,
data: Partial<Models.ColumnBoolean>,
originalKey?: string
) {
await sdk
.forProject(page.params.region, page.params.project)
.databases.updateBooleanAttribute(
.tables.updateBooleanColumn(
databaseId,
collectionId,
tableId,
originalKey,
data.required,
data.default,
@@ -43,7 +43,7 @@
import { InputSelect } from '$lib/elements/forms';
export let editing = false;
export let data: Partial<Models.AttributeBoolean> = {
export let data: Partial<Models.ColumnBoolean> = {
required: false,
array: false,
default: null
@@ -66,7 +66,7 @@
const {
stores: { required, array },
listen
} = createConservative<Partial<Models.AttributeBoolean>>({
} = createConservative<Partial<Models.ColumnBoolean>>({
required: false,
array: false,
...data
@@ -5,15 +5,15 @@
export async function submitDatetime(
databaseId: string,
collectionId: string,
tableId: string,
key: string,
data: Partial<Models.AttributeDatetime>
data: Partial<Models.ColumnDatetime>
) {
await sdk
.forProject(page.params.region, page.params.project)
.databases.createDatetimeAttribute(
.tables.createDatetimeColumn(
databaseId,
collectionId,
tableId,
key,
data.required,
data.default,
@@ -23,15 +23,15 @@
export async function updateDatetime(
databaseId: string,
collectionId: string,
data: Partial<Models.AttributeDatetime>,
tableId: string,
data: Partial<Models.ColumnDatetime>,
originalKey?: string
) {
await sdk
.forProject(page.params.region, page.params.project)
.databases.updateDatetimeAttribute(
.tables.updateDatetimeColumn(
databaseId,
collectionId,
tableId,
originalKey,
data.required,
data.default,
@@ -44,7 +44,7 @@
import { InputDateTime } from '$lib/elements/forms';
export let editing = false;
export let data: Partial<Models.AttributeDatetime>;
export let data: Partial<Models.ColumnDatetime>;
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.AttributeDatetime>>({
} = createConservative<Partial<Models.ColumnDatetime>>({
required: false,
array: false,
...data
@@ -4,8 +4,8 @@
import { page } from '$app/state';
import { InputChoice } from '$lib/elements/forms';
import { addNotification } from '$lib/stores/notifications';
import { collection } from '../store';
import type { Attributes } from '../store';
import { table } from '../store';
import type { Columns } from '../store';
import { sdk } from '$lib/stores/sdk';
import { Dependencies } from '$lib/constants';
import { Submit, trackEvent, trackError } from '$lib/actions/analytics';
@@ -13,7 +13,8 @@
import Confirm from '$lib/components/confirm.svelte';
export let showDelete = false;
export let selectedAttribute: Attributes;
export let selectedColumn: Columns;
const databaseId = page.params.database;
let checked = false;
let error: string;
@@ -21,7 +22,7 @@
try {
await sdk
.forProject(page.params.region, page.params.project)
.databases.deleteAttribute(databaseId, $collection.$id, selectedAttribute.key);
.tables.deleteColumn(databaseId, $table.$id, selectedColumn.key);
await invalidate(Dependencies.TABLE);
showDelete = false;
addNotification({
@@ -30,7 +31,7 @@
});
trackEvent(Submit.ColumnDelete);
await goto(
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${databaseId}/table-${page.params.table}/attributes`
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${databaseId}/table-${page.params.table}/columns`
);
} catch (e) {
error = e.message;
@@ -38,8 +39,7 @@
}
}
$: isDeleteBtnDisabled =
isRelationship(selectedAttribute) && selectedAttribute?.twoWay && !checked;
$: isDeleteBtnDisabled = isRelationship(selectedColumn) && selectedColumn?.twoWay && !checked;
</script>
<Confirm
@@ -49,10 +49,10 @@
bind:error
disabled={isDeleteBtnDisabled}>
<p>
Are you sure you want to delete <b data-private>{selectedAttribute?.key}</b> from
<b data-private>{$collection?.name}</b>?
Are you sure you want to delete <b data-private>{selectedColumn?.key}</b> from
<b data-private>{$table?.name}</b>?
</p>
{#if isRelationship(selectedAttribute) && selectedAttribute?.twoWay}
{#if isRelationship(selectedColumn) && selectedColumn?.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
@@ -61,8 +61,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>{selectedAttribute.key}</b> to
<b data-private>{selectedAttribute.twoWayKey}</b>
Delete relationship between <b data-private>{selectedColumn.key}</b> to
<b data-private>{selectedColumn.twoWayKey}</b>
</InputChoice>
</ul>
</div>
@@ -8,41 +8,41 @@
import { Button, InputText } from '$lib/elements/forms';
import deepEqual from 'deep-equal';
import { addNotification } from '$lib/stores/notifications';
import type { Attributes } from '../store';
import type { Columns } from '../store';
import { columnOptions, type Option } from './store';
export let showEdit = false;
export let selectedAttribute: Attributes;
export let selectedColumn: Columns;
const databaseId = page.params.database;
const collectionId = page.params.table;
const tableId = page.params.table;
let originalKey = '';
let error: string;
let currentAttr: Attributes;
let currentColumn: Columns;
$: option = columnOptions.find((option) => {
if (selectedAttribute) {
if ('format' in selectedAttribute && selectedAttribute.format) {
return option?.format === selectedAttribute?.format;
if (selectedColumn) {
if ('format' in selectedColumn && selectedColumn.format) {
return option?.format === selectedColumn?.format;
} else {
return option?.type === selectedAttribute?.type;
return option?.type === selectedColumn?.type;
}
}
}) as Option;
async function submit() {
try {
await option.update(databaseId, collectionId, selectedAttribute, originalKey);
await option.update(databaseId, tableId, selectedColumn, originalKey);
await invalidate(Dependencies.TABLE);
if (!page.url.pathname.includes('attributes')) {
if (!page.url.pathname.includes('columns')) {
await goto(
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${databaseId}/table-${collectionId}/attributes`
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${databaseId}/table-${tableId}/columns`
);
}
addNotification({
type: 'success',
message: `Column ${selectedAttribute.key} has been updated`
message: `Column ${selectedColumn.key} has been updated`
});
showEdit = false;
trackEvent(Submit.ColumnUpdate);
@@ -57,11 +57,11 @@
function onShow(show: boolean) {
if (show) {
currentAttr ??= { ...selectedAttribute };
originalKey = currentAttr.key;
currentColumn ??= { ...selectedColumn };
originalKey = currentColumn.key;
error = null;
} else {
currentAttr = null;
currentColumn = null;
}
}
</script>
@@ -78,26 +78,26 @@
</div>
</svelte:fragment>
{#if selectedAttribute}
{#if selectedAttribute?.type !== 'relationship'}
{#if selectedColumn}
{#if selectedColumn?.type !== 'relationship'}
<InputText
id="key"
label="Column Key"
placeholder="Enter Key"
bind:value={selectedAttribute.key}
bind:value={selectedColumn.key}
autofocus />
{/if}
{#if option}
<svelte:component
this={option.component}
editing
bind:data={selectedAttribute}
bind:data={selectedColumn}
onclose={() => (option = null)} />
{/if}
{/if}
<svelte:fragment slot="footer">
<Button secondary on:click={() => (showEdit = false)}>Cancel</Button>
<Button submit disabled={deepEqual(currentAttr, selectedAttribute)}>Update</Button>
<Button submit disabled={deepEqual(currentColumn, selectedColumn)}>Update</Button>
</svelte:fragment>
</Modal>
@@ -5,15 +5,15 @@
export async function submitEmail(
databaseId: string,
collectionId: string,
tableId: string,
key: string,
data: Partial<Models.AttributeEmail>
data: Partial<Models.ColumnEmail>
) {
await sdk
.forProject(page.params.region, page.params.project)
.databases.createEmailAttribute(
.tables.createEmailColumn(
databaseId,
collectionId,
tableId,
key,
data.required,
data.default,
@@ -23,15 +23,15 @@
export async function updateEmail(
databaseId: string,
collectionId: string,
data: Partial<Models.AttributeEmail>,
tableId: string,
data: Partial<Models.ColumnEmail>,
originalKey?: string
) {
await sdk
.forProject(page.params.region, page.params.project)
.databases.updateEmailAttribute(
.tables.updateEmailColumn(
databaseId,
collectionId,
tableId,
originalKey,
data.required,
data.default,
@@ -44,7 +44,7 @@
import { InputEmail } from '$lib/elements/forms';
export let editing = false;
export let data: Partial<Models.AttributeEmail>;
export let data: Partial<Models.ColumnEmail>;
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.AttributeEmail>>({
} = createConservative<Partial<Models.ColumnEmail>>({
required: false,
array: false,
...data
@@ -5,15 +5,15 @@
export async function submitEnum(
databaseId: string,
collectionId: string,
tableId: string,
key: string,
data: Partial<Models.AttributeEnum>
data: Partial<Models.ColumnEnum>
) {
await sdk
.forProject(page.params.region, page.params.project)
.databases.createEnumAttribute(
.tables.createEnumColumn(
databaseId,
collectionId,
tableId,
key,
data.elements,
data.required,
@@ -24,15 +24,15 @@
export async function updateEnum(
databaseId: string,
collectionId: string,
data: Partial<Models.AttributeEnum>,
tableId: string,
data: Partial<Models.ColumnEnum>,
originalKey?: string
) {
await sdk
.forProject(page.params.region, page.params.project)
.databases.updateEnumAttribute(
.tables.updateEnumColumn(
databaseId,
collectionId,
tableId,
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.AttributeEnum>;
export let data: Partial<Models.ColumnEnum>;
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.AttributeEnum>>({
} = createConservative<Partial<Models.ColumnEnum>>({
required: false,
array: false,
...data
@@ -5,15 +5,15 @@
export async function submitFloat(
databaseId: string,
collectionId: string,
tableId: string,
key: string,
data: Partial<Models.AttributeFloat>
data: Partial<Models.ColumnFloat>
) {
await sdk
.forProject(page.params.region, page.params.project)
.databases.createFloatAttribute(
.tables.createFloatColumn(
databaseId,
collectionId,
tableId,
key,
data.required,
data.min,
@@ -25,15 +25,15 @@
export async function updateFloat(
databaseId: string,
collectionId: string,
data: Partial<Models.AttributeFloat>,
tableId: string,
data: Partial<Models.ColumnFloat>,
originalKey?: string
) {
await sdk
.forProject(page.params.region, page.params.project)
.databases.updateFloatAttribute(
.tables.updateFloatColumn(
databaseId,
collectionId,
tableId,
originalKey,
data.required,
data.default,
@@ -48,7 +48,7 @@
import { InputNumber } from '$lib/elements/forms';
export let editing = false;
export let data: Partial<Models.AttributeFloat> = {
export let data: Partial<Models.ColumnFloat> = {
required: false,
min: 0,
max: 0,
@@ -73,7 +73,7 @@
const {
stores: { required, array },
listen
} = createConservative<Partial<Models.AttributeFloat>>({
} = createConservative<Partial<Models.ColumnFloat>>({
required: false,
array: false,
...data
@@ -5,15 +5,15 @@
export async function submitInteger(
databaseId: string,
collectionId: string,
tableId: string,
key: string,
data: Partial<Models.AttributeInteger>
data: Partial<Models.ColumnInteger>
) {
await sdk
.forProject(page.params.region, page.params.project)
.databases.createIntegerAttribute(
.tables.createIntegerColumn(
databaseId,
collectionId,
tableId,
key,
data.required,
data.min,
@@ -25,15 +25,15 @@
export async function updateInteger(
databaseId: string,
collectionId: string,
data: Partial<Models.AttributeInteger>,
tableId: string,
data: Partial<Models.ColumnInteger>,
originalKey?: string
) {
await sdk
.forProject(page.params.region, page.params.project)
.databases.updateIntegerAttribute(
.tables.updateIntegerColumn(
databaseId,
collectionId,
tableId,
originalKey,
data.required,
data.default,
@@ -49,7 +49,7 @@
export let editing = false;
export let data: Partial<Models.AttributeInteger> = {
export let data: Partial<Models.ColumnInteger> = {
required: false,
min: 0,
max: 0,
@@ -74,7 +74,7 @@
const {
stores: { required, array },
listen
} = createConservative<Partial<Models.AttributeInteger>>({
} = createConservative<Partial<Models.ColumnInteger>>({
required: false,
array: false,
...data
@@ -5,15 +5,15 @@
export async function submitIp(
databaseId: string,
collectionId: string,
tableId: string,
key: string,
data: Partial<Models.AttributeIp>
data: Partial<Models.ColumnIp>
) {
await sdk
.forProject(page.params.region, page.params.project)
.databases.createIpAttribute(
.tables.createIpColumn(
databaseId,
collectionId,
tableId,
key,
data.required,
data.default,
@@ -22,15 +22,15 @@
}
export async function updateIp(
databaseId: string,
collectionId: string,
data: Partial<Models.AttributeIp>,
tableId: string,
data: Partial<Models.ColumnIp>,
originalKey?: string
) {
await sdk
.forProject(page.params.region, page.params.project)
.databases.updateIpAttribute(
.tables.updateIpColumn(
databaseId,
collectionId,
tableId,
originalKey,
data.required,
data.default,
@@ -43,7 +43,7 @@
import { InputText } from '$lib/elements/forms';
export let editing = false;
export let data: Partial<Models.AttributeIp>;
export let data: Partial<Models.ColumnIp>;
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.AttributeIp>>({
} = createConservative<Partial<Models.ColumnIp>>({
required: false,
array: false,
...data
@@ -6,9 +6,9 @@
export async function submitRelationship(
databaseId: string,
collectionId: string,
tableId: string,
_key: string,
data: Partial<Models.AttributeRelationship>
data: Partial<Models.ColumnRelationship>
) {
if (!isValueOfStringEnum(RelationshipType, data.relationType)) {
throw new Error(
@@ -21,10 +21,10 @@
await sdk
.forProject(page.params.region, page.params.project)
.databases.createRelationshipAttribute(
.tables.createRelationshipColumn(
databaseId,
collectionId,
data.relatedCollection,
tableId,
data.relatedTable,
data.relationType,
data.twoWay,
data.key,
@@ -35,8 +35,8 @@
export async function updateRelationship(
databaseId: string,
collectionId: string,
data: Partial<Models.AttributeRelationship>,
tableId: string,
data: Partial<Models.ColumnRelationship>,
originalKey?: string
) {
if (!isValueOfStringEnum(RelationMutate, data.onDelete)) {
@@ -45,9 +45,9 @@
await sdk
.forProject(page.params.region, page.params.project)
.databases.updateRelationshipAttribute(
.tables.updateRelationshipColumn(
databaseId,
collectionId,
tableId,
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 { collection } from '../store';
import { table } 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.AttributeRelationship;
export let data: Models.ColumnRelationship;
// Constants
const databaseId = page.params.database;
@@ -89,39 +89,37 @@
// Variables
let way = 'one';
let search = undefined;
let collectionList: Models.CollectionList;
let originalCollectionList: Models.CollectionList;
let tableList: Models.TableList;
let originalTableList: Models.TableList;
// Lifecycle hooks
async function getCollections() {
async function getTables() {
const queries = [Query.limit(100)];
return sdk
.forProject(page.params.region, page.params.project)
.databases.listCollections(databaseId, queries, search);
.tables.list(databaseId, queries, search);
}
const debouncedFetchCollections = debounce(async () => {
collectionList = await getCollections();
const debouncedFetchTables = debounce(async () => {
tableList = await getTables();
// reset search
search = undefined;
}, 500);
function updateKeyName() {
if (!editing) {
const collection = collectionList.collections.find(
(n) => n.$id === data.relatedCollection
);
const collection = tableList.tables.find((n) => n.$id === data.relatedTable);
data.key = camelize(collection.name);
}
}
onMount(async () => {
collectionList = await getCollections();
originalCollectionList = collectionList;
tableList = await getTables();
originalTableList = tableList;
});
// Reactive statements
$: collections = collectionList?.collections?.filter((n) => n.$id !== $collection.$id) ?? [];
$: collections = tableList?.tables?.filter((n) => n.$id !== $table.$id) ?? [];
$: if (editing) {
way = data.twoWay ? 'two' : 'one';
@@ -129,26 +127,26 @@
if (way === 'two') {
data.twoWay = true;
if (!data.twoWayKey) {
data.twoWayKey = camelize($collection.name);
data.twoWayKey = camelize($table.name);
}
} else {
data.twoWay = false;
}
}
$: search = data.relatedCollection || undefined;
$: search = data.relatedTable || undefined;
$: if (search) {
const exists = collectionList?.collections?.some((c) =>
const exists = tableList?.tables?.some((c) =>
c.$id.toLocaleLowerCase().includes(search.toLocaleLowerCase())
);
if (!exists) {
debouncedFetchCollections();
debouncedFetchTables();
}
} else if (!collectionList?.total) {
} else if (!tableList?.total) {
// reset to original list!
collectionList = originalCollectionList;
tableList = originalTableList;
}
</script>
@@ -176,11 +174,11 @@
id="related"
label="Related table"
placeholder="Select a table"
bind:value={data.relatedCollection}
bind:value={data.relatedTable}
on:change={updateKeyName}
options={collections?.map((n) => ({ value: n.$id, label: `${n.name} (${n.$id})` })) ?? []} />
{#if data?.relatedCollection}
{#if data?.relatedTable}
<InputText
id="key"
label="Column key"
@@ -212,7 +210,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($collection.name)}</span>
<span data-private>{camelize($table.name)}</span>
{#if data.twoWay}
<img src={arrowTwo} alt={'Two way relationship'} />
{:else}
@@ -224,7 +222,7 @@
{#if data.relationType}
<div>
<p class="u-text-center">
<b data-private>{camelize($collection.name)}</b> can contain {[
<b data-private>{camelize($table.name)}</b> can contain {[
'oneToOne',
'manyToOne'
].includes(data.relationType)
@@ -237,7 +235,7 @@
can belong to {['oneToOne', 'oneToMany'].includes(data.relationType)
? 'one'
: 'many'}
<b data-private>{camelize($collection.name)}</b>
<b data-private>{camelize($table.name)}</b>
</p>
</div>
{/if}
@@ -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 { Attributes } from '../store';
import type { Columns } from '../store';
import Relationship, { submitRelationship, updateRelationship } from './relationship.svelte';
import {
IconCalendar,
@@ -41,14 +41,14 @@ export type Option = {
type: 'string' | 'integer' | 'double' | 'boolean' | 'datetime' | 'relationship';
create: (
databaseId: string,
collectionId: string,
tableId: string,
key: string,
data: Partial<Attributes>
data: Partial<Columns>
) => Promise<void>;
update: (
databaseId: string,
collectionId: string,
data: Partial<Attributes>,
tableId: string,
data: Partial<Columns>,
originalKey: string
) => Promise<void>;
format?: 'email' | 'ip' | 'url' | 'enum';
@@ -5,15 +5,15 @@
export async function submitString(
databaseId: string,
collectionId: string,
tableId: string,
key: string,
data: Partial<Models.AttributeString>
data: Partial<Models.ColumnString>
) {
await sdk
.forProject(page.params.region, page.params.project)
.databases.createStringAttribute(
.tables.createStringColumn(
databaseId,
collectionId,
tableId,
key,
data.size,
data.required,
@@ -24,15 +24,15 @@
}
export async function updateString(
databaseId: string,
collectionId: string,
data: Partial<Models.AttributeString>,
tableId: string,
data: Partial<Models.ColumnString>,
originalKey?: string
) {
await sdk
.forProject(page.params.region, page.params.project)
.databases.updateStringAttribute(
.tables.updateStringColumn(
databaseId,
collectionId,
tableId,
originalKey,
data.required,
data.default,
@@ -52,7 +52,7 @@
import { Popover, Layout, Tag, Typography, Link } from '@appwrite.io/pink-svelte';
import { flags } from '$lib/flags';
export let data: Partial<Models.AttributeString> = {
export let data: Partial<Models.ColumnString> = {
required: false,
size: 0,
array: false,
@@ -77,7 +77,7 @@
const {
stores: { required, array },
listen
} = createConservative<Partial<Models.AttributeString>>({
} = createConservative<Partial<Models.ColumnString>>({
required: false,
array: false,
...data
@@ -5,15 +5,15 @@
export async function submitUrl(
databaseId: string,
collectionId: string,
tableId: string,
key: string,
data: Partial<Models.AttributeUrl>
data: Partial<Models.ColumnUrl>
) {
await sdk
.forProject(page.params.region, page.params.project)
.databases.createUrlAttribute(
.tables.createUrlColumn(
databaseId,
collectionId,
tableId,
key,
data.required,
data.default,
@@ -23,15 +23,15 @@
export async function updateUrl(
databaseId: string,
collectionId: string,
data: Partial<Models.AttributeUrl>,
tableId: string,
data: Partial<Models.ColumnUrl>,
originalKey?: string
) {
await sdk
.forProject(page.params.region, page.params.project)
.databases.updateUrlAttribute(
.tables.updateUrlColumn(
databaseId,
collectionId,
tableId,
originalKey,
data.required,
data.default,
@@ -43,7 +43,7 @@
<script lang="ts">
import { InputURL } from '$lib/elements/forms';
export let data: Partial<Models.AttributeUrl>;
export let data: Partial<Models.ColumnUrl>;
export let editing = false;
import { createConservative } from '$lib/helpers/stores';
@@ -63,7 +63,7 @@
const {
stores: { required, array },
listen
} = createConservative<Partial<Models.AttributeUrl>>({
} = createConservative<Partial<Models.ColumnUrl>>({
required: false,
array: false,
...data
@@ -13,7 +13,7 @@
import ColumnForm from '../row-[row]/columnForm.svelte';
import { Permissions } from '$lib/components/permissions';
import type { PageData } from './$types';
import type { Attributes } from '../store';
import type { Columns } from '../store';
import { ID } from '@appwrite.io/console';
export let data: PageData;
@@ -24,41 +24,41 @@
type CreateDocument = {
id?: string;
document: object;
row: object;
permissions: string[];
attributes: Attributes[];
columns: Columns[];
};
function createDocumentWritable() {
const availableAttributes = (data.collection.attributes as unknown as Attributes[]).filter(
function createRowWritable() {
const availableColumns = (data.table.columns as unknown as Columns[]).filter(
(a) => a.status === 'available'
);
const initial = {
id: null,
document: availableAttributes.reduce((acc, attr) => {
row: availableColumns.reduce((acc, attr) => {
acc[attr.key] = attr.array ? [] : null;
return acc;
}, {}),
permissions: [],
attributes: availableAttributes
columns: availableColumns
};
return writable<CreateDocument>({ ...initial });
}
const createDocument = createDocumentWritable();
const createRow = createRowWritable();
async function create() {
try {
const { $id } = await sdk
.forProject(page.params.region, page.params.project)
.databases.createDocument(
.tables.createRow(
page.params.database,
page.params.table,
$createDocument.id ?? ID.unique(),
$createDocument.document,
$createDocument.permissions
$createRow.id ?? ID.unique(),
$createRow.row,
$createRow.permissions
);
addNotification({
@@ -66,7 +66,7 @@
type: 'success'
});
trackEvent(Submit.RowCreate, {
customId: !!$createDocument.id
customId: !!$createRow.id // todo: @itznotabug - change store name
});
goto(
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${page.params.database}/table-${page.params.table}/row-${$id}`
@@ -92,9 +92,9 @@
<Layout.Stack gap="xxl">
<Fieldset legend="Data">
<ColumnForm
bind:formValues={$createDocument.document}
attributes={$createDocument.attributes}
bind:customId={$createDocument.id} />
bind:formValues={$createRow.row}
columns={$createRow.columns}
bind:customId={$createRow.id} />
</Fieldset>
<Fieldset legend="Permissions">
@@ -103,13 +103,13 @@
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.collection.documentSecurity}
{#if data.table.rowSecurity}
<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>.
</Alert.Inline>
<Permissions bind:permissions={$createDocument.permissions} />
<Permissions bind:permissions={$createRow.permissions} />
{:else}
<Alert.Inline status="info">
<svelte:fragment slot="title">Row security is disabled</svelte:fragment>
@@ -11,7 +11,7 @@
import { page } from '$app/state';
import { addNotification } from '$lib/stores/notifications';
import { base } from '$app/paths';
import type { Attributes } from './store';
import type { Columns } from './store';
import { Submit, trackEvent, trackError } from '$lib/actions/analytics';
import { preferences } from '$lib/stores/preferences';
@@ -22,7 +22,7 @@
const databaseId = page.params.database;
let key: string = null;
let data: Partial<Attributes> = {
let data: Partial<Columns> = {
required: false,
array: false,
default: null
@@ -33,7 +33,7 @@
try {
await $option.create(databaseId, tableId, key, data);
let selectedColumns = preferences.getCustomCollectionColumns(tableId);
let selectedColumns = preferences.getCustomTableColumns(tableId);
selectedColumns.push(key ?? data?.key);
preferences.setCustomCollectionColumns(selectedColumns);
await invalidate(Dependencies.TABLE);
@@ -5,15 +5,15 @@
import { isTabSelected } from '$lib/helpers/load';
import { Cover, CoverTitle } from '$lib/layout';
import { canWriteCollections } from '$lib/stores/roles';
import { collection } from './store';
import { table } from './store';
import { isTabletViewport } from '$lib/stores/viewport';
const databaseId = $derived(page.params.database);
const collectionId = $derived(page.params.table);
const tableId = $derived(page.params.table);
const path = $derived(
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${databaseId}/table-${collectionId}`
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${databaseId}/table-${tableId}`
);
const tabs = $derived(
@@ -61,10 +61,10 @@
<svelte:fragment slot="header">
<CoverTitle
href={`${base}/project-${page.params.region}-${page.params.project}/databases/database-${databaseId}`}>
{$collection?.name}
{$table?.name}
</CoverTitle>
{#key $collection?.$id}
<Id value={$collection?.$id}>{$collection?.$id}</Id>
{#key $table?.$id}
<Id value={$table?.$id}>{$table?.$id}</Id>
{/key}
</svelte:fragment>
@@ -1,7 +1,7 @@
<script lang="ts">
import { Empty } from '$lib/components';
import { Container } from '$lib/layout';
import { collection } from '../store';
import { table } from '../store';
import Delete from './deleteIndex.svelte';
import Create from './createIndex.svelte';
import Overview from './overviewIndex.svelte';
@@ -33,16 +33,16 @@
export let data;
let selectedIndex: Models.Index = null;
let showCreateIndex = false;
let showOverview = false;
let showDelete = false;
let showCreateAttribute = false;
let selectedAttribute: Option['name'] = null;
let showFailed = false;
let error = '';
let showFailed = false;
let showDelete = false;
let showOverview = false;
let showCreateIndex = false;
let showCreateColumn = false;
let selectedColumn: Option['name'] = null;
let selectedIndex: Models.ColumnIndex = null;
function getAttributeStatusBadge(status: string): ComponentProps<Badge>['type'] {
function getColumnStatusBadge(status: string): ComponentProps<Badge>['type'] {
switch (status) {
case 'processing':
return 'warning';
@@ -62,7 +62,7 @@
{#if $canWriteCollections}
<Button
event="create_index"
disabled={!$collection?.attributes?.length}
disabled={!$table?.columns?.length}
on:click={() => (showCreateIndex = true)}>
<Icon icon={IconPlus} slot="start" size="s" />
Create index
@@ -70,8 +70,8 @@
{/if}
</Layout.Stack>
{#if data.collection?.attributes?.length}
{#if data.collection.indexes.length}
{#if data.table?.columns?.length}
{#if data.table.indexes.length}
<Table.Root
let:root
columns={[
@@ -90,7 +90,7 @@
<Table.Header.Cell column="lengths" {root}>Lengths</Table.Header.Cell>
<Table.Header.Cell column="actions" {root} />
</svelte:fragment>
{#each data.collection.indexes as index}
{#each data.table.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={getAttributeStatusBadge(index.status)} />
type={getColumnStatusBadge(index.status)} />
{#if index.error}
<Link.Button
variant="muted"
@@ -115,7 +115,7 @@
</Table.Cell>
<Table.Cell column="type" {root}>{index.type}</Table.Cell>
<Table.Cell column="columns" {root}>
{index.attributes}
{index.columns}
</Table.Cell>
<Table.Cell column="orders" {root}>
{index.orders}
@@ -152,7 +152,7 @@
<Empty
allowCreate={$canWriteCollections}
single
href="https://appwrite.io/docs/products/databases/collections#indexes"
href="https://appwrite.io/docs/products/databases/tables#indexes"
target="index"
on:click={() => (showCreateIndex = true)} />
{/if}
@@ -161,16 +161,16 @@
<svelte:fragment slot="actions">
<Button
external
href="https://appwrite.io/docs/products/databases/collections#attributes"
href="https://appwrite.io/docs/products/databases/tables#columns"
text
event="empty_documentation"
ariaLabel="create index">Documentation</Button>
{#if $canWriteCollections}
<CreateColumnDropdown
bind:selectedOption={selectedAttribute}
bind:showCreate={showCreateAttribute}
bind:selectedOption={selectedColumn}
bind:showCreate={showCreateColumn}
let:toggle>
<Button secondary event="create_attribute" on:click={toggle}>
<Button secondary event="create_column" on:click={toggle}>
Create column
</Button>
</CreateColumnDropdown>
@@ -187,11 +187,8 @@
<Overview bind:showOverview {selectedIndex} />
{/if}
<!--todo: @itznotabug - var name -->
{#if showCreateAttribute}
<CreateColumn
bind:showCreate={showCreateAttribute}
bind:selectedOption={selectedAttribute} />
{#if showCreateColumn}
<CreateColumn bind:showCreate={showCreateColumn} bind:selectedOption={selectedColumn} />
{/if}
<FailedModal bind:show={showFailed} title="Create index" header="Creation failed" {error} />
@@ -11,13 +11,13 @@
import { sdk } from '$lib/stores/sdk';
import { IndexType } from '@appwrite.io/console';
import { isRelationship } from '../row-[row]/columns/store';
import { type Attributes, collection, indexes } from '../store';
import { type Columns, table, 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 externalAttribute: Attributes = null;
export let externalColumn: Columns = null;
const databaseId = page.params.database;
@@ -30,14 +30,14 @@
];
let selectedType = IndexType.Key;
let attributeOptions = $collection.attributes
.filter((attribute) => !isRelationship(attribute))
.map((attribute) => ({
value: attribute.key,
label: attribute.key
let columnOptions = $table.columns
.filter((column) => !isRelationship(column))
.map((column) => ({
value: column.key,
label: column.key
}));
let attributeList = [{ value: '', order: '', length: null }];
let columnList = [{ value: '', order: '', length: null }];
const showLengths = flags.showIndexLengths(page.data);
@@ -53,8 +53,8 @@
}
function initialize() {
attributeList = externalAttribute
? [{ value: externalAttribute.key, order: 'ASC', length: null }]
columnList = externalColumn
? [{ value: externalColumn.key, order: 'ASC', length: null }]
: [{ value: '', order: 'ASC', length: null }];
selectedType = IndexType.Key;
key = `index_${$indexes.length + 1}`;
@@ -66,23 +66,23 @@
key = generateIndexKey();
}
$: addAttributeDisabled = !attributeList.at(-1)?.value || !attributeList.at(-1)?.order;
$: addColumnDisabled = !columnList.at(-1)?.value || !columnList.at(-1)?.order;
async function create() {
if (!(key && selectedType && !addAttributeDisabled)) {
if (!(key && selectedType && !addColumnDisabled)) {
error = 'All fields are required';
return;
}
try {
await sdk.forProject(page.params.region, page.params.project).databases.createIndex(
await sdk.forProject(page.params.region, page.params.project).tables.createIndex(
databaseId,
$collection.$id,
$table.$id,
key,
selectedType,
attributeList.map((a) => a.value),
attributeList.map((a) => a.order),
attributeList.map((a) => (a.length ? Number(a.length) : null))
columnList.map((a) => a.value),
columnList.map((a) => a.order),
columnList.map((a) => (a.length ? Number(a.length) : null))
);
await Promise.allSettled([
@@ -91,7 +91,7 @@
]);
goto(
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${databaseId}/table-${$collection.$id}/indexes`
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${databaseId}/table-${$table.$id}/indexes`
);
addNotification({
@@ -106,11 +106,11 @@
}
}
function addAttribute() {
if (addAttributeDisabled) return;
function addColumn() {
if (addColumnDisabled) return;
// We assign instead of pushing to trigger Svelte's reactivity
attributeList = [...attributeList, { value: '', order: '', length: null }];
columnList = [...columnList, { 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 attributeList as attribute, i}
{#each columnList as column, index}
<Layout.Stack direction="row">
<InputSelect
required
@@ -133,12 +133,12 @@
{ value: '$id', label: '$id' },
{ value: '$createdAt', label: '$createdAt' },
{ value: '$updatedAt', label: '$updatedAt' },
...attributeOptions
...columnOptions
]}
id={`column-${i}`}
label={i === 0 ? 'Column' : undefined}
id={`column-${index}`}
label={index === 0 ? 'Column' : undefined}
placeholder="Select column"
bind:value={attribute.value} />
bind:value={column.value} />
<InputSelect
options={[
@@ -146,25 +146,25 @@
{ value: 'DESC', label: 'DESC' }
]}
required
id={`order-${i}`}
label={i === 0 ? 'Order' : undefined}
bind:value={attribute.order}
id={`order-${index}`}
label={index === 0 ? 'Order' : undefined}
bind:value={column.order}
placeholder="Select order" />
<Layout.Stack direction="row" alignItems="flex-end" gap="xs">
{#if selectedType === IndexType.Key && showLengths}
<InputNumber
id={`length-${i}`}
label={i === 0 ? 'Length' : undefined}
id={`length-${index}`}
label={index === 0 ? 'Length' : undefined}
placeholder="Enter length"
bind:value={attribute.length} />
bind:value={column.length} />
{/if}
<Button
icon
compact
disabled={attributeList.length <= 1}
disabled={columnList.length <= 1}
on:click={() => {
attributeList = remove(attributeList, i);
columnList = remove(columnList, index);
}}>
<span class="icon-x" aria-hidden="true"></span>
</Button>
@@ -172,7 +172,7 @@
</Layout.Stack>
{/each}
<div>
<Button compact on:click={addAttribute} disabled={addAttributeDisabled}>
<Button compact on:click={addColumn} disabled={addColumnDisabled}>
<Icon icon={IconPlus} slot="start" size="s" />
Add column
</Button>
@@ -1,6 +1,6 @@
<script lang="ts">
import { addNotification } from '$lib/stores/notifications';
import { collection } from '../store';
import { table } from '../store';
import { sdk } from '$lib/stores/sdk';
import type { Models } from '@appwrite.io/console';
import { page } from '$app/state';
@@ -11,16 +11,16 @@
import { Typography } from '@appwrite.io/pink-svelte';
export let showDelete = false;
export let selectedIndex: Models.Index;
export let selectedIndex: Models.ColumnIndex;
const databaseId = page.params.database;
let error: string;
const databaseId = page.params.database;
async function handleDelete() {
try {
await sdk
.forProject(page.params.region, page.params.project)
.databases.deleteIndex(databaseId, $collection.$id, selectedIndex.key);
.tables.deleteIndex(databaseId, $table.$id, selectedIndex.key);
await invalidate(Dependencies.TABLE);
showDelete = false;
addNotification({
@@ -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>{$collection.name}</b>?
Are you sure you want to delete <b>{selectedIndex.key}</b> from <b>{$table.name}</b>?
</Typography.Text>
</Confirm>
@@ -7,7 +7,7 @@
import { flags } from '$lib/flags';
export let showOverview = false;
export let selectedIndex: Models.Index = null;
export let selectedIndex: Models.ColumnIndex = null;
const showLengths = flags.showIndexLengths(page.data);
</script>
@@ -28,14 +28,14 @@
value={selectedIndex.type}
readonly />
{#if selectedIndex?.attributes?.length}
{#each selectedIndex.attributes as attribute, i}
{#if selectedIndex?.columns?.length}
{#each selectedIndex.columns as column, i}
<Layout.Stack direction="row">
<InputText
required
label={i === 0 ? 'Column' : ''}
id={`value-${attribute}`}
value={attribute}
id={`value-${column}`}
value={column}
readonly />
<InputText
required
@@ -9,14 +9,14 @@
export let show = false;
export let data: Partial<Models.Document>[];
export let selectedRelationship: Models.AttributeRelationship = null;
export let selectedRelationship: Models.ColumnRelationship = null;
const databaseId = page.params.database;
const limit = 10;
$: args =
preferences
.getDisplayNames()
?.[selectedRelationship?.relatedCollection]?.filter((p) => p !== '$id') ?? [];
?.[selectedRelationship?.relatedTable]?.filter((p) => p !== '$id') ?? [];
$: if (!show) {
data = null;
@@ -42,7 +42,7 @@
{#each paginatedItems as doc}
<Table.Row.Link
{root}
href={`${base}/project-${page.params.region}-${page.params.project}/databases/database-${databaseId}/table-${selectedRelationship.relatedCollection}/row-${doc.$id}`}
href={`${base}/project-${page.params.region}-${page.params.project}/databases/database-${databaseId}/table-${selectedRelationship.relatedTable}/row-${doc.$id}`}
on:click={() => (show = false)}>
<Table.Cell column="$id" {root}>
<Id value={doc.$id}>{doc.$id}</Id>
@@ -3,34 +3,34 @@ import { Dependencies } from '$lib/constants';
import type { LayoutLoad } from './$types';
import Breadcrumbs from './breadcrumbs.svelte';
import Header from './header.svelte';
import type { Attributes } from '../store';
import type { Columns } from '../store';
export const load: LayoutLoad = async ({ params, parent, depends }) => {
depends(Dependencies.ROW);
const { collection } = await parent();
const { table } = await parent();
const document = await sdk
const row = await sdk
.forProject(params.region, params.project)
.databases.getDocument(params.database, params.table, params.row);
.tables.getRow(params.database, params.table, params.row);
/**
* Sanitize DateTime to remove UTC Timezone section.
*/
collection.attributes.forEach((attribute) => {
const { type, key, array } = attribute as unknown as Attributes;
table.columns.forEach((column) => {
const { type, key, array } = column as unknown as Columns;
if (type === 'datetime') {
if (array) {
document[key] = document[key].map((n: string) => {
row[key] = row[key].map((n: string) => {
if (!n) {
return null;
}
return new Date(n).toISOString().slice(0, 23);
});
} else {
if (document[key]) {
document[key] = new Date(document[key]).toISOString().slice(0, 23);
if (row[key]) {
row[key] = new Date(row[key]).toISOString().slice(0, 23);
} else {
document[key] = null;
row[key] = null;
}
}
}
@@ -39,6 +39,6 @@ export const load: LayoutLoad = async ({ params, parent, depends }) => {
return {
header: Header,
breadcrumbs: Breadcrumbs,
document
row
};
};
@@ -11,36 +11,36 @@
import type { Models } from '@appwrite.io/console';
import { Dependencies } from '$lib/constants';
import { invalidate } from '$app/navigation';
import { doc } from './store';
import { collection, type Attributes } from '../store';
import { row } from './store';
import { table, type Columns } from '../store';
import ColumnItem from './columnItem.svelte';
import { isRelationship, isRelationshipToMany } from './columns/store';
import { deepClone } from '$lib/helpers/object';
const databaseId = page.params.database;
const collectionId = page.params.table;
const documentId = page.params.row;
const tableId = page.params.table;
const rowId = page.params.row;
function initWork() {
const prohibitedKeys = [
'$id',
'$collection',
'$collectionId',
'$tableId',
'$databaseId',
'$createdAt',
'$updatedAt'
];
const filteredKeys = Object.keys($doc).filter((key) => {
const filteredKeys = Object.keys($row).filter((key) => {
return !prohibitedKeys.includes(key);
});
const result = filteredKeys.reduce((obj, key) => {
obj[key] = $doc[key];
obj[key] = $row[key];
return obj;
}, {});
return writable(deepClone(result as Models.Document));
return writable(deepClone(result as Models.Row));
}
const work = initWork();
@@ -49,13 +49,7 @@
try {
await sdk
.forProject(page.params.region, page.params.project)
.databases.updateDocument(
databaseId,
collectionId,
documentId,
$work,
$work.$permissions
);
.tables.updateRow(databaseId, tableId, rowId, $work, $work.$permissions);
invalidate(Dependencies.ROW);
trackEvent(Submit.RowUpdate);
@@ -72,42 +66,36 @@
}
}
function compareAttributes(
attribute: Attributes,
$work: Models.Document,
$doc: Models.Document
) {
if (!attribute) {
function compareColumns(column: Columns, $work: Models.Row, $row: Models.Row) {
if (!column) {
return false;
}
const workAttribute = $work?.[attribute.key];
const docAttribute = $doc?.[attribute.key];
const workColumn = $work?.[column.key];
const docColumn = $row?.[column.key];
if (attribute.array) {
return !symmetricDifference(Array.from(workAttribute), Array.from(docAttribute)).length;
if (column.array) {
return !symmetricDifference(Array.from(workColumn), Array.from(docColumn)).length;
}
if (isRelationship(attribute)) {
if (isRelationshipToMany(attribute as Models.AttributeRelationship)) {
const workIds = workAttribute.map((doc: string | Record<string, unknown>) =>
if (isRelationship(column)) {
if (isRelationshipToMany(column as Models.ColumnRelationship)) {
const workIds = workColumn.map((doc: string | Record<string, unknown>) =>
typeof doc === 'string' ? doc : doc.$id
);
const relatedIds = docAttribute.map((doc: string | Record<string, unknown>) =>
const relatedIds = docColumn.map((doc: string | Record<string, unknown>) =>
typeof doc === 'string' ? doc : doc.$id
);
return !symmetricDifference(workIds, relatedIds).length;
} else {
const workId =
typeof workAttribute === 'string' ? workAttribute : workAttribute?.$id;
const relatedId =
typeof docAttribute === 'string' ? docAttribute : docAttribute?.$id;
const workId = typeof workColumn === 'string' ? workColumn : workColumn?.$id;
const relatedId = typeof docColumn === 'string' ? docColumn : docColumn?.$id;
return workId === relatedId;
}
}
return workAttribute === docAttribute;
return workColumn === docColumn;
}
</script>
@@ -116,19 +104,19 @@
</svelte:head>
<Container>
{#if $collection?.attributes?.length}
{#each $collection.attributes as attribute}
{@const label = attribute.key}
{#if $table?.columns?.length}
{#each $table.columns as column}
{@const label = column.key}
<CardGrid>
<svelte:fragment slot="title">{label}</svelte:fragment>
<svelte:fragment slot="aside">
<ColumnItem {attribute} bind:formValues={$work} {label} editing />
<ColumnItem {column} bind:formValues={$work} {label} editing />
</svelte:fragment>
<svelte:fragment slot="actions">
<Button
disabled={compareAttributes(attribute, $work, $doc)}
disabled={compareColumns(column, $work, $row)}
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)
.databases.listDocumentLogs(params.database, params.table, params.row, [
.tables.listRowLogs(params.database, params.table, params.row, [
Query.limit(limit),
Query.offset(offset)
])
@@ -3,8 +3,8 @@
import { page } from '$app/state';
import { Breadcrumbs } from '$lib/layout';
import { database } from '../../store';
import { collection } from '../store';
import { doc } from './store';
import { table } from '../store';
import { row } from './store';
$: breadcrumbs = [
{
@@ -15,12 +15,12 @@
title: $database?.name
},
{
href: `${base}/project-${page.params.region}-${page.params.project}/databases/database-${$database?.$id}/table-${$collection?.$id}`,
title: $collection?.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}/table-${$collection?.$id}/row-${$doc?.$id}`,
title: $doc?.$id
href: `${base}/project-${page.params.region}-${page.params.project}/databases/database-${$database?.$id}/table-${$table?.$id}/row-${$row?.$id}`,
title: $row?.$id
}
];
</script>
@@ -13,18 +13,18 @@
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;
export let column:
| Models.ColumnBoolean
| Models.ColumnEmail
| Models.ColumnEnum
| Models.ColumnFloat
| Models.ColumnInteger
| Models.ColumnIp
| Models.ColumnString
| Models.ColumnDatetime
| Models.ColumnUrl;
const attributesTypeMap = {
const columnsTypeMap = {
string: String,
integer: Integer,
double: Integer,
@@ -33,7 +33,7 @@
relationship: Relationship
};
const attributesFormatMap = {
const columnsFormatMap = {
ip: String,
url: Url,
email: String,
@@ -41,22 +41,22 @@
};
</script>
{#if attribute.type in attributesTypeMap}
{#if 'format' in attribute && attribute.format}
{#if column.type in columnsTypeMap}
{#if 'format' in column && column.format}
<svelte:component
this={attributesFormatMap[attribute.format]}
this={columnsFormatMap[column.format]}
{id}
{label}
{attribute}
{column}
{optionalText}
bind:value />
{:else}
<svelte:component
this={attributesTypeMap[attribute.type]}
this={columnsTypeMap[column.type]}
{id}
{editing}
{label}
{attribute}
{column}
{optionalText}
bind:value />
{/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 { Attributes } from '../store';
import type { Columns } from '../store';
import ColumnItem from './columnItem.svelte';
import { IconPencil } from '@appwrite.io/pink-icons-svelte';
export let attributes: Attributes[] = [];
export let columns: Columns[] = [];
export let formValues: object = {};
export let customId: string | null | undefined = undefined;
let showCustomId = false;
</script>
{#if attributes.length}
{#if columns.length}
<Layout.Stack>
{#each attributes as attribute}
{@const label = attribute.key}
<ColumnItem {attribute} bind:formValues {label} />
{#each columns as column}
{@const label = column.key}
<ColumnItem {column} bind:formValues {label} />
{/each}
{#if customId !== undefined}
@@ -4,9 +4,9 @@
import { Icon, Layout, Typography } from '@appwrite.io/pink-svelte';
import { IconPlus } from '@appwrite.io/pink-icons-svelte';
import Column from './column.svelte';
import type { Attributes } from '../store';
import type { Columns } from '../store';
export let attribute: Attributes;
export let column: Columns;
export let formValues: object = {};
export let label: string;
export let editing = false;
@@ -25,9 +25,9 @@
};
}
function getColumnType(attribute: Attributes) {
if ('format' in attribute) {
switch (attribute.format) {
function getColumnType(column: Columns) {
if ('format' in column) {
switch (column.format) {
case 'ip':
return 'IP';
case 'email':
@@ -41,41 +41,41 @@
break;
}
}
return `${capitalize(attribute.type)}${attribute.array ? '[]' : ''}`;
return `${capitalize(column.type)}${column.array ? '[]' : ''}`;
}
</script>
{#if attribute.array}
{#if formValues[attribute.key]?.length === 0}
{#if column.array}
{#if formValues[column.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(attribute)}
{getColumnType(column)}
</Typography.Text>
</Layout.Stack>
<Button secondary on:click={() => addArrayItem(attribute.key)}>
<Button secondary on:click={() => addArrayItem(column.key)}>
<Icon icon={IconPlus} slot="start" size="s" />
Add item
</Button>
</Layout.Stack>
{:else}
<Layout.Stack>
{#each [...formValues[attribute.key].keys()] as index}
{#each [...formValues[column.key].keys()] as index}
<Layout.Stack direction="row" alignItems="flex-end" gap="xs">
<Column
{attribute}
id={`${attribute.key}-${index}`}
optionalText={index === 0 ? getColumnType(attribute) : undefined}
{column}
id={`${column.key}-${index}`}
optionalText={index === 0 ? getColumnType(column) : undefined}
label={index === 0 ? label : ''}
bind:value={formValues[attribute.key][index]} />
<Button text icon on:click={() => removeArrayItem(attribute.key, index)}>
bind:value={formValues[column.key][index]} />
<Button text icon on:click={() => removeArrayItem(column.key, index)}>
<span class="icon-x" aria-hidden="true"></span>
</Button>
</Layout.Stack>
{/each}
<div>
<Button secondary on:click={() => addArrayItem(attribute.key)}>
<Button secondary on:click={() => addArrayItem(column.key)}>
<Icon icon={IconPlus} slot="start" size="s" />
Add item
</Button>
@@ -86,8 +86,8 @@
<Column
{label}
{editing}
{attribute}
id={attribute.key}
optionalText={getColumnType(attribute)}
bind:value={formValues[attribute.key]} />
{column}
id={column.key}
optionalText={getColumnType(column)}
bind:value={formValues[column.key]} />
{/if}
@@ -5,7 +5,7 @@
export let id: string;
export let label: string;
export let value: boolean;
export let attribute: Models.AttributeBoolean;
export let column: Models.ColumnBoolean;
export let optionalText: string | undefined = undefined;
</script>
@@ -14,9 +14,9 @@
{label}
{optionalText}
placeholder="Select a value"
required={attribute.required}
required={column.required}
options={[
!attribute.required && { label: 'NULL', value: null },
!column.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 attribute: Models.AttributeDatetime;
export let column: Models.ColumnDatetime;
export let type: 'date' | 'time' | 'datetime-local' = 'datetime-local';
</script>
@@ -14,5 +14,5 @@
{label}
{type}
bind:value
required={attribute.required}
nullable={!attribute.required} />
required={column.required}
nullable={!column.required} />
@@ -5,15 +5,15 @@
export let id: string;
export let label: string;
export let value: string | null;
export let attribute: Models.AttributeUrl;
export let column: Models.ColumnEmail;
$: nullable = attribute.required ? false : !value;
$: nullable = column.required ? false : !value;
</script>
<InputEmail
{id}
{label}
{nullable}
placeholder="Enter URL"
required={attribute.required}
placeholder="Enter Email"
required={column.required}
bind:value />
@@ -5,17 +5,17 @@
export let id: string;
export let label: string;
export let value: string;
export let attribute: Models.AttributeEnum;
export let column: Models.ColumnEnum;
export let optionalText: string | undefined = undefined;
$: options = [
...attribute.elements.map((element) => {
...column.elements.map((element) => {
return {
label: element,
value: element
};
}),
!attribute.required && {
!column.required && {
label: 'NULL',
value: null
}
@@ -28,5 +28,5 @@
{id}
{label}
{optionalText}
required={attribute.required}
required={column.required}
placeholder="Select a value" />
@@ -5,17 +5,17 @@
export let id: string;
export let label: string;
export let value: number;
export let attribute: Models.AttributeInteger;
export let column: Models.ColumnInteger;
$: nullable = attribute.required ? false : !value;
$: nullable = column.required ? false : !value;
</script>
<InputNumber
{id}
{label}
{nullable}
required={attribute.required}
min={attribute.min}
max={attribute.max}
step={attribute.type === 'double' ? 'any' : 1}
required={column.required}
min={column.min}
max={column.max}
step={column.type === 'double' ? 'any' : 1}
bind:value />
@@ -5,7 +5,7 @@
import { sdk } from '$lib/stores/sdk';
import { Query, type Models } from '@appwrite.io/console';
import { onMount } from 'svelte';
import { doc } from '../store';
import { row } 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 attribute: Models.AttributeRelationship;
export let column: Models.ColumnRelationship;
export let optionalText: string | undefined = undefined;
const databaseId = page.params.database;
let documentList: Models.DocumentList<Models.Document>;
let rowList: Models.RowList<Models.Row>;
let search: string = null;
let displayNames = ['$id'];
let relatedList: string[] = [];
@@ -32,37 +32,37 @@
onMount(async () => {
if (value) {
if (isRelationshipToMany(attribute)) {
if (isRelationshipToMany(column)) {
relatedList = (value as string[]).slice();
} else {
singleRel = value as string;
}
}
documentList = await getDocuments();
rowList = await getRows();
if (editing && $doc?.[attribute.key]) {
if ($doc[attribute.key]?.length) {
if (editing && $row?.[column.key]) {
if ($row[column.key]?.length) {
relatedList =
$doc[attribute.key]?.map((d: Record<string, unknown>) => {
$row[column.key]?.map((d: Record<string, unknown>) => {
return d?.$id;
}) ?? [];
} else {
singleRel = $doc[attribute.key]?.$id;
singleRel = $row[column.key]?.$id;
}
}
displayNames = preferences.getDisplayNames()?.[attribute?.relatedCollection] ?? ['$id'];
displayNames = preferences.getDisplayNames()?.[column?.relatedTable] ?? ['$id'];
if (!displayNames?.includes('$id')) {
displayNames.unshift('$id');
}
});
async function getDocuments(search: string = null) {
async function getRows(search: string = null) {
const queries = search ? [Query.startsWith('$id', search), Query.orderDesc('')] : [];
return await sdk
.forProject(page.params.region, page.params.project)
.databases.listDocuments(databaseId, attribute.relatedCollection, queries);
.tables.listRows(databaseId, column.relatedTable, queries);
}
function getAvailableOptions(excludeIndex?: number) {
@@ -104,7 +104,7 @@
}
//Reactive statements
$: getDocuments(search).then((res) => (documentList = res));
$: getRows(search).then((res) => (rowList = res));
$: paginatedItems = editing
? relatedList
@@ -116,7 +116,7 @@
$: totalCount = relatedList?.length ?? 0;
$: options =
documentList?.documents?.map((n) => {
rowList?.rows?.map((n) => {
const data = displayNames.filter((name) => name !== '$id').map((name) => n?.[name]);
return { value: n.$id, label: n.$id, data };
}) ?? [];
@@ -129,7 +129,7 @@
$: showEmptyInput = editing && totalCount === 0 && !showInput;
</script>
{#if isRelationshipToMany(attribute)}
{#if isRelationshipToMany(column)}
<Layout.Stack gap="xxl">
<Layout.Stack gap="m">
<Layout.Stack direction="row" alignContent="space-between">
@@ -157,7 +157,7 @@
required
{options}
bind:value={relatedList[0]}
placeholder={`Select ${attribute.key}`}
placeholder={`Select ${column.key}`}
on:change={() => {
if (!relatedList[0]) relatedList = [''];
updateRelatedList();
@@ -175,7 +175,7 @@
required
options={getAvailableOptions(actualIndex)}
bind:value={relatedList[actualIndex]}
placeholder={`Select ${attribute.key}`}
placeholder={`Select ${column.key}`}
on:change={updateRelatedList} />
{#if relatedList[actualIndex]}
<div style:padding-block-start="0.5rem">
@@ -223,7 +223,7 @@
<InputSelect
{id}
required
placeholder={`Select ${attribute.key}`}
placeholder={`Select ${column.key}`}
bind:value={newItemValue}
options={getAvailableOptions()}
on:change={addNewItem} />
@@ -251,8 +251,8 @@
{id}
{label}
{options}
required={attribute.required}
placeholder={`Select ${attribute.key}`}
required={column.required}
placeholder={`Select ${column.key}`}
bind:value={singleRel}
on:change={() => (value = singleRel)} />
{/if}
@@ -1,22 +1,22 @@
import type { Models } from '@appwrite.io/console';
import type { Attributes } from '../../store';
import type { Columns } 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);
export function isRelationshipToMany(column: Models.ColumnRelationship) {
if (!column) return false;
if (!column?.relationType) return false;
if (column?.side === 'child') {
return !['oneToOne', 'oneToMany'].includes(column?.relationType);
} else {
return !['oneToOne', 'manyToOne'].includes(attribute?.relationType);
return !['oneToOne', 'manyToOne'].includes(column?.relationType);
}
}
export function isRelationship(attribute: Attributes): attribute is Models.AttributeRelationship {
if (!attribute) return false;
return attribute?.type === 'relationship';
export function isRelationship(column: Columns): column is Models.ColumnRelationship {
if (!column) return false;
return column?.type === 'relationship';
}
export function isString(attribute: Attributes): attribute is Models.AttributeString {
if (!attribute) return false;
return attribute?.type === 'string';
export function isString(column: Columns): column is Models.ColumnString {
if (!column) return false;
return column?.type === 'string';
}
@@ -5,19 +5,19 @@
export let id: string;
export let label: string;
export let value: string;
export let attribute: Models.AttributeString;
export let column: Models.ColumnString;
$: nullable = attribute.required ? false : !value;
$: nullable = column.required ? false : !value;
</script>
{#if attribute.size >= 50}
{#if column.size >= 50}
<InputTextarea
{id}
{label}
{nullable}
placeholder="Enter string"
required={attribute.required}
maxlength={attribute.size}
required={column.required}
maxlength={column.size}
bind:value />
{:else}
<InputText
@@ -25,7 +25,7 @@
{label}
{nullable}
placeholder="Enter string"
required={attribute.required}
maxlength={attribute.size}
required={column.required}
maxlength={column.size}
bind:value />
{/if}
@@ -5,15 +5,9 @@
export let id: string;
export let label: string;
export let value: string | null;
export let attribute: Models.AttributeUrl;
export let column: Models.ColumnUrl;
$: nullable = attribute.required ? false : !value;
$: nullable = column.required ? false : !value;
</script>
<InputURL
{id}
{label}
{nullable}
placeholder="Enter URL"
required={attribute.required}
bind:value />
<InputURL {id} {label} {nullable} placeholder="Enter URL" required={column.required} bind:value />
@@ -8,7 +8,7 @@
import { addNotification } from '$lib/stores/notifications';
import { sdk } from '$lib/stores/sdk';
import { Alert, Layout, Selector, Table } from '@appwrite.io/pink-svelte';
import { columns, collection } from '../store';
import { columns, table } from '../store';
import { isRelationship, isRelationshipToMany } from './columns/store';
import type { Models } from '@appwrite.io/console';
@@ -20,7 +20,7 @@
try {
await sdk
.forProject(page.params.region, page.params.project)
.databases.deleteDocument(databaseId, page.params.table, page.params.row);
.tables.deleteRow(databaseId, page.params.table, page.params.row);
showDelete = false;
addNotification({
type: 'success',
@@ -45,7 +45,7 @@
'restrict' = 'Row cannot be deleted'
}
$: relAttributes = $columns?.filter(
$: relColumns = $columns?.filter(
(attribute) =>
isRelationship(attribute) &&
// One-to-One are always included
@@ -56,17 +56,15 @@
(attribute.relationType === 'manyToOne' && attribute.side === 'child') ||
// Many-to-Many: Only include if the parent is being deleted
(isRelationshipToMany(attribute) && attribute.side === 'parent'))
) as Models.AttributeRelationship[];
) as Models.ColumnRelationship[];
</script>
<Confirm title="Delete row" onSubmit={handleDelete} bind:open={showDelete}>
<p data-private>
Are you sure you want to delete <b
>the row from <span data-private>{$collection.name}</span></b
>?
Are you sure you want to delete <b>the row from <span data-private>{$table.name}</span></b>?
</p>
{#if relAttributes?.length}
{#if relColumns?.length}
<p class="text">This row contains the following relationships:</p>
<Table.Root
let:root
@@ -80,7 +78,7 @@
<Table.Header.Cell column="setting" {root}>Setting</Table.Header.Cell>
<Table.Header.Cell column="desc" {root} />
</svelte:fragment>
{#each relAttributes as attr}
{#each relColumns as attr}
<Table.Row.Base {root}>
<Table.Cell column="relations" {root}>
<span class="u-flex u-cross-center u-gap-8">
@@ -105,15 +103,12 @@
<Alert.Inline
title="To change these deletion behaviors edit the relationship settings." />
<Selector.Checkbox
id="delete"
label={`Delete document from ${$collection.name}`}
bind:checked />
<Selector.Checkbox id="delete" label="Delete row from ${$table.name}" bind:checked />
</Layout.Stack>
{/if}
<svelte:fragment slot="footer">
<Button text on:click={() => (showDelete = false)}>Cancel</Button>
<Button danger submit disabled={relAttributes?.length && !checked}>Delete</Button>
<Button danger submit disabled={relColumns?.length && !checked}>Delete</Button>
</svelte:fragment>
</Confirm>
@@ -4,14 +4,14 @@
import { Id, Tab, Tabs } from '$lib/components';
import { isTabSelected } from '$lib/helpers/load';
import { Cover, CoverTitle } from '$lib/layout';
import { doc } from './store';
import { row } from './store';
const projectId = page.params.project;
const databaseId = page.params.database;
const collectionId = page.params.table;
const documentId = page.params.row;
const tableId = page.params.table;
const rowId = page.params.row;
const path = `${base}/project-${page.params.region}-${page.params.project}/databases/database-${databaseId}/table-${collectionId}/row-${documentId}`;
const path = `${base}/project-${page.params.region}-${page.params.project}/databases/database-${databaseId}/table-${tableId}/row-${rowId}`;
const tabs = [
{
href: path,
@@ -36,10 +36,10 @@
<Cover>
<svelte:fragment slot="header">
<CoverTitle
href={`${base}/project-${page.params.region}-${projectId}/databases/database-${databaseId}/table-${collectionId}`}>
{$doc?.$id}
href={`${base}/project-${page.params.region}-${projectId}/databases/database-${databaseId}/table-${tableId}`}>
{$row?.$id}
</CoverTitle>
<Id value={$doc?.$id} event="document">Document ID</Id>
<Id value={$row?.$id} event="row">Row ID</Id>
</svelte:fragment>
<Tabs>
@@ -1,8 +1,8 @@
<script lang="ts">
import { Button } from '$lib/elements/forms';
import { CardGrid } from '$lib/components';
import { collection } from '../store';
import { doc } from './store';
import { table } from '../store';
import { row } from './store';
import { onMount } from 'svelte';
import { page } from '$app/state';
import { sdk } from '$lib/stores/sdk';
@@ -15,55 +15,45 @@
import ColumnForm from './columnForm.svelte';
let disableUpdate = true;
let currentDoc: string;
let currentRow: string;
const databaseId = page.params.database;
const collectionId = page.params.table;
const documentId = page.params.row;
const tableId = page.params.table;
const rowId = page.params.row;
const work = writable(
Object.keys($doc)
Object.keys($row)
.filter((key) => {
return ![
'$id',
'$collection',
'$collectionId',
'$tableId',
'$databaseId',
'$createdAt',
'$updatedAt'
].includes(key);
})
.reduce((obj, key) => {
obj[key] = $doc[key];
obj[key] = $row[key];
return obj;
}, {}) as Models.Document
}, {}) as Models.Row
);
onMount(async () => {
currentDoc = JSON.stringify($work);
currentRow = JSON.stringify($work);
});
$: {
if (currentDoc !== JSON.stringify($work)) {
disableUpdate = false;
} else {
disableUpdate = true;
}
disableUpdate = currentRow === JSON.stringify($work);
}
async function updateData() {
try {
await sdk
.forProject(page.params.region, page.params.project)
.databases.updateDocument(
databaseId,
collectionId,
documentId,
$work,
$work.$permissions
);
.tables.updateRow(databaseId, tableId, rowId, $work, $work.$permissions);
await invalidate(Dependencies.ROW);
currentDoc = JSON.stringify($work);
currentRow = JSON.stringify($work);
trackEvent(Submit.RowUpdate);
disableUpdate = true;
addNotification({
@@ -82,9 +72,9 @@
<CardGrid>
<svelte:fragment slot="title">Data</svelte:fragment>
Update document data based on the attributes created earlier.
Update row data based on the columns created earlier.
<svelte:fragment slot="aside">
<ColumnForm attributes={$collection.attributes} bind:formValues={$work} />
<ColumnForm columns={$table.columns} bind:formValues={$work} />
</svelte:fragment>
<svelte:fragment slot="actions">
@@ -3,7 +3,7 @@
import { Container } from '$lib/layout';
import { Button } from '$lib/elements/forms';
import { sdk } from '$lib/stores/sdk';
import { doc } from '../store';
import { row } from '../store';
import { addNotification } from '$lib/stores/notifications';
import { toLocaleDateTime } from '$lib/helpers/date';
import Delete from '../delete.svelte';
@@ -12,23 +12,24 @@
import { invalidate } from '$app/navigation';
import { Dependencies } from '$lib/constants';
import { Submit, trackEvent, trackError } from '$lib/actions/analytics';
import { collection } from '../../store';
import { page } from '$app/stores';
import { table } from '../../store';
import { page } from '$app/state';
let showDelete = false;
let permissions = $doc?.$permissions;
let permissions = $row?.$permissions;
let arePermsDisabled = true;
let showPermissionAlert = true;
async function updatePermissions() {
try {
await sdk
.forProject($page.params.region, $page.params.project)
.databases.updateDocument(
$doc.$databaseId,
$doc.$collectionId,
$doc.$id,
$doc.data,
.forProject(page.params.region, page.params.project)
.tables.updateRow(
$row.$databaseId,
$row.$tableId,
$row.$id,
$row.data,
permissions
);
await invalidate(Dependencies.ROW);
@@ -48,7 +49,7 @@
}
$: if (permissions) {
arePermsDisabled = !symmetricDifference(permissions, $doc.$permissions).length;
arePermsDisabled = !symmetricDifference(permissions, $row.$permissions).length;
}
</script>
@@ -62,8 +63,8 @@
<svelte:fragment slot="aside">
<div>
<p>Created: {toLocaleDateTime($doc.$createdAt)}</p>
<p>Last updated: {toLocaleDateTime($doc.$updatedAt)}</p>
<p>Created: {toLocaleDateTime($row.$createdAt)}</p>
<p>Last updated: {toLocaleDateTime($row.$updatedAt)}</p>
</div>
</svelte:fragment>
</CardGrid>
@@ -83,7 +84,7 @@
</p>
<svelte:fragment slot="aside">
{#if $collection.documentSecurity}
{#if $table.rowSecurity}
{#if showPermissionAlert}
<Alert type="info" dismissible on:dismiss={() => (showPermissionAlert = false)}>
<svelte:fragment slot="title">Row security is enabled</svelte:fragment>
@@ -109,11 +110,7 @@
</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>
@@ -126,10 +123,10 @@
<svelte:fragment slot="aside">
<BoxAvatar>
<svelte:fragment slot="title">
<h6 class="u-bold u-trim-1">{$doc.$id}</h6>
<h6 class="u-bold u-trim-1">{$row.$id}</h6>
</svelte:fragment>
<p>
Last updated: {toLocaleDateTime($doc.$updatedAt)}
Last updated: {toLocaleDateTime($row.$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 doc = derived(page, ($page) => $page.data.document as Models.Document);
export const row = derived(page, ($page) => $page.data.row as Models.Row);
@@ -1,6 +1,6 @@
<script lang="ts">
import { Container } from '$lib/layout';
import { collection } from '../store';
import { table } from '../store';
import DangerZone from './dangerZone.svelte';
import DisplayName from './displayName.svelte';
import UpdateName from './updateName.svelte';
@@ -10,7 +10,7 @@
</script>
<Container>
{#if $collection}
{#if $table}
<UpdateStatus />
<UpdateName />
<DisplayName />
@@ -2,7 +2,7 @@
import { BoxAvatar, CardGrid } from '$lib/components';
import { Button } from '$lib/elements/forms';
import { toLocaleDateTime } from '$lib/helpers/date';
import { collection } from '../store';
import { table } from '../store';
import Delete from './deleteTable.svelte';
import { Click, trackEvent } from '$lib/actions/analytics';
@@ -15,9 +15,9 @@
<svelte:fragment slot="aside">
<BoxAvatar>
<svelte:fragment slot="title">
<h6 class="u-bold u-trim-1">{$collection.name}</h6>
<h6 class="u-bold u-trim-1">{$table.name}</h6>
</svelte:fragment>
<p>Last updated: {toLocaleDateTime($collection.$updatedAt)}</p>
<p>Last updated: {toLocaleDateTime($table.$updatedAt)}</p>
</BoxAvatar>
</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 { collection } from '../store';
import { table } from '../store';
export let showDelete = false;
@@ -19,12 +19,12 @@
try {
await sdk
.forProject(page.params.region, page.params.project)
.databases.deleteCollection(databaseId, $collection.$id);
.tables.delete(databaseId, $table.$id);
await invalidate(Dependencies.DATABASE);
showDelete = false;
addNotification({
type: 'success',
message: `${$collection.name} has been deleted`
message: `${$table.name} has been deleted`
});
trackEvent(Submit.TableDelete);
await goto(
@@ -39,6 +39,6 @@
<Confirm onSubmit={handleDelete} title="Delete table" bind:open={showDelete} bind:error>
<Typography.Text>
Are you sure you want to delete <b>{$collection.name}</b>?
Are you sure you want to delete <b>{$table.name}</b>?
</Typography.Text>
</Confirm>
@@ -12,14 +12,15 @@
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 collectionId = page.params.table;
let names: string[] = [...(preferences.getDisplayNames()?.[collectionId] ?? [])];
const tableId = page.params.table;
let names: string[] = [...(preferences.getDisplayNames()?.[tableId] ?? [])];
async function updateDisplayName() {
try {
await preferences.setDisplayNames(collectionId, names);
names = [...(preferences.getDisplayNames()?.[collectionId] ?? [])];
await preferences.setDisplayNames($organization.$id, tableId, names);
names = [...(preferences.getDisplayNames()?.[tableId] ?? [])];
await invalidate(Dependencies.TEAM);
addNotification({
message: 'Display names have been updated',
@@ -35,7 +36,7 @@
}
}
$: options = ($columns as Models.AttributeString[])
$: options = ($columns as Models.ColumnString[])
.filter(
(attr) =>
attr.type === 'string' && !attr?.array && !names?.some((name) => name === attr.key)
@@ -50,7 +51,7 @@
$: addAttributeDisabled = names?.length >= 5 || (names?.length && !names[names?.length - 1]);
$: updateBtnDisabled =
!symmetricDifference(names, preferences.getDisplayNames()?.[collectionId] ?? [])?.length ||
!symmetricDifference(names, preferences.getDisplayNames()?.[tableId] ?? [])?.length ||
(names?.length && !last(names));
</script>
@@ -8,27 +8,27 @@
import { addNotification } from '$lib/stores/notifications';
import { sdk } from '$lib/stores/sdk';
import { onMount } from 'svelte';
import { collection } from '../store';
import { table } from '../store';
const databaseId = page.params.database;
let collectionName: string = null;
let tableName: string = null;
onMount(() => {
collectionName ??= $collection.name;
tableName ??= $table.name;
});
async function updateName() {
try {
await sdk
.forProject(page.params.region, page.params.project)
.databases.updateCollection(
.tables.update(
databaseId,
$collection.$id,
collectionName,
$collection.$permissions,
$collection.documentSecurity,
$collection.enabled
$table.$id,
tableName,
$table.$permissions,
$table.rowSecurity,
$table.enabled
);
await invalidate(Dependencies.TABLE);
addNotification({
@@ -56,12 +56,11 @@
label="Name"
placeholder="Enter name"
autocomplete={false}
bind:value={collectionName} />
bind:value={tableName} />
</svelte:fragment>
<svelte:fragment slot="actions">
<Button disabled={collectionName === $collection.name || !collectionName} submit
>Update</Button>
<Button disabled={tableName === $table.name || !tableName} submit>Update</Button>
</svelte:fragment>
</CardGrid>
</Form>
@@ -10,30 +10,30 @@
import { addNotification } from '$lib/stores/notifications';
import { sdk } from '$lib/stores/sdk';
import { onMount } from 'svelte';
import { collection } from '../store';
import { table } from '../store';
import { Link } from '@appwrite.io/pink-svelte';
const databaseId = page.params.database;
let arePermsDisabled = true;
let collectionPermissions: string[] = null;
let tablePermissions: string[] = null;
onMount(() => {
collectionPermissions ??= $collection.$permissions;
tablePermissions ??= $table.$permissions;
});
async function updatePermissions() {
try {
await sdk
.forProject(page.params.region, page.params.project)
.databases.updateCollection(
.tables.update(
databaseId,
$collection.$id,
$collection.name,
collectionPermissions,
$collection.documentSecurity,
$collection.enabled
$table.$id,
$table.name,
tablePermissions,
$table.rowSecurity,
$table.enabled
);
await invalidate(Dependencies.TABLE);
addNotification({
@@ -51,8 +51,7 @@
}
$: arePermsDisabled = !(
collectionPermissions &&
symmetricDifference(collectionPermissions, $collection.$permissions).length
tablePermissions && symmetricDifference(tablePermissions, $table.$permissions).length
);
</script>
@@ -65,8 +64,8 @@
Learn more
</Link.Anchor>.
<svelte:fragment slot="aside">
{#if collectionPermissions}
<Permissions bind:permissions={collectionPermissions} withCreate />
{#if tablePermissions}
<Permissions bind:permissions={tablePermissions} withCreate />
{/if}
</svelte:fragment>
<svelte:fragment slot="actions">
@@ -8,27 +8,27 @@
import { addNotification } from '$lib/stores/notifications';
import { sdk } from '$lib/stores/sdk';
import { onMount } from 'svelte';
import { collection } from '../store';
import { table } from '../store';
const databaseId = page.params.database;
let collectionDocumentSecurity: boolean = null;
let tableRowSecurity: boolean = null;
onMount(() => {
collectionDocumentSecurity ??= $collection.documentSecurity;
tableRowSecurity ??= $table.rowSecurity;
});
async function updateSecurity() {
try {
await sdk
.forProject(page.params.region, page.params.project)
.databases.updateCollection(
.tables.update(
databaseId,
$collection.$id,
$collection.name,
$collection.$permissions,
collectionDocumentSecurity,
$collection.enabled
$table.$id,
$table.name,
$table.$permissions,
tableRowSecurity,
$table.enabled
);
await invalidate(Dependencies.TABLE);
addNotification({
@@ -49,7 +49,7 @@
<CardGrid>
<svelte:fragment slot="title">Row security</svelte:fragment>
<svelte:fragment slot="aside">
<InputSwitch bind:value={collectionDocumentSecurity} id="security" label="Row security" />
<InputSwitch bind:value={tableRowSecurity} id="security" label="Row security" />
<p class="text">
When row security is enabled, users will be able to access rows for which they have been
@@ -62,8 +62,7 @@
</p>
</svelte:fragment>
<svelte:fragment slot="actions">
<Button
disabled={collectionDocumentSecurity === $collection.documentSecurity}
on:click={updateSecurity}>Update</Button>
<Button disabled={tableRowSecurity === $table.rowSecurity} on:click={updateSecurity}
>Update</Button>
</svelte:fragment>
</CardGrid>
@@ -9,31 +9,31 @@
import { addNotification } from '$lib/stores/notifications';
import { sdk } from '$lib/stores/sdk';
import { onMount } from 'svelte';
import { collection } from '../store';
import { table } from '../store';
const databaseId = page.params.database;
let enabled: boolean = null;
onMount(() => {
enabled ??= $collection.enabled;
enabled ??= $table.enabled;
});
async function toggleCollection() {
try {
await sdk
.forProject(page.params.region, page.params.project)
.databases.updateCollection(
.tables.update(
databaseId,
$collection.$id,
$collection.name,
$collection.$permissions,
$collection.documentSecurity,
$table.$id,
$table.name,
$table.$permissions,
$table.rowSecurity,
enabled
);
await invalidate(Dependencies.TABLE);
addNotification({
message: `${$collection.name} has been updated`,
message: `${$table.name} has been updated`,
type: 'success'
});
trackEvent(Submit.TableUpdateEnabled);
@@ -48,7 +48,7 @@
</script>
<CardGrid>
<svelte:fragment slot="title">{$collection.name}</svelte:fragment>
<svelte:fragment slot="title">{$table.name}</svelte:fragment>
<svelte:fragment slot="aside">
<ul>
<InputSwitch
@@ -57,14 +57,12 @@
bind:value={enabled} />
</ul>
<div>
<p>Created: {toLocaleDateTime($collection.$createdAt)}</p>
<p>Last updated: {toLocaleDateTime($collection.$updatedAt)}</p>
<p>Created: {toLocaleDateTime($table.$createdAt)}</p>
<p>Last updated: {toLocaleDateTime($table.$updatedAt)}</p>
</div>
</svelte:fragment>
<svelte:fragment slot="actions">
<Button disabled={enabled === $collection.enabled} on:click={toggleCollection}>
Update
</Button>
<Button disabled={enabled === $table.enabled} on:click={toggleCollection}>Update</Button>
</svelte:fragment>
</CardGrid>
@@ -1,30 +1,27 @@
import { page } from '$app/stores';
import type { Column } from '$lib/helpers/types';
import type { Column as TableColumn } from '$lib/helpers/types';
import type { Models } from '@appwrite.io/console';
import { derived, writable } from 'svelte/store';
export type Attributes =
| Models.AttributeBoolean
| Models.AttributeEmail
| Models.AttributeEnum
| Models.AttributeFloat
| Models.AttributeInteger
| Models.AttributeIp
| Models.AttributeString
| Models.AttributeUrl
| (Models.AttributeRelationship & { default?: never });
export type Columns =
| Models.ColumnBoolean
| Models.ColumnEmail
| Models.ColumnEnum
| Models.ColumnFloat
| Models.ColumnInteger
| Models.ColumnIp
| Models.ColumnString
| Models.ColumnUrl
| (Models.ColumnRelationship & { default?: never });
type Collection = Omit<Models.Collection, 'attributes'> & {
attributes: Array<Attributes>;
type Table = Omit<Models.Table, 'columns'> & {
columns: Array<Columns>;
};
export const collection = derived(page, ($page) => $page.data.collection as Collection);
export const columns = derived(
page,
($page) => $page.data.collection.attributes as Attributes[]
);
export const indexes = derived(page, ($page) => $page.data.collection.indexes as Models.Index[]);
export const table = derived(page, ($page) => $page.data.table as Table);
export const columns = derived(page, ($page) => $page.data.table.columns as Columns[]);
export const indexes = derived(page, ($page) => $page.data.table.indexes as Models.ColumnIndex[]);
export const tableColumns = writable<Column[]>([]);
export const tableColumns = writable<TableColumn[]>([]);
export const isCsvImportInProgress = writable(false);
@@ -18,14 +18,14 @@
let region = $derived(page.params.region);
let project = $derived(page.params.project);
let databaseId = $derived(page.params.database);
let collectionId = $derived(page.params.table);
let tableId = $derived(page.params.table);
const sortedCollections = $derived.by(() =>
data?.allCollections?.collections?.slice().sort((a, b) => a.name.localeCompare(b.name))
const sortedTables = $derived.by(() =>
data?.allTables?.tables?.slice().sort((a, b) => a.name.localeCompare(b.name))
);
const selectedCollection = $derived.by(() =>
sortedCollections?.find((collection) => collection.$id === collectionId)
const selectedTable = $derived.by(() =>
sortedTables?.find((collection) => collection.$id === tableId)
);
let openBottomSheet = $state(false);
@@ -48,11 +48,11 @@
{data.database?.name}
</a>
<div class="collection-content">
{#if data?.allCollections?.total}
{#if data?.allTables?.total}
<ul class="drop-list u-margin-inline-start-8 u-margin-block-start-8">
{#each sortedCollections as collection}
{@const href = `${base}/project-${region}-${project}/databases/database-${databaseId}/table-${collection.$id}`}
{@const isSelected = collectionId === collection.$id}
{#each sortedTables as table}
{@const href = `${base}/project-${region}-${project}/databases/database-${databaseId}/table-${table.$id}`}
{@const isSelected = tableId === table.$id}
<li class:is-selected={isSelected}>
<a
class="u-padding-block-8 u-padding-inline-end-4 u-padding-inline-start-8 u-flex u-cross-center u-gap-8"
@@ -64,7 +64,7 @@
? '--fgcolor-neutral-tertiary'
: '--fgcolor-neutral-weak'} />
<span class="text collection-name" data-private
>{collection.name}</span>
>{table.name}</span>
</a>
</li>
{/each}
@@ -99,7 +99,7 @@
onclick={() => {
openBottomSheet = !openBottomSheet;
}}>
<span class="orgName">{selectedCollection.name}</span>
<span class="orgName">{selectedTable.name}</span>
<Icon icon={IconChevronDown} size="s" />
</button>
</Layout.Stack>
@@ -111,7 +111,7 @@
bind:isOpen={openBottomSheet}
menu={{
top: {
items: sortedCollections.slice(0, 10).map((collection) => {
items: sortedTables.slice(0, 10).map((collection) => {
return {
name: collection.name,
leadingIcon: IconTable,
@@ -120,7 +120,7 @@
})
},
bottom:
sortedCollections.length > 10
sortedTables.length > 10
? {
items: [
{
@@ -14,7 +14,7 @@
import type { PageData } from './$types';
import { isRelationship, isRelationshipToMany, isString } from './row-[row]/columns/store';
import RelationshipsModal from './relationshipsModal.svelte';
import { columns, collection, tableColumns } from './store';
import { columns, table, tableColumns } from './store';
import type { ColumnType } from '$lib/helpers/types';
import {
Tooltip,
@@ -33,9 +33,9 @@
export let data: PageData;
const databaseId = page.params.database;
const collectionId = page.params.table;
const tableId = page.params.table;
let showRelationships = false;
let selectedRelationship: Models.AttributeRelationship = null;
let selectedRelationship: Models.ColumnRelationship = null;
let relationshipData: Partial<Models.Document>[];
let displayNames = {};
@@ -96,20 +96,19 @@
};
}
$: selected = preferences.getCustomCollectionColumns(page.params.table);
$: selected = preferences.getCustomTableColumns(page.params.table);
$: {
tableColumns.set(
$collection.attributes.map((attribute) => ({
id: attribute.key,
title: attribute.key,
type: attribute.type as ColumnType,
show: selected?.includes(attribute.key) ?? true,
array: attribute?.array,
$table.columns.map((column) => ({
id: column.key,
title: column.key,
type: column.type as ColumnType,
show: selected?.includes(column.key) ?? true,
array: column?.array,
width: { min: 168 },
format:
'format' in attribute && attribute?.format === 'enum' ? attribute.format : null,
elements: 'elements' in attribute ? attribute.elements : null
format: 'format' in column && column?.format === 'enum' ? column.format : null,
elements: 'elements' in column ? column.elements : null
}))
);
}
@@ -120,10 +119,10 @@
async function handleDelete() {
showDelete = false;
const promises = selectedRows.map((documentId) =>
const promises = selectedRows.map((rowId) =>
sdk
.forProject(page.params.region, page.params.project)
.databases.deleteDocument(databaseId, collectionId, documentId)
.tables.deleteRow(databaseId, tableId, rowId)
);
try {
await Promise.all(promises);
@@ -162,7 +161,7 @@
(attribute.relationType === 'manyToOne' && attribute.side === 'child') ||
// Many-to-Many: Only include if the parent is being deleted
(isRelationshipToMany(attribute) && attribute.side === 'parent'))
) as Models.AttributeRelationship[];
) as Models.ColumnRelationship[];
let checked = false;
@@ -187,35 +186,35 @@
<Table.Header.Cell column="$created" {root}>Created</Table.Header.Cell>
<Table.Header.Cell column="$updated" {root}>Updated</Table.Header.Cell>
</svelte:fragment>
{#each data.documents.documents as document (document.$id)}
{#each data.rows.rows as row (row.$id)}
<Table.Row.Link
{root}
id={document.$id}
href={`${base}/project-${page.params.region}-${page.params.project}/databases/database-${databaseId}/table-${$collection.$id}/row-${document.$id}`}>
id={row.$id}
href={`${base}/project-${page.params.region}-${page.params.project}/databases/database-${databaseId}/table-${$table.$id}/row-${row.$id}`}>
<Table.Cell column="$id" {root}>
{#key document.$id}
<Id value={document.$id}>
{document.$id}
{#key row.$id}
<Id value={row.$id}>
{row.$id}
</Id>
{/key}
</Table.Cell>
{#each $tableColumns as { id } (id)}
{@const attr = $columns.find((n) => n.key === id)}
{#if attr}
{@const column = $columns.find((n) => n.key === id)}
{#if column}
<Table.Cell column={id} {root}>
{#if isRelationship(attr)}
{@const args = displayNames?.[attr.relatedCollection] ?? ['$id']}
{#if !isRelationshipToMany(attr)}
{#if document[id]}
{@const related = document[id]}
{#if isRelationship(column)}
{@const args = displayNames?.[column.relatedTable] ?? ['$id']}
{#if !isRelationshipToMany(column)}
{#if row[id]}
{@const related = row[id]}
<Link.Button
variant="muted"
on:click={(e) => {
e.preventDefault();
e.stopPropagation();
goto(
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${databaseId}/table-${attr.relatedCollection}/row-${related.$id}`
`${base}/project-${page.params.region}-${page.params.project}/databases/database-${databaseId}/table-${column.relatedTable}/row-${related.$id}`
);
}}>
{#each args as arg, i}
@@ -233,7 +232,7 @@
<span class="text">n/a</span>
{/if}
{:else}
{@const itemsNum = document[id]?.length}
{@const itemsNum = row[id]?.length}
<Button.Button
variant="extra-compact"
disabled={!itemsNum}
@@ -241,18 +240,18 @@
on:click={(e) => {
e.stopPropagation();
e.preventDefault();
relationshipData = document[id];
relationshipData = row[id];
showRelationships = true;
selectedRelationship = attr;
selectedRelationship = column;
}}>
Items
</Button.Button>
{/if}
{:else}
{@const datetime = document[id]}
{@const formatted = formatColumn(document[id])}
{@const isDatetimeAttribute = attr.type === 'datetime'}
{@const isEncryptedAttribute = isString(attr) && attr.encrypt}
{@const datetime = row[id]}
{@const formatted = formatColumn(row[id])}
{@const isDatetimeAttribute = column.type === 'datetime'}
{@const isEncryptedAttribute = isString(column) && column.encrypt}
{#if isDatetimeAttribute}
<DualTimeView time={datetime}>
<span slot="title">Timestamp</span>
@@ -287,10 +286,10 @@
{/if}
{/each}
<Table.Cell column="$created" {root}>
<DualTimeView time={document.$createdAt} />
<DualTimeView time={row.$createdAt} />
</Table.Cell>
<Table.Cell column="$updated" {root}>
<DualTimeView time={document.$updatedAt} />
<DualTimeView time={row.$updatedAt} />
</Table.Cell>
</Table.Row.Link>
{/each}
@@ -360,7 +359,7 @@
<ul>
<InputChoice id="delete" label="Delete" showLabel={false} bind:value={checked}>
Delete row from <span data-private>{$collection.name}</span>
Delete row from <span data-private>{$table.name}</span>
</InputChoice>
</ul>
</div>
@@ -5,8 +5,9 @@
import Container from '$lib/layout/container.svelte';
export let data;
$: total = data.documentsTotal;
$: count = data.documents;
$: count = data.rows;
$: total = data.rowsTotal;
</script>
<Container>
@@ -7,7 +7,8 @@ export const load: PageLoad = async ({ params }) => {
const period = isValueOfStringEnum(DatabaseUsageRange, params.period)
? params.period
: DatabaseUsageRange.ThirtyDays;
return sdk
.forProject(params.region, params.project)
.databases.getCollectionUsage(params.database, params.table, period);
.tables.getUsage(params.database, params.table, period);
};
@@ -12,32 +12,32 @@
import { sdk } from '$lib/stores/sdk';
import { Badge, FloatingActionBar, Table, Typography } from '@appwrite.io/pink-svelte';
import type { PageData } from './$types';
import { columns } from './store';
import { tableViewColumns } from './store';
import Confirm from '$lib/components/confirm.svelte';
export let data: PageData;
const databaseId = page.params.database;
let selectedRows: string[] = [];
let showDelete = false;
let deleting = false;
let showDelete = false;
let selectedTables: string[] = [];
async function handleDelete() {
showDelete = false;
const promises = selectedRows.map((collectionId) =>
const promises = selectedTables.map((tableId) =>
sdk
.forProject(page.params.region, page.params.project)
.databases.deleteCollection(databaseId, collectionId)
.tables.delete(databaseId, tableId)
);
try {
await Promise.all(promises);
trackEvent(Submit.TableDelete);
addNotification({
type: 'success',
message: `${selectedRows.length} table${selectedRows.length > 1 ? 's' : ''} deleted`
message: `${selectedTables.length} table${selectedTables.length > 1 ? 's' : ''} deleted`
});
invalidate(Dependencies.COLLECTIONS);
invalidate(Dependencies.TABLES);
} catch (error) {
addNotification({
type: 'error',
@@ -45,33 +45,37 @@
});
trackError(error, Submit.TableDelete);
} finally {
selectedRows = [];
selectedTables = [];
showDelete = false;
}
}
</script>
<Table.Root columns={$columns} allowSelection={$canWriteCollections} bind:selectedRows let:root>
<Table.Root
columns={$tableViewColumns}
allowSelection={$canWriteCollections}
bind:selectedRows={selectedTables}
let:root>
<svelte:fragment slot="header" let:root>
{#each $columns as { id, title }}
{#each $tableViewColumns as { id, title }}
<Table.Header.Cell column={id} {root}>{title}</Table.Header.Cell>
{/each}
</svelte:fragment>
{#each data.collections.collections as collection (collection.$id)}
{#each data.tables.tables as table (table.$id)}
<Table.Row.Link
{root}
id={collection.$id}
href={`${base}/project-${page.params.region}-${page.params.project}/databases/database-${databaseId}/table-${collection.$id}`}>
{#each $columns as column}
id={table.$id}
href={`${base}/project-${page.params.region}-${page.params.project}/databases/database-${databaseId}/table-${table.$id}`}>
{#each $tableViewColumns as column}
<Table.Cell column={column.id} {root}>
{#if column.id === '$id'}
{#key $columns}
<Id value={collection.$id}>{collection.$id}</Id>
{#key $tableViewColumns}
<Id value={table.$id}>{table.$id}</Id>
{/key}
{:else if column.id === 'name'}
{collection.name}
{table.name}
{:else}
{toLocaleDateTime(collection[column.id])}
{toLocaleDateTime(table[column.id])}
{/if}
</Table.Cell>
{/each}
@@ -79,17 +83,17 @@
{/each}
</Table.Root>
{#if selectedRows.length > 0}
{#if selectedTables.length > 0}
<FloatingActionBar>
<svelte:fragment slot="start">
<Badge content={selectedRows.length.toString()} />
<Badge content={selectedTables.length.toString()} />
<span>
{selectedRows.length > 1 ? 'tables' : 'table'}
{selectedTables.length > 1 ? 'tables' : 'table'}
selected
</span>
</svelte:fragment>
<svelte:fragment slot="end">
<Button text on:click={() => (selectedRows = [])}>Cancel</Button>
<Button text on:click={() => (selectedTables = [])}>Cancel</Button>
<Button secondary on:click={() => (showDelete = true)}>Delete</Button>
</svelte:fragment>
</FloatingActionBar>
@@ -97,7 +101,7 @@
<Confirm title="Delete tables" bind:open={showDelete} onSubmit={handleDelete} disabled={deleting}>
<Typography.Text>
Are you sure you want to delete <b>{selectedRows.length}</b>
{selectedRows.length > 1 ? 'tables' : 'table'}?
Are you sure you want to delete <b>{selectedTables.length}</b>
{selectedTables.length > 1 ? 'tables' : 'table'}?
</Typography.Text>
</Confirm>
@@ -6,8 +6,8 @@
export let data;
$: total = data.collectionsTotal;
$: count = data.collections;
$: total = data.tablesTotal;
$: count = data.tables;
$: reads = data.databaseReads;
$: readsTotal = data.databaseReadsTotal;
@@ -23,8 +23,8 @@
{total}
{count}
countMetadata={{
legend: 'Collections',
title: 'Total collections'
legend: 'Tables',
title: 'Total tables'
}} />
<UsageMultiple
@@ -6,6 +6,7 @@
import type { PageData } from './$types';
export let data: PageData;
$: total = data.databasesTotal;
$: count = data.databases;
@@ -7,5 +7,6 @@ export const load: PageLoad = async ({ params }) => {
const period = isValueOfStringEnum(DatabaseUsageRange, params.period)
? params.period
: DatabaseUsageRange.ThirtyDays;
return sdk.forProject(params.region, params.project).databases.getUsage(period);
return sdk.forProject(params.region, params.project).databases.listUsage(period);
};
@@ -18,9 +18,10 @@
const dispatch = createEventDispatcher();
// TODO: @itznotabug - check what needs to be changed here. we might need to do dual stuff to manage backwards compat?
const labelMap = {
users: { root: 'Users', teams: 'Include teams' },
databases: { root: 'Databases', documents: 'Include documents' },
databases: { root: 'Databases', rows: 'Include rows' },
functions: {
root: 'Functions',
env: 'Include environment variables',
@@ -36,7 +37,7 @@
},
databases: {
root: 'Import all databases, including tables, indexes and columns',
documents: 'Import all rows inside tables'
rows: 'Import all rows inside tables'
},
functions: {
root: 'Import all functions and their active deployment',
@@ -99,6 +99,9 @@
'attributes.read',
'indexes.read',
'documents.read',
'tables.read',
'columns.read',
'rows.read',
'files.read',
'buckets.read',
'functions.read',
@@ -98,6 +98,10 @@
'attributes.read',
'indexes.read',
'documents.read',
'tables.read',
'columns.read',
'indexes.read',
'rows.read',
'files.read',
'buckets.read',
'functions.read',
@@ -77,8 +77,9 @@
Edit the expiry of the file token created on <b>{formattedDate}</b>.
{:else}
Create a file token to grant access to a file.
<!-- TODO: @itznotabug, @adityaoberai need documentations link -->
<Link.Anchor href="https://appwrite.com/docs/">Learn more</Link.Anchor>.
<Link.Anchor href="https://appwrite.io/docs/products/storage/file-tokens"
>Learn more</Link.Anchor
>.
{/if}
</svelte:fragment>