使用sql_query的get_results不返回插入行的数组,Postgres 15,Rust 1.70.0,Diesel 2.0。

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

get_results using sql_query not returning array of inserted rows , Postgres 15, Rust 1.70.0 , Diesel 2.0

问题

以下是您提供的代码的翻译:

能够将行添加到表中,但sql_query(query).get_results不返回行数组 即使数据已插入,我仍然得到一个空数组。

当使用Select语句与get_results一起使用时,将返回一个值数组。

不确定我做错了什么。 请建议。

结构体Asset具有#[derive(QueryableByName)]
谢谢。

#[test]
fn test_get_result(){
     use crate::service_tests::prelude::connection_without_transaction;
     use diesel::sql_query;
     use diesel::RunQueryDsl;

     use crate::models::asset::Asset;

     let mut connection = connection_without_transaction();

     let query = "Select * from assets";
     let result1 = diesel::sql_query(query)
                            .get_results::<Asset>(&mut connection)
                            .unwrap();
    dbg!(result1.len());

    let query = "insert into assets (
        parent_assetcode,category_code,label_code,
        erp_code,name,description,is_depreciable,
        physical_id,machine_tag_no,in_store,
        quantity,is_multiple_entries,group_qty,
        acquired_value,acquired_date,date_put_to_use,
        physical_verification,asset_type,asset_user,
        cost_center_code,department_code,branch_code,
        location_code,physical_location_code,requires_maintenance,
        created_user_id,remarks
        )
        values
        (
            'BL00000SP','BLD','L-BLD-2','BL00000SP',
            'name of asset','descr',false,'aaaa',
            'mactag',true,1200,false,10,13250.0,
            '2023-05-01','2023-05-02',true,'Owned',
            1,'162','NA','MA003','276 VMART PATNA KURJI',
            'NA',false,1,'remarksss'
        )";
     let result2 = diesel::sql_query(query)
                        .get_results::<Asset>(&mut connection)
                        .unwrap();
     dbg!(result2.len());

}

输出如下:

运行1个测试
[src/service_tests/csv_import_test.rs:53] result1.len() = 44
[src/service_tests/csv_import_test.rs:78] result2.len() = 0
测试service_tests::csv_import_test::test_get_result ... ok

请注意,我已将代码中的HTML实体引号(")转换为正常的双引号(")以使其有效。

英文:

Able to add rows into the table but sql_query(query).get_results does not return array of rows. i.e. I am getting a null array though data gets inserted.

When get_results is used with Select statement an array of values is returned.

Not sure what I am doing wrong. Please advise.

The struct Asset has #[derive(QueryableByName)].
Thank you.

#[test]
fn test_get_result(){
     use crate::service_tests::prelude::connection_without_transaction;
     use diesel::sql_query;
     use diesel::RunQueryDsl;

     use crate::models::asset::Asset;

     let mut connection = connection_without_transaction();

     let query = &quot;Select * from assets&quot;;
     let result1 = diesel::sql_query(query)
                            .get_results::&lt;Asset&gt;(&amp;mut connection)
                            .unwrap();
    dbg!(result1.len());

    let query = &quot;insert into assets (
        parent_assetcode,category_code,label_code,
        erp_code,name,description,is_depreciable,
        physical_id,machine_tag_no,in_store,
        quantity,is_multiple_entries,group_qty,
        acquired_value,acquired_date,date_put_to_use,
        physical_verification,asset_type,asset_user,
        cost_center_code,department_code,branch_code,
        location_code,physical_location_code,requires_maintenance,
        created_user_id,remarks
        )
        values
        (
            &#39;BL00000SP&#39;,&#39;BLD&#39;,&#39;L-BLD-2&#39;,&#39;BL00000SP&#39;,
            &#39;name of asset&#39;,&#39;descr&#39;,false,&#39;aaaa&#39;,
            &#39;mactag&#39;,true,1200,false,10,13250.0,
            &#39;2023-05-01&#39;,&#39;2023-05-02&#39;,true,&#39;Owned&#39;,
            1,&#39;162&#39;,&#39;NA&#39;,&#39;MA003&#39;,&#39;276 VMART PATNA KURJI&#39;,
            &#39;NA&#39;,false,1,&#39;remarksss&#39;
        )&quot;;
     let result2 = diesel::sql_query(query)
                        .get_results::&lt;Asset&gt;(&amp;mut connection)
                        .unwrap();
     dbg!(result2.len());

}

The output is below:

running 1 test
[src/service_tests/csv_import_test.rs:53] result1.len() = 44
[src/service_tests/csv_import_test.rs:78] result2.len() = 0
test service_tests::csv_import_test::test_get_result ... ok

答案1

得分: 1

以下是您提供的内容的翻译:

migrations - up.sql ->

/// 安装 Diesel 后,使用 diesel migration generate create table plans 来生成查询的表,
/// 然后运行 diesel setup 和 diesel migration run 来更新 schema.rs
create table plans(
    id serial not null,
    code varchar(20) not null,
    constraint pk_test_id primary key(id)
);

models\plan.rs ->

/// 在 models 目录下创建一个名为 plan.rs 的文件
// 添加以下代码 - 创建一个用于查询表 plans 中的值的结构体

use diesel::prelude::*;
use serde::{Deserialize, Serialize};

use crate::schema::plans;

#[derive(Debug, Clone, Identifiable, Insertable, AsChangeset, Queryable, QueryableByName, Deserialize, Serialize)]
#[diesel(table_name = plans)]
#[diesel(primary_key(code))]
pub struct Plan {
    pub id: i32,
    pub code: String
}

services_test_plan.rs ->

/// 在 services_test_plan.rs 中创建一个测试文件,包含以下代码
// 使用终端运行测试 >> cargo test test_get_result_plans
#[test]
fn test_get_result_plans(){
    use crate::service_tests::prelude::connection_without_transaction;
    use diesel::sql_query;
    use diesel::RunQueryDsl;

    use crate::models::test::Plan;
    use crate::schema::plans::code;
    use crate::schema::plans::id;

    let mut connection = connection_without_transaction();

    let query = "Select * from plans"; // 返回表 plans 中的现有行

    let result1: Result<Vec<Plan>, diesel::result::Error> = diesel::sql_query(query).get_results::<Plan>(&mut connection);
    
    dbg!(result1.unwrap());

    let query = "INSERT INTO plans (code) VALUES ('CC-1') RETURNING *"; // 向表 plans 中的列 'code' 插入数据
    let result2: Result<Vec<Plan>, diesel::result::Error> = diesel::sql_query(query).get_results::<Plan>(&mut connection);

    dbg!(result2.unwrap()); // result2 包含表 plans 中新创建的行。
}
英文:

migrations - up.sql ->

/// after installing diesel , using diesel migration generate create table plans to query,
/// then run diesel setup and diesel migration run to update schema.rs
create table plans(
    id serial not null,
    code varchar(20) not null,
    constraint pk_test_id primary key(id)
);

models\plan.rs ->

/// create a file - plan.rs under models directory plan.rs
// add the following code - creates a struct to query hold values from table plans

use diesel::prelude::*;
use serde::{Deserialize, Serialize};

use crate::schema::plans;

#[derive(Debug, Clone, Identifiable, Insertable, AsChangeset, Queryable,QueryableByName,Deserialize,Serialize)]
#[diesel(table_name = plans)]
#[diesel(primary_key(code))]
pub struct Plan {
    pub id: i32,
    pub code: String
}

services_test_plan.rs

/// create a test file - services_test_plan.rs with the following code
// run the test using from terminal &gt;&gt; cargo test test_get_result_plans
#[test]
fn test_get_result_plans(){
    use crate::service_tests::prelude::connection_without_transaction;
    use diesel::sql_query;
    use diesel::RunQueryDsl;

    use crate::models::test::Plan;
    use crate::schema::plans::code;
    use crate::schema::plans::id;

    let mut connection = connection_without_transaction();

    let query = &quot;Select * from plans&quot;; // returns existing rows in table plans

    let result1:Result&lt;Vec&lt;Plan&gt;, diesel::result::Error&gt; = diesel::sql_query(query).get_results::&lt;Plan&gt;(&amp;mut connection);
    
    dbg!(result1.unwrap());

    let query = &quot;INSERT INTO plans (code) VALUES (&#39;CC-1&#39;) RETURNING *&quot;; // insert data into plans table column &#39;code&#39; 
    let result2: Result&lt;Vec&lt;Plan&gt;, diesel::result::Error&gt; = diesel::sql_query(query).get_results::&lt;Plan&gt;(&amp;mut connection);

    dbg!(result2.unwrap()); // result2 contains newly created rows in table plans.

}

huangapple
  • 本文由 发表于 2023年7月3日 05:50:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76600930.html
匿名

发表评论

匿名网友

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

确定