Skip to content

Instantly share code, notes, and snippets.

@mem
Last active July 19, 2021 16:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mem/30eb040a652ef6b77dcaa809960c93ca to your computer and use it in GitHub Desktop.
Save mem/30eb040a652ef6b77dcaa809960c93ca to your computer and use it in GitHub Desktop.
-- http://sylnsr.blogspot.com/2015/08/generate-golang-struct-model-from.html
WITH models AS (
WITH data AS (
SELECT
replace(initcap(table_name::text), '_', '') table_name,
replace(initcap(column_name::text), '_', '') column_name,
CASE data_type
WHEN 'timestamp without time zone' THEN 'time.Time'
WHEN 'timestamp with time zone' THEN 'time.Time'
WHEN 'boolean' THEN 'bool'
-- add your own type converters as needed or it will default to 'string'
ELSE 'string'
END AS type_info,
'`json:"' || column_name ||'"`' AS annotation
FROM information_schema.columns
WHERE table_schema IN ('dvs_app', 'dvs_system')
ORDER BY table_schema, table_name, ordinal_position
)
SELECT table_name, STRING_AGG(E'\t' || column_name || E'\t' || type_info || E'\t' || annotation, E'\n') fields
FROM data
GROUP BY table_name
)
SELECT 'type ' || table_name || E' struct {\n' || fields || E'\n}' models
FROM models ORDER BY 1
@sylnsr
Copy link

sylnsr commented Jul 19, 2021

Moved post here: https://www.mikemugge.org/posts/golang-struct-from-pg-table/ ... and I would be glad to make some adaptations if its not robust enough. Just tell me what you need.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment