diff --git a/AGENT.md b/AGENT.md deleted file mode 100644 index ab1a51175..000000000 --- a/AGENT.md +++ /dev/null @@ -1,24 +0,0 @@ -# AGENT.md - -## Commands -- **Build**: `turbo build` or `turbo run build:dry-run` (type check only) -- **Tests**: `turbo run test:unit` (run before completing tasks), `turbo run test:integration --filter=` -- **Single test**: `turbo run test:unit --filter=` or run test files directly in specific packages -- **Lint**: `turbo lint`, `pnpm run check:fix ` (auto-fixes with Biome) -- **Pre-completion check**: `turbo run build:dry-run lint test:unit` - -## Architecture -**Monorepo**: pnpm + Turborepo with `@buster/*` packages and `@buster-app/*` apps -- **Apps**: web (Next.js), server (Hono API), trigger (background jobs), electric-server, api (Rust legacy), cli (Rust) -- **Key packages**: ai (Mastra framework), database (Drizzle ORM), server-shared (API types), data-source, access-controls -- **Database**: PostgreSQL with Supabase, soft deletes only (`deleted_at`), queries in `@buster/database/src/queries/` -- **APIs**: Hono with functional handlers, type-safe with Zod schemas in `@buster/server-shared` - -## Code Style -- **TypeScript**: Strict mode, no `any`, handle null/undefined explicitly -- **Imports**: Use type-only imports (`import type`), Node.js protocol (`node:fs`) -- **Formatting**: Biome - 2 spaces, single quotes, trailing commas, 100 char width -- **Functions**: Functional/composable over classes, dependency injection, small focused functions -- **Logging**: Never `console.log`, use `console.info/warn/error` -- **Naming**: `@buster/{package}` for packages, `@buster-app/{app}` for apps -- **Error handling**: Comprehensive with strategic logging, soft deletes, upserts preferred diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 000000000..b34afddcd --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,136 @@ +# CLAUDE.md + +This file provides core guidance to Claude/AI assistants when working with the Buster monorepo. + +**Note**: Each package and app has its own CLAUDE.md with specific implementation details. This document contains only universal principles. + +## Monorepo Philosophy + +### Architecture Principles +1. **Packages are standalone building blocks** - Modular components with minimal cross-dependencies +2. **Apps assemble packages** - Apps piece together package code, never contain business logic directly +3. **Avoid spaghetti dependencies** - Keep clean boundaries between packages +4. **Type flow hierarchy** - Types flow: `database` → `server-shared` → `apps` + +### Critical Package Boundaries +- **`@buster/database`** - Owns ALL database queries. No direct Drizzle usage elsewhere +- **`@buster/server-shared`** - API contract layer. All request/response types live here +- **`@buster/data-source`** - Isolated data source connection logic for customer databases +- **Package imports** - Packages can use each other but maintain clear, logical dependencies + +## Development Principles + +### Functional Programming First +- **Pure functions only** - No classes for business logic +- **Composable modules** - Build features by composing small, focused functions +- **Immutable data** - Never mutate; always create new data structures +- **Higher-order functions** - Use functions that return configured functions for dependency injection +- **No OOP** - No classes, no inheritance, no `this` keyword in business logic + +### Type Safety Standards +- **Zod-first everything** - Define ALL types as Zod schemas with descriptions +- **Export inferred types** - Always use `z.infer` for TypeScript types +- **Runtime validation** - Use `.parse()` for trusted data, `.safeParse()` for user input +- **No implicit any** - Every variable, parameter, and return type must be explicitly typed +- **Constants for strings** - Use const assertions for type-safe string literals + +### Testing Philosophy +- **Test-driven development** - Write tests and assertions first, then implement +- **Colocate tests** - Keep `.test.ts` (unit) and `.int.test.ts` (integration) next to implementation +- **Test naming** - If file is `user.ts`, tests are `user.test.ts` and/or `user.int.test.ts` +- **Minimize integration dependencies** - Most logic should be testable with unit tests +- **Test descriptions** - Test names should describe the assertion and situation clearly + +## Development Workflow + +### Command Standards +**CRITICAL**: Only use Turbo commands. Never use pnpm, npm, or vitest directly. + +```bash +# Build commands +turbo build # Build entire monorepo +turbo build --filter=@buster/ai # Build specific package + +# Linting +turbo lint # Lint entire monorepo +turbo lint --filter=@buster-app/web # Lint specific app + +# Testing +turbo test:unit # Run all unit tests +turbo test:unit --filter=@buster/database # Test specific package +turbo test:integration --filter=@buster/ai # Integration tests for specific package + +# Development +turbo dev # Start development servers +``` + +### Pre-Completion Checklist +Before completing any task: +1. Run `turbo build` - Ensure everything compiles +2. Run `turbo lint` - Fix all linting issues +3. Run `turbo test:unit` - All unit tests must pass + +## Code Organization + +### File Structure +- **Small, focused files** - Each file has a single responsibility +- **Deep nesting is OK** - Organize into logical subdirectories +- **Explicit exports** - Use named exports and comprehensive index.ts files +- **Functional patterns** - Export factory functions that return configured function sets + +### Module Patterns +```typescript +// Good: Functional approach with Zod +import { z } from 'zod'; + +const UserParamsSchema = z.object({ + userId: z.string().describe('Unique user identifier'), + orgId: z.string().describe('Organization identifier') +}); + +type UserParams = z.infer; + +export function validateUser(params: UserParams) { + const validated = UserParamsSchema.parse(params); + // Implementation +} + +// Bad: Class-based approach +class UserService { // Never do this + validateUser() { } +} +``` + +## Cross-Cutting Concerns + +### Environment Variables +- Centralized at root level in `.env` file +- Turbo passes variables via `globalEnv` configuration +- Individual packages validate their required variables + +### Database Operations +- ALL queries go through `@buster/database` package +- Never use Drizzle directly outside the database package +- Soft deletes only (use `deleted_at` field) +- Prefer upserts over updates + +### API Development +- Request/response types in `@buster/server-shared` +- Import database types through server-shared for consistency +- Validate with Zod at API boundaries +- Use type imports: `import type { User } from '@buster/database'` + +## Legacy Code Migration +- **Rust code** (`apps/api`) is legacy and being migrated to TypeScript +- Focus new development on TypeScript patterns +- Follow patterns in `apps/server` for new API development + +## Agent Workflows +- Use `planner` agent for spec, plan, ticket, research development workflows. + +## Important Reminders +- Do only what has been asked; nothing more, nothing less +- Never create files unless absolutely necessary +- Always prefer editing existing files over creating new ones +- Never proactively create documentation unless explicitly requested +- Check package/app-specific CLAUDE.md files for implementation details \ No newline at end of file diff --git a/apps/server/src/api/v2/chats/[id]/index.ts b/apps/server/src/api/v2/chats/[id]/index.ts index 5f75e86fe..3cebe2107 100644 --- a/apps/server/src/api/v2/chats/[id]/index.ts +++ b/apps/server/src/api/v2/chats/[id]/index.ts @@ -1,8 +1,10 @@ import { Hono } from 'hono'; import GET from './GET'; +import SHARING from './sharing'; const app = new Hono(); app.route('/', GET); +app.route('/sharing', SHARING); export default app; diff --git a/apps/server/src/api/v2/chats/[id]/sharing/DELETE.ts b/apps/server/src/api/v2/chats/[id]/sharing/DELETE.ts new file mode 100644 index 000000000..8f2de38d9 --- /dev/null +++ b/apps/server/src/api/v2/chats/[id]/sharing/DELETE.ts @@ -0,0 +1,88 @@ +import { checkPermission } from '@buster/access-controls'; +import { findUsersByEmails, getChatById, removeAssetPermission } from '@buster/database/queries'; +import type { User } from '@buster/database/queries'; +import type { ShareDeleteRequest, ShareDeleteResponse } from '@buster/server-shared/share'; +import { ShareDeleteRequestSchema } from '@buster/server-shared/share'; +import { zValidator } from '@hono/zod-validator'; +import { Hono } from 'hono'; +import { HTTPException } from 'hono/http-exception'; + +export async function deleteChatSharingHandler( + chatId: string, + emails: ShareDeleteRequest, + user: User +): Promise { + // Get the chat to verify it exists and get owner info + const chat = await getChatById(chatId); + if (!chat) { + throw new HTTPException(404, { message: 'Chat not found' }); + } + + const permissionCheck = await checkPermission({ + userId: user.id, + assetId: chatId, + assetType: 'chat', + requiredRole: 'full_access', + workspaceSharing: chat.workspaceSharing, + organizationId: chat.organizationId, + }); + + if (!permissionCheck.hasAccess) { + throw new HTTPException(403, { + message: 'You do not have permission to delete sharing for this chat', + }); + } + + // Find users by emails + const userMap = await findUsersByEmails(emails); + + const removedEmails = []; + const notFoundEmails = []; + + for (const email of emails) { + const targetUser = userMap.get(email); + + if (!targetUser) { + notFoundEmails.push(email); + continue; + } + + // Don't allow removing permissions from the owner + if (targetUser.id === chat.createdBy) { + continue; // Skip the owner + } + + // Remove the permission + await removeAssetPermission({ + identityId: targetUser.id, + identityType: 'user', + assetId: chatId, + assetType: 'chat', + updatedBy: user.id, + }); + + removedEmails.push(email); + } + + return { + success: true, + removed: removedEmails, + notFound: notFoundEmails, + }; +} + +const app = new Hono().delete('/', zValidator('json', ShareDeleteRequestSchema), async (c) => { + const chatId = c.req.param('id'); + const emails = c.req.valid('json'); + const user = c.get('busterUser'); + + if (!chatId) { + throw new HTTPException(400, { message: 'Chat ID is required' }); + } + + const result = await deleteChatSharingHandler(chatId, emails, user); + + return c.json(result); +}); + +export default app; diff --git a/apps/server/src/api/v2/chats/[id]/sharing/GET.ts b/apps/server/src/api/v2/chats/[id]/sharing/GET.ts new file mode 100644 index 000000000..7109bc47f --- /dev/null +++ b/apps/server/src/api/v2/chats/[id]/sharing/GET.ts @@ -0,0 +1,55 @@ +import { checkPermission } from '@buster/access-controls'; +import { checkAssetPermission, getChatById, listAssetPermissions } from '@buster/database/queries'; +import type { User } from '@buster/database/queries'; +import type { ShareGetResponse } from '@buster/server-shared/reports'; +import { Hono } from 'hono'; +import { HTTPException } from 'hono/http-exception'; + +export async function getChatSharingHandler(chatId: string, user: User): Promise { + // Check if chat exists + const chat = await getChatById(chatId); + if (!chat) { + throw new HTTPException(404, { message: 'Chat not found' }); + } + + // Check if user has permission to view the chat + const permissionCheck = await checkPermission({ + userId: user.id, + assetId: chatId, + assetType: 'chat', + requiredRole: 'can_view', + workspaceSharing: chat.workspaceSharing, + organizationId: chat.organizationId, + }); + + if (!permissionCheck.hasAccess) { + throw new HTTPException(403, { + message: 'You do not have permission to view this chat', + }); + } + + // Get all permissions for the chat + const permissions = await listAssetPermissions({ + assetId: chatId, + assetType: 'chat', + }); + + return { + permissions, + }; +} + +const app = new Hono().get('/', async (c) => { + const chatId = c.req.param('id'); + const user = c.get('busterUser'); + + if (!chatId) { + throw new HTTPException(400, { message: 'Chat ID is required' }); + } + + const result = await getChatSharingHandler(chatId, user); + + return c.json(result); +}); + +export default app; diff --git a/apps/server/src/api/v2/chats/[id]/sharing/POST.ts b/apps/server/src/api/v2/chats/[id]/sharing/POST.ts new file mode 100644 index 000000000..3ba89f5ee --- /dev/null +++ b/apps/server/src/api/v2/chats/[id]/sharing/POST.ts @@ -0,0 +1,113 @@ +import { checkPermission } from '@buster/access-controls'; +import { + bulkCreateAssetPermissions, + findUsersByEmails, + getChatById, +} from '@buster/database/queries'; +import type { User } from '@buster/database/queries'; +import type { SharePostRequest, SharePostResponse } from '@buster/server-shared/share'; +import { SharePostRequestSchema } from '@buster/server-shared/share'; +import { zValidator } from '@hono/zod-validator'; +import { Hono } from 'hono'; +import { HTTPException } from 'hono/http-exception'; + +export async function createChatSharingHandler( + chatId: string, + shareRequests: SharePostRequest, + user: User +): Promise { + // Get the chat to verify it exists + const chat = await getChatById(chatId); + if (!chat) { + throw new HTTPException(404, { message: 'Chat not found' }); + } + + const permissionCheck = await checkPermission({ + userId: user.id, + assetId: chatId, + assetType: 'chat', + requiredRole: 'can_edit', + workspaceSharing: chat.workspaceSharing, + organizationId: chat.organizationId, + }); + + if (!permissionCheck.hasAccess) { + throw new HTTPException(403, { + message: 'You do not have permission to edit this chat', + }); + } + + // Extract emails from the share requests + const emails = shareRequests.map((req) => req.email); + + // Find users by emails + const userMap = await findUsersByEmails(emails); + + const permissions = []; + const sharedEmails = []; + const notFoundEmails = []; + + for (const shareRequest of shareRequests) { + const targetUser = userMap.get(shareRequest.email); + + if (!targetUser) { + notFoundEmails.push(shareRequest.email); + continue; + } + + sharedEmails.push(shareRequest.email); + + // Map ShareRole to AssetPermissionRole + const roleMapping = { + owner: 'owner', + full_access: 'full_access', + can_edit: 'can_edit', + can_filter: 'can_filter', + can_view: 'can_view', + viewer: 'can_view', // Map viewer to can_view + } as const; + + const mappedRole = roleMapping[shareRequest.role]; + if (!mappedRole) { + throw new HTTPException(400, { + message: `Invalid role: ${shareRequest.role} for user ${shareRequest.email}`, + }); + } + + permissions.push({ + identityId: targetUser.id, + identityType: 'user' as const, + assetId: chatId, + assetType: 'chat' as const, + role: mappedRole, + createdBy: user.id, + }); + } + + // Create permissions in bulk + if (permissions.length > 0) { + await bulkCreateAssetPermissions({ permissions }); + } + + return { + success: true, + shared: sharedEmails, + notFound: notFoundEmails, + }; +} + +const app = new Hono().post('/', zValidator('json', SharePostRequestSchema), async (c) => { + const chatId = c.req.param('id'); + const shareRequests = c.req.valid('json'); + const user = c.get('busterUser'); + + if (!chatId) { + throw new HTTPException(400, { message: 'Chat ID is required' }); + } + + const result = await createChatSharingHandler(chatId, shareRequests, user); + + return c.json(result); +}); + +export default app; diff --git a/apps/server/src/api/v2/chats/[id]/sharing/PUT.ts b/apps/server/src/api/v2/chats/[id]/sharing/PUT.ts new file mode 100644 index 000000000..306cfdbf9 --- /dev/null +++ b/apps/server/src/api/v2/chats/[id]/sharing/PUT.ts @@ -0,0 +1,140 @@ +import { checkPermission } from '@buster/access-controls'; +import { + bulkCreateAssetPermissions, + findUsersByEmails, + getChatById, + getUserOrganizationId, + updateChatSharing, +} from '@buster/database/queries'; +import type { User } from '@buster/database/queries'; +import type { GetChatResponse } from '@buster/server-shared/chats'; +import { type ShareUpdateRequest, ShareUpdateRequestSchema } from '@buster/server-shared/share'; +import { zValidator } from '@hono/zod-validator'; +import { Hono } from 'hono'; +import { HTTPException } from 'hono/http-exception'; +import { getChatHandler } from '../GET'; + +export async function updateChatShareHandler( + chatId: string, + request: ShareUpdateRequest, + user: User & { organizationId: string } +) { + // Check if chat exists + const chat = await getChatById(chatId); + if (!chat) { + throw new HTTPException(404, { message: 'Chat not found' }); + } + + const permissionCheck = await checkPermission({ + userId: user.id, + assetId: chatId, + assetType: 'chat', + requiredRole: 'full_access', + workspaceSharing: chat.workspaceSharing, + organizationId: chat.organizationId, + }); + + if (!permissionCheck.hasAccess) { + throw new HTTPException(403, { + message: 'You do not have permission to update sharing for this chat', + }); + } + + const { publicly_accessible, public_expiry_date, workspace_sharing, users } = request; + + // Handle user permissions if provided + if (users && users.length > 0) { + // Extract emails from the user permissions + const emails = users.map((u) => u.email); + + // Find users by emails + const userMap = await findUsersByEmails(emails); + + const permissions = []; + + for (const userPermission of users) { + const targetUser = userMap.get(userPermission.email); + + if (!targetUser) { + // Skip users that don't exist - you may want to collect these and return as warnings + continue; + } + + // Map ShareRole to AssetPermissionRole + const roleMapping = { + owner: 'owner', + full_access: 'full_access', + can_edit: 'can_edit', + can_filter: 'can_filter', + can_view: 'can_view', + viewer: 'can_view', // Map viewer to can_view + } as const; + + const mappedRole = roleMapping[userPermission.role]; + if (!mappedRole) { + throw new HTTPException(400, { + message: `Invalid role: ${userPermission.role} for user ${userPermission.email}`, + }); + } + + permissions.push({ + identityId: targetUser.id, + identityType: 'user' as const, + assetId: chatId, + assetType: 'chat' as const, + role: mappedRole, + createdBy: user.id, + }); + } + + // Create/update permissions in bulk + if (permissions.length > 0) { + await bulkCreateAssetPermissions({ permissions }); + } + } + + // Update chat sharing settings - only pass defined values + const updateOptions: Parameters[2] = {}; + if (publicly_accessible !== undefined) { + updateOptions.publicly_accessible = publicly_accessible; + } + if (public_expiry_date !== undefined) { + updateOptions.public_expiry_date = public_expiry_date; + } + if (workspace_sharing !== undefined) { + updateOptions.workspace_sharing = workspace_sharing; + } + await updateChatSharing(chatId, user.id, updateOptions); + + const updatedChat: GetChatResponse = await getChatHandler({ + chatId, + user, + }); + + return updatedChat; +} + +const app = new Hono().put('/', zValidator('json', ShareUpdateRequestSchema), async (c) => { + const chatId = c.req.param('id'); + const request = c.req.valid('json'); + const user = c.get('busterUser'); + + if (!chatId) { + throw new HTTPException(404, { message: 'Chat not found' }); + } + + const userOrg = await getUserOrganizationId(user.id); + + if (!userOrg) { + throw new HTTPException(403, { message: 'User is not associated with an organization' }); + } + + const updatedChat: GetChatResponse = await updateChatShareHandler(chatId, request, { + ...user, + organizationId: userOrg.organizationId, + }); + + return c.json(updatedChat); +}); + +export default app; diff --git a/apps/server/src/api/v2/chats/[id]/sharing/index.ts b/apps/server/src/api/v2/chats/[id]/sharing/index.ts new file mode 100644 index 000000000..659e3fcbc --- /dev/null +++ b/apps/server/src/api/v2/chats/[id]/sharing/index.ts @@ -0,0 +1,15 @@ +import { Hono } from 'hono'; +import { requireAuth } from '../../../../../middleware/auth'; +import DELETE from './DELETE'; +import GET from './GET'; +import POST from './POST'; +import PUT from './PUT'; + +const app = new Hono() + .use('*', requireAuth) + .route('/', GET) + .route('/', POST) + .route('/', PUT) + .route('/', DELETE); + +export default app; diff --git a/apps/server/src/api/v2/dashboards/[id]/index.ts b/apps/server/src/api/v2/dashboards/[id]/index.ts index e2401431d..11abb7e7c 100644 --- a/apps/server/src/api/v2/dashboards/[id]/index.ts +++ b/apps/server/src/api/v2/dashboards/[id]/index.ts @@ -1,9 +1,11 @@ import { Hono } from 'hono'; import '../../../../types/hono.types'; import dashboardByIdRoutes from './GET'; +import SHARING from './sharing'; const app = new Hono() // /dashboards/:id GET - .route('/', dashboardByIdRoutes); + .route('/', dashboardByIdRoutes) + .route('/sharing', SHARING); export default app; diff --git a/apps/server/src/api/v2/dashboards/[id]/sharing/DELETE.ts b/apps/server/src/api/v2/dashboards/[id]/sharing/DELETE.ts new file mode 100644 index 000000000..3a20c016d --- /dev/null +++ b/apps/server/src/api/v2/dashboards/[id]/sharing/DELETE.ts @@ -0,0 +1,93 @@ +import { checkPermission } from '@buster/access-controls'; +import { + findUsersByEmails, + getDashboardById, + removeAssetPermission, +} from '@buster/database/queries'; +import type { User } from '@buster/database/queries'; +import type { ShareDeleteResponse } from '@buster/server-shared/share'; +import type { ShareDeleteRequest } from '@buster/server-shared/share'; +import { ShareDeleteRequestSchema } from '@buster/server-shared/share'; +import { zValidator } from '@hono/zod-validator'; +import { Hono } from 'hono'; +import { HTTPException } from 'hono/http-exception'; + +export async function deleteDashboardSharingHandler( + dashboardId: string, + emails: ShareDeleteRequest, + user: User +): Promise { + // Get the dashboard to verify it exists and get owner info + const dashboard = await getDashboardById({ dashboardId }); + if (!dashboard) { + throw new HTTPException(404, { message: 'Dashboard not found' }); + } + + const permissionCheck = await checkPermission({ + userId: user.id, + assetId: dashboardId, + assetType: 'dashboard_file', + requiredRole: 'full_access', + workspaceSharing: dashboard.workspaceSharing, + organizationId: dashboard.organizationId, + }); + + if (!permissionCheck.hasAccess) { + throw new HTTPException(403, { + message: 'You do not have permission to delete sharing for this dashboard', + }); + } + + // Find users by emails + const userMap = await findUsersByEmails(emails); + + const removedEmails = []; + const notFoundEmails = []; + + for (const email of emails) { + const targetUser = userMap.get(email); + + if (!targetUser) { + notFoundEmails.push(email); + continue; + } + + // Don't allow removing permissions from the owner + if (targetUser.id === dashboard.createdBy) { + continue; // Skip the owner + } + + // Remove the permission + await removeAssetPermission({ + identityId: targetUser.id, + identityType: 'user', + assetId: dashboardId, + assetType: 'dashboard_file', + updatedBy: user.id, + }); + + removedEmails.push(email); + } + + return { + success: true, + removed: removedEmails, + notFound: notFoundEmails, + }; +} + +const app = new Hono().delete('/', zValidator('json', ShareDeleteRequestSchema), async (c) => { + const dashboardId = c.req.param('id'); + const emails = c.req.valid('json'); + const user = c.get('busterUser'); + + if (!dashboardId) { + throw new HTTPException(400, { message: 'Dashboard ID is required' }); + } + + const result = await deleteDashboardSharingHandler(dashboardId, emails, user); + + return c.json(result); +}); + +export default app; diff --git a/apps/server/src/api/v2/dashboards/[id]/sharing/GET.ts b/apps/server/src/api/v2/dashboards/[id]/sharing/GET.ts new file mode 100644 index 000000000..c41272af3 --- /dev/null +++ b/apps/server/src/api/v2/dashboards/[id]/sharing/GET.ts @@ -0,0 +1,58 @@ +import { checkPermission } from '@buster/access-controls'; +import { getDashboardById, listAssetPermissions } from '@buster/database/queries'; +import type { User } from '@buster/database/queries'; +import type { ShareGetResponse } from '@buster/server-shared/reports'; +import { Hono } from 'hono'; +import { HTTPException } from 'hono/http-exception'; + +export async function getDashboardSharingHandler( + dashboardId: string, + user: User +): Promise { + // Check if dashboard exists + const dashboard = await getDashboardById({ dashboardId }); + if (!dashboard) { + throw new HTTPException(404, { message: 'Dashboard not found' }); + } + + // Check if user has permission to view the dashboard + const permissionCheck = await checkPermission({ + userId: user.id, + assetId: dashboardId, + assetType: 'dashboard_file', + requiredRole: 'can_view', + workspaceSharing: dashboard.workspaceSharing, + organizationId: dashboard.organizationId, + }); + + if (!permissionCheck.hasAccess) { + throw new HTTPException(403, { + message: 'You do not have permission to view this dashboard', + }); + } + + // Get all permissions for the dashboard + const permissions = await listAssetPermissions({ + assetId: dashboardId, + assetType: 'dashboard_file', + }); + + return { + permissions, + }; +} + +const app = new Hono().get('/', async (c) => { + const dashboardId = c.req.param('id'); + const user = c.get('busterUser'); + + if (!dashboardId) { + throw new HTTPException(400, { message: 'Dashboard ID is required' }); + } + + const result = await getDashboardSharingHandler(dashboardId, user); + + return c.json(result); +}); + +export default app; diff --git a/apps/server/src/api/v2/dashboards/[id]/sharing/POST.ts b/apps/server/src/api/v2/dashboards/[id]/sharing/POST.ts new file mode 100644 index 000000000..cea46fa56 --- /dev/null +++ b/apps/server/src/api/v2/dashboards/[id]/sharing/POST.ts @@ -0,0 +1,114 @@ +import { checkPermission } from '@buster/access-controls'; +import { + bulkCreateAssetPermissions, + findUsersByEmails, + getDashboardById, +} from '@buster/database/queries'; +import type { User } from '@buster/database/queries'; +import type { SharePostResponse } from '@buster/server-shared/share'; +import type { SharePostRequest } from '@buster/server-shared/share'; +import { SharePostRequestSchema } from '@buster/server-shared/share'; +import { zValidator } from '@hono/zod-validator'; +import { Hono } from 'hono'; +import { HTTPException } from 'hono/http-exception'; + +export async function createDashboardSharingHandler( + dashboardId: string, + shareRequests: SharePostRequest, + user: User +): Promise { + // Get the dashboard to verify it exists + const dashboard = await getDashboardById({ dashboardId }); + if (!dashboard) { + throw new HTTPException(404, { message: 'Dashboard not found' }); + } + + const permissionCheck = await checkPermission({ + userId: user.id, + assetId: dashboardId, + assetType: 'dashboard_file', + requiredRole: 'can_edit', + workspaceSharing: dashboard.workspaceSharing, + organizationId: dashboard.organizationId, + }); + + if (!permissionCheck.hasAccess) { + throw new HTTPException(403, { + message: 'You do not have permission to edit this dashboard', + }); + } + + // Extract emails from the share requests + const emails = shareRequests.map((req) => req.email); + + // Find users by emails + const userMap = await findUsersByEmails(emails); + + const permissions = []; + const sharedEmails = []; + const notFoundEmails = []; + + for (const shareRequest of shareRequests) { + const targetUser = userMap.get(shareRequest.email); + + if (!targetUser) { + notFoundEmails.push(shareRequest.email); + continue; + } + + sharedEmails.push(shareRequest.email); + + // Map ShareRole to AssetPermissionRole + const roleMapping = { + owner: 'owner', + full_access: 'full_access', + can_edit: 'can_edit', + can_filter: 'can_filter', + can_view: 'can_view', + viewer: 'can_view', // Map viewer to can_view + } as const; + + const mappedRole = roleMapping[shareRequest.role]; + if (!mappedRole) { + throw new HTTPException(400, { + message: `Invalid role: ${shareRequest.role} for user ${shareRequest.email}`, + }); + } + + permissions.push({ + identityId: targetUser.id, + identityType: 'user' as const, + assetId: dashboardId, + assetType: 'dashboard_file' as const, + role: mappedRole, + createdBy: user.id, + }); + } + + // Create permissions in bulk + if (permissions.length > 0) { + await bulkCreateAssetPermissions({ permissions }); + } + + return { + success: true, + shared: sharedEmails, + notFound: notFoundEmails, + }; +} + +const app = new Hono().post('/', zValidator('json', SharePostRequestSchema), async (c) => { + const dashboardId = c.req.param('id'); + const shareRequests = c.req.valid('json'); + const user = c.get('busterUser'); + + if (!dashboardId) { + throw new HTTPException(400, { message: 'Dashboard ID is required' }); + } + + const result = await createDashboardSharingHandler(dashboardId, shareRequests, user); + + return c.json(result); +}); + +export default app; diff --git a/apps/server/src/api/v2/dashboards/[id]/sharing/PUT.ts b/apps/server/src/api/v2/dashboards/[id]/sharing/PUT.ts new file mode 100644 index 000000000..3af2582e0 --- /dev/null +++ b/apps/server/src/api/v2/dashboards/[id]/sharing/PUT.ts @@ -0,0 +1,139 @@ +import { checkPermission } from '@buster/access-controls'; +import { + bulkCreateAssetPermissions, + findUsersByEmails, + getDashboardById, + getUserOrganizationId, + updateDashboard, +} from '@buster/database/queries'; +import type { User } from '@buster/database/queries'; +import type { GetDashboardResponse } from '@buster/server-shared/dashboards'; +import { type ShareUpdateRequest, ShareUpdateRequestSchema } from '@buster/server-shared/share'; +import { zValidator } from '@hono/zod-validator'; +import { Hono } from 'hono'; +import { HTTPException } from 'hono/http-exception'; +import { getDashboardHandler } from '../GET'; + +export async function updateDashboardShareHandler( + dashboardId: string, + request: ShareUpdateRequest, + user: User & { organizationId: string } +) { + // Check if dashboard exists + const dashboard = await getDashboardById({ dashboardId }); + if (!dashboard) { + throw new HTTPException(404, { message: 'Dashboard not found' }); + } + + const permissionCheck = await checkPermission({ + userId: user.id, + assetId: dashboardId, + assetType: 'dashboard_file', + requiredRole: 'full_access', + workspaceSharing: dashboard.workspaceSharing, + organizationId: dashboard.organizationId, + }); + + if (!permissionCheck.hasAccess) { + throw new HTTPException(403, { + message: 'You do not have permission to update sharing for this dashboard', + }); + } + + const { publicly_accessible, public_expiry_date, public_password, workspace_sharing, users } = + request; + + // Handle user permissions if provided + if (users && users.length > 0) { + // Extract emails from the user permissions + const emails = users.map((u) => u.email); + + // Find users by emails + const userMap = await findUsersByEmails(emails); + + const permissions = []; + + for (const userPermission of users) { + const targetUser = userMap.get(userPermission.email); + + if (!targetUser) { + // Skip users that don't exist - you may want to collect these and return as warnings + continue; + } + + // Map ShareRole to AssetPermissionRole + const roleMapping = { + owner: 'owner', + full_access: 'full_access', + can_edit: 'can_edit', + can_filter: 'can_filter', + can_view: 'can_view', + viewer: 'can_view', // Map viewer to can_view + } as const; + + const mappedRole = roleMapping[userPermission.role]; + if (!mappedRole) { + throw new HTTPException(400, { + message: `Invalid role: ${userPermission.role} for user ${userPermission.email}`, + }); + } + + permissions.push({ + identityId: targetUser.id, + identityType: 'user' as const, + assetId: dashboardId, + assetType: 'dashboard_file' as const, + role: mappedRole, + createdBy: user.id, + }); + } + + // Create/update permissions in bulk + if (permissions.length > 0) { + await bulkCreateAssetPermissions({ permissions }); + } + } + + // Update dashboard sharing settings + await updateDashboard({ + dashboardId, + userId: user.id, + publicly_accessible, + public_expiry_date, + public_password, + workspace_sharing, + }); + + const updatedDashboard: GetDashboardResponse = await getDashboardHandler({ dashboardId }, user); + + return updatedDashboard; +} + +const app = new Hono().put('/', zValidator('json', ShareUpdateRequestSchema), async (c) => { + const dashboardId = c.req.param('id'); + const request = c.req.valid('json'); + const user = c.get('busterUser'); + + if (!dashboardId) { + throw new HTTPException(404, { message: 'Dashboard not found' }); + } + + const userOrg = await getUserOrganizationId(user.id); + + if (!userOrg) { + throw new HTTPException(403, { message: 'User is not associated with an organization' }); + } + + const updatedDashboard: GetDashboardResponse = await updateDashboardShareHandler( + dashboardId, + request, + { + ...user, + organizationId: userOrg.organizationId, + } + ); + + return c.json(updatedDashboard); +}); + +export default app; diff --git a/apps/server/src/api/v2/dashboards/[id]/sharing/index.ts b/apps/server/src/api/v2/dashboards/[id]/sharing/index.ts new file mode 100644 index 000000000..659e3fcbc --- /dev/null +++ b/apps/server/src/api/v2/dashboards/[id]/sharing/index.ts @@ -0,0 +1,15 @@ +import { Hono } from 'hono'; +import { requireAuth } from '../../../../../middleware/auth'; +import DELETE from './DELETE'; +import GET from './GET'; +import POST from './POST'; +import PUT from './PUT'; + +const app = new Hono() + .use('*', requireAuth) + .route('/', GET) + .route('/', POST) + .route('/', PUT) + .route('/', DELETE); + +export default app; diff --git a/apps/server/src/api/v2/metric_files/[id]/index.ts b/apps/server/src/api/v2/metric_files/[id]/index.ts index 8229d9888..af121e56c 100644 --- a/apps/server/src/api/v2/metric_files/[id]/index.ts +++ b/apps/server/src/api/v2/metric_files/[id]/index.ts @@ -3,11 +3,13 @@ import { standardErrorHandler } from '../../../../utils/response'; import GET from './GET'; import DATA from './data/GET'; import DOWNLOAD from './download/GET'; +import SHARING from './sharing'; const app = new Hono() .route('/', GET) .route('/data', DATA) .route('/download', DOWNLOAD) + .route('/sharing', SHARING) .onError(standardErrorHandler); export default app; diff --git a/apps/server/src/api/v2/metric_files/[id]/sharing/DELETE.ts b/apps/server/src/api/v2/metric_files/[id]/sharing/DELETE.ts new file mode 100644 index 000000000..e1674c2ac --- /dev/null +++ b/apps/server/src/api/v2/metric_files/[id]/sharing/DELETE.ts @@ -0,0 +1,93 @@ +import { checkPermission } from '@buster/access-controls'; +import { + findUsersByEmails, + getMetricFileById, + removeAssetPermission, +} from '@buster/database/queries'; +import type { User } from '@buster/database/queries'; +import type { ShareDeleteResponse } from '@buster/server-shared/share'; +import type { ShareDeleteRequest } from '@buster/server-shared/share'; +import { ShareDeleteRequestSchema } from '@buster/server-shared/share'; +import { zValidator } from '@hono/zod-validator'; +import { Hono } from 'hono'; +import { HTTPException } from 'hono/http-exception'; + +export async function deleteMetricSharingHandler( + metricId: string, + emails: ShareDeleteRequest, + user: User +): Promise { + // Get the metric to verify it exists and get owner info + const metric = await getMetricFileById(metricId); + if (!metric) { + throw new HTTPException(404, { message: 'Metric not found' }); + } + + const permissionCheck = await checkPermission({ + userId: user.id, + assetId: metricId, + assetType: 'metric_file', + requiredRole: 'full_access', + workspaceSharing: metric.workspaceSharing, + organizationId: metric.organizationId, + }); + + if (!permissionCheck.hasAccess) { + throw new HTTPException(403, { + message: 'You do not have permission to delete sharing for this metric', + }); + } + + // Find users by emails + const userMap = await findUsersByEmails(emails); + + const removedEmails = []; + const notFoundEmails = []; + + for (const email of emails) { + const targetUser = userMap.get(email); + + if (!targetUser) { + notFoundEmails.push(email); + continue; + } + + // Don't allow removing permissions from the owner + if (targetUser.id === metric.createdBy) { + continue; // Skip the owner + } + + // Remove the permission + await removeAssetPermission({ + identityId: targetUser.id, + identityType: 'user', + assetId: metricId, + assetType: 'metric_file', + updatedBy: user.id, + }); + + removedEmails.push(email); + } + + return { + success: true, + removed: removedEmails, + notFound: notFoundEmails, + }; +} + +const app = new Hono().delete('/', zValidator('json', ShareDeleteRequestSchema), async (c) => { + const metricId = c.req.param('id'); + const emails = c.req.valid('json'); + const user = c.get('busterUser'); + + if (!metricId) { + throw new HTTPException(400, { message: 'Metric ID is required' }); + } + + const result = await deleteMetricSharingHandler(metricId, emails, user); + + return c.json(result); +}); + +export default app; diff --git a/apps/server/src/api/v2/metric_files/[id]/sharing/GET.ts b/apps/server/src/api/v2/metric_files/[id]/sharing/GET.ts new file mode 100644 index 000000000..0708b3fba --- /dev/null +++ b/apps/server/src/api/v2/metric_files/[id]/sharing/GET.ts @@ -0,0 +1,58 @@ +import { checkPermission } from '@buster/access-controls'; +import { getMetricFileById, listAssetPermissions } from '@buster/database/queries'; +import type { User } from '@buster/database/queries'; +import type { ShareGetResponse } from '@buster/server-shared/reports'; +import { Hono } from 'hono'; +import { HTTPException } from 'hono/http-exception'; + +export async function getMetricSharingHandler( + metricId: string, + user: User +): Promise { + // Check if metric exists + const metric = await getMetricFileById(metricId); + if (!metric) { + throw new HTTPException(404, { message: 'Metric not found' }); + } + + // Check if user has permission to view the metric + const permissionCheck = await checkPermission({ + userId: user.id, + assetId: metricId, + assetType: 'metric_file', + requiredRole: 'can_view', + workspaceSharing: metric.workspaceSharing, + organizationId: metric.organizationId, + }); + + if (!permissionCheck.hasAccess) { + throw new HTTPException(403, { + message: 'You do not have permission to view this metric', + }); + } + + // Get all permissions for the metric + const permissions = await listAssetPermissions({ + assetId: metricId, + assetType: 'metric_file', + }); + + return { + permissions, + }; +} + +const app = new Hono().get('/', async (c) => { + const metricId = c.req.param('id'); + const user = c.get('busterUser'); + + if (!metricId) { + throw new HTTPException(400, { message: 'Metric ID is required' }); + } + + const result = await getMetricSharingHandler(metricId, user); + + return c.json(result); +}); + +export default app; diff --git a/apps/server/src/api/v2/metric_files/[id]/sharing/POST.ts b/apps/server/src/api/v2/metric_files/[id]/sharing/POST.ts new file mode 100644 index 000000000..a1cab1f8d --- /dev/null +++ b/apps/server/src/api/v2/metric_files/[id]/sharing/POST.ts @@ -0,0 +1,116 @@ +import { checkPermission } from '@buster/access-controls'; +import { + bulkCreateAssetPermissions, + findUsersByEmails, + getMetricFileById, +} from '@buster/database/queries'; +import type { User } from '@buster/database/queries'; +import type { SharePostResponse } from '@buster/server-shared/share'; +import type { SharePostRequest } from '@buster/server-shared/share'; +import { SharePostRequestSchema } from '@buster/server-shared/share'; +import { zValidator } from '@hono/zod-validator'; +import { Hono } from 'hono'; +import { HTTPException } from 'hono/http-exception'; +import { checkIfAssetIsEditable } from '../../../../../shared-helpers/asset-public-access'; + +export async function createMetricSharingHandler( + metricId: string, + shareRequests: SharePostRequest, + user: User +): Promise { + // Get the metric to verify it exists + const metric = await getMetricFileById(metricId); + if (!metric) { + throw new HTTPException(404, { message: 'Metric not found' }); + } + + // Check if user has permission to edit the metric + const permissionCheck = await checkPermission({ + userId: user.id, + assetId: metricId, + assetType: 'metric_file', + requiredRole: 'can_edit', + workspaceSharing: metric.workspaceSharing, + organizationId: metric.organizationId, + }); + + if (!permissionCheck.hasAccess) { + throw new HTTPException(403, { + message: 'You do not have permission to edit this metric', + }); + } + + // Extract emails from the share requests + const emails = shareRequests.map((req) => req.email); + + // Find users by emails + const userMap = await findUsersByEmails(emails); + + const permissions = []; + const sharedEmails = []; + const notFoundEmails = []; + + for (const shareRequest of shareRequests) { + const targetUser = userMap.get(shareRequest.email); + + if (!targetUser) { + notFoundEmails.push(shareRequest.email); + continue; + } + + sharedEmails.push(shareRequest.email); + + // Map ShareRole to AssetPermissionRole + const roleMapping = { + owner: 'owner', + full_access: 'full_access', + can_edit: 'can_edit', + can_filter: 'can_filter', + can_view: 'can_view', + viewer: 'can_view', // Map viewer to can_view + } as const; + + const mappedRole = roleMapping[shareRequest.role]; + if (!mappedRole) { + throw new HTTPException(400, { + message: `Invalid role: ${shareRequest.role} for user ${shareRequest.email}`, + }); + } + + permissions.push({ + identityId: targetUser.id, + identityType: 'user' as const, + assetId: metricId, + assetType: 'metric_file' as const, + role: mappedRole, + createdBy: user.id, + }); + } + + // Create permissions in bulk + if (permissions.length > 0) { + await bulkCreateAssetPermissions({ permissions }); + } + + return { + success: true, + shared: sharedEmails, + notFound: notFoundEmails, + }; +} + +const app = new Hono().post('/', zValidator('json', SharePostRequestSchema), async (c) => { + const metricId = c.req.param('id'); + const shareRequests = c.req.valid('json'); + const user = c.get('busterUser'); + + if (!metricId) { + throw new HTTPException(400, { message: 'Metric ID is required' }); + } + + const result = await createMetricSharingHandler(metricId, shareRequests, user); + + return c.json(result); +}); + +export default app; diff --git a/apps/server/src/api/v2/metric_files/[id]/sharing/PUT.ts b/apps/server/src/api/v2/metric_files/[id]/sharing/PUT.ts new file mode 100644 index 000000000..6ffb99ed4 --- /dev/null +++ b/apps/server/src/api/v2/metric_files/[id]/sharing/PUT.ts @@ -0,0 +1,139 @@ +import { checkPermission } from '@buster/access-controls'; +import { + bulkCreateAssetPermissions, + findUsersByEmails, + getMetricFileById, + getUserOrganizationId, + updateMetric, +} from '@buster/database/queries'; +import type { User } from '@buster/database/queries'; +import type { ShareMetricUpdateResponse } from '@buster/server-shared/metrics'; +import { type ShareUpdateRequest, ShareUpdateRequestSchema } from '@buster/server-shared/share'; +import { zValidator } from '@hono/zod-validator'; +import { Hono } from 'hono'; +import { HTTPException } from 'hono/http-exception'; +import { getMetricHandler } from '../GET'; + +export async function updateMetricShareHandler( + metricId: string, + request: ShareUpdateRequest, + user: User & { organizationId: string } +) { + // Check if metric exists + const metric = await getMetricFileById(metricId); + if (!metric) { + throw new HTTPException(404, { message: 'Metric not found' }); + } + + const permissionCheck = await checkPermission({ + userId: user.id, + assetId: metricId, + assetType: 'metric_file', + requiredRole: 'full_access', + workspaceSharing: metric.workspaceSharing, + organizationId: metric.organizationId, + }); + + if (!permissionCheck.hasAccess) { + throw new HTTPException(403, { + message: 'You do not have permission to update sharing for this metric', + }); + } + + const { publicly_accessible, public_expiry_date, public_password, workspace_sharing, users } = + request; + + // Handle user permissions if provided + if (users && users.length > 0) { + // Extract emails from the user permissions + const emails = users.map((u) => u.email); + + // Find users by emails + const userMap = await findUsersByEmails(emails); + + const permissions = []; + + for (const userPermission of users) { + const targetUser = userMap.get(userPermission.email); + + if (!targetUser) { + // Skip users that don't exist - you may want to collect these and return as warnings + continue; + } + + // Map ShareRole to AssetPermissionRole + const roleMapping = { + owner: 'owner', + full_access: 'full_access', + can_edit: 'can_edit', + can_filter: 'can_filter', + can_view: 'can_view', + viewer: 'can_view', // Map viewer to can_view + } as const; + + const mappedRole = roleMapping[userPermission.role]; + if (!mappedRole) { + throw new HTTPException(400, { + message: `Invalid role: ${userPermission.role} for user ${userPermission.email}`, + }); + } + + permissions.push({ + identityId: targetUser.id, + identityType: 'user' as const, + assetId: metricId, + assetType: 'metric_file' as const, + role: mappedRole, + createdBy: user.id, + }); + } + + // Create/update permissions in bulk + if (permissions.length > 0) { + await bulkCreateAssetPermissions({ permissions }); + } + } + + // Update metric sharing settings + await updateMetric({ + metricId, + userId: user.id, + publicly_accessible, + public_expiry_date, + public_password, + workspace_sharing, + }); + + const updatedMetric: ShareMetricUpdateResponse = await getMetricHandler({ metricId }, user); + + return updatedMetric; +} + +const app = new Hono().put('/', zValidator('json', ShareUpdateRequestSchema), async (c) => { + const metricId = c.req.param('id'); + const request = c.req.valid('json'); + const user = c.get('busterUser'); + + if (!metricId) { + throw new HTTPException(404, { message: 'Metric not found' }); + } + + const userOrg = await getUserOrganizationId(user.id); + + if (!userOrg) { + throw new HTTPException(403, { message: 'User is not associated with an organization' }); + } + + const updatedMetric: ShareMetricUpdateResponse = await updateMetricShareHandler( + metricId, + request, + { + ...user, + organizationId: userOrg.organizationId, + } + ); + + return c.json(updatedMetric); +}); + +export default app; diff --git a/apps/server/src/api/v2/metric_files/[id]/sharing/index.ts b/apps/server/src/api/v2/metric_files/[id]/sharing/index.ts new file mode 100644 index 000000000..659e3fcbc --- /dev/null +++ b/apps/server/src/api/v2/metric_files/[id]/sharing/index.ts @@ -0,0 +1,15 @@ +import { Hono } from 'hono'; +import { requireAuth } from '../../../../../middleware/auth'; +import DELETE from './DELETE'; +import GET from './GET'; +import POST from './POST'; +import PUT from './PUT'; + +const app = new Hono() + .use('*', requireAuth) + .route('/', GET) + .route('/', POST) + .route('/', PUT) + .route('/', DELETE); + +export default app; diff --git a/apps/server/src/api/v2/reports/[id]/sharing/DELETE.ts b/apps/server/src/api/v2/reports/[id]/sharing/DELETE.ts index a5f0633b1..5b8f7ddcf 100644 --- a/apps/server/src/api/v2/reports/[id]/sharing/DELETE.ts +++ b/apps/server/src/api/v2/reports/[id]/sharing/DELETE.ts @@ -1,37 +1,43 @@ +import { checkPermission } from '@buster/access-controls'; import { findUsersByEmails, getReportFileById, - getReportWorkspaceSharing, removeAssetPermission, } from '@buster/database/queries'; import type { User } from '@buster/database/queries'; -import type { ShareDeleteResponse } from '@buster/server-shared/reports'; +import type { ShareDeleteResponse } from '@buster/server-shared/share'; import type { ShareDeleteRequest } from '@buster/server-shared/share'; import { ShareDeleteRequestSchema } from '@buster/server-shared/share'; import { zValidator } from '@hono/zod-validator'; import { Hono } from 'hono'; import { HTTPException } from 'hono/http-exception'; -import { checkIfAssetIsEditable } from '../../../../../shared-helpers/asset-public-access'; export async function deleteReportSharingHandler( reportId: string, emails: ShareDeleteRequest, user: User ): Promise { - await checkIfAssetIsEditable({ - user, - assetId: reportId, - assetType: 'report_file', - workspaceSharing: getReportWorkspaceSharing, - requiredRole: 'full_access', - }); - // Get the report to verify it exists and get owner info const report = await getReportFileById({ reportId, userId: user.id }); if (!report) { throw new HTTPException(404, { message: 'Report not found' }); } + const permissionCheck = await checkPermission({ + userId: user.id, + assetId: reportId, + assetType: 'report_file', + requiredRole: 'full_access', + workspaceSharing: report.workspace_sharing, + organizationId: report.organization_id, + }); + + if (!permissionCheck.hasAccess) { + throw new HTTPException(403, { + message: 'You do not have permission to delete sharing for this report', + }); + } + // Find users by emails const userMap = await findUsersByEmails(emails); diff --git a/apps/server/src/api/v2/reports/[id]/sharing/GET.ts b/apps/server/src/api/v2/reports/[id]/sharing/GET.ts index 990f997e1..71cb1a22c 100644 --- a/apps/server/src/api/v2/reports/[id]/sharing/GET.ts +++ b/apps/server/src/api/v2/reports/[id]/sharing/GET.ts @@ -1,3 +1,4 @@ +import { checkPermission } from '@buster/access-controls'; import { checkAssetPermission, getReportFileById, @@ -19,10 +20,13 @@ export async function getReportSharingHandler( } // Check if user has permission to view the report - const permissionCheck = await checkAssetPermission({ + const permissionCheck = await checkPermission({ + userId: user.id, assetId: reportId, assetType: 'report_file', - userId: user.id, + requiredRole: 'can_view', + workspaceSharing: report.workspace_sharing, + organizationId: report.organization_id, }); if (!permissionCheck.hasAccess) { diff --git a/apps/server/src/api/v2/reports/[id]/sharing/POST.ts b/apps/server/src/api/v2/reports/[id]/sharing/POST.ts index 30f40aba9..bae2ea451 100644 --- a/apps/server/src/api/v2/reports/[id]/sharing/POST.ts +++ b/apps/server/src/api/v2/reports/[id]/sharing/POST.ts @@ -1,37 +1,44 @@ +import { checkPermission } from '@buster/access-controls'; import { bulkCreateAssetPermissions, findUsersByEmails, getReportFileById, - getReportWorkspaceSharing, } from '@buster/database/queries'; import type { User } from '@buster/database/queries'; -import type { SharePostResponse } from '@buster/server-shared/reports'; +import type { SharePostResponse } from '@buster/server-shared/share'; import type { SharePostRequest } from '@buster/server-shared/share'; import { SharePostRequestSchema } from '@buster/server-shared/share'; import { zValidator } from '@hono/zod-validator'; import { Hono } from 'hono'; import { HTTPException } from 'hono/http-exception'; -import { checkIfAssetIsEditable } from '../../../../../shared-helpers/asset-public-access'; export async function createReportSharingHandler( reportId: string, shareRequests: SharePostRequest, user: User ): Promise { - await checkIfAssetIsEditable({ - user, - assetId: reportId, - assetType: 'report_file', - workspaceSharing: getReportWorkspaceSharing, - requiredRole: 'can_edit', - }); - // Get the report to verify it exists const report = await getReportFileById({ reportId, userId: user.id }); if (!report) { throw new HTTPException(404, { message: 'Report not found' }); } + // Check if user has permission to edit the report + const permissionCheck = await checkPermission({ + userId: user.id, + assetId: reportId, + assetType: 'report_file', + requiredRole: 'can_edit', + workspaceSharing: report.workspace_sharing, + organizationId: report.organization_id, + }); + + if (!permissionCheck.hasAccess) { + throw new HTTPException(403, { + message: 'You do not have permission to edit this report', + }); + } + // Extract emails from the share requests const emails = shareRequests.map((req) => req.email); diff --git a/apps/server/src/api/v2/reports/[id]/sharing/PUT.ts b/apps/server/src/api/v2/reports/[id]/sharing/PUT.ts index e40e082e9..98bc2bc2b 100644 --- a/apps/server/src/api/v2/reports/[id]/sharing/PUT.ts +++ b/apps/server/src/api/v2/reports/[id]/sharing/PUT.ts @@ -1,9 +1,8 @@ +import { checkPermission } from '@buster/access-controls'; import { bulkCreateAssetPermissions, - checkAssetPermission, findUsersByEmails, getReportFileById, - getReportWorkspaceSharing, getUserOrganizationId, updateReport, } from '@buster/database/queries'; @@ -13,7 +12,6 @@ import { type ShareUpdateRequest, ShareUpdateRequestSchema } from '@buster/serve import { zValidator } from '@hono/zod-validator'; import { Hono } from 'hono'; import { HTTPException } from 'hono/http-exception'; -import { checkIfAssetIsEditable } from '../../../../../shared-helpers/asset-public-access'; import { getReportHandler } from '../GET'; export async function updateReportShareHandler( @@ -21,29 +19,27 @@ export async function updateReportShareHandler( request: ShareUpdateRequest, user: User & { organizationId: string } ) { - // Check if user has permission to edit asset permissions - const permissionCheck = await checkAssetPermission({ - assetId: reportId, - assetType: 'report_file', - userId: user.id, - }); - - // Check if user has at least full_access permission - if ( - !permissionCheck.hasAccess || - (permissionCheck.role !== 'full_access' && permissionCheck.role !== 'owner') - ) { - throw new HTTPException(403, { - message: 'User does not have permission to edit asset permissions', - }); - } - // Check if report exists const report = await getReportFileById({ reportId, userId: user.id }); if (!report) { throw new HTTPException(404, { message: 'Report not found' }); } + const permissionCheck = await checkPermission({ + userId: user.id, + assetId: reportId, + assetType: 'report_file', + requiredRole: 'full_access', + workspaceSharing: report.workspace_sharing, + organizationId: report.organization_id, + }); + + if (!permissionCheck.hasAccess) { + throw new HTTPException(403, { + message: 'You do not have permission to update sharing for this report', + }); + } + const { publicly_accessible, public_expiry_date, public_password, workspace_sharing, users } = request; @@ -131,15 +127,6 @@ const app = new Hono().put('/', zValidator('json', ShareUpdateRequestSchema), as throw new HTTPException(403, { message: 'User is not associated with an organization' }); } - await checkIfAssetIsEditable({ - user, - assetId: reportId, - assetType: 'report_file', - workspaceSharing: getReportWorkspaceSharing, - organizationId: userOrg.organizationId, - requiredRole: 'full_access', - }); - const updatedReport: ShareUpdateResponse = await updateReportShareHandler(reportId, request, { ...user, organizationId: userOrg.organizationId, diff --git a/apps/web/src/api/buster_rest/chats/requests.ts b/apps/web/src/api/buster_rest/chats/requests.ts index 7b43cd1c2..c19bfb3cd 100644 --- a/apps/web/src/api/buster_rest/chats/requests.ts +++ b/apps/web/src/api/buster_rest/chats/requests.ts @@ -14,7 +14,9 @@ import type { } from '@buster/server-shared/chats'; import type { ShareDeleteRequest, + ShareDeleteResponse, SharePostRequest, + SharePostResponse, ShareUpdateRequest, } from '@buster/server-shared/share'; import { mainApi, mainApiV2 } from '../instances'; @@ -61,11 +63,15 @@ export const duplicateChat = async ({ }; export const shareChat = async ({ id, params }: { id: string; params: SharePostRequest }) => { - return mainApi.post(`${CHATS_BASE}/${id}/sharing`, params).then((res) => res.data); + return mainApiV2 + .post(`${CHATS_BASE}/${id}/sharing`, params) + .then((res) => res.data); }; export const unshareChat = async ({ id, data }: { id: string; data: ShareDeleteRequest }) => { - return mainApi.delete(`${CHATS_BASE}/${id}/sharing`, { data }).then((res) => res.data); + return mainApiV2 + .delete(`${CHATS_BASE}/${id}/sharing`, { data }) + .then((res) => res.data); }; export const updateChatShare = async ({ @@ -75,7 +81,7 @@ export const updateChatShare = async ({ id: string; params: ShareUpdateRequest; }) => { - return mainApi + return mainApiV2 .put(`${CHATS_BASE}/${id}/sharing`, params) .then((res) => res.data); }; diff --git a/apps/web/src/api/buster_rest/dashboards/requests.ts b/apps/web/src/api/buster_rest/dashboards/requests.ts index c641fefb4..9915ab103 100644 --- a/apps/web/src/api/buster_rest/dashboards/requests.ts +++ b/apps/web/src/api/buster_rest/dashboards/requests.ts @@ -1,7 +1,9 @@ import type { DashboardConfig, GetDashboardResponse } from '@buster/server-shared/dashboards'; import type { ShareDeleteRequest, + ShareDeleteResponse, SharePostRequest, + SharePostResponse, ShareUpdateRequest, } from '@buster/server-shared/share'; import type { BusterDashboardListItem } from '@/api/asset_interfaces/dashboard'; @@ -76,11 +78,15 @@ export const dashboardsDeleteDashboard = async (data: { ids: string[] }) => { // share dashboards export const shareDashboard = async ({ id, params }: { id: string; params: SharePostRequest }) => { - return mainApi.post(`/dashboards/${id}/sharing`, params).then((res) => res.data); + return mainApiV2 + .post(`/dashboards/${id}/sharing`, params) + .then((res) => res.data); }; export const unshareDashboard = async ({ id, data }: { id: string; data: ShareDeleteRequest }) => { - return mainApi.delete(`/dashboards/${id}/sharing`, { data }).then((res) => res.data); + return mainApiV2 + .delete(`/dashboards/${id}/sharing`, { data }) + .then((res) => res.data); }; export const updateDashboardShare = async ({ @@ -90,7 +96,7 @@ export const updateDashboardShare = async ({ id: string; params: ShareUpdateRequest; }) => { - return mainApi + return mainApiV2 .put(`/dashboards/${id}/sharing`, params) .then((res) => res.data); }; diff --git a/apps/web/src/api/buster_rest/metrics/requests.ts b/apps/web/src/api/buster_rest/metrics/requests.ts index 565031ee3..a8544bd26 100644 --- a/apps/web/src/api/buster_rest/metrics/requests.ts +++ b/apps/web/src/api/buster_rest/metrics/requests.ts @@ -15,14 +15,15 @@ import type { MetricDownloadParams, MetricDownloadQueryParams, MetricDownloadResponse, - ShareDeleteResponse, - ShareUpdateResponse, + ShareMetricUpdateResponse, UpdateMetricRequest, UpdateMetricResponse, } from '@buster/server-shared/metrics'; import type { ShareDeleteRequest, + ShareDeleteResponse, SharePostRequest, + SharePostResponse, ShareUpdateRequest, } from '@buster/server-shared/share'; import { mainApi, mainApiV2 } from '../instances'; @@ -80,11 +81,13 @@ export const bulkUpdateMetricVerificationStatus = async ( // share metrics export const shareMetric = async ({ id, params }: { id: string; params: SharePostRequest }) => { - return mainApi.post(`/metric_files/${id}/sharing`, params).then((res) => res.data); + return mainApiV2 + .post(`/metric_files/${id}/sharing`, params) + .then((res) => res.data); }; export const unshareMetric = async ({ id, data }: { id: string; data: ShareDeleteRequest }) => { - return mainApi + return mainApiV2 .delete(`/metric_files/${id}/sharing`, { data }) .then((res) => res.data); }; @@ -96,8 +99,8 @@ export const updateMetricShare = async ({ id: string; params: ShareUpdateRequest; }) => { - return mainApi - .put(`/metric_files/${id}/sharing`, params) + return mainApiV2 + .put(`/metric_files/${id}/sharing`, params) .then((res) => res.data); }; diff --git a/apps/web/src/api/buster_rest/metrics/updateMetricQueryRequests.ts b/apps/web/src/api/buster_rest/metrics/updateMetricQueryRequests.ts index e41b9e312..cc774d5c6 100644 --- a/apps/web/src/api/buster_rest/metrics/updateMetricQueryRequests.ts +++ b/apps/web/src/api/buster_rest/metrics/updateMetricQueryRequests.ts @@ -282,13 +282,6 @@ export const useUnshareMetric = () => { }); }); }, - onSuccess: (data) => { - const upgradedMetric = upgradeMetricToIMetric(data, null); - queryClient.setQueryData( - metricsQueryKeys.metricsGetMetric(data.id, 'LATEST').queryKey, - upgradedMetric - ); - }, }); }; diff --git a/apps/web/src/api/buster_rest/reports/requests.ts b/apps/web/src/api/buster_rest/reports/requests.ts index b28a7e9b8..c8aaa5c24 100644 --- a/apps/web/src/api/buster_rest/reports/requests.ts +++ b/apps/web/src/api/buster_rest/reports/requests.ts @@ -7,7 +7,12 @@ import type { UpdateReportRequest, UpdateReportResponse, } from '@buster/server-shared/reports'; -import type { SharePostRequest, ShareUpdateRequest } from '@buster/server-shared/share'; +import type { + ShareDeleteResponse, + SharePostRequest, + SharePostResponse, + ShareUpdateRequest, +} from '@buster/server-shared/share'; import { mainApiV2 } from '../instances'; /** @@ -42,7 +47,7 @@ export const updateReport = async ({ */ export const shareReport = async ({ id, params }: { id: string; params: SharePostRequest }) => { return mainApiV2 - .post(`/reports/${id}/sharing`, params) + .post(`/reports/${id}/sharing`, params) .then((res) => res.data); }; @@ -51,7 +56,7 @@ export const shareReport = async ({ id, params }: { id: string; params: SharePos */ export const unshareReport = async ({ id, data }: { id: string; data: string[] }) => { return mainApiV2 - .delete(`/reports/${id}/sharing`, { data }) + .delete(`/reports/${id}/sharing`, { data }) .then((res) => res.data); }; diff --git a/packages/ai/src/tools/communication-tools/done-tool/done-tool-delta.ts b/packages/ai/src/tools/communication-tools/done-tool/done-tool-delta.ts index 0f00ed407..1213f4864 100644 --- a/packages/ai/src/tools/communication-tools/done-tool/done-tool-delta.ts +++ b/packages/ai/src/tools/communication-tools/done-tool/done-tool-delta.ts @@ -29,6 +29,9 @@ export function createDoneToolDelta(context: DoneToolContext, doneToolState: Don return async function doneToolDelta( options: { inputTextDelta: string } & ToolCallOptions ): Promise { + if (doneToolState.isFinalizing) { + return; + } // Accumulate the delta to the args doneToolState.args = (doneToolState.args || '') + options.inputTextDelta; @@ -52,32 +55,71 @@ export function createDoneToolDelta(context: DoneToolContext, doneToolState: Don assetId: string; assetName: string; assetType: ResponseMessageFileType; + versionNumber: number; }; - function isAssetToReturn(value: unknown): value is AssetToReturn { - if (!value || typeof value !== 'object') return false; - const obj = value as Record; - const idOk = typeof obj.assetId === 'string'; - const nameOk = typeof obj.assetName === 'string'; - const typeVal = obj.assetType; - const typeOk = - typeof typeVal === 'string' && - ResponseMessageFileTypeSchema.options.includes(typeVal as ResponseMessageFileType); - return idOk && nameOk && typeOk; - } - - let assetsToInsert: AssetToReturn[] = []; - if (Array.isArray(rawAssets)) { - assetsToInsert = rawAssets.filter(isAssetToReturn); - } else if (typeof rawAssets === 'string') { - try { - const parsed: unknown = JSON.parse(rawAssets); - if (Array.isArray(parsed)) { - assetsToInsert = parsed.filter(isAssetToReturn); - } - } catch { - // ignore malformed JSON until more delta arrives + const rawAssetItems: unknown[] = (() => { + if (Array.isArray(rawAssets)) { + return rawAssets; } + if (typeof rawAssets === 'string') { + try { + const parsed: unknown = JSON.parse(rawAssets); + if (Array.isArray(parsed)) { + return parsed; + } + } catch { + // ignore malformed JSON until more delta arrives + } + } + return []; + })(); + + const assetsToInsert: AssetToReturn[] = []; + for (const candidate of rawAssetItems) { + if (!candidate || typeof candidate !== 'object') { + continue; + } + + const data = candidate as Record; + const assetId = typeof data.assetId === 'string' ? data.assetId : undefined; + const assetName = typeof data.assetName === 'string' ? data.assetName : undefined; + const rawType = data.assetType; + const normalizedType = + typeof rawType === 'string' && + ResponseMessageFileTypeSchema.options.includes(rawType as ResponseMessageFileType) + ? (rawType as ResponseMessageFileType) + : undefined; + + if (!assetId || !assetName || !normalizedType) { + continue; + } + + let versionNumber: number | undefined; + if (typeof data.versionNumber === 'number') { + versionNumber = data.versionNumber; + } else if (typeof (data as { version_number?: unknown }).version_number === 'number') { + versionNumber = (data as { version_number: number }).version_number; + } + + if (versionNumber === undefined || Number.isNaN(versionNumber) || versionNumber <= 0) { + try { + versionNumber = await getAssetLatestVersion({ + assetId, + assetType: normalizedType, + }); + } catch (error) { + console.error('[done-tool] Failed to fetch asset version, defaulting to 1:', error); + versionNumber = 1; + } + } + + assetsToInsert.push({ + assetId, + assetName, + assetType: normalizedType, + versionNumber, + }); } // Insert any newly completed asset items as response messages (dedupe via state) @@ -95,7 +137,7 @@ export function createDoneToolDelta(context: DoneToolContext, doneToolState: Don type: 'file' as const, file_type: a.assetType, file_name: a.assetName, - version_number: 1, + version_number: a.versionNumber, filter_version_id: null, metadata: [ { @@ -128,7 +170,11 @@ export function createDoneToolDelta(context: DoneToolContext, doneToolState: Don if (newAssets.length > 0) { doneToolState.addedAssets = [ ...(doneToolState.addedAssets || []), - ...newAssets.map((a) => ({ assetId: a.assetId, assetType: a.assetType })), + ...newAssets.map((a) => ({ + assetId: a.assetId, + assetType: a.assetType, + versionNumber: a.versionNumber, + })), ]; } } @@ -159,16 +205,10 @@ export function createDoneToolDelta(context: DoneToolContext, doneToolState: Don const firstAsset = doneToolState.addedAssets[0]; if (firstAsset) { - // Get the actual version number from the database - const versionNumber = await getAssetLatestVersion({ - assetId: firstAsset.assetId, - assetType: firstAsset.assetType, - }); - await updateChat(context.chatId, { mostRecentFileId: firstAsset.assetId, mostRecentFileType: firstAsset.assetType, - mostRecentVersionNumber: versionNumber, + mostRecentVersionNumber: firstAsset.versionNumber, }); } } catch (error) { diff --git a/packages/ai/src/tools/communication-tools/done-tool/done-tool-execute.ts b/packages/ai/src/tools/communication-tools/done-tool/done-tool-execute.ts index 009151051..6a86fc382 100644 --- a/packages/ai/src/tools/communication-tools/done-tool/done-tool-execute.ts +++ b/packages/ai/src/tools/communication-tools/done-tool/done-tool-execute.ts @@ -75,6 +75,7 @@ export function createDoneToolExecute(context: DoneToolContext, state: DoneToolS throw new Error('Tool call ID is required'); } + state.isFinalizing = true; // CRITICAL: Wait for ALL pending updates from delta/finish to complete FIRST // This ensures execute's update is always the last one in the queue await waitForPendingUpdates(context.messageId); diff --git a/packages/ai/src/tools/communication-tools/done-tool/done-tool-start.ts b/packages/ai/src/tools/communication-tools/done-tool/done-tool-start.ts index 9b248dedf..7f78c978c 100644 --- a/packages/ai/src/tools/communication-tools/done-tool/done-tool-start.ts +++ b/packages/ai/src/tools/communication-tools/done-tool/done-tool-start.ts @@ -24,6 +24,7 @@ export function createDoneToolStart(context: DoneToolContext, doneToolState: Don doneToolState.finalResponse = undefined; doneToolState.addedAssetIds = []; doneToolState.addedAssets = []; + doneToolState.isFinalizing = false; // Selection logic moved to delta; skip extracting files here if (options.messages) { diff --git a/packages/ai/src/tools/communication-tools/done-tool/done-tool-streaming.test.ts b/packages/ai/src/tools/communication-tools/done-tool/done-tool-streaming.test.ts index 0503441ef..0f4adf977 100644 --- a/packages/ai/src/tools/communication-tools/done-tool/done-tool-streaming.test.ts +++ b/packages/ai/src/tools/communication-tools/done-tool/done-tool-streaming.test.ts @@ -603,6 +603,29 @@ describe('Done Tool Streaming Tests', () => { expect(state.args).toBe('{"finalResponse": ""}'); expect(state.finalResponse).toBeUndefined(); }); + + test('should ignore deltas after execute begins', async () => { + vi.clearAllMocks(); + const state: DoneToolState = { + toolCallId: 'test-entry', + args: '', + finalResponse: 'Complete response', + isFinalizing: true, + }; + + const deltaHandler = createDoneToolDelta(mockContext, state); + + await deltaHandler({ + inputTextDelta: '{"finalResponse": "Stale"}', + toolCallId: 'tool-call-123', + messages: [], + }); + + const queries = await import('@buster/database/queries'); + expect(queries.updateMessageEntries).not.toHaveBeenCalled(); + expect(state.args).toBe(''); + expect(state.finalResponse).toBe('Complete response'); + }); }); describe('createDoneToolFinish', () => { diff --git a/packages/ai/src/tools/communication-tools/done-tool/done-tool.ts b/packages/ai/src/tools/communication-tools/done-tool/done-tool.ts index 3cbb2263d..44532b15d 100644 --- a/packages/ai/src/tools/communication-tools/done-tool/done-tool.ts +++ b/packages/ai/src/tools/communication-tools/done-tool/done-tool.ts @@ -15,6 +15,11 @@ export const DoneToolInputSchema = z.object({ assetId: z.string().uuid(), assetName: z.string(), assetType: AssetTypeSchema, + versionNumber: z + .number() + .int() + .positive() + .describe('The version number of the asset to return'), }) ) .describe( @@ -60,17 +65,16 @@ const DoneToolStateSchema = z.object({ .array( z.object({ assetId: z.string(), - assetType: z.enum([ - 'metric_file', - 'dashboard_file', - 'report_file', - 'analyst_chat', - 'collection', - ]), + assetType: AssetTypeSchema, + versionNumber: z.number(), }) ) .optional() - .describe('Assets that have been added with their types for chat update'), + .describe('Assets that have been added with their types and version numbers for chat update'), + isFinalizing: z + .boolean() + .optional() + .describe('Indicates the execute phase has started so further deltas should be ignored'), }); export type DoneToolInput = z.infer; @@ -85,6 +89,7 @@ export function createDoneTool(context: DoneToolContext) { finalResponse: undefined, addedAssetIds: [], addedAssets: [], + isFinalizing: false, }; const execute = createDoneToolExecute(context, state); diff --git a/packages/ai/src/utils/tool-call-repair/strategies/re-ask-strategy.ts b/packages/ai/src/utils/tool-call-repair/strategies/re-ask-strategy.ts index 62113c9e5..5ed29662d 100644 --- a/packages/ai/src/utils/tool-call-repair/strategies/re-ask-strategy.ts +++ b/packages/ai/src/utils/tool-call-repair/strategies/re-ask-strategy.ts @@ -2,8 +2,8 @@ import type { LanguageModelV2ToolCall } from '@ai-sdk/provider'; import { type ModelMessage, NoSuchToolError, generateText, streamText } from 'ai'; import { wrapTraced } from 'braintrust'; import { ANALYST_AGENT_NAME, DOCS_AGENT_NAME, THINK_AND_PREP_AGENT_NAME } from '../../../agents'; -import { Sonnet4 } from '../../../llm'; -import { DEFAULT_ANTHROPIC_OPTIONS } from '../../../llm/providers/gateway'; +import { GPT5Mini, Sonnet4 } from '../../../llm'; +import { DEFAULT_ANTHROPIC_OPTIONS, DEFAULT_OPENAI_OPTIONS } from '../../../llm/providers/gateway'; import type { RepairContext } from '../types'; export function canHandleNoSuchTool(error: Error): boolean { @@ -58,11 +58,11 @@ export async function repairWrongToolName( try { const result = streamText({ - model: Sonnet4, - providerOptions: DEFAULT_ANTHROPIC_OPTIONS, + model: GPT5Mini, + providerOptions: DEFAULT_OPENAI_OPTIONS, messages: healingMessages, tools: context.tools, - maxOutputTokens: 1000, + maxOutputTokens: 10000, temperature: 0, }); diff --git a/packages/ai/src/utils/tool-call-repair/strategies/structured-output-strategy.ts b/packages/ai/src/utils/tool-call-repair/strategies/structured-output-strategy.ts index 746c83a06..aab09334c 100644 --- a/packages/ai/src/utils/tool-call-repair/strategies/structured-output-strategy.ts +++ b/packages/ai/src/utils/tool-call-repair/strategies/structured-output-strategy.ts @@ -1,8 +1,8 @@ import type { LanguageModelV2ToolCall } from '@ai-sdk/provider'; import { InvalidToolInputError, generateObject } from 'ai'; import { wrapTraced } from 'braintrust'; -import { Sonnet4 } from '../../../llm'; -import { DEFAULT_ANTHROPIC_OPTIONS } from '../../../llm/providers/gateway'; +import { GPT5Mini, Sonnet4 } from '../../../llm'; +import { DEFAULT_ANTHROPIC_OPTIONS, DEFAULT_OPENAI_OPTIONS } from '../../../llm/providers/gateway'; import type { RepairContext } from '../types'; export function canHandleInvalidInput(error: Error): boolean { @@ -41,9 +41,10 @@ export async function repairInvalidInput( try { const { object: repairedInput } = await generateObject({ - model: Sonnet4, - providerOptions: DEFAULT_ANTHROPIC_OPTIONS, + model: GPT5Mini, + providerOptions: DEFAULT_OPENAI_OPTIONS, schema: tool.inputSchema, + maxOutputTokens: 10000, prompt: `Fix these tool arguments to match the schema:\n${JSON.stringify(currentInput, null, 2)}`, mode: 'json', }); diff --git a/packages/database/drizzle/0112_shortcuts_trigger_backfill.sql b/packages/database/drizzle/0112_shortcuts_trigger_backfill.sql new file mode 100644 index 000000000..cc6455908 --- /dev/null +++ b/packages/database/drizzle/0112_shortcuts_trigger_backfill.sql @@ -0,0 +1,148 @@ +-- Create Buster system user if it doesn't exist +DO $$ +DECLARE + buster_user_id uuid; +BEGIN + -- Check if Buster user already exists + SELECT id INTO buster_user_id + FROM users + WHERE email = 'support@buster.so'; + + -- If not exists, create the user + IF buster_user_id IS NULL THEN + INSERT INTO users ( + email, + name, + created_at, + updated_at + ) VALUES ( + 'support@buster.so', + 'Buster', + now(), + now() + ) + RETURNING id INTO buster_user_id; + END IF; +END $$; + +--> statement-breakpoint + +-- Function to add default shortcuts for an organization +CREATE OR REPLACE FUNCTION add_default_shortcuts_for_org(org_id uuid) +RETURNS void AS $$ +DECLARE + buster_user_id uuid; +BEGIN + -- Get the Buster user ID + SELECT id INTO buster_user_id + FROM users + WHERE email = 'support@buster.so'; + + -- Insert default shortcuts if they don't exist + -- quick shortcut + INSERT INTO shortcuts (name, instructions, created_by, organization_id, share_with_workspace, created_at, updated_at) + VALUES ( + 'quick', + 'Quickly answer my request as fast as possible. Use as little prep, thoughts, validation as possible. Again, this should be fulfilled as quickly as possible: ', + buster_user_id, + org_id, + true, + now(), + now() + ) + ON CONFLICT (name, organization_id) WHERE share_with_workspace = true + DO NOTHING; + + -- deep-dive shortcut + INSERT INTO shortcuts (name, instructions, created_by, organization_id, share_with_workspace, created_at, updated_at) + VALUES ( + 'deep-dive', + 'Do a deep dive and build me a thorough report. Find meaningful insights and thoroughly explore. If I have a specific topic in mind, I''ll include it here: ', + buster_user_id, + org_id, + true, + now(), + now() + ) + ON CONFLICT (name, organization_id) WHERE share_with_workspace = true + DO NOTHING; + + -- csv shortcut + INSERT INTO shortcuts (name, instructions, created_by, organization_id, share_with_workspace, created_at, updated_at) + VALUES ( + 'csv', + 'Return a table/list that I can export as a CSV. Here is my request: ', + buster_user_id, + org_id, + true, + now(), + now() + ) + ON CONFLICT (name, organization_id) WHERE share_with_workspace = true + DO NOTHING; + + -- suggestions shortcut + INSERT INTO shortcuts (name, instructions, created_by, organization_id, share_with_workspace, created_at, updated_at) + VALUES ( + 'suggestions', + 'What specific questions I can ask that may be of value? The more specific and high-impact the better. If I have a specific topic in mind, I''ll include it here: ', + buster_user_id, + org_id, + true, + now(), + now() + ) + ON CONFLICT (name, organization_id) WHERE share_with_workspace = true + DO NOTHING; + + -- dashboard shortcut + INSERT INTO shortcuts (name, instructions, created_by, organization_id, share_with_workspace, created_at, updated_at) + VALUES ( + 'dashboard', + 'Build me a dashboard. If I have a specific topic in mind, I''ll include it here: ', + buster_user_id, + org_id, + true, + now(), + now() + ) + ON CONFLICT (name, organization_id) WHERE share_with_workspace = true + DO NOTHING; +END; +$$ LANGUAGE plpgsql; + +--> statement-breakpoint + +-- Backfill existing organizations with default shortcuts +DO $$ +DECLARE + org_record RECORD; +BEGIN + FOR org_record IN + SELECT id + FROM organizations + WHERE deleted_at IS NULL + LOOP + PERFORM add_default_shortcuts_for_org(org_record.id); + END LOOP; +END $$; + +--> statement-breakpoint + +-- Create trigger function for new organizations +CREATE OR REPLACE FUNCTION add_default_shortcuts_on_org_create() +RETURNS TRIGGER AS $$ +BEGIN + PERFORM add_default_shortcuts_for_org(NEW.id); + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +--> statement-breakpoint + +-- Create trigger on organization insert +DROP TRIGGER IF EXISTS add_default_shortcuts_trigger ON organizations; +CREATE TRIGGER add_default_shortcuts_trigger +AFTER INSERT ON organizations +FOR EACH ROW +EXECUTE FUNCTION add_default_shortcuts_on_org_create(); \ No newline at end of file diff --git a/packages/database/drizzle/meta/0112_snapshot.json b/packages/database/drizzle/meta/0112_snapshot.json new file mode 100644 index 000000000..04d173e9a --- /dev/null +++ b/packages/database/drizzle/meta/0112_snapshot.json @@ -0,0 +1,5943 @@ +{ + "id": "e92f38f0-d150-427e-834f-5a9180da1c64", + "prevId": "e99e0196-f7e5-4e83-ad36-ddf350e50805", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.api_keys": { + "name": "api_keys", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "owner_id": { + "name": "owner_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "api_keys_organization_id_fkey": { + "name": "api_keys_organization_id_fkey", + "tableFrom": "api_keys", + "tableTo": "organizations", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "api_keys_owner_id_fkey": { + "name": "api_keys_owner_id_fkey", + "tableFrom": "api_keys", + "tableTo": "users", + "columnsFrom": [ + "owner_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "api_keys_key_key": { + "name": "api_keys_key_key", + "nullsNotDistinct": false, + "columns": [ + "key" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.asset_permissions": { + "name": "asset_permissions", + "schema": "", + "columns": { + "identity_id": { + "name": "identity_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "identity_type": { + "name": "identity_type", + "type": "identity_type_enum", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "asset_id": { + "name": "asset_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "asset_type": { + "name": "asset_type", + "type": "asset_type_enum", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "role": { + "name": "role", + "type": "asset_permission_role_enum", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "updated_by": { + "name": "updated_by", + "type": "uuid", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "asset_permissions_created_by_fkey": { + "name": "asset_permissions_created_by_fkey", + "tableFrom": "asset_permissions", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "cascade" + }, + "asset_permissions_updated_by_fkey": { + "name": "asset_permissions_updated_by_fkey", + "tableFrom": "asset_permissions", + "tableTo": "users", + "columnsFrom": [ + "updated_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "cascade" + } + }, + "compositePrimaryKeys": { + "asset_permissions_pkey": { + "name": "asset_permissions_pkey", + "columns": [ + "identity_id", + "identity_type", + "asset_id", + "asset_type" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.asset_search": { + "name": "asset_search", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "asset_id": { + "name": "asset_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "asset_type": { + "name": "asset_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "asset_search_asset_id_asset_type_idx": { + "name": "asset_search_asset_id_asset_type_idx", + "columns": [ + { + "expression": "asset_id", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "text_ops" + }, + { + "expression": "asset_type", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "text_ops" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "pgroonga_content_index": { + "name": "pgroonga_content_index", + "columns": [ + { + "expression": "content", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "pgroonga_text_full_text_search_ops_v2" + } + ], + "isUnique": false, + "concurrently": false, + "method": "pgroonga", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.asset_search_v2": { + "name": "asset_search_v2", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "asset_type": { + "name": "asset_type", + "type": "asset_type_enum", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "asset_id": { + "name": "asset_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "additional_text": { + "name": "additional_text", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "pgroonga_search_title_description_index": { + "name": "pgroonga_search_title_description_index", + "columns": [ + { + "expression": "title", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "pgroonga_text_full_text_search_ops_v2" + }, + { + "expression": "additional_text", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "pgroonga_text_full_text_search_ops_v2" + } + ], + "isUnique": false, + "concurrently": false, + "method": "pgroonga", + "with": {} + } + }, + "foreignKeys": { + "asset_search_v2_organization_id_fkey": { + "name": "asset_search_v2_organization_id_fkey", + "tableFrom": "asset_search_v2", + "tableTo": "organizations", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "asset_search_v2_asset_type_asset_id_unique": { + "name": "asset_search_v2_asset_type_asset_id_unique", + "nullsNotDistinct": false, + "columns": [ + "asset_id", + "asset_type" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.chats": { + "name": "chats", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "updated_by": { + "name": "updated_by", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "publicly_accessible": { + "name": "publicly_accessible", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "publicly_enabled_by": { + "name": "publicly_enabled_by", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "public_expiry_date": { + "name": "public_expiry_date", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "public_password": { + "name": "public_password", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "most_recent_file_id": { + "name": "most_recent_file_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "most_recent_file_type": { + "name": "most_recent_file_type", + "type": "asset_type_enum", + "typeSchema": "public", + "primaryKey": false, + "notNull": false + }, + "most_recent_version_number": { + "name": "most_recent_version_number", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "slack_chat_authorization": { + "name": "slack_chat_authorization", + "type": "slack_chat_authorization_enum", + "typeSchema": "public", + "primaryKey": false, + "notNull": false + }, + "slack_thread_ts": { + "name": "slack_thread_ts", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "slack_channel_id": { + "name": "slack_channel_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "workspace_sharing": { + "name": "workspace_sharing", + "type": "workspace_sharing_enum", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'none'" + }, + "workspace_sharing_enabled_by": { + "name": "workspace_sharing_enabled_by", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "workspace_sharing_enabled_at": { + "name": "workspace_sharing_enabled_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "chats_created_at_idx": { + "name": "chats_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "timestamptz_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "chats_created_by_idx": { + "name": "chats_created_by_idx", + "columns": [ + { + "expression": "created_by", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "uuid_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "chats_organization_id_idx": { + "name": "chats_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "uuid_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_chats_most_recent_file_id": { + "name": "idx_chats_most_recent_file_id", + "columns": [ + { + "expression": "most_recent_file_id", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "uuid_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_chats_most_recent_file_type": { + "name": "idx_chats_most_recent_file_type", + "columns": [ + { + "expression": "most_recent_file_type", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "text_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "chats_organization_id_fkey": { + "name": "chats_organization_id_fkey", + "tableFrom": "chats", + "tableTo": "organizations", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "chats_created_by_fkey": { + "name": "chats_created_by_fkey", + "tableFrom": "chats", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "cascade" + }, + "chats_updated_by_fkey": { + "name": "chats_updated_by_fkey", + "tableFrom": "chats", + "tableTo": "users", + "columnsFrom": [ + "updated_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "cascade" + }, + "chats_publicly_enabled_by_fkey": { + "name": "chats_publicly_enabled_by_fkey", + "tableFrom": "chats", + "tableTo": "users", + "columnsFrom": [ + "publicly_enabled_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "cascade" + }, + "chats_workspace_sharing_enabled_by_fkey": { + "name": "chats_workspace_sharing_enabled_by_fkey", + "tableFrom": "chats", + "tableTo": "users", + "columnsFrom": [ + "workspace_sharing_enabled_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.collections": { + "name": "collections", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "updated_by": { + "name": "updated_by", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "workspace_sharing": { + "name": "workspace_sharing", + "type": "workspace_sharing_enum", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'none'" + }, + "workspace_sharing_enabled_by": { + "name": "workspace_sharing_enabled_by", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "workspace_sharing_enabled_at": { + "name": "workspace_sharing_enabled_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "collections_organization_id_fkey": { + "name": "collections_organization_id_fkey", + "tableFrom": "collections", + "tableTo": "organizations", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "cascade" + }, + "collections_created_by_fkey": { + "name": "collections_created_by_fkey", + "tableFrom": "collections", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "cascade" + }, + "collections_updated_by_fkey": { + "name": "collections_updated_by_fkey", + "tableFrom": "collections", + "tableTo": "users", + "columnsFrom": [ + "updated_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "cascade" + }, + "collections_workspace_sharing_enabled_by_fkey": { + "name": "collections_workspace_sharing_enabled_by_fkey", + "tableFrom": "collections", + "tableTo": "users", + "columnsFrom": [ + "workspace_sharing_enabled_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.collections_to_assets": { + "name": "collections_to_assets", + "schema": "", + "columns": { + "collection_id": { + "name": "collection_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "asset_id": { + "name": "asset_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "asset_type": { + "name": "asset_type", + "type": "asset_type_enum", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "updated_by": { + "name": "updated_by", + "type": "uuid", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "collections_to_assets_created_by_fkey": { + "name": "collections_to_assets_created_by_fkey", + "tableFrom": "collections_to_assets", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "cascade" + }, + "collections_to_assets_updated_by_fkey": { + "name": "collections_to_assets_updated_by_fkey", + "tableFrom": "collections_to_assets", + "tableTo": "users", + "columnsFrom": [ + "updated_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "cascade" + } + }, + "compositePrimaryKeys": { + "collections_to_assets_pkey": { + "name": "collections_to_assets_pkey", + "columns": [ + "collection_id", + "asset_id", + "asset_type" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.dashboard_files": { + "name": "dashboard_files", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "name": { + "name": "name", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "file_name": { + "name": "file_name", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "content": { + "name": "content", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "filter": { + "name": "filter", + "type": "varchar", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "CURRENT_TIMESTAMP" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "CURRENT_TIMESTAMP" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "publicly_accessible": { + "name": "publicly_accessible", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "publicly_enabled_by": { + "name": "publicly_enabled_by", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "public_expiry_date": { + "name": "public_expiry_date", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "version_history": { + "name": "version_history", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "public_password": { + "name": "public_password", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "workspace_sharing": { + "name": "workspace_sharing", + "type": "workspace_sharing_enum", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'none'" + }, + "workspace_sharing_enabled_by": { + "name": "workspace_sharing_enabled_by", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "workspace_sharing_enabled_at": { + "name": "workspace_sharing_enabled_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "dashboard_files_created_by_idx": { + "name": "dashboard_files_created_by_idx", + "columns": [ + { + "expression": "created_by", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "uuid_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "dashboard_files_deleted_at_idx": { + "name": "dashboard_files_deleted_at_idx", + "columns": [ + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "timestamptz_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "dashboard_files_organization_id_idx": { + "name": "dashboard_files_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "uuid_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "dashboard_files_created_by_fkey": { + "name": "dashboard_files_created_by_fkey", + "tableFrom": "dashboard_files", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "cascade" + }, + "dashboard_files_publicly_enabled_by_fkey": { + "name": "dashboard_files_publicly_enabled_by_fkey", + "tableFrom": "dashboard_files", + "tableTo": "users", + "columnsFrom": [ + "publicly_enabled_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "cascade" + }, + "dashboard_files_workspace_sharing_enabled_by_fkey": { + "name": "dashboard_files_workspace_sharing_enabled_by_fkey", + "tableFrom": "dashboard_files", + "tableTo": "users", + "columnsFrom": [ + "workspace_sharing_enabled_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.data_sources": { + "name": "data_sources", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "secret_id": { + "name": "secret_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "onboarding_status": { + "name": "onboarding_status", + "type": "data_source_onboarding_status_enum", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'notStarted'" + }, + "onboarding_error": { + "name": "onboarding_error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "updated_by": { + "name": "updated_by", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "env": { + "name": "env", + "type": "varchar", + "primaryKey": false, + "notNull": true, + "default": "'dev'" + } + }, + "indexes": {}, + "foreignKeys": { + "data_sources_organization_id_fkey": { + "name": "data_sources_organization_id_fkey", + "tableFrom": "data_sources", + "tableTo": "organizations", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "data_sources_created_by_fkey": { + "name": "data_sources_created_by_fkey", + "tableFrom": "data_sources", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "cascade" + }, + "data_sources_updated_by_fkey": { + "name": "data_sources_updated_by_fkey", + "tableFrom": "data_sources", + "tableTo": "users", + "columnsFrom": [ + "updated_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "data_sources_name_organization_id_env_key": { + "name": "data_sources_name_organization_id_env_key", + "nullsNotDistinct": false, + "columns": [ + "name", + "organization_id", + "env" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.dataset_groups": { + "name": "dataset_groups", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "dataset_groups_deleted_at_idx": { + "name": "dataset_groups_deleted_at_idx", + "columns": [ + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "timestamptz_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "dataset_groups_organization_id_idx": { + "name": "dataset_groups_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "uuid_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "dataset_groups_organization_id_fkey": { + "name": "dataset_groups_organization_id_fkey", + "tableFrom": "dataset_groups", + "tableTo": "organizations", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": { + "dataset_groups_policy": { + "name": "dataset_groups_policy", + "as": "PERMISSIVE", + "for": "ALL", + "to": [ + "authenticated" + ], + "using": "true" + } + }, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.dataset_groups_permissions": { + "name": "dataset_groups_permissions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "dataset_group_id": { + "name": "dataset_group_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "permission_id": { + "name": "permission_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "permission_type": { + "name": "permission_type", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "dataset_groups_permissions_dataset_group_id_idx": { + "name": "dataset_groups_permissions_dataset_group_id_idx", + "columns": [ + { + "expression": "dataset_group_id", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "uuid_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "dataset_groups_permissions_organization_id_idx": { + "name": "dataset_groups_permissions_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "uuid_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "dataset_groups_permissions_permission_id_idx": { + "name": "dataset_groups_permissions_permission_id_idx", + "columns": [ + { + "expression": "permission_id", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "uuid_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "dataset_groups_permissions_dataset_group_id_fkey": { + "name": "dataset_groups_permissions_dataset_group_id_fkey", + "tableFrom": "dataset_groups_permissions", + "tableTo": "dataset_groups", + "columnsFrom": [ + "dataset_group_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "dataset_groups_permissions_organization_id_fkey": { + "name": "dataset_groups_permissions_organization_id_fkey", + "tableFrom": "dataset_groups_permissions", + "tableTo": "organizations", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "unique_dataset_group_permission": { + "name": "unique_dataset_group_permission", + "nullsNotDistinct": false, + "columns": [ + "dataset_group_id", + "permission_id", + "permission_type" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.dataset_permissions": { + "name": "dataset_permissions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "dataset_id": { + "name": "dataset_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "permission_id": { + "name": "permission_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "permission_type": { + "name": "permission_type", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "dataset_permissions_dataset_id_idx": { + "name": "dataset_permissions_dataset_id_idx", + "columns": [ + { + "expression": "dataset_id", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "uuid_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "dataset_permissions_deleted_at_idx": { + "name": "dataset_permissions_deleted_at_idx", + "columns": [ + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "timestamptz_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "dataset_permissions_organization_id_idx": { + "name": "dataset_permissions_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "uuid_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "dataset_permissions_permission_lookup_idx": { + "name": "dataset_permissions_permission_lookup_idx", + "columns": [ + { + "expression": "permission_id", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "uuid_ops" + }, + { + "expression": "permission_type", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "text_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "dataset_permissions_organization_id_fkey": { + "name": "dataset_permissions_organization_id_fkey", + "tableFrom": "dataset_permissions", + "tableTo": "organizations", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "dataset_permissions_dataset_id_fkey": { + "name": "dataset_permissions_dataset_id_fkey", + "tableFrom": "dataset_permissions", + "tableTo": "datasets", + "columnsFrom": [ + "dataset_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "dataset_permissions_dataset_id_permission_id_permission_typ_key": { + "name": "dataset_permissions_dataset_id_permission_id_permission_typ_key", + "nullsNotDistinct": false, + "columns": [ + "dataset_id", + "permission_id", + "permission_type" + ] + } + }, + "policies": { + "dataset_permissions_policy": { + "name": "dataset_permissions_policy", + "as": "PERMISSIVE", + "for": "ALL", + "to": [ + "authenticated" + ], + "using": "true" + } + }, + "checkConstraints": { + "dataset_permissions_permission_type_check": { + "name": "dataset_permissions_permission_type_check", + "value": "(permission_type)::text = ANY ((ARRAY['user'::character varying, 'dataset_group'::character varying, 'permission_group'::character varying])::text[])" + } + }, + "isRLSEnabled": false + }, + "public.datasets": { + "name": "datasets", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "database_name": { + "name": "database_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "when_to_use": { + "name": "when_to_use", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "when_not_to_use": { + "name": "when_not_to_use", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "type": { + "name": "type", + "type": "dataset_type_enum", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "definition": { + "name": "definition", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "schema": { + "name": "schema", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "imported": { + "name": "imported", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "data_source_id": { + "name": "data_source_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "updated_by": { + "name": "updated_by", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "yml_file": { + "name": "yml_file", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "database_identifier": { + "name": "database_identifier", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "datasets_data_source_id_fkey": { + "name": "datasets_data_source_id_fkey", + "tableFrom": "datasets", + "tableTo": "data_sources", + "columnsFrom": [ + "data_source_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "datasets_organization_id_fkey": { + "name": "datasets_organization_id_fkey", + "tableFrom": "datasets", + "tableTo": "organizations", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "datasets_created_by_fkey": { + "name": "datasets_created_by_fkey", + "tableFrom": "datasets", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "cascade" + }, + "datasets_updated_by_fkey": { + "name": "datasets_updated_by_fkey", + "tableFrom": "datasets", + "tableTo": "users", + "columnsFrom": [ + "updated_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "datasets_name_schema_database_identifier_data_source_id_key": { + "name": "datasets_name_schema_database_identifier_data_source_id_key", + "nullsNotDistinct": false, + "columns": [ + "name", + "schema", + "database_identifier", + "data_source_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.datasets_to_dataset_groups": { + "name": "datasets_to_dataset_groups", + "schema": "", + "columns": { + "dataset_id": { + "name": "dataset_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "dataset_group_id": { + "name": "dataset_group_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "datasets_to_dataset_groups_dataset_group_id_idx": { + "name": "datasets_to_dataset_groups_dataset_group_id_idx", + "columns": [ + { + "expression": "dataset_group_id", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "uuid_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "datasets_to_dataset_groups_dataset_id_fkey": { + "name": "datasets_to_dataset_groups_dataset_id_fkey", + "tableFrom": "datasets_to_dataset_groups", + "tableTo": "datasets", + "columnsFrom": [ + "dataset_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "datasets_to_dataset_groups_dataset_group_id_fkey": { + "name": "datasets_to_dataset_groups_dataset_group_id_fkey", + "tableFrom": "datasets_to_dataset_groups", + "tableTo": "dataset_groups", + "columnsFrom": [ + "dataset_group_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "datasets_to_dataset_groups_pkey": { + "name": "datasets_to_dataset_groups_pkey", + "columns": [ + "dataset_id", + "dataset_group_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": { + "datasets_to_dataset_groups_policy": { + "name": "datasets_to_dataset_groups_policy", + "as": "PERMISSIVE", + "for": "ALL", + "to": [ + "authenticated" + ], + "using": "true" + } + }, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.datasets_to_permission_groups": { + "name": "datasets_to_permission_groups", + "schema": "", + "columns": { + "dataset_id": { + "name": "dataset_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "permission_group_id": { + "name": "permission_group_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "datasets_to_permission_groups_dataset_id_fkey": { + "name": "datasets_to_permission_groups_dataset_id_fkey", + "tableFrom": "datasets_to_permission_groups", + "tableTo": "datasets", + "columnsFrom": [ + "dataset_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "datasets_to_permission_groups_permission_group_id_fkey": { + "name": "datasets_to_permission_groups_permission_group_id_fkey", + "tableFrom": "datasets_to_permission_groups", + "tableTo": "permission_groups", + "columnsFrom": [ + "permission_group_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "datasets_to_permission_groups_pkey": { + "name": "datasets_to_permission_groups_pkey", + "columns": [ + "dataset_id", + "permission_group_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": { + "datasets_to_permission_groups_policy": { + "name": "datasets_to_permission_groups_policy", + "as": "PERMISSIVE", + "for": "ALL", + "to": [ + "authenticated" + ], + "using": "true" + } + }, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.docs": { + "name": "docs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "name": { + "name": "name", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "type": { + "name": "type", + "type": "docs_type_enum", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'normal'" + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "docs_organization_id_fkey": { + "name": "docs_organization_id_fkey", + "tableFrom": "docs", + "tableTo": "organizations", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "docs_name_organization_id_key": { + "name": "docs_name_organization_id_key", + "nullsNotDistinct": false, + "columns": [ + "name", + "organization_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.github_integrations": { + "name": "github_integrations", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "installation_id": { + "name": "installation_id", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true + }, + "app_id": { + "name": "app_id", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false + }, + "github_org_id": { + "name": "github_org_id", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true + }, + "github_org_name": { + "name": "github_org_name", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false + }, + "token_vault_key": { + "name": "token_vault_key", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false + }, + "webhook_secret_vault_key": { + "name": "webhook_secret_vault_key", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false + }, + "repository_permissions": { + "name": "repository_permissions", + "type": "jsonb", + "primaryKey": false, + "notNull": false, + "default": "'{}'::jsonb" + }, + "status": { + "name": "status", + "type": "github_integration_status_enum", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "installed_at": { + "name": "installed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "last_used_at": { + "name": "last_used_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "idx_github_integrations_org_id": { + "name": "idx_github_integrations_org_id", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "uuid_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_github_integrations_installation_id": { + "name": "idx_github_integrations_installation_id", + "columns": [ + { + "expression": "installation_id", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "text_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_github_integrations_github_org_id": { + "name": "idx_github_integrations_github_org_id", + "columns": [ + { + "expression": "github_org_id", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "text_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "github_integrations_organization_id_fkey": { + "name": "github_integrations_organization_id_fkey", + "tableFrom": "github_integrations", + "tableTo": "organizations", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "github_integrations_user_id_fkey": { + "name": "github_integrations_user_id_fkey", + "tableFrom": "github_integrations", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "github_integrations_token_vault_key_unique": { + "name": "github_integrations_token_vault_key_unique", + "nullsNotDistinct": false, + "columns": [ + "token_vault_key" + ] + }, + "github_integrations_org_installation_key": { + "name": "github_integrations_org_installation_key", + "nullsNotDistinct": false, + "columns": [ + "organization_id", + "installation_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.logs_write_back_configs": { + "name": "logs_write_back_configs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "data_source_id": { + "name": "data_source_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "database": { + "name": "database", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true + }, + "schema": { + "name": "schema", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true + }, + "table_name": { + "name": "table_name", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true, + "default": "'buster_query_logs'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "logs_write_back_configs_org_unique": { + "name": "logs_write_back_configs_org_unique", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"logs_write_back_configs\".\"deleted_at\" IS NULL", + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_logs_write_back_configs_org_id": { + "name": "idx_logs_write_back_configs_org_id", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "uuid_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_logs_write_back_configs_data_source_id": { + "name": "idx_logs_write_back_configs_data_source_id", + "columns": [ + { + "expression": "data_source_id", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "uuid_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_logs_write_back_configs_deleted_at": { + "name": "idx_logs_write_back_configs_deleted_at", + "columns": [ + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "logs_write_back_configs_organization_id_fkey": { + "name": "logs_write_back_configs_organization_id_fkey", + "tableFrom": "logs_write_back_configs", + "tableTo": "organizations", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "logs_write_back_configs_data_source_id_fkey": { + "name": "logs_write_back_configs_data_source_id_fkey", + "tableFrom": "logs_write_back_configs", + "tableTo": "data_sources", + "columnsFrom": [ + "data_source_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.messages": { + "name": "messages", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "request_message": { + "name": "request_message", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "response_messages": { + "name": "response_messages", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "message_analysis_mode": { + "name": "message_analysis_mode", + "type": "message_analysis_mode_enum", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'auto'" + }, + "reasoning": { + "name": "reasoning", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "raw_llm_messages": { + "name": "raw_llm_messages", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "final_reasoning_message": { + "name": "final_reasoning_message", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "chat_id": { + "name": "chat_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "feedback": { + "name": "feedback", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "is_completed": { + "name": "is_completed", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "post_processing_message": { + "name": "post_processing_message", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "trigger_run_id": { + "name": "trigger_run_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "metadata": { + "name": "metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + } + }, + "indexes": { + "messages_chat_id_idx": { + "name": "messages_chat_id_idx", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "uuid_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "messages_created_at_idx": { + "name": "messages_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "timestamptz_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "messages_created_by_idx": { + "name": "messages_created_by_idx", + "columns": [ + { + "expression": "created_by", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "uuid_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "messages_deleted_at_idx": { + "name": "messages_deleted_at_idx", + "columns": [ + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "timestamptz_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "messages_raw_llm_messages_gin_idx": { + "name": "messages_raw_llm_messages_gin_idx", + "columns": [ + { + "expression": "raw_llm_messages", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "jsonb_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "gin", + "with": {} + }, + "messages_response_messages_gin_idx": { + "name": "messages_response_messages_gin_idx", + "columns": [ + { + "expression": "response_messages", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "jsonb_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "gin", + "with": {} + }, + "messages_reasoning_gin_idx": { + "name": "messages_reasoning_gin_idx", + "columns": [ + { + "expression": "reasoning", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "jsonb_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "gin", + "with": {} + }, + "messages_id_deleted_at_idx": { + "name": "messages_id_deleted_at_idx", + "columns": [ + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "uuid_ops" + }, + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "timestamptz_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "messages_chat_id_fkey": { + "name": "messages_chat_id_fkey", + "tableFrom": "messages", + "tableTo": "chats", + "columnsFrom": [ + "chat_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "messages_created_by_fkey": { + "name": "messages_created_by_fkey", + "tableFrom": "messages", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.messages_to_files": { + "name": "messages_to_files", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "message_id": { + "name": "message_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "file_id": { + "name": "file_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "CURRENT_TIMESTAMP" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "CURRENT_TIMESTAMP" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "is_duplicate": { + "name": "is_duplicate", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "version_number": { + "name": "version_number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + } + }, + "indexes": { + "messages_files_file_id_idx": { + "name": "messages_files_file_id_idx", + "columns": [ + { + "expression": "file_id", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "uuid_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "messages_files_message_id_idx": { + "name": "messages_files_message_id_idx", + "columns": [ + { + "expression": "message_id", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "uuid_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "messages_to_files_message_id_fkey": { + "name": "messages_to_files_message_id_fkey", + "tableFrom": "messages_to_files", + "tableTo": "messages", + "columnsFrom": [ + "message_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "messages_to_files_message_id_file_id_key": { + "name": "messages_to_files_message_id_file_id_key", + "nullsNotDistinct": false, + "columns": [ + "message_id", + "file_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.messages_to_slack_messages": { + "name": "messages_to_slack_messages", + "schema": "", + "columns": { + "message_id": { + "name": "message_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "slack_message_id": { + "name": "slack_message_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "messages_to_slack_messages_message_id_idx": { + "name": "messages_to_slack_messages_message_id_idx", + "columns": [ + { + "expression": "message_id", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "uuid_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "messages_to_slack_messages_slack_message_id_idx": { + "name": "messages_to_slack_messages_slack_message_id_idx", + "columns": [ + { + "expression": "slack_message_id", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "uuid_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "messages_to_slack_messages_message_id_fkey": { + "name": "messages_to_slack_messages_message_id_fkey", + "tableFrom": "messages_to_slack_messages", + "tableTo": "messages", + "columnsFrom": [ + "message_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "messages_to_slack_messages_slack_message_id_fkey": { + "name": "messages_to_slack_messages_slack_message_id_fkey", + "tableFrom": "messages_to_slack_messages", + "tableTo": "slack_message_tracking", + "columnsFrom": [ + "slack_message_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "messages_to_slack_messages_pkey": { + "name": "messages_to_slack_messages_pkey", + "columns": [ + "message_id", + "slack_message_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.metric_files": { + "name": "metric_files", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "name": { + "name": "name", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "file_name": { + "name": "file_name", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "content": { + "name": "content", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "verification": { + "name": "verification", + "type": "verification_enum", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'notRequested'" + }, + "evaluation_obj": { + "name": "evaluation_obj", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "evaluation_summary": { + "name": "evaluation_summary", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "evaluation_score": { + "name": "evaluation_score", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "CURRENT_TIMESTAMP" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "CURRENT_TIMESTAMP" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "publicly_accessible": { + "name": "publicly_accessible", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "publicly_enabled_by": { + "name": "publicly_enabled_by", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "public_expiry_date": { + "name": "public_expiry_date", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "version_history": { + "name": "version_history", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "data_metadata": { + "name": "data_metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "public_password": { + "name": "public_password", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "data_source_id": { + "name": "data_source_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "workspace_sharing": { + "name": "workspace_sharing", + "type": "workspace_sharing_enum", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'none'" + }, + "workspace_sharing_enabled_by": { + "name": "workspace_sharing_enabled_by", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "workspace_sharing_enabled_at": { + "name": "workspace_sharing_enabled_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "metric_files_created_by_idx": { + "name": "metric_files_created_by_idx", + "columns": [ + { + "expression": "created_by", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "uuid_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "metric_files_data_metadata_idx": { + "name": "metric_files_data_metadata_idx", + "columns": [ + { + "expression": "data_metadata", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "jsonb_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "gin", + "with": {} + }, + "metric_files_deleted_at_idx": { + "name": "metric_files_deleted_at_idx", + "columns": [ + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "timestamptz_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "metric_files_organization_id_idx": { + "name": "metric_files_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "uuid_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "metric_files_created_by_fkey": { + "name": "metric_files_created_by_fkey", + "tableFrom": "metric_files", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "cascade" + }, + "metric_files_publicly_enabled_by_fkey": { + "name": "metric_files_publicly_enabled_by_fkey", + "tableFrom": "metric_files", + "tableTo": "users", + "columnsFrom": [ + "publicly_enabled_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "cascade" + }, + "fk_data_source": { + "name": "fk_data_source", + "tableFrom": "metric_files", + "tableTo": "data_sources", + "columnsFrom": [ + "data_source_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "metric_files_workspace_sharing_enabled_by_fkey": { + "name": "metric_files_workspace_sharing_enabled_by_fkey", + "tableFrom": "metric_files", + "tableTo": "users", + "columnsFrom": [ + "workspace_sharing_enabled_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.metric_files_to_dashboard_files": { + "name": "metric_files_to_dashboard_files", + "schema": "", + "columns": { + "metric_file_id": { + "name": "metric_file_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "dashboard_file_id": { + "name": "dashboard_file_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "CURRENT_TIMESTAMP" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "CURRENT_TIMESTAMP" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "uuid", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "metric_files_to_dashboard_files_dashboard_id_idx": { + "name": "metric_files_to_dashboard_files_dashboard_id_idx", + "columns": [ + { + "expression": "dashboard_file_id", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "uuid_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "metric_files_to_dashboard_files_deleted_at_idx": { + "name": "metric_files_to_dashboard_files_deleted_at_idx", + "columns": [ + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "timestamptz_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "metric_files_to_dashboard_files_metric_id_idx": { + "name": "metric_files_to_dashboard_files_metric_id_idx", + "columns": [ + { + "expression": "metric_file_id", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "uuid_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "metric_files_to_dashboard_files_metric_file_id_fkey": { + "name": "metric_files_to_dashboard_files_metric_file_id_fkey", + "tableFrom": "metric_files_to_dashboard_files", + "tableTo": "metric_files", + "columnsFrom": [ + "metric_file_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "metric_files_to_dashboard_files_dashboard_file_id_fkey": { + "name": "metric_files_to_dashboard_files_dashboard_file_id_fkey", + "tableFrom": "metric_files_to_dashboard_files", + "tableTo": "dashboard_files", + "columnsFrom": [ + "dashboard_file_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "metric_files_to_dashboard_files_created_by_fkey": { + "name": "metric_files_to_dashboard_files_created_by_fkey", + "tableFrom": "metric_files_to_dashboard_files", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "cascade" + } + }, + "compositePrimaryKeys": { + "metric_files_to_dashboard_files_pkey": { + "name": "metric_files_to_dashboard_files_pkey", + "columns": [ + "metric_file_id", + "dashboard_file_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.metric_files_to_datasets": { + "name": "metric_files_to_datasets", + "schema": "", + "columns": { + "metric_file_id": { + "name": "metric_file_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "dataset_id": { + "name": "dataset_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "metric_version_number": { + "name": "metric_version_number", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "fk_metric_file": { + "name": "fk_metric_file", + "tableFrom": "metric_files_to_datasets", + "tableTo": "metric_files", + "columnsFrom": [ + "metric_file_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "fk_dataset": { + "name": "fk_dataset", + "tableFrom": "metric_files_to_datasets", + "tableTo": "datasets", + "columnsFrom": [ + "dataset_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "metric_files_to_datasets_pkey": { + "name": "metric_files_to_datasets_pkey", + "columns": [ + "metric_file_id", + "dataset_id", + "metric_version_number" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.metric_files_to_report_files": { + "name": "metric_files_to_report_files", + "schema": "", + "columns": { + "metric_file_id": { + "name": "metric_file_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "report_file_id": { + "name": "report_file_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "CURRENT_TIMESTAMP" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "CURRENT_TIMESTAMP" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "uuid", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "metric_files_to_report_files_report_id_idx": { + "name": "metric_files_to_report_files_report_id_idx", + "columns": [ + { + "expression": "report_file_id", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "uuid_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "metric_files_to_report_files_deleted_at_idx": { + "name": "metric_files_to_report_files_deleted_at_idx", + "columns": [ + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "timestamptz_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "metric_files_to_report_files_metric_id_idx": { + "name": "metric_files_to_report_files_metric_id_idx", + "columns": [ + { + "expression": "metric_file_id", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "uuid_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "metric_files_to_report_files_metric_file_id_fkey": { + "name": "metric_files_to_report_files_metric_file_id_fkey", + "tableFrom": "metric_files_to_report_files", + "tableTo": "metric_files", + "columnsFrom": [ + "metric_file_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "metric_files_to_report_files_report_file_id_fkey": { + "name": "metric_files_to_report_files_report_file_id_fkey", + "tableFrom": "metric_files_to_report_files", + "tableTo": "report_files", + "columnsFrom": [ + "report_file_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "metric_files_to_report_files_created_by_fkey": { + "name": "metric_files_to_report_files_created_by_fkey", + "tableFrom": "metric_files_to_report_files", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "cascade" + } + }, + "compositePrimaryKeys": { + "metric_files_to_report_files_pkey": { + "name": "metric_files_to_report_files_pkey", + "columns": [ + "metric_file_id", + "report_file_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.organizations": { + "name": "organizations", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "domain": { + "name": "domain", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "payment_required": { + "name": "payment_required", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "domains": { + "name": "domains", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "restrict_new_user_invitations": { + "name": "restrict_new_user_invitations", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "default_role": { + "name": "default_role", + "type": "user_organization_role_enum", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'restricted_querier'" + }, + "organization_color_palettes": { + "name": "organization_color_palettes", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{\"selectedId\": null, \"palettes\": [], \"selectedDictionaryPalette\": null}'::jsonb" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "organizations_name_key": { + "name": "organizations_name_key", + "nullsNotDistinct": false, + "columns": [ + "name" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.permission_groups": { + "name": "permission_groups", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "updated_by": { + "name": "updated_by", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "permission_groups_organization_id_fkey": { + "name": "permission_groups_organization_id_fkey", + "tableFrom": "permission_groups", + "tableTo": "organizations", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "permission_groups_created_by_fkey": { + "name": "permission_groups_created_by_fkey", + "tableFrom": "permission_groups", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "cascade" + }, + "permission_groups_updated_by_fkey": { + "name": "permission_groups_updated_by_fkey", + "tableFrom": "permission_groups", + "tableTo": "users", + "columnsFrom": [ + "updated_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.permission_groups_to_identities": { + "name": "permission_groups_to_identities", + "schema": "", + "columns": { + "permission_group_id": { + "name": "permission_group_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "identity_id": { + "name": "identity_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "identity_type": { + "name": "identity_type", + "type": "identity_type_enum", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "updated_by": { + "name": "updated_by", + "type": "uuid", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "permission_groups_to_identities_created_by_fkey": { + "name": "permission_groups_to_identities_created_by_fkey", + "tableFrom": "permission_groups_to_identities", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "cascade" + }, + "permission_groups_to_identities_updated_by_fkey": { + "name": "permission_groups_to_identities_updated_by_fkey", + "tableFrom": "permission_groups_to_identities", + "tableTo": "users", + "columnsFrom": [ + "updated_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "cascade" + } + }, + "compositePrimaryKeys": { + "permission_groups_to_identities_pkey": { + "name": "permission_groups_to_identities_pkey", + "columns": [ + "permission_group_id", + "identity_id", + "identity_type" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.permission_groups_to_users": { + "name": "permission_groups_to_users", + "schema": "", + "columns": { + "permission_group_id": { + "name": "permission_group_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "permission_groups_to_users_user_id_idx": { + "name": "permission_groups_to_users_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "uuid_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "permission_groups_to_users_permission_group_id_fkey": { + "name": "permission_groups_to_users_permission_group_id_fkey", + "tableFrom": "permission_groups_to_users", + "tableTo": "permission_groups", + "columnsFrom": [ + "permission_group_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "permission_groups_to_users_user_id_fkey": { + "name": "permission_groups_to_users_user_id_fkey", + "tableFrom": "permission_groups_to_users", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "cascade" + } + }, + "compositePrimaryKeys": { + "permission_groups_to_users_pkey": { + "name": "permission_groups_to_users_pkey", + "columns": [ + "permission_group_id", + "user_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": { + "permission_groups_to_users_policy": { + "name": "permission_groups_to_users_policy", + "as": "PERMISSIVE", + "for": "ALL", + "to": [ + "authenticated" + ], + "using": "true" + } + }, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.report_files": { + "name": "report_files", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "name": { + "name": "name", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "CURRENT_TIMESTAMP" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "CURRENT_TIMESTAMP" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "publicly_accessible": { + "name": "publicly_accessible", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "publicly_enabled_by": { + "name": "publicly_enabled_by", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "public_expiry_date": { + "name": "public_expiry_date", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "version_history": { + "name": "version_history", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "public_password": { + "name": "public_password", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "workspace_sharing": { + "name": "workspace_sharing", + "type": "workspace_sharing_enum", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'none'" + }, + "workspace_sharing_enabled_by": { + "name": "workspace_sharing_enabled_by", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "workspace_sharing_enabled_at": { + "name": "workspace_sharing_enabled_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "report_files_created_by_idx": { + "name": "report_files_created_by_idx", + "columns": [ + { + "expression": "created_by", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "uuid_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "report_files_deleted_at_idx": { + "name": "report_files_deleted_at_idx", + "columns": [ + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "timestamptz_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "report_files_organization_id_idx": { + "name": "report_files_organization_id_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "uuid_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "report_files_created_by_fkey": { + "name": "report_files_created_by_fkey", + "tableFrom": "report_files", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "cascade" + }, + "report_files_publicly_enabled_by_fkey": { + "name": "report_files_publicly_enabled_by_fkey", + "tableFrom": "report_files", + "tableTo": "users", + "columnsFrom": [ + "publicly_enabled_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "cascade" + }, + "report_files_workspace_sharing_enabled_by_fkey": { + "name": "report_files_workspace_sharing_enabled_by_fkey", + "tableFrom": "report_files", + "tableTo": "users", + "columnsFrom": [ + "workspace_sharing_enabled_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "cascade" + }, + "report_files_organization_id_fkey": { + "name": "report_files_organization_id_fkey", + "tableFrom": "report_files", + "tableTo": "organizations", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.s3_integrations": { + "name": "s3_integrations", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "provider": { + "name": "provider", + "type": "storage_provider_enum", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "idx_s3_integrations_organization_id": { + "name": "idx_s3_integrations_organization_id", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "uuid_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_s3_integrations_deleted_at": { + "name": "idx_s3_integrations_deleted_at", + "columns": [ + { + "expression": "deleted_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "s3_integrations_organization_id_fkey": { + "name": "s3_integrations_organization_id_fkey", + "tableFrom": "s3_integrations", + "tableTo": "organizations", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.shortcuts": { + "name": "shortcuts", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "name": { + "name": "name", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true + }, + "instructions": { + "name": "instructions", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "updated_by": { + "name": "updated_by", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "share_with_workspace": { + "name": "share_with_workspace", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "shortcuts_org_user_idx": { + "name": "shortcuts_org_user_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "uuid_ops" + }, + { + "expression": "created_by", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "uuid_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "shortcuts_name_idx": { + "name": "shortcuts_name_idx", + "columns": [ + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "shortcuts_workspace_unique": { + "name": "shortcuts_workspace_unique", + "columns": [ + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"shortcuts\".\"share_with_workspace\" = true", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "shortcuts_created_by_fkey": { + "name": "shortcuts_created_by_fkey", + "tableFrom": "shortcuts", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "cascade" + }, + "shortcuts_updated_by_fkey": { + "name": "shortcuts_updated_by_fkey", + "tableFrom": "shortcuts", + "tableTo": "users", + "columnsFrom": [ + "updated_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "cascade" + }, + "shortcuts_organization_id_fkey": { + "name": "shortcuts_organization_id_fkey", + "tableFrom": "shortcuts", + "tableTo": "organizations", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "shortcuts_personal_unique": { + "name": "shortcuts_personal_unique", + "nullsNotDistinct": false, + "columns": [ + "name", + "organization_id", + "created_by" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.slack_integrations": { + "name": "slack_integrations", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "oauth_state": { + "name": "oauth_state", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false + }, + "oauth_expires_at": { + "name": "oauth_expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "oauth_metadata": { + "name": "oauth_metadata", + "type": "jsonb", + "primaryKey": false, + "notNull": false, + "default": "'{}'::jsonb" + }, + "team_id": { + "name": "team_id", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false + }, + "team_name": { + "name": "team_name", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false + }, + "team_domain": { + "name": "team_domain", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false + }, + "enterprise_id": { + "name": "enterprise_id", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false + }, + "bot_user_id": { + "name": "bot_user_id", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "token_vault_key": { + "name": "token_vault_key", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false + }, + "installed_by_slack_user_id": { + "name": "installed_by_slack_user_id", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false + }, + "installed_at": { + "name": "installed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "last_used_at": { + "name": "last_used_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "slack_integration_status_enum", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "default_channel": { + "name": "default_channel", + "type": "jsonb", + "primaryKey": false, + "notNull": false, + "default": "'{}'::jsonb" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "default_sharing_permissions": { + "name": "default_sharing_permissions", + "type": "slack_sharing_permission_enum", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'shareWithChannel'" + } + }, + "indexes": { + "idx_slack_integrations_org_id": { + "name": "idx_slack_integrations_org_id", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "uuid_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_slack_integrations_team_id": { + "name": "idx_slack_integrations_team_id", + "columns": [ + { + "expression": "team_id", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "text_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_slack_integrations_oauth_state": { + "name": "idx_slack_integrations_oauth_state", + "columns": [ + { + "expression": "oauth_state", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "text_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_slack_integrations_oauth_expires": { + "name": "idx_slack_integrations_oauth_expires", + "columns": [ + { + "expression": "oauth_expires_at", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "timestamptz_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "slack_integrations_organization_id_fkey": { + "name": "slack_integrations_organization_id_fkey", + "tableFrom": "slack_integrations", + "tableTo": "organizations", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "slack_integrations_user_id_fkey": { + "name": "slack_integrations_user_id_fkey", + "tableFrom": "slack_integrations", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "slack_integrations_oauth_state_unique": { + "name": "slack_integrations_oauth_state_unique", + "nullsNotDistinct": false, + "columns": [ + "oauth_state" + ] + }, + "slack_integrations_token_vault_key_unique": { + "name": "slack_integrations_token_vault_key_unique", + "nullsNotDistinct": false, + "columns": [ + "token_vault_key" + ] + }, + "slack_integrations_org_team_key": { + "name": "slack_integrations_org_team_key", + "nullsNotDistinct": false, + "columns": [ + "organization_id", + "team_id" + ] + } + }, + "policies": {}, + "checkConstraints": { + "slack_integrations_status_check": { + "name": "slack_integrations_status_check", + "value": "(status = 'pending' AND oauth_state IS NOT NULL) OR (status != 'pending' AND team_id IS NOT NULL)" + } + }, + "isRLSEnabled": false + }, + "public.slack_message_tracking": { + "name": "slack_message_tracking", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "integration_id": { + "name": "integration_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "internal_message_id": { + "name": "internal_message_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "slack_channel_id": { + "name": "slack_channel_id", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true + }, + "slack_message_ts": { + "name": "slack_message_ts", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true + }, + "slack_thread_ts": { + "name": "slack_thread_ts", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false + }, + "message_type": { + "name": "message_type", + "type": "varchar(50)", + "primaryKey": false, + "notNull": true + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "sender_info": { + "name": "sender_info", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "sent_at": { + "name": "sent_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_message_tracking_integration": { + "name": "idx_message_tracking_integration", + "columns": [ + { + "expression": "integration_id", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "uuid_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_message_tracking_channel": { + "name": "idx_message_tracking_channel", + "columns": [ + { + "expression": "slack_channel_id", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "text_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_message_tracking_thread": { + "name": "idx_message_tracking_thread", + "columns": [ + { + "expression": "slack_thread_ts", + "isExpression": false, + "asc": true, + "nulls": "last", + "opclass": "text_ops" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "slack_message_tracking_integration_id_fkey": { + "name": "slack_message_tracking_integration_id_fkey", + "tableFrom": "slack_message_tracking", + "tableTo": "slack_integrations", + "columnsFrom": [ + "integration_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "slack_message_tracking_internal_message_id_unique": { + "name": "slack_message_tracking_internal_message_id_unique", + "nullsNotDistinct": false, + "columns": [ + "internal_message_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.teams": { + "name": "teams", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "sharing_setting": { + "name": "sharing_setting", + "type": "sharing_setting_enum", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'none'" + }, + "edit_sql": { + "name": "edit_sql", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "upload_csv": { + "name": "upload_csv", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "export_assets": { + "name": "export_assets", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "email_slack_enabled": { + "name": "email_slack_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "created_by": { + "name": "created_by", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "teams_organization_id_fkey": { + "name": "teams_organization_id_fkey", + "tableFrom": "teams", + "tableTo": "organizations", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "teams_created_by_fkey": { + "name": "teams_created_by_fkey", + "tableFrom": "teams", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "cascade" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "teams_name_key": { + "name": "teams_name_key", + "nullsNotDistinct": false, + "columns": [ + "name" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.teams_to_users": { + "name": "teams_to_users", + "schema": "", + "columns": { + "team_id": { + "name": "team_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "role": { + "name": "role", + "type": "team_role_enum", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'member'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "teams_to_users_team_id_fkey": { + "name": "teams_to_users_team_id_fkey", + "tableFrom": "teams_to_users", + "tableTo": "teams", + "columnsFrom": [ + "team_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "teams_to_users_user_id_fkey": { + "name": "teams_to_users_user_id_fkey", + "tableFrom": "teams_to_users", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "cascade" + } + }, + "compositePrimaryKeys": { + "teams_to_users_pkey": { + "name": "teams_to_users_pkey", + "columns": [ + "team_id", + "user_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.user_favorites": { + "name": "user_favorites", + "schema": "", + "columns": { + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "asset_id": { + "name": "asset_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "asset_type": { + "name": "asset_type", + "type": "asset_type_enum", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "order_index": { + "name": "order_index", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "user_favorites_user_id_fkey": { + "name": "user_favorites_user_id_fkey", + "tableFrom": "user_favorites", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "cascade" + } + }, + "compositePrimaryKeys": { + "user_favorites_pkey": { + "name": "user_favorites_pkey", + "columns": [ + "user_id", + "asset_id", + "asset_type" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.users": { + "name": "users", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "config": { + "name": "config", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "attributes": { + "name": "attributes", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "avatar_url": { + "name": "avatar_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "suggested_prompts": { + "name": "suggested_prompts", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{\"suggestedPrompts\":{\"report\":[\"provide a trend analysis of quarterly profits\",\"evaluate product performance across regions\"],\"dashboard\":[\"create a sales performance dashboard\",\"design a revenue forecast dashboard\"],\"visualization\":[\"create a metric for monthly sales\",\"show top vendors by purchase volume\"],\"help\":[\"what types of analyses can you perform?\",\"what questions can I as buster?\",\"what data models are available for queries?\",\"can you explain your forecasting capabilities?\"]},\"updatedAt\":\"2025-09-29T21:30:34.051Z\"}'::jsonb" + }, + "personalization_enabled": { + "name": "personalization_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "personalization_config": { + "name": "personalization_config", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "last_used_shortcuts": { + "name": "last_used_shortcuts", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "users_email_key": { + "name": "users_email_key", + "nullsNotDistinct": false, + "columns": [ + "email" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.users_to_organizations": { + "name": "users_to_organizations", + "schema": "", + "columns": { + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "role": { + "name": "role", + "type": "user_organization_role_enum", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'querier'" + }, + "sharing_setting": { + "name": "sharing_setting", + "type": "sharing_setting_enum", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'none'" + }, + "edit_sql": { + "name": "edit_sql", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "upload_csv": { + "name": "upload_csv", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "export_assets": { + "name": "export_assets", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "email_slack_enabled": { + "name": "email_slack_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "updated_by": { + "name": "updated_by", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "deleted_by": { + "name": "deleted_by", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "user_organization_status_enum", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'active'" + } + }, + "indexes": {}, + "foreignKeys": { + "users_to_organizations_organization_id_fkey": { + "name": "users_to_organizations_organization_id_fkey", + "tableFrom": "users_to_organizations", + "tableTo": "organizations", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "users_to_organizations_user_id_fkey": { + "name": "users_to_organizations_user_id_fkey", + "tableFrom": "users_to_organizations", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "cascade" + }, + "users_to_organizations_created_by_fkey": { + "name": "users_to_organizations_created_by_fkey", + "tableFrom": "users_to_organizations", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "cascade" + }, + "users_to_organizations_updated_by_fkey": { + "name": "users_to_organizations_updated_by_fkey", + "tableFrom": "users_to_organizations", + "tableTo": "users", + "columnsFrom": [ + "updated_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "cascade" + }, + "users_to_organizations_deleted_by_fkey": { + "name": "users_to_organizations_deleted_by_fkey", + "tableFrom": "users_to_organizations", + "tableTo": "users", + "columnsFrom": [ + "deleted_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "cascade" + } + }, + "compositePrimaryKeys": { + "users_to_organizations_pkey": { + "name": "users_to_organizations_pkey", + "columns": [ + "user_id", + "organization_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": { + "public.asset_permission_role_enum": { + "name": "asset_permission_role_enum", + "schema": "public", + "values": [ + "owner", + "viewer", + "can_view", + "can_filter", + "can_edit", + "full_access" + ] + }, + "public.asset_type_enum": { + "name": "asset_type_enum", + "schema": "public", + "values": [ + "chat", + "metric_file", + "dashboard_file", + "report_file", + "collection" + ] + }, + "public.data_source_onboarding_status_enum": { + "name": "data_source_onboarding_status_enum", + "schema": "public", + "values": [ + "notStarted", + "inProgress", + "completed", + "failed" + ] + }, + "public.dataset_type_enum": { + "name": "dataset_type_enum", + "schema": "public", + "values": [ + "table", + "view", + "materializedView" + ] + }, + "public.docs_type_enum": { + "name": "docs_type_enum", + "schema": "public", + "values": [ + "analyst", + "normal" + ] + }, + "public.github_integration_status_enum": { + "name": "github_integration_status_enum", + "schema": "public", + "values": [ + "pending", + "active", + "suspended", + "revoked" + ] + }, + "public.identity_type_enum": { + "name": "identity_type_enum", + "schema": "public", + "values": [ + "user", + "team", + "organization" + ] + }, + "public.message_analysis_mode_enum": { + "name": "message_analysis_mode_enum", + "schema": "public", + "values": [ + "auto", + "standard", + "investigation" + ] + }, + "public.message_feedback_enum": { + "name": "message_feedback_enum", + "schema": "public", + "values": [ + "positive", + "negative" + ] + }, + "public.sharing_setting_enum": { + "name": "sharing_setting_enum", + "schema": "public", + "values": [ + "none", + "team", + "organization", + "public" + ] + }, + "public.slack_chat_authorization_enum": { + "name": "slack_chat_authorization_enum", + "schema": "public", + "values": [ + "unauthorized", + "authorized", + "auto_added" + ] + }, + "public.slack_integration_status_enum": { + "name": "slack_integration_status_enum", + "schema": "public", + "values": [ + "pending", + "active", + "failed", + "revoked" + ] + }, + "public.slack_sharing_permission_enum": { + "name": "slack_sharing_permission_enum", + "schema": "public", + "values": [ + "shareWithWorkspace", + "shareWithChannel", + "noSharing" + ] + }, + "public.storage_provider_enum": { + "name": "storage_provider_enum", + "schema": "public", + "values": [ + "s3", + "r2", + "gcs" + ] + }, + "public.stored_values_status_enum": { + "name": "stored_values_status_enum", + "schema": "public", + "values": [ + "syncing", + "success", + "failed" + ] + }, + "public.table_type_enum": { + "name": "table_type_enum", + "schema": "public", + "values": [ + "TABLE", + "VIEW", + "MATERIALIZED_VIEW", + "EXTERNAL_TABLE", + "TEMPORARY_TABLE" + ] + }, + "public.team_role_enum": { + "name": "team_role_enum", + "schema": "public", + "values": [ + "manager", + "member", + "none" + ] + }, + "public.user_organization_role_enum": { + "name": "user_organization_role_enum", + "schema": "public", + "values": [ + "workspace_admin", + "data_admin", + "querier", + "restricted_querier", + "viewer" + ] + }, + "public.user_organization_status_enum": { + "name": "user_organization_status_enum", + "schema": "public", + "values": [ + "active", + "inactive", + "pending", + "guest" + ] + }, + "public.verification_enum": { + "name": "verification_enum", + "schema": "public", + "values": [ + "verified", + "backlogged", + "inReview", + "requested", + "notRequested" + ] + }, + "public.workspace_sharing_enum": { + "name": "workspace_sharing_enum", + "schema": "public", + "values": [ + "none", + "can_view", + "can_edit", + "full_access" + ] + } + }, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/packages/database/drizzle/meta/_journal.json b/packages/database/drizzle/meta/_journal.json index b0e2d764b..7f93bcec0 100644 --- a/packages/database/drizzle/meta/_journal.json +++ b/packages/database/drizzle/meta/_journal.json @@ -782,8 +782,8 @@ { "idx": 112, "version": "7", - "when": 1759181434094, - "tag": "0112_write-back-logs-config", + "when": 1759179073594, + "tag": "0112_shortcuts_trigger_backfill", "breakpoints": true } ] diff --git a/packages/database/src/queries/chats/chats.ts b/packages/database/src/queries/chats/chats.ts index a06ebbe60..0b15da9f3 100644 --- a/packages/database/src/queries/chats/chats.ts +++ b/packages/database/src/queries/chats/chats.ts @@ -223,3 +223,56 @@ export async function updateChat( throw new Error(`Failed to update chat fields for chat ${chatId}`); } } + +/** + * Updates a chat's sharing settings + */ +export async function updateChatSharing( + chatId: string, + userId: string, + options: { + publicly_accessible?: boolean; + public_expiry_date?: string | null; + workspace_sharing?: 'none' | 'can_view' | 'can_edit' | 'full_access'; + } +): Promise<{ success: boolean }> { + const updateFields: UpdateableChatFields = { + updatedBy: userId, + }; + + if (options.publicly_accessible !== undefined) { + updateFields.publiclyAccessible = options.publicly_accessible; + updateFields.publiclyEnabledBy = options.publicly_accessible ? userId : null; + } + + if (options.public_expiry_date !== undefined) { + updateFields.publicExpiryDate = options.public_expiry_date; + } + + if (options.workspace_sharing !== undefined) { + updateFields.workspaceSharing = options.workspace_sharing; + + if (options.workspace_sharing !== 'none') { + updateFields.workspaceSharingEnabledBy = userId; + updateFields.workspaceSharingEnabledAt = new Date().toISOString(); + } else { + updateFields.workspaceSharingEnabledBy = null; + updateFields.workspaceSharingEnabledAt = null; + } + } + + return await updateChat(chatId, updateFields); +} + +/** + * Get a chat by ID (simple version for sharing handlers) + */ +export async function getChatById(chatId: string): Promise { + const [chat] = await db + .select() + .from(chats) + .where(and(eq(chats.id, chatId), isNull(chats.deletedAt))) + .limit(1); + + return chat || null; +} diff --git a/packages/database/src/queries/chats/index.ts b/packages/database/src/queries/chats/index.ts index 6ebec7241..41801317c 100644 --- a/packages/database/src/queries/chats/index.ts +++ b/packages/database/src/queries/chats/index.ts @@ -4,6 +4,8 @@ export { updateChat, getChatWithDetails, createMessage, + updateChatSharing, + getChatById, CreateChatInputSchema, GetChatInputSchema, CreateMessageInputSchema, diff --git a/packages/database/src/queries/dashboards/index.ts b/packages/database/src/queries/dashboards/index.ts index f25aaf7c6..d95137424 100644 --- a/packages/database/src/queries/dashboards/index.ts +++ b/packages/database/src/queries/dashboards/index.ts @@ -16,6 +16,8 @@ export { type GetDashboardByIdInput, } from './get-dashboard-by-id'; +export { updateDashboard } from './update-dashboard'; + export { getCollectionsAssociatedWithDashboard, type AssociatedCollection, diff --git a/packages/database/src/queries/dashboards/update-dashboard.ts b/packages/database/src/queries/dashboards/update-dashboard.ts new file mode 100644 index 000000000..14266e068 --- /dev/null +++ b/packages/database/src/queries/dashboards/update-dashboard.ts @@ -0,0 +1,92 @@ +import { and, eq, isNull } from 'drizzle-orm'; +import { z } from 'zod'; +import { db } from '../../connection'; +import { dashboardFiles } from '../../schema'; +import { WorkspaceSharingSchema } from '../../schema-types'; + +// Type for updating dashboardFiles - excludes read-only fields +type UpdateDashboardData = Partial< + Omit +>; + +// Input validation schema for updating a dashboard +const UpdateDashboardInputSchema = z.object({ + dashboardId: z.string().uuid('Dashboard ID must be a valid UUID'), + userId: z.string().uuid('User ID must be a valid UUID'), + name: z.string().optional(), + publicly_accessible: z.boolean().optional(), + public_expiry_date: z.string().nullable().optional(), + public_password: z.string().nullable().optional(), + workspace_sharing: WorkspaceSharingSchema.optional(), +}); + +type UpdateDashboardInput = z.infer; + +/** + * Updates a dashboard with the provided fields + * Only updates fields that are provided in the input + * Always updates the updatedAt timestamp + */ +export const updateDashboard = async (params: UpdateDashboardInput): Promise => { + // Validate and destructure input + const { + dashboardId, + userId, + name, + publicly_accessible, + public_expiry_date, + public_password, + workspace_sharing, + } = UpdateDashboardInputSchema.parse(params); + + try { + // Build update data - only include fields that are provided + const updateData: UpdateDashboardData = { + updatedAt: new Date().toISOString(), + }; + + // Only add fields that are provided + if (name !== undefined) { + updateData.name = name; + } + + if (publicly_accessible !== undefined) { + updateData.publiclyAccessible = publicly_accessible; + // Set publiclyEnabledBy to userId when enabling, null when disabling + updateData.publiclyEnabledBy = publicly_accessible ? userId : null; + } + + if (public_expiry_date !== undefined) { + updateData.publicExpiryDate = public_expiry_date; + } + + if (public_password !== undefined) { + updateData.publicPassword = public_password; + } + + if (workspace_sharing !== undefined) { + updateData.workspaceSharing = workspace_sharing; + + if (workspace_sharing !== 'none') { + updateData.workspaceSharingEnabledBy = userId; + updateData.workspaceSharingEnabledAt = new Date().toISOString(); + } else { + updateData.workspaceSharingEnabledBy = null; + updateData.workspaceSharingEnabledAt = null; + } + } + + // Update the dashboard + await db + .update(dashboardFiles) + .set(updateData) + .where(and(eq(dashboardFiles.id, dashboardId), isNull(dashboardFiles.deletedAt))); + + console.info(`Successfully updated dashboard ${dashboardId}`); + } catch (error) { + console.error(`Failed to update dashboard ${dashboardId}:`, error); + throw new Error( + `Failed to update dashboard: ${error instanceof Error ? error.message : 'Unknown error'}` + ); + } +}; diff --git a/packages/database/src/queries/metrics/index.ts b/packages/database/src/queries/metrics/index.ts index bb8412f94..469323841 100644 --- a/packages/database/src/queries/metrics/index.ts +++ b/packages/database/src/queries/metrics/index.ts @@ -32,6 +32,8 @@ export { type MetricFile, } from './get-metric-by-id'; +export { updateMetric } from './update-metric'; + export { getDashboardsAssociatedWithMetric, getCollectionsAssociatedWithMetric, diff --git a/packages/database/src/queries/metrics/update-metric.ts b/packages/database/src/queries/metrics/update-metric.ts new file mode 100644 index 000000000..72e29a206 --- /dev/null +++ b/packages/database/src/queries/metrics/update-metric.ts @@ -0,0 +1,92 @@ +import { and, eq, isNull } from 'drizzle-orm'; +import { z } from 'zod'; +import { db } from '../../connection'; +import { metricFiles } from '../../schema'; +import { WorkspaceSharingSchema } from '../../schema-types'; + +// Type for updating metricFiles - excludes read-only fields +type UpdateMetricData = Partial< + Omit +>; + +// Input validation schema for updating a metric +const UpdateMetricInputSchema = z.object({ + metricId: z.string().uuid('Metric ID must be a valid UUID'), + userId: z.string().uuid('User ID must be a valid UUID'), + name: z.string().optional(), + publicly_accessible: z.boolean().optional(), + public_expiry_date: z.string().nullable().optional(), + public_password: z.string().nullable().optional(), + workspace_sharing: WorkspaceSharingSchema.optional(), +}); + +type UpdateMetricInput = z.infer; + +/** + * Updates a metric with the provided fields + * Only updates fields that are provided in the input + * Always updates the updatedAt timestamp + */ +export const updateMetric = async (params: UpdateMetricInput): Promise => { + // Validate and destructure input + const { + metricId, + userId, + name, + publicly_accessible, + public_expiry_date, + public_password, + workspace_sharing, + } = UpdateMetricInputSchema.parse(params); + + try { + // Build update data - only include fields that are provided + const updateData: UpdateMetricData = { + updatedAt: new Date().toISOString(), + }; + + // Only add fields that are provided + if (name !== undefined) { + updateData.name = name; + } + + if (publicly_accessible !== undefined) { + updateData.publiclyAccessible = publicly_accessible; + // Set publiclyEnabledBy to userId when enabling, null when disabling + updateData.publiclyEnabledBy = publicly_accessible ? userId : null; + } + + if (public_expiry_date !== undefined) { + updateData.publicExpiryDate = public_expiry_date; + } + + if (public_password !== undefined) { + updateData.publicPassword = public_password; + } + + if (workspace_sharing !== undefined) { + updateData.workspaceSharing = workspace_sharing; + + if (workspace_sharing !== 'none') { + updateData.workspaceSharingEnabledBy = userId; + updateData.workspaceSharingEnabledAt = new Date().toISOString(); + } else { + updateData.workspaceSharingEnabledBy = null; + updateData.workspaceSharingEnabledAt = null; + } + } + + // Update the metric + await db + .update(metricFiles) + .set(updateData) + .where(and(eq(metricFiles.id, metricId), isNull(metricFiles.deletedAt))); + + console.info(`Successfully updated metric ${metricId}`); + } catch (error) { + console.error(`Failed to update metric ${metricId}:`, error); + throw new Error( + `Failed to update metric: ${error instanceof Error ? error.message : 'Unknown error'}` + ); + } +}; diff --git a/packages/server-shared/src/metrics/responses.types.ts b/packages/server-shared/src/metrics/responses.types.ts index 4ba68f80a..7fa746b23 100644 --- a/packages/server-shared/src/metrics/responses.types.ts +++ b/packages/server-shared/src/metrics/responses.types.ts @@ -9,8 +9,7 @@ export const UpdateMetricResponseSchema = MetricSchema; export const DuplicateMetricResponseSchema = MetricSchema; export const DeleteMetricResponseSchema = z.array(z.string()); export const ShareMetricResponseSchema = MetricSchema; -export const ShareDeleteResponseSchema = MetricSchema; -export const ShareUpdateResponseSchema = MetricSchema; +export const ShareMetricUpdateResponseSchema = MetricSchema; export const BulkUpdateMetricVerificationStatusResponseSchema = z.object({ failed_updates: z.array(MetricSchema), @@ -36,8 +35,7 @@ export type BulkUpdateMetricVerificationStatusResponse = z.infer< typeof BulkUpdateMetricVerificationStatusResponseSchema >; export type ShareMetricResponse = z.infer; -export type ShareDeleteResponse = z.infer; -export type ShareUpdateResponse = z.infer; +export type ShareMetricUpdateResponse = z.infer; export type MetricDataResponse = z.infer; /** diff --git a/packages/server-shared/src/reports/responses.ts b/packages/server-shared/src/reports/responses.ts index 2b81faecf..00a3ea3c2 100644 --- a/packages/server-shared/src/reports/responses.ts +++ b/packages/server-shared/src/reports/responses.ts @@ -6,19 +6,6 @@ export const GetReportsListResponseSchema = PaginatedResponseSchema(ReportListIt export const UpdateReportResponseSchema = ReportResponseSchema; export const ShareUpdateResponseSchema = ReportResponseSchema; -// Sharing operation response schemas -export const SharePostResponseSchema = z.object({ - success: z.boolean(), - shared: z.array(z.string()), - notFound: z.array(z.string()), -}); - -export const ShareDeleteResponseSchema = z.object({ - success: z.boolean(), - removed: z.array(z.string()), - notFound: z.array(z.string()), -}); - // For GET sharing endpoint - matches AssetPermissionWithUser from database export const ShareGetResponseSchema = z.object({ permissions: z.array( @@ -51,6 +38,4 @@ export type GetReportsListResponse = z.infer; export type GetReportResponse = z.infer; export type ShareUpdateResponse = z.infer; -export type SharePostResponse = z.infer; -export type ShareDeleteResponse = z.infer; export type ShareGetResponse = z.infer; diff --git a/packages/server-shared/src/share/index.ts b/packages/server-shared/src/share/index.ts index 4ce8201c2..6fd93ecb5 100644 --- a/packages/server-shared/src/share/index.ts +++ b/packages/server-shared/src/share/index.ts @@ -3,3 +3,4 @@ export * from './verification.types'; export * from './requests'; export * from './individual-permissions'; export * from './assets'; +export * from './responses'; diff --git a/packages/server-shared/src/share/responses.ts b/packages/server-shared/src/share/responses.ts new file mode 100644 index 000000000..c7b10db21 --- /dev/null +++ b/packages/server-shared/src/share/responses.ts @@ -0,0 +1,17 @@ +import z from 'zod'; + +// Sharing operation response schemas +export const SharePostResponseSchema = z.object({ + success: z.boolean(), + shared: z.array(z.string()), + notFound: z.array(z.string()), +}); + +export const ShareDeleteResponseSchema = z.object({ + success: z.boolean(), + removed: z.array(z.string()), + notFound: z.array(z.string()), +}); + +export type SharePostResponse = z.infer; +export type ShareDeleteResponse = z.infer;