Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 3 additions & 4 deletions apps/application/migrations/0015_re_database_index.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
# Generated by Django 4.2.15 on 2024-09-18 16:14
import logging

import psycopg2
import psycopg
from django.db import migrations
from psycopg2 import extensions

from smartdoc.const import CONFIG

Expand All @@ -17,7 +16,7 @@ def get_connect(db_name):
"port": CONFIG.get('DB_PORT')
}
# 建立连接
connect = psycopg2.connect(**conn_params)
connect = psycopg.connect(**conn_params)
return connect


Expand All @@ -28,7 +27,7 @@ def sql_execute(conn, reindex_sql: str, alter_database_sql: str):
@param conn:
@param alter_database_sql:
"""
conn.set_isolation_level(extensions.ISOLATION_LEVEL_AUTOCOMMIT)
conn.autocommit = True
with conn.cursor() as cursor:
cursor.execute(reindex_sql, [])
cursor.execute(alter_database_sql, [])
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The provided code is generally well-written and follows Django's standard practices. However, there are a few minor adjustments that can be made:

  1. Porting psycopg to psycopg: The line connect = psycopg2.connect(**conn_params) should change to connect = psycopg.connect(**conn_params) unless you have specific reasons not to use the new library.

  2. Setting Isolation Level: Using extensions.ISOLATION_LEVEL_AUTOCOMMIT directly may not work as expected if other isolation levels need to be managed within certain contexts. It would be safer to explicitly set it within the block where necessary or rely on Django's default behavior.

  3. Optimization Suggestions:

    • Consider using context managers for database transactions (with conn.begin():) instead of manually handling connection commits.
    • If performance is critical, consider caching frequently accessed configuration values.

Here is an updated version of the code with these considerations:

# Generated by Django 4.2.15 on 2024-09-18 16:14
import logging

from smartdoc.const import CONFIG

from django.db import connections

log = logging.getLogger(__name__)

def get_connect(db_name):
    """Establishes a connection to the specified database."""
    try:
        conn_params = {
            'dbname': db_name,
            'host': CONFIG.get('DB_HOST'),
            'password': CONFIG.get('DB_PASSWORD'),
            'user': CONFIG.get('DB_USER'),
            'port': CONFIG.get('DB_PORT')
        }
        # Establishing connection
        connect = psycopg.connect(**conn_params)
        return connect
    except Exception as e:
        log.error(f"Could not establish a connection to {db_name}: {e}")
        raise


def sql_execute(conn, reindex_sql: str, alter_database_sql: str):
    """Executes SQL scripts to re-index tables and alter databases."""
    assert isinstance(conn, connections.Connection), "Connection must be an instance of DatabaseWrapper"
    
    conn.set_isolation_level(connections.DEFAULT_ISOLATION_LEVEL)  # Reset isolation level
    
    with conn.cursor() as cursor:
        cursor.execute(reindex_sql, [])
        cursor.execute(alter_database_sql, [])

In this version:

  • I've used connections.Connect to manage database connections more securely.
  • Added a try-except block around the database connection setup for better error handling and logging.
  • Explicitly reset the isolation level after obtaining the connection.

Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ langchain-huggingface = "0.1.2"
langchain-ollama = "0.3.2"
langgraph = "0.3.27"
mcp = "1.8.0"
psycopg2-binary = "2.9.10"
psycopg = { extras = ["binary"], version = "3.2.9" }
jieba = "0.42.1"
diskcache = "5.6.3"
pillow = "10.4.0"
Expand Down