Skip to content

Instantly share code, notes, and snippets.

@rpromyshlennikov
Last active September 25, 2019 11:23
Show Gist options
  • Save rpromyshlennikov/906e08b18c0f3f94e3e355c879cadc63 to your computer and use it in GitHub Desktop.
Save rpromyshlennikov/906e08b18c0f3f94e3e355c879cadc63 to your computer and use it in GitHub Desktop.
Generate Golang struct (model) from Postgres tables
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 ('information_schema', 'public')
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
@rpromyshlennikov
Copy link
Author

psql -h localhost -p 5432 -U postgres --password "DB" < go_struct_from_tables.sql > models.go

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