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
end

Accessing 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_logger

Configuration Options

Core Database Settings

Option
Type
Default
Description

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

Option
Type
Default
Description

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

Option
Type
Default
Description

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

Option
Type
Default
Description

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 settings

  • ssl - SSL/TLS configuration

  • postgresql - PostgreSQL-specific settings

  • mysql - MySQL-specific settings

  • sqlite - 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

Option
Type
Default
Description

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

Option
Type
Default
Description

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_url cannot be empty

  • schema_path cannot be empty

  • schema_file_name cannot be empty

  • schema_file_name must end with .cr extension

  • connection_pool.size must be positive

  • connection_pool.initial_size must be positive

  • connection_pool.max_idle_size must be positive

  • connection_pool.max_retry_attempts must be positive

  • default_timezone must be :utc or :local

  • ssl.mode must be one of: disable, allow, prefer, require, verify-ca, verify-full

  • sqlite.journal_mode must be one of: delete, truncate, persist, memory, wal, off

  • sqlite.synchronous must be one of: off, normal, full, extra

  • sqlite.busy_timeout must 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 parameters

  • database_adapter : Adapter - Get database adapter based on URL

  • database_config : DatabaseConfig - Get database-specific configuration

  • effective_logger : Log - Get the effective logger instance

  • schema_file_path : String - Get full schema file path

Migration Methods

  • create_migrator_config(**args) : CQL::MigratorConfig - Create migrator configuration

  • create_migrator_config_for_environment(env : String) : CQL::MigratorConfig - Create environment-specific migrator config

  • create_migrator(schema : Schema) : CQL::Migrator - Create migrator with configuration

  • setup_performance_monitoring(schema : Schema) : Nil - Setup performance monitoring

Validation Methods

  • validate! : Nil - Validate all configuration settings

  • add_validator(validator : ConfigValidator) : Nil - Add custom validator

CQL Schema and Migration Methods

  • CQL.create_schema(name : Symbol, &block) : Schema - Create schema with configuration

  • CQL.create_migrator(schema : Schema, migrator_config : MigratorConfig? = nil) : Migrator - Create migrator

  • CQL.bootstrap_schema(schema : Schema) : Migrator - Bootstrap schema from existing database

  • CQL.verify_schema(schema : Schema, auto_fix : Bool = false) : Bool - Verify schema consistency

  • CQL.create_migrator_config(**args) : MigratorConfig - Create migrator config

  • CQL.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 examples

  • examples/configure_migration_example.cr - Migration workflow integration examples

Last updated

Was this helpful?