The minimalistic document archiving platform.
refactor(database): completely rewrote the db migration tooling (#452)
Corentin Thomasset7f7e5bffcbcf
diff --git a/.changeset/chubby-baboons-beg.md b/.changeset/chubby-baboons-beg.mdnew file mode 100644index 00000000..96a19c8a--- /dev/null+++ b/.changeset/chubby-baboons-beg.md@@ -0,0 +1,5 @@+---+"@papra/app-server": minor+---++Completely rewrote the migration mechanismdiff --git a/apps/papra-server/migrations/0000_initial_schema_setup.sql b/apps/papra-server/migrations/0000_initial_schema_setup.sqlindex 0d0d6344..cb8c5e35 100644--- a/apps/papra-server/migrations/0000_initial_schema_setup.sql+++ b/apps/papra-server/migrations/0000_initial_schema_setup.sql@@ -1,172 +1,172 @@-CREATE TABLE `documents` (- `id` text PRIMARY KEY NOT NULL,- `created_at` integer NOT NULL,- `updated_at` integer NOT NULL,- `is_deleted` integer DEFAULT false NOT NULL,- `deleted_at` integer,- `organization_id` text NOT NULL,- `created_by` text,- `deleted_by` text,- `original_name` text NOT NULL,- `original_size` integer DEFAULT 0 NOT NULL,- `original_storage_key` text NOT NULL,- `original_sha256_hash` text NOT NULL,- `name` text NOT NULL,- `mime_type` text NOT NULL,- `content` text DEFAULT '' NOT NULL,- FOREIGN KEY (`organization_id`) REFERENCES `organizations`(`id`) ON UPDATE cascade ON DELETE cascade,- FOREIGN KEY (`created_by`) REFERENCES `users`(`id`) ON UPDATE cascade ON DELETE set null,- FOREIGN KEY (`deleted_by`) REFERENCES `users`(`id`) ON UPDATE cascade ON DELETE set null+CREATE TABLE "documents" (+ "id" text PRIMARY KEY NOT NULL,+ "created_at" integer NOT NULL,+ "updated_at" integer NOT NULL,+ "is_deleted" integer DEFAULT false NOT NULL,+ "deleted_at" integer,+ "organization_id" text NOT NULL,+ "created_by" text,+ "deleted_by" text,+ "original_name" text NOT NULL,+ "original_size" integer DEFAULT 0 NOT NULL,+ "original_storage_key" text NOT NULL,+ "original_sha256_hash" text NOT NULL,+ "name" text NOT NULL,+ "mime_type" text NOT NULL,+ "content" text DEFAULT '' NOT NULL,+ FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON UPDATE cascade ON DELETE cascade,+ FOREIGN KEY ("created_by") REFERENCES "users"("id") ON UPDATE cascade ON DELETE set null,+ FOREIGN KEY ("deleted_by") REFERENCES "users"("id") ON UPDATE cascade ON DELETE set null);--> statement-breakpoint-CREATE INDEX `documents_organization_id_is_deleted_created_at_index` ON `documents` (`organization_id`,`is_deleted`,`created_at`);--> statement-breakpoint-CREATE INDEX `documents_organization_id_is_deleted_index` ON `documents` (`organization_id`,`is_deleted`);--> statement-breakpoint-CREATE UNIQUE INDEX `documents_organization_id_original_sha256_hash_unique` ON `documents` (`organization_id`,`original_sha256_hash`);--> statement-breakpoint-CREATE INDEX `documents_original_sha256_hash_index` ON `documents` (`original_sha256_hash`);--> statement-breakpoint-CREATE INDEX `documents_organization_id_size_index` ON `documents` (`organization_id`,`original_size`);--> statement-breakpoint-CREATE TABLE `organization_invitations` (- `id` text PRIMARY KEY NOT NULL,- `created_at` integer NOT NULL,- `updated_at` integer NOT NULL,- `organization_id` text NOT NULL,- `email` text NOT NULL,- `role` text,- `status` text NOT NULL,- `expires_at` integer NOT NULL,- `inviter_id` text NOT NULL,- FOREIGN KEY (`organization_id`) REFERENCES `organizations`(`id`) ON UPDATE cascade ON DELETE cascade,- FOREIGN KEY (`inviter_id`) REFERENCES `users`(`id`) ON UPDATE cascade ON DELETE cascade+CREATE INDEX "documents_organization_id_is_deleted_created_at_index" ON "documents" ("organization_id","is_deleted","created_at");--> statement-breakpoint+CREATE INDEX "documents_organization_id_is_deleted_index" ON "documents" ("organization_id","is_deleted");--> statement-breakpoint+CREATE UNIQUE INDEX "documents_organization_id_original_sha256_hash_unique" ON "documents" ("organization_id","original_sha256_hash");--> statement-breakpoint+CREATE INDEX "documents_original_sha256_hash_index" ON "documents" ("original_sha256_hash");--> statement-breakpoint+CREATE INDEX "documents_organization_id_size_index" ON "documents" ("organization_id","original_size");--> statement-breakpoint+CREATE TABLE "organization_invitations" (+ "id" text PRIMARY KEY NOT NULL,+ "created_at" integer NOT NULL,+ "updated_at" integer NOT NULL,+ "organization_id" text NOT NULL,+ "email" text NOT NULL,+ "role" text,+ "status" text NOT NULL,+ "expires_at" integer NOT NULL,+ "inviter_id" text NOT NULL,+ FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON UPDATE cascade ON DELETE cascade,+ FOREIGN KEY ("inviter_id") REFERENCES "users"("id") ON UPDATE cascade ON DELETE cascade);--> statement-breakpoint-CREATE TABLE `organization_members` (- `id` text PRIMARY KEY NOT NULL,- `created_at` integer NOT NULL,- `updated_at` integer NOT NULL,- `organization_id` text NOT NULL,- `user_id` text NOT NULL,- `role` text NOT NULL,- FOREIGN KEY (`organization_id`) REFERENCES `organizations`(`id`) ON UPDATE cascade ON DELETE cascade,- FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE cascade ON DELETE cascade+CREATE TABLE "organization_members" (+ "id" text PRIMARY KEY NOT NULL,+ "created_at" integer NOT NULL,+ "updated_at" integer NOT NULL,+ "organization_id" text NOT NULL,+ "user_id" text NOT NULL,+ "role" text NOT NULL,+ FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON UPDATE cascade ON DELETE cascade,+ FOREIGN KEY ("user_id") REFERENCES "users"("id") ON UPDATE cascade ON DELETE cascade);--> statement-breakpoint-CREATE UNIQUE INDEX `organization_members_user_organization_unique` ON `organization_members` (`organization_id`,`user_id`);--> statement-breakpoint-CREATE TABLE `organizations` (- `id` text PRIMARY KEY NOT NULL,- `created_at` integer NOT NULL,- `updated_at` integer NOT NULL,- `name` text NOT NULL,- `customer_id` text+CREATE UNIQUE INDEX "organization_members_user_organization_unique" ON "organization_members" ("organization_id","user_id");--> statement-breakpoint+CREATE TABLE "organizations" (+ "id" text PRIMARY KEY NOT NULL,+ "created_at" integer NOT NULL,+ "updated_at" integer NOT NULL,+ "name" text NOT NULL,+ "customer_id" text);--> statement-breakpoint-CREATE TABLE `user_roles` (- `id` text PRIMARY KEY NOT NULL,- `created_at` integer NOT NULL,- `updated_at` integer NOT NULL,- `user_id` text NOT NULL,- `role` text NOT NULL,- FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE cascade ON DELETE cascade+CREATE TABLE "user_roles" (+ "id" text PRIMARY KEY NOT NULL,+ "created_at" integer NOT NULL,+ "updated_at" integer NOT NULL,+ "user_id" text NOT NULL,+ "role" text NOT NULL,+ FOREIGN KEY ("user_id") REFERENCES "users"("id") ON UPDATE cascade ON DELETE cascade);--> statement-breakpoint-CREATE INDEX `user_roles_role_index` ON `user_roles` (`role`);--> statement-breakpoint-CREATE UNIQUE INDEX `user_roles_user_id_role_unique_index` ON `user_roles` (`user_id`,`role`);--> statement-breakpoint-CREATE TABLE `documents_tags` (- `document_id` text NOT NULL,- `tag_id` text NOT NULL,- PRIMARY KEY(`document_id`, `tag_id`),- FOREIGN KEY (`document_id`) REFERENCES `documents`(`id`) ON UPDATE cascade ON DELETE cascade,- FOREIGN KEY (`tag_id`) REFERENCES `tags`(`id`) ON UPDATE cascade ON DELETE cascade+CREATE INDEX "user_roles_role_index" ON "user_roles" ("role");--> statement-breakpoint+CREATE UNIQUE INDEX "user_roles_user_id_role_unique_index" ON "user_roles" ("user_id","role");--> statement-breakpoint+CREATE TABLE "documents_tags" (+ "document_id" text NOT NULL,+ "tag_id" text NOT NULL,+ PRIMARY KEY("document_id", "tag_id"),+ FOREIGN KEY ("document_id") REFERENCES "documents"("id") ON UPDATE cascade ON DELETE cascade,+ FOREIGN KEY ("tag_id") REFERENCES "tags"("id") ON UPDATE cascade ON DELETE cascade);--> statement-breakpoint-CREATE TABLE `tags` (- `id` text PRIMARY KEY NOT NULL,- `created_at` integer NOT NULL,- `updated_at` integer NOT NULL,- `organization_id` text NOT NULL,- `name` text NOT NULL,- `color` text NOT NULL,- `description` text,- FOREIGN KEY (`organization_id`) REFERENCES `organizations`(`id`) ON UPDATE cascade ON DELETE cascade+CREATE TABLE "tags" (+ "id" text PRIMARY KEY NOT NULL,+ "created_at" integer NOT NULL,+ "updated_at" integer NOT NULL,+ "organization_id" text NOT NULL,+ "name" text NOT NULL,+ "color" text NOT NULL,+ "description" text,+ FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON UPDATE cascade ON DELETE cascade);--> statement-breakpoint-CREATE UNIQUE INDEX `tags_organization_id_name_unique` ON `tags` (`organization_id`,`name`);--> statement-breakpoint-CREATE TABLE `users` (- `id` text PRIMARY KEY NOT NULL,- `created_at` integer NOT NULL,- `updated_at` integer NOT NULL,- `email` text NOT NULL,- `email_verified` integer DEFAULT false NOT NULL,- `name` text,- `image` text,- `max_organization_count` integer+CREATE UNIQUE INDEX "tags_organization_id_name_unique" ON "tags" ("organization_id","name");--> statement-breakpoint+CREATE TABLE "users" (+ "id" text PRIMARY KEY NOT NULL,+ "created_at" integer NOT NULL,+ "updated_at" integer NOT NULL,+ "email" text NOT NULL,+ "email_verified" integer DEFAULT false NOT NULL,+ "name" text,+ "image" text,+ "max_organization_count" integer);--> statement-breakpoint-CREATE UNIQUE INDEX `users_email_unique` ON `users` (`email`);--> statement-breakpoint-CREATE INDEX `users_email_index` ON `users` (`email`);--> statement-breakpoint-CREATE TABLE `auth_accounts` (- `id` text PRIMARY KEY NOT NULL,- `created_at` integer NOT NULL,- `updated_at` integer NOT NULL,- `user_id` text,- `account_id` text NOT NULL,- `provider_id` text NOT NULL,- `access_token` text,- `refresh_token` text,- `access_token_expires_at` integer,- `refresh_token_expires_at` integer,- `scope` text,- `id_token` text,- `password` text,- FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE cascade ON DELETE cascade+CREATE UNIQUE INDEX "users_email_unique" ON "users" ("email");--> statement-breakpoint+CREATE INDEX "users_email_index" ON "users" ("email");--> statement-breakpoint+CREATE TABLE "auth_accounts" (+ "id" text PRIMARY KEY NOT NULL,+ "created_at" integer NOT NULL,+ "updated_at" integer NOT NULL,+ "user_id" text,+ "account_id" text NOT NULL,+ "provider_id" text NOT NULL,+ "access_token" text,+ "refresh_token" text,+ "access_token_expires_at" integer,+ "refresh_token_expires_at" integer,+ "scope" text,+ "id_token" text,+ "password" text,+ FOREIGN KEY ("user_id") REFERENCES "users"("id") ON UPDATE cascade ON DELETE cascade);--> statement-breakpoint-CREATE TABLE `auth_sessions` (- `id` text PRIMARY KEY NOT NULL,- `created_at` integer NOT NULL,- `updated_at` integer NOT NULL,- `token` text NOT NULL,- `user_id` text,- `expires_at` integer NOT NULL,- `ip_address` text,- `user_agent` text,- `active_organization_id` text,- FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE cascade ON DELETE cascade,- FOREIGN KEY (`active_organization_id`) REFERENCES `organizations`(`id`) ON UPDATE cascade ON DELETE set null+CREATE TABLE "auth_sessions" (+ "id" text PRIMARY KEY NOT NULL,+ "created_at" integer NOT NULL,+ "updated_at" integer NOT NULL,+ "token" text NOT NULL,+ "user_id" text,+ "expires_at" integer NOT NULL,+ "ip_address" text,+ "user_agent" text,+ "active_organization_id" text,+ FOREIGN KEY ("user_id") REFERENCES "users"("id") ON UPDATE cascade ON DELETE cascade,+ FOREIGN KEY ("active_organization_id") REFERENCES "organizations"("id") ON UPDATE cascade ON DELETE set null);--> statement-breakpoint-CREATE INDEX `auth_sessions_token_index` ON `auth_sessions` (`token`);--> statement-breakpoint-CREATE TABLE `auth_verifications` (- `id` text PRIMARY KEY NOT NULL,- `created_at` integer NOT NULL,- `updated_at` integer NOT NULL,- `identifier` text NOT NULL,- `value` text NOT NULL,- `expires_at` integer NOT NULL+CREATE INDEX "auth_sessions_token_index" ON "auth_sessions" ("token");--> statement-breakpoint+CREATE TABLE "auth_verifications" (+ "id" text PRIMARY KEY NOT NULL,+ "created_at" integer NOT NULL,+ "updated_at" integer NOT NULL,+ "identifier" text NOT NULL,+ "value" text NOT NULL,+ "expires_at" integer NOT NULL);--> statement-breakpoint-CREATE INDEX `auth_verifications_identifier_index` ON `auth_verifications` (`identifier`);--> statement-breakpoint-CREATE TABLE `intake_emails` (- `id` text PRIMARY KEY NOT NULL,- `created_at` integer NOT NULL,- `updated_at` integer NOT NULL,- `email_address` text NOT NULL,- `organization_id` text NOT NULL,- `allowed_origins` text DEFAULT '[]' NOT NULL,- `is_enabled` integer DEFAULT true NOT NULL,- FOREIGN KEY (`organization_id`) REFERENCES `organizations`(`id`) ON UPDATE cascade ON DELETE cascade+CREATE INDEX "auth_verifications_identifier_index" ON "auth_verifications" ("identifier");--> statement-breakpoint+CREATE TABLE "intake_emails" (+ "id" text PRIMARY KEY NOT NULL,+ "created_at" integer NOT NULL,+ "updated_at" integer NOT NULL,+ "email_address" text NOT NULL,+ "organization_id" text NOT NULL,+ "allowed_origins" text DEFAULT '[]' NOT NULL,+ "is_enabled" integer DEFAULT true NOT NULL,+ FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON UPDATE cascade ON DELETE cascade);--> statement-breakpoint-CREATE UNIQUE INDEX `intake_emails_email_address_unique` ON `intake_emails` (`email_address`);--> statement-breakpoint-CREATE TABLE `organization_subscriptions` (- `id` text PRIMARY KEY NOT NULL,- `customer_id` text NOT NULL,- `organization_id` text NOT NULL,- `plan_id` text NOT NULL,- `status` text NOT NULL,- `seats_count` integer NOT NULL,- `current_period_end` integer NOT NULL,- `current_period_start` integer NOT NULL,- `cancel_at_period_end` integer DEFAULT false NOT NULL,- `created_at` integer NOT NULL,- `updated_at` integer NOT NULL,- FOREIGN KEY (`organization_id`) REFERENCES `organizations`(`id`) ON UPDATE cascade ON DELETE cascade+CREATE UNIQUE INDEX "intake_emails_email_address_unique" ON "intake_emails" ("email_address");--> statement-breakpoint+CREATE TABLE "organization_subscriptions" (+ "id" text PRIMARY KEY NOT NULL,+ "customer_id" text NOT NULL,+ "organization_id" text NOT NULL,+ "plan_id" text NOT NULL,+ "status" text NOT NULL,+ "seats_count" integer NOT NULL,+ "current_period_end" integer NOT NULL,+ "current_period_start" integer NOT NULL,+ "cancel_at_period_end" integer DEFAULT false NOT NULL,+ "created_at" integer NOT NULL,+ "updated_at" integer NOT NULL,+ FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON UPDATE cascade ON DELETE cascade);diff --git a/apps/papra-server/migrations/0002_tagging_rules.sql b/apps/papra-server/migrations/0002_tagging_rules.sqlindex 38828e9e..9257b320 100644--- a/apps/papra-server/migrations/0002_tagging_rules.sql+++ b/apps/papra-server/migrations/0002_tagging_rules.sql@@ -1,32 +1,32 @@-CREATE TABLE `tagging_rule_actions` (- `id` text PRIMARY KEY NOT NULL,- `created_at` integer NOT NULL,- `updated_at` integer NOT NULL,- `tagging_rule_id` text NOT NULL,- `tag_id` text NOT NULL,- FOREIGN KEY (`tagging_rule_id`) REFERENCES `tagging_rules`(`id`) ON UPDATE cascade ON DELETE cascade,- FOREIGN KEY (`tag_id`) REFERENCES `tags`(`id`) ON UPDATE cascade ON DELETE cascade+CREATE TABLE "tagging_rule_actions" (+ "id" text PRIMARY KEY NOT NULL,+ "created_at" integer NOT NULL,+ "updated_at" integer NOT NULL,+ "tagging_rule_id" text NOT NULL,+ "tag_id" text NOT NULL,+ FOREIGN KEY ("tagging_rule_id") REFERENCES "tagging_rules"("id") ON UPDATE cascade ON DELETE cascade,+ FOREIGN KEY ("tag_id") REFERENCES "tags"("id") ON UPDATE cascade ON DELETE cascade);--> statement-breakpoint-CREATE TABLE `tagging_rule_conditions` (- `id` text PRIMARY KEY NOT NULL,- `created_at` integer NOT NULL,- `updated_at` integer NOT NULL,- `tagging_rule_id` text NOT NULL,- `field` text NOT NULL,- `operator` text NOT NULL,- `value` text NOT NULL,- `is_case_sensitive` integer DEFAULT false NOT NULL,- FOREIGN KEY (`tagging_rule_id`) REFERENCES `tagging_rules`(`id`) ON UPDATE cascade ON DELETE cascade+CREATE TABLE "tagging_rule_conditions" (+ "id" text PRIMARY KEY NOT NULL,+ "created_at" integer NOT NULL,+ "updated_at" integer NOT NULL,+ "tagging_rule_id" text NOT NULL,+ "field" text NOT NULL,+ "operator" text NOT NULL,+ "value" text NOT NULL,+ "is_case_sensitive" integer DEFAULT false NOT NULL,+ FOREIGN KEY ("tagging_rule_id") REFERENCES "tagging_rules"("id") ON UPDATE cascade ON DELETE cascade);--> statement-breakpoint-CREATE TABLE `tagging_rules` (- `id` text PRIMARY KEY NOT NULL,- `created_at` integer NOT NULL,- `updated_at` integer NOT NULL,- `organization_id` text NOT NULL,- `name` text NOT NULL,- `description` text,- `enabled` integer DEFAULT true NOT NULL,- FOREIGN KEY (`organization_id`) REFERENCES `organizations`(`id`) ON UPDATE cascade ON DELETE cascade+CREATE TABLE "tagging_rules" (+ "id" text PRIMARY KEY NOT NULL,+ "created_at" integer NOT NULL,+ "updated_at" integer NOT NULL,+ "organization_id" text NOT NULL,+ "name" text NOT NULL,+ "description" text,+ "enabled" integer DEFAULT true NOT NULL,+ FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON UPDATE cascade ON DELETE cascade);diff --git a/apps/papra-server/migrations/0003_api-keys.sql b/apps/papra-server/migrations/0003_api-keys.sqlindex 0aaadbdb..1747a892 100644--- a/apps/papra-server/migrations/0003_api-keys.sql+++ b/apps/papra-server/migrations/0003_api-keys.sql@@ -1,24 +1,24 @@-CREATE TABLE `api_key_organizations` (- `api_key_id` text NOT NULL,- `organization_member_id` text NOT NULL,- FOREIGN KEY (`api_key_id`) REFERENCES `api_keys`(`id`) ON UPDATE cascade ON DELETE cascade,- FOREIGN KEY (`organization_member_id`) REFERENCES `organization_members`(`id`) ON UPDATE cascade ON DELETE cascade+CREATE TABLE "api_key_organizations" (+ "api_key_id" text NOT NULL,+ "organization_member_id" text NOT NULL,+ FOREIGN KEY ("api_key_id") REFERENCES "api_keys"("id") ON UPDATE cascade ON DELETE cascade,+ FOREIGN KEY ("organization_member_id") REFERENCES "organization_members"("id") ON UPDATE cascade ON DELETE cascade);--> statement-breakpoint-CREATE TABLE `api_keys` (- `id` text PRIMARY KEY NOT NULL,- `created_at` integer NOT NULL,- `updated_at` integer NOT NULL,- `name` text NOT NULL,- `key_hash` text NOT NULL,- `prefix` text NOT NULL,- `user_id` text NOT NULL,- `last_used_at` integer,- `expires_at` integer,- `permissions` text DEFAULT '[]' NOT NULL,- `all_organizations` integer DEFAULT false NOT NULL,- FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE cascade ON DELETE cascade+CREATE TABLE "api_keys" (+ "id" text PRIMARY KEY NOT NULL,+ "created_at" integer NOT NULL,+ "updated_at" integer NOT NULL,+ "name" text NOT NULL,+ "key_hash" text NOT NULL,+ "prefix" text NOT NULL,+ "user_id" text NOT NULL,+ "last_used_at" integer,+ "expires_at" integer,+ "permissions" text DEFAULT '[]' NOT NULL,+ "all_organizations" integer DEFAULT false NOT NULL,+ FOREIGN KEY ("user_id") REFERENCES "users"("id") ON UPDATE cascade ON DELETE cascade);--> statement-breakpoint-CREATE UNIQUE INDEX `api_keys_key_hash_unique` ON `api_keys` (`key_hash`);--> statement-breakpoint-CREATE INDEX `key_hash_index` ON `api_keys` (`key_hash`);\ No newline at end of file+CREATE UNIQUE INDEX "api_keys_key_hash_unique" ON "api_keys" ("key_hash");--> statement-breakpoint+CREATE INDEX "key_hash_index" ON "api_keys" ("key_hash");\ No newline at end of filediff --git a/apps/papra-server/migrations/0004_organizations-webhooks.sql b/apps/papra-server/migrations/0004_organizations-webhooks.sqlindex 6082e103..a9a50f9b 100644--- a/apps/papra-server/migrations/0004_organizations-webhooks.sql+++ b/apps/papra-server/migrations/0004_organizations-webhooks.sql@@ -1,35 +1,35 @@-CREATE TABLE `webhook_deliveries` (- `id` text PRIMARY KEY NOT NULL,- `created_at` integer NOT NULL,- `updated_at` integer NOT NULL,- `webhook_id` text NOT NULL,- `event_name` text NOT NULL,- `request_payload` text NOT NULL,- `response_payload` text NOT NULL,- `response_status` integer NOT NULL,- FOREIGN KEY (`webhook_id`) REFERENCES `webhooks`(`id`) ON UPDATE cascade ON DELETE cascade+CREATE TABLE "webhook_deliveries" (+ "id" text PRIMARY KEY NOT NULL,+ "created_at" integer NOT NULL,+ "updated_at" integer NOT NULL,+ "webhook_id" text NOT NULL,+ "event_name" text NOT NULL,+ "request_payload" text NOT NULL,+ "response_payload" text NOT NULL,+ "response_status" integer NOT NULL,+ FOREIGN KEY ("webhook_id") REFERENCES "webhooks"("id") ON UPDATE cascade ON DELETE cascade);--> statement-breakpoint-CREATE TABLE `webhook_events` (- `id` text PRIMARY KEY NOT NULL,- `created_at` integer NOT NULL,- `updated_at` integer NOT NULL,- `webhook_id` text NOT NULL,- `event_name` text NOT NULL,- FOREIGN KEY (`webhook_id`) REFERENCES `webhooks`(`id`) ON UPDATE cascade ON DELETE cascade+CREATE TABLE "webhook_events" (+ "id" text PRIMARY KEY NOT NULL,+ "created_at" integer NOT NULL,+ "updated_at" integer NOT NULL,+ "webhook_id" text NOT NULL,+ "event_name" text NOT NULL,+ FOREIGN KEY ("webhook_id") REFERENCES "webhooks"("id") ON UPDATE cascade ON DELETE cascade);--> statement-breakpoint-CREATE UNIQUE INDEX `webhook_events_webhook_id_event_name_unique` ON `webhook_events` (`webhook_id`,`event_name`);--> statement-breakpoint-CREATE TABLE `webhooks` (- `id` text PRIMARY KEY NOT NULL,- `created_at` integer NOT NULL,- `updated_at` integer NOT NULL,- `name` text NOT NULL,- `url` text NOT NULL,- `secret` text,- `enabled` integer DEFAULT true NOT NULL,- `created_by` text,- `organization_id` text,- FOREIGN KEY (`created_by`) REFERENCES `users`(`id`) ON UPDATE cascade ON DELETE set null,- FOREIGN KEY (`organization_id`) REFERENCES `organizations`(`id`) ON UPDATE cascade ON DELETE cascade+CREATE UNIQUE INDEX "webhook_events_webhook_id_event_name_unique" ON "webhook_events" ("webhook_id","event_name");--> statement-breakpoint+CREATE TABLE "webhooks" (+ "id" text PRIMARY KEY NOT NULL,+ "created_at" integer NOT NULL,+ "updated_at" integer NOT NULL,+ "name" text NOT NULL,+ "url" text NOT NULL,+ "secret" text,+ "enabled" integer DEFAULT true NOT NULL,+ "created_by" text,+ "organization_id" text,+ FOREIGN KEY ("created_by") REFERENCES "users"("id") ON UPDATE cascade ON DELETE set null,+ FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON UPDATE cascade ON DELETE cascade);diff --git a/apps/papra-server/migrations/0005_organizations-invitations-improvement.sql b/apps/papra-server/migrations/0005_organizations-invitations-improvement.sqlindex 53cd9eaf..76830392 100644--- a/apps/papra-server/migrations/0005_organizations-invitations-improvement.sql+++ b/apps/papra-server/migrations/0005_organizations-invitations-improvement.sql@@ -1,4 +1,4 @@-ALTER TABLE `organization_invitations` ALTER COLUMN "role" TO "role" text NOT NULL;--> statement-breakpoint-CREATE UNIQUE INDEX `organization_invitations_organization_email_unique` ON `organization_invitations` (`organization_id`,`email`);--> statement-breakpoint-ALTER TABLE `organization_invitations` ALTER COLUMN "status" TO "status" text NOT NULL DEFAULT 'pending';\ No newline at end of file+ALTER TABLE "organization_invitations" ALTER COLUMN "role" TO "role" text NOT NULL;--> statement-breakpoint+CREATE UNIQUE INDEX "organization_invitations_organization_email_unique" ON "organization_invitations" ("organization_id","email");--> statement-breakpoint+ALTER TABLE "organization_invitations" ALTER COLUMN "status" TO "status" text NOT NULL DEFAULT 'pending';\ No newline at end of filediff --git a/apps/papra-server/migrations/0006_document-activity-log.sql b/apps/papra-server/migrations/0006_document-activity-log.sqlindex f41de3d9..a8fdebf8 100644--- a/apps/papra-server/migrations/0006_document-activity-log.sql+++ b/apps/papra-server/migrations/0006_document-activity-log.sql@@ -1,12 +1,12 @@-CREATE TABLE `document_activity_log` (- `id` text PRIMARY KEY NOT NULL,- `created_at` integer NOT NULL,- `document_id` text NOT NULL,- `event` text NOT NULL,- `event_data` text,- `user_id` text,- `tag_id` text,- FOREIGN KEY (`document_id`) REFERENCES `documents`(`id`) ON UPDATE cascade ON DELETE cascade,- FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE cascade ON DELETE no action,- FOREIGN KEY (`tag_id`) REFERENCES `tags`(`id`) ON UPDATE cascade ON DELETE no action+CREATE TABLE "document_activity_log" (+ "id" text PRIMARY KEY NOT NULL,+ "created_at" integer NOT NULL,+ "document_id" text NOT NULL,+ "event" text NOT NULL,+ "event_data" text,+ "user_id" text,+ "tag_id" text,+ FOREIGN KEY ("document_id") REFERENCES "documents"("id") ON UPDATE cascade ON DELETE cascade,+ FOREIGN KEY ("user_id") REFERENCES "users"("id") ON UPDATE cascade ON DELETE no action,+ FOREIGN KEY ("tag_id") REFERENCES "tags"("id") ON UPDATE cascade ON DELETE no action);diff --git a/apps/papra-server/migrations/0007_document-activity-log-on-delete-set-null.sql b/apps/papra-server/migrations/0007_document-activity-log-on-delete-set-null.sqlindex 42bab0b5..4ebf1cfc 100644--- a/apps/papra-server/migrations/0007_document-activity-log-on-delete-set-null.sql+++ b/apps/papra-server/migrations/0007_document-activity-log-on-delete-set-null.sql@@ -1,18 +1,18 @@PRAGMA foreign_keys=OFF;--> statement-breakpoint-CREATE TABLE `__new_document_activity_log` (- `id` text PRIMARY KEY NOT NULL,- `created_at` integer NOT NULL,- `document_id` text NOT NULL,- `event` text NOT NULL,- `event_data` text,- `user_id` text,- `tag_id` text,- FOREIGN KEY (`document_id`) REFERENCES `documents`(`id`) ON UPDATE cascade ON DELETE cascade,- FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE cascade ON DELETE set null,- FOREIGN KEY (`tag_id`) REFERENCES `tags`(`id`) ON UPDATE cascade ON DELETE set null+CREATE TABLE "__new_document_activity_log" (+ "id" text PRIMARY KEY NOT NULL,+ "created_at" integer NOT NULL,+ "document_id" text NOT NULL,+ "event" text NOT NULL,+ "event_data" text,+ "user_id" text,+ "tag_id" text,+ FOREIGN KEY ("document_id") REFERENCES "documents"("id") ON UPDATE cascade ON DELETE cascade,+ FOREIGN KEY ("user_id") REFERENCES "users"("id") ON UPDATE cascade ON DELETE set null,+ FOREIGN KEY ("tag_id") REFERENCES "tags"("id") ON UPDATE cascade ON DELETE set null);--> statement-breakpoint-INSERT INTO `__new_document_activity_log`("id", "created_at", "document_id", "event", "event_data", "user_id", "tag_id") SELECT "id", "created_at", "document_id", "event", "event_data", "user_id", "tag_id" FROM `document_activity_log`;--> statement-breakpoint-DROP TABLE `document_activity_log`;--> statement-breakpoint-ALTER TABLE `__new_document_activity_log` RENAME TO `document_activity_log`;--> statement-breakpoint+INSERT INTO "__new_document_activity_log"("id", "created_at", "document_id", "event", "event_data", "user_id", "tag_id") SELECT "id", "created_at", "document_id", "event", "event_data", "user_id", "tag_id" FROM "document_activity_log";--> statement-breakpoint+DROP TABLE "document_activity_log";--> statement-breakpoint+ALTER TABLE "__new_document_activity_log" RENAME TO "document_activity_log";--> statement-breakpointPRAGMA foreign_keys=ON;\ No newline at end of filediff --git a/apps/papra-server/package.json b/apps/papra-server/package.jsonindex 9b0a72fa..e3f20979 100644--- a/apps/papra-server/package.json+++ b/apps/papra-server/package.json@@ -18,8 +18,9 @@"test": "vitest run","test:watch": "vitest watch","typecheck": "tsc --noEmit",- "migrate:up": "tsx --env-file-if-exists=.env src/scripts/migrate-up.script.ts",+ "migrate:up": "tsx --env-file-if-exists=.env src/scripts/migrate-up.script.ts | crowlog-pretty","migrate:push": "drizzle-kit push",+ "migrate:create": "sh -c 'drizzle-kit generate --name \"$1\" && tsx --env-file-if-exists=.env src/scripts/create-migration.ts \"$1\" | crowlog-pretty' --","db:studio": "drizzle-kit studio","clean:dist": "rm -rf dist","clean:db": "rm db.sqlite",@@ -85,6 +86,7 @@"@vitest/coverage-v8": "catalog:","esbuild": "^0.24.2","eslint": "catalog:",+ "magicast": "^0.3.5","memfs": "^4.17.2","typescript": "catalog:","vitest": "catalog:"diff --git a/apps/papra-server/src/migrations/list/0001-initial-schema-setup.migration.test.ts b/apps/papra-server/src/migrations/list/0001-initial-schema-setup.migration.test.tsnew file mode 100644index 00000000..8df34205--- /dev/null+++ b/apps/papra-server/src/migrations/list/0001-initial-schema-setup.migration.test.ts@@ -0,0 +1,51 @@+import { sql } from 'drizzle-orm';+import { describe, expect, test } from 'vitest';+import { setupDatabase } from '../../modules/app/database/database';+import { initialSchemaSetupMigration } from './0001-initial-schema-setup.migration';++describe('0001-initial-schema-setup migration', () => {+ describe('initialSchemaSetupMigration', () => {+ test('the up setup some default tables', async () => {+ const { db } = setupDatabase({ url: ':memory:' });+ await initialSchemaSetupMigration.up({ db });++ const { rows: existingTables } = await db.run(sql`SELECT name FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'`);++ expect(existingTables.map(({ name }) => name)).to.eql([+ 'documents',+ 'documents_organization_id_is_deleted_created_at_index',+ 'documents_organization_id_is_deleted_index',+ 'documents_organization_id_original_sha256_hash_unique',+ 'documents_original_sha256_hash_index',+ 'documents_organization_id_size_index',+ 'organization_invitations',+ 'organization_members',+ 'organization_members_user_organization_unique',+ 'organizations',+ 'user_roles',+ 'user_roles_role_index',+ 'user_roles_user_id_role_unique_index',+ 'documents_tags',+ 'tags',+ 'tags_organization_id_name_unique',+ 'users',+ 'users_email_unique',+ 'users_email_index',+ 'auth_accounts',+ 'auth_sessions',+ 'auth_sessions_token_index',+ 'auth_verifications',+ 'auth_verifications_identifier_index',+ 'intake_emails',+ 'intake_emails_email_address_unique',+ 'organization_subscriptions',+ ]);++ await initialSchemaSetupMigration.down({ db });++ const { rows: existingTablesAfterDown } = await db.run(sql`SELECT name FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'`);++ expect(existingTablesAfterDown.map(({ name }) => name)).to.eql([]);+ });+ });+});diff --git a/apps/papra-server/src/migrations/list/0001-initial-schema-setup.migration.ts b/apps/papra-server/src/migrations/list/0001-initial-schema-setup.migration.tsnew file mode 100644index 00000000..1ff777f5--- /dev/null+++ b/apps/papra-server/src/migrations/list/0001-initial-schema-setup.migration.ts@@ -0,0 +1,220 @@+import type { Migration } from '../migrations.types';+import { sql } from 'drizzle-orm';++export const initialSchemaSetupMigration = {+ name: 'initial-schema-setup',+ description: 'Creation of the base tables for the application',++ up: async ({ db }) => {+ await db.batch([+ db.run(sql`+ CREATE TABLE IF NOT EXISTS "documents" (+ "id" text PRIMARY KEY NOT NULL,+ "created_at" integer NOT NULL,+ "updated_at" integer NOT NULL,+ "is_deleted" integer DEFAULT false NOT NULL,+ "deleted_at" integer,+ "organization_id" text NOT NULL,+ "created_by" text,+ "deleted_by" text,+ "original_name" text NOT NULL,+ "original_size" integer DEFAULT 0 NOT NULL,+ "original_storage_key" text NOT NULL,+ "original_sha256_hash" text NOT NULL,+ "name" text NOT NULL,+ "mime_type" text NOT NULL,+ "content" text DEFAULT '' NOT NULL,+ FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON UPDATE cascade ON DELETE cascade,+ FOREIGN KEY ("created_by") REFERENCES "users"("id") ON UPDATE cascade ON DELETE set null,+ FOREIGN KEY ("deleted_by") REFERENCES "users"("id") ON UPDATE cascade ON DELETE set null+ );+ `),++ db.run(sql`CREATE INDEX IF NOT EXISTS "documents_organization_id_is_deleted_created_at_index" ON "documents" ("organization_id","is_deleted","created_at");`),+ db.run(sql`CREATE INDEX IF NOT EXISTS "documents_organization_id_is_deleted_index" ON "documents" ("organization_id","is_deleted");`),+ db.run(sql`CREATE UNIQUE INDEX IF NOT EXISTS "documents_organization_id_original_sha256_hash_unique" ON "documents" ("organization_id","original_sha256_hash");`),+ db.run(sql`CREATE INDEX IF NOT EXISTS "documents_original_sha256_hash_index" ON "documents" ("original_sha256_hash");`),+ db.run(sql`CREATE INDEX IF NOT EXISTS "documents_organization_id_size_index" ON "documents" ("organization_id","original_size");`),+ db.run(sql`+ CREATE TABLE IF NOT EXISTS "organization_invitations" (+ "id" text PRIMARY KEY NOT NULL,+ "created_at" integer NOT NULL,+ "updated_at" integer NOT NULL,+ "organization_id" text NOT NULL,+ "email" text NOT NULL,+ "role" text,+ "status" text NOT NULL,+ "expires_at" integer NOT NULL,+ "inviter_id" text NOT NULL,+ FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON UPDATE cascade ON DELETE cascade,+ FOREIGN KEY ("inviter_id") REFERENCES "users"("id") ON UPDATE cascade ON DELETE cascade+ );+ `),++ db.run(sql`CREATE TABLE IF NOT EXISTS "organization_members" (+ "id" text PRIMARY KEY NOT NULL,+ "created_at" integer NOT NULL,+ "updated_at" integer NOT NULL,+ "organization_id" text NOT NULL,+ "user_id" text NOT NULL,+ "role" text NOT NULL,+ FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON UPDATE cascade ON DELETE cascade,+ FOREIGN KEY ("user_id") REFERENCES "users"("id") ON UPDATE cascade ON DELETE cascade+);`),++ db.run(sql`CREATE UNIQUE INDEX IF NOT EXISTS "organization_members_user_organization_unique" ON "organization_members" ("organization_id","user_id");`),+ db.run(sql`CREATE TABLE IF NOT EXISTS "organizations" (+ "id" text PRIMARY KEY NOT NULL,+ "created_at" integer NOT NULL,+ "updated_at" integer NOT NULL,+ "name" text NOT NULL,+ "customer_id" text+);`),++ db.run(sql`CREATE TABLE IF NOT EXISTS "user_roles" (+ "id" text PRIMARY KEY NOT NULL,+ "created_at" integer NOT NULL,+ "updated_at" integer NOT NULL,+ "user_id" text NOT NULL,+ "role" text NOT NULL,+ FOREIGN KEY ("user_id") REFERENCES "users"("id") ON UPDATE cascade ON DELETE cascade+);`),++ db.run(sql`CREATE INDEX IF NOT EXISTS "user_roles_role_index" ON "user_roles" ("role");`),+ db.run(sql`CREATE UNIQUE INDEX IF NOT EXISTS "user_roles_user_id_role_unique_index" ON "user_roles" ("user_id","role");`),+ db.run(sql`CREATE TABLE IF NOT EXISTS "documents_tags" (+ "document_id" text NOT NULL,+ "tag_id" text NOT NULL,+ PRIMARY KEY("document_id", "tag_id"),+ FOREIGN KEY ("document_id") REFERENCES "documents"("id") ON UPDATE cascade ON DELETE cascade,+ FOREIGN KEY ("tag_id") REFERENCES "tags"("id") ON UPDATE cascade ON DELETE cascade+);`),++ db.run(sql`CREATE TABLE IF NOT EXISTS "tags" (+ "id" text PRIMARY KEY NOT NULL,+ "created_at" integer NOT NULL,+ "updated_at" integer NOT NULL,+ "organization_id" text NOT NULL,+ "name" text NOT NULL,+ "color" text NOT NULL,+ "description" text,+ FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON UPDATE cascade ON DELETE cascade+);`),++ db.run(sql`CREATE UNIQUE INDEX IF NOT EXISTS "tags_organization_id_name_unique" ON "tags" ("organization_id","name");`),+ db.run(sql`+ CREATE TABLE IF NOT EXISTS "users" (+ "id" text PRIMARY KEY NOT NULL,+ "created_at" integer NOT NULL,+ "updated_at" integer NOT NULL,+ "email" text NOT NULL,+ "email_verified" integer DEFAULT false NOT NULL,+ "name" text,+ "image" text,+ "max_organization_count" integer+ );+ `),++ db.run(sql`CREATE UNIQUE INDEX IF NOT EXISTS "users_email_unique" ON "users" ("email");`),+ db.run(sql`CREATE INDEX IF NOT EXISTS "users_email_index" ON "users" ("email");`),+ db.run(sql`CREATE TABLE IF NOT EXISTS "auth_accounts" (+ "id" text PRIMARY KEY NOT NULL,+ "created_at" integer NOT NULL,+ "updated_at" integer NOT NULL,+ "user_id" text,+ "account_id" text NOT NULL,+ "provider_id" text NOT NULL,+ "access_token" text,+ "refresh_token" text,+ "access_token_expires_at" integer,+ "refresh_token_expires_at" integer,+ "scope" text,+ "id_token" text,+ "password" text,+ FOREIGN KEY ("user_id") REFERENCES "users"("id") ON UPDATE cascade ON DELETE cascade+);`),++ db.run(sql`CREATE TABLE IF NOT EXISTS "auth_sessions" (+ "id" text PRIMARY KEY NOT NULL,+ "created_at" integer NOT NULL,+ "updated_at" integer NOT NULL,+ "token" text NOT NULL,+ "user_id" text,+ "expires_at" integer NOT NULL,+ "ip_address" text,+ "user_agent" text,+ "active_organization_id" text,+ FOREIGN KEY ("user_id") REFERENCES "users"("id") ON UPDATE cascade ON DELETE cascade,+ FOREIGN KEY ("active_organization_id") REFERENCES "organizations"("id") ON UPDATE cascade ON DELETE set null+);`),++ db.run(sql`CREATE INDEX IF NOT EXISTS "auth_sessions_token_index" ON "auth_sessions" ("token");`),+ db.run(sql`CREATE TABLE IF NOT EXISTS "auth_verifications" (+ "id" text PRIMARY KEY NOT NULL,+ "created_at" integer NOT NULL,+ "updated_at" integer NOT NULL,+ "identifier" text NOT NULL,+ "value" text NOT NULL,+ "expires_at" integer NOT NULL+);`),++ db.run(sql`CREATE INDEX IF NOT EXISTS "auth_verifications_identifier_index" ON "auth_verifications" ("identifier");`),+ db.run(sql`CREATE TABLE IF NOT EXISTS "intake_emails" (+ "id" text PRIMARY KEY NOT NULL,+ "created_at" integer NOT NULL,+ "updated_at" integer NOT NULL,+ "email_address" text NOT NULL,+ "organization_id" text NOT NULL,+ "allowed_origins" text DEFAULT '[]' NOT NULL,+ "is_enabled" integer DEFAULT true NOT NULL,+ FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON UPDATE cascade ON DELETE cascade+);`),++ db.run(sql`CREATE UNIQUE INDEX IF NOT EXISTS "intake_emails_email_address_unique" ON "intake_emails" ("email_address");`),+ db.run(sql`CREATE TABLE IF NOT EXISTS "organization_subscriptions" (+ "id" text PRIMARY KEY NOT NULL,+ "customer_id" text NOT NULL,+ "organization_id" text NOT NULL,+ "plan_id" text NOT NULL,+ "status" text NOT NULL,+ "seats_count" integer NOT NULL,+ "current_period_end" integer NOT NULL,+ "current_period_start" integer NOT NULL,+ "cancel_at_period_end" integer DEFAULT false NOT NULL,+ "created_at" integer NOT NULL,+ "updated_at" integer NOT NULL,+ FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON UPDATE cascade ON DELETE cascade+);`),+ ]);+ },++ down: async ({ db }) => {+ await db.batch([+ // Tables+ db.run(sql`DROP TABLE IF EXISTS "organization_subscriptions";`),+ db.run(sql`DROP TABLE IF EXISTS "intake_emails";`),+ db.run(sql`DROP TABLE IF EXISTS "auth_verifications";`),+ db.run(sql`DROP TABLE IF EXISTS "auth_sessions";`),+ db.run(sql`DROP TABLE IF EXISTS "auth_accounts";`),+ db.run(sql`DROP TABLE IF EXISTS "tags";`),+ db.run(sql`DROP TABLE IF EXISTS "documents_tags";`),+ db.run(sql`DROP TABLE IF EXISTS "user_roles";`),+ db.run(sql`DROP TABLE IF EXISTS "organizations";`),+ db.run(sql`DROP TABLE IF EXISTS "organization_members";`),+ db.run(sql`DROP TABLE IF EXISTS "organization_invitations";`),+ db.run(sql`DROP TABLE IF EXISTS "documents";`),+ db.run(sql`DROP TABLE IF EXISTS "users";`),++ // // Indexes+ db.run(sql`DROP INDEX IF EXISTS "documents_organization_id_is_deleted_created_at_index";`),+ db.run(sql`DROP INDEX IF EXISTS "documents_organization_id_is_deleted_index";`),+ db.run(sql`DROP INDEX IF EXISTS "documents_organization_id_original_sha256_hash_unique";`),+ db.run(sql`DROP INDEX IF EXISTS "documents_original_sha256_hash_index";`),+ db.run(sql`DROP INDEX IF EXISTS "documents_organization_id_size_index";`),+ db.run(sql`DROP INDEX IF EXISTS "user_roles_role_index";`),+ db.run(sql`DROP INDEX IF EXISTS "user_roles_user_id_role_unique_index";`),+ db.run(sql`DROP INDEX IF EXISTS "tags_organization_id_name_unique";`),+ db.run(sql`DROP INDEX IF EXISTS "users_email_unique";`),+ ]);+ },+} satisfies Migration;diff --git a/apps/papra-server/src/migrations/list/0002-documents-fts.migration.ts b/apps/papra-server/src/migrations/list/0002-documents-fts.migration.tsnew file mode 100644index 00000000..8f51e127--- /dev/null+++ b/apps/papra-server/src/migrations/list/0002-documents-fts.migration.ts@@ -0,0 +1,37 @@+import type { Migration } from '../migrations.types';+import { sql } from 'drizzle-orm';++export const documentsFtsMigration = {+ name: 'documents-fts',++ up: async ({ db }) => {+ await db.batch([+ db.run(sql`CREATE VIRTUAL TABLE IF NOT EXISTS documents_fts USING fts5(id UNINDEXED, name, original_name, content, prefix='2 3 4')`),+ db.run(sql`INSERT INTO documents_fts(id, name, original_name, content) SELECT id, name, original_name, content FROM documents`),+ db.run(sql`+ CREATE TRIGGER IF NOT EXISTS trigger_documents_fts_insert AFTER INSERT ON documents BEGIN+ INSERT INTO documents_fts(id, name, original_name, content) VALUES (new.id, new.name, new.original_name, new.content);+ END+ `),+ db.run(sql`+ CREATE TRIGGER IF NOT EXISTS trigger_documents_fts_update AFTER UPDATE ON documents BEGIN+ UPDATE documents_fts SET name = new.name, original_name = new.original_name, content = new.content WHERE id = new.id;+ END+ `),+ db.run(sql`+ CREATE TRIGGER IF NOT EXISTS trigger_documents_fts_delete AFTER DELETE ON documents BEGIN+ DELETE FROM documents_fts WHERE id = old.id;+ END+ `),+ ]);+ },++ down: async ({ db }) => {+ await db.batch([+ db.run(sql`DROP TRIGGER IF EXISTS trigger_documents_fts_insert`),+ db.run(sql`DROP TRIGGER IF EXISTS trigger_documents_fts_update`),+ db.run(sql`DROP TRIGGER IF EXISTS trigger_documents_fts_delete`),+ db.run(sql`DROP TABLE IF EXISTS documents_fts`),+ ]);+ },+} satisfies Migration;diff --git a/apps/papra-server/src/migrations/list/0003-tagging-rules.migration.ts b/apps/papra-server/src/migrations/list/0003-tagging-rules.migration.tsnew file mode 100644index 00000000..90649de5--- /dev/null+++ b/apps/papra-server/src/migrations/list/0003-tagging-rules.migration.ts@@ -0,0 +1,57 @@+import type { Migration } from '../migrations.types';+import { sql } from 'drizzle-orm';++export const taggingRulesMigration = {+ name: 'tagging-rules',++ up: async ({ db }) => {+ await db.batch([+ db.run(sql`+ CREATE TABLE IF NOT EXISTS "tagging_rule_actions" (+ "id" text PRIMARY KEY NOT NULL,+ "created_at" integer NOT NULL,+ "updated_at" integer NOT NULL,+ "tagging_rule_id" text NOT NULL,+ "tag_id" text NOT NULL,+ FOREIGN KEY ("tagging_rule_id") REFERENCES "tagging_rules"("id") ON UPDATE cascade ON DELETE cascade,+ FOREIGN KEY ("tag_id") REFERENCES "tags"("id") ON UPDATE cascade ON DELETE cascade+ );+ `),++ db.run(sql`+ CREATE TABLE IF NOT EXISTS "tagging_rule_conditions" (+ "id" text PRIMARY KEY NOT NULL,+ "created_at" integer NOT NULL,+ "updated_at" integer NOT NULL,+ "tagging_rule_id" text NOT NULL,+ "field" text NOT NULL,+ "operator" text NOT NULL,+ "value" text NOT NULL,+ "is_case_sensitive" integer DEFAULT false NOT NULL,+ FOREIGN KEY ("tagging_rule_id") REFERENCES "tagging_rules"("id") ON UPDATE cascade ON DELETE cascade+ );+ `),++ db.run(sql`+ CREATE TABLE IF NOT EXISTS "tagging_rules" (+ "id" text PRIMARY KEY NOT NULL,+ "created_at" integer NOT NULL,+ "updated_at" integer NOT NULL,+ "organization_id" text NOT NULL,+ "name" text NOT NULL,+ "description" text,+ "enabled" integer DEFAULT true NOT NULL,+ FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON UPDATE cascade ON DELETE cascade+ );+ `),+ ]);+ },++ down: async ({ db }) => {+ await db.batch([+ db.run(sql`DROP TABLE IF EXISTS "tagging_rule_actions"`),+ db.run(sql`DROP TABLE IF EXISTS "tagging_rule_conditions"`),+ db.run(sql`DROP TABLE IF EXISTS "tagging_rules"`),+ ]);+ },+} satisfies Migration;diff --git a/apps/papra-server/src/migrations/list/0004-api-keys.migration.ts b/apps/papra-server/src/migrations/list/0004-api-keys.migration.tsnew file mode 100644index 00000000..6c72f8e3--- /dev/null+++ b/apps/papra-server/src/migrations/list/0004-api-keys.migration.ts@@ -0,0 +1,46 @@+import type { Migration } from '../migrations.types';+import { sql } from 'drizzle-orm';++export const apiKeysMigration = {+ name: 'api-keys',++ up: async ({ db }) => {+ await db.batch([+ db.run(sql`+ CREATE TABLE IF NOT EXISTS "api_key_organizations" (+ "api_key_id" text NOT NULL,+ "organization_member_id" text NOT NULL,+ FOREIGN KEY ("api_key_id") REFERENCES "api_keys"("id") ON UPDATE cascade ON DELETE cascade,+ FOREIGN KEY ("organization_member_id") REFERENCES "organization_members"("id") ON UPDATE cascade ON DELETE cascade+ );+ `),+ db.run(sql`+ CREATE TABLE IF NOT EXISTS "api_keys" (+ "id" text PRIMARY KEY NOT NULL,+ "created_at" integer NOT NULL,+ "updated_at" integer NOT NULL,+ "name" text NOT NULL,+ "key_hash" text NOT NULL,+ "prefix" text NOT NULL,+ "user_id" text NOT NULL,+ "last_used_at" integer,+ "expires_at" integer,+ "permissions" text DEFAULT '[]' NOT NULL,+ "all_organizations" integer DEFAULT false NOT NULL,+ FOREIGN KEY ("user_id") REFERENCES "users"("id") ON UPDATE cascade ON DELETE cascade+ );+ `),+ db.run(sql`CREATE UNIQUE INDEX IF NOT EXISTS "api_keys_key_hash_unique" ON "api_keys" ("key_hash")`),+ db.run(sql`CREATE INDEX IF NOT EXISTS "key_hash_index" ON "api_keys" ("key_hash")`),+ ]);+ },++ down: async ({ db }) => {+ await db.batch([+ db.run(sql`DROP TABLE IF EXISTS "api_key_organizations"`),+ db.run(sql`DROP TABLE IF EXISTS "api_keys"`),+ db.run(sql`DROP INDEX IF EXISTS "api_keys_key_hash_unique"`),+ db.run(sql`DROP INDEX IF EXISTS "key_hash_index"`),+ ]);+ },+} satisfies Migration;diff --git a/apps/papra-server/src/migrations/list/0005-organizations-webhooks.migration.ts b/apps/papra-server/src/migrations/list/0005-organizations-webhooks.migration.tsnew file mode 100644index 00000000..27a3f59f--- /dev/null+++ b/apps/papra-server/src/migrations/list/0005-organizations-webhooks.migration.ts@@ -0,0 +1,62 @@+import type { Migration } from '../migrations.types';+import { sql } from 'drizzle-orm';++export const organizationsWebhooksMigration = {+ name: 'organizations-webhooks',++ up: async ({ db }) => {+ await db.batch([+ db.run(sql`+ CREATE TABLE IF NOT EXISTS "webhook_deliveries" (+ "id" text PRIMARY KEY NOT NULL,+ "created_at" integer NOT NULL,+ "updated_at" integer NOT NULL,+ "webhook_id" text NOT NULL,+ "event_name" text NOT NULL,+ "request_payload" text NOT NULL,+ "response_payload" text NOT NULL,+ "response_status" integer NOT NULL,+ FOREIGN KEY ("webhook_id") REFERENCES "webhooks"("id") ON UPDATE cascade ON DELETE cascade+ );+ `),+ db.run(sql`+ CREATE TABLE IF NOT EXISTS "webhook_events" (+ "id" text PRIMARY KEY NOT NULL,+ "created_at" integer NOT NULL,+ "updated_at" integer NOT NULL,+ "webhook_id" text NOT NULL,+ "event_name" text NOT NULL,+ FOREIGN KEY ("webhook_id") REFERENCES "webhooks"("id") ON UPDATE cascade ON DELETE cascade+ );+ `),++ db.run(sql`CREATE UNIQUE INDEX IF NOT EXISTS "webhook_events_webhook_id_event_name_unique" ON "webhook_events" ("webhook_id","event_name")`),++ db.run(sql`+ CREATE TABLE IF NOT EXISTS "webhooks" (+ "id" text PRIMARY KEY NOT NULL,+ "created_at" integer NOT NULL,+ "updated_at" integer NOT NULL,+ "name" text NOT NULL,+ "url" text NOT NULL,+ "secret" text,+ "enabled" integer DEFAULT true NOT NULL,+ "created_by" text,+ "organization_id" text,+ FOREIGN KEY ("created_by") REFERENCES "users"("id") ON UPDATE cascade ON DELETE set null,+ FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON UPDATE cascade ON DELETE cascade+ );+ `),++ ]);+ },++ down: async ({ db }) => {+ await db.batch([+ db.run(sql`DROP TABLE IF EXISTS "webhook_deliveries"`),+ db.run(sql`DROP TABLE IF EXISTS "webhook_events"`),+ db.run(sql`DROP INDEX IF EXISTS "webhook_events_webhook_id_event_name_unique"`),+ db.run(sql`DROP TABLE IF EXISTS "webhooks"`),+ ]);+ },+} satisfies Migration;diff --git a/apps/papra-server/src/migrations/list/0006-organizations-invitations-improvement.migration.ts b/apps/papra-server/src/migrations/list/0006-organizations-invitations-improvement.migration.tsnew file mode 100644index 00000000..cf0f7532--- /dev/null+++ b/apps/papra-server/src/migrations/list/0006-organizations-invitations-improvement.migration.ts@@ -0,0 +1,22 @@+import type { Migration } from '../migrations.types';+import { sql } from 'drizzle-orm';++export const organizationsInvitationsImprovementMigration = {+ name: 'organizations-invitations-improvement',++ up: async ({ db }) => {+ await db.batch([+ db.run(sql`ALTER TABLE "organization_invitations" ALTER COLUMN "role" TO "role" text NOT NULL`),+ db.run(sql`CREATE UNIQUE INDEX IF NOT EXISTS "organization_invitations_organization_email_unique" ON "organization_invitations" ("organization_id","email")`),+ db.run(sql`ALTER TABLE "organization_invitations" ALTER COLUMN "status" TO "status" text NOT NULL DEFAULT 'pending'`),+ ]);+ },++ down: async ({ db }) => {+ await db.batch([+ db.run(sql`ALTER TABLE "organization_invitations" ALTER COLUMN "role" TO "role" text`),+ db.run(sql`DROP INDEX IF EXISTS "organization_invitations_organization_email_unique"`),+ db.run(sql`ALTER TABLE "organization_invitations" ALTER COLUMN "status" TO "status" text NOT NULL`),+ ]);+ },+} satisfies Migration;diff --git a/apps/papra-server/src/migrations/list/0007-document-activity-log.migration.ts b/apps/papra-server/src/migrations/list/0007-document-activity-log.migration.tsnew file mode 100644index 00000000..6bc8c348--- /dev/null+++ b/apps/papra-server/src/migrations/list/0007-document-activity-log.migration.ts@@ -0,0 +1,31 @@+import type { Migration } from '../migrations.types';+import { sql } from 'drizzle-orm';++export const documentActivityLogMigration = {+ name: 'document-activity-log',++ up: async ({ db }) => {+ await db.batch([+ db.run(sql`+ CREATE TABLE IF NOT EXISTS "document_activity_log" (+ "id" text PRIMARY KEY NOT NULL,+ "created_at" integer NOT NULL,+ "document_id" text NOT NULL,+ "event" text NOT NULL,+ "event_data" text,+ "user_id" text,+ "tag_id" text,+ FOREIGN KEY ("document_id") REFERENCES "documents"("id") ON UPDATE cascade ON DELETE cascade,+ FOREIGN KEY ("user_id") REFERENCES "users"("id") ON UPDATE cascade ON DELETE no action,+ FOREIGN KEY ("tag_id") REFERENCES "tags"("id") ON UPDATE cascade ON DELETE no action+ );+ `),+ ]);+ },++ down: async ({ db }) => {+ await db.batch([+ db.run(sql`DROP TABLE IF EXISTS "document_activity_log"`),+ ]);+ },+} satisfies Migration;diff --git a/apps/papra-server/src/migrations/list/0008-document-activity-log-on-delete-set-null.migration.ts b/apps/papra-server/src/migrations/list/0008-document-activity-log-on-delete-set-null.migration.tsnew file mode 100644index 00000000..f064fe02--- /dev/null+++ b/apps/papra-server/src/migrations/list/0008-document-activity-log-on-delete-set-null.migration.ts@@ -0,0 +1,56 @@+import type { Migration } from '../migrations.types';+import { sql } from 'drizzle-orm';++export const documentActivityLogOnDeleteSetNullMigration = {+ name: 'document-activity-log-on-delete-set-null',++ up: async ({ db }) => {+ await db.batch([+ db.run(sql`PRAGMA foreign_keys=OFF`),+ db.run(sql`+ CREATE TABLE "__new_document_activity_log" (+ "id" text PRIMARY KEY NOT NULL,+ "created_at" integer NOT NULL,+ "document_id" text NOT NULL,+ "event" text NOT NULL,+ "event_data" text,+ "user_id" text,+ "tag_id" text,+ FOREIGN KEY ("document_id") REFERENCES "documents"("id") ON UPDATE cascade ON DELETE cascade,+ FOREIGN KEY ("user_id") REFERENCES "users"("id") ON UPDATE cascade ON DELETE set null,+ FOREIGN KEY ("tag_id") REFERENCES "tags"("id") ON UPDATE cascade ON DELETE set null+ );+ `),+ db.run(sql`+ INSERT INTO "__new_document_activity_log"("id", "created_at", "document_id", "event", "event_data", "user_id", "tag_id") SELECT "id", "created_at", "document_id", "event", "event_data", "user_id", "tag_id" FROM "document_activity_log";+ `),+ db.run(sql`DROP TABLE IF EXISTS "document_activity_log"`),+ db.run(sql`ALTER TABLE "__new_document_activity_log" RENAME TO "document_activity_log"`),+ db.run(sql`PRAGMA foreign_keys=ON`),+ ]);+ },++ down: async ({ db }) => {+ await db.batch([+ db.run(sql`PRAGMA foreign_keys=OFF`),+ db.run(sql`+ CREATE TABLE "__restore_document_activity_log" (+ "id" text PRIMARY KEY NOT NULL,+ "created_at" integer NOT NULL,+ "document_id" text NOT NULL,+ "event" text NOT NULL,+ "event_data" text,+ "user_id" text,+ "tag_id" text,+ FOREIGN KEY ("document_id") REFERENCES "documents"("id") ON UPDATE cascade ON DELETE cascade,+ FOREIGN KEY ("user_id") REFERENCES "users"("id") ON UPDATE cascade ON DELETE no action,+ FOREIGN KEY ("tag_id") REFERENCES "tags"("id") ON UPDATE cascade ON DELETE no action+ );+ `),+ db.run(sql`INSERT INTO "__restore_document_activity_log"("id", "created_at", "document_id", "event", "event_data", "user_id", "tag_id") SELECT "id", "created_at", "document_id", "event", "event_data", "user_id", "tag_id" FROM "document_activity_log";`),+ db.run(sql`DROP TABLE IF EXISTS "document_activity_log"`),+ db.run(sql`ALTER TABLE "__restore_document_activity_log" RENAME TO "document_activity_log"`),+ db.run(sql`PRAGMA foreign_keys=ON`),+ ]);+ },+} satisfies Migration;diff --git a/apps/papra-server/src/migrations/list/0009-drop-legacy-migrations.migration.ts b/apps/papra-server/src/migrations/list/0009-drop-legacy-migrations.migration.tsnew file mode 100644index 00000000..06361271--- /dev/null+++ b/apps/papra-server/src/migrations/list/0009-drop-legacy-migrations.migration.ts@@ -0,0 +1,12 @@+import type { Migration } from '../migrations.types';+import { sql } from 'drizzle-orm';++export const dropLegacyMigrationsMigration = {+ name: 'drop-legacy-migrations',+ description: 'Drop the legacy migrations table as it is not used anymore',++ up: async ({ db }) => {+ await db.run(sql`DROP TABLE IF EXISTS "__drizzle_migrations"`);+ },++} satisfies Migration;diff --git a/apps/papra-server/src/migrations/migration.tables.ts b/apps/papra-server/src/migrations/migration.tables.tsnew file mode 100644index 00000000..bc3364db--- /dev/null+++ b/apps/papra-server/src/migrations/migration.tables.ts@@ -0,0 +1,14 @@+import { index, integer, sqliteTable, text } from 'drizzle-orm/sqlite-core';++export const migrationsTable = sqliteTable(+ 'migrations',+ {+ id: integer('id').primaryKey({ autoIncrement: true }),+ name: text('name').notNull(),+ runAt: integer('run_at', { mode: 'timestamp_ms' }).notNull().$default(() => new Date()),+ },+ t => [+ index('name_index').on(t.name),+ index('run_at_index').on(t.runAt),+ ],+);diff --git a/apps/papra-server/src/migrations/migrations.registry.test.ts b/apps/papra-server/src/migrations/migrations.registry.test.tsnew file mode 100644index 00000000..c3101856--- /dev/null+++ b/apps/papra-server/src/migrations/migrations.registry.test.ts@@ -0,0 +1,169 @@+import type { Migration } from './migrations.types';+import { join } from 'node:path';+import { sql } from 'drizzle-orm';+import { migrate } from 'drizzle-orm/libsql/migrator';+import { describe, expect, test } from 'vitest';+import { setupDatabase } from '../modules/app/database/database';+import { serializeSchema } from '../modules/app/database/database.test-utils';+import { getRootDirPath } from '../modules/shared/path';+import { migrations } from './migrations.registry';+import { rollbackLastAppliedMigration, runMigrations } from './migrations.usecases';++describe('migrations registry', () => {+ describe('migrations', () => {+ test('each migration should have a unique name', () => {+ const migrationNames = migrations.map(m => m.name);+ const duplicateMigrationNames = migrationNames.filter(name => migrationNames.filter(n => n === name).length > 1);++ expect(duplicateMigrationNames).to.eql([], 'Each migration should have a unique name');+ });++ test('each migration should have a non empty name', () => {+ const migrationNames = migrations.map(m => m.name);+ const emptyMigrationNames = migrationNames.filter(name => name === '');++ expect(emptyMigrationNames).to.eql([], 'Each migration should have a non empty name');+ });++ test('all migrations must be able to be applied without error and the database should be in a consistent state', async () => {+ const { db } = setupDatabase({ url: ':memory:' });++ // This will throw if any migration is not able to be applied+ await runMigrations({ db, migrations });++ // check foreign keys are enabled+ const { rows } = await db.run(sql`pragma foreign_keys;`);+ expect(rows).to.eql([{ foreign_keys: 1 }]);+ });++ test('we can stop to any migration and still have a consistent database state', async () => {+ // Given like 3 migrations [A,B,C], creates [[A], [A,B], [A,B,C]]+ const migrationCombinations = migrations.map((m, i) => migrations.slice(0, i + 1));++ for (const migrationCombination of migrationCombinations) {+ const { db } = setupDatabase({ url: ':memory:' });+ await runMigrations({ db, migrations: migrationCombination });+ }+ });++ test('when we rollback to a previous migration, the database should be in the state of the previous migration', async () => {+ // Given like 3 migrations [A,B,C], creates [[A], [A,B], [A,B,C]]+ const migrationCombinations = migrations.map((m, i) => migrations.slice(0, i + 1));++ for (const [index, migrationCombination] of migrationCombinations.entries()) {+ const { db } = setupDatabase({ url: ':memory:' });+ const previousMigration = migrationCombinations[index - 1] ?? [] as Migration[];++ await runMigrations({ db, migrations: previousMigration });+ const previousDbState = await serializeSchema({ db });+ await runMigrations({ db, migrations: migrationCombination });+ await rollbackLastAppliedMigration({ db });++ const currentDbState = await serializeSchema({ db });++ expect(currentDbState).to.eql(previousDbState, `Downgrading from ${migrationCombination.at(-1)?.name ?? 'no migration'} should result in the same state as the previous migration`);+ }+ });++ test('regression test of the database state after running migrations, update the snapshot when the database state changes', async () => {+ const { db } = setupDatabase({ url: ':memory:' });++ await runMigrations({ db, migrations });++ expect(await serializeSchema({ db })).toMatchInlineSnapshot(`+ "CREATE UNIQUE INDEX "api_keys_key_hash_unique" ON "api_keys" ("key_hash");+ CREATE INDEX "auth_sessions_token_index" ON "auth_sessions" ("token");+ CREATE INDEX "auth_verifications_identifier_index" ON "auth_verifications" ("identifier");+ CREATE INDEX "documents_organization_id_is_deleted_created_at_index" ON "documents" ("organization_id","is_deleted","created_at");+ CREATE INDEX "documents_organization_id_is_deleted_index" ON "documents" ("organization_id","is_deleted");+ CREATE UNIQUE INDEX "documents_organization_id_original_sha256_hash_unique" ON "documents" ("organization_id","original_sha256_hash");+ CREATE INDEX "documents_organization_id_size_index" ON "documents" ("organization_id","original_size");+ CREATE INDEX "documents_original_sha256_hash_index" ON "documents" ("original_sha256_hash");+ CREATE UNIQUE INDEX "intake_emails_email_address_unique" ON "intake_emails" ("email_address");+ CREATE INDEX "key_hash_index" ON "api_keys" ("key_hash");+ CREATE INDEX migrations_name_index ON migrations (name);+ CREATE INDEX migrations_run_at_index ON migrations (run_at);+ CREATE UNIQUE INDEX "organization_invitations_organization_email_unique" ON "organization_invitations" ("organization_id","email");+ CREATE UNIQUE INDEX "organization_members_user_organization_unique" ON "organization_members" ("organization_id","user_id");+ CREATE UNIQUE INDEX "tags_organization_id_name_unique" ON "tags" ("organization_id","name");+ CREATE INDEX "user_roles_role_index" ON "user_roles" ("role");+ CREATE UNIQUE INDEX "user_roles_user_id_role_unique_index" ON "user_roles" ("user_id","role");+ CREATE INDEX "users_email_index" ON "users" ("email");+ CREATE UNIQUE INDEX "users_email_unique" ON "users" ("email");+ CREATE UNIQUE INDEX "webhook_events_webhook_id_event_name_unique" ON "webhook_events" ("webhook_id","event_name");+ CREATE TABLE "api_key_organizations" ( "api_key_id" text NOT NULL, "organization_member_id" text NOT NULL, FOREIGN KEY ("api_key_id") REFERENCES "api_keys"("id") ON UPDATE cascade ON DELETE cascade, FOREIGN KEY ("organization_member_id") REFERENCES "organization_members"("id") ON UPDATE cascade ON DELETE cascade );+ CREATE TABLE "api_keys" ( "id" text PRIMARY KEY NOT NULL, "created_at" integer NOT NULL, "updated_at" integer NOT NULL, "name" text NOT NULL, "key_hash" text NOT NULL, "prefix" text NOT NULL, "user_id" text NOT NULL, "last_used_at" integer, "expires_at" integer, "permissions" text DEFAULT '[]' NOT NULL, "all_organizations" integer DEFAULT false NOT NULL, FOREIGN KEY ("user_id") REFERENCES "users"("id") ON UPDATE cascade ON DELETE cascade );+ CREATE TABLE "auth_accounts" ( "id" text PRIMARY KEY NOT NULL, "created_at" integer NOT NULL, "updated_at" integer NOT NULL, "user_id" text, "account_id" text NOT NULL, "provider_id" text NOT NULL, "access_token" text, "refresh_token" text, "access_token_expires_at" integer, "refresh_token_expires_at" integer, "scope" text, "id_token" text, "password" text, FOREIGN KEY ("user_id") REFERENCES "users"("id") ON UPDATE cascade ON DELETE cascade );+ CREATE TABLE "auth_sessions" ( "id" text PRIMARY KEY NOT NULL, "created_at" integer NOT NULL, "updated_at" integer NOT NULL, "token" text NOT NULL, "user_id" text, "expires_at" integer NOT NULL, "ip_address" text, "user_agent" text, "active_organization_id" text, FOREIGN KEY ("user_id") REFERENCES "users"("id") ON UPDATE cascade ON DELETE cascade, FOREIGN KEY ("active_organization_id") REFERENCES "organizations"("id") ON UPDATE cascade ON DELETE set null );+ CREATE TABLE "auth_verifications" ( "id" text PRIMARY KEY NOT NULL, "created_at" integer NOT NULL, "updated_at" integer NOT NULL, "identifier" text NOT NULL, "value" text NOT NULL, "expires_at" integer NOT NULL );+ CREATE TABLE "document_activity_log" ( "id" text PRIMARY KEY NOT NULL, "created_at" integer NOT NULL, "document_id" text NOT NULL, "event" text NOT NULL, "event_data" text, "user_id" text, "tag_id" text, FOREIGN KEY ("document_id") REFERENCES "documents"("id") ON UPDATE cascade ON DELETE cascade, FOREIGN KEY ("user_id") REFERENCES "users"("id") ON UPDATE cascade ON DELETE set null, FOREIGN KEY ("tag_id") REFERENCES "tags"("id") ON UPDATE cascade ON DELETE set null );+ CREATE TABLE "documents" ( "id" text PRIMARY KEY NOT NULL, "created_at" integer NOT NULL, "updated_at" integer NOT NULL, "is_deleted" integer DEFAULT false NOT NULL, "deleted_at" integer, "organization_id" text NOT NULL, "created_by" text, "deleted_by" text, "original_name" text NOT NULL, "original_size" integer DEFAULT 0 NOT NULL, "original_storage_key" text NOT NULL, "original_sha256_hash" text NOT NULL, "name" text NOT NULL, "mime_type" text NOT NULL, "content" text DEFAULT '' NOT NULL, FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON UPDATE cascade ON DELETE cascade, FOREIGN KEY ("created_by") REFERENCES "users"("id") ON UPDATE cascade ON DELETE set null, FOREIGN KEY ("deleted_by") REFERENCES "users"("id") ON UPDATE cascade ON DELETE set null );+ CREATE VIRTUAL TABLE documents_fts USING fts5(id UNINDEXED, name, original_name, content, prefix='2 3 4');+ CREATE TABLE 'documents_fts_config'(k PRIMARY KEY, v) WITHOUT ROWID;+ CREATE TABLE 'documents_fts_content'(id INTEGER PRIMARY KEY, c0, c1, c2, c3);+ CREATE TABLE 'documents_fts_data'(id INTEGER PRIMARY KEY, block BLOB);+ CREATE TABLE 'documents_fts_docsize'(id INTEGER PRIMARY KEY, sz BLOB);+ CREATE TABLE 'documents_fts_idx'(segid, term, pgno, PRIMARY KEY(segid, term)) WITHOUT ROWID;+ CREATE TABLE "documents_tags" ( "document_id" text NOT NULL, "tag_id" text NOT NULL, PRIMARY KEY("document_id", "tag_id"), FOREIGN KEY ("document_id") REFERENCES "documents"("id") ON UPDATE cascade ON DELETE cascade, FOREIGN KEY ("tag_id") REFERENCES "tags"("id") ON UPDATE cascade ON DELETE cascade );+ CREATE TABLE "intake_emails" ( "id" text PRIMARY KEY NOT NULL, "created_at" integer NOT NULL, "updated_at" integer NOT NULL, "email_address" text NOT NULL, "organization_id" text NOT NULL, "allowed_origins" text DEFAULT '[]' NOT NULL, "is_enabled" integer DEFAULT true NOT NULL, FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON UPDATE cascade ON DELETE cascade );+ CREATE TABLE migrations (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, run_at INTEGER NOT NULL);+ CREATE TABLE "organization_invitations" ( "id" text PRIMARY KEY NOT NULL, "created_at" integer NOT NULL, "updated_at" integer NOT NULL, "organization_id" text NOT NULL, "email" text NOT NULL, "role" text NOT NULL, "status" text NOT NULL DEFAULT 'pending', "expires_at" integer NOT NULL, "inviter_id" text NOT NULL, FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON UPDATE cascade ON DELETE cascade, FOREIGN KEY ("inviter_id") REFERENCES "users"("id") ON UPDATE cascade ON DELETE cascade );+ CREATE TABLE "organization_members" ( "id" text PRIMARY KEY NOT NULL, "created_at" integer NOT NULL, "updated_at" integer NOT NULL, "organization_id" text NOT NULL, "user_id" text NOT NULL, "role" text NOT NULL, FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON UPDATE cascade ON DELETE cascade, FOREIGN KEY ("user_id") REFERENCES "users"("id") ON UPDATE cascade ON DELETE cascade );+ CREATE TABLE "organization_subscriptions" ( "id" text PRIMARY KEY NOT NULL, "customer_id" text NOT NULL, "organization_id" text NOT NULL, "plan_id" text NOT NULL, "status" text NOT NULL, "seats_count" integer NOT NULL, "current_period_end" integer NOT NULL, "current_period_start" integer NOT NULL, "cancel_at_period_end" integer DEFAULT false NOT NULL, "created_at" integer NOT NULL, "updated_at" integer NOT NULL, FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON UPDATE cascade ON DELETE cascade );+ CREATE TABLE "organizations" ( "id" text PRIMARY KEY NOT NULL, "created_at" integer NOT NULL, "updated_at" integer NOT NULL, "name" text NOT NULL, "customer_id" text );+ CREATE TABLE sqlite_sequence(name,seq);+ CREATE TABLE "tagging_rule_actions" ( "id" text PRIMARY KEY NOT NULL, "created_at" integer NOT NULL, "updated_at" integer NOT NULL, "tagging_rule_id" text NOT NULL, "tag_id" text NOT NULL, FOREIGN KEY ("tagging_rule_id") REFERENCES "tagging_rules"("id") ON UPDATE cascade ON DELETE cascade, FOREIGN KEY ("tag_id") REFERENCES "tags"("id") ON UPDATE cascade ON DELETE cascade );+ CREATE TABLE "tagging_rule_conditions" ( "id" text PRIMARY KEY NOT NULL, "created_at" integer NOT NULL, "updated_at" integer NOT NULL, "tagging_rule_id" text NOT NULL, "field" text NOT NULL, "operator" text NOT NULL, "value" text NOT NULL, "is_case_sensitive" integer DEFAULT false NOT NULL, FOREIGN KEY ("tagging_rule_id") REFERENCES "tagging_rules"("id") ON UPDATE cascade ON DELETE cascade );+ CREATE TABLE "tagging_rules" ( "id" text PRIMARY KEY NOT NULL, "created_at" integer NOT NULL, "updated_at" integer NOT NULL, "organization_id" text NOT NULL, "name" text NOT NULL, "description" text, "enabled" integer DEFAULT true NOT NULL, FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON UPDATE cascade ON DELETE cascade );+ CREATE TABLE "tags" ( "id" text PRIMARY KEY NOT NULL, "created_at" integer NOT NULL, "updated_at" integer NOT NULL, "organization_id" text NOT NULL, "name" text NOT NULL, "color" text NOT NULL, "description" text, FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON UPDATE cascade ON DELETE cascade );+ CREATE TABLE "user_roles" ( "id" text PRIMARY KEY NOT NULL, "created_at" integer NOT NULL, "updated_at" integer NOT NULL, "user_id" text NOT NULL, "role" text NOT NULL, FOREIGN KEY ("user_id") REFERENCES "users"("id") ON UPDATE cascade ON DELETE cascade );+ CREATE TABLE "users" ( "id" text PRIMARY KEY NOT NULL, "created_at" integer NOT NULL, "updated_at" integer NOT NULL, "email" text NOT NULL, "email_verified" integer DEFAULT false NOT NULL, "name" text, "image" text, "max_organization_count" integer );+ CREATE TABLE "webhook_deliveries" ( "id" text PRIMARY KEY NOT NULL, "created_at" integer NOT NULL, "updated_at" integer NOT NULL, "webhook_id" text NOT NULL, "event_name" text NOT NULL, "request_payload" text NOT NULL, "response_payload" text NOT NULL, "response_status" integer NOT NULL, FOREIGN KEY ("webhook_id") REFERENCES "webhooks"("id") ON UPDATE cascade ON DELETE cascade );+ CREATE TABLE "webhook_events" ( "id" text PRIMARY KEY NOT NULL, "created_at" integer NOT NULL, "updated_at" integer NOT NULL, "webhook_id" text NOT NULL, "event_name" text NOT NULL, FOREIGN KEY ("webhook_id") REFERENCES "webhooks"("id") ON UPDATE cascade ON DELETE cascade );+ CREATE TABLE "webhooks" ( "id" text PRIMARY KEY NOT NULL, "created_at" integer NOT NULL, "updated_at" integer NOT NULL, "name" text NOT NULL, "url" text NOT NULL, "secret" text, "enabled" integer DEFAULT true NOT NULL, "created_by" text, "organization_id" text, FOREIGN KEY ("created_by") REFERENCES "users"("id") ON UPDATE cascade ON DELETE set null, FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON UPDATE cascade ON DELETE cascade );+ CREATE TRIGGER trigger_documents_fts_delete AFTER DELETE ON documents BEGIN DELETE FROM documents_fts WHERE id = old.id; END;+ CREATE TRIGGER trigger_documents_fts_insert AFTER INSERT ON documents BEGIN INSERT INTO documents_fts(id, name, original_name, content) VALUES (new.id, new.name, new.original_name, new.content); END;+ CREATE TRIGGER trigger_documents_fts_update AFTER UPDATE ON documents BEGIN UPDATE documents_fts SET name = new.name, original_name = new.original_name, content = new.content WHERE id = new.id; END;"+ `);+ });++ // Maybe a bit fragile, but it's to try to enforce to have migrations fail-safe+ test('if for some reasons we drop the migrations table, we can reapply all migrations', async () => {+ const { db } = setupDatabase({ url: ':memory:' });++ await runMigrations({ db, migrations });++ const dbState = await serializeSchema({ db });++ await db.run(sql`DROP TABLE migrations`);+ await runMigrations({ db, migrations });++ expect(await serializeSchema({ db })).to.eq(dbState);+ });++ test('the new migrations system bring the database in the same state as the drizzle built-in migrations', async () => {+ const { db: drizzleDb } = setupDatabase({ url: ':memory:' });++ await migrate(drizzleDb, { migrationsFolder: join(getRootDirPath(), 'migrations') });++ const drizzleSchemaRaw = await serializeSchema({ db: drizzleDb });++ // Remove the migrations table from the schema+ const drizzleSchema = drizzleSchemaRaw.split('\n').filter(line => !line.startsWith('CREATE TABLE "__drizzle_migrations')).join('\n');++ const { db } = setupDatabase({ url: ':memory:' });++ await runMigrations({ db, migrations: migrations.slice(0, 8) });++ const papraSchemaRaw = await serializeSchema({ db });+ const papraSchema = papraSchemaRaw.split('\n').filter(line =>+ !line.startsWith('CREATE TABLE migrations')+ && !line.startsWith('CREATE INDEX migrations_')+ && !line.startsWith('CREATE TABLE sqlite_sequence(name,seq)'),++ ).join('\n');++ expect(papraSchema).to.eq(drizzleSchema);+ });+ });+});diff --git a/apps/papra-server/src/migrations/migrations.registry.ts b/apps/papra-server/src/migrations/migrations.registry.tsnew file mode 100644index 00000000..356c5bd5--- /dev/null+++ b/apps/papra-server/src/migrations/migrations.registry.ts@@ -0,0 +1,24 @@+import type { Migration } from './migrations.types';++import { initialSchemaSetupMigration } from './list/0001-initial-schema-setup.migration';+import { documentsFtsMigration } from './list/0002-documents-fts.migration';+import { taggingRulesMigration } from './list/0003-tagging-rules.migration';+import { apiKeysMigration } from './list/0004-api-keys.migration';+import { organizationsWebhooksMigration } from './list/0005-organizations-webhooks.migration';+import { organizationsInvitationsImprovementMigration } from './list/0006-organizations-invitations-improvement.migration';+import { documentActivityLogMigration } from './list/0007-document-activity-log.migration';+import { documentActivityLogOnDeleteSetNullMigration } from './list/0008-document-activity-log-on-delete-set-null.migration';++import { dropLegacyMigrationsMigration } from './list/0009-drop-legacy-migrations.migration';++export const migrations: Migration[] = [+ initialSchemaSetupMigration,+ documentsFtsMigration,+ taggingRulesMigration,+ apiKeysMigration,+ organizationsWebhooksMigration,+ organizationsInvitationsImprovementMigration,+ documentActivityLogMigration,+ documentActivityLogOnDeleteSetNullMigration,+ dropLegacyMigrationsMigration,+];diff --git a/apps/papra-server/src/migrations/migrations.repository.ts b/apps/papra-server/src/migrations/migrations.repository.tsnew file mode 100644index 00000000..3d22666d--- /dev/null+++ b/apps/papra-server/src/migrations/migrations.repository.ts@@ -0,0 +1,29 @@+import type { Database } from '../modules/app/database/database.types';+import { asc, eq, sql } from 'drizzle-orm';+import { migrationsTable } from './migration.tables';++export async function setupMigrationTableIfNotExists({ db }: { db: Database }) {+ await db.batch([+ db.run(sql`CREATE TABLE IF NOT EXISTS migrations (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, run_at INTEGER NOT NULL)`),+ db.run(sql`CREATE INDEX IF NOT EXISTS migrations_name_index ON migrations (name)`),+ db.run(sql`CREATE INDEX IF NOT EXISTS migrations_run_at_index ON migrations (run_at)`),+ ]);+}++export async function getMigrations({ db }: { db: Database }) {+ const migrations = await db.select().from(migrationsTable).orderBy(asc(migrationsTable.runAt));++ return { migrations };+}++export async function saveMigration({ db, migrationName, now = new Date() }: { db: Database; migrationName: string; now?: Date }) {+ await db.insert(migrationsTable).values({ name: migrationName, runAt: now });+}++export async function deleteMigration({ db, migrationName }: { db: Database; migrationName: string }) {+ await db.delete(migrationsTable).where(eq(migrationsTable.name, migrationName));+}++export async function deleteAllMigrations({ db }: { db: Database }) {+ await db.delete(migrationsTable);+}diff --git a/apps/papra-server/src/migrations/migrations.types.ts b/apps/papra-server/src/migrations/migrations.types.tsnew file mode 100644index 00000000..5c65a751--- /dev/null+++ b/apps/papra-server/src/migrations/migrations.types.ts@@ -0,0 +1,20 @@+import type { Database } from '../modules/app/database/database.types';++export type MigrationArguments = {+ db: Database;+};++export type Migration = {+ /**+ * The name of the migration. Must be unique.+ */+ name: string;++ /**+ * Optional description of the migration, serves to add more context to the migration for humans.+ */+ description?: string;++ up: (args: MigrationArguments) => Promise<unknown>;+ down?: (args: MigrationArguments) => Promise<unknown>;+};diff --git a/apps/papra-server/src/migrations/migrations.usecases.test.ts b/apps/papra-server/src/migrations/migrations.usecases.test.tsnew file mode 100644index 00000000..25a39d08--- /dev/null+++ b/apps/papra-server/src/migrations/migrations.usecases.test.ts@@ -0,0 +1,141 @@+import type { Migration } from './migrations.types';+import { sql } from 'drizzle-orm';+import { describe, expect, test } from 'vitest';+import { setupDatabase } from '../modules/app/database/database';+import { migrationsTable } from './migration.tables';+import { rollbackLastAppliedMigration, runMigrations } from './migrations.usecases';++const createTableUserMigration: Migration = {+ name: 'create-table-user',+ up: async ({ db }) => {+ await db.run(sql`CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL)`);+ },+ down: async ({ db }) => {+ await db.run(sql`DROP TABLE users`);+ },+};++const createTableOrganizationMigration: Migration = {+ name: 'create-table-organization',+ up: async ({ db }) => {+ await db.batch([+ db.run(sql`CREATE TABLE organizations (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL)`),+ db.run(sql`CREATE TABLE organization_members (id INTEGER PRIMARY KEY AUTOINCREMENT, organization_id INTEGER NOT NULL, user_id INTEGER NOT NULL, role TEXT NOT NULL, created_at INTEGER NOT NULL)`),+ ]);+ },+ down: async ({ db }) => {+ await db.batch([+ db.run(sql`DROP TABLE organizations`),+ db.run(sql`DROP TABLE organization_members`),+ ]);+ },+};++const createTableDocumentMigration: Migration = {+ name: 'create-table-document',+ up: async ({ db }) => {+ await db.batch([+ db.run(sql`CREATE TABLE documents (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, created_at INTEGER NOT NULL)`),+ ]);+ },+ down: async ({ db }) => {+ await db.run(sql`DROP TABLE documents`);+ },+};++describe('migrations usecases', () => {+ describe('runMigrations', () => {+ test('should run all migrations that are not already applied', async () => {+ const { db } = setupDatabase({ url: ':memory:' });++ const migrations = [createTableUserMigration, createTableOrganizationMigration];++ await runMigrations({ db, migrations });++ const migrationsInDb = await db.select().from(migrationsTable);++ expect(migrationsInDb.map(({ id, name }) => ({ id, name }))).to.eql([+ { id: 1, name: 'create-table-user' },+ { id: 2, name: 'create-table-organization' },+ ]);++ migrations.push(createTableDocumentMigration);++ await runMigrations({ db, migrations });++ const migrationsInDb2 = await db.select().from(migrationsTable);++ expect(migrationsInDb2.map(({ id, name }) => ({ id, name }))).to.eql([+ { id: 1, name: 'create-table-user' },+ { id: 2, name: 'create-table-organization' },+ { id: 3, name: 'create-table-document' },+ ]);++ const { rows: tables } = await db.run(sql`SELECT name FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'`);++ // Ensure all tables and indexes are created+ expect(tables.map(t => t.name)).to.eql([+ 'migrations',+ 'migrations_name_index',+ 'migrations_run_at_index',+ 'users',+ 'organizations',+ 'organization_members',+ 'documents',+ ]);+ });+ });++ describe('rollbackLastAppliedMigration', () => {+ test('the last migration down is called', async () => {+ const { db } = setupDatabase({ url: ':memory:' });++ const migrations = [createTableUserMigration, createTableDocumentMigration];++ await runMigrations({ db, migrations });++ const initialMigrations = await db.select().from(migrationsTable);++ expect(initialMigrations.map(({ id, name }) => ({ id, name }))).to.eql([+ { id: 1, name: 'create-table-user' },+ { id: 2, name: 'create-table-document' },+ ]);++ // Ensure the tables exists, no error is thrown+ await db.run(sql`SELECT * FROM users`);+ await db.run(sql`SELECT * FROM documents`);++ await rollbackLastAppliedMigration({ db, migrations });++ const migrationsInDb = await db.select().from(migrationsTable);++ expect(migrationsInDb.map(({ id, name }) => ({ id, name }))).to.eql([+ { id: 1, name: 'create-table-user' },+ ]);++ // Ensure the table document is dropped+ await db.run(sql`SELECT * FROM users`);+ await expect(db.run(sql`SELECT * FROM documents`)).rejects.toThrow();+ });++ test('when their is no migration to rollback, nothing is done', async () => {+ const { db } = setupDatabase({ url: ':memory:' });++ await rollbackLastAppliedMigration({ db });++ const migrationsInDb = await db.select().from(migrationsTable);++ expect(migrationsInDb).to.eql([]);+ });++ test('when the last migration in the database does not exist in the migrations list, an error is thrown', async () => {+ const { db } = setupDatabase({ url: ':memory:' });++ await runMigrations({ db, migrations: [createTableUserMigration] });++ await expect(+ rollbackLastAppliedMigration({ db, migrations: [] }),+ ).rejects.toThrow('Migration create-table-user not found');+ });+ });+});diff --git a/apps/papra-server/src/migrations/migrations.usecases.ts b/apps/papra-server/src/migrations/migrations.usecases.tsnew file mode 100644index 00000000..3eb6eee8--- /dev/null+++ b/apps/papra-server/src/migrations/migrations.usecases.ts@@ -0,0 +1,83 @@+import type { Database } from '../modules/app/database/database.types';+import type { Logger } from '../modules/shared/logger/logger';+import type { Migration } from './migrations.types';+import { safely } from '@corentinth/chisels';+import { createLogger } from '../modules/shared/logger/logger';+import { migrations as migrationsList } from './migrations.registry';+import { deleteMigration, getMigrations, saveMigration, setupMigrationTableIfNotExists } from './migrations.repository';++export async function runMigrations({ db, migrations = migrationsList, logger = createLogger({ namespace: 'migrations' }) }: { db: Database; migrations?: Migration[]; logger?: Logger }) {+ await setupMigrationTableIfNotExists({ db });++ if (migrations.length === 0) {+ logger.info('No migrations to run, skipping');+ return;+ }++ const { migrations: existingMigrations } = await getMigrations({ db });++ const migrationsToRun = migrations.filter(migration => !existingMigrations.some(m => m.name === migration.name));++ if (migrationsToRun.length === 0) {+ logger.info('All migrations already applied');+ return;+ }++ logger.debug({+ migrations: migrations.map(m => m.name),+ migrationsToRun: migrationsToRun.map(m => m.name),+ existingMigrations: existingMigrations.map(m => m.name),+ migrationsToRunCount: migrationsToRun.length,+ existingMigrationsCount: existingMigrations.length,+ }, 'Running migrations');++ for (const migration of migrationsToRun) {+ const [, error] = await safely(upMigration({ db, migration }));++ if (error) {+ logger.error({ error, migrationName: migration.name }, 'Failed to run migration');+ throw error;+ }++ logger.info({ migrationName: migration.name }, 'Migration run successfully');+ }++ logger.info('All migrations run successfully');+}++async function upMigration({ db, migration }: { db: Database; migration: Migration }) {+ const { name, up } = migration;++ await up({ db });+ await saveMigration({ db, migrationName: name });+}++export async function rollbackLastAppliedMigration({ db, migrations = migrationsList, logger = createLogger({ namespace: 'migrations' }) }: { db: Database; migrations?: Migration[]; logger?: Logger }) {+ await setupMigrationTableIfNotExists({ db });++ const { migrations: existingMigrations } = await getMigrations({ db });+ const lastMigrationInDb = existingMigrations[existingMigrations.length - 1];++ if (!lastMigrationInDb) {+ logger.info('No migrations to rollback');+ return;+ }++ const lastMigration = migrations.find(m => m.name === lastMigrationInDb.name);++ if (!lastMigration) {+ logger.error({ migrationName: lastMigrationInDb.name }, 'Migration in database not found in saved migrations');+ throw new Error(`Migration ${lastMigrationInDb.name} not found`);+ }++ await downMigration({ db, migration: lastMigration });++ logger.info({ migrationName: lastMigration.name }, 'Migration rolled back successfully');+}++async function downMigration({ db, migration }: { db: Database; migration: Migration }) {+ const { name, down } = migration;++ await down?.({ db });+ await deleteMigration({ db, migrationName: name });+}diff --git a/apps/papra-server/src/modules/app/database/database.services.ts b/apps/papra-server/src/modules/app/database/database.services.tsindex b563e3c3..7fcd1fd9 100644--- a/apps/papra-server/src/modules/app/database/database.services.ts+++ b/apps/papra-server/src/modules/app/database/database.services.ts@@ -1,19 +1,11 @@import type { Config } from '../../config/config.types';-import type { Database } from './database.types';-import { dirname, join } from 'node:path';-import { migrate } from 'drizzle-orm/libsql/migrator';+import { dirname } from 'node:path';import { ensureDirectoryExists } from '../../shared/fs/fs.services';import { createLogger } from '../../shared/logger/logger';-import { fileUrlToPath, getRootDirPath } from '../../shared/path';+import { fileUrlToPath } from '../../shared/path';const logger = createLogger({ namespace: 'database-services' });-export async function runMigrations({ db }: { db: Database }) {- const migrationsFolder = join(getRootDirPath(), 'migrations');-- await migrate(db, { migrationsFolder });-}-export async function ensureLocalDatabaseDirectoryExists({ config }: { config: Config }) {const { url } = config.database;diff --git a/apps/papra-server/src/modules/app/database/database.test-utils.test.ts b/apps/papra-server/src/modules/app/database/database.test-utils.test.tsnew file mode 100644index 00000000..7ec7238b--- /dev/null+++ b/apps/papra-server/src/modules/app/database/database.test-utils.test.ts@@ -0,0 +1,24 @@+import { sql } from 'drizzle-orm';+import { describe, expect, test } from 'vitest';+import { setupDatabase } from './database';+import { serializeSchema } from './database.test-utils';++describe('database-utils test', () => {+ describe('serializeSchema', () => {+ test('given a database with some tables, it should return the schema as a string, used for db state snapshot', async () => {+ const { db } = setupDatabase({ url: ':memory:' });+ await db.run(sql`CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT)`);+ await db.run(sql`CREATE INDEX idx_test_name ON test (name)`);+ await db.run(sql`CREATE VIEW test_view AS SELECT * FROM test`);+ await db.run(sql`CREATE TRIGGER test_trigger AFTER INSERT ON test BEGIN SELECT 1; END`);++ const schema = await serializeSchema({ db });+ expect(schema).toMatchInlineSnapshot(`+ "CREATE INDEX idx_test_name ON test (name);+ CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT);+ CREATE TRIGGER test_trigger AFTER INSERT ON test BEGIN SELECT 1; END;+ CREATE VIEW test_view AS SELECT * FROM test;"+ `);+ });+ });+});diff --git a/apps/papra-server/src/modules/app/database/database.test-utils.ts b/apps/papra-server/src/modules/app/database/database.test-utils.tsindex b6c5cbed..7399e050 100644--- a/apps/papra-server/src/modules/app/database/database.test-utils.ts+++ b/apps/papra-server/src/modules/app/database/database.test-utils.ts@@ -1,4 +1,6 @@import type { Database } from './database.types';+import { sql } from 'drizzle-orm';+import { runMigrations } from '../../../migrations/migrations.usecases';import { apiKeyOrganizationsTable, apiKeysTable } from '../../api-keys/api-keys.tables';import { documentsTable } from '../../documents/documents.table';import { intakeEmailsTable } from '../../intake-emails/intake-emails.tables';@@ -9,7 +11,6 @@ import { documentsTagsTable, tagsTable } from '../../tags/tags.table';import { usersTable } from '../../users/users.table';import { webhookDeliveriesTable, webhookEventsTable, webhooksTable } from '../../webhooks/webhooks.tables';import { setupDatabase } from './database';-import { runMigrations } from './database.services';export { createInMemoryDatabase, seedDatabase };@@ -60,3 +61,34 @@ async function seedDatabase({ db, ...seedRows }: { db: Database } & SeedTablesRo),);}++/*+PRAGMA encoding;+PRAGMA page_size;+PRAGMA auto_vacuum;+PRAGMA journal_mode; -- WAL is persistent+PRAGMA user_version;+PRAGMA application_id;++*/++export async function serializeSchema({ db }: { db: Database }) {+ const result = await db.batch([+ // db.run(sql`PRAGMA encoding`),+ // db.run(sql`PRAGMA page_size`),+ // db.run(sql`PRAGMA auto_vacuum`),+ // db.run(sql`PRAGMA journal_mode`),+ // db.run(sql`PRAGMA user_version`),+ // db.run(sql`PRAGMA application_id`),+ db.run(sql`SELECT sql FROM sqlite_schema WHERE sql IS NOT NULL AND type IN ('table','index','view','trigger') ORDER BY type, name`),+ ]);++ return Array+ .from(result.values())+ .flatMap(({ rows }) => rows.map(({ sql }) => minifyQuery(String(sql))))+ .join('\n');+}++function minifyQuery(query: string) {+ return `${query.replace(/\s+/g, ' ').trim().replace(/;$/, '')};`;+}diff --git a/apps/papra-server/src/scripts/commons/run-script.ts b/apps/papra-server/src/scripts/commons/run-script.tsindex 852686ef..918455c3 100644--- a/apps/papra-server/src/scripts/commons/run-script.ts+++ b/apps/papra-server/src/scripts/commons/run-script.ts@@ -7,9 +7,7 @@ import { ensureLocalDatabaseDirectoryExists } from '../../modules/app/database/dimport { parseConfig } from '../../modules/config/config';import { createLogger, wrapWithLoggerContext } from '../../modules/shared/logger/logger';-export { runScript };--async function runScript(+export async function runScriptWithDb({ scriptName }: { scriptName: string },fn: (args: { isDryRun: boolean; logger: Logger; db: Database; config: Config }) => Promise<void> | void,) {@@ -25,18 +23,32 @@ async function runScript(const { config } = await parseConfig({ env: process.env });await ensureLocalDatabaseDirectoryExists({ config });- const { db, client } = setupDatabase({ ...config.database });-- try {- logger.info('Script started');- await fn({ isDryRun, logger, db, config });- logger.info('Script finished');- } catch (error) {- logger.error({ error }, 'Script failed');- process.exit(1);- } finally {- client.close();- }+ const { db } = setupDatabase({ ...config.database });++ await executeScript({ logger, fn: async () => fn({ isDryRun, logger, db, config }) });},);}++export async function runScript(+ { scriptName }: { scriptName: string },+ fn: (args: { isDryRun: boolean; logger: Logger }) => Promise<void> | void,+) {+ const isDryRun = process.argv.includes('--dry-run');++ await wrapWithLoggerContext({ scriptName, isDryRun }, async () => {+ const logger = createLogger({ namespace: 'scripts' });++ await executeScript({ logger, fn: async () => fn({ isDryRun, logger }) });+ });+}++async function executeScript({ logger, fn }: { logger: Logger; fn: () => Promise<unknown> }) {+ try {+ await fn();+ logger.debug('Script finished');+ } catch (error) {+ logger.error({ error }, 'Script failed');+ process.exit(1);+ }+}diff --git a/apps/papra-server/src/scripts/create-migration.ts b/apps/papra-server/src/scripts/create-migration.tsnew file mode 100644index 00000000..32793f91--- /dev/null+++ b/apps/papra-server/src/scripts/create-migration.ts@@ -0,0 +1,79 @@+import fs from 'node:fs/promises';+import path from 'node:path';+import process from 'node:process';+import { camelCase, kebabCase } from 'lodash-es';+import { builders, loadFile, writeFile } from 'magicast';+import { runScript } from './commons/run-script';++const currentDirectory = import.meta.dirname;++const migrationsDirectory = path.join(currentDirectory, '..', 'migrations', 'list');++async function getLastMigrationFilePrefixNumber() {+ const migrations = await fs.readdir(migrationsDirectory);+ const lastMigrationFileName = migrations.filter(file => file.endsWith('.migration.ts')).toSorted().pop();++ if (lastMigrationFileName === undefined) {+ return 0;+ }++ const [, lastMigrationNumber] = lastMigrationFileName.match(/^(\d+)/) ?? [];+ return lastMigrationNumber === undefined ? 0 : Number.parseInt(lastMigrationNumber);+}++await runScript(+ { scriptName: 'create-migration' },+ async ({ logger }) => {+ const rawMigrationName = process.argv[2];++ if (rawMigrationName === undefined || rawMigrationName === '') {+ logger.error('Migration name is required, example: pnpm migrate:create <migration-name>');+ process.exit(1);+ }++ const migrationName = kebabCase(rawMigrationName);++ const lastMigrationPrefixNumber = await getLastMigrationFilePrefixNumber();+ const prefixNumber = (lastMigrationPrefixNumber + 1).toString().padStart(4, '0');++ const fileNameWithoutExtension = `${prefixNumber}-${migrationName}.migration`;+ const fileName = `${fileNameWithoutExtension}.ts`;++ const migrationPath = path.join(migrationsDirectory, fileName);+ const migrationObjectIdentifier = `${camelCase(migrationName)}Migration`;++ await fs.writeFile(migrationPath, `+import type { Migration } from '../migrations.types';+import { sql } from 'drizzle-orm';++export const ${migrationObjectIdentifier} = {+ name: '${migrationName}',++ up: async ({ db }) => {+ await db.batch([+ db.run(sql\`SELECT 1\`),+ ]);+ },++ down: async ({ db }) => {+ await db.batch([+ db.run(sql\`SELECT 1\`),+ ]);+ },+} satisfies Migration;`.trim());++ logger.info(`Migration ${fileName} created`);++ const registry = await loadFile(path.join(migrationsDirectory, '..', 'migrations.registry.ts'));++ registry.imports.$append({+ imported: migrationObjectIdentifier,+ from: `./list/${fileNameWithoutExtension}`,+ });++ // eslint-disable-next-line ts/no-unsafe-call, ts/no-unsafe-member-access+ registry.exports.migrations.push(builders.raw(migrationObjectIdentifier));++ await writeFile(registry, path.join(migrationsDirectory, '..', 'migrations.registry.ts'));+ },+);diff --git a/apps/papra-server/src/scripts/migrate-up.script.ts b/apps/papra-server/src/scripts/migrate-up.script.tsindex 317c79be..43d97858 100644--- a/apps/papra-server/src/scripts/migrate-up.script.ts+++ b/apps/papra-server/src/scripts/migrate-up.script.ts@@ -1,11 +1,9 @@-import { runMigrations } from '../modules/app/database/database.services';-import { runScript } from './commons/run-script';+import { runMigrations } from '../migrations/migrations.usecases';+import { runScriptWithDb } from './commons/run-script';-await runScript(+await runScriptWithDb({ scriptName: 'migrate-up' },async ({ db }) => {- // Drizzle kit config don't support encryption yet so we cannot use npx drizzle-kit migrate- // to run migrations. We have to run them manually.await runMigrations({ db });},);diff --git a/apps/papra-server/src/scripts/send-intake-email.script.ts b/apps/papra-server/src/scripts/send-intake-email.script.tsindex 57535e64..0e8fc236 100644--- a/apps/papra-server/src/scripts/send-intake-email.script.ts+++ b/apps/papra-server/src/scripts/send-intake-email.script.ts@@ -2,9 +2,9 @@ import { buildUrl } from '@corentinth/chisels';import { triggerWebhook } from '@owlrelay/webhook';import { getServerBaseUrl } from '../modules/config/config.models';import { INTAKE_EMAILS_INGEST_ROUTE } from '../modules/intake-emails/intake-emails.constants';-import { runScript } from './commons/run-script';+import { runScriptWithDb } from './commons/run-script';-await runScript(+await runScriptWithDb({ scriptName: 'simulate-intake-email' },async ({ config }) => {const { serverBaseUrl } = getServerBaseUrl({ config });diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex f94ae97d..9b9ea4fc 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -401,6 +401,9 @@ importers:eslint:specifier: 'catalog:'version: 9.30.1([email protected])+ magicast:+ specifier: ^0.3.5+ version: 0.3.5memfs:specifier: ^4.17.2version: 4.17.2@@ -995,16 +998,6 @@ packages:resolution: {integrity: sha512-tbhNuIxNcVb21pInl3ZSjksLCvgdZy9KwJ8brv993QtIVKJBBkYXz4q4ZbAv31GdnC+R90np23L5FbEBlthAEw==}engines: {node: '>=6.9.0'}- '@babel/[email protected]':- resolution: {integrity: sha512-QYLs8299NA7WM/bZAdp+CviYYkVoYXlDW2rzliy3chxd1PQjej7JORuMJDJXJUb9g0TT+B99EwaVLKmX+sPXWw==}- engines: {node: '>=6.0.0'}- hasBin: true-- '@babel/[email protected]':- resolution: {integrity: sha512-OsQd175SxWkGlzbny8J3K8TnnDD0N3lrIUtB92xwyRpzaenGZhxDvxN/JgU00U3CDZNj9tPuDJ5H0WS4Nt3vKg==}- engines: {node: '>=6.0.0'}- hasBin: true-'@babel/[email protected]':resolution: {integrity: sha512-jVZGvOxOuNSsuQuLRTh13nU0AogFlw32w/MT+LV6D3sP5WdbW61E77RnkbaO2dUvmPAYrBDJXGn5gGS6tH4j8g==}engines: {node: '>=6.0.0'}@@ -1028,14 +1021,6 @@ packages:resolution: {integrity: sha512-fH+b7Y4p3yqvApJALCPJcwb0/XaOSgtK4pzV6WVjPR5GLFQBRI7pfoX2V2iM48NXvX07NUxxm1Vw98YjqTcU5w==}engines: {node: '>=6.9.0'}- '@babel/[email protected]':- resolution: {integrity: sha512-+EzkxvLNfiUeKMgy/3luqfsCWFRXLb7U6wNQTk60tovuckwB15B191tJWvpp4HjiQWdJkCxO3Wbvc6jlk3Xb2Q==}- engines: {node: '>=6.9.0'}-- '@babel/[email protected]':- resolution: {integrity: sha512-ETyHEk2VHHvl9b9jZP5IHPavHYk57EhanlRRuae9XCpb/j5bDCbPPMOBfCWhnl/7EDJz0jEMCi/RhccCE8r1+Q==}- engines: {node: '>=6.9.0'}-'@babel/[email protected]':resolution: {integrity: sha512-jYnje+JyZG5YThjHiF28oT4SIZLnYOcSBb6+SDaFIyzDVSkXQmQQYclJ2R+YxcdmK0AX6x1E5OQNtuh3jHDrUg==}engines: {node: '>=6.9.0'}@@ -9269,10 +9254,10 @@ snapshots:'@babel/helper-compilation-targets': 7.25.9'@babel/helper-module-transforms': 7.26.0(@babel/[email protected])'@babel/helpers': 7.26.0- '@babel/parser': 7.27.2+ '@babel/parser': 7.28.0'@babel/template': 7.25.9'@babel/traverse': 7.26.4- '@babel/types': 7.27.1+ '@babel/types': 7.28.0convert-source-map: 2.0.0debug: 4.4.1gensync: 1.0.0-beta.2@@ -9283,8 +9268,8 @@ snapshots:'@babel/[email protected]':dependencies:- '@babel/parser': 7.27.2- '@babel/types': 7.27.1+ '@babel/parser': 7.28.0+ '@babel/types': 7.28.0'@jridgewell/gen-mapping': 0.3.8'@jridgewell/trace-mapping': 0.3.25jsesc: 3.1.0@@ -9299,12 +9284,12 @@ snapshots:'@babel/[email protected]':dependencies:- '@babel/types': 7.27.1+ '@babel/types': 7.28.0'@babel/[email protected]':dependencies:'@babel/traverse': 7.26.4- '@babel/types': 7.27.1+ '@babel/types': 7.28.0transitivePeerDependencies:- supports-color@@ -9330,15 +9315,7 @@ snapshots:'@babel/[email protected]':dependencies:'@babel/template': 7.25.9- '@babel/types': 7.27.1-- '@babel/[email protected]':- dependencies:- '@babel/types': 7.27.1-- '@babel/[email protected]':- dependencies:- '@babel/types': 7.27.6+ '@babel/types': 7.28.0'@babel/[email protected]':dependencies:@@ -9356,31 +9333,21 @@ snapshots:'@babel/[email protected]':dependencies:'@babel/code-frame': 7.26.2- '@babel/parser': 7.27.2- '@babel/types': 7.27.1+ '@babel/parser': 7.28.0+ '@babel/types': 7.28.0'@babel/[email protected]':dependencies:'@babel/code-frame': 7.26.2'@babel/generator': 7.26.3- '@babel/parser': 7.27.2+ '@babel/parser': 7.28.0'@babel/template': 7.25.9- '@babel/types': 7.27.1+ '@babel/types': 7.28.0debug: 4.4.1globals: 11.12.0transitivePeerDependencies:- supports-color- '@babel/[email protected]':- dependencies:- '@babel/helper-string-parser': 7.27.1- '@babel/helper-validator-identifier': 7.27.1-- '@babel/[email protected]':- dependencies:- '@babel/helper-string-parser': 7.27.1- '@babel/helper-validator-identifier': 7.27.1-'@babel/[email protected]':dependencies:'@babel/helper-string-parser': 7.27.1@@ -11506,24 +11473,24 @@ snapshots:'@types/[email protected]':dependencies:- '@babel/parser': 7.27.2- '@babel/types': 7.27.1+ '@babel/parser': 7.28.0+ '@babel/types': 7.28.0'@types/babel__generator': 7.6.8'@types/babel__template': 7.4.4'@types/babel__traverse': 7.20.6'@types/[email protected]':dependencies:- '@babel/types': 7.27.1+ '@babel/types': 7.28.0'@types/[email protected]':dependencies:- '@babel/parser': 7.27.2- '@babel/types': 7.27.1+ '@babel/parser': 7.28.0+ '@babel/types': 7.28.0'@types/[email protected]':dependencies:- '@babel/types': 7.27.1+ '@babel/types': 7.28.0'@types/[email protected]':dependencies:@@ -12512,7 +12479,7 @@ snapshots:'@babel/core': 7.26.0'@babel/helper-module-imports': 7.18.6'@babel/plugin-syntax-jsx': 7.25.9(@babel/[email protected])- '@babel/types': 7.27.1+ '@babel/types': 7.28.0html-entities: 2.3.3parse5: 7.3.0validate-html-nesting: 1.2.2@@ -14991,8 +14958,8 @@ snapshots:dependencies:- '@babel/parser': 7.27.5- '@babel/types': 7.27.6+ '@babel/parser': 7.28.0+ '@babel/types': 7.28.0source-map-js: 1.2.1@@ -16745,7 +16712,7 @@ snapshots:dependencies:'@babel/generator': 7.26.3'@babel/helper-module-imports': 7.25.9- '@babel/types': 7.27.1+ '@babel/types': 7.28.0solid-js: 1.9.7transitivePeerDependencies:- supports-color