Skip to content

Instantly share code, notes, and snippets.

@m-wild
Created October 4, 2023 10:16
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 m-wild/017a62d926575380c8ea50b880c69522 to your computer and use it in GitHub Desktop.
Save m-wild/017a62d926575380c8ea50b880c69522 to your computer and use it in GitHub Desktop.
Jetbrains Rider/DataGrip C# POCO extractor
/*
* Available context bindings:
* COLUMNS List<DataColumn>
* ROWS Iterable<DataRow>
* OUT { append() }
* FORMATTER { format(row, col); formatValue(Object, col); getTypeName(Object, col); isStringLiteral(Object, col); }
* TRANSPOSED Boolean
* plus ALL_COLUMNS, TABLE, DIALECT
*
* where:
* DataRow { rowNumber(); first(); last(); data(): List<Object>; value(column): Object }
* DataColumn { columnNumber(), name() }
*/
NEWLINE = System.getProperty("line.separator")
TYPE_MAPPING = [
(~/(?i)^bit$/) : "bool",
(~/(?i)^tinyint$/) : "byte",
(~/(?i)^uniqueidentifier|uuid$/) : "Guid",
(~/(?i)^int|integer|number$/) : "int",
(~/(?i)^bigint$/) : "long",
(~/(?i)^varbinary|image$/) : "byte[]",
(~/(?i)^double|float|real$/) : "double",
(~/(?i)^decimal|money|numeric|smallmoney$/) : "decimal",
(~/(?i)^datetimeoffset$/) : "DateTimeOffset",
(~/(?i)^datetime|datetime2|timestamp|date|time$/) : "DateTime",
(~/(?i)^char$/) : "char",
]
def className = TABLE != null ? TABLE.getName() : "MyClass"
OUT.append("public class ${className}").append(NEWLINE)
.append("{").append(NEWLINE)
COLUMNS.each { column ->
def dbType = FORMATTER.getTypeName(null, column)
def clrType = TYPE_MAPPING.find { p, t -> p.matcher(dbType).find() }?.value ?: "string"
def name = column.name()
OUT.append(" public ${clrType} ${name} { get; set; }")
.append(NEWLINE)
}
OUT.append("}").append(NEWLINE)
@m-wild
Copy link
Author

m-wild commented Oct 4, 2023

Creates a C# class definition for the type of the query results.
Only uses the column types & names, not any of the values.

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