-
-
Notifications
You must be signed in to change notification settings - Fork 6
docs: 173 usage configuration #234
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 15 commits
cbd7023
31cbf31
5dcc426
da7a9ad
0ff5c15
2d28f08
2ca1def
a6256a6
b85c152
642816a
5dd81fa
27364bb
9c7c689
e0b1082
cdca6b3
a65c6cb
f6d748f
fffec01
91c6d0e
6aec1d2
5c5d60d
8d2c24c
4629000
05a1b8f
c254d32
93154b9
2fcd5c1
93250d4
8d7f4e8
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| def test_sqlite_memory_db() -> None: | ||
| from sqlspec import SQLSpec | ||
| from sqlspec.adapters.sqlite import SqliteConfig | ||
|
|
||
| # Create SQLSpec instance | ||
| spec = SQLSpec() | ||
|
|
||
| # Add database configuration | ||
| db = spec.add_config(SqliteConfig(pool_config={"database": ":memory:"})) | ||
|
|
||
| # Use the database | ||
| with spec.provide_session(db) as session: | ||
| result = session.execute("SELECT 1") | ||
| assert result[0] == {"1": 1} |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| POOL_INSTANCE = 20 | ||
|
|
||
|
|
||
| def test_manual_pool() -> None: | ||
| from sqlspec.adapters.asyncpg import AsyncpgConfig | ||
|
|
||
| pool = {"dsn": "postgresql://localhost/db", "min_size": 10, "max_size": POOL_INSTANCE} | ||
| db = AsyncpgConfig(pool_instance=pool) | ||
| assert db.pool_instance["max_size"] == POOL_INSTANCE |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| def test_thread_local_connections() -> None: | ||
| from sqlspec.adapters.sqlite import SqliteConfig | ||
|
|
||
| config = SqliteConfig(pool_config={"database": "test.db"}) | ||
| assert config.pool_config["database"] == "test.db" |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| def test_basic_statement_config() -> None: | ||
| from sqlspec.adapters.asyncpg import AsyncpgConfig | ||
| from sqlspec.core.statement import StatementConfig | ||
|
|
||
| statement_config = StatementConfig( | ||
| dialect="postgres", # SQLGlot dialect | ||
| enable_parsing=True, # Parse SQL into AST | ||
| enable_validation=True, # Run security/performance validators | ||
| enable_transformations=True, # Apply AST transformations | ||
| enable_caching=True, # Enable multi-tier caching | ||
| ) | ||
|
|
||
| # Apply to adapter | ||
| config = AsyncpgConfig(pool_config={"dsn": "postgresql://localhost/db"}, statement_config=statement_config) | ||
| assert config.statement_config.dialect == "postgres" | ||
| assert config.statement_config.enable_parsing is True | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| def test_parameter_style_config() -> None: | ||
| from sqlspec.core.parameters import ParameterStyle, ParameterStyleConfig | ||
| from sqlspec.core.statement import StatementConfig | ||
euri10 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| param_config = ParameterStyleConfig( | ||
| default_parameter_style=ParameterStyle.NUMERIC, # $1, $2, ... | ||
| supported_parameter_styles={ | ||
| ParameterStyle.NUMERIC, | ||
| ParameterStyle.NAMED_COLON, # :name | ||
| }, | ||
| has_native_list_expansion=False, | ||
| needs_static_script_compilation=False, | ||
| ) | ||
|
|
||
| statement_config = StatementConfig(dialect="postgres", parameter_config=param_config) | ||
| assert statement_config.parameter_config.default_parameter_style == ParameterStyle.NUMERIC | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| def test_parameter_styles() -> None: | ||
| from sqlspec.core.parameters import ParameterStyle | ||
|
|
||
| # Question mark (SQLite, DuckDB) | ||
| qmark = ParameterStyle.QMARK # WHERE id = ? | ||
|
|
||
| # Numeric (PostgreSQL, asyncpg) | ||
| numeric = ParameterStyle.NUMERIC # WHERE id = $1 | ||
|
|
||
| # Named colon (Oracle, SQLite) | ||
| named_colon = ParameterStyle.NAMED_COLON # WHERE id = :id | ||
|
|
||
| # Named at (BigQuery) | ||
|
|
||
| # Format/pyformat (psycopg, MySQL) | ||
|
|
||
| assert qmark == ParameterStyle.QMARK | ||
| assert numeric == ParameterStyle.NUMERIC | ||
| assert named_colon == ParameterStyle.NAMED_COLON |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| """Test configuration example: Global cache configuration.""" | ||
|
|
||
| SQL_CACHE_SIZE = 1000 | ||
|
|
||
|
|
||
| def test_global_cache_config() -> None: | ||
| """Test global cache configuration.""" | ||
| from sqlspec.core.cache import CacheConfig, update_cache_config | ||
|
|
||
| cache_config = CacheConfig( | ||
| compiled_cache_enabled=True, # Cache compiled SQL | ||
| sql_cache_enabled=True, # Cache SQL strings | ||
| fragment_cache_enabled=True, # Cache SQL fragments | ||
| optimized_cache_enabled=True, # Cache optimized AST | ||
| sql_cache_size=SQL_CACHE_SIZE, # Maximum cached SQL items | ||
| ) | ||
|
|
||
| # Update global cache configuration | ||
| update_cache_config(cache_config) | ||
|
|
||
| # Verify config applied | ||
| assert cache_config.sql_cache_enabled is True | ||
| assert cache_config.sql_cache_size == SQL_CACHE_SIZE |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| """Test configuration example: Per-instance cache configuration.""" | ||
|
|
||
|
|
||
| def test_per_instance_cache_config() -> None: | ||
| """Test per-instance cache configuration.""" | ||
| import tempfile | ||
|
|
||
| from sqlspec import SQLSpec | ||
| from sqlspec.adapters.sqlite import SqliteConfig | ||
| from sqlspec.core.cache import CacheConfig | ||
|
|
||
| with tempfile.NamedTemporaryFile(suffix=".db", delete=True) as tmp: | ||
| # Configure cache for specific SQLSpec instance | ||
| spec = SQLSpec() | ||
| spec.update_cache_config(CacheConfig(sql_cache_enabled=True, sql_cache_size=500)) | ||
|
|
||
| # Add database config | ||
| db = spec.add_config(SqliteConfig(pool_config={"database": tmp.name})) | ||
|
|
||
| # Use the configured spec | ||
| with spec.provide_session(db) as session: | ||
| result = session.execute("SELECT 1") | ||
| assert result is not None |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| """Test configuration example: Cache statistics tracking.""" | ||
|
|
||
|
|
||
| def test_cache_statistics() -> None: | ||
| """Test cache statistics tracking.""" | ||
| import tempfile | ||
|
|
||
| from sqlspec import SQLSpec | ||
| from sqlspec.adapters.sqlite import SqliteConfig | ||
| from sqlspec.core.cache import get_cache_statistics, log_cache_stats | ||
|
|
||
| with tempfile.NamedTemporaryFile(suffix=".db", delete=True) as tmp: | ||
| spec = SQLSpec() | ||
| db = spec.add_config(SqliteConfig(pool_config={"database": tmp.name})) | ||
|
|
||
| # Execute some queries to generate cache activity | ||
| with spec.provide_session(db) as session: | ||
| session.execute("SELECT 1") | ||
| session.execute("SELECT 1") # Should hit cache | ||
|
|
||
| # Get statistics | ||
| stats = get_cache_statistics() | ||
| assert isinstance(stats, dict) | ||
| assert "multi_level" in stats | ||
|
|
||
| # Log statistics (logs to configured logger) | ||
| log_cache_stats() |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| """Test configuration example: Cache clearing operations.""" | ||
|
|
||
|
|
||
| def test_clear_cache() -> None: | ||
| """Test cache clearing operations.""" | ||
| from sqlspec.core.cache import clear_all_caches, get_cache_statistics | ||
|
|
||
| # Get initial statistics | ||
| stats_before = get_cache_statistics() | ||
| assert isinstance(stats_before, dict) | ||
|
|
||
| # Clear all caches and reset statistics | ||
| clear_all_caches() | ||
|
|
||
| # Verify caches were cleared | ||
| stats_after = get_cache_statistics() | ||
| assert isinstance(stats_after, dict) | ||
| assert "multi_level" in stats_after |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| """Test configuration example: Binding multiple database configurations.""" | ||
|
|
||
|
|
||
| def test_binding_multiple_configs() -> None: | ||
| """Test binding multiple database configurations.""" | ||
| import tempfile | ||
|
|
||
| from sqlspec import SQLSpec | ||
| from sqlspec.adapters.asyncpg import AsyncpgConfig | ||
| from sqlspec.adapters.sqlite import SqliteConfig | ||
|
|
||
| with tempfile.NamedTemporaryFile(suffix=".db", delete=True) as tmp: | ||
| spec = SQLSpec() | ||
|
|
||
| # Add multiple configurations | ||
| sqlite_db = spec.add_config(SqliteConfig(pool_config={"database": tmp.name})) | ||
| spec.add_config(AsyncpgConfig(pool_config={"dsn": "postgresql://..."})) | ||
euri10 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| # Use specific configuration | ||
| with spec.provide_session(sqlite_db) as session: | ||
| session.execute("SELECT 1") | ||
|
|
||
| assert spec.configs[SqliteConfig].pool_config["database"] == tmp.name | ||
euri10 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| assert spec.configs[AsyncpgConfig].pool_config["dsn"] == "postgresql://..." | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| def test_sqlite_config_setup() -> None: | ||
| from sqlspec.adapters.sqlite import SqliteConfig | ||
|
|
||
| config = SqliteConfig( | ||
| pool_config={ | ||
| "database": "myapp.db", # Database file path | ||
| "timeout": 5.0, # Lock timeout in seconds | ||
| "check_same_thread": False, # Allow multi-thread access | ||
| "cached_statements": 100, # Statement cache size | ||
| "uri": False, # Enable URI mode | ||
| } | ||
| ) | ||
| assert config.pool_config["database"] == "myapp.db" |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| """Test configuration example: Named database bindings.""" | ||
|
|
||
|
|
||
| def test_named_bindings() -> None: | ||
| """Test named database bindings.""" | ||
| import tempfile | ||
|
|
||
| from sqlspec import SQLSpec | ||
| from sqlspec.adapters.asyncpg import AsyncpgConfig | ||
| from sqlspec.adapters.sqlite import SqliteConfig | ||
|
|
||
| with tempfile.NamedTemporaryFile(suffix=".db", delete=True) as tmp: | ||
| spec = SQLSpec() | ||
|
|
||
| # Add with bind keys | ||
| spec.add_config(SqliteConfig(pool_config={"database": tmp.name}, bind_key="cache_db")) | ||
| spec.add_config(AsyncpgConfig(pool_config={"dsn": "postgresql://..."}, bind_key="main_db")) | ||
|
|
||
| # Access by bind key | ||
| with spec.provide_session("cache_db") as session: | ||
| session.execute("SELECT 1") | ||
|
|
||
| assert spec.configs[SqliteConfig].pool_config["database"] == tmp.name | ||
euri10 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| assert spec.configs[AsyncpgConfig].pool_config["dsn"] == "postgresql://..." | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| """Test configuration example: Basic migration configuration.""" | ||
|
|
||
| import pytest | ||
|
|
||
|
|
||
| @pytest.mark.skipif( | ||
| not pytest.importorskip("asyncpg", reason="AsyncPG not installed"), reason="AsyncPG integration tests disabled" | ||
| ) | ||
| def test_basic_migration_config() -> None: | ||
| """Test basic migration configuration.""" | ||
| from sqlspec.adapters.asyncpg import AsyncpgConfig | ||
|
|
||
| config = AsyncpgConfig( | ||
| pool_config={"dsn": "postgresql://localhost/db"}, | ||
| extension_config={ | ||
| "litestar": {"session_table": "custom_sessions"} # Extension settings | ||
| }, | ||
| migration_config={ | ||
| "script_location": "migrations", # Migration directory | ||
| "version_table": "alembic_version", # Version tracking table | ||
| "include_extensions": ["litestar"], # Simple string list only | ||
| }, | ||
| ) | ||
|
|
||
| assert config.migration_config["script_location"] == "migrations" | ||
| assert "litestar" in config.migration_config["include_extensions"] |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| def test_basic_migration_config() -> None: | ||
| from sqlspec.adapters.asyncpg import AsyncpgConfig | ||
|
|
||
| config = AsyncpgConfig( | ||
| pool_config={"dsn": "postgresql://localhost/db"}, | ||
| extension_config={ | ||
| "litestar": {"session_table": "custom_sessions"} # Extension settings | ||
| }, | ||
| migration_config={ | ||
| "script_location": "migrations", # Migration directory | ||
| "version_table": "alembic_version", # Version tracking table | ||
| "include_extensions": ["litestar"], # Simple string list only | ||
| }, | ||
| ) | ||
| assert config.migration_config["script_location"] == "migrations" | ||
| assert "litestar" in config.migration_config["include_extensions"] |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| """Test configuration example: Environment-based configuration.""" | ||
|
|
||
|
|
||
| def test_extension_config() -> None: | ||
| from sqlspec.adapters.asyncpg import AsyncpgConfig | ||
|
|
||
| config = AsyncpgConfig( | ||
| pool_config={"dsn": "postgresql://localhost/db"}, | ||
| extension_config={ | ||
| "litestar": { | ||
| "connection_key": "db_connection", | ||
| "session_key": "db_session", | ||
| "pool_key": "db_pool", | ||
| "commit_mode": "autocommit", | ||
| "enable_correlation_middleware": True, | ||
|
||
| } | ||
| }, | ||
| ) | ||
| assert config.extension_config == { | ||
| "litestar": { | ||
| "connection_key": "db_connection", | ||
| "session_key": "db_session", | ||
| "pool_key": "db_pool", | ||
| "commit_mode": "autocommit", | ||
| "enable_correlation_middleware": True, | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| """Test configuration example: Environment-based configuration.""" | ||
|
|
||
| import os | ||
| from unittest.mock import patch | ||
|
|
||
| import pytest | ||
|
|
||
| POSTGRES_PORT = 5433 | ||
|
|
||
|
|
||
| @pytest.mark.skipif(os.getenv("TEST_ASYNCPG", "0") != "1", reason="AsyncPG integration tests disabled") | ||
| def test_environment_based_configuration() -> None: | ||
| """Test environment-based configuration pattern.""" | ||
|
|
||
| # Mock environment variables | ||
| env_vars = { | ||
| "DB_HOST": "testhost", | ||
| "DB_PORT": "5433", | ||
| "DB_USER": "testuser", | ||
| "DB_PASSWORD": "testpass", | ||
| "DB_NAME": "testdb", | ||
| } | ||
|
|
||
| with patch.dict(os.environ, env_vars, clear=False): | ||
| from sqlspec.adapters.asyncpg import AsyncpgConfig | ||
|
|
||
| config = AsyncpgConfig( | ||
| pool_config={ | ||
| "host": os.getenv("DB_HOST", "localhost"), | ||
| "port": int(os.getenv("DB_PORT", "5432")), | ||
| "user": os.getenv("DB_USER"), | ||
| "password": os.getenv("DB_PASSWORD"), | ||
| "database": os.getenv("DB_NAME"), | ||
| } | ||
| ) | ||
|
|
||
| assert config.pool_config["host"] == "testhost" | ||
| assert config.pool_config["port"] == POSTGRES_PORT | ||
| assert config.pool_config["user"] == "testuser" | ||
| assert config.pool_config["password"] == "testpass" | ||
| assert config.pool_config["database"] == "testdb" |
Uh oh!
There was an error while loading. Please reload this page.