如何理解返回类型?

huangapple go评论76阅读模式
英文:

How to understand the return type?

问题

我正在构建一个用于 Rust 的 rust-postgres 框架。

我需要知道从 row.try_get 返回的值类型将是什么,以便将该值存储在适当类型的变量中。

我可以从 row.columns()[index].type 获取 SQL 类型,但无法确定该值是否可为空,因此我无法决定将值放入正常类型还是 Option<T>

我只能使用行的内容来理解它,无法像“从 PostgreSQL 获取表结构”这样的操作。

有没有办法?

英文:

I'm building a framework for rust-postgres.

I need to know what value type will be returned from a row.try_get, to get the value in a variable of the appropriate type.

I can get the sql type from row.columns()[index].type, but not if the value is nullable , so i can't decide to put the value in a normal type or a Option&lt;T&gt;.

I can use just the content of the row to understand it, i can't do things like "get the table structure from Postgresql".

is there a way?

答案1

得分: 1

Column类型不提供任何方法来确定结果列是否可为空的原因是因为数据库不返回此信息。

请记住,结果列是从运行查询派生出来的,而查询可能包含任意表达式。如果查询只是从表中选择列的简单SELECT,那么确定列是否可为空将相对简单。

但它也可能是一个非常复杂的表达式,由多个列、子选择或甚至自定义函数派生而来。Postgres可以确定每个列的数据类型,但在一般情况下,它不知道结果列是否可能包含空值。

如果您的应用程序只执行简单的查询,并且您知道每个结果列来自哪个表列,那么您可以这样找出该表列是否可为空:

SELECT is_nullable 
FROM information_schema.columns 
WHERE table_schema='myschema' 
  AND table_name='mytable' 
  AND column_name='mycolumn';

如果您的查询不那么简单,那么我建议您始终将结果作为Option&lt;T&gt;获取,并处理结果可能为None的情况。

英文:

The reason that the Column type does not expose any way to find out if a result column is nullable is because the database does not return this information.

Remember that result columns are derived from running a query, and that query may contain arbitrary expressions. If the query was a simple SELECT of columns from a table, then it would be reasonably simple to determine if a column could be nullable.

But it could also be a very complex expression, derived from multiple columns, subselects or even custom functions. Postgres can figure out the data type of each column, but in the general case it doesn't know if a result column may contain nulls.

If your application is only performing simple queries, and you know which table column each result column comes from, then you can find out if that table column is nullable like this:

SELECT is_nullable 
FROM information_schema.columns 
WHERE table_schema=&#39;myschema&#39; 
  AND table_name=&#39;mytable&#39; 
  AND column_name=&#39;mycolumn&#39;;

If your queries are not that simple then I recommend you always get the result as an Option&lt;T&gt; and handle the possibility that the result might be None.

huangapple
  • 本文由 发表于 2023年2月16日 06:19:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/75465959.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定