当字段类型在编译时未知时,如何使用tokio-postgres枚举列? [英] How to enumerate over columns with tokio-postgres when the field types are unknown at compile-time?
问题描述
我想要一个将SQL查询结果转换为JSON的通用函数.我想手动构建JSON字符串(或使用外部库).为此,我需要能够动态枚举一行中的列.
I would like a generic function that converts the result of a SQL query to JSON. I would like to build a JSON string manually (or use an external library). For that to happen, I need to be able to enumerate the columns in a row dynamically.
let rows = client
.query("select * from ExampleTable;")
.await?;
// This is how you read a string if you know the first column is a string type.
let thisValue: &str = rows[0].get(0);
使用Rust可以实现动态类型 ,但不能使用tokio-postgres库API.
Dynamic types are possible with Rust, but not with the tokio-postgres library API.
tokio-postgres的row.get
函数旨在要求通用推断
The row.get
function of tokio-postgres is designed to require generic inference according to the source code
如果没有正确的API,如何枚举行和列?
Without the right API, how can I enumerate rows and columns?
推荐答案
您需要枚举行和列,这样做可以在枚举时获取列引用,并从中获取postgresql类型.利用类型信息,可以有条件逻辑选择两个不同的子函数:i)获取强类型变量;并且,ii)转换为JSON值.
You need to enumerate the rows and columns, doing so you can get the column reference while enumerating, and from that get the postgresql-type. With the type information it's possible to have conditional logic to choose different sub-functions to both: i) get the strongly typed variable; and, ii) convert to a JSON value.
for (rowIndex, row) in rows.iter().enumerate() {
for (colIndex, column) in row.columns().iter().enumerate() {
let colType: string = col.type_().to_string();
if colType == "int4" { //i32
let value: i32 = row.get(colIndex);
return value.to_string();
}
else if colType == "text" {
let value: &str = row.get(colIndex);
return value; //TODO: escape characters
}
//TODO: more type support
else {
//TODO: raise error
}
}
}
tokio-postgres代码维护者的奖金提示
理想情况下,tokio-postgres应该包含直接返回dyn any
类型的API. row.rs内部已经使用数据库列类型信息来确认所提供的泛型类型有效.理想情况下,新API的使用将通过改进的FromSQL API直接直接使用内部列信息,但存在更简单的中间立场:-
Ideally, tokio-postgres would include a direct API that returns a dyn any
type. The internals of row.rs already use the database column type information to confirm that the supplied generic type is valid. Ideally a new API uses would use the internal column information quite directly with improved FromSQL API, but a simpler middle-ground exists:-
row.rs中可能有一个额外的功能层,它使用此答案中使用的相同列类型条件逻辑来利用现有的get
函数.如果像我这样的用户需要处理这种条件逻辑,则当tokio-postgresql处理新类型时,我也需要维护此代码,因此,应在库中包含此类逻辑,这样可以更好地实现此功能.保持.
It would be possible for an extra function layer in row.rs that uses the same column type conditional logic used in this answer to then leverage the existing get
function. If a user such as myself needs to handle this kind of conditional logic, I also need to maintain this code when new types are handled by tokio-postgresql, therefore, this kind of logic should be included inside the library where such functionality can be better maintained.
这篇关于当字段类型在编译时未知时,如何使用tokio-postgres枚举列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!