Module: Simple::SQL::Reflection

Extended by:
Forwardable, Reflection
Included in:
Reflection
Defined in:
lib/simple/sql/reflection.rb

Constant Summary collapse

TIMESTAMP_COLUMN_NAMES =
%w(inserted_at created_at updated_at)

Instance Method Summary collapse

Instance Method Details

#column_info(table_name) ⇒ Object



56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/simple/sql/reflection.rb', line 56

def column_info(table_name)
  schema, table_name = parse_table_name(table_name)
  recs = all <<~SQL, schema, table_name, into: Hash
    SELECT
      column_name AS name,
      *
    FROM information_schema.columns
    WHERE table_schema=$1 AND table_name=$2
  SQL

  records_by_attr(recs, :column_name)
end

#columns(table_name) ⇒ Object



37
38
39
# File 'lib/simple/sql/reflection.rb', line 37

def columns(table_name)
  column_info(table_name).keys
end

#primary_key_columns(table_name) ⇒ Object



15
16
17
18
19
20
21
22
23
# File 'lib/simple/sql/reflection.rb', line 15

def primary_key_columns(table_name)
  all <<~SQL, table_name
    SELECT pg_attribute.attname
    FROM   pg_index
    JOIN   pg_attribute ON pg_attribute.attrelid = pg_index.indrelid AND pg_attribute.attnum = ANY(pg_index.indkey)
    WHERE  pg_index.indrelid = $1::regclass
    AND    pg_index.indisprimary;
  SQL
end

#table_info(schema: "public") ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/simple/sql/reflection.rb', line 41

def table_info(schema: "public")
  columns = if schema == "public"
              "table_name AS name, *"
            else
              "table_schema || '.' || table_name AS name, *"
            end

  recs = all <<~SQL, schema, into: Hash
    SELECT #{columns}
    FROM information_schema.tables
    WHERE table_schema=$1
    SQL
  records_by_attr(recs, :name)
end

#tables(schema: "public") ⇒ Object



11
12
13
# File 'lib/simple/sql/reflection.rb', line 11

def tables(schema: "public")
  table_info(schema: schema).keys
end

#timestamp_columns(table_name) ⇒ Object

timestamp_columns are columns that will be set automatically after inserting or updating a record. This includes:

  • inserted_at (for Ecto)
  • created_at (for ActiveRecord)
  • updated_at (for Ecto and ActiveRecord)


33
34
35
# File 'lib/simple/sql/reflection.rb', line 33

def timestamp_columns(table_name)
  columns(table_name) & TIMESTAMP_COLUMN_NAMES
end