🔍 Code Extractor

function _get_conn

Maturity: 34

Lazy initialization function that returns a singleton SQLite database connection, creating the database and required table schema if they don't exist.

File:
/tf/active/vicechatdev/rmcl/datacache.py
Lines:
21 - 33
Complexity:
moderate

Purpose

This function implements the singleton pattern for database connection management. It ensures only one SQLite connection is created and reused throughout the application lifecycle. On first call, it creates the cache directory structure, establishes a connection to a SQLite database file, and initializes a 'filedata' table with columns for id, version, property, and value. Subsequent calls return the existing connection. This is typically used for caching file metadata or properties with versioning support.

Source Code

def _get_conn():
    global _conn
    if _conn is not None:
        return _conn

    CACHE_FILE.parent.mkdir(parents=True, exist_ok=True)
    _conn = sqlite3.connect(CACHE_FILE)
    c = _conn.cursor()
    c.execute('''CREATE TABLE IF NOT EXISTS filedata
                 (id TEXT, version INTEGER, property TEXT, value BLOB,
                  UNIQUE(id, version, property))''')
    _conn.commit()
    return _conn

Return Value

Returns a sqlite3.Connection object representing an active connection to the SQLite database. This connection can be used to create cursors and execute SQL queries against the 'filedata' table. The same connection instance is returned on all subsequent calls (singleton pattern).

Dependencies

  • sqlite3
  • xdg

Required Imports

import sqlite3
from xdg import xdg_cache_home

Usage Example

import sqlite3
from pathlib import Path
from xdg import xdg_cache_home

# Module-level setup
_conn = None
CACHE_FILE = Path(xdg_cache_home()) / 'myapp' / 'cache.db'

def _get_conn():
    global _conn
    if _conn is not None:
        return _conn
    CACHE_FILE.parent.mkdir(parents=True, exist_ok=True)
    _conn = sqlite3.connect(CACHE_FILE)
    c = _conn.cursor()
    c.execute('''CREATE TABLE IF NOT EXISTS filedata
                 (id TEXT, version INTEGER, property TEXT, value BLOB,
                  UNIQUE(id, version, property))''')
    _conn.commit()
    return _conn

# Usage
conn = _get_conn()
cursor = conn.cursor()
cursor.execute('INSERT OR REPLACE INTO filedata VALUES (?, ?, ?, ?)', 
               ('file1', 1, 'size', b'1024'))
conn.commit()

Best Practices

  • This function relies on global state (_conn) which can make testing difficult; consider dependency injection for better testability
  • The connection is never explicitly closed; ensure proper cleanup on application shutdown
  • The function is not thread-safe; use threading locks if accessing from multiple threads
  • CACHE_FILE must be defined before calling this function, typically using xdg_cache_home() for cross-platform cache directory support
  • The 'filedata' table uses a UNIQUE constraint on (id, version, property) to prevent duplicate entries
  • Consider using context managers or connection pooling for production applications
  • The BLOB type for 'value' column allows storing binary data; use appropriate serialization (pickle, json, etc.) when storing complex objects

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function get_driver 59.3% similar

    Singleton function that initializes and returns a Neo4j database driver instance with connection verification.

    From: /tf/active/vicechatdev/CDocs/db/__init__.py
  • function get_filecloud_client 56.3% similar

    Singleton factory function that returns a globally cached FileCloud API client instance, handling initialization, authentication, and re-authentication as needed.

    From: /tf/active/vicechatdev/CDocs/controllers/filecloud_controller.py
  • function get_default_connection_config 54.7% similar

    Retrieves the default database connection configuration by loading settings from a sql_config.py file located in the same directory as the function.

    From: /tf/active/vicechatdev/full_smartstat/sql_query_generator.py
  • function init_connections 54.7% similar

    Initializes and returns a Neo4j database session and driver connection using configuration settings.

    From: /tf/active/vicechatdev/offline_docstore_multi_vice.py
  • function get_client 54.6% similar

    Asynchronous singleton factory function that retrieves or initializes a global Client instance with optional device registration prompting.

    From: /tf/active/vicechatdev/rmcl/api.py
← Back to Browse