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.



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

def clear_context!
  Context.clear!
end

.current_schemaObject



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

def current_schema
  SchemaManager.current_schema
end

.current_shardObject


Thread-local (stateful)




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

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
43
# 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
    inner_run = run
    run = -> {SchemaManager.with_schema(schema, &inner_run)}
  end

  # 2. Shard (outermost — switches the connection first)
  if shard
    inner_run = run
    run = -> {ShardManager.with_shard(shard, &inner_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.



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

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.



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

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