postgresql_view.sql 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. create view list_column as
  2. SELECT c.relname AS table_name,
  3. a.attname AS column_name,
  4. d.description AS column_comment,
  5. CASE
  6. WHEN a.attnotnull AND con.conname IS NULL THEN 1
  7. ELSE 0
  8. END AS is_required,
  9. CASE
  10. WHEN con.conname IS NOT NULL THEN 1
  11. ELSE 0
  12. END AS is_pk,
  13. a.attnum AS sort,
  14. CASE
  15. WHEN "position"(pg_get_expr(ad.adbin, ad.adrelid), ((c.relname::text || '_'::text) || a.attname
  16. ::text) || '_seq'::text) > 0 THEN 1
  17. ELSE 0
  18. END AS is_increment,
  19. btrim(
  20. CASE
  21. WHEN t.typelem <> 0::oid AND t.typlen = '-1'::integer THEN 'ARRAY'::text
  22. ELSE
  23. CASE
  24. WHEN t.typtype = 'd'::"char" THEN format_type(t.typbasetype, NULL::integer)
  25. ELSE format_type(a.atttypid, NULL::integer)
  26. END
  27. END, '"'::text) AS column_type
  28. FROM pg_attribute a
  29. JOIN (pg_class c
  30. JOIN pg_namespace n ON c.relnamespace = n.oid) ON a.attrelid = c.oid
  31. LEFT JOIN pg_description d ON d.objoid = c.oid AND a.attnum = d.objsubid
  32. LEFT JOIN pg_constraint con ON con.conrelid = c.oid AND (a.attnum = ANY (con.conkey))
  33. LEFT JOIN pg_attrdef ad ON a.attrelid = ad.adrelid AND a.attnum = ad.adnum
  34. LEFT JOIN pg_type t ON a.atttypid = t.oid
  35. WHERE (c.relkind = ANY (ARRAY['r'::"char", 'p'::"char"]))
  36. AND a.attnum > 0
  37. AND n.nspname = 'public'::name
  38. ORDER BY c.relname, a.attnum;
  39. create view list_table as
  40. SELECT c.relname AS table_name,
  41. obj_description(c.oid) AS table_comment,
  42. CURRENT_TIMESTAMP AS create_time,
  43. CURRENT_TIMESTAMP AS update_time
  44. FROM pg_class c
  45. LEFT JOIN pg_namespace n ON n.oid = c.relnamespace
  46. WHERE (c.relkind = ANY (ARRAY['r'::"char", 'p'::"char"]))
  47. AND c.relname !~~ 'spatial_%'::text AND n.nspname = 'public'::name AND n.nspname <> ''::name;
  48. CREATE OR REPLACE FUNCTION substring_index(varchar, varchar, integer)
  49. RETURNS varchar AS $$
  50. DECLARE
  51. tokens varchar[];
  52. length integer ;
  53. indexnum integer;
  54. BEGIN
  55. tokens := pg_catalog.string_to_array($1, $2);
  56. length := pg_catalog.array_upper(tokens, 1);
  57. indexnum := length - ($3 * -1) + 1;
  58. IF $3 >= 0 THEN
  59. RETURN pg_catalog.array_to_string(tokens[1:$3], $2);
  60. ELSE
  61. RETURN pg_catalog.array_to_string(tokens[indexnum:length], $2);
  62. END IF;
  63. END;
  64. $$ IMMUTABLE STRICT LANGUAGE PLPGSQL;