### Establish libSQL Database Connections Programmatically in Ruby Source: https://context7.com/tursodatabase/libsql-activerecord/llms.txt Provides Ruby code examples for establishing libSQL database connections programmatically using `ActiveRecord::Base.establish_connection`. It covers creating an in-memory database, connecting to a remote Turso database, and configuring an embedded replica. Includes a verification step to confirm successful connection. ```ruby require 'libsql_activerecord' require 'active_record' # In-memory database for testing ActiveRecord::Base.establish_connection(adapter: 'libsql') # Remote Turso database ActiveRecord::Base.establish_connection( adapter: 'libsql', url: 'libsql://your-database.turso.io', auth_token: 'your_auth_token' ) # Embedded replica configuration ActiveRecord::Base.establish_connection( adapter: 'libsql', url: 'libsql://your-database.turso.io', auth_token: 'your_auth_token', path: 'storage/local_replica.db' ) # Verify connection begin ActiveRecord::Base.connection.execute("SELECT 1") puts "Connected successfully" rescue => e puts "Connection failed: #{e.message}" end ``` -------------------------------- ### Install libsql_activerecord Gem Source: https://github.com/tursodatabase/libsql-activerecord/blob/main/README.md This command installs the libsql_activerecord gem, which is necessary to use libSQL with ActiveRecord in Ruby on Rails applications. Ensure you have RubyGems installed and configured. ```bash gem install libsql_activerecord ``` -------------------------------- ### Define ActiveRecord Models and Perform CRUD in Ruby Source: https://context7.com/tursodatabase/libsql-activerecord/llms.txt Illustrates how to define ActiveRecord models and perform standard CRUD (Create, Read, Update, Delete) operations with the libSQL adapter in Ruby. It showcases model definition with validations and scopes, as well as examples for creating, reading, updating, and deleting records. Also includes examples of querying and iterating through results. ```ruby class Product < ActiveRecord::Base validates :name, presence: true validates :price, numericality: { greater_than: 0 } scope :expensive, -> { where('price > ?', 100) } end # Create records product = Product.create(name: 'Book', price: 29.99) product = Product.new(name: 'Laptop', price: 999.99) product.save # Read records all_products = Product.all book = Product.find_by(name: 'Book') expensive = Product.expensive # Update records book.update(price: 34.99) book.price = 39.99 book.save # Delete records book.destroy Product.where('price < ?', 10).destroy_all # Query results Product.where('price > ?', 50).order(price: :desc).limit(10).each do |p| puts "#{p.name}: $#{p.price}" end ``` -------------------------------- ### Generate and Manage Database Migrations with ActiveRecord DSL in Ruby Source: https://context7.com/tursodatabase/libsql-activerecord/llms.txt Shows how to create and manage database schema changes using ActiveRecord migrations in Ruby with the libSQL adapter. It includes examples of creating tables with various column types (string, text, decimal, integer, boolean, JSON) and adding indexes. Also demonstrates how to run migrations and perform rollbacks. ```ruby class CreateProducts < ActiveRecord::Migration[8.0] def change create_table :products do |t| t.string :name, null: false t.text :description t.decimal :price, precision: 10, scale: 2 t.integer :stock, default: 0 t.boolean :active, default: true t.json :metadata t.timestamps end add_index :products, :name add_index :products, :active end end class AddCategoryToProducts < ActiveRecord::Migration[8.0] def change add_column :products, :category, :string add_index :products, :category end end # Run migrations CreateProducts.migrate(:up) AddCategoryToProducts.migrate(:up) # Rollback AddCategoryToProducts.migrate(:down) ``` -------------------------------- ### Associations and Relationships with ActiveRecord in Ruby Source: https://context7.com/tursodatabase/libsql-activerecord/llms.txt Defines various ActiveRecord associations such as `has_many`, `belongs_to`, `has_one`, and `has_and_belongs_to_many`. It includes examples of dependent associations, through relationships, and model validations. ```ruby class User < ActiveRecord::Base has_many :posts, dependent: :destroy has_many :comments, dependent: :destroy has_one :profile, dependent: :destroy end class Post < ActiveRecord::Base belongs_to :user has_many :comments, dependent: :destroy has_many :tags, through: :post_tags has_many :post_tags validates :title, presence: true validates :content, length: { minimum: 10 } end class Comment < ActiveRecord::Base belongs_to :user belongs_to :post validates :content, presence: true end ``` -------------------------------- ### Advanced Queries with Prepared Statements in Ruby Source: https://context7.com/tursodatabase/libsql-activerecord/llms.txt Illustrates executing raw SQL queries with parameter binding using libSQL's prepare/execute mechanism for security and performance. It covers simple queries, parameterized queries, and ActiveRecord's `where` method for safer execution. Also shows how to insert data and retrieve the last inserted ID. ```ruby # Simple query result = ActiveRecord::Base.connection.execute("SELECT * FROM products WHERE price > 50") result.each do |row| puts "Product: #{row['name']}, Price: #{row['price']}" end # Parameterized query (preferred for safety) connection = ActiveRecord::Base.connection sql = "SELECT * FROM products WHERE category = ? AND price BETWEEN ? AND ?" params = ['Electronics', 100, 1000] stmt = connection.raw_connection.prepare(sql) begin rows = stmt.query(params) rows.each do |row| puts "#{row['name']}: $#{row['price']}" end ensure stmt.close end # Execute with ActiveRecord query methods (safer) Product.where('category = ? AND price BETWEEN ? AND ?', 'Electronics', 100, 1000).each do |p| puts "#{p.name}: $#{p.price}" end # Insert with last_inserted_id connection.execute("INSERT INTO products (name, price) VALUES (?, ?)", ['Widget', 19.99]) last_id = connection.raw_connection.last_inserted_id puts "Created product with ID: #{last_id}" ``` -------------------------------- ### Usage and Associations with ActiveRecord Models Source: https://context7.com/tursodatabase/libsql-activerecord/llms.txt Demonstrates how to create and associate records using ActiveRecord models. It shows creating a user, then a post associated with that user, and a comment associated with both a user and a post. This highlights the benefits of established associations. ```ruby # Usage with associations user = User.create(name: 'John Doe', email: 'john@example.com') post = user.posts.create(title: 'My First Post', content: 'Hello world!') comment = post.comments.create(user: user, content: 'Great post!') ``` -------------------------------- ### Configure libSQL Database Adapter in Rails Source: https://context7.com/tursodatabase/libsql-activerecord/llms.txt Demonstrates how to configure libSQL as the database adapter in Rails applications using the standard `database.yml` syntax. It shows configurations for remote Turso databases via URL and auth token, as well as embedded replicas with a local file path. Connection pooling and timeouts adhere to Rails conventions. ```yaml # config/database.yml default: adapter: libsql pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> timeout: 5000 development: <<: *default url: <%= ENV['TURSO_DATABASE_URL'] %> auth_token: <%= ENV['TURSO_AUTH_TOKEN'] %> path: storage/embedded_replica.turso test: <<: *default database: storage/test.sqlite3 production: <<: *default url: libsql://your-database.turso.io auth_token: your_production_token path: storage/production_replica.turso ``` -------------------------------- ### Transactions and Batch Operations in Ruby Source: https://context7.com/tursodatabase/libsql-activerecord/llms.txt Demonstrates how to manage database transactions, including standard and nested transactions with automatic rollback on exceptions. It also shows how to execute multiple SQL statements efficiently using `execute_batch`. ```ruby # Standard transaction begin ActiveRecord::Base.transaction do product = Product.create!(name: 'Gadget', price: 49.99) product.update!(stock: 100) # This will rollback both operations if it fails raise "Out of stock" if product.stock < 50 end rescue => e puts "Transaction rolled back: #{e.message}" end # Nested transactions Product.transaction do product1 = Product.create!(name: 'Item 1', price: 10) Product.transaction do product2 = Product.create!(name: 'Item 2', price: 20) # Inner transaction can rollback independently end product3 = Product.create!(name: 'Item 3', price: 30) end # Batch operations connection = ActiveRecord::Base.connection sql = <<~SQL INSERT INTO products (name, price, created_at, updated_at) VALUES ('Product A', 10, datetime('now'), datetime('now')); INSERT INTO products (name, price, created_at, updated_at) VALUES ('Product B', 20, datetime('now'), datetime('now')); INSERT INTO products (name, price, created_at, updated_at) VALUES ('Product C', 30, datetime('now'), datetime('now')); SQL connection.raw_connection.execute_batch(sql) puts "Batch insert completed: #{Product.count} products" ``` -------------------------------- ### Create Database Migrations for Associations in Rails Source: https://context7.com/tursodatabase/libsql-activerecord/llms.txt Defines a Rails migration to create tables for users, posts, and comments, establishing foreign key associations between them. This is a standard ActiveRecord migration pattern. ```ruby class CreateAssociations < ActiveRecord::Migration[8.0] def change create_table :users do |t| t.string :name t.string :email t.timestamps end create_table :posts do |t| t.references :user, foreign_key: true t.string :title t.text :content t.timestamps end create_table :comments do |t| t.references :user, foreign_key: true t.references :post, foreign_key: true t.text :content t.timestamps end end end ``` -------------------------------- ### ActiveRecord Connection Management and Reconnection Source: https://context7.com/tursodatabase/libsql-activerecord/llms.txt Shows how to manage database connections using ActiveRecord, including checking status, reconnecting, disconnecting, and using connection pooling. This is crucial for robust applications, especially those with potential network interruptions or long run times. ```ruby connection = ActiveRecord::Base.connection # Check connection status begin connection.execute("SELECT 1") puts "Connection is active" rescue => e puts "Connection failed: #{e.message}" # Reconnect connection.reconnect puts "Reconnected successfully" end # Manual connection management connection.disconnect! puts "Disconnected from database" connection.reconnect! puts "Reconnected to database" # Connection pooling ActiveRecord::Base.connection_pool.with_connection do |conn| result = conn.execute("SELECT COUNT(*) as count FROM products") puts "Product count: #{result.first['count']}" end # Clear all connections (useful in multi-threaded apps) ActiveRecord::Base.clear_active_connections! ActiveRecord::Base.clear_all_connections! # Verify connection is working if ActiveRecord::Base.connected? puts "Database connection is active" else puts "No active database connection" end ``` -------------------------------- ### Configure Rails Database Connection Source: https://github.com/tursodatabase/libsql-activerecord/blob/main/README.md This YAML configuration snippet sets up the database connection for a Ruby on Rails application using libSQL ActiveRecord. It defines connection parameters such as the adapter, connection pool size, database URL, authentication token, and a local path for embedded replicas. ```yaml default: &default adapter: libsql pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> development: <<: *default url: <%= ENV['TURSO_DATABASE_URL'] %> auth_token: <%= ENV['TURSO_AUTH_TOKEN'] %> path: "path/to/local/replica.db" ``` -------------------------------- ### Eager Loading with ActiveRecord for Performance Source: https://context7.com/tursodatabase/libsql-activerecord/llms.txt Illustrates using ActiveRecord's `includes` method for eager loading to prevent N+1 query problems. This fetches associated records in advance, improving performance when accessing related data. ```ruby # Eager loading to avoid N+1 queries posts_with_users = Post.includes(:user, :comments).all posts_with_users.each do |post| puts "#{post.title} by #{post.user.name} (#{post.comments.count} comments)" ``` -------------------------------- ### Schema Introspection with ActiveRecord in Ruby Source: https://context7.com/tursodatabase/libsql-activerecord/llms.txt Provides methods for inspecting database metadata such as tables, columns, primary keys, and indexes. This is useful for understanding the database structure and is used internally by ActiveRecord. ```ruby connection = ActiveRecord::Base.connection # List all tables tables = connection.tables puts "Tables: #{tables.join(', ')}" # Get column definitions columns = connection.columns('products') columns.each do |col| puts "#{col.name}: #{col.type} (#{col.sql_type})" puts " Default: #{col.default}" if col.default puts " Nullable: #{col.null}" puts " Primary Key: #{col.is_primary}" if col.respond_to?(:is_primary) end # Get primary keys primary_keys = connection.primary_keys('products') puts "Primary keys: #{primary_keys.join(', ')}" # Get indexes indexes = connection.indexes('products') indexes.each do |idx| puts "Index: #{idx.name}" puts " Columns: #{idx.columns.join(', ')}" puts " Unique: #{idx.unique}" puts " Where: #{idx.where}" if idx.where end # Check if table exists if connection.table_exists?('products') puts "Products table exists" end # Get native database types types = connection.native_database_types types.each do |name, definition| puts "#{name}: #{definition}" end ``` -------------------------------- ### Check Table Existence with ActiveRecord Source: https://context7.com/tursodatabase/libsql-activerecord/llms.txt This snippet demonstrates how to check if a specific table exists in the database using ActiveRecord's connection methods. It's a common utility for conditional database operations. ```ruby if ActiveRecord::Base.connection.table_exists?('products') puts "Products table created successfully" end ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.