class AddIndexesToPosts < ActiveRecord::Migration[6.1]
def change
add_index :posts, :author_id
add_index :posts, :published_at
add_index :posts, [:author_id, :published_at]
add_index :posts, :created_at, order: { created_at: :desc }
from django.db import transaction
from django.http import JsonResponse
@transaction.atomic
def transfer_funds(request):
-- Import CSV with COPY (fastest method)
COPY users (username, email, age, created_at)
FROM '/path/to/users.csv'
WITH (
FORMAT csv,
HEADER true,
class TransferFundsService
def initialize(from_account:, to_account:, amount:)
@from_account = from_account
@to_account = to_account
@amount = amount
end
# Find products with specific spec value
products = Product.objects.filter(specs__weight__gte=100)
# Check if JSON key exists
products = Product.objects.filter(specs__has_key='color')
class AddConstraintsToUsers < ActiveRecord::Migration[6.1]
def change
# Null constraints
change_column_null :users, :email, false
change_column_null :users, :username, false
from products.models import Product
def import_products_bulk(product_data):
"""Import thousands of products efficiently."""
products = [
package com.example.demo.service;
import com.example.demo.model.Order;
import com.example.demo.model.OrderItem;
import com.example.demo.model.User;
import com.example.demo.repository.OrderRepository;
class AddStatusToPosts < ActiveRecord::Migration[6.1]
# Use change for automatic rollback
def change
# Add column without default to avoid table lock
add_column :posts, :status, :string
production:
primary:
adapter: postgresql
url: <%= ENV['DATABASE_URL'] %>
pool: <%= ENV.fetch("RAILS_MAX_THREADS", 5) %>
primary_replica:
module StatementTimeout
extend ActiveSupport::Concern
class TimeoutExceeded < StandardError; end
def with_statement_timeout(milliseconds)
from django.db import migrations
def populate_slugs(apps, schema_editor):
"""Generate slugs for existing posts."""
Post = apps.get_model('blog', 'Post')