-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
5249 lines (4915 loc) · 203 KB
/
Copy pathdatabase.py
File metadata and controls
5249 lines (4915 loc) · 203 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import json
import os
import hashlib
from datetime import datetime
from typing import Any, List, Optional, Tuple
from uuid import uuid4
from auth import hash_password, normalize_username, verify_password_hash, parse_password_hash
from config import Config
from models import (
BilibiliCourse,
AnalysisReport,
AnalysisTask,
ClaimCheckResult,
FitExamAttempt,
FitExamPaper,
FitExamQuestion,
JDRecord,
JobAnalysis,
JobPosting,
SalarySnapshot,
User,
)
def safe_datetime(val) -> Optional[datetime]:
if val is None:
return None
if isinstance(val, datetime):
return val.replace(tzinfo=None)
if isinstance(val, str):
try:
return datetime.fromisoformat(val).replace(tzinfo=None)
except ValueError:
return datetime.strptime(val.split(".")[0], "%Y-%m-%d %H:%M:%S")
return None
def safe_json_load(value: Any, default: Any = None) -> Any:
if value is None:
return default
if isinstance(value, (dict, list)):
return value
if not isinstance(value, (str, bytes, bytearray)):
return value
try:
return json.loads(value)
except (TypeError, ValueError, json.JSONDecodeError):
return default
class DatabaseCursorWrapper:
def __init__(self, cursor, is_postgres: bool):
if not is_postgres:
raise RuntimeError("DatabaseCursorWrapper supports PostgreSQL connections only.")
self._cursor = cursor
self._lastrowid = None
def execute(self, query: str, params: tuple = ()):
query = query.replace("?", "%s")
# Translate legacy table creation keywords used by older query helpers.
if "CREATE TABLE" in query.upper():
query = query.replace("INTEGER PRIMARY KEY AUTOINCREMENT", "SERIAL PRIMARY KEY")
is_insert = query.strip().upper().startswith("INSERT")
if is_insert and "RETURNING" not in query.upper():
# Avoid appending "RETURNING id" if the table does not have an "id" column
q_lower = query.lower()
has_no_id_col = (
"into sessions" in q_lower or
"into user_settings" in q_lower or
"into agent_resume_tasks" in q_lower or
"into agent_resume_conversation_state" in q_lower or
"into agent_cache_entries" in q_lower or
"into model_config_assignments" in q_lower
)
if not has_no_id_col:
q = query.strip()
if q.endswith(";"):
q = q[:-1]
query = f"{q} RETURNING id"
self._cursor.execute(query, params)
res = self._cursor.fetchone()
self._lastrowid = res[0] if res else None
return self
self._cursor.execute(query, params)
return self
@property
def lastrowid(self):
return self._lastrowid
def fetchone(self):
return self._cursor.fetchone()
def fetchall(self):
return self._cursor.fetchall()
def fetchmany(self, size=None):
return self._cursor.fetchmany(size) if size is not None else self._cursor.fetchmany()
def __getattr__(self, name):
return getattr(self._cursor, name)
def __iter__(self):
return iter(self._cursor)
class DatabaseConnectionWrapper:
def __init__(self, conn, is_postgres: bool):
if not is_postgres:
raise RuntimeError("DatabaseConnectionWrapper supports PostgreSQL connections only.")
self._conn = conn
def cursor(self):
return DatabaseCursorWrapper(self._conn.cursor(), True)
def commit(self):
return self._conn.commit()
def rollback(self):
return self._conn.rollback()
def close(self):
return self._conn.close()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is not None:
self.rollback()
else:
self.commit()
self.close()
def __getattr__(self, name):
return getattr(self._conn, name)
class Database:
_DEFAULT_DB_PATH = Config.DB_PATH
@property
def is_postgres(self) -> bool:
return True
@is_postgres.setter
def is_postgres(self, value: bool) -> None:
if value is not True:
raise RuntimeError("InternPath runtime supports PostgreSQL only.")
def __init__(self, db_path: Optional[str] = None):
self.db_path = db_path if db_path is not None else Config.DB_PATH
self.database_url = (Config.DATABASE_URL or os.getenv("DATABASE_URL") or "").strip()
self.schema_name = self._resolve_schema_name(self.db_path)
if not self.database_url:
raise RuntimeError("DATABASE_URL is required. InternPath now runs on PostgreSQL only.")
if not (self.database_url.startswith("postgresql://") or self.database_url.startswith("postgres://")):
raise RuntimeError("DATABASE_URL must be a PostgreSQL connection string.")
self.is_postgres = True
try:
import psycopg2
conn = psycopg2.connect(self.database_url)
self._prepare_connection(conn)
conn.close()
except Exception as exc:
raise RuntimeError(f"PostgreSQL is required but unavailable: {exc}") from exc
self.init_db()
def get_connection(self):
import psycopg2
conn = psycopg2.connect(self.database_url)
self._prepare_connection(conn)
return DatabaseConnectionWrapper(conn, True)
def _resolve_schema_name(self, db_path: str) -> str:
configured_schema = (Config.DATABASE_SCHEMA or os.getenv("DATABASE_SCHEMA") or "public").strip() or "public"
if self._is_custom_db_path(db_path):
path_key = os.path.abspath(str(db_path)).lower()
return f"internpath_test_{hashlib.sha1(path_key.encode('utf-8')).hexdigest()[:16]}"
return self._validate_schema_name(configured_schema)
def _is_custom_db_path(self, db_path: str) -> bool:
try:
return os.path.abspath(str(db_path)) != os.path.abspath(str(self._DEFAULT_DB_PATH))
except Exception:
return str(db_path) != str(self._DEFAULT_DB_PATH)
def _validate_schema_name(self, schema_name: str) -> str:
if not schema_name or not schema_name[0].isalpha() or not schema_name.replace("_", "").isalnum():
raise RuntimeError("DATABASE_SCHEMA must contain only letters, numbers, and underscores, and start with a letter.")
return schema_name
def _prepare_connection(self, conn) -> None:
schema_name = self._validate_schema_name(self.schema_name)
cursor = conn.cursor()
cursor.execute(f'CREATE SCHEMA IF NOT EXISTS "{schema_name}"')
cursor.execute(f'SET search_path TO "{schema_name}", public')
conn.commit()
cursor.close()
@classmethod
def for_user(cls, user_id: int) -> "Database":
db = cls()
db._ensure_user_id(user_id)
return db
def _ensure_user_id(self, user_id: int) -> None:
conn = self.get_connection()
cursor = conn.cursor()
username = f"system-user-{int(user_id)}@internpath.local"
cursor.execute(
"""
INSERT INTO users (id, username, password_hash, created_at)
VALUES (?, ?, ?, ?)
ON CONFLICT (id) DO NOTHING
""",
(int(user_id), username, hash_password(f"system-user-{int(user_id)}"), datetime.now().isoformat()),
)
cursor.execute(
"SELECT setval(pg_get_serial_sequence('users', 'id'), COALESCE((SELECT MAX(id) FROM users), 1), true)"
)
conn.commit()
conn.close()
def _ensure_numeric_user_id(self, user_id: Any) -> None:
try:
numeric_user_id = int(user_id)
except (TypeError, ValueError):
return
self._ensure_user_id(numeric_user_id)
def _serialize_datetime_value(self, value: Any) -> Any:
if isinstance(value, datetime):
return value.isoformat()
return value
def _column_exists(self, cursor, table_name: str, column_name: str) -> bool:
cursor.execute(
"""
SELECT EXISTS (
SELECT 1
FROM information_schema.columns
WHERE table_schema = current_schema()
AND table_name = %s
AND column_name = %s
)
""",
(table_name.lower(), column_name.lower()),
)
return bool(cursor.fetchone()[0])
def _table_columns(self, cursor, table_name: str) -> set[str]:
cursor.execute(
"""
SELECT column_name
FROM information_schema.columns
WHERE table_schema = current_schema()
AND table_name = %s
""",
(table_name.lower(),),
)
return {str(row[0]).lower() for row in cursor.fetchall()}
def _is_unique_constraint_error(self, exc: Exception) -> bool:
if getattr(exc, "pgcode", None) == "23505":
return True
message = str(exc).lower()
return "unique" in message or "duplicate" in message
def init_db(self):
conn = self.get_connection()
cursor = conn.cursor()
if self.is_postgres:
# 1. Enable required PostgreSQL extensions.
try:
cursor.execute("CREATE EXTENSION IF NOT EXISTS pgcrypto WITH SCHEMA public;")
conn.commit()
except Exception as exc:
try:
conn.rollback()
except Exception:
pass
raise RuntimeError(f"PostgreSQL extension pgcrypto is required: {exc}") from exc
try:
cursor.execute("CREATE EXTENSION IF NOT EXISTS vector WITH SCHEMA public;")
conn.commit()
except Exception as exc:
try:
conn.rollback()
except Exception:
pass
if Config.PGVECTOR_REQUIRED:
raise RuntimeError(f"PostgreSQL extension vector is required: {exc}") from exc
raise
# 2. Create users table
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
username VARCHAR(255) UNIQUE NOT NULL,
password_hash VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
"""
)
# 3. Create registered_devices table
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS registered_devices (
id SERIAL PRIMARY KEY,
device_signature VARCHAR(255) UNIQUE NOT NULL,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
username VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
"""
)
# 4. Create analysis_records table
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS analysis_records (
id VARCHAR(255) PRIMARY KEY DEFAULT gen_random_uuid()::text,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
status VARCHAR(50) NOT NULL,
input_json JSONB NOT NULL,
parsed_jd_json JSONB,
parsed_resume_json JSONB,
requirement_matches_json JSONB,
hard_constraint_results_json JSONB,
result_json JSONB,
failed_step VARCHAR(255),
error_message TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
"""
)
# 5. Create drafts table
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS drafts (
id VARCHAR(255) PRIMARY KEY DEFAULT gen_random_uuid()::text,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
status VARCHAR(50) NOT NULL,
input_json JSONB NOT NULL,
failed_step VARCHAR(255),
error_message TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
"""
)
# 5b. Create resumes table
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS resumes (
id VARCHAR(255) PRIMARY KEY,
user_id VARCHAR(255) NOT NULL,
file_name VARCHAR(255) NOT NULL,
file_size INTEGER NOT NULL,
file_type VARCHAR(100),
parsed_json JSONB NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
"""
)
# 6. Create user_settings table
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS user_settings (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
settings_json JSONB NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
"""
)
# 7. Create model_configs table
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS model_configs (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
provider VARCHAR(50) NOT NULL,
model_id VARCHAR(255) NOT NULL,
display_name VARCHAR(255),
encrypted_api_key TEXT,
is_server_managed BOOLEAN NOT NULL DEFAULT FALSE,
enabled BOOLEAN NOT NULL DEFAULT TRUE,
config_json TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
owner_type VARCHAR(50) NOT NULL DEFAULT 'user',
created_by_admin_id INTEGER REFERENCES users(id) ON DELETE SET NULL
);
"""
)
if not self._column_exists(cursor, "model_configs", "config_json"):
cursor.execute("ALTER TABLE model_configs ADD COLUMN config_json TEXT")
if not self._column_exists(cursor, "users", "role"):
cursor.execute("ALTER TABLE users ADD COLUMN role VARCHAR(50) DEFAULT 'user'")
if not self._column_exists(cursor, "model_configs", "owner_type"):
cursor.execute("ALTER TABLE model_configs ADD COLUMN owner_type VARCHAR(50) DEFAULT 'user'")
if not self._column_exists(cursor, "model_configs", "created_by_admin_id"):
cursor.execute("ALTER TABLE model_configs ADD COLUMN created_by_admin_id INTEGER REFERENCES users(id) ON DELETE SET NULL")
if not self._column_exists(cursor, "users", "is_active"):
cursor.execute("ALTER TABLE users ADD COLUMN is_active BOOLEAN DEFAULT TRUE")
if not self._column_exists(cursor, "users", "expires_at"):
cursor.execute("ALTER TABLE users ADD COLUMN expires_at TIMESTAMP")
if not self._column_exists(cursor, "users", "generation_limit"):
cursor.execute("ALTER TABLE users ADD COLUMN generation_limit INTEGER DEFAULT 5")
if not self._column_exists(cursor, "users", "remark"):
cursor.execute("ALTER TABLE users ADD COLUMN remark TEXT")
# 7b. Create model_config_assignments table
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS model_config_assignments (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
config_id UUID NOT NULL REFERENCES model_configs(id) ON DELETE CASCADE,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
assigned_by_admin_id INTEGER REFERENCES users(id) ON DELETE SET NULL,
enabled BOOLEAN NOT NULL DEFAULT TRUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE (config_id, user_id)
);
"""
)
# 7c. Create model_usage_logs table
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS model_usage_logs (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id INTEGER REFERENCES users(id) ON DELETE SET NULL,
config_id UUID REFERENCES model_configs(id) ON DELETE SET NULL,
assignment_id UUID REFERENCES model_config_assignments(id) ON DELETE SET NULL,
analysis_id VARCHAR(255),
provider VARCHAR(50) NOT NULL,
model_id VARCHAR(255) NOT NULL,
usage_type VARCHAR(50),
endpoint TEXT,
success BOOLEAN NOT NULL,
error_type TEXT,
prompt_tokens INTEGER,
completion_tokens INTEGER,
total_tokens INTEGER,
input_chars INTEGER,
output_chars INTEGER,
latency_ms INTEGER,
cost_estimate NUMERIC,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
"""
)
# 7d. Create admin_audit_logs table
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS admin_audit_logs (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
admin_user_id INTEGER REFERENCES users(id) ON DELETE SET NULL,
action VARCHAR(255) NOT NULL,
target_user_id INTEGER REFERENCES users(id) ON DELETE SET NULL,
target_resource_type VARCHAR(255),
target_resource_id VARCHAR(255),
metadata_json JSONB,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
"""
)
# 8. Create embeddings table
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS embeddings (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
analysis_id VARCHAR(255) REFERENCES analysis_records(id) ON DELETE CASCADE,
source_type VARCHAR(50) NOT NULL,
source_id VARCHAR(255),
content_hash VARCHAR(255),
embedding vector,
metadata_json JSONB,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
"""
)
# 9. Create all other original tables for PostgreSQL
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS jd_records (
id SERIAL PRIMARY KEY,
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
jd_text TEXT NOT NULL,
skills TEXT NOT NULL,
difficulty VARCHAR(50) NOT NULL,
job_summary TEXT NOT NULL,
personal_decision_json TEXT,
display_name VARCHAR(255),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
"""
)
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS course_records (
id SERIAL PRIMARY KEY,
skill VARCHAR(255) NOT NULL,
title VARCHAR(255) NOT NULL,
url TEXT NOT NULL,
view_count INTEGER NOT NULL,
favorite_count INTEGER NOT NULL,
like_count INTEGER NOT NULL,
coin_count INTEGER DEFAULT 0,
publish_date VARCHAR(50) NOT NULL,
uploader VARCHAR(255) NOT NULL,
rank_score REAL NOT NULL,
jd_record_id INTEGER NOT NULL REFERENCES jd_records(id) ON DELETE CASCADE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
"""
)
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS job_postings (
id SERIAL PRIMARY KEY,
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
title VARCHAR(255) NOT NULL,
company VARCHAR(255) NOT NULL DEFAULT '',
region VARCHAR(255) NOT NULL DEFAULT '',
latitude REAL,
longitude REAL,
transit_minutes INTEGER,
salary_monthly_k REAL NOT NULL,
jd_record_id INTEGER REFERENCES jd_records(id) ON DELETE SET NULL,
source_url TEXT NOT NULL DEFAULT '',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
"""
)
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS salary_snapshots (
id SERIAL PRIMARY KEY,
job_posting_id INTEGER NOT NULL REFERENCES job_postings(id) ON DELETE CASCADE,
observed_at TIMESTAMP NOT NULL,
salary_monthly_k REAL NOT NULL,
note TEXT NOT NULL DEFAULT ''
);
"""
)
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS fit_exam_attempts (
id SERIAL PRIMARY KEY,
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
jd_record_id INTEGER REFERENCES jd_records(id) ON DELETE SET NULL,
major_profile VARCHAR(255) NOT NULL DEFAULT '',
paper_json TEXT NOT NULL,
answers_json TEXT NOT NULL,
score REAL NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
"""
)
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS analysis_task (
id SERIAL PRIMARY KEY,
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
task_id VARCHAR(255) UNIQUE NOT NULL,
jd_id INTEGER,
status VARCHAR(50),
enable_rag INTEGER,
enable_verification INTEGER,
enable_hallucination_check INTEGER,
enable_rewrite INTEGER,
error_message TEXT,
created_at TEXT,
updated_at TEXT
);
"""
)
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS analysis_report (
id SERIAL PRIMARY KEY,
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
task_id VARCHAR(255) NOT NULL,
jd_text TEXT,
resume_text TEXT,
knowledge_texts TEXT,
original_analysis_json TEXT,
final_report_json TEXT,
evidence_summary_json TEXT,
hallucination_control_json TEXT,
citations_json TEXT,
credibility_score REAL,
evidence_coverage REAL,
hallucination_risk VARCHAR(50),
created_at TEXT,
updated_at TEXT
);
"""
)
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS claim_check_result (
id SERIAL PRIMARY KEY,
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
task_id VARCHAR(255) NOT NULL,
claim_id VARCHAR(255),
claim_text TEXT,
claim_type VARCHAR(50),
check_status VARCHAR(50),
confidence_score REAL,
evidence_count INTEGER,
reason TEXT,
evidence_json TEXT,
created_at TEXT
);
"""
)
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS knowledge_document (
id SERIAL PRIMARY KEY,
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
title VARCHAR(255),
file_name VARCHAR(255),
file_type VARCHAR(50),
source_type VARCHAR(50),
raw_text TEXT,
summary TEXT,
chunk_count INTEGER,
status VARCHAR(50),
error_message TEXT,
created_at TEXT,
updated_at TEXT
);
"""
)
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS knowledge_chunk (
id SERIAL PRIMARY KEY,
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
document_id INTEGER REFERENCES knowledge_document(id) ON DELETE CASCADE,
chunk_index INTEGER,
chunk_text TEXT,
token_count INTEGER,
metadata_json TEXT,
created_at TEXT,
section_id VARCHAR(255),
section_type VARCHAR(255),
section_title VARCHAR(255),
hierarchy_json TEXT,
semantic_type VARCHAR(255),
importance REAL,
keywords_json TEXT,
embedding_text TEXT,
embedding vector
);
"""
)
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS analysis_workflow_log (
id SERIAL PRIMARY KEY,
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
task_id VARCHAR(255) NOT NULL,
node_name VARCHAR(255),
status VARCHAR(50),
duration_ms INTEGER,
input_summary TEXT,
output_summary TEXT,
error_message TEXT,
created_at TEXT
);
"""
)
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS analysis_quality_evaluation (
id SERIAL PRIMARY KEY,
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
task_id VARCHAR(255) NOT NULL,
final_quality_score REAL,
quality_grade VARCHAR(50),
quality_gate_status VARCHAR(50),
evidence_coverage_score REAL,
hallucination_risk_score REAL,
citation_completeness_score REAL,
resume_honesty_score REAL,
match_score_reasonableness REAL,
issues_json TEXT,
summary TEXT,
created_at TEXT
);
"""
)
# 10. Indexes
cursor.execute("CREATE INDEX IF NOT EXISTS idx_users_username ON users(username);")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_model_configs_owner_type ON model_configs(owner_type, enabled);")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_model_config_assignments_user ON model_config_assignments(user_id);")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_model_config_assignments_config ON model_config_assignments(config_id);")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_model_usage_logs_user ON model_usage_logs(user_id, created_at DESC);")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_model_usage_logs_config ON model_usage_logs(config_id, created_at DESC);")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_model_usage_logs_provider_model ON model_usage_logs(provider, model_id, created_at DESC);")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_model_usage_logs_success ON model_usage_logs(success, created_at DESC);")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_analysis_records_user_created ON analysis_records(user_id, created_at DESC);")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_drafts_user_updated ON drafts(user_id, updated_at DESC);")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_user_settings_user ON user_settings(user_id);")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_model_configs_user_provider ON model_configs(user_id, provider);")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_embeddings_user_analysis ON embeddings(user_id, analysis_id);")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_embeddings_user_hash ON embeddings(user_id, content_hash);")
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS email_verification_codes (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
email VARCHAR(255) NOT NULL,
code_hash TEXT NOT NULL,
purpose VARCHAR(50) NOT NULL DEFAULT 'register',
attempts INTEGER NOT NULL DEFAULT 0,
max_attempts INTEGER NOT NULL DEFAULT 5,
expires_at TIMESTAMP NOT NULL,
used_at TIMESTAMP,
request_ip VARCHAR(255),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
"""
)
cursor.execute("CREATE INDEX IF NOT EXISTS idx_email_codes_email_purpose ON email_verification_codes(email, purpose, created_at DESC);")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_jd_records_user_created ON jd_records(user_id, created_at);")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_analysis_report_user_created ON analysis_report(user_id, created_at);")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_analysis_task_user_updated ON analysis_task(user_id, updated_at);")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_knowledge_document_user ON knowledge_document(user_id);")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_knowledge_chunk_user_doc ON knowledge_chunk(user_id, document_id);")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_job_postings_user ON job_postings(user_id);")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_fit_exam_attempts_user ON fit_exam_attempts(user_id);")
# PostgreSQL columns migration for knowledge_chunk
if not self._column_exists(cursor, "knowledge_chunk", "section_id"):
cursor.execute("ALTER TABLE knowledge_chunk ADD COLUMN section_id VARCHAR(255)")
if not self._column_exists(cursor, "knowledge_chunk", "section_type"):
cursor.execute("ALTER TABLE knowledge_chunk ADD COLUMN section_type VARCHAR(255)")
if not self._column_exists(cursor, "knowledge_chunk", "section_title"):
cursor.execute("ALTER TABLE knowledge_chunk ADD COLUMN section_title VARCHAR(255)")
if not self._column_exists(cursor, "knowledge_chunk", "hierarchy_json"):
cursor.execute("ALTER TABLE knowledge_chunk ADD COLUMN hierarchy_json TEXT")
if not self._column_exists(cursor, "knowledge_chunk", "semantic_type"):
cursor.execute("ALTER TABLE knowledge_chunk ADD COLUMN semantic_type VARCHAR(255)")
if not self._column_exists(cursor, "knowledge_chunk", "importance"):
cursor.execute("ALTER TABLE knowledge_chunk ADD COLUMN importance REAL")
if not self._column_exists(cursor, "knowledge_chunk", "keywords_json"):
cursor.execute("ALTER TABLE knowledge_chunk ADD COLUMN keywords_json TEXT")
if not self._column_exists(cursor, "knowledge_chunk", "embedding_text"):
cursor.execute("ALTER TABLE knowledge_chunk ADD COLUMN embedding_text TEXT")
if not self._column_exists(cursor, "knowledge_chunk", "embedding"):
cursor.execute("ALTER TABLE knowledge_chunk ADD COLUMN embedding vector")
# 11. Sessions table for persistent authentication
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS sessions (
token VARCHAR(64) PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
expires_at TIMESTAMP NOT NULL
);
"""
)
cursor.execute("CREATE INDEX IF NOT EXISTS idx_sessions_user ON sessions(user_id);")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_sessions_expires ON sessions(expires_at);")
# 12. star_stories table
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS star_stories (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
title VARCHAR(255) NOT NULL,
situation TEXT,
task TEXT,
action TEXT,
result TEXT,
full_text TEXT,
style VARCHAR(50) DEFAULT 'standard',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
"""
)
cursor.execute("CREATE INDEX IF NOT EXISTS idx_star_stories_user ON star_stories(user_id);")
# 13. announcements table
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS announcements (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
title VARCHAR(255) NOT NULL,
content TEXT NOT NULL,
start_time TIMESTAMP NOT NULL,
end_time TIMESTAMP NOT NULL,
target_type VARCHAR(50) NOT NULL DEFAULT 'all',
target_users TEXT,
announcement_type VARCHAR(50) NOT NULL DEFAULT 'top',
show_behavior VARCHAR(50) NOT NULL DEFAULT 'once',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
"""
)
cursor.execute("CREATE INDEX IF NOT EXISTS idx_announcements_time ON announcements(start_time, end_time);")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_analysis_records_user ON analysis_records(user_id, created_at DESC);")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_sessions_user ON sessions(user_id);")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_sessions_expires ON sessions(expires_at);")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_model_configs_owner_type ON model_configs(owner_type, enabled);")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_model_config_assignments_user ON model_config_assignments(user_id);")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_model_config_assignments_config ON model_config_assignments(config_id);")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_model_usage_logs_user ON model_usage_logs(user_id, created_at DESC);")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_model_usage_logs_config ON model_usage_logs(config_id, created_at DESC);")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_model_usage_logs_provider_model ON model_usage_logs(provider, model_id, created_at DESC);")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_model_usage_logs_success ON model_usage_logs(success, created_at DESC);")
# Check and alter announcements table to ensure compatibility with announcement_type column
try:
if not self._column_exists(cursor, "announcements", "announcement_type"):
cursor.execute("ALTER TABLE announcements ADD COLUMN announcement_type VARCHAR(50) DEFAULT 'top';")
except Exception as e:
print(f"[DATABASE] Migration warning for announcements type column: {e}")
# Check and alter announcements table to ensure compatibility with show_behavior column
try:
if not self._column_exists(cursor, "announcements", "show_behavior"):
cursor.execute("ALTER TABLE announcements ADD COLUMN show_behavior VARCHAR(50) DEFAULT 'once';")
except Exception as e:
print(f"[DATABASE] Migration warning for announcements show_behavior column: {e}")
# 14. Create agent_resume_tasks table
try:
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS agent_resume_tasks (
task_id VARCHAR(255) PRIMARY KEY,
user_id VARCHAR(255) NOT NULL,
trace_id VARCHAR(255),
status VARCHAR(50) NOT NULL,
resume_id VARCHAR(255),
original_resume_name VARCHAR(255),
jd_text TEXT,
workspace_path VARCHAR(500),
logs TEXT,
optimized_resume_md TEXT,
error_message TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
"""
)
cursor.execute("CREATE INDEX IF NOT EXISTS idx_agent_resume_tasks_user ON agent_resume_tasks(user_id);")
except Exception as e:
print(f"[DATABASE] Error creating agent_resume_tasks table: {e}")
# 澧為噺杩佺Щ锛氫负 agent_resume_tasks 琛ㄨˉ鍏?pending_question, human_answer, execution_plan 瀛楁
# 缁熶竴浣跨敤鍚屼竴涓?cursor 杩涜澧為噺淇敼锛屼笉鍐嶅紑鍚柊杩炴帴锛岄槻姝?PostgreSQL 骞跺彂浜嬪姟姝婚攣瀵艰嚧杩炴帴琚己琛屾柇寮€
for col_name in ["pending_question", "human_answer", "execution_plan"]:
if not self._column_exists(cursor, "agent_resume_tasks", col_name):
cursor.execute(f"ALTER TABLE agent_resume_tasks ADD COLUMN {col_name} TEXT;")
if not self._column_exists(cursor, "agent_resume_tasks", "trace_id"):
cursor.execute("ALTER TABLE agent_resume_tasks ADD COLUMN trace_id VARCHAR(255);")
cursor.execute(
"""
UPDATE agent_resume_tasks
SET trace_id = CONCAT('tr-', REPLACE(gen_random_uuid()::text, '-', ''))
WHERE trace_id IS NULL OR trace_id = ''
"""
)
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS agent_resume_turns (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
task_id VARCHAR(255) NOT NULL,
user_id VARCHAR(255) NOT NULL,
step_index INTEGER,
role VARCHAR(50) NOT NULL,
content TEXT NOT NULL,
answer_type VARCHAR(50) DEFAULT '',
remember BOOLEAN DEFAULT FALSE,
evidence_scope VARCHAR(50) DEFAULT '',
consumed_at TIMESTAMP NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (task_id) REFERENCES agent_resume_tasks(task_id) ON DELETE CASCADE
);
"""
)
cursor.execute(
"CREATE INDEX IF NOT EXISTS idx_agent_resume_turns_task_step ON agent_resume_turns(user_id, task_id, step_index, created_at);"
)
cursor.execute(
"CREATE INDEX IF NOT EXISTS idx_agent_resume_turns_unconsumed ON agent_resume_turns(user_id, task_id, step_index, role, consumed_at);"
)
if not self._column_exists(cursor, "agent_resume_turns", "summary"):
cursor.execute("ALTER TABLE agent_resume_turns ADD COLUMN summary TEXT DEFAULT '';")
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS agent_resume_conversation_state (
task_id VARCHAR(255) PRIMARY KEY,
user_id VARCHAR(255) NOT NULL,
summary TEXT DEFAULT '',
global_preferences TEXT DEFAULT '[]',
fact_ledger TEXT DEFAULT '[]',
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (task_id) REFERENCES agent_resume_tasks(task_id) ON DELETE CASCADE
);
"""
)
cursor.execute(
"CREATE INDEX IF NOT EXISTS idx_agent_resume_conversation_state_user ON agent_resume_conversation_state(user_id, updated_at DESC);"
)
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS agent_preferences (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id VARCHAR(255) NOT NULL,
section_name VARCHAR(255) NOT NULL,
preference_text TEXT NOT NULL,
source_task_id VARCHAR(255),
evidence_text TEXT,
tags TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE (user_id, section_name, preference_text)
);
"""
)
cursor.execute(
"CREATE INDEX IF NOT EXISTS idx_agent_preferences_user_section ON agent_preferences(user_id, section_name, created_at DESC);"
)
for col_name, col_type in [
("source_task_id", "VARCHAR(255)"),
("evidence_text", "TEXT"),
("tags", "TEXT"),
]:
if not self._column_exists(cursor, "agent_preferences", col_name):
cursor.execute(f"ALTER TABLE agent_preferences ADD COLUMN {col_name} {col_type};")
from backend.migrations.resume_advisor import run_resume_advisor_migrations
run_resume_advisor_migrations(cursor)
conn.commit()
conn.close()
def create_user(self, username: str, password: str, device_signature: Optional[str] = None) -> int:
normalized = normalize_username(username)
if not normalized:
raise ValueError("username_required")
if len(password) < 8:
raise ValueError("password_too_short")
conn = self.get_connection()
cursor = conn.cursor()
try:
if device_signature:
cursor.execute(
"SELECT 1 FROM registered_devices WHERE device_signature = ?",
(device_signature,),