Last active
November 26, 2019 08:35
-
-
Save kyrylomyr/1bb5e5858f8e15fd4afa6c5cf9e76348 to your computer and use it in GitHub Desktop.
PostgreSQL to C# POCO
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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