sql_wrapper/
pg_generator.rs

1use sqlx::{Connection, PgConnection};
2use crate::generator::{ColumnInfo, Generator};
3
4pub struct PgGenerator;
5
6impl Generator for PgGenerator {
7    async fn query_columns(&self, conn_url: &str, table_name: &str) -> Vec<ColumnInfo> {
8        let mut conn: PgConnection = PgConnection::connect(conn_url).await.unwrap();
9        let sql = format!("select * from information_schema.columns where table_name = '{table_name}' order by ordinal_position asc; ");
10        let columns: Vec<ColumnInfo> = sqlx::query_as(sql.as_str()).fetch_all(&mut conn).await.unwrap();
11        return columns;
12    }
13
14    fn get_mapping_type(&self, sql_type: &str) -> String {
15        let sql_type = sql_type.to_uppercase();
16        let ret = if sql_type == "BOOLEAN" {
17            "bool"
18        } else if sql_type == "CHARACTER" {
19            "String"
20        } else if sql_type == "SMALLINT" {
21            "i16"
22        } else if sql_type == "SMALLSERIAL" {
23            "i16"
24        } else if sql_type == "INT2" {
25            "i16"
26        } else if sql_type == "INT" {
27            "i32"
28        } else if sql_type == "SERIAL" {
29            "i32"
30        } else if sql_type == "INTEGER" {
31            "i32"
32        } else if sql_type == "INT4" {
33            "i32"
34        } else if sql_type == "BIGINT" {
35            "i64"
36        } else if sql_type == "BIGSERIAL" {
37            "i64"
38        } else if sql_type == "INT8" {
39            "i64"
40        } else if sql_type == "REAL" {
41            "f32"
42        } else if sql_type == "FLOAT4" {
43            "f32"
44        } else if sql_type == "DOUBLE PRECISION" {
45            "f64"
46        } else if sql_type == "FLOAT8" {
47            "f64"
48        } else if sql_type == "CHARACTER VARYING" {
49            "String"
50        } else if sql_type == "TEXT" {
51            "String"
52        } else if sql_type == "NAME" {
53            "String"
54        } else if sql_type == "CITEXT" {
55            "String"
56        } else if sql_type == "BYTEA" {
57            "Vec<u8>"
58        } else if sql_type == "VOID" {
59            "()"
60        } else if sql_type == "INTERVAL" {
61            "sqlx::postgres::types::PgInterval"
62        } else if sql_type == "NUMERIC" {
63            "sqlx::types::Decimal"
64        } else if sql_type == "TIMESTAMP WITH TIME ZONE" {
65            "chrono::DateTime<chrono::Utc>"
66        } else if sql_type == "TIMESTAMP WITHOUT TIME ZONE" {
67            "chrono::NaiveDateTime"
68        } else if sql_type == "DATE" {
69            "chrono::NaiveDate"
70        } else if sql_type == "TIME WITHOUT TIME ZONE" {
71            "chrono::NaiveTime"
72        } else if sql_type == "TIME WITH TIME ZONE" {
73            "sqlx::postgres::types::PgTimeTz"
74        } else if sql_type == "UUID" {
75            "uuid::Uuid"
76        } else if sql_type == "JSON" {
77            "serde_json::Value"
78        } else if sql_type == "JSONB" {
79            "serde_json::Value"
80        } else {
81            panic!("{}", format!("not support type:{}", sql_type))
82        };
83        ret.to_string()
84    }
85
86    fn gen_insert_returning_id_fn(&self, table_name: &str, column_infos: &Vec<ColumnInfo>) -> String {
87        let struct_name = self.gen_struct_name(table_name);
88        let ret = self.gen_field_and_value_str(column_infos, false);
89
90        let fn_str = format!(r#"
91pub async fn insert_returning_id(conn: &mut PgConnection, obj: {struct_name}) -> i64 {{
92    let mut sql = sql_builder::SqlBuilder::insert_into("{table_name}");
93{ret}
94    sql.returning_id();
95    let sql = sql.sql().unwrap();
96    let columns:(i64,) = sqlx::query_as(sql.as_str()).fetch_one(conn).await.unwrap();
97    return columns.0
98}}
99    "#);
100
101        return fn_str
102    }
103
104    fn gen_insert_fn(&self, table_name: &str, column_infos: &Vec<ColumnInfo>) -> String {
105        let struct_name = self.gen_struct_name(table_name);
106        let ret = self.gen_field_and_value_str(column_infos, true);
107
108        let fn_str = format!(r#"
109pub async fn insert(conn: &mut PgConnection, obj: {struct_name}) -> Result<sqlx::postgres::PgQueryResult, sqlx::Error>  {{
110    let mut sql = sql_builder::SqlBuilder::insert_into("{table_name}");
111{ret}
112    let sql = sql.sql().unwrap();
113    sqlx::query(sql.as_str()).execute(conn).await
114
115}}
116    "#);
117
118        return fn_str
119    }
120
121    fn gen_batch_insert_returning_id_fn(&self, table_name: &str, column_infos: &Vec<ColumnInfo>) -> String {
122        let struct_name = self.gen_struct_name(table_name);
123
124        let ret = self.gen_field_and_batch_values_str(column_infos, false);
125
126        let fn_str = format!(r#"
127
128pub async fn batch_insert_returning_id(conn: &mut PgConnection, objs: Vec<{struct_name}>) -> Vec<i64> {{
129    let mut sql = sql_builder::SqlBuilder::insert_into("{table_name}");
130{ret}
131
132    sql.returning_id();
133    let sql = sql.sql().unwrap();
134    let columns:Vec<(i64,)> = sqlx::query_as(sql.as_str()).fetch_all(conn).await.unwrap();
135    let mut ret = vec![];
136    for v in columns {{
137        ret.push(v.0)
138    }}
139    println!("insert id:{{:?}}", ret);
140    return ret;
141
142}}
143    "#);
144
145        fn_str
146    }
147
148    fn gen_batch_insert_fn(&self, table_name: &str, column_infos: &Vec<ColumnInfo>) -> String {
149        let struct_name = self.gen_struct_name(table_name);
150
151        let ret = self.gen_field_and_batch_values_str(column_infos, true);
152
153        let fn_str = format!(r#"
154
155pub async fn batch_insert(conn: &mut PgConnection, objs: Vec<{struct_name}>) -> Result<sqlx::postgres::PgQueryResult, sqlx::Error>  {{
156    let mut sql = sql_builder::SqlBuilder::insert_into("{table_name}");
157{ret}
158
159    let sql = sql.sql().unwrap();
160    sqlx::query(sql.as_str()).execute(conn).await
161
162}}
163    "#);
164
165        fn_str
166    }
167
168    fn gen_select_by_id_fn(&self, table_name: &str, column_infos: &Vec<ColumnInfo>) -> String {
169        let sql = self.gen_select_sql(table_name, column_infos);
170        let struct_name = self.gen_struct_name(table_name);
171        format!(r#"
172pub async fn select_by_id(conn: &mut PgConnection,id: i64) -> Result<{struct_name}, sqlx::Error> {{
173    let sql = format!("{sql} where id='{{}}'", id);
174    let result = sqlx::query_as(sql.as_str()).fetch_one(conn).await;
175    result
176}}
177
178        "#)
179    }
180
181    fn gen_delete_by_id_fn(&self, table_name: &str) -> String {
182        let sql = self.gen_delete_by_id_sql(table_name);
183        format!(r#"
184pub async fn delete_by_id(conn: &mut PgConnection,id: i64) -> Result<sqlx::postgres::PgQueryResult, sqlx::Error> {{
185    let sql = format!("{sql} '{{}}'", id);
186    sqlx::query(sql.as_str()).execute(conn).await
187}}
188        "#)
189    }
190}
191
192
193#[cfg(test)]
194mod test {
195    use std::time::SystemTime;
196    use chrono::{DateTime, FixedOffset, Utc};
197    use sqlx::{Connection, PgConnection};
198    use sqlx::postgres::types::{PgInterval, PgTimeTz};
199    use sqlx::types::Decimal;
200    use crate::field_to_string::FieldToString;
201    use crate::generator::Generator;
202    use crate::pg_generator::PgGenerator;
203    #[derive(sqlx::FromRow, Debug, PartialEq)]
204    pub struct TestTable {
205        id: i64,
206        b1: bool,
207        b2: Option<bool>,
208        c1: String,
209        c2: Option<String>,
210        i4: i32,
211        i41: Option<i32>,
212        r1: f32,
213        r2: Option<f64>,
214        d1: f64,
215        d2: Option<f64>,
216        t1: String,
217        t2: String,
218        t3: Option<String>,
219        t4: Option<String>,
220        byte1: Option<Vec<u8>>,
221        interval1: Option<sqlx::postgres::types::PgInterval>,
222        big1: Option<sqlx::types::Decimal>,
223        big2: Option<sqlx::types::Decimal>,
224        ts1: chrono::NaiveDateTime,
225        ts2: Option<chrono::DateTime<chrono::Utc>>,
226        date1: Option<chrono::NaiveDate>,
227        date2: Option<chrono::NaiveDate>,
228        time1: chrono::NaiveTime,
229        time2: Option<sqlx::postgres::types::PgTimeTz>,
230        uid1: uuid::Uuid,
231        json1: Option<serde_json::Value>,
232        json2: Option<serde_json::Value>,
233        i5: Option<i16>,
234    }
235
236
237
238    pub async fn insert_returning_id(conn: &mut PgConnection, obj: TestTable) -> i64 {
239        let mut sql = sql_builder::SqlBuilder::insert_into("test_table");
240        sql.field("b1");
241        sql.field("b2");
242        sql.field("c1");
243        sql.field("c2");
244        sql.field("i4");
245        sql.field("i41");
246        sql.field("r1");
247        sql.field("r2");
248        sql.field("d1");
249        sql.field("d2");
250        sql.field("t1");
251        sql.field("t2");
252        sql.field("t3");
253        sql.field("t4");
254        sql.field("byte1");
255        sql.field("interval1");
256        sql.field("big1");
257        sql.field("big2");
258        sql.field("ts1");
259        sql.field("ts2");
260        sql.field("date1");
261        sql.field("date2");
262        sql.field("time1");
263        sql.field("time2");
264        sql.field("uid1");
265        sql.field("json1");
266        sql.field("json2");
267        sql.field("i5");
268        sql.values(&[
269            sql_builder::quote(obj.b1.field_to_string()),
270            sql_builder::quote(obj.b2.unwrap().field_to_string()),
271            sql_builder::quote(obj.c1.field_to_string()),
272            sql_builder::quote(obj.c2.unwrap().field_to_string()),
273            sql_builder::quote(obj.i4.field_to_string()),
274            sql_builder::quote(obj.i41.unwrap().field_to_string()),
275            sql_builder::quote(obj.r1.field_to_string()),
276            sql_builder::quote(obj.r2.unwrap().field_to_string()),
277            sql_builder::quote(obj.d1.field_to_string()),
278            sql_builder::quote(obj.d2.unwrap().field_to_string()),
279            sql_builder::quote(obj.t1.field_to_string()),
280            sql_builder::quote(obj.t2.field_to_string()),
281            sql_builder::quote(obj.t3.unwrap().field_to_string()),
282            sql_builder::quote(obj.t4.unwrap().field_to_string()),
283            sql_builder::quote(obj.byte1.unwrap().field_to_string()),
284            sql_builder::quote(obj.interval1.unwrap().field_to_string()),
285            sql_builder::quote(obj.big1.unwrap().field_to_string()),
286            sql_builder::quote(obj.big2.unwrap().field_to_string()),
287            sql_builder::quote(obj.ts1.field_to_string()),
288            sql_builder::quote(obj.ts2.unwrap().field_to_string()),
289            sql_builder::quote(obj.date1.unwrap().field_to_string()),
290            sql_builder::quote(obj.date2.unwrap().field_to_string()),
291            sql_builder::quote(obj.time1.field_to_string()),
292            sql_builder::quote(obj.time2.unwrap().field_to_string()),
293            sql_builder::quote(obj.uid1.field_to_string()),
294            sql_builder::quote(obj.json1.unwrap().field_to_string()),
295            sql_builder::quote(obj.json2.unwrap().field_to_string()),
296            sql_builder::quote(obj.i5.unwrap().field_to_string())
297        ]);
298
299        sql.returning_id();
300        let sql = sql.sql().unwrap();
301        let columns:(i64,) = sqlx::query_as(sql.as_str()).fetch_one(conn).await.unwrap();
302        return columns.0
303    }
304
305    pub async fn insert(conn: &mut PgConnection, obj: TestTable) -> Result<sqlx::postgres::PgQueryResult, sqlx::Error>  {
306        let mut sql = sql_builder::SqlBuilder::insert_into("test_table");
307        sql.field("id");
308        sql.field("b1");
309        sql.field("b2");
310        sql.field("c1");
311        sql.field("c2");
312        sql.field("i4");
313        sql.field("i41");
314        sql.field("r1");
315        sql.field("r2");
316        sql.field("d1");
317        sql.field("d2");
318        sql.field("t1");
319        sql.field("t2");
320        sql.field("t3");
321        sql.field("t4");
322        sql.field("byte1");
323        sql.field("interval1");
324        sql.field("big1");
325        sql.field("big2");
326        sql.field("ts1");
327        sql.field("ts2");
328        sql.field("date1");
329        sql.field("date2");
330        sql.field("time1");
331        sql.field("time2");
332        sql.field("uid1");
333        sql.field("json1");
334        sql.field("json2");
335        sql.field("i5");
336        sql.values(&[
337            sql_builder::quote(obj.id.field_to_string()),
338            sql_builder::quote(obj.b1.field_to_string()),
339            sql_builder::quote(obj.b2.unwrap().field_to_string()),
340            sql_builder::quote(obj.c1.field_to_string()),
341            sql_builder::quote(obj.c2.unwrap().field_to_string()),
342            sql_builder::quote(obj.i4.field_to_string()),
343            sql_builder::quote(obj.i41.unwrap().field_to_string()),
344            sql_builder::quote(obj.r1.field_to_string()),
345            sql_builder::quote(obj.r2.unwrap().field_to_string()),
346            sql_builder::quote(obj.d1.field_to_string()),
347            sql_builder::quote(obj.d2.unwrap().field_to_string()),
348            sql_builder::quote(obj.t1.field_to_string()),
349            sql_builder::quote(obj.t2.field_to_string()),
350            sql_builder::quote(obj.t3.unwrap().field_to_string()),
351            sql_builder::quote(obj.t4.unwrap().field_to_string()),
352            sql_builder::quote(obj.byte1.unwrap().field_to_string()),
353            sql_builder::quote(obj.interval1.unwrap().field_to_string()),
354            sql_builder::quote(obj.big1.unwrap().field_to_string()),
355            sql_builder::quote(obj.big2.unwrap().field_to_string()),
356            sql_builder::quote(obj.ts1.field_to_string()),
357            sql_builder::quote(obj.ts2.unwrap().field_to_string()),
358            sql_builder::quote(obj.date1.unwrap().field_to_string()),
359            sql_builder::quote(obj.date2.unwrap().field_to_string()),
360            sql_builder::quote(obj.time1.field_to_string()),
361            sql_builder::quote(obj.time2.unwrap().field_to_string()),
362            sql_builder::quote(obj.uid1.field_to_string()),
363            sql_builder::quote(obj.json1.unwrap().field_to_string()),
364            sql_builder::quote(obj.json2.unwrap().field_to_string()),
365            sql_builder::quote(obj.i5.unwrap().field_to_string())
366        ]);
367
368        let sql = sql.sql().unwrap();
369        sqlx::query(sql.as_str()).execute(conn).await
370
371    }
372
373
374    pub async fn batch_insert_returning_id(conn: &mut PgConnection, objs: Vec<TestTable>) -> Vec<i64> {
375        let mut sql = sql_builder::SqlBuilder::insert_into("test_table");
376        sql.field("b1");
377        sql.field("b2");
378        sql.field("c1");
379        sql.field("c2");
380        sql.field("i4");
381        sql.field("i41");
382        sql.field("r1");
383        sql.field("r2");
384        sql.field("d1");
385        sql.field("d2");
386        sql.field("t1");
387        sql.field("t2");
388        sql.field("t3");
389        sql.field("t4");
390        sql.field("byte1");
391        sql.field("interval1");
392        sql.field("big1");
393        sql.field("big2");
394        sql.field("ts1");
395        sql.field("ts2");
396        sql.field("date1");
397        sql.field("date2");
398        sql.field("time1");
399        sql.field("time2");
400        sql.field("uid1");
401        sql.field("json1");
402        sql.field("json2");
403        sql.field("i5");
404        for obj in objs {
405            sql.values(&[
406                sql_builder::quote(obj.b1.field_to_string()),
407                sql_builder::quote(obj.b2.unwrap().field_to_string()),
408                sql_builder::quote(obj.c1.field_to_string()),
409                sql_builder::quote(obj.c2.unwrap().field_to_string()),
410                sql_builder::quote(obj.i4.field_to_string()),
411                sql_builder::quote(obj.i41.unwrap().field_to_string()),
412                sql_builder::quote(obj.r1.field_to_string()),
413                sql_builder::quote(obj.r2.unwrap().field_to_string()),
414                sql_builder::quote(obj.d1.field_to_string()),
415                sql_builder::quote(obj.d2.unwrap().field_to_string()),
416                sql_builder::quote(obj.t1.field_to_string()),
417                sql_builder::quote(obj.t2.field_to_string()),
418                sql_builder::quote(obj.t3.unwrap().field_to_string()),
419                sql_builder::quote(obj.t4.unwrap().field_to_string()),
420                sql_builder::quote(obj.byte1.unwrap().field_to_string()),
421                sql_builder::quote(obj.interval1.unwrap().field_to_string()),
422                sql_builder::quote(obj.big1.unwrap().field_to_string()),
423                sql_builder::quote(obj.big2.unwrap().field_to_string()),
424                sql_builder::quote(obj.ts1.field_to_string()),
425                sql_builder::quote(obj.ts2.unwrap().field_to_string()),
426                sql_builder::quote(obj.date1.unwrap().field_to_string()),
427                sql_builder::quote(obj.date2.unwrap().field_to_string()),
428                sql_builder::quote(obj.time1.field_to_string()),
429                sql_builder::quote(obj.time2.unwrap().field_to_string()),
430                sql_builder::quote(obj.uid1.field_to_string()),
431                sql_builder::quote(obj.json1.unwrap().field_to_string()),
432                sql_builder::quote(obj.json2.unwrap().field_to_string()),
433                sql_builder::quote(obj.i5.unwrap().field_to_string())
434            ]);
435        }
436
437
438        sql.returning_id();
439        let sql = sql.sql().unwrap();
440        let columns:Vec<(i64,)> = sqlx::query_as(sql.as_str()).fetch_all(conn).await.unwrap();
441        let mut ret = vec![];
442        for v in columns {
443            ret.push(v.0)
444        }
445        println!("insert id:{:?}", ret);
446        return ret;
447
448    }
449
450
451    pub async fn batch_insert(conn: &mut PgConnection, objs: Vec<TestTable>) -> Result<sqlx::postgres::PgQueryResult, sqlx::Error>  {
452        let mut sql = sql_builder::SqlBuilder::insert_into("test_table");
453        sql.field("id");
454        sql.field("b1");
455        sql.field("b2");
456        sql.field("c1");
457        sql.field("c2");
458        sql.field("i4");
459        sql.field("i41");
460        sql.field("r1");
461        sql.field("r2");
462        sql.field("d1");
463        sql.field("d2");
464        sql.field("t1");
465        sql.field("t2");
466        sql.field("t3");
467        sql.field("t4");
468        sql.field("byte1");
469        sql.field("interval1");
470        sql.field("big1");
471        sql.field("big2");
472        sql.field("ts1");
473        sql.field("ts2");
474        sql.field("date1");
475        sql.field("date2");
476        sql.field("time1");
477        sql.field("time2");
478        sql.field("uid1");
479        sql.field("json1");
480        sql.field("json2");
481        sql.field("i5");
482        for obj in objs {
483            sql.values(&[
484                sql_builder::quote(obj.id.field_to_string()),
485                sql_builder::quote(obj.b1.field_to_string()),
486                sql_builder::quote(obj.b2.unwrap().field_to_string()),
487                sql_builder::quote(obj.c1.field_to_string()),
488                sql_builder::quote(obj.c2.unwrap().field_to_string()),
489                sql_builder::quote(obj.i4.field_to_string()),
490                sql_builder::quote(obj.i41.unwrap().field_to_string()),
491                sql_builder::quote(obj.r1.field_to_string()),
492                sql_builder::quote(obj.r2.unwrap().field_to_string()),
493                sql_builder::quote(obj.d1.field_to_string()),
494                sql_builder::quote(obj.d2.unwrap().field_to_string()),
495                sql_builder::quote(obj.t1.field_to_string()),
496                sql_builder::quote(obj.t2.field_to_string()),
497                sql_builder::quote(obj.t3.unwrap().field_to_string()),
498                sql_builder::quote(obj.t4.unwrap().field_to_string()),
499                sql_builder::quote(obj.byte1.unwrap().field_to_string()),
500                sql_builder::quote(obj.interval1.unwrap().field_to_string()),
501                sql_builder::quote(obj.big1.unwrap().field_to_string()),
502                sql_builder::quote(obj.big2.unwrap().field_to_string()),
503                sql_builder::quote(obj.ts1.field_to_string()),
504                sql_builder::quote(obj.ts2.unwrap().field_to_string()),
505                sql_builder::quote(obj.date1.unwrap().field_to_string()),
506                sql_builder::quote(obj.date2.unwrap().field_to_string()),
507                sql_builder::quote(obj.time1.field_to_string()),
508                sql_builder::quote(obj.time2.unwrap().field_to_string()),
509                sql_builder::quote(obj.uid1.field_to_string()),
510                sql_builder::quote(obj.json1.unwrap().field_to_string()),
511                sql_builder::quote(obj.json2.unwrap().field_to_string()),
512                sql_builder::quote(obj.i5.unwrap().field_to_string())
513            ]);
514        }
515
516
517        let sql = sql.sql().unwrap();
518        sqlx::query(sql.as_str()).execute(conn).await
519
520    }
521
522    pub fn select_sql() -> String {
523        "select id, b1, b2, c1, c2, i4, i41, r1, r2, d1, d2, t1, t2, t3, t4, byte1, interval1, big1, big2, ts1, ts2, date1, date2, time1, time2, uid1, json1, json2, i5  from test_table".to_string()
524    }
525
526    pub async fn select_by_id(conn: &mut PgConnection,id: i64) -> Result<TestTable, sqlx::Error> {
527        let sql = format!("select id, b1, b2, c1, c2, i4, i41, r1, r2, d1, d2, t1, t2, t3, t4, byte1, interval1, big1, big2, ts1, ts2, date1, date2, time1, time2, uid1, json1, json2, i5  from test_table where id='{}'", id);
528        let result = sqlx::query_as(sql.as_str()).fetch_one(conn).await;
529        result
530    }
531
532    pub async fn delete_by_id(conn: &mut PgConnection,id: i64) -> Result<sqlx::postgres::PgQueryResult, sqlx::Error> {
533        let sql = format!("delete from test_table where id= '{}'", id);
534        sqlx::query(sql.as_str()).execute(conn).await
535    }
536
537
538    #[test]
539    fn name_struct_test() {
540        let name = "group_history";
541        let gen = PgGenerator{};
542        gen.gen_struct_name(name);
543    }
544
545    #[tokio::test]
546    async fn select_test() {
547
548        let conn_url = "postgres://postgres:123456@localhost/jixin_message?&stringtype=unspecified";
549        let mut conn: PgConnection = PgConnection::connect(conn_url).await.unwrap();
550        let sql = format!("select * from test_table");
551
552        let columns: Vec<TestTable> = sqlx::query_as(sql.as_str())
553            .fetch_all(&mut conn)
554            .await
555            .unwrap();
556        println!("columns:{:?}", columns)
557    }
558
559    #[test]
560    fn to_string_test() {
561        let now: DateTime<Utc> = DateTime::from(SystemTime::now());
562        println!("now:{}", now.to_string())
563    }
564
565
566    #[tokio::test]
567    async fn gen_file_test() {
568        let gen = PgGenerator{};
569        let conn_url = "postgres://postgres:123456@localhost/jixin_message?&stringtype=unspecified";
570        let table_name = "test_table";
571        let result = gen.gen_file(conn_url, table_name).await;
572        println!("result:{:?}", result)
573    }
574
575    #[tokio::test]
576    async fn insert_returning_id_test() {
577        let obj = gen_test_table_obj();
578        let conn_url = "postgres://postgres:123456@localhost/jixin_message?&stringtype=unspecified";
579        let mut conn: PgConnection = PgConnection::connect(conn_url).await.unwrap();
580        let id = insert_returning_id(&mut conn, obj).await;
581        println!("insert return id:{id}")
582    }
583    #[tokio::test]
584    async fn insert_test() {
585        let obj = gen_test_table_obj();
586        let conn_url = "postgres://postgres:123456@localhost/jixin_message?&stringtype=unspecified";
587        let mut conn: PgConnection = PgConnection::connect(conn_url).await.unwrap();
588        let result = insert(&mut conn, obj).await;
589        println!("{}", result.unwrap().rows_affected())
590    }
591
592    #[tokio::test]
593    async fn test_query_1() {
594        let conn_url = "postgres://postgres:123456@localhost/jixin_message?&stringtype=unspecified";
595        let mut conn: PgConnection = PgConnection::connect(conn_url).await.unwrap();
596        let columns: Vec<TestTable> = sqlx::query_as("select * from test_table")
597            .fetch_all(&mut conn)
598            .await
599            .unwrap();
600        println!("columns:{:?}", columns)
601    }
602
603    #[tokio::test]
604    async fn batch_insert_returning_id_test() {
605        let obj = gen_test_table_obj();
606        let obj1 = gen_test_table_obj();
607        let list = vec![obj, obj1];
608        let conn_url = "postgres://postgres:123456@localhost/jixin_message?&stringtype=unspecified";
609        let mut conn: PgConnection = PgConnection::connect(conn_url).await.unwrap();
610        let ids = batch_insert_returning_id(&mut conn, list).await;
611        println!("insert ids: {:?}", ids)
612    }
613
614    #[tokio::test]
615    async fn batch_insert_test() {
616        let mut obj = gen_test_table_obj();
617        obj.id = 60;
618        let mut obj1 = gen_test_table_obj();
619        obj1.id = 61;
620        let list = vec![obj, obj1];
621        let conn_url = "postgres://postgres:123456@localhost/jixin_message?&stringtype=unspecified";
622        let mut conn: PgConnection = PgConnection::connect(conn_url).await.unwrap();
623        let result = batch_insert(&mut conn, list).await;
624        println!("{:?}", result);
625    }
626
627    #[tokio::test]
628    async fn select_by_id_test() {
629        let conn_url = "postgres://postgres:123456@localhost/jixin_message?&stringtype=unspecified";
630        let mut conn: PgConnection = PgConnection::connect(conn_url).await.unwrap();
631        let result = select_by_id(&mut conn, 65).await;
632        println!("{:?}", result)
633    }
634
635
636    fn gen_test_table_obj() -> TestTable {
637        TestTable {
638            id: 0,
639            b1: false,
640            b2: Some(true),
641            c1: "c".to_string(),
642            c2: Some("c".to_string()),
643            i4: 44,
644            i41: Some(455),
645            r1: 0.0,
646            r2: Some(3.14),
647            d1: 0.0,
648            d2: Some(345.0),
649            t1: "4".to_string(),
650            t2: "5da".to_string(),
651            t3: Some("test".to_string()),
652            t4: Some("adf".to_string()),
653            byte1: Some(Vec::from("안녕하세요你好こんにちはЗдравствуйте💖💖💖💖💖")),
654            interval1: Some(PgInterval{
655                months: 0,
656                days: 1,
657                microseconds: 10000,
658            }),
659            big1: Some(Decimal::new(234,1)),
660            big2: Some(Decimal::new(223434,2)),
661            ts1: Default::default(),
662            ts2: Some(Default::default()),
663            date1: Some(Default::default()),
664            date2: Some(Default::default()),
665            time1: Default::default(),
666            time2: Some(PgTimeTz{ time: Default::default(), offset: FixedOffset::east_opt(0).unwrap() }),
667            uid1: Default::default(),
668            json1: Some(serde_json::from_str("{}").unwrap()),
669            json2: Some(serde_json::from_str("[{}, {}]").unwrap()),
670            i5: Some(12),
671        }
672    }
673
674    #[test]
675    fn test_vec8() {
676        let vec = Vec::from("안녕하세요你好こんにちはЗдравствуйте💖💖💖💖💖");
677        let str2 = String::from_utf8(vec).unwrap();
678        println!("{}", str2);
679    }
680
681    #[tokio::test]
682    async fn delete_by_id_test() {
683        let conn_url = "postgres://postgres:123456@localhost/jixin_message?&stringtype=unspecified";
684        let mut conn: PgConnection = PgConnection::connect(conn_url).await.unwrap();
685        let result =delete_by_id(&mut conn, 3).await;
686        println!("delete result:{:?}", result)
687    }
688
689
690}