kamau1 commited on
Commit
20dd904
·
verified ·
1 Parent(s): 8e73a41

Upload 10 files

Browse files
Files changed (1) hide show
  1. main.py +237 -0
main.py CHANGED
@@ -675,6 +675,243 @@ async def health_check():
675
  "database_type": getattr(app, "db_type", "unknown")
676
  }
677
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
678
  # Import and include routers
679
  from app.api.routes import auth_router, projects_router, journals_router
680
 
 
675
  "database_type": getattr(app, "db_type", "unknown")
676
  }
677
 
678
+ # Database test endpoint
679
+ @app.get("/test-db", tags=["General"])
680
+ async def test_database():
681
+ """
682
+ Test endpoint to verify database operations.
683
+ This is for debugging purposes only.
684
+ """
685
+ import time
686
+
687
+ # Generate a unique test ID
688
+ test_id = f"test_{int(time.time())}"
689
+ logger.info(f"[{test_id}] Starting database test")
690
+
691
+ results = {
692
+ "connection_type": getattr(app, "db_type", "unknown"),
693
+ "connection_object_type": type(app.db_conn).__name__ if hasattr(app, "db_conn") else "None",
694
+ "operations": []
695
+ }
696
+
697
+ if hasattr(app, "last_successful_connection_method"):
698
+ results["connection_method"] = app.last_successful_connection_method
699
+
700
+ if not hasattr(app, "db_conn"):
701
+ logger.error(f"[{test_id}] Database connection not available")
702
+ results["operations"].append({
703
+ "name": "Database connection check",
704
+ "success": False,
705
+ "error": "Database connection not available"
706
+ })
707
+ return results
708
+
709
+ try:
710
+ # Test 1: Simple SELECT
711
+ logger.info(f"[{test_id}] Test 1: Simple SELECT")
712
+ test_query = "SELECT 1 as test"
713
+ result = app.db_conn.execute(test_query).fetchone()
714
+ results["operations"].append({
715
+ "name": "Simple SELECT",
716
+ "success": result is not None,
717
+ "result": str(result) if result is not None else None
718
+ })
719
+ logger.info(f"[{test_id}] Test 1 result: {result}")
720
+
721
+ # Test 2: Create a temporary table
722
+ logger.info(f"[{test_id}] Test 2: Create a temporary table")
723
+ create_temp_table = """
724
+ CREATE TABLE IF NOT EXISTS test_table (
725
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
726
+ name TEXT NOT NULL,
727
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
728
+ )
729
+ """
730
+ app.db_conn.execute(create_temp_table)
731
+ app.db_conn.commit()
732
+ results["operations"].append({
733
+ "name": "Create temporary table",
734
+ "success": True
735
+ })
736
+ logger.info(f"[{test_id}] Test 2 completed successfully")
737
+
738
+ # Test 3: Insert into the temporary table
739
+ logger.info(f"[{test_id}] Test 3: Insert into the temporary table")
740
+ test_name = f"test_user_{int(time.time())}"
741
+ insert_query = "INSERT INTO test_table (name) VALUES (?)"
742
+ cursor = app.db_conn.execute(insert_query, (test_name,))
743
+ app.db_conn.commit()
744
+
745
+ # Check if lastrowid is available
746
+ last_id = None
747
+ try:
748
+ last_id = cursor.lastrowid
749
+ logger.info(f"[{test_id}] Got lastrowid: {last_id}")
750
+ except Exception as e:
751
+ logger.warning(f"[{test_id}] Could not get lastrowid: {str(e)}")
752
+
753
+ # Try to get the ID using a query
754
+ try:
755
+ id_query = "SELECT id FROM test_table WHERE name = ? ORDER BY id DESC LIMIT 1"
756
+ id_result = app.db_conn.execute(id_query, (test_name,)).fetchone()
757
+ if id_result:
758
+ last_id = id_result[0]
759
+ logger.info(f"[{test_id}] Got ID from query: {last_id}")
760
+ except Exception as e2:
761
+ logger.error(f"[{test_id}] Error getting ID from query: {str(e2)}")
762
+
763
+ results["operations"].append({
764
+ "name": "Insert into temporary table",
765
+ "success": True,
766
+ "last_id": last_id
767
+ })
768
+ logger.info(f"[{test_id}] Test 3 completed successfully. Last ID: {last_id}")
769
+
770
+ # Test 4: Select from the temporary table
771
+ logger.info(f"[{test_id}] Test 4: Select from the temporary table")
772
+ select_query = "SELECT * FROM test_table WHERE name = ?"
773
+ result = app.db_conn.execute(select_query, (test_name,)).fetchone()
774
+ results["operations"].append({
775
+ "name": "Select from temporary table",
776
+ "success": result is not None,
777
+ "result": str(result) if result is not None else None
778
+ })
779
+ logger.info(f"[{test_id}] Test 4 result: {result}")
780
+
781
+ # Test 5: Check if users table exists and has the expected structure
782
+ logger.info(f"[{test_id}] Test 5: Check users table structure")
783
+ try:
784
+ table_info = app.db_conn.execute("PRAGMA table_info(users)").fetchall()
785
+ results["operations"].append({
786
+ "name": "Check users table structure",
787
+ "success": len(table_info) > 0,
788
+ "columns": [col[1] for col in table_info] if table_info else []
789
+ })
790
+ logger.info(f"[{test_id}] Test 5 result: {table_info}")
791
+ except Exception as e:
792
+ logger.error(f"[{test_id}] Error checking users table structure: {str(e)}")
793
+ results["operations"].append({
794
+ "name": "Check users table structure",
795
+ "success": False,
796
+ "error": str(e)
797
+ })
798
+
799
+ # Test 6: List all users
800
+ logger.info(f"[{test_id}] Test 6: List all users")
801
+ try:
802
+ all_users = app.db_conn.execute("SELECT id, email FROM users").fetchall()
803
+ results["operations"].append({
804
+ "name": "List all users",
805
+ "success": True,
806
+ "count": len(all_users) if all_users else 0,
807
+ "users": [{"id": user[0], "email": user[1]} for user in all_users] if all_users else []
808
+ })
809
+ logger.info(f"[{test_id}] Test 6 result: {all_users}")
810
+ except Exception as e:
811
+ logger.error(f"[{test_id}] Error listing all users: {str(e)}")
812
+ results["operations"].append({
813
+ "name": "List all users",
814
+ "success": False,
815
+ "error": str(e)
816
+ })
817
+
818
+ logger.info(f"[{test_id}] Database test completed successfully")
819
+ return results
820
+ except Exception as e:
821
+ logger.error(f"[{test_id}] Database test failed: {str(e)}")
822
+ results["operations"].append({
823
+ "name": "Error during tests",
824
+ "success": False,
825
+ "error": str(e)
826
+ })
827
+ return results
828
+
829
+ # Test user creation endpoint (direct SQL)
830
+ @app.get("/create-test-user", tags=["General"])
831
+ async def create_test_user():
832
+ """
833
+ Create a test user with email [email protected].
834
+ This is for testing purposes only.
835
+
836
+ Returns:
837
+ dict: Information about the created test user.
838
+ """
839
+ import time
840
+
841
+ # Generate a unique test ID
842
+ test_id = f"test_{int(time.time())}"
843
+ logger.info(f"[{test_id}] Starting test user creation (direct SQL)")
844
+
845
+ if not hasattr(app, "db_conn"):
846
+ logger.error(f"[{test_id}] Database connection not available")
847
+ return {
848
+ "success": False,
849
+ "error": "Database connection not available"
850
+ }
851
+
852
+ try:
853
+ # First check if the test user already exists
854
+ logger.info(f"[{test_id}] Checking if test user already exists")
855
+ check_query = "SELECT id FROM users WHERE email = ?"
856
+ existing_user = app.db_conn.execute(check_query, ("[email protected]",)).fetchone()
857
+
858
+ if existing_user:
859
+ logger.info(f"[{test_id}] Test user already exists with ID: {existing_user[0]}")
860
+ return {
861
+ "success": True,
862
+ "user_id": existing_user[0],
863
+ "email": "[email protected]",
864
+ "status": "already_exists"
865
+ }
866
+
867
+ # Use a pre-hashed password to avoid dependency on passlib
868
+ logger.info(f"[{test_id}] Using pre-hashed password for test user")
869
+ # This is a pre-hashed version of "TestPassword123!" using Argon2
870
+ hashed_password = "$argon2id$v=19$m=65536,t=3,p=4$NElQRUZCWDRZSHpIWWRGSA$TYU8R7EfXGgEu9FWZGMX9AVwmMwpSKECCZMXgbzr6JE"
871
+
872
+ # Insert the test user
873
+ logger.info(f"[{test_id}] Inserting test user with email: [email protected]")
874
+ insert_query = "INSERT INTO users (email, hashed_password) VALUES (?, ?)"
875
+ cursor = app.db_conn.execute(insert_query, ("[email protected]", hashed_password))
876
+ app.db_conn.commit()
877
+ logger.info(f"[{test_id}] Committed test user insert")
878
+
879
+ # Try to get the user ID
880
+ user_id = None
881
+ try:
882
+ user_id = cursor.lastrowid
883
+ logger.info(f"[{test_id}] Got test user lastrowid: {user_id}")
884
+ except Exception as e:
885
+ logger.warning(f"[{test_id}] Could not get test user lastrowid: {str(e)}")
886
+
887
+ # Verify the insert with a separate query
888
+ logger.info(f"[{test_id}] Verifying test user was created")
889
+ verify_query = "SELECT id, email, created_at FROM users WHERE email = ?"
890
+ verify_result = app.db_conn.execute(verify_query, ("[email protected]",)).fetchone()
891
+
892
+ if verify_result:
893
+ user_id = verify_result[0]
894
+ logger.info(f"[{test_id}] Verified test user with ID: {user_id}")
895
+ return {
896
+ "success": True,
897
+ "user_id": user_id,
898
+ "email": "[email protected]",
899
+ "created_at": verify_result[2] if len(verify_result) > 2 else None,
900
+ "status": "created"
901
+ }
902
+ else:
903
+ logger.error(f"[{test_id}] Failed to verify test user after insert")
904
+ return {
905
+ "success": False,
906
+ "error": "Failed to verify user after insert"
907
+ }
908
+ except Exception as e:
909
+ logger.error(f"[{test_id}] Error creating test user: {str(e)}")
910
+ return {
911
+ "success": False,
912
+ "error": str(e)
913
+ }
914
+
915
  # Import and include routers
916
  from app.api.routes import auth_router, projects_router, journals_router
917