Generate POCOs.groovy – generate C# POCOs from table structure using JetBrains DataGrip

Use the Scripted Extensions menu available when right-clicking on a table in JetBrains DataGrip to run this script. It will then generate POCOs using the table structure. Save aa Generate POCOs.groovy.

import com.intellij.database.model.DasTable
import com.intellij.database.model.ObjectKind
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil

/*
 * Available context bindings:
 *   SELECTION   Iterable<DasObject>
 *   PROJECT     project
 *   FILES       files helper
 */

packageName = "com.sample // TODO: change me!"
typeMapping = [
  (~/(?i)bit/)                          : "bool",
  (~/(?i)tinyint/)                      : "byte",
  (~/(?i)uniqueidentifier|uuid/)        : "Guid",
  (~/(?i)int|integer/)                  : "int",
  (~/(?i)bigint/)                       : "long",
  (~/(?i)char/)                         : "string",
  (~/(?i)varbinary|image/)              : "byte[]",
  (~/(?i)double|float|real/)            : "double",
  (~/(?i)decimal|money|numeric|smallmoney/)       : "decimal",
  (~/(?i)datetime|datetime2|timestamp|date|time/) : "DateTime",
  (~/(?i)datetimeoffset/)                         : "DateTimeOffset",
  (~/(?i)/)                                       : "String"
]

FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->
  SELECTION.filter { it instanceof DasTable && it.getKind() == ObjectKind.TABLE }.each { generate(it, dir) }
}

def generate(table, dir) {
  def className = csName(table.getName())
  def fields = calcFields(table)
  new File(dir, className + ".cs").withPrintWriter { out -> generate(out, className, fields) }
}

def generate(out, className, fields) {
  out.println "using System;"
  out.println ""
  out.println "namespace $packageName"
  out.println "{"
  out.println "\tpublic class $className"
  out.println "\t{"
  fields.each() {
    out.println "\t\tpublic ${it.type} ${it.name.capitalize()} { get; set; }"
  }
  out.println "\t}"
  out.println "}"
}

def calcFields(table) {
  DasUtil.getColumns(table).reduce([]) { fields, col ->
    def spec = Case.LOWER.apply(col.getDataType().getSpecification())
    def typeStr = typeMapping.find { p, t -> p.matcher(spec).find() }.value
    fields += [[
                 name : csName(col.getName()),
                 type : typeStr,
                 annos: ""]]
  }
}

def csName(str) {
  str.replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")
}
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *