I’m working on code that will scan a db table for column names, and then build a SQL statement to create table based upon a subset of columns. The end statement can be quite huge (60 cols in some instances).
Here’s a small snippet:
case ["VARCHAR", "CHAR"]:
clause = "${row.name} ${row.colType.trim()}(${row.length})"
break
My question is when I should force interpolation of the GString. Currently I wait until I build the entire statement, then call .toString() at the very end. Would it make any difference if I called .toString() at this level instead?
More code:
//CONTEXT
def rs = inputs.connection.sqlConnection.eachRow(tableNamesSql){ row ->
clause = buildSqlClause(row)
columnNames.append(clause).append(',\n')
}
def formatted = columnNames.toString().replaceAll(",\$", "")
def sql = """CREATE TABLE ${inputs.outputSchemaName}.${inputs.outputTableName}_${inputs.cycle} (
${formatted}
) IN TBTS_${inputs.outputSchemaName}"""
And the code that analyzes the row:
def buildSqlClause(row){
def clause
switch(row.colType.trim()){
case "INTEGER":
clause = "${row.name} ${row.colType.trim()}"
break
case "DECIMAL":
clause = "${row.name} ${row.colType.trim()}(${row.length}, ${row.scale})"
break
case ["VARCHAR", "CHAR"]:
clause = "${row.name} ${row.colType.trim()}(${row.length})"
break
case "TIMESTMP":
clause = "${row.name} TIMESTAMP"
break
case "DATE":
clause = "${row.name} ${row.colType.trim()}"
break
default: throw new Exception("Invalid SQL data type: [${row.colType}]")
}
def nullVal = row.nulls
if(nullVal.equalsIgnoreCase("N")){
clause = "${clause} NOT NULL"
}
return clause
}
So in other words, in the case of a db column “foo” I need the sql clause to read
FOO VARCHAR(INT).
Do you need to call toString() at all?
Also, you might get better results
collecting aListof field definition string (as you are doing), then calljointo stitch them all together?