### Installation and Configuration Source: https://context7.com/trilogy-libraries/activerecord-trilogy-adapter/llms.txt Instructions on how to add the gem to your Gemfile and configure the database adapter in config/database.yml. ```APIDOC ## Installation Add the gem to your Gemfile and configure the database adapter. ```ruby # Gemfile gem "activerecord-trilogy-adapter" ``` ```yaml # config/database.yml development: adapter: trilogy host: localhost port: 3306 database: myapp_development username: root password: secret ``` ``` -------------------------------- ### Establishing Database Connections Source: https://context7.com/trilogy-libraries/activerecord-trilogy-adapter/llms.txt Examples of how to establish database connections using Active Record's standard API with various Trilogy-specific options. ```APIDOC ## Establishing Database Connections Configure and establish connections using Active Record's standard connection API with Trilogy-specific options. ```ruby # Basic connection establishment ActiveRecord::Base.establish_connection( adapter: "trilogy", host: "localhost", port: 3306, database: "demo_development", username: "root", password: "secret" ) # Connection with SSL mode ActiveRecord::Base.establish_connection( adapter: "trilogy", host: "db.example.com", database: "production_db", username: "app_user", ssl_mode: "SSL_MODE_VERIFY_IDENTITY", # or "required", "preferred", "disabled" sslca: "/path/to/ca-cert.pem", sslcert: "/path/to/client-cert.pem", sslkey: "/path/to/client-key.pem" ) # Connection via Unix socket ActiveRecord::Base.establish_connection( adapter: "trilogy", socket: "/var/run/mysqld/mysqld.sock", database: "myapp_development", username: "root" ) # Connection with custom SQL mode and timeout ActiveRecord::Base.establish_connection( adapter: "trilogy", host: "localhost", database: "myapp_development", username: "root", read_timeout: 5, variables: { sql_mode: "STRICT_ALL_TABLES" } ) ``` ``` -------------------------------- ### Managing Database Connections with Trilogy Adapter Source: https://context7.com/trilogy-libraries/activerecord-trilogy-adapter/llms.txt Provides examples for managing database connection lifecycle, including checking active status, explicit connection, reconnection, disconnection, and discarding connections. It also covers safe string and identifier quoting. ```ruby adapter = ActiveRecord::Base.connection if adapter.active? puts "Connection is active and responding to ping" else puts "Connection is inactive" end adapter.connected? adapter.connect! adapter.reconnect! adapter.reset! adapter.disconnect! adapter.discard! safe_string = adapter.quote_string("O'Reilly") adapter.quote_column_name("user") adapter.quote_table_name("order_items") ``` -------------------------------- ### Add Trilogy Adapter Gem to Gemfile Source: https://github.com/trilogy-libraries/activerecord-trilogy-adapter/blob/main/README.md This snippet shows how to add the activerecord-trilogy-adapter gem to your application's Gemfile. After adding the gem, run 'bundle install' to install it and its dependencies. ```ruby gem "activerecord-trilogy-adapter" ``` -------------------------------- ### Error Handling for Database Connections Source: https://context7.com/trilogy-libraries/activerecord-trilogy-adapter/llms.txt Provides examples of how to handle various database connection errors using Active Record exceptions. This includes scenarios like a non-existent database, authentication failures, host connection issues, and query timeouts, with specific rescue blocks for each. ```ruby # Database not found error begin ActiveRecord::Base.establish_connection( adapter: "trilogy", host: "localhost", database: "nonexistent_db", username: "root" ) ActiveRecord::Base.connection.execute("SELECT 1") rescue ActiveRecord::NoDatabaseError => e puts "Database does not exist: #{e.message}" # Create the database system("bin/rails db:create") end # Authentication error begin ActiveRecord::Base.establish_connection( adapter: "trilogy", host: "localhost", database: "myapp", username: "invalid_user", password: "wrong_password" ) ActiveRecord::Base.connection.execute("SELECT 1") rescue ActiveRecord::DatabaseConnectionError => e puts "Authentication failed: #{e.message}" end # Host connection error begin ActiveRecord::Base.establish_connection( adapter: "trilogy", host: "invalid.hostname.local", database: "myapp" ) ActiveRecord::Base.connection.execute("SELECT 1") rescue ActiveRecord::DatabaseConnectionError => e puts "Cannot connect to host: #{e.message}" end # Query timeout error begin ActiveRecord::Base.establish_connection( adapter: "trilogy", host: "localhost", database: "myapp", read_timeout: 1 ) ActiveRecord::Base.connection.execute("SELECT SLEEP(5)") rescue ActiveRecord::StatementInvalid => e if e.cause.is_a?(Trilogy::TimeoutError) puts "Query timed out" else raise end end ``` -------------------------------- ### Configuring Timezone Handling for Datetime Columns Source: https://context7.com/trilogy-libraries/activerecord-trilogy-adapter/llms.txt Explains how to configure timezone handling for datetime columns in ActiveRecord when using the Trilogy adapter. It demonstrates setting the default timezone and shows an example of inserting and retrieving datetime values with UTC. ```ruby ActiveRecord.default_timezone = :utc adapter = ActiveRecord::Base.connection adapter.execute("INSERT INTO posts (title, body, kind, created_at, updated_at) VALUES ('Test', 'Content', 'article', '2024-01-15 12:00:00', '2024-01-15 12:00:00')") result = adapter.execute("SELECT created_at FROM posts LIMIT 1") puts result.rows.first.first ``` -------------------------------- ### Analyze Query Plans with EXPLAIN Source: https://context7.com/trilogy-libraries/activerecord-trilogy-adapter/llms.txt Demonstrates how to use the `explain` method provided by the Trilogy adapter to analyze the execution plan of SQL queries, which is useful for query optimization. ```ruby adapter = ActiveRecord::Base.connection # Basic EXPLAIN explain_output = adapter.explain( Post.where(published: true).arel, [] ) puts explain_output # +----+-------------+-------+------+---------------+------+---------+------+------+-------------+ ``` -------------------------------- ### Establish Database Connections with Active Record and Trilogy Source: https://context7.com/trilogy-libraries/activerecord-trilogy-adapter/llms.txt Demonstrates how to establish database connections using Active Record's `establish_connection` method with various Trilogy-specific options, including basic configuration, SSL settings, Unix socket connections, and custom SQL modes or timeouts. ```ruby # Basic connection establishment ActiveRecord::Base.establish_connection( adapter: "trilogy", host: "localhost", port: 3306, database: "demo_development", username: "root", password: "secret" ) ``` ```ruby # Connection with SSL mode ActiveRecord::Base.establish_connection( adapter: "trilogy", host: "db.example.com", database: "production_db", username: "app_user", ssl_mode: "SSL_MODE_VERIFY_IDENTITY", # or "required", "preferred", "disabled" sslca: "/path/to/ca-cert.pem", sslcert: "/path/to/client-cert.pem", sslkey: "/path/to/client-key.pem" ) ``` ```ruby # Connection via Unix socket ActiveRecord::Base.establish_connection( adapter: "trilogy", socket: "/var/run/mysqld/mysqld.sock", database: "myapp_development", username: "root" ) ``` ```ruby # Connection with custom SQL mode and timeout ActiveRecord::Base.establish_connection( adapter: "trilogy", host: "localhost", database: "myapp_development", username: "root", read_timeout: 5, variables: { sql_mode: "STRICT_ALL_TABLES" } ) ``` -------------------------------- ### Launching and Using Rails dbconsole with Trilogy Adapter Source: https://context7.com/trilogy-libraries/activerecord-trilogy-adapter/llms.txt Illustrates how to launch the Rails database console for interactive MySQL sessions using the Trilogy adapter. It covers command-line options and programmatic access. ```bash bin/rails dbconsole bin/rails dbconsole -p bin/rails dbconsole -e production ``` -------------------------------- ### Executing SQL Queries with ActiveRecord Trilogy Adapter Source: https://context7.com/trilogy-libraries/activerecord-trilogy-adapter/llms.txt Demonstrates how to execute raw SQL queries, including EXPLAIN with ANALYZE and selecting single values. It uses the adapter's `explain` and `select_value` methods. ```ruby explain_output = adapter.explain( Post.joins(:author).where(authors: { active: true }).arel, [], ["ANALYZE"] ) puts explain_output count = adapter.select_value("SELECT COUNT(*) FROM posts WHERE published = 1") puts "Published posts: #{count}" ``` -------------------------------- ### Executing SQL Queries Source: https://context7.com/trilogy-libraries/activerecord-trilogy-adapter/llms.txt Demonstrates how to execute raw SQL queries and retrieve results using the connection adapter, including SELECT, INSERT, DELETE, and UPDATE operations. ```APIDOC ## Executing SQL Queries Execute raw SQL queries and retrieve results using the connection adapter. ```ruby # Get the connection adapter adapter = ActiveRecord::Base.connection # Execute a SELECT query result = adapter.execute("SELECT * FROM users WHERE active = 1") puts result.columns # => ["id", "name", "email", "active", "created_at"] puts result.rows # => [[1, "John", "john@example.com", 1, 2024-01-15 10:30:00 UTC], ...] # Execute INSERT adapter.execute("INSERT INTO posts (title, body, created_at, updated_at) VALUES ('Hello', 'World', NOW(), NOW())") # Execute with internal_exec_query for Active Record Result objects result = adapter.internal_exec_query("SELECT id, title FROM posts WHERE published = ?", "SQL", [true]) result.columns # => ["id", "title"] result.rows # => [[1, "First Post"], [2, "Second Post"]] # Execute DELETE and get affected rows count affected = adapter.exec_delete("DELETE FROM posts WHERE id = ?", nil, [1]) puts "Deleted #{affected} rows" # Execute UPDATE and get affected rows count affected = adapter.exec_update("UPDATE posts SET title = ? WHERE id = ?", nil, ["New Title", 2]) puts "Updated #{affected} rows" ``` ``` -------------------------------- ### Inspecting Database Schema and Indexes Source: https://context7.com/trilogy-libraries/activerecord-trilogy-adapter/llms.txt Shows how to programmatically query database schema information, including table indexes, and check for feature support like JSON and comments. It also demonstrates retrieving the adapter name. ```ruby adapter = ActiveRecord::Base.connection indexes = adapter.indexes("posts") indexes.each do |index| puts "Index: #{index.name}" puts " Columns: #{index.columns.join(', ')}" puts " Unique: #{index.unique}" puts " Using: #{index.using}" end adapter.supports_json? adapter.supports_comments? adapter.supports_comments_in_create? adapter.supports_savepoints? adapter.supports_lazy_transactions? adapter.adapter_name ``` -------------------------------- ### Query Explanation and Debugging Source: https://context7.com/trilogy-libraries/activerecord-trilogy-adapter/llms.txt Shows how to use the EXPLAIN command to analyze query execution plans for optimization. ```APIDOC ## Query Explanation and Debugging Use EXPLAIN to analyze query execution plans for optimization. ```ruby adapter = ActiveRecord::Base.connection # Basic EXPLAIN explain_output = adapter.explain( Post.where(published: true).arel, [] ) puts explain_output # +----+-------------+-------+------+---------------+------+---------+------+------+-------------+ ``` -------------------------------- ### Execute Raw SQL Queries with Trilogy Adapter Source: https://context7.com/trilogy-libraries/activerecord-trilogy-adapter/llms.txt Shows how to execute raw SQL queries using the Active Record connection adapter provided by the Trilogy adapter. It covers executing SELECT, INSERT, DELETE, and UPDATE statements, as well as using `internal_exec_query` for Active Record Result objects and retrieving affected row counts. ```ruby # Get the connection adapter adapter = ActiveRecord::Base.connection ``` ```ruby # Execute a SELECT query result = adapter.execute("SELECT * FROM users WHERE active = 1") puts result.columns # => ["id", "name", "email", "active", "created_at"] puts result.rows # => [[1, "John", "john@example.com", 1, 2024-01-15 10:30:00 UTC], ...] ``` ```ruby # Execute INSERT adapter.execute("INSERT INTO posts (title, body, created_at, updated_at) VALUES ('Hello', 'World', NOW(), NOW())") ``` ```ruby # Execute with internal_exec_query for Active Record Result objects result = adapter.internal_exec_query("SELECT id, title FROM posts WHERE published = ?", "SQL", [true]) result.columns # => ["id", "title"] result.rows # => [[1, "First Post"], [2, "Second Post"]] ``` ```ruby # Execute DELETE and get affected rows count affected = adapter.exec_delete("DELETE FROM posts WHERE id = ?", nil, [1]) puts "Deleted #{affected} rows" ``` ```ruby # Execute UPDATE and get affected rows count affected = adapter.exec_update("UPDATE posts SET title = ? WHERE id = ?", nil, ["New Title", 2]) puts "Updated #{affected} rows" ``` -------------------------------- ### Configure Database Connection with Trilogy Adapter Source: https://context7.com/trilogy-libraries/activerecord-trilogy-adapter/llms.txt Configure your database connection in `config/database.yml` to use the Trilogy adapter, specifying connection details like host, port, database name, username, and password. ```yaml development: adapter: trilogy host: localhost port: 3306 database: myapp_development username: root password: secret ``` -------------------------------- ### Programmatic Access to Rails dbconsole Source: https://context7.com/trilogy-libraries/activerecord-trilogy-adapter/llms.txt Demonstrates how to programmatically access the Rails database console using the Trilogy adapter. This allows for automated or scripted database interactions. ```ruby config = ActiveRecord::Base.configurations.configs_for(env_name: "development").first ActiveRecord::ConnectionAdapters::TrilogyAdapter.dbconsole(config, include_password: false) ``` -------------------------------- ### Manage Database Transactions with Trilogy Adapter Source: https://context7.com/trilogy-libraries/activerecord-trilogy-adapter/llms.txt Illustrates transaction management using the Trilogy adapter, including manual transaction control with `begin_db_transaction`, `commit_db_transaction`, and `rollback_db_transaction`, as well as utilizing Active Record's `transaction` block for automatic handling and nested transactions with savepoints. ```ruby adapter = ActiveRecord::Base.connection # Manual transaction control adapter.begin_db_transaction begin adapter.execute("INSERT INTO accounts (name, balance) VALUES ('Alice', 1000)") adapter.execute("INSERT INTO accounts (name, balance) VALUES ('Bob', 500)") adapter.commit_db_transaction rescue => e adapter.rollback_db_transaction raise e end ``` ```ruby # Using Active Record transaction block ActiveRecord::Base.transaction do User.create!(name: "Alice", email: "alice@example.com") Account.create!(user_id: User.last.id, balance: 1000) # Automatic rollback on exception end ``` ```ruby # Nested transactions with savepoints (supported by Trilogy) ActiveRecord::Base.transaction do User.create!(name: "Outer User") ActiveRecord::Base.transaction(requires_new: true) do User.create!(name: "Inner User") raise ActiveRecord::Rollback # Only rolls back inner transaction end # Outer transaction continues User.create!(name: "Another Outer User") end ``` -------------------------------- ### Enabling Multi-Statement Mode for Bulk Operations Source: https://context7.com/trilogy-libraries/activerecord-trilogy-adapter/llms.txt Shows how to enable and utilize multi-statement mode for bulk operations like fixture loading. This involves setting `multi_statement: true` in the connection configuration and executing multiple SQL statements sequentially. ```ruby ActiveRecord::Base.establish_connection( adapter: "trilogy", host: "localhost", database: "test_db", username: "root", multi_statement: true ) conn = ActiveRecord::Base.connection conn.execute("SELECT 1; SELECT 2;") conn.raw_connection.next_result while conn.raw_connection.more_results_exist? fixtures = { "posts" => [ { "id" => 1, "title" => "First Post", "body" => "Content 1", "kind" => "article", "created_at" => Time.now.utc, "updated_at" => Time.now.utc }, { "id" => 2, "title" => "Second Post", "body" => "Content 2", "kind" => "tutorial", "created_at" => Time.now.utc, "updated_at" => Time.now.utc } ], "users" => [ { "id" => 1, "name" => "Alice", "email" => "alice@example.com", "created_at" => Time.now.utc, "updated_at" => Time.now.utc } ] } conn.insert_fixtures_set(fixtures) ``` -------------------------------- ### Query Caching with Active Record Source: https://context7.com/trilogy-libraries/activerecord-trilogy-adapter/llms.txt Demonstrates how to enable and utilize Active Record's query caching mechanism with the Trilogy adapter. This speeds up repeated identical queries by storing results in memory. SQL notifications are used to verify cache hits and misses. ```ruby adapter = ActiveRecord::Base.connection # Enable query caching adapter.cache do # First query hits the database result1 = adapter.select_all("SELECT * FROM posts", "uncached query") # Second identical query returns cached result result2 = adapter.select_all("SELECT * FROM posts", "cached query") end # Subscribe to SQL notifications to verify caching ActiveSupport::Notifications.subscribe("sql.active_record") do |name, start, finish, id, payload| if payload[:cached] puts "Cache hit: #{payload[:sql]}" else puts "Cache miss: #{payload[:sql]}" end end ``` -------------------------------- ### Async Queries in Rails 7.0+ Source: https://context7.com/trilogy-libraries/activerecord-trilogy-adapter/llms.txt Shows how to execute database queries asynchronously using the Trilogy adapter in Rails 7.0 and later. This feature improves performance by allowing other operations to proceed while waiting for query results. It includes checking the query status and retrieving results. ```ruby # Requires Rails 7.0+ with async query support adapter = ActiveRecord::Base.connection adapter.pool = ActiveRecord::Base.connection_pool ActiveRecord::Base.asynchronous_queries_tracker.start_session # Execute async query result = adapter.select_all("SELECT * FROM large_table", async: true) # Check if still loading while result.pending? puts "Query still running..." sleep 0.01 end # Get results (blocks if not ready) rows = result.to_a puts "Got #{rows.count} rows" ActiveRecord::Base.asynchronous_queries_tracker.finalize_session ``` -------------------------------- ### Configure Database Adapter in database.yml Source: https://github.com/trilogy-libraries/activerecord-trilogy-adapter/blob/main/README.md This snippet demonstrates how to configure your application's database.yml file to use the Trilogy adapter. This change directs Active Record to use Trilogy for database connections. ```yaml adapter: trilogy ``` -------------------------------- ### Transaction Management Source: https://context7.com/trilogy-libraries/activerecord-trilogy-adapter/llms.txt Covers database transaction management, including manual control, Active Record transaction blocks, and nested transactions with savepoints. ```APIDOC ## Transaction Management Manage database transactions with support for savepoints and rollbacks. ```ruby adapter = ActiveRecord::Base.connection # Manual transaction control adapter.begin_db_transaction begin adapter.execute("INSERT INTO accounts (name, balance) VALUES ('Alice', 1000)") adapter.execute("INSERT INTO accounts (name, balance) VALUES ('Bob', 500)") adapter.commit_db_transaction rescue => e adapter.rollback_db_transaction raise e end # Using Active Record transaction block ActiveRecord::Base.transaction do User.create!(name: "Alice", email: "alice@example.com") Account.create!(user_id: User.last.id, balance: 1000) # Automatic rollback on exception end # Nested transactions with savepoints (supported by Trilogy) ActiveRecord::Base.transaction do User.create!(name: "Outer User") ActiveRecord::Base.transaction(requires_new: true) do User.create!(name: "Inner User") raise ActiveRecord::Rollback # Only rolls back inner transaction end # Outer transaction continues User.create!(name: "Another Outer User") end ``` ``` -------------------------------- ### Setting Default Timezone Source: https://context7.com/trilogy-libraries/activerecord-trilogy-adapter/llms.txt Configures Active Record to use the local timezone for date and time operations. This ensures that timestamps stored and retrieved from the database are interpreted according to the application's local time settings. ```ruby ActiveRecord.default_timezone = :local result = adapter.execute("SELECT created_at FROM posts LIMIT 1") puts result.rows.first.first # => 2024-01-15 12:00:00 -0500 (local time) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.