Module: Ec::Pg::TenantContext

Defined in:
lib/ec/pg/tenant_context.rb

Defined Under Namespace

Classes: TenantNotSet

Class Method Summary collapse

Class Method Details

.clear_context!Object

Clears all multi-tenant context for the current thread.



67
68
69
# File 'lib/ec/pg/tenant_context.rb', line 67

def clear_context!
  Context.clear!
end

.current_schemaObject



62
63
64
# File 'lib/ec/pg/tenant_context.rb', line 62

def current_schema
  SchemaManager.current_schema
end

.current_shardObject


Thread-local (stateful)




58
59
60
# File 'lib/ec/pg/tenant_context.rb', line 58

def current_shard
  ShardManager.current_shard
end

.switch(shard: nil, schema: nil, &block) ⇒ Object

Executes block within the given tenant context.

Parameters:

  • shard (Symbol, nil) (defaults to: nil)

    shard to connect to (skipped when nil)

  • schema (String, nil) (defaults to: nil)

    Postgres schema to set (skipped when nil)



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/ec/pg/tenant_context.rb', line 19

def switch(shard: nil, schema: nil, &block)

  # Layer composition: innermost layer first so that the outermost wrapper
  # controls the connection that the inner layers receive.
  run = block

  # 1. Schema (innermost)
  if schema
    schema_run = run
    run = -> {SchemaManager.with_schema(schema, &schema_run)}
  end

  # 2. Shard (outermost — switches the connection first)
  if shard
    shard_run = run
    run = -> {ShardManager.with_shard(shard, &shard_run)}
  end

  if run.present?
    run.call
  else
    raise TenantNotSet, "No schema or shard specified"
  end
end

.with_schema(schema_name, &block) ⇒ Object

Convenience alias that shard and only switches schema.



45
46
47
# File 'lib/ec/pg/tenant_context.rb', line 45

def with_schema(schema_name, &block)
  SchemaManager.with_schema(schema_name, &block)
end

.with_shard(shard_name, role: :writing, &block) ⇒ Object

Convenience alias that skips schema and only switches shard.



50
51
52
# File 'lib/ec/pg/tenant_context.rb', line 50

def with_shard(shard_name, role: :writing, &block)
  ShardManager.with_shard(shard_name, role: role, &block)
end