welearn-database 1.5.7.dev0__py3-none-any.whl → 1.5.8.dev0__py3-none-any.whl

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.
@@ -1,5 +1,7 @@
1
1
  import os
2
+ import sys
2
3
  from logging.config import fileConfig
4
+ from pathlib import Path
3
5
 
4
6
  from alembic import context
5
7
  from dotenv import load_dotenv
@@ -33,6 +35,57 @@ target_metadata = Base.metadata
33
35
  # my_important_option = config.get_main_option("my_important_option")
34
36
  # ... etc.
35
37
 
38
+ # Targets that ask the user to type their name before an online run.
39
+ PROTECTED_TARGETS = {"prod"}
40
+
41
+
42
+ def load_target_env() -> str | None:
43
+ """Load the database settings for the target given with `-x env=<name>`.
44
+
45
+ With the flag, `.env.<name>` at the repository root is loaded and its values
46
+ override variables already exported in the shell. Without it, `.env` is
47
+ loaded as before and exported variables win.
48
+ """
49
+ target = context.get_x_argument(as_dictionary=True).get("env")
50
+ root = Path(config.config_file_name or "alembic.ini").resolve().parent
51
+
52
+ if not target:
53
+ load_dotenv(root / ".env")
54
+ return None
55
+
56
+ env_file = root / f".env.{target}"
57
+ if not env_file.is_file():
58
+ available = sorted(
59
+ p.name for p in root.glob(".env.*") if p.name != ".env.example"
60
+ )
61
+ raise SystemExit(
62
+ f"No {env_file.name} found in {root}. "
63
+ f"Available: {', '.join(available) or 'none'}"
64
+ )
65
+ load_dotenv(env_file, override=True)
66
+ return target
67
+
68
+
69
+ def confirm_target(target: str | None) -> None:
70
+ """Print where the migration goes, and ask before touching a protected database."""
71
+ host = os.getenv("PG_HOST", "")
72
+ db = os.getenv("PG_DB", "")
73
+ label = target or ".env"
74
+ print(f"Target: {label} -> {host}/{db}", file=sys.stderr)
75
+
76
+ if context.is_offline_mode():
77
+ return
78
+
79
+ if target in PROTECTED_TARGETS or "prod" in host.lower():
80
+ expected = target or "prod"
81
+ answer = input(f"Type '{expected}' to run against this database: ")
82
+ if answer.strip() != expected:
83
+ raise SystemExit("Aborted.")
84
+
85
+
86
+ TARGET = load_target_env()
87
+ confirm_target(TARGET)
88
+
36
89
 
37
90
  def run_migrations_offline() -> None:
38
91
  """Run migrations in 'offline' mode.
@@ -46,8 +99,6 @@ def run_migrations_offline() -> None:
46
99
  script output.
47
100
 
48
101
  """
49
- load_dotenv()
50
-
51
102
  db_url = URL.create(
52
103
  drivername=os.getenv("PG_DRIVER", "postgresql+psycopg"),
53
104
  username=os.environ["PG_USER"],
@@ -61,6 +112,7 @@ def run_migrations_offline() -> None:
61
112
  target_metadata=target_metadata,
62
113
  literal_binds=True,
63
114
  dialect_opts={"paramstyle": "named"},
115
+ version_table_schema="public",
64
116
  )
65
117
 
66
118
  with context.begin_transaction():
@@ -83,25 +135,8 @@ def run_migrations_online() -> None:
83
135
  and associate a connection with the context.
84
136
 
85
137
  """
86
- load_dotenv()
87
138
  connectable = create_sqlalchemy_engine()
88
139
 
89
- if "prod" in os.getenv("PG_HOST").lower():
90
- print("Connecting to production database for migrations!")
91
- input("Press Enter to continue...")
92
- elif (
93
- "dev" in os.getenv("PG_HOST" "").lower()
94
- and "staging" in os.getenv("PG_DB" "").lower()
95
- ):
96
- print("Connecting to staging database for migrations!")
97
- elif (
98
- "dev" in os.getenv("PG_HOST" "").lower()
99
- and not "staging" in os.getenv("PG_DB" "").lower()
100
- ):
101
- print("Connecting to dev database for migrations!")
102
- else:
103
- print("Connecting to unknown database for migrations!")
104
-
105
140
  with connectable.connect() as connection:
106
141
  context.configure(
107
142
  connection=connection,
@@ -0,0 +1,436 @@
1
+ """add auth_event table, its grafana views and the grafana usage views
2
+
3
+ Revision ID: 1_5_8
4
+ Revises: 1_5_7
5
+ Create Date: 2026-11-26 17:36:17.512738
6
+
7
+ """
8
+
9
+ from typing import Sequence, Union
10
+
11
+ import sqlalchemy as sa
12
+ from alembic import op
13
+ from sqlalchemy.dialects import postgresql
14
+
15
+ # revision identifiers, used by Alembic.
16
+ revision: str = "1_5_8"
17
+ down_revision: Union[str, None] = "1_5_7"
18
+ branch_labels: Union[str, Sequence[str], None] = None
19
+ depends_on: Union[str, Sequence[str], None] = None
20
+
21
+ SCHEMA = "user_related"
22
+
23
+ # written out rather than read from AuthEventType, so this revision keeps
24
+ # creating the same type if the enum changes later
25
+ EVENT_TYPES = ["signup", "account_created", "login", "logout"]
26
+
27
+ # the API paths (endpoint_request.endpoint_name) of each feature, as LIKE
28
+ # patterns that don't overlap, so a request gets one feature at most. Paths not
29
+ # listed (session, guest quota, access, logout, metrics, health, the lists
30
+ # loaded when the app starts...) are plumbing and have no feature.
31
+ ENDPOINT_FEATURES = [
32
+ # a question asked; history and threads are loaded on boot, so left out
33
+ ("/api/v1/qna/chat/agent", "chat"),
34
+ ("/api/v1/qna/chat/agent_stream", "chat"),
35
+ ("/api/v1/qna/chat/answer", "chat"),
36
+ ("/api/v1/qna/stream", "chat"),
37
+ ("/api/v1/qna/reformulate/%", "chat"),
38
+ ("/api/v1/search/by_document", "search"),
39
+ ("/api/v1/search/by_slices", "search"),
40
+ ("/api/v1/search/multiple_by_slices", "search"),
41
+ ("/api/v1/search/collections/%", "search"),
42
+ # the client sends it with each search, to show the query's SDGs
43
+ ("/api/v1/search/sdg_classify", "sdg detection"),
44
+ ("/api/v1/tutor/files/content", "syllabus (from scratch)"),
45
+ ("/api/v1/tutor/search_extracts", "syllabus (from scratch)"),
46
+ ("/api/v1/tutor/search_datasets", "syllabus (from scratch)"),
47
+ ("/api/v1/tutor/syllabus", "syllabus (from scratch)"),
48
+ ("/api/v1/tutor/syllabus/feedback", "syllabus (from scratch)"),
49
+ ("/api/v1/tutor/syllabus/user_update", "syllabus (from scratch)"),
50
+ ("/api/v1/tutor/course/%", "syllabus v2 (existing course)"),
51
+ # the hidden /tutor_test page and the steps it calls
52
+ ("/api/v1/tutor/mas_files/%", "syllabus (test page)"),
53
+ ("/api/v1/tutor/api/%", "syllabus (test page)"),
54
+ ("/api/v1/tutor/syllabus/description", "syllabus (test page)"),
55
+ ("/api/v1/tutor/syllabus/learning_objectives", "syllabus (test page)"),
56
+ ("/api/v1/tutor/syllabus/learning_outcomes", "syllabus (test page)"),
57
+ ("/api/v1/tutor/syllabus/competency_map", "syllabus (test page)"),
58
+ ("/api/v1/tutor/syllabus/sustainability_integration", "syllabus (test page)"),
59
+ # a bookmark added or removed; the bare list is loaded on boot
60
+ ("/api/v1/user/bookmarks/%", "bookmarks"),
61
+ ("/api/v1/user/%/bookmarks/%", "bookmarks"),
62
+ ("/api/v1/bibliography/%", "bibliography export"),
63
+ ("/api/v1/micro_learning/%", "learn (microlearning)"),
64
+ ("/api/v1/user/university-request", "university request"),
65
+ ]
66
+
67
+ # a guest who logs in later gets its keycloak_id on the same row, so it counts
68
+ # as an account for its past too
69
+ USER_KIND = "CASE WHEN iu.keycloak_id IS NULL THEN 'guest' ELSE 'account' END"
70
+
71
+ # 6d4346fad6f4's definition, restored as is by the downgrade
72
+ OLD_USED_FEATURE_PER_SESSION = """
73
+ CREATE OR REPLACE VIEW grafana.used_feature_per_session
74
+ AS WITH matching_features_endpoint AS (
75
+ SELECT
76
+ endpoint_name,
77
+ feature_name
78
+ FROM
79
+ (
80
+ VALUES
81
+ ('/api/v1/search/by_document', 'search'),
82
+ ('/api/v1/qna/chat/answer', 'chat'),
83
+ ('/api/v1/qna/chat/agent', 'chat'),
84
+ ('/api/v1/tutor/syllabus', 'syllabus'),
85
+ ('/api/v1/user/bookmarks/' || ':' || 'document_id', 'bookmark'),
86
+ ('/api/v1/user/' || ':' || 'user_id' || '/bookmarks/' || ':' || 'document_id', 'bookmark')
87
+ ) AS t(endpoint_name, feature_name)
88
+ ),
89
+ session_feature_pair AS (
90
+ SELECT
91
+ DISTINCT
92
+ er.session_id,
93
+ mfe.feature_name
94
+ FROM
95
+ user_related.endpoint_request er
96
+ CROSS JOIN matching_features_endpoint mfe
97
+ ORDER BY
98
+ er.session_id
99
+ ),
100
+ actual_count AS (
101
+ SELECT
102
+ er.session_id,
103
+ mfe.feature_name,
104
+ COUNT(1) AS cnt
105
+ FROM
106
+ user_related.endpoint_request er
107
+ INNER JOIN
108
+ user_related."session" s ON
109
+ s.id = er.session_id
110
+ INNER JOIN
111
+ matching_features_endpoint mfe ON
112
+ mfe.endpoint_name = er.endpoint_name
113
+ GROUP BY
114
+ er.session_id,
115
+ mfe.feature_name
116
+ )
117
+ SELECT
118
+ s.inferred_user_id,
119
+ sfp.session_id,
120
+ sfp.feature_name,
121
+ COALESCE(ac.cnt, 0) AS cnt,
122
+ COALESCE(ac.cnt, 0) > 0 AS is_feature_used,
123
+ s.created_at AS session_created_at
124
+ FROM
125
+ session_feature_pair sfp
126
+ LEFT JOIN actual_count ac ON
127
+ ac.feature_name = sfp.feature_name
128
+ AND ac.session_id = sfp.session_id
129
+ INNER JOIN user_related."session" s ON
130
+ s.id = sfp.session_id
131
+ ORDER BY
132
+ session_created_at
133
+ """
134
+
135
+
136
+ def _comment(view: str, text: str) -> None:
137
+ op.execute(f"COMMENT ON VIEW grafana.{view} IS '{text}';")
138
+
139
+
140
+ def upgrade() -> None:
141
+ op.create_table(
142
+ "auth_event",
143
+ sa.Column(
144
+ "id", sa.Uuid(), server_default=sa.text("gen_random_uuid()"), nullable=False
145
+ ),
146
+ sa.Column("inferred_user_id", sa.Uuid(), nullable=False),
147
+ sa.Column("session_id", sa.Uuid(), nullable=True),
148
+ sa.Column(
149
+ "event_type",
150
+ postgresql.ENUM(*EVENT_TYPES, name="auth_event_type", schema=SCHEMA),
151
+ nullable=False,
152
+ ),
153
+ sa.Column("identity_provider", sa.String(), nullable=True),
154
+ sa.Column("is_limited_access", sa.Boolean(), nullable=False),
155
+ sa.Column("keycloak_session_id", sa.String(), nullable=True),
156
+ sa.Column(
157
+ "created_at",
158
+ sa.TIMESTAMP(),
159
+ server_default=sa.text("NOW()"),
160
+ nullable=False,
161
+ ),
162
+ sa.PrimaryKeyConstraint("id"),
163
+ sa.ForeignKeyConstraint(
164
+ ["inferred_user_id"],
165
+ [f"{SCHEMA}.inferred_user.id"],
166
+ name="auth_event_inferred_user_id_fkey",
167
+ ondelete="CASCADE",
168
+ ),
169
+ # events outlive a purged session, they only lose its host
170
+ sa.ForeignKeyConstraint(
171
+ ["session_id"],
172
+ [f"{SCHEMA}.session.id"],
173
+ name="auth_event_session_id_fkey",
174
+ ondelete="SET NULL",
175
+ ),
176
+ schema=SCHEMA,
177
+ )
178
+ op.create_index(
179
+ "auth_event_created_at_idx", "auth_event", ["created_at"], schema=SCHEMA
180
+ )
181
+ op.create_index(
182
+ "auth_event_event_type_created_at_idx",
183
+ "auth_event",
184
+ ["event_type", "created_at"],
185
+ schema=SCHEMA,
186
+ )
187
+ # one login per Keycloak session: a concurrent second insert fails here
188
+ op.create_index(
189
+ "auth_event_login_keycloak_session_key",
190
+ "auth_event",
191
+ ["inferred_user_id", "keycloak_session_id"],
192
+ unique=True,
193
+ schema=SCHEMA,
194
+ postgresql_where=sa.text(
195
+ "event_type = 'login' AND keycloak_session_id IS NOT NULL"
196
+ ),
197
+ )
198
+
199
+ # keycloak_session_id is left out: dashboards don't need it
200
+ op.execute(
201
+ """
202
+ CREATE OR REPLACE VIEW grafana.auth_event
203
+ AS SELECT auth_event.id,
204
+ auth_event.inferred_user_id,
205
+ auth_event.session_id,
206
+ auth_event.event_type,
207
+ auth_event.identity_provider,
208
+ auth_event.is_limited_access,
209
+ auth_event.created_at,
210
+ session.host
211
+ FROM user_related.auth_event
212
+ LEFT JOIN user_related.session ON session.id = auth_event.session_id;
213
+ """
214
+ )
215
+ # provider labels the NULL identity_provider (email/password or unknown) so
216
+ # it shows up as its own series in Grafana
217
+ op.execute(
218
+ """
219
+ CREATE OR REPLACE VIEW grafana.auth_event_daily
220
+ AS SELECT date_trunc('day', auth_event.created_at) AS day,
221
+ auth_event.event_type,
222
+ auth_event.identity_provider,
223
+ COALESCE(auth_event.identity_provider, 'email_or_unknown') AS provider,
224
+ auth_event.is_limited_access,
225
+ count(*) AS events,
226
+ count(DISTINCT auth_event.inferred_user_id) AS users
227
+ FROM user_related.auth_event
228
+ GROUP BY date_trunc('day', auth_event.created_at),
229
+ auth_event.event_type,
230
+ auth_event.identity_provider,
231
+ auth_event.is_limited_access;
232
+ """
233
+ )
234
+
235
+ values = ",\n ".join(
236
+ f"('{pattern}', '{feature}')" for pattern, feature in ENDPOINT_FEATURES
237
+ )
238
+ op.execute(
239
+ f"""
240
+ CREATE OR REPLACE VIEW grafana.endpoint_feature
241
+ AS SELECT endpoint_feature.endpoint_pattern,
242
+ endpoint_feature.feature
243
+ FROM (VALUES
244
+ {values}
245
+ ) AS endpoint_feature(endpoint_pattern, feature);
246
+ """
247
+ )
248
+ _comment(
249
+ "endpoint_feature",
250
+ "The feature of each API path, as a LIKE pattern on "
251
+ "endpoint_request.endpoint_name; other paths are plumbing.",
252
+ )
253
+ op.execute(
254
+ f"""
255
+ CREATE OR REPLACE VIEW grafana.feature_request
256
+ AS SELECT er.id,
257
+ er.session_id,
258
+ s.inferred_user_id,
259
+ {USER_KIND} AS user_kind,
260
+ ef.feature,
261
+ er.created_at
262
+ FROM user_related.endpoint_request er
263
+ JOIN grafana.endpoint_feature ef ON er.endpoint_name LIKE ef.endpoint_pattern
264
+ JOIN user_related.session s ON s.id = er.session_id
265
+ JOIN user_related.inferred_user iu ON iu.id = s.inferred_user_id;
266
+ """
267
+ )
268
+ _comment(
269
+ "feature_request",
270
+ "The API requests that use a feature (see endpoint_feature), with their "
271
+ "user. user_kind is guest when the user has no account today.",
272
+ )
273
+ op.execute(
274
+ f"""
275
+ CREATE OR REPLACE VIEW grafana.active_user_day
276
+ AS SELECT date_trunc('day', er.created_at) AS day,
277
+ s.inferred_user_id,
278
+ {USER_KIND} AS user_kind,
279
+ count(*) AS requests
280
+ FROM user_related.endpoint_request er
281
+ JOIN user_related.session s ON s.id = er.session_id
282
+ JOIN user_related.inferred_user iu ON iu.id = s.inferred_user_id
283
+ GROUP BY (date_trunc('day', er.created_at)), s.inferred_user_id, iu.keycloak_id;
284
+ """
285
+ )
286
+ _comment(
287
+ "active_user_day",
288
+ "One row per user and day with at least one API request. user_kind is "
289
+ "guest when the user has no account today: a guest who logs in later "
290
+ "counts as an account for its past days too.",
291
+ )
292
+ op.execute(
293
+ """
294
+ CREATE OR REPLACE VIEW grafana.active_users_daily
295
+ AS SELECT active_user_day.day,
296
+ active_user_day.user_kind,
297
+ count(*) AS active_users,
298
+ sum(active_user_day.requests)::bigint AS requests
299
+ FROM grafana.active_user_day
300
+ GROUP BY active_user_day.day, active_user_day.user_kind;
301
+ """
302
+ )
303
+ _comment(
304
+ "active_users_daily",
305
+ "Users with at least one API request per day, guests and accounts "
306
+ "(see active_user_day). Days cannot be summed: count distinct users "
307
+ "of active_user_day over a range instead.",
308
+ )
309
+ op.execute(
310
+ """
311
+ CREATE OR REPLACE VIEW grafana.new_users_daily
312
+ AS SELECT date_trunc('day', inferred_user.created_at) AS day,
313
+ count(*) AS new_users,
314
+ count(inferred_user.keycloak_id) AS with_account
315
+ FROM user_related.inferred_user
316
+ GROUP BY (date_trunc('day', inferred_user.created_at));
317
+ """
318
+ )
319
+ _comment(
320
+ "new_users_daily",
321
+ "Users (inferred_user rows) created per day, and how many of them have "
322
+ "an account today.",
323
+ )
324
+ op.execute(
325
+ """
326
+ CREATE OR REPLACE VIEW grafana.feature_usage_daily
327
+ AS SELECT date_trunc('day', feature_request.created_at) AS day,
328
+ feature_request.feature,
329
+ feature_request.user_kind,
330
+ count(DISTINCT feature_request.inferred_user_id) AS users,
331
+ count(*) AS requests
332
+ FROM grafana.feature_request
333
+ GROUP BY (date_trunc('day', feature_request.created_at)),
334
+ feature_request.feature,
335
+ feature_request.user_kind;
336
+ """
337
+ )
338
+ _comment(
339
+ "feature_usage_daily",
340
+ "Distinct users and requests per day, feature and user_kind (see "
341
+ "feature_request). Days cannot be summed for users.",
342
+ )
343
+ op.execute(
344
+ """
345
+ CREATE OR REPLACE VIEW grafana.guest_limit_hit
346
+ AS SELECT guest_feature_usage.id,
347
+ guest_feature_usage.inferred_user_id,
348
+ feature.title AS feature,
349
+ guest_feature_usage.created_at
350
+ FROM user_related.guest_feature_usage
351
+ JOIN user_related.feature ON feature.id = guest_feature_usage.feature_id
352
+ WHERE guest_feature_usage.action = 'quota_exceeded';
353
+ """
354
+ )
355
+ _comment(
356
+ "guest_limit_hit",
357
+ "Each time a guest was refused a use of a feature (feature table title) "
358
+ "because its daily quota was used up.",
359
+ )
360
+ op.execute(
361
+ """
362
+ CREATE OR REPLACE VIEW grafana.guest_limit_hits_daily
363
+ AS SELECT date_trunc('day', guest_limit_hit.created_at) AS day,
364
+ guest_limit_hit.feature,
365
+ count(DISTINCT guest_limit_hit.inferred_user_id) AS users,
366
+ count(*) AS refusals
367
+ FROM grafana.guest_limit_hit
368
+ GROUP BY (date_trunc('day', guest_limit_hit.created_at)), guest_limit_hit.feature;
369
+ """
370
+ )
371
+ _comment(
372
+ "guest_limit_hits_daily",
373
+ "Guests refused for a used-up quota, and refusals, per day and feature "
374
+ "(see guest_limit_hit). Days cannot be summed for users.",
375
+ )
376
+ # same columns as 6d4346fad6f4, so its panels keep working; it now uses the
377
+ # current paths and matches a bookmark path with its document id
378
+ op.execute(
379
+ """
380
+ CREATE OR REPLACE VIEW grafana.used_feature_per_session
381
+ AS WITH used AS (
382
+ SELECT feature_request.session_id,
383
+ feature_request.feature,
384
+ count(*) AS cnt
385
+ FROM grafana.feature_request
386
+ GROUP BY feature_request.session_id, feature_request.feature
387
+ ), features AS (
388
+ SELECT DISTINCT endpoint_feature.feature
389
+ FROM grafana.endpoint_feature
390
+ ), sessions AS (
391
+ SELECT DISTINCT endpoint_request.session_id
392
+ FROM user_related.endpoint_request
393
+ )
394
+ SELECT s.inferred_user_id,
395
+ sessions.session_id,
396
+ features.feature AS feature_name,
397
+ COALESCE(used.cnt, 0::bigint) AS cnt,
398
+ COALESCE(used.cnt, 0::bigint) > 0 AS is_feature_used,
399
+ s.created_at AS session_created_at
400
+ FROM sessions
401
+ CROSS JOIN features
402
+ JOIN user_related.session s ON s.id = sessions.session_id
403
+ LEFT JOIN used ON used.session_id = sessions.session_id
404
+ AND used.feature = features.feature;
405
+ """
406
+ )
407
+ _comment(
408
+ "used_feature_per_session",
409
+ "One row per session with API requests and per feature (see "
410
+ "endpoint_feature): cnt requests, is_feature_used when cnt > 0.",
411
+ )
412
+
413
+
414
+ def downgrade() -> None:
415
+ # back to its old definition first, so the views it used can be dropped
416
+ op.execute(OLD_USED_FEATURE_PER_SESSION)
417
+ op.execute("COMMENT ON VIEW grafana.used_feature_per_session IS NULL;")
418
+ op.execute("DROP VIEW IF EXISTS grafana.guest_limit_hits_daily;")
419
+ op.execute("DROP VIEW IF EXISTS grafana.guest_limit_hit;")
420
+ op.execute("DROP VIEW IF EXISTS grafana.feature_usage_daily;")
421
+ op.execute("DROP VIEW IF EXISTS grafana.new_users_daily;")
422
+ op.execute("DROP VIEW IF EXISTS grafana.active_users_daily;")
423
+ op.execute("DROP VIEW IF EXISTS grafana.active_user_day;")
424
+ op.execute("DROP VIEW IF EXISTS grafana.feature_request;")
425
+ op.execute("DROP VIEW IF EXISTS grafana.endpoint_feature;")
426
+ op.execute("DROP VIEW IF EXISTS grafana.auth_event_daily;")
427
+ op.execute("DROP VIEW IF EXISTS grafana.auth_event;")
428
+ op.drop_index(
429
+ "auth_event_login_keycloak_session_key", table_name="auth_event", schema=SCHEMA
430
+ )
431
+ op.drop_index(
432
+ "auth_event_event_type_created_at_idx", table_name="auth_event", schema=SCHEMA
433
+ )
434
+ op.drop_index("auth_event_created_at_idx", table_name="auth_event", schema=SCHEMA)
435
+ op.drop_table("auth_event", schema=SCHEMA)
436
+ op.execute(f"DROP TYPE IF EXISTS {SCHEMA}.auth_event_type;")
@@ -19,13 +19,10 @@ depends_on: Union[str, Sequence[str], None] = None
19
19
 
20
20
 
21
21
  def upgrade() -> None:
22
- op.execute(
23
- """
24
- DROP MATERIALIZED VIEW corpus_related.corpus_name_embedding_model_lang;
25
- """
26
- )
27
- op.execute(
28
- """
22
+ op.execute("""
23
+ DROP MATERIALIZED VIEW IF EXISTS corpus_related.corpus_name_embedding_model_lang;
24
+ """)
25
+ op.execute("""
29
26
 
30
27
  CREATE MATERIALIZED VIEW corpus_related.corpus_name_embedding_model_lang
31
28
  TABLESPACE pg_default
@@ -67,18 +64,14 @@ WHERE
67
64
  rn = 1
68
65
 
69
66
  WITH DATA;
70
- """
71
- )
67
+ """)
72
68
 
73
69
 
74
70
  def downgrade() -> None:
75
- op.execute(
76
- """
71
+ op.execute("""
77
72
  DROP MATERIALIZED VIEW corpus_related.corpus_name_embedding_model_lang;
78
- """
79
- )
80
- op.execute(
81
- """
73
+ """)
74
+ op.execute("""
82
75
  CREATE MATERIALIZED VIEW corpus_related.corpus_name_embedding_model_lang
83
76
  TABLESPACE pg_default
84
77
  AS SELECT corpus.source_name,
@@ -89,5 +82,4 @@ def downgrade() -> None:
89
82
  JOIN corpus_related.embedding_model ON embedding_model.id = corpus_embedding_model.embedding_model_id
90
83
  WHERE corpus.is_active
91
84
  WITH DATA;
92
- """
93
- )
85
+ """)
@@ -50,3 +50,12 @@ class QuestionType(StrEnum):
50
50
  TEXT = auto()
51
51
  CHECKBOX = auto()
52
52
  PREDEFINED_TEXT = auto()
53
+
54
+
55
+ class AuthEventType(StrEnum):
56
+ # an email account created through WeLearn's sign-up form
57
+ SIGNUP = auto()
58
+ # a Keycloak account seen by WeLearn for the first time (first Google, university or email login)
59
+ ACCOUNT_CREATED = auto()
60
+ LOGIN = auto()
61
+ LOGOUT = auto()
@@ -11,6 +11,62 @@ from welearn_database.data.models import Base
11
11
  schema_name = DbSchemaEnum.GRAFANA.value
12
12
 
13
13
 
14
+ class ActiveUserDay(Base):
15
+ __tablename__ = "active_user_day"
16
+ __table_args__ = {"schema": schema_name}
17
+ __read_only__ = True
18
+
19
+ day: Mapped[datetime] = mapped_column(primary_key=True)
20
+ inferred_user_id: Mapped[uuid.UUID] = mapped_column(
21
+ UUID(as_uuid=True), primary_key=True
22
+ )
23
+ user_kind: Mapped[str] = mapped_column()
24
+ requests: Mapped[int] = mapped_column()
25
+
26
+
27
+ class ActiveUsersDaily(Base):
28
+ __tablename__ = "active_users_daily"
29
+ __table_args__ = {"schema": schema_name}
30
+ __read_only__ = True
31
+
32
+ day: Mapped[datetime] = mapped_column(primary_key=True)
33
+ user_kind: Mapped[str] = mapped_column(primary_key=True)
34
+ active_users: Mapped[int] = mapped_column()
35
+ requests: Mapped[int] = mapped_column()
36
+
37
+
38
+ class AuthEvent(Base):
39
+ __tablename__ = "auth_event"
40
+ __table_args__ = {"schema": schema_name}
41
+ __read_only__ = True
42
+
43
+ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
44
+ inferred_user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True))
45
+ session_id: Mapped[uuid.UUID | None] = mapped_column(
46
+ UUID(as_uuid=True), nullable=True
47
+ )
48
+ event_type: Mapped[str] = mapped_column()
49
+ identity_provider: Mapped[str | None] = mapped_column(nullable=True)
50
+ is_limited_access: Mapped[bool] = mapped_column()
51
+ created_at: Mapped[datetime] = mapped_column()
52
+ host: Mapped[str | None] = mapped_column(nullable=True)
53
+
54
+
55
+ class AuthEventDaily(Base):
56
+ __tablename__ = "auth_event_daily"
57
+ __table_args__ = {"schema": schema_name}
58
+ __read_only__ = True
59
+
60
+ # the view has no id: its grouping columns identify a row
61
+ day: Mapped[datetime] = mapped_column(primary_key=True)
62
+ event_type: Mapped[str] = mapped_column(primary_key=True)
63
+ provider: Mapped[str] = mapped_column(primary_key=True)
64
+ is_limited_access: Mapped[bool] = mapped_column(primary_key=True)
65
+ identity_provider: Mapped[str | None] = mapped_column(nullable=True)
66
+ events: Mapped[int] = mapped_column()
67
+ users: Mapped[int] = mapped_column()
68
+
69
+
14
70
  class Corpus(Base):
15
71
  __tablename__ = "corpus"
16
72
  __table_args__ = {"schema": schema_name}
@@ -61,6 +117,15 @@ class DocumentStateSummary(Base):
61
117
  total_documents: Mapped[int] = mapped_column()
62
118
 
63
119
 
120
+ class EndpointFeature(Base):
121
+ __tablename__ = "endpoint_feature"
122
+ __table_args__ = {"schema": schema_name}
123
+ __read_only__ = True
124
+
125
+ endpoint_pattern: Mapped[str] = mapped_column(primary_key=True)
126
+ feature: Mapped[str] = mapped_column()
127
+
128
+
64
129
  class EndpointRequest(Base):
65
130
  __tablename__ = "endpoint_request"
66
131
  __table_args__ = {"schema": schema_name}
@@ -74,6 +139,53 @@ class EndpointRequest(Base):
74
139
  created_at: Mapped[datetime] = mapped_column()
75
140
 
76
141
 
142
+ class FeatureRequest(Base):
143
+ __tablename__ = "feature_request"
144
+ __table_args__ = {"schema": schema_name}
145
+ __read_only__ = True
146
+
147
+ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
148
+ session_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True))
149
+ inferred_user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True))
150
+ user_kind: Mapped[str] = mapped_column()
151
+ feature: Mapped[str] = mapped_column()
152
+ created_at: Mapped[datetime] = mapped_column()
153
+
154
+
155
+ class FeatureUsageDaily(Base):
156
+ __tablename__ = "feature_usage_daily"
157
+ __table_args__ = {"schema": schema_name}
158
+ __read_only__ = True
159
+
160
+ day: Mapped[datetime] = mapped_column(primary_key=True)
161
+ feature: Mapped[str] = mapped_column(primary_key=True)
162
+ user_kind: Mapped[str] = mapped_column(primary_key=True)
163
+ users: Mapped[int] = mapped_column()
164
+ requests: Mapped[int] = mapped_column()
165
+
166
+
167
+ class GuestLimitHit(Base):
168
+ __tablename__ = "guest_limit_hit"
169
+ __table_args__ = {"schema": schema_name}
170
+ __read_only__ = True
171
+
172
+ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
173
+ inferred_user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True))
174
+ feature: Mapped[str] = mapped_column()
175
+ created_at: Mapped[datetime] = mapped_column()
176
+
177
+
178
+ class GuestLimitHitsDaily(Base):
179
+ __tablename__ = "guest_limit_hits_daily"
180
+ __table_args__ = {"schema": schema_name}
181
+ __read_only__ = True
182
+
183
+ day: Mapped[datetime] = mapped_column(primary_key=True)
184
+ feature: Mapped[str] = mapped_column(primary_key=True)
185
+ users: Mapped[int] = mapped_column()
186
+ refusals: Mapped[int] = mapped_column()
187
+
188
+
77
189
  class InferredUser(Base):
78
190
  __tablename__ = "inferred_user"
79
191
  __table_args__ = {"schema": schema_name}
@@ -83,6 +195,16 @@ class InferredUser(Base):
83
195
  created_at: Mapped[datetime] = mapped_column()
84
196
 
85
197
 
198
+ class NewUsersDaily(Base):
199
+ __tablename__ = "new_users_daily"
200
+ __table_args__ = {"schema": schema_name}
201
+ __read_only__ = True
202
+
203
+ day: Mapped[datetime] = mapped_column(primary_key=True)
204
+ new_users: Mapped[int] = mapped_column()
205
+ with_account: Mapped[int] = mapped_column()
206
+
207
+
86
208
  class ProcessState(Base):
87
209
  __tablename__ = "process_state"
88
210
  __table_args__ = {"schema": schema_name}
@@ -5,7 +5,12 @@ from sqlalchemy import Computed, ForeignKey, Index, func, text, types
5
5
  from sqlalchemy.dialects.postgresql import ENUM, TIMESTAMP
6
6
  from sqlalchemy.orm import Mapped, mapped_column, relationship
7
7
 
8
- from welearn_database.data.enumeration import DbSchemaEnum, FilterType, QuestionType
8
+ from welearn_database.data.enumeration import (
9
+ AuthEventType,
10
+ DbSchemaEnum,
11
+ FilterType,
12
+ QuestionType,
13
+ )
9
14
  from welearn_database.data.models.document_related import WeLearnDocument
10
15
 
11
16
  from . import Base
@@ -440,3 +445,78 @@ class GuestFeatureUsage(Base):
440
445
  )
441
446
  inferred_user: Mapped["InferredUser"] = relationship()
442
447
  feature: Mapped["Feature"] = relationship()
448
+
449
+
450
+ # the API records one login per Keycloak session; this filter lets a concurrent
451
+ # second insert of the same login fail on the unique index instead of duplicating it
452
+ _ONE_LOGIN_PER_KEYCLOAK_SESSION = text(
453
+ "event_type = 'login' AND keycloak_session_id IS NOT NULL"
454
+ )
455
+
456
+
457
+ class AuthEvent(Base):
458
+ """
459
+ An authentication event of a user: a sign-up through WeLearn's form, an
460
+ account seen for the first time, a login or a logout. The user is only
461
+ known by its pseudonymous inferred_user id: no email or name is stored.
462
+ identity_provider is the Keycloak IdP alias (google, a university...), NULL
463
+ for email/password or when unknown.
464
+ """
465
+
466
+ __tablename__ = "auth_event"
467
+ __table_args__ = (
468
+ Index("auth_event_created_at_idx", "created_at"),
469
+ Index("auth_event_event_type_created_at_idx", "event_type", "created_at"),
470
+ Index(
471
+ "auth_event_login_keycloak_session_key",
472
+ "inferred_user_id",
473
+ "keycloak_session_id",
474
+ unique=True,
475
+ postgresql_where=_ONE_LOGIN_PER_KEYCLOAK_SESSION,
476
+ sqlite_where=_ONE_LOGIN_PER_KEYCLOAK_SESSION,
477
+ ),
478
+ {"schema": DbSchemaEnum.USER_RELATED.value},
479
+ )
480
+
481
+ id: Mapped[UUID] = mapped_column(
482
+ types.Uuid, primary_key=True, nullable=False, server_default="gen_random_uuid()"
483
+ )
484
+ inferred_user_id: Mapped[UUID] = mapped_column(
485
+ types.Uuid,
486
+ ForeignKey(
487
+ f"{DbSchemaEnum.USER_RELATED.value}.inferred_user.id",
488
+ name="auth_event_inferred_user_id_fkey",
489
+ ondelete="CASCADE",
490
+ ),
491
+ nullable=False,
492
+ )
493
+ session_id: Mapped[UUID | None] = mapped_column(
494
+ types.Uuid,
495
+ ForeignKey(
496
+ f"{DbSchemaEnum.USER_RELATED.value}.session.id",
497
+ name="auth_event_session_id_fkey",
498
+ ondelete="SET NULL",
499
+ ),
500
+ nullable=True,
501
+ )
502
+ event_type: Mapped[str] = mapped_column(
503
+ ENUM(
504
+ *(e.value for e in AuthEventType),
505
+ name="auth_event_type",
506
+ schema=DbSchemaEnum.USER_RELATED.value,
507
+ # SQLite has no enum type: a CHECK keeps the same rule in the tests
508
+ create_constraint=True,
509
+ ),
510
+ nullable=False,
511
+ )
512
+ identity_provider: Mapped[str | None]
513
+ is_limited_access: Mapped[bool]
514
+ keycloak_session_id: Mapped[str | None]
515
+ created_at: Mapped[datetime] = mapped_column(
516
+ TIMESTAMP(timezone=False),
517
+ nullable=False,
518
+ default=func.localtimestamp(),
519
+ server_default="NOW()",
520
+ )
521
+ inferred_user: Mapped["InferredUser"] = relationship()
522
+ session: Mapped["Session | None"] = relationship()
@@ -0,0 +1,150 @@
1
+ Metadata-Version: 2.3
2
+ Name: welearn-database
3
+ Version: 1.5.8.dev0
4
+ Summary: All stuff related to relationnal database from the WeLearn project
5
+ License: cc-by-sa-nc
6
+ Author: Théo
7
+ Author-email: theo.nardin@cri-paris.org
8
+ Requires-Python: >=3.10
9
+ Classifier: License :: Other/Proprietary License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Requires-Dist: alembic (>=1.4.3,<2.0.0)
16
+ Requires-Dist: psycopg2-binary (>=2.9.11,<3.0.0)
17
+ Requires-Dist: python-dotenv (>=1.2.2,<2.0.0)
18
+ Requires-Dist: sqlalchemy (>=2.0.43,<3.0.0)
19
+ Description-Content-Type: text/markdown
20
+
21
+ # WeLearn Database
22
+
23
+ This repository contains the database schema and sample data for the WeLearn application, an online learning platform.
24
+
25
+ ## Pypi Package
26
+ You can install this pacakge via pypi :
27
+
28
+ ```bash
29
+ pip install welearn-database
30
+ ```
31
+ or you can read pypi page [here](https://pypi.org/project/welearn-database/)
32
+
33
+ ## Environment Variables
34
+ Before running the application, make sure to set the following environment variables:
35
+ ```
36
+ PG_USER=<pg user>
37
+ PG_PASSWORD=<pg password>
38
+ PG_HOST=<pg address>
39
+ PG_PORT=<pg port, 5432 by default>
40
+ PG_DB=<pg database name>
41
+ PG_DRIVER=<driver to use, pg default is : postgresql+psycopg2>
42
+ PG_SCHEMA=document_related,corpus_related,user_related,agent_related
43
+ LOG_LEVEL=INFO
44
+ LOG_FORMAT=[%(asctime)s][%(name)s][%(levelname)s] - %(message)s
45
+ ```
46
+
47
+ ## Release Workflow
48
+ A schema change goes from code to the prod database in seven steps. The commands for steps 3 and 7 are in [Database Migrations](#database-migrations).
49
+
50
+ 1. **Change the code.** On a feature branch, edit the models in `welearn_database/data/models`.
51
+ 2. **Write the Alembic migration.** Add one revision for the release in `welearn_database/alembic/versions`. Name its id after the version with underscores, and point `down_revision` at the previous one:
52
+ ```bash
53
+ poetry run alembic revision -m "add my table" --rev-id 1_5_8
54
+ # creates welearn_database/alembic/versions/1_5_8_add_my_table.py
55
+ ```
56
+ `--autogenerate` can draft it from the models, but it ignores indexes and compares against the database in `.env`, so always read and fix the result. Test `upgrade` then `downgrade` on a local database (`welearn-fullstack`, `scripts/bootstrap-db.sh`). `poetry run alembic heads` must show a single head. Open the PR and get it merged on `main`.
57
+ 3. **Update the dev databases.** On Azure dev, preview the SQL with `--sql`, then run `alembic -x env=dev upgrade <revision>` (VPN on). On Scaleway dev, generate the SQL and run it in pgAdmin (see [Scaleway dev](#scaleway-dev-run-the-sql-in-pgadmin)). If the change only adds tables or columns, the API already deployed on dev keeps working. If it renames or drops something, deploy the matching API at the same time.
58
+ 4. **Tag a `.dev` version and make a pre-release.**
59
+ - In `pyproject.toml`, set `version = "1.5.8.dev0"` and merge it on `main`.
60
+ - Create a GitHub release with the same tag (`1.5.8.dev0`) on `main`, with "Set as a pre-release" checked.
61
+ - Pushing the tag runs the workflow, which publishes the package to PyPI. Every push also publishes to TestPyPI.
62
+ - PyPI normalizes the version: a tag `1.5.7.dev` is published as `1.5.7.dev0`.
63
+ 5. **Validate in dev.**
64
+ - In the API, pin the exact pre-release, `welearn-database = "1.5.8.dev0"`, then run `poetry lock`. A caret constraint like `^1.5.7` never picks up a `.dev` version.
65
+ - Deploy on dev and test the feature.
66
+ - If you need a fix, publish `1.5.8.dev1` the same way. If the migration itself changed, run `downgrade` then `upgrade` on dev again.
67
+ 6. **Tag the prod version, coordinated with the API.**
68
+ - Set `version = "1.5.8"` (no `.dev`), merge it, and create a normal GitHub release (not a pre-release) tagged `1.5.8`.
69
+ - In the API, a PR moves the dependency to `^1.5.8`.
70
+ - Agree with the API team on when it goes out: that PR must not reach an environment whose database hasn't been migrated (step 7).
71
+ 7. **Update the prod database.**
72
+ - Migrate staging first, then prod. Both are on Azure; Scaleway only has a dev environment for now.
73
+ - Make sure a recent backup exists, then preview with `--sql` and run `alembic -x env=<staging|prod> upgrade <revision>`. For `prod`, `env.py` asks you to type the environment name before it goes on.
74
+ - After that, deploy the API version that uses the new schema.
75
+
76
+ ## Database Migrations
77
+ Migrations are Alembic revisions in `welearn_database/alembic/versions`. Run them from a clone of this repository, after `poetry install`, not from the package installed from PyPI.
78
+
79
+ ### Setup
80
+ - Create one file per environment at the root of the repository, copied from `.env.example`: `.env.dev`, `.env.staging`, `.env.prod`. Only `PG_HOST`, `PG_DB` and the credentials change between them. `PG_DB` is the database name (the API calls it `PG_DATABASE`).
81
+ - These files are git-ignored. Keep them private with `chmod 600 .env.*`.
82
+ - Pick the database with `-x env=<name>`, which loads `.env.<name>`. The flag goes before the subcommand: `poetry run alembic -x env=staging current`. The file's values override variables exported in your shell.
83
+ - Without `-x env`, `env.py` loads `.env` (handy for a local database), and a variable already exported in your shell wins. Check that `env | grep PG_` prints nothing, or only the values you expect.
84
+ - The dev and staging databases need the VPN.
85
+ - The Scaleway database isn't reachable from your machine, so it has no `.env` file. See [Scaleway dev](#scaleway-dev-run-the-sql-in-pgadmin).
86
+
87
+ ### Check where the database is
88
+ ```bash
89
+ poetry run alembic -x env=dev current # revision the database is at
90
+ poetry run alembic heads # latest revision in this repository
91
+ poetry run alembic history # full chain
92
+ ```
93
+ `env.py` prints the target first, for example `Target: staging -> <host>/welearn_datastack_staging`. For `prod`, or a host with `prod` in its name, it asks you to type the environment name before it connects.
94
+
95
+ The staging database has no `alembic_version` table yet, so `current` prints no revision there. Before its first `upgrade`, check which revision its schema matches and record it with `poetry run alembic -x env=staging stamp <revision>`. `stamp` changes nothing but `alembic_version`.
96
+
97
+ ### Preview the SQL (`--sql`, nothing is applied)
98
+ ```bash
99
+ poetry run alembic -x env=dev upgrade 1_5_6:1_5_7 --sql > 1_5_7.sql
100
+ ```
101
+ - Offline mode only writes the SQL out. It doesn't connect to the database, doesn't change it, and doesn't update `alembic_version`. The SQL is the same for every environment, so any `-x env` works.
102
+ - It needs a `from:to` range, because it can't read the database's current revision.
103
+ - If you see `-- Running upgrade 1_5_6 -> 1_5_7` followed by SQL, nothing was applied.
104
+ - If you run the file by hand (psql, DBeaver…), it ends with `UPDATE alembic_version …`. That table lives in the `public` schema.
105
+
106
+ ### Apply the migration
107
+ ```bash
108
+ poetry run alembic -x env=staging upgrade 1_5_7 # or: upgrade head
109
+ poetry run alembic -x env=staging current # should print 1_5_7
110
+ ```
111
+ - Upgrading to a named revision runs only what you expect.
112
+ - A real run logs `INFO … Running upgrade 1_5_6 -> 1_5_7, …` and prints no SQL.
113
+
114
+ ### Roll back
115
+ ```bash
116
+ poetry run alembic -x env=staging downgrade 1_5_6
117
+ ```
118
+ This runs the revision's `downgrade()`. For `1_5_7`, that drops the `feature`, `thread` and `guest_feature_usage` tables.
119
+
120
+ ### Scaleway dev: run the SQL in pgAdmin
121
+ The Scaleway database is only reachable from inside the cluster, so Alembic can't connect to it. Generate the SQL locally and run it in the cluster's pgAdmin:
122
+ 1. In pgAdmin, check where the database is:
123
+ ```sql
124
+ SELECT version_num FROM public.alembic_version;
125
+ ```
126
+ 2. Generate the SQL from that revision to the target one. Nothing connects: `-x env=dev` only fills in the URL Alembic needs.
127
+ ```bash
128
+ poetry run alembic -x env=dev upgrade 1_5_6:1_5_7 --sql > 1_5_7.sql
129
+ ```
130
+ 3. Read the file, then paste it into pgAdmin's Query Tool on the Scaleway database and run it. It is wrapped in `BEGIN;` … `COMMIT;`, so it applies fully or not at all, and it ends with `UPDATE public.alembic_version …`.
131
+ 4. Run the query from step 1 again: it should print the target revision.
132
+
133
+ To roll back, generate the downgrade the same way, with the range reversed: `poetry run alembic -x env=dev downgrade 1_5_7:1_5_6 --sql > 1_5_7_down.sql`.
134
+
135
+ ### Order across environments
136
+ Migrate dev (Azure with `-x env=dev`, Scaleway through pgAdmin), then staging (`-x env=staging`), then prod (`-x env=prod`). An environment must be migrated before an API version that uses the new tables is deployed there. A migration that only adds tables, like `1_5_7`, doesn't break an older API running on the migrated database.
137
+
138
+ ## Database Schema
139
+ The database schema is organized into four main schemas:
140
+ - `document_related`: Contains tables related to documents and their metadata.
141
+ - `corpus_related`: Contains tables related to corpora and their metadata.
142
+ - `user_related`: Contains tables related to users and their profiles.
143
+ - `agent_related`: Contains tables related to agents and their interactions.
144
+
145
+ ## How to Use
146
+ Data models are defined using SQLAlchemy ORM. You can import the models and use them to interact with the database.
147
+ ```python
148
+ from welearn_database.data.models import WeLearnDocument
149
+ ```
150
+ Every model are accessible there, schema are handled under the hood.
@@ -1,6 +1,6 @@
1
1
  welearn_database/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
2
  welearn_database/alembic/README,sha256=MVlc9TYmr57RbhXET6QxgyCcwWP7w-vLkEsirENqiIQ,38
3
- welearn_database/alembic/env.py,sha256=hCDvutEfJ5Kx7WfHkWKsSqSFc_t08igkoZ6HTzY6gAo,3464
3
+ welearn_database/alembic/env.py,sha256=-YSCXHqvsMVTwfDIRGMbrJTjUlaNO96aWayZFHuydcY,4589
4
4
  welearn_database/alembic/script.py.mako,sha256=MEqL-2qATlST9TAOeYgscMn1uy6HUS9NFvDgl93dMj8,635
5
5
  welearn_database/alembic/versions/0310ff0bda4f_track_document_last_state.py,sha256=3ohy8ZsAdPVQnfMhCK0XdgR6phhD2Qt2aeriBDlOs_c,1030
6
6
  welearn_database/alembic/versions/068312e7800c_add_referrer_origin_column_to_user_and_.py,sha256=H9rGLdUy9Xhz7P0H-JJagGknloP5RyrlXlfOwU45gf8,1008
@@ -9,6 +9,7 @@ welearn_database/alembic/versions/16ff997426d3_remove_error_retrieval_unique_con
9
9
  welearn_database/alembic/versions/1_5_5_analytical_view_for_research.py,sha256=p_cooMLToNBxaa1PxIYDBuBNmGb7i4gOXpk43TYEADU,1732
10
10
  welearn_database/alembic/versions/1_5_6_add_is_hidden_column_to_category.py,sha256=RQ8ej4KwJI8LzE5usczjDfas_Vqzz3n4xbK6iwETuUI,669
11
11
  welearn_database/alembic/versions/1_5_7_add_feature_thread_and_guest_feature_usage_tables.py,sha256=VnElYNQuEVdRe6sJcDT40EzwSr8a0FsC1OKAGtbvKiQ,4076
12
+ welearn_database/alembic/versions/1_5_8_add_auth_event_table_and_grafana_views.py,sha256=xlc8N2a4Q-Q9Mi9cQpmPmY8U7HdRAhvu8lmhkBf-a50,15493
12
13
  welearn_database/alembic/versions/2ad4895b2674_data_collection.py,sha256=MZOfb1agtrugsY5okwtRPTDBKwixgg1MaqLpod0KjL0,2975
13
14
  welearn_database/alembic/versions/4c7161819e5a_grafana_views.py,sha256=t03z7pPatxzxmBkpMOy5emEUZGKbxsyJ8wOmA1TbQiM,6359
14
15
  welearn_database/alembic/versions/4f5a188dd614_add_main_url_column.py,sha256=VuHPPC2v8uYTFiO1ouGBXpenw3gtRbs_LlMWalvYeiE,681
@@ -26,7 +27,7 @@ welearn_database/alembic/versions/96bba9e4842a_merge_external_id_error_quality.p
26
27
  welearn_database/alembic/versions/9b4f1da0c1f2_data_collection_for_focus_group.py,sha256=lsQBzBOqQffjqGNZcJ5iJkcbxAPrve2so69eNk8pv-A,2209
27
28
  welearn_database/alembic/versions/a50a1db3ca2a_add_used_since_column_for_embeddings.py,sha256=PRYDlKeBnobJc62Neph-DXHMKopf7I2chzV9M0B4bvU,836
28
29
  welearn_database/alembic/versions/b031206324b7_agent_related.py,sha256=BAB1js3qgR8FLojfhNyVVKU7tDBjxPAtY8MheLbe15g,4448
29
- welearn_database/alembic/versions/b049924f7067_modify_corpus_name_embedding_model_lang_.py,sha256=v9h4jxHakTTxupJzw4lPb-ZEnhzV5BQOOiAE5YITl-s,2167
30
+ welearn_database/alembic/versions/b049924f7067_modify_corpus_name_embedding_model_lang_.py,sha256=S4Bc9DynCsckgXNyrG1eS6N_bNpOL8XSchPzMTPDSdg,2121
30
31
  welearn_database/alembic/versions/b84462ca3800_update_grafana_process_state_view.py,sha256=5xmW9BO3Y3Aq-qyssXHZGKk6pNfX_9oq9Grpwk6-pug,1318
31
32
  welearn_database/alembic/versions/ccdbd708c997_create_column_external_id.py,sha256=xQtLsONPsaqHFck_RgV2VAcpRN-RFdeF3relGQ7A7-c,1757
32
33
  welearn_database/alembic/versions/d22d6324c256_cleaned_document_state.py,sha256=gSeipL3j2PnzS6sDjVojFz92EyuUa9TwzHkoe2iZc3o,656
@@ -38,19 +39,19 @@ welearn_database/alembic/versions/f5e91a5c950d_add_analytic_form.py,sha256=q0BBZ
38
39
  welearn_database/alembic/versions/f8602200fa99_update_session_view.py,sha256=92lb6Lr-9HuW3zVHuD5SzyUhHRQrwVup8a3QSTI1s4g,831
39
40
  welearn_database/data/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
40
41
  welearn_database/data/details_dict.py,sha256=9C-WA6owsMh_ZflbV6LvZ8084QjPZK8-wN-bXPn5Zn8,957
41
- welearn_database/data/enumeration.py,sha256=BDdwzV5pHapyCQoBNwPj0i-DHRcgA4VJr3sBc44ba68,1187
42
+ welearn_database/data/enumeration.py,sha256=kqivf7bAgGgjlVFZrnM5w04SyNO_25SFn88dAncoAc8,1471
42
43
  welearn_database/data/models/__init__.py,sha256=J0k9nHY6D5j-nEXGWYsbI2nBhmlHPaXIaW0RWsUs32A,1149
43
44
  welearn_database/data/models/agent_related.py,sha256=Z0foQ-dcsORp7Wi_bPMsS2zulU843MySMWxrC7GLD7I,3139
44
45
  welearn_database/data/models/corpus_related.py,sha256=gU3pkGH0qr6_06mavc4R6W1MlvBl0NTPgGm3JqVvT7A,6910
45
46
  welearn_database/data/models/document_related.py,sha256=PLsOIWUrwT0tgRnY58EbhSEFondWahD3kq5wuik6yPk,18427
46
- welearn_database/data/models/grafana.py,sha256=Q_8RKoXSyNShqVx7Bl-763ImuCnqzmWdJU04mlg4axU,5614
47
- welearn_database/data/models/user_related.py,sha256=OzRednZ10jDKKyC_CouKDwqaZWA_heKTb9y7HAIwvAE,14309
47
+ welearn_database/data/models/grafana.py,sha256=Lz8geY_Td5QByIX75ZuZ_3e5I3jtbMFPLQmcWYDMsS8,9852
48
+ welearn_database/data/models/user_related.py,sha256=htuA1LVEoFRn5-zv5BZpPajKNsBfZF6ntP9VHcmAzmk,17019
48
49
  welearn_database/database_utils.py,sha256=fFCjFHXLYa80XblQAB5so0NQgd5yr_RmO5rM4r3qm0I,800
49
50
  welearn_database/exceptions.py,sha256=6XP4vxRSJ40mwqGZ7PdjWaW1MarZLX3vRsBL9WQe4WI,1173
50
51
  welearn_database/modules/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
51
52
  welearn_database/modules/text_cleaning.py,sha256=N_OgJNsjOOKp6m05iljvM0f22_U9wEhy7nKpqnfuG0k,2169
52
53
  welearn_database/regular_expression.py,sha256=qAUCoxBSfzD1DLlaRfz0R8H6wp7iyQPiBgNhNOT-2Qw,668
53
- welearn_database-1.5.7.dev0.dist-info/LICENSE,sha256=5mwmnUgZqqs0tJ71IgxN2rZ1byG7UYB2Gk64Vh8re70,20850
54
- welearn_database-1.5.7.dev0.dist-info/METADATA,sha256=TJG1esFbwcOVze0iq3ymOzhkSK6ELhYLfVi--D6fSF0,2182
55
- welearn_database-1.5.7.dev0.dist-info/WHEEL,sha256=RaoafKOydTQ7I_I3JTrPCg6kUmTgtm4BornzOqyEfJ8,88
56
- welearn_database-1.5.7.dev0.dist-info/RECORD,,
54
+ welearn_database-1.5.8.dev0.dist-info/LICENSE,sha256=5mwmnUgZqqs0tJ71IgxN2rZ1byG7UYB2Gk64Vh8re70,20850
55
+ welearn_database-1.5.8.dev0.dist-info/METADATA,sha256=SY_BwetLAuUieHrQcrGgQ5usO0KPBQfkFfdP-Azy3G4,9546
56
+ welearn_database-1.5.8.dev0.dist-info/WHEEL,sha256=RaoafKOydTQ7I_I3JTrPCg6kUmTgtm4BornzOqyEfJ8,88
57
+ welearn_database-1.5.8.dev0.dist-info/RECORD,,
@@ -1,59 +0,0 @@
1
- Metadata-Version: 2.3
2
- Name: welearn-database
3
- Version: 1.5.7.dev0
4
- Summary: All stuff related to relationnal database from the WeLearn project
5
- License: cc-by-sa-nc
6
- Author: Théo
7
- Author-email: theo.nardin@cri-paris.org
8
- Requires-Python: >=3.10
9
- Classifier: License :: Other/Proprietary License
10
- Classifier: Programming Language :: Python :: 3
11
- Classifier: Programming Language :: Python :: 3.10
12
- Classifier: Programming Language :: Python :: 3.11
13
- Classifier: Programming Language :: Python :: 3.12
14
- Classifier: Programming Language :: Python :: 3.13
15
- Requires-Dist: alembic (>=1.4.3,<2.0.0)
16
- Requires-Dist: psycopg2-binary (>=2.9.11,<3.0.0)
17
- Requires-Dist: python-dotenv (>=1.2.2,<2.0.0)
18
- Requires-Dist: sqlalchemy (>=2.0.43,<3.0.0)
19
- Description-Content-Type: text/markdown
20
-
21
- # WeLearn Database
22
-
23
- This repository contains the database schema and sample data for the WeLearn application, an online learning platform.
24
-
25
- ## Pypi Package
26
- You can install this pacakge via pypi :
27
-
28
- ```bash
29
- pip install welearn-database
30
- ```
31
- or you can read pypi page [here](https://pypi.org/project/welearn-database/)
32
-
33
- ## Environment Variables
34
- Before running the application, make sure to set the following environment variables:
35
- ```
36
- PG_USER=<pg user>
37
- PG_PASSWORD=<pg password>
38
- PG_HOST=<pg address>
39
- PG_PORT=<pg port, 5432 by default>
40
- PG_DB=<pg database name>
41
- PG_DRIVER=<driver to use, pg default is : postgresql+psycopg2>
42
- PG_SCHEMA=document_related,corpus_related,user_related,agent_related
43
- LOG_LEVEL=INFO
44
- LOG_FORMAT=[%(asctime)s][%(name)s][%(levelname)s] - %(message)s
45
- ```
46
-
47
- ## Database Schema
48
- The database schema is organized into four main schemas:
49
- - `document_related`: Contains tables related to documents and their metadata.
50
- - `corpus_related`: Contains tables related to corpora and their metadata.
51
- - `user_related`: Contains tables related to users and their profiles.
52
- - `agent_related`: Contains tables related to agents and their interactions.
53
-
54
- ## How to Use
55
- Data models are defined using SQLAlchemy ORM. You can import the models and use them to interact with the database.
56
- ```python
57
- from welearn_database.data.models import WeLearnDocument
58
- ```
59
- Every model are accessible there, schema are handled under the hood.