gpt4 book ai didi

groovy - 如何将 XML 文件中的条目视为 GString 并让 groovy 仍然是 'evaluate' 呢?

转载 作者:行者123 更新时间:2023-12-01 15:03:37 28 4
gpt4 key购买 nike

下面的第一个示例说明了工作代码。我想进一步处理工作代码并将 SQL 存储在 XML 文件中。但是,一旦我从 XML 文件中读取它,我似乎就无法再正常地将 SQL 语句视为 GString 了。

这是工作示例:

private void testRefCursors(){

//object owner paramter
String owner = 'HR';

//Block of Oracle SQL to execute, returning 4 parameters
def sqlBlock =
"""
declare
type crsr is ref cursor;
tables crsr;
objects crsr;
begin
select count(*) into ${Sql.INTEGER} from all_tables where owner= ${owner} ;
open tables for select * from all_tables where owner= ${owner} ;
${Sql.resultSet OracleTypes.CURSOR} := tables;
select count(*) into ${Sql.INTEGER} from all_objects where owner= ${owner} ;
open objects for select * from all_objects where owner= ${owner};
${Sql.resultSet OracleTypes.CURSOR} := objects;
end;
"""

//note the order below, is the order of the 'types'
//in the SQL block used in the closure as parameters.
sqlSEDREF.call(sqlBlock){
t,user_tables,o,user_objects ->
println "found ${t} tables from a total of ${o} objects"
user_tables.eachRow(){x ->println "table:${x.table_name}"}
user_objects.eachRow(){println "object:${it.object_name}"}
}
}

现在,当我更改示例以从 XML 文件读取 SQL block 时;我不知道如何(或者是否可能)将该值视为 GString:

private void testRefCursors(){

//object owner paramter
String owner = 'HR';
def configFile = new File("config.xml");
config = new XmlSlurper().parse(configFile);
// FAILURE HERE -
GString sqlBlock = config.'sql-test-cursors'


//note the order below, is the order of the 'types'
//in the SQL block used in the closure as parameters.
sqlSEDREF.call(sqlBlock){
t,user_tables,o,user_objects ->
println "found ${t} tables from a total of ${o} objects"
user_tables.eachRow(){x ->println "table:${x.table_name}"}
user_objects.eachRow(){println "object:${it.object_name}"}
}
}

返回的错误是无法使用 SQL.call(GSTring, Closure) 的 GString 实现的结果:

Caught: groovy.lang.MissingMethodException: No signature of method:groovy.sql.Sql.call() is applicable for argument types: (java.lang.String,tools.UAT$_testRefCursors_closure2)

我目前的解决方法可能是从拥有 config.xml 文件切换到拥有 CONFIG.groovy 文件,并从 .groovy 文件而不是 XML 中读取 GString。非常感谢任何建议。

最佳答案

XML 文件不会返回 GString,因为 GString 是由 groovy 编译器在编译时构造的。当您解析 XML 文件时,您会得到一个字符串,而不是编译后的 Groovy 可执行文件。

如果您真的想在 XML 文档中嵌入 groovy 代码(这正是您在这里真正想要做的),那么您应该先看看这个:Embedding Groovy .基本上,您会读入 SQL 并将其视为嵌入式 groovy 脚本。

另一种方法(我在遇到类似问题时采用的一种方法)是使用 MessageFormat 来替换 XML 中的值。

def s = '<sql><query-name>Some SQL</query-name>
<query>
select * from {0}
</query>
</sql>'

然后在 xml 上使用 XmlSlurper 之后,您可以像这样替换 XML 中的值:

assert java.text.MessageFormat (xml.sql.query.text()).format ('dual') 
== 'select * from dual'

关于groovy - 如何将 XML 文件中的条目视为 GString 并让 groovy 仍然是 'evaluate' 呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/655838/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com