postgres

sql
CREATE TABLE idempotency_keys (
    request_key         text        NOT NULL,
    endpoint            text        NOT NULL,
    request_fingerprint text        NOT NULL,
    status              text        NOT NULL DEFAULT 'in_progress'
                                    CHECK (status IN ('in_progress', 'completed')),

Idempotency keys for “create” endpoints

reliability postgres idempotency
by codesnips 3 tabs
ruby
module ConnectionHealth
  extend ActiveSupport::Concern

  def with_fresh_connection
    conn = ActiveRecord::Base.connection
    conn.verify! # pings and reconnects if the socket is dead

Keep DB Connections Healthy in Long Jobs

rails activerecord background-jobs
by codesnips 3 tabs
python
import csv


class _LineBuffer:
    def __init__(self):
        self._data = ""

Stream a Large CSV Export in Chunks from a Flask Endpoint

flask streaming csv
by codesnips 3 tabs
ruby
class Current < ActiveSupport::CurrentAttributes
  attribute :tenant, :request_id

  def tenant=(tenant)
    super
    Rails.logger.tagged("tenant=#{tenant&.id}") if tenant

Tenant Isolation in Rails with CurrentAttributes and an around_action

rails multi-tenancy current-attributes
by codesnips 4 tabs
ruby
class CreateAuditLogs < ActiveRecord::Migration[7.1]
  def change
    create_table :audit_logs do |t|
      t.references :auditable, polymorphic: true, null: false
      t.references :user, null: true, foreign_key: true
      t.string :action, null: false

Rails Audit Log for Model Changes Using ActiveRecord Callbacks

rails activerecord callbacks
by codesnips 4 tabs
go
package export

import (
	"encoding/csv"
	"log"
	"net/http"

Streaming Large CSV Exports in Go Without Buffering the Whole File

go http csv
by codesnips 3 tabs
ruby
class OverdueInvoicesQuery
  def initialize(relation: Invoice.all, as_of: Time.current)
    @relation = relation
    @as_of = as_of
  end

ActiveRecord::Relation as a Boundary (No Arrays)

rails activerecord query-objects
by codesnips 3 tabs
typescript
import { Pool } from "pg";

async function keyFor(pool: Pool, name: string): Promise<string> {
  const { rows } = await pool.query<{ key: string }>(
    "SELECT hashtextextended($1, 0) AS key",
    [name]

Postgres advisory lock for one-at-a-time work

postgres concurrency reliability
by codesnips 3 tabs
rust
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
use serde::{Deserialize, Serialize};
use time::OffsetDateTime;
use uuid::Uuid;

#[derive(Debug, Clone, Serialize, Deserialize)]

Cursor-Paginated Streaming REST Endpoint in Axum with Keyset Pagination

axum rust pagination
by codesnips 3 tabs
ruby
class Order < ApplicationRecord
  include TransactionalEnqueue

  belongs_to :customer
  has_many :line_items, dependent: :destroy

Transaction-Safe After-Commit Hook (Avoid Ghost Jobs)

rails activerecord background-jobs
by codesnips 4 tabs
ruby
class CreateAuditLogs < ActiveRecord::Migration[7.1]
  def change
    create_table :audit_logs do |t|
      t.references :auditable, polymorphic: true, null: false
      t.string :actor
      t.string :action, null: false

Audit Trail with JSON Diff (Minimal, Useful)

rails activerecord auditing
by codesnips 4 tabs
ruby
class CreateCustomerRevenueSummaries < ActiveRecord::Migration[7.0]
  def change
    create_view :customer_revenue_summaries, materialized: true, version: 1

    add_index :customer_revenue_summaries,
              :customer_id,

Database Views for Read Models

rails postgres performance
by codesnips 4 tabs