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



48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/simple/sql/reflection.rb', line 48

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

#columns(table_name) ⇒ Object



35
36
37
# File 'lib/simple/sql/reflection.rb', line 35

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

#primary_key_columns(table_name) ⇒ Object



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

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

#table_info(schema: "public") ⇒ Object



39
40
41
42
43
44
45
46
# File 'lib/simple/sql/reflection.rb', line 39

def table_info(schema: "public")
  recs = all "    SELECT table_schema || '.' || table_name AS name, *\n    FROM information_schema.tables\n    WHERE table_schema=$1\n    SQL\n  records_by_attr(recs, :name)\nend\n", schema, into: Hash

#tables(schema: "public") ⇒ Object



9
10
11
# File 'lib/simple/sql/reflection.rb', line 9

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)



31
32
33
# File 'lib/simple/sql/reflection.rb', line 31

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