Configuration
The CQL::Configure module provides a centralized, thread-safe way to configure all fundamental settings of the CQL library. This guide covers how to use the configuration system effectively in your Crystal applications.
Quick Start
Basic Configuration
The simplest way to configure CQL is using the CQL.configure block:
require "cql"
CQL.configure do |config|
config.database_url = "postgresql://localhost/myapp_development"
config.logger = Log.for("MyApp")
config.default_timezone = :utc
config.auto_load_models = true
endAccessing Configuration
After configuration, you can access settings throughout your application:
# Direct access
puts CQL.config.database_url
puts CQL.config.connection_pool.size
# Using effective methods
puts CQL.config.effective_database_url
puts CQL.config.effective_loggerConfiguration Options
Core Database Settings
database_url
String
"sqlite3://./db/development.db"
Database connection URL
logger
Log
Environment-based
Logger instance for CQL operations
default_timezone
Symbol
:utc
Default timezone (:utc or :local)
environment
String
ENV["CRYSTAL_ENV"] or "development"
Application environment
Migration and Schema Management
migration_table_name
Symbol
:cql_schema_migrations
Name of migration tracking table
schema_path
String
"src/schemas"
Path where schema files are stored
schema_file_name
String
"app_schema.cr"
Default schema file name
schema_constant_name
Symbol
:AppSchema
Schema constant name in generated file
schema_symbol
Symbol
:app_schema
Schema symbol for internal use
auto_load_models
Bool
true
Whether to automatically load model files
enable_auto_schema_sync
Bool
true
Enable automatic schema file synchronization
bootstrap_on_startup
Bool
false
Whether to bootstrap schema on first run
verify_schema_on_startup
Bool
false
Whether to verify schema consistency on startup
Query and Performance Settings
enable_query_cache
Bool
false
Enable query result caching
cache_ttl
Time::Span
1.hour
Default cache time-to-live
enable_performance_monitoring
Bool
false
Enable performance monitoring
performance_config
CQL::Performance::PerformanceConfig
PerformanceConfig.new
Performance monitoring configuration
Custom Configuration
adapter_config
Hash(String, String)
Hash(String, String).new
Custom adapter configuration
Composed Configuration Objects
The configuration system uses composed objects for specialized settings:
connection_pool- Connection pooling settingsssl- SSL/TLS configurationpostgresql- PostgreSQL-specific settingsmysql- MySQL-specific settingssqlite- SQLite-specific settings
Environment-Specific Configuration
CQL automatically applies environment-specific defaults based on the CRYSTAL_ENV environment variable:
Development Environment
Test Environment
Production Environment
Custom Environment Configuration
Integration with Schema Definition
Use the configuration in your schema definitions:
Configuration-Aware Schema Setup
Performance Monitoring Configuration
Configure performance monitoring through the main configuration:
Database-Specific Configuration
PostgreSQL Configuration
MySQL Configuration
SQLite Configuration
Connection Pooling Configuration
Configure connection pooling settings:
Connection Pool Settings
size
Int32
10
Maximum pool size
initial_size
Int32
1
Initial pool size
max_idle_size
Int32
1
Maximum idle connections
checkout_timeout
Time::Span
10.seconds
Connection checkout timeout
query_timeout
Time::Span
30.seconds
Query execution timeout
max_retry_attempts
Int32
3
Maximum retry attempts
retry_delay
Time::Span
1.second
Delay between retries
use_prepared_statements
Bool
true
Use prepared statements
SSL Configuration
Configure SSL/TLS settings for secure database connections:
SSL Settings
mode
String
"prefer"
SSL mode (disable, allow, prefer, require, verify-ca, verify-full)
cert_path
String?
nil
Path to client certificate
key_path
String?
nil
Path to client private key
ca_path
String?
nil
Path to CA certificate
Migration Workflow Integration
CQL's configuration system integrates seamlessly with the migration workflow to provide automatic schema generation and synchronization.
Basic Migration Setup
Environment-Specific Migration Settings
The configuration automatically applies environment-specific migration defaults:
Migration Helper Methods
CQL provides helper methods for common migration operations:
Complete Migration Workflow Example
Thread Safety
The configuration system is fully thread-safe:
Configuration Initialization
Configuration is lazily initialized and cached:
Validation
Configuration settings are validated when the configuration block completes:
Validation Rules
database_urlcannot be emptyschema_pathcannot be emptyschema_file_namecannot be emptyschema_file_namemust end with.crextensionconnection_pool.sizemust be positiveconnection_pool.initial_sizemust be positiveconnection_pool.max_idle_sizemust be positiveconnection_pool.max_retry_attemptsmust be positivedefault_timezonemust be:utcor:localssl.modemust be one of:disable,allow,prefer,require,verify-ca,verify-fullsqlite.journal_modemust be one of:delete,truncate,persist,memory,wal,offsqlite.synchronousmust be one of:off,normal,full,extrasqlite.busy_timeoutmust be non-negative
Custom Validation
Add custom validators to the configuration:
Best Practices
1. Configure Early
Configure CQL before defining schemas or models:
2. Use Environment Variables
3. Separate Configuration by Environment
4. Reset Configuration in Tests
5. Use Configuration Validation
API Reference
CQL.configure
Main configuration method that yields a configuration object:
CQL.config
Returns the current configuration instance (read-only):
CQL.reset_config!
Resets configuration to defaults (useful for testing):
CQL::Configure::Config
Configuration object with all settings. See Configuration Options for complete list.
CQL::Configure::Config Methods
Core Methods
effective_database_url : String- Get effective database URL with all parametersdatabase_adapter : Adapter- Get database adapter based on URLdatabase_config : DatabaseConfig- Get database-specific configurationeffective_logger : Log- Get the effective logger instanceschema_file_path : String- Get full schema file path
Migration Methods
create_migrator_config(**args) : CQL::MigratorConfig- Create migrator configurationcreate_migrator_config_for_environment(env : String) : CQL::MigratorConfig- Create environment-specific migrator configcreate_migrator(schema : Schema) : CQL::Migrator- Create migrator with configurationsetup_performance_monitoring(schema : Schema) : Nil- Setup performance monitoring
Validation Methods
validate! : Nil- Validate all configuration settingsadd_validator(validator : ConfigValidator) : Nil- Add custom validator
CQL Schema and Migration Methods
CQL.create_schema(name : Symbol, &block) : Schema- Create schema with configurationCQL.create_migrator(schema : Schema, migrator_config : MigratorConfig? = nil) : Migrator- Create migratorCQL.bootstrap_schema(schema : Schema) : Migrator- Bootstrap schema from existing databaseCQL.verify_schema(schema : Schema, auto_fix : Bool = false) : Bool- Verify schema consistencyCQL.create_migrator_config(**args) : MigratorConfig- Create migrator configCQL.create_migrator_config_for_environment(env : String) : MigratorConfig- Create environment-specific migrator config
Examples
For complete usage examples, see:
examples/configure_example.cr- Basic configuration examplesexamples/configure_migration_example.cr- Migration workflow integration examples
Related Guides
Performance Monitoring
Last updated
Was this helpful?