🔍 Code Extractor

function refresh_database_schema

Maturity: 49

Flask route endpoint that forces a refresh of the database schema by invoking the schema discovery service with LLM-generated descriptions.

File:
/tf/active/vicechatdev/full_smartstat/app.py
Lines:
1051 - 1073
Complexity:
moderate

Purpose

This endpoint provides a way to manually trigger a complete refresh of the database schema cache. It uses the DynamicSchemaDiscovery service to rediscover all database tables, columns, and relationships, enriching them with LLM-generated descriptions. This is useful when database structure changes or when schema metadata needs to be updated without restarting the application.

Source Code

def refresh_database_schema():
    """Force refresh of database schema with LLM descriptions"""
    try:
        if hasattr(app, 'schema_discovery'):
            logger.info("Forcing database schema refresh with LLM descriptions...")
            app.discovered_schema = app.schema_discovery.discover_schema(force_refresh=True)
            return jsonify({
                'success': True,
                'message': 'Database schema refreshed successfully',
                'total_tables': app.discovered_schema.total_tables if app.discovered_schema else 0
            }), 200
        else:
            return jsonify({
                'success': False,
                'error': 'Schema discovery service not available'
            }), 503
            
    except Exception as e:
        logger.error(f"Error refreshing database schema: {str(e)}")
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

Return Value

Returns a Flask JSON response tuple containing: (1) A JSON object with 'success' boolean, 'message' or 'error' string, and optionally 'total_tables' integer count, and (2) An HTTP status code (200 for success, 503 if service unavailable, 500 for errors). The response indicates whether the schema refresh was successful and provides relevant metadata.

Dependencies

  • flask
  • logging
  • dynamic_schema_discovery

Required Imports

from flask import Flask
from flask import jsonify
import logging
from dynamic_schema_discovery import DynamicSchemaDiscovery

Usage Example

# This is a Flask route handler, typically called via HTTP POST request
# Example using curl:
# curl -X POST http://localhost:5000/refresh_database_schema

# Example using Python requests library:
import requests

response = requests.post('http://localhost:5000/refresh_database_schema')
result = response.json()

if result['success']:
    print(f"Schema refreshed successfully. Total tables: {result['total_tables']}")
else:
    print(f"Error: {result['error']}")

# Example Flask app setup:
from flask import Flask, jsonify
import logging
from dynamic_schema_discovery import DynamicSchemaDiscovery

app = Flask(__name__)
logger = logging.getLogger(__name__)

# Initialize schema discovery service
app.schema_discovery = DynamicSchemaDiscovery(db_config)
app.discovered_schema = None

@app.route('/refresh_database_schema', methods=['POST'])
def refresh_database_schema():
    # Function implementation here
    pass

Best Practices

  • This endpoint should be protected with authentication/authorization as it performs potentially expensive operations
  • Consider implementing rate limiting to prevent abuse, as schema discovery with LLM can be resource-intensive
  • Ensure proper error handling and logging for debugging schema refresh issues
  • The force_refresh=True parameter bypasses caching, so use this endpoint judiciously
  • Monitor the execution time as LLM-based schema description generation can be slow for large databases
  • Consider implementing a background job queue for schema refresh in production environments
  • Verify that app.schema_discovery is properly initialized before deploying this endpoint
  • The endpoint returns 503 if schema_discovery service is not available, handle this gracefully in client code
  • Use POST method (not GET) as this operation modifies server state by refreshing cached schema

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function get_database_schema 70.4% similar

    Flask route handler that retrieves and returns comprehensive database schema information, including tables, columns, relationships, and statistics.

    From: /tf/active/vicechatdev/full_smartstat/app.py
  • function get_database_schema_viewer 68.0% similar

    Flask route handler that retrieves and formats detailed database schema information from a discovered schema stored in the Flask app object, returning it as JSON for visualization purposes.

    From: /tf/active/vicechatdev/full_smartstat/app.py
  • function database_schema 62.4% similar

    Flask route handler that renders the database schema viewer page template.

    From: /tf/active/vicechatdev/full_smartstat/app.py
  • function add_manual_relationship 61.0% similar

    Flask route handler that adds a manually specified database relationship to the schema and clears the schema cache to force reload with the new relationship.

    From: /tf/active/vicechatdev/full_smartstat/app.py
  • function get_database_tables_columns 58.3% similar

    Flask route handler that retrieves database schema information including tables, columns, and relationships, filtered and sorted by relevance for data analysis workflows.

    From: /tf/active/vicechatdev/full_smartstat/app.py
← Back to Browse