Skip to content

Instantly share code, notes, and snippets.

@kyrylomyr
Last active November 26, 2019 08: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 kyrylomyr/1bb5e5858f8e15fd4afa6c5cf9e76348 to your computer and use it in GitHub Desktop.
Save kyrylomyr/1bb5e5858f8e15fd4afa6c5cf9e76348 to your computer and use it in GitHub Desktop.
PostgreSQL to C# POCO
void Main()
{
// 1. Generate CREATE TABLE command for the existing table.
// 2. Select only text with the columns definitions and copy to the Clipboard.
// 3. Run the code below. C# properties will be in the Clipboard.
var sql = Clipboard.GetText();
var exclusions = new[] { "primary key", "constraint .*", "unique" };
var typeMapping = new Dictionary<string, string>
{
{ "integer", "int" },
{ "integer?", "int?" },
{ "varchar", "string" },
{ "varchar?", "string" },
{ "boolean", "bool" },
{ "boolean?", "bool?" },
{ "timestamp", "DateTime" },
{ "timestamp?", "DateTime?" },
{ "date", "DateTime" },
{ "date?", "DateTime?" }
};
string toProperty(Match columnMatch)
{
var name = columnMatch.Groups["name"].Value;
var sqlType = columnMatch.Groups["type"].Value;
var isNullable = !columnMatch.Groups["not_null"].Success;
var type = typeMapping[sqlType + (isNullable ? "?" : "")];
return $"public {type} {name} {{ get; set; }}";
}
var poco = Regex.Matches(sql, @"(?<name>\w+) (?<type>\w+)\(?\d*\)?\s?(?<not_null>not null)?")
.Cast<Match>()
.Where(m => exclusions.All(e => !Regex.IsMatch(m.Value, e)))
.Select(m => toProperty(m));
var cs = string.Join("\r\n\r\n", poco);
Clipboard.SetText(cs);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment