@meith/db 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (205) hide show
  1. package/LICENSE.md +165 -0
  2. package/migrations/0000_initial_schema.sql +538 -0
  3. package/migrations/0001_seed_usergroups.sql +111 -0
  4. package/migrations/0002_group_promotions.sql +25 -0
  5. package/migrations/0003_counter_maintenance.sql +34 -0
  6. package/migrations/0004_post_render_cache.sql +7 -0
  7. package/migrations/0005_reports.sql +51 -0
  8. package/migrations/0006_warnings.sql +91 -0
  9. package/migrations/0007_notifications.sql +44 -0
  10. package/migrations/0008_subscriptions.sql +48 -0
  11. package/migrations/0009_member_preferences.sql +13 -0
  12. package/migrations/0010_profile_fields.sql +53 -0
  13. package/migrations/0011_private_messages.sql +63 -0
  14. package/migrations/0012_user_relations.sql +18 -0
  15. package/migrations/0013_reputation.sql +45 -0
  16. package/migrations/0014_signatures.sql +16 -0
  17. package/migrations/0015_admin_sessions.sql +24 -0
  18. package/migrations/0016_attachments.sql +51 -0
  19. package/migrations/0017_avatars.sql +33 -0
  20. package/migrations/0018_mass_mail.sql +15 -0
  21. package/migrations/0019_word_filters.sql +8 -0
  22. package/migrations/0020_searches.sql +15 -0
  23. package/migrations/0021_presence_stats.sql +18 -0
  24. package/migrations/0022_api_tokens_webhooks.sql +58 -0
  25. package/migrations/0023_install_state.sql +6 -0
  26. package/migrations/0024_component_versions.sql +13 -0
  27. package/migrations/0025_import.sql +25 -0
  28. package/migrations/0026_polls.sql +40 -0
  29. package/migrations/0027_drafts.sql +13 -0
  30. package/migrations/0028_board_vocabulary.sql +32 -0
  31. package/migrations/0029_announcements.sql +16 -0
  32. package/migrations/0030_antispam.sql +18 -0
  33. package/migrations/0031_markdown.sql +24 -0
  34. package/migrations/0032_theme_enablement.sql +1 -0
  35. package/migrations/0033_group_identity.sql +5 -0
  36. package/migrations/0034_search_document_version.sql +4 -0
  37. package/migrations/0035_categories_hold_no_threads.sql +1 -0
  38. package/migrations/0036_expiring_group_grants.sql +6 -0
  39. package/migrations/0037_automatic_timezone.sql +3 -0
  40. package/migrations/0038_primary_group_grants.sql +3 -0
  41. package/migrations/0039_moderator_log_forum_scope.sql +1 -0
  42. package/migrations/0040_moderator_restore_grants.sql +1 -0
  43. package/migrations/0041_drop_placebo_moderator_rights.sql +3 -0
  44. package/migrations/0042_drop_placebo_delete_others.sql +2 -0
  45. package/migrations/0043_federated_identity.sql +28 -0
  46. package/migrations/0044_second_factor.sql +34 -0
  47. package/migrations/0045_drop_dead_task_due_index.sql +1 -0
  48. package/migrations/0046_member_locale.sql +1 -0
  49. package/migrations/0047_navigation_items.sql +34 -0
  50. package/migrations/0048_web_push.sql +16 -0
  51. package/migrations/0049_plugin_health.sql +7 -0
  52. package/migrations/0050_drop_forum_password_grants.sql +1 -0
  53. package/migrations/0051_glossy_barracuda.sql +1 -0
  54. package/migrations/0052_many_professor_monster.sql +2 -0
  55. package/migrations/0053_strange_maximus.sql +14 -0
  56. package/migrations/0054_legacy_import_sources.sql +25 -0
  57. package/migrations/0055_poll_parity.sql +14 -0
  58. package/migrations/0056_marketplace_catalog.sql +11 -0
  59. package/migrations/meta/0000_snapshot.json +4412 -0
  60. package/migrations/meta/0006_snapshot.json +5411 -0
  61. package/migrations/meta/0007_snapshot.json +5634 -0
  62. package/migrations/meta/0008_snapshot.json +5779 -0
  63. package/migrations/meta/0009_snapshot.json +5816 -0
  64. package/migrations/meta/0010_snapshot.json +6117 -0
  65. package/migrations/meta/0011_snapshot.json +6406 -0
  66. package/migrations/meta/0012_snapshot.json +6517 -0
  67. package/migrations/meta/0013_snapshot.json +6722 -0
  68. package/migrations/meta/0014_snapshot.json +6777 -0
  69. package/migrations/meta/0015_snapshot.json +6914 -0
  70. package/migrations/meta/0016_snapshot.json +7192 -0
  71. package/migrations/meta/0017_snapshot.json +7248 -0
  72. package/migrations/meta/0018_snapshot.json +7355 -0
  73. package/migrations/meta/0019_snapshot.json +7419 -0
  74. package/migrations/meta/0020_snapshot.json +7562 -0
  75. package/migrations/meta/0021_snapshot.json +7653 -0
  76. package/migrations/meta/0031_snapshot.json +8162 -0
  77. package/migrations/meta/0032_snapshot.json +8169 -0
  78. package/migrations/meta/0033_snapshot.json +8193 -0
  79. package/migrations/meta/0034_snapshot.json +8221 -0
  80. package/migrations/meta/0036_snapshot.json +8262 -0
  81. package/migrations/meta/0037_snapshot.json +8262 -0
  82. package/migrations/meta/0038_snapshot.json +8293 -0
  83. package/migrations/meta/0039_snapshot.json +8308 -0
  84. package/migrations/meta/0041_snapshot.json +8287 -0
  85. package/migrations/meta/0042_snapshot.json +8274 -0
  86. package/migrations/meta/0043_snapshot.json +8521 -0
  87. package/migrations/meta/0044_snapshot.json +8814 -0
  88. package/migrations/meta/0045_snapshot.json +8797 -0
  89. package/migrations/meta/0046_snapshot.json +8804 -0
  90. package/migrations/meta/0047_snapshot.json +9018 -0
  91. package/migrations/meta/0048_snapshot.json +9145 -0
  92. package/migrations/meta/0049_snapshot.json +9190 -0
  93. package/migrations/meta/0050_snapshot.json +9126 -0
  94. package/migrations/meta/0051_snapshot.json +9132 -0
  95. package/migrations/meta/0052_snapshot.json +9148 -0
  96. package/migrations/meta/0053_snapshot.json +9268 -0
  97. package/migrations/meta/0054_snapshot.json +9378 -0
  98. package/migrations/meta/0056_snapshot.json +9447 -0
  99. package/migrations/meta/_journal.json +405 -0
  100. package/package.json +64 -0
  101. package/src/account-repos.ts +580 -0
  102. package/src/actor-builder.ts +130 -0
  103. package/src/admin-repo.ts +85 -0
  104. package/src/admin-session-repo.ts +205 -0
  105. package/src/admin-undo-repo.ts +128 -0
  106. package/src/announcement-repo.ts +176 -0
  107. package/src/antispam-repo.ts +145 -0
  108. package/src/api-repo.ts +276 -0
  109. package/src/attachment-admin-repo.ts +161 -0
  110. package/src/attachment-repo.ts +240 -0
  111. package/src/authorization-source.ts +138 -0
  112. package/src/avatar-repo.ts +185 -0
  113. package/src/ban-repos.ts +146 -0
  114. package/src/client.ts +85 -0
  115. package/src/content-admin-repo.ts +298 -0
  116. package/src/content-counters.ts +152 -0
  117. package/src/counter-recount.ts +263 -0
  118. package/src/cursor.ts +16 -0
  119. package/src/denormalised-username.ts +34 -0
  120. package/src/discovery-repo.ts +140 -0
  121. package/src/draft-repo.ts +59 -0
  122. package/src/feed-repo.ts +219 -0
  123. package/src/forum-admin-repo.ts +310 -0
  124. package/src/forum-repo.ts +206 -0
  125. package/src/group-admin-repo.ts +256 -0
  126. package/src/group-identity-repo.ts +84 -0
  127. package/src/identity-link-repo.ts +145 -0
  128. package/src/import-repo.ts +123 -0
  129. package/src/import-sink.ts +1377 -0
  130. package/src/index.ts +316 -0
  131. package/src/inline-moderation.ts +344 -0
  132. package/src/install-repo.ts +67 -0
  133. package/src/latest-repo.ts +115 -0
  134. package/src/maintenance-repo.ts +54 -0
  135. package/src/marketplace-repo.ts +111 -0
  136. package/src/member-profile-repo.ts +82 -0
  137. package/src/member-settings-repo.ts +160 -0
  138. package/src/message-repo.ts +384 -0
  139. package/src/migrate-run.ts +18 -0
  140. package/src/migrate.ts +129 -0
  141. package/src/modcp-repo.ts +253 -0
  142. package/src/moderation-queue.ts +279 -0
  143. package/src/navigation-repo.ts +288 -0
  144. package/src/notification-repo.ts +402 -0
  145. package/src/orphan-keys.ts +19 -0
  146. package/src/outbox-repo.ts +78 -0
  147. package/src/permission-version.ts +24 -0
  148. package/src/permissions-map.ts +52 -0
  149. package/src/pglite.fixture.ts +87 -0
  150. package/src/plugin-data.ts +88 -0
  151. package/src/plugin-grants.ts +369 -0
  152. package/src/plugin-health-repo.ts +80 -0
  153. package/src/plugin-purge-repo.ts +91 -0
  154. package/src/plugin-users.ts +39 -0
  155. package/src/poll-repo.ts +334 -0
  156. package/src/post-repo.ts +261 -0
  157. package/src/post-writes.ts +227 -0
  158. package/src/presence-repo.ts +220 -0
  159. package/src/profile-field-repo.ts +182 -0
  160. package/src/promotion-repo.ts +152 -0
  161. package/src/read-state-repo.ts +81 -0
  162. package/src/relation-repo.ts +113 -0
  163. package/src/render-backfill.ts +110 -0
  164. package/src/render-signature.ts +33 -0
  165. package/src/report-repo.ts +349 -0
  166. package/src/reputation-repo.ts +295 -0
  167. package/src/result-rows.ts +13 -0
  168. package/src/row-values.ts +7 -0
  169. package/src/schema/content.ts +451 -0
  170. package/src/schema/identity.ts +699 -0
  171. package/src/schema/index.ts +10 -0
  172. package/src/schema/messages.ts +76 -0
  173. package/src/schema/permission-columns.ts +34 -0
  174. package/src/schema/platform.ts +376 -0
  175. package/src/schema/structure.ts +164 -0
  176. package/src/search-repo.ts +359 -0
  177. package/src/search-store.ts +113 -0
  178. package/src/seed-groups.ts +11 -0
  179. package/src/settings-repo.ts +32 -0
  180. package/src/signature-repo.ts +102 -0
  181. package/src/sql-lists.ts +17 -0
  182. package/src/staff-groups.ts +50 -0
  183. package/src/stats-repo.ts +151 -0
  184. package/src/subscription-repo.ts +350 -0
  185. package/src/system-health-repo.ts +130 -0
  186. package/src/task-repo.ts +104 -0
  187. package/src/theme-admin-repo.ts +172 -0
  188. package/src/theme-repo.ts +43 -0
  189. package/src/thread-audience.ts +45 -0
  190. package/src/thread-counters.ts +107 -0
  191. package/src/thread-repo.ts +255 -0
  192. package/src/thread-surgery.ts +282 -0
  193. package/src/thread-tools.ts +311 -0
  194. package/src/thread-views.ts +41 -0
  195. package/src/thread-writes.ts +356 -0
  196. package/src/two-factor-repo.ts +235 -0
  197. package/src/upgrade-repo.ts +66 -0
  198. package/src/user-admin-repo.ts +367 -0
  199. package/src/user-bulk-repo.ts +397 -0
  200. package/src/user-merge-map.ts +111 -0
  201. package/src/user-merge-repo.ts +304 -0
  202. package/src/visibility-counters.ts +190 -0
  203. package/src/visibility.ts +17 -0
  204. package/src/vocabulary-repo.ts +54 -0
  205. package/src/warning-repo.ts +328 -0
@@ -0,0 +1,10 @@
1
+ export * from './content'
2
+ export * from './identity'
3
+ export * from './messages'
4
+ export {
5
+ columnName,
6
+ forumPermissionColumns,
7
+ groupPermissionColumns,
8
+ } from './permission-columns'
9
+ export * from './platform'
10
+ export * from './structure'
@@ -0,0 +1,76 @@
1
+ import { sql } from 'drizzle-orm'
2
+ import {
3
+ type AnyPgColumn,
4
+ boolean,
5
+ index,
6
+ integer,
7
+ pgTable,
8
+ smallint,
9
+ text,
10
+ timestamp,
11
+ unique,
12
+ uniqueIndex,
13
+ } from 'drizzle-orm/pg-core'
14
+
15
+ import { users } from './identity'
16
+
17
+ export const MESSAGE_FOLDERS = ['inbox', 'sent', 'trash'] as const
18
+ export type MessageFolder = (typeof MESSAGE_FOLDERS)[number]
19
+
20
+ export const MESSAGE_ROLES = ['author', 'to', 'bcc'] as const
21
+ export type MessageRole = (typeof MESSAGE_ROLES)[number]
22
+
23
+ export const privateMessages = pgTable(
24
+ 'private_messages',
25
+ {
26
+ id: integer('id').primaryKey().generatedByDefaultAsIdentity(),
27
+ authorUserId: integer('author_user_id').references(() => users.id, {
28
+ onDelete: 'set null',
29
+ }),
30
+ authorUsername: text('author_username').notNull().default(''),
31
+ subject: text('subject').notNull(),
32
+ message: text('message').notNull(),
33
+ bodyFormat: smallint('body_format').notNull().default(1),
34
+ messageHtml: text('message_html'),
35
+ renderVersion: smallint('render_version').notNull().default(0),
36
+ vocabVersion: smallint('vocab_version').notNull().default(0),
37
+ replyToId: integer('reply_to_id').references((): AnyPgColumn => privateMessages.id, {
38
+ onDelete: 'set null',
39
+ }),
40
+ receiptRequested: boolean('receipt_requested').notNull().default(false),
41
+ legacyId: integer('legacy_id'),
42
+ sentAt: timestamp('sent_at', { withTimezone: true }).notNull().defaultNow(),
43
+ },
44
+ (t) => [
45
+ index('private_messages_render_version_idx').on(t.renderVersion, t.id),
46
+ index('private_messages_vocab_version_idx').on(t.vocabVersion, t.id),
47
+ uniqueIndex('private_messages_legacy_id_key')
48
+ .on(t.legacyId)
49
+ .where(sql`${t.legacyId} is not null`),
50
+ ],
51
+ )
52
+
53
+ export const privateMessageCopies = pgTable(
54
+ 'private_message_copies',
55
+ {
56
+ id: integer('id').primaryKey().generatedByDefaultAsIdentity(),
57
+ messageId: integer('message_id')
58
+ .notNull()
59
+ .references(() => privateMessages.id, { onDelete: 'cascade' }),
60
+ ownerUserId: integer('owner_user_id')
61
+ .notNull()
62
+ .references(() => users.id, { onDelete: 'cascade' }),
63
+ folder: text('folder').notNull().default('inbox'),
64
+ role: text('role').notNull().default('to'),
65
+ readAt: timestamp('read_at', { withTimezone: true }),
66
+ createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
67
+ },
68
+ (t) => [
69
+ unique('private_message_copies_unique').on(t.messageId, t.ownerUserId),
70
+ index('private_message_copies_folder_idx').on(t.ownerUserId, t.folder, t.id.desc()),
71
+ index('private_message_copies_unread_idx')
72
+ .on(t.ownerUserId)
73
+ .where(sql`${t.readAt} is null and ${t.folder} = 'inbox'`),
74
+ index('private_message_copies_message_idx').on(t.messageId),
75
+ ],
76
+ )
@@ -0,0 +1,34 @@
1
+ import { boolean, integer } from 'drizzle-orm/pg-core'
2
+
3
+ import { PERMISSION_FIELDS, type PermissionField, type PermissionScope } from '@meith/core'
4
+
5
+ export function columnName(key: string): string {
6
+ return key.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`)
7
+ }
8
+
9
+ function declare(field: PermissionField, nullable: boolean) {
10
+ const name = columnName(field.key)
11
+ if (field.kind === 'numeric') {
12
+ const col = integer(name)
13
+ return nullable ? col : col.notNull().default(field.fallback as number)
14
+ }
15
+ const col = boolean(name)
16
+ return nullable ? col : col.notNull().default(field.fallback as boolean)
17
+ }
18
+
19
+ export function groupPermissionColumns() {
20
+ const out: Record<string, ReturnType<typeof declare>> = {}
21
+ for (const field of PERMISSION_FIELDS) {
22
+ out[field.key] = declare(field, false)
23
+ }
24
+ return out
25
+ }
26
+
27
+ export function forumPermissionColumns() {
28
+ const out: Record<string, ReturnType<typeof declare>> = {}
29
+ for (const field of PERMISSION_FIELDS) {
30
+ if ((field.scope satisfies PermissionScope) !== 'forum') continue
31
+ out[field.key] = declare(field, true)
32
+ }
33
+ return out
34
+ }
@@ -0,0 +1,376 @@
1
+ import { sql } from 'drizzle-orm'
2
+ import {
3
+ boolean,
4
+ check,
5
+ foreignKey,
6
+ index,
7
+ integer,
8
+ jsonb,
9
+ pgTable,
10
+ primaryKey,
11
+ smallint,
12
+ text,
13
+ timestamp,
14
+ uniqueIndex,
15
+ } from 'drizzle-orm/pg-core'
16
+
17
+ import { usergroups, users } from './identity'
18
+
19
+ export const settingGroups = pgTable(
20
+ 'setting_groups',
21
+ {
22
+ id: integer('id').primaryKey().generatedByDefaultAsIdentity(),
23
+ key: text('key').notNull(),
24
+ title: text('title').notNull(),
25
+ description: text('description'),
26
+ displayOrder: integer('display_order').notNull().default(0),
27
+ },
28
+ (t) => [uniqueIndex('setting_groups_key_key').on(t.key)],
29
+ )
30
+
31
+ export const settings = pgTable(
32
+ 'settings',
33
+ {
34
+ key: text('key').primaryKey(),
35
+ value: text('value').notNull(),
36
+ groupKey: text('group_key'),
37
+ updatedByUserId: integer('updated_by_user_id').references(() => users.id, {
38
+ onDelete: 'set null',
39
+ }),
40
+ updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
41
+ },
42
+ (t) => [index('settings_group_idx').on(t.groupKey)],
43
+ )
44
+
45
+ export const themes = pgTable(
46
+ 'themes',
47
+ {
48
+ key: text('key').primaryKey(),
49
+ title: text('title').notNull(),
50
+
51
+ tokenOverrides: jsonb('token_overrides').notNull().default({}),
52
+ branding: jsonb('branding').notNull().default({}),
53
+ layoutOptions: jsonb('layout_options').notNull().default({}),
54
+ customCss: text('custom_css'),
55
+
56
+ isDefault: boolean('is_default').notNull().default(false),
57
+
58
+ enabled: boolean('enabled').notNull().default(true),
59
+
60
+ updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
61
+ },
62
+ (t) => [uniqueIndex('themes_single_default_key').on(t.isDefault).where(sql`${t.isDefault}`)],
63
+ )
64
+
65
+ export const outbox = pgTable(
66
+ 'outbox',
67
+ {
68
+ id: integer('id').primaryKey().generatedByDefaultAsIdentity(),
69
+
70
+ topic: text('topic').notNull(),
71
+ payload: jsonb('payload').notNull(),
72
+
73
+ correlationId: text('correlation_id'),
74
+
75
+ dispatchedAt: timestamp('dispatched_at', { withTimezone: true }),
76
+ attempts: smallint('attempts').notNull().default(0),
77
+ lastError: text('last_error'),
78
+
79
+ createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
80
+ },
81
+ (t) => [index('outbox_pending_idx').on(t.id).where(sql`${t.dispatchedAt} is null`)],
82
+ )
83
+
84
+ export const jobs = pgTable(
85
+ 'jobs',
86
+ {
87
+ id: integer('id').primaryKey().generatedByDefaultAsIdentity(),
88
+
89
+ kind: text('kind').notNull(),
90
+ payload: jsonb('payload').notNull().default({}),
91
+
92
+ status: text('status').notNull().default('pending'),
93
+
94
+ idempotencyKey: text('idempotency_key'),
95
+
96
+ runAt: timestamp('run_at', { withTimezone: true }).notNull().defaultNow(),
97
+ attempts: smallint('attempts').notNull().default(0),
98
+ maxAttempts: smallint('max_attempts').notNull().default(5),
99
+
100
+ lockedUntil: timestamp('locked_until', { withTimezone: true }),
101
+ lockedBy: text('locked_by'),
102
+
103
+ lastError: text('last_error'),
104
+ correlationId: text('correlation_id'),
105
+
106
+ createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
107
+ completedAt: timestamp('completed_at', { withTimezone: true }),
108
+ },
109
+ (t) => [
110
+ index('jobs_pending_idx').on(t.status, t.runAt).where(sql`${t.status} = 'pending'`),
111
+
112
+ uniqueIndex('jobs_idempotency_key')
113
+ .on(t.idempotencyKey)
114
+ .where(sql`${t.idempotencyKey} is not null and ${t.status} = 'pending'`),
115
+
116
+ index('jobs_status_idx').on(t.status),
117
+ ],
118
+ )
119
+
120
+ export const tasks = pgTable('tasks', {
121
+ key: text('key').primaryKey(),
122
+
123
+ intervalSeconds: integer('interval_seconds').notNull(),
124
+
125
+ enabled: boolean('enabled').notNull().default(true),
126
+
127
+ lastRunAt: timestamp('last_run_at', { withTimezone: true }),
128
+ nextRunAt: timestamp('next_run_at', { withTimezone: true }).notNull().defaultNow(),
129
+
130
+ lockedUntil: timestamp('locked_until', { withTimezone: true }),
131
+
132
+ consecutiveFailures: smallint('consecutive_failures').notNull().default(0),
133
+ })
134
+
135
+ export const taskLog = pgTable(
136
+ 'task_log',
137
+ {
138
+ id: integer('id').primaryKey().generatedByDefaultAsIdentity(),
139
+ taskKey: text('task_key').notNull(),
140
+ succeeded: boolean('succeeded').notNull(),
141
+ durationMs: integer('duration_ms'),
142
+ detail: text('detail'),
143
+ error: text('error'),
144
+ ranAt: timestamp('ran_at', { withTimezone: true }).notNull().defaultNow(),
145
+ },
146
+ (t) => [index('task_log_key_ran_idx').on(t.taskKey, t.ranAt.desc())],
147
+ )
148
+
149
+ export const cacheVersions = pgTable('cache_versions', {
150
+ key: text('key').primaryKey(),
151
+ version: integer('version').notNull().default(1),
152
+ bumpedAt: timestamp('bumped_at', { withTimezone: true }).notNull().defaultNow(),
153
+ })
154
+
155
+ export const pluginHealth = pgTable('plugin_health', {
156
+ pluginKey: text('plugin_key').primaryKey(),
157
+ failures: integer('failures').notNull().default(0),
158
+ disabledAt: timestamp('disabled_at', { withTimezone: true }),
159
+ reason: text('reason'),
160
+ updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
161
+ })
162
+
163
+ /**
164
+ * The cached copy of the meith.dev marketplace feed (or a self-hosted
165
+ * mirror's) — a single row, refreshed daily by a task and on demand by the
166
+ * admin panel's "Refresh" button. `feed` and `fetchedAt` are null until the
167
+ * first successful fetch; `error`/`errorAt` describe the most recent failed
168
+ * attempt, cleared on the next success, so a board with no outbound network
169
+ * shows a plain "unreachable" note rather than nothing. `notifiedUpdates`
170
+ * carries `"<plugin key>@<version>"` strings, one per update notification
171
+ * ever sent, which is what makes that notification fire once per version —
172
+ * not once per unread bell entry, which the notification service's own
173
+ * dedupe key gives up on as soon as the entry is read.
174
+ */
175
+ export const marketplaceCatalog = pgTable(
176
+ 'marketplace_catalog',
177
+ {
178
+ id: smallint('id').primaryKey().default(1),
179
+ feed: jsonb('feed'),
180
+ /** The feed URL the cached copy was actually fetched from — screenshots are
181
+ * absolute *paths*, resolved against this rather than against whatever the
182
+ * setting reads today, so a mid-day setting change cannot point an old
183
+ * cached screenshot at the wrong host. */
184
+ sourceUrl: text('source_url'),
185
+ fetchedAt: timestamp('fetched_at', { withTimezone: true }),
186
+ error: text('error'),
187
+ errorAt: timestamp('error_at', { withTimezone: true }),
188
+ notifiedUpdates: jsonb('notified_updates').notNull().default([]),
189
+ updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
190
+ },
191
+ (t) => [check('marketplace_catalog_single_row', sql`${t.id} = 1`)],
192
+ )
193
+
194
+ export const adminLog = pgTable(
195
+ 'admin_log',
196
+ {
197
+ id: integer('id').primaryKey().generatedByDefaultAsIdentity(),
198
+ userId: integer('user_id').references(() => users.id, {
199
+ onDelete: 'set null',
200
+ }),
201
+ action: text('action').notNull(),
202
+ detail: jsonb('detail').notNull().default({}),
203
+ ipPrefix: text('ip_prefix'),
204
+ correlationId: text('correlation_id'),
205
+ createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
206
+ },
207
+ (t) => [
208
+ index('admin_log_user_idx').on(t.userId, t.createdAt.desc()),
209
+ index('admin_log_action_idx').on(t.action, t.createdAt.desc()),
210
+ index('admin_log_forum_scope_idx').using(
211
+ 'gin',
212
+ sql`(${t.detail} -> 'forumIds') jsonb_path_ops`,
213
+ ),
214
+ ],
215
+ )
216
+
217
+ export const adminUndoOperations = pgTable(
218
+ 'admin_undo_operations',
219
+ {
220
+ id: integer('id').primaryKey().generatedByDefaultAsIdentity(),
221
+ tokenHash: text('token_hash').notNull(),
222
+ actorUserId: integer('actor_user_id')
223
+ .notNull()
224
+ .references(() => users.id, { onDelete: 'cascade' }),
225
+ operation: text('operation').notNull(),
226
+ snapshot: jsonb('snapshot').notNull(),
227
+ createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
228
+ expiresAt: timestamp('expires_at', { withTimezone: true }).notNull(),
229
+ consumedAt: timestamp('consumed_at', { withTimezone: true }),
230
+ },
231
+ (t) => [
232
+ uniqueIndex('admin_undo_operations_token_key').on(t.tokenHash),
233
+ index('admin_undo_operations_live_idx').on(t.actorUserId, t.expiresAt),
234
+ ],
235
+ )
236
+
237
+ export const contentCounterRollups = pgTable('content_counter_rollups', {
238
+ postId: integer('post_id').primaryKey(),
239
+ appliedAt: timestamp('applied_at', { withTimezone: true }).notNull().defaultNow(),
240
+ })
241
+
242
+ export const counterRecountState = pgTable('counter_recount_state', {
243
+ id: text('id').primaryKey(),
244
+ phase: text('phase').notNull().default('threads'),
245
+ cursor: integer('cursor').notNull().default(0),
246
+ passes: integer('passes').notNull().default(0),
247
+ corrected: integer('corrected').notNull().default(0),
248
+ updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
249
+ })
250
+
251
+ export const massMails = pgTable('mass_mails', {
252
+ id: integer('id').primaryKey().generatedByDefaultAsIdentity(),
253
+ subject: text('subject').notNull(),
254
+ body: text('body').notNull(),
255
+ targetGroupId: integer('target_group_id').references(() => usergroups.id, {
256
+ onDelete: 'set null',
257
+ }),
258
+ lastUserId: integer('last_user_id').notNull().default(0),
259
+ queuedCount: integer('queued_count').notNull().default(0),
260
+ status: text('status').notNull().default('sending'),
261
+ createdByUserId: integer('created_by_user_id').references(() => users.id, {
262
+ onDelete: 'set null',
263
+ }),
264
+ createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
265
+ finishedAt: timestamp('finished_at', { withTimezone: true }),
266
+ })
267
+
268
+ export const searches = pgTable(
269
+ 'searches',
270
+ {
271
+ id: integer('id').primaryKey().generatedByDefaultAsIdentity(),
272
+ token: text('token').notNull(),
273
+ userId: integer('user_id').references(() => users.id, { onDelete: 'cascade' }),
274
+ sessionKey: text('session_key'),
275
+ terms: text('terms').notNull(),
276
+ filters: jsonb('filters').notNull().default({}),
277
+ hitCount: integer('hit_count').notNull().default(0),
278
+ createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
279
+ },
280
+ (t) => [
281
+ uniqueIndex('searches_token_key').on(t.token),
282
+ index('searches_user_recent_idx').on(t.userId, t.createdAt),
283
+ index('searches_session_recent_idx').on(t.sessionKey, t.createdAt),
284
+ ],
285
+ )
286
+
287
+ export const boardStats = pgTable(
288
+ 'board_stats',
289
+ {
290
+ id: smallint('id').primaryKey().default(1),
291
+
292
+ threadCount: integer('thread_count').notNull().default(0),
293
+ postCount: integer('post_count').notNull().default(0),
294
+ memberCount: integer('member_count').notNull().default(0),
295
+
296
+ newestUserId: integer('newest_user_id'),
297
+ newestUsername: text('newest_username'),
298
+
299
+ mostOnlineCount: integer('most_online_count').notNull().default(0),
300
+ mostOnlineAt: timestamp('most_online_at', { withTimezone: true }),
301
+
302
+ computedAt: timestamp('computed_at', { withTimezone: true }),
303
+
304
+ updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
305
+ },
306
+ (t) => [check('board_stats_singleton', sql`${t.id} = 1`)],
307
+ )
308
+
309
+ export const rateLimits = pgTable(
310
+ 'rate_limits',
311
+ {
312
+ scope: text('scope').notNull(),
313
+ subject: text('subject').notNull(),
314
+ windowStart: timestamp('window_start', { withTimezone: true }).notNull(),
315
+ used: integer('used').notNull().default(0),
316
+ },
317
+ (t) => [
318
+ primaryKey({ columns: [t.scope, t.subject, t.windowStart] }),
319
+ index('rate_limits_window_idx').on(t.windowStart),
320
+ ],
321
+ )
322
+
323
+ export const captchaQuestions = pgTable('captcha_questions', {
324
+ id: integer('id').primaryKey().generatedByDefaultAsIdentity(),
325
+ question: text('question').notNull(),
326
+ answers: text('answers').notNull(),
327
+ enabled: boolean('enabled').notNull().default(true),
328
+ createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
329
+ })
330
+
331
+ export const NAVIGATION_AUDIENCES = ['all', 'guests', 'members', 'staff'] as const
332
+
333
+ export const navigationItems = pgTable(
334
+ 'navigation_items',
335
+ {
336
+ id: integer('id').primaryKey().generatedByDefaultAsIdentity(),
337
+ key: text('key'),
338
+ parentId: integer('parent_id'),
339
+ label: text('label').notNull().default(''),
340
+ href: text('href').notNull(),
341
+ displayOrder: integer('display_order').notNull().default(0),
342
+ audience: text('audience').notNull().default('all'),
343
+ newTab: boolean('new_tab').notNull().default(false),
344
+ enabled: boolean('enabled').notNull().default(true),
345
+ createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
346
+ },
347
+ (t) => [
348
+ uniqueIndex('navigation_items_key_key').on(t.key).where(sql`${t.key} is not null`),
349
+ index('navigation_items_order_idx').on(t.parentId, t.displayOrder, t.id),
350
+ foreignKey({
351
+ columns: [t.parentId],
352
+ foreignColumns: [t.id],
353
+ name: 'navigation_items_parent_id_fk',
354
+ }).onDelete('cascade'),
355
+ check(
356
+ 'navigation_items_audience_check',
357
+ sql`${t.audience} in ('all', 'guests', 'members', 'staff')`,
358
+ ),
359
+ ],
360
+ )
361
+
362
+ export const navigationItemGroups = pgTable(
363
+ 'navigation_item_groups',
364
+ {
365
+ itemId: integer('item_id')
366
+ .notNull()
367
+ .references(() => navigationItems.id, { onDelete: 'cascade' }),
368
+ groupId: integer('group_id')
369
+ .notNull()
370
+ .references(() => usergroups.id, { onDelete: 'cascade' }),
371
+ },
372
+ (t) => [
373
+ primaryKey({ columns: [t.itemId, t.groupId] }),
374
+ index('navigation_item_groups_group_idx').on(t.groupId),
375
+ ],
376
+ )
@@ -0,0 +1,164 @@
1
+ import { sql } from 'drizzle-orm'
2
+ import { boolean, index, integer, pgTable, text, timestamp, uniqueIndex } from 'drizzle-orm/pg-core'
3
+
4
+ import { usergroups, users } from './identity'
5
+ import { forumPermissionColumns } from './permission-columns'
6
+
7
+ export const FORUM_TYPES = ['category', 'forum', 'link'] as const
8
+
9
+ export const forums = pgTable(
10
+ 'forums',
11
+ {
12
+ id: integer('id').primaryKey().generatedByDefaultAsIdentity(),
13
+
14
+ type: text('type').notNull().default('forum'),
15
+
16
+ title: text('title').notNull(),
17
+ description: text('description'),
18
+ slug: text('slug').notNull(),
19
+
20
+ parentId: integer('parent_id'),
21
+
22
+ path: text('path').notNull(),
23
+ depth: integer('depth').notNull().default(0),
24
+
25
+ displayOrder: integer('display_order').notNull().default(0),
26
+
27
+ linkUrl: text('link_url'),
28
+ linkHits: integer('link_hits').notNull().default(0),
29
+
30
+ isOpen: boolean('is_open').notNull().default(true),
31
+ allowThreads: boolean('allow_threads').notNull().default(true),
32
+ allowReplies: boolean('allow_replies').notNull().default(true),
33
+ allowPolls: boolean('allow_polls').notNull().default(true),
34
+ allowAttachments: boolean('allow_attachments').notNull().default(true),
35
+ requiresPrefix: boolean('requires_prefix').notNull().default(false),
36
+
37
+ moderateNewThreads: boolean('moderate_new_threads').notNull().default(false),
38
+ moderateNewPosts: boolean('moderate_new_posts').notNull().default(false),
39
+
40
+ passwordHash: text('password_hash'),
41
+
42
+ threadCount: integer('thread_count').notNull().default(0),
43
+ postCount: integer('post_count').notNull().default(0),
44
+
45
+ lastPostId: integer('last_post_id'),
46
+ lastPostThreadId: integer('last_post_thread_id'),
47
+ lastPostThreadTitle: text('last_post_thread_title'),
48
+ lastPostUserId: integer('last_post_user_id'),
49
+ lastPostUsername: text('last_post_username'),
50
+ lastPostAt: timestamp('last_post_at', { withTimezone: true }),
51
+
52
+ legacyId: integer('legacy_id'),
53
+
54
+ createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
55
+ updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
56
+ },
57
+ (t) => [
58
+ uniqueIndex('forums_parent_slug_key')
59
+ .on(t.parentId, t.slug)
60
+ .where(sql`${t.parentId} is not null`),
61
+ uniqueIndex('forums_root_slug_key').on(t.slug).where(sql`${t.parentId} is null`),
62
+
63
+ index('forums_parent_order_idx').on(t.parentId, t.displayOrder),
64
+ index('forums_path_idx').on(t.path),
65
+ uniqueIndex('forums_legacy_id_key').on(t.legacyId).where(sql`${t.legacyId} is not null`),
66
+ ],
67
+ )
68
+
69
+ export const forumPermissions = pgTable(
70
+ 'forum_permissions',
71
+ {
72
+ forumId: integer('forum_id')
73
+ .notNull()
74
+ .references(() => forums.id, { onDelete: 'cascade' }),
75
+ groupId: integer('group_id')
76
+ .notNull()
77
+ .references(() => usergroups.id, { onDelete: 'cascade' }),
78
+
79
+ ...forumPermissionColumns(),
80
+
81
+ updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
82
+ },
83
+ (t) => [
84
+ uniqueIndex('forum_permissions_pkey').on(t.forumId, t.groupId),
85
+ index('forum_permissions_group_idx').on(t.groupId),
86
+ ],
87
+ )
88
+
89
+ export const forumModerators = pgTable(
90
+ 'forum_moderators',
91
+ {
92
+ id: integer('id').primaryKey().generatedByDefaultAsIdentity(),
93
+
94
+ forumId: integer('forum_id')
95
+ .notNull()
96
+ .references(() => forums.id, { onDelete: 'cascade' }),
97
+
98
+ userId: integer('user_id').references(() => users.id, {
99
+ onDelete: 'cascade',
100
+ }),
101
+ groupId: integer('group_id').references(() => usergroups.id, {
102
+ onDelete: 'cascade',
103
+ }),
104
+
105
+ cascadeToSubforums: boolean('cascade_to_subforums').notNull().default(false),
106
+
107
+ canEditPosts: boolean('can_edit_posts').notNull().default(false),
108
+ canSoftDeletePosts: boolean('can_soft_delete_posts').notNull().default(false),
109
+ canRestorePosts: boolean('can_restore_posts').notNull().default(false),
110
+ canApproveContent: boolean('can_approve_content').notNull().default(false),
111
+ canOpenCloseThreads: boolean('can_open_close_threads').notNull().default(false),
112
+ canStickThreads: boolean('can_stick_threads').notNull().default(false),
113
+ canMoveThreads: boolean('can_move_threads').notNull().default(false),
114
+ canMergeThreads: boolean('can_merge_threads').notNull().default(false),
115
+ canSplitThreads: boolean('can_split_threads').notNull().default(false),
116
+
117
+ createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
118
+ },
119
+ (t) => [
120
+ uniqueIndex('forum_moderators_user_key')
121
+ .on(t.forumId, t.userId)
122
+ .where(sql`${t.userId} is not null`),
123
+ uniqueIndex('forum_moderators_group_key')
124
+ .on(t.forumId, t.groupId)
125
+ .where(sql`${t.groupId} is not null`),
126
+ index('forum_moderators_user_idx').on(t.userId),
127
+ index('forum_moderators_group_idx').on(t.groupId),
128
+ ],
129
+ )
130
+
131
+ export const forumsRead = pgTable(
132
+ 'forums_read',
133
+ {
134
+ userId: integer('user_id')
135
+ .notNull()
136
+ .references(() => users.id, { onDelete: 'cascade' }),
137
+ forumId: integer('forum_id')
138
+ .notNull()
139
+ .references(() => forums.id, { onDelete: 'cascade' }),
140
+ readAt: timestamp('read_at', { withTimezone: true }).notNull().defaultNow(),
141
+ },
142
+ (t) => [uniqueIndex('forums_read_pkey').on(t.userId, t.forumId)],
143
+ )
144
+
145
+ export const forumSubscriptions = pgTable(
146
+ 'forum_subscriptions',
147
+ {
148
+ userId: integer('user_id')
149
+ .notNull()
150
+ .references(() => users.id, { onDelete: 'cascade' }),
151
+ forumId: integer('forum_id')
152
+ .notNull()
153
+ .references(() => forums.id, { onDelete: 'cascade' }),
154
+ mode: text('mode').notNull().default('instant'),
155
+ lastNotifiedPostId: integer('last_notified_post_id').notNull().default(0),
156
+ createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
157
+ },
158
+ (t) => [
159
+ uniqueIndex('forum_subscriptions_pkey').on(t.userId, t.forumId),
160
+ index('forum_subscriptions_forum_idx').on(t.forumId),
161
+ index('forum_subscriptions_user_idx').on(t.userId, t.createdAt.desc()),
162
+ index('forum_subscriptions_mode_idx').on(t.mode, t.userId),
163
+ ],
164
+ )