rusty_postgres/method/
methods.rs

1//  use rusty_postgres::method::types::{OneToMany,OneToOne};
2#[macro_export]
3macro_rules! model {
4    ($model:expr => {$($billionaire:expr => {$($value:expr),*}),*}) => {
5        {
6            use rusty_postgres::serde_json;
7            use std::panic;
8            use rusty_postgres::rand::Rng;
9            use rusty_postgres::rand;
10            //  use rusty_postgres::method::types::{OneToMany,OneToOne};
11            use rusty_postgres::method::types::{OneToMany, OneToOne};
12            use rusty_postgres::rand::distributions::Alphanumeric;
13
14            let mut table = String::new();
15            let mut primary_key = String::new();
16            let mut index = String::new();
17            let mut foriegn_key = String::new();
18            let mut index_relation = String::new();
19            let mut id = String::new();
20            let mut unique = String::new();
21            // $(
22                if $model.len() != 0 {
23                    table.push_str(&format!("\r\nCREATE TABLE IF NOT EXISTS {} (\r\n",$model));
24                }
25                else {
26                    panic!("Provide model")
27                }
28                // table.push_str(&$model.to_lowercase());
29                // println!("{}",$model);
30                $(
31                    if $billionaire.len() != 0 {
32                        table.push_str(&format!("{} ",$billionaire.to_lowercase()));
33                    }
34                    else {
35                        panic!("Provide model name c    use model name is unknown {}",$billionaire);
36                    }
37                    //
38                    $(
39                        let value = stringify!($value);
40                        // println!("{}",stringify!($value));
41                        // for id
42                        if value.starts_with("ID(") {
43                            if value == ("ID(UUID)") {
44                                // primary_key.push_str(&format!("{},",$billionaire.to_lowercase()));
45                                table.push_str("UUID ");
46                                id.push_str("UUID");
47                                primary_key.push_str(&format!("{},",$billionaire.to_lowercase()));
48                                // table.push_str("PRIMARY KEY ");
49                                table.push_str("DEFAULT uuid_generate_v4() ");
50                            }
51                            else if value == ("ID(CUID)"){
52                                table.push_str("TEXT ");
53                                id.push_str("TEXT ");
54                                primary_key.push_str(&format!("{},",$billionaire.to_lowercase()));
55                                // table.push_str("PRIMARY KEY ");
56                                table.push_str("DEFAULT encode(gen_random_bytes(12),'hex') ");
57                            }
58                            else if value == ("ID(AUTO)") {
59                                id.push_str("INT ");
60                                primary_key.push_str(&format!("{},",$billionaire.to_lowercase()));
61                                table.push_str("INT GENERATED ALWAYS AS IDENTITY ");
62                                // table.push_str("PRIMARY KEY ");
63                            }
64                            else if value == ("ID(BIGINT)") {
65                                id.push_str("BIGINT ");
66                                primary_key.push_str(&format!("{},",$billionaire.to_lowercase()));
67                                table.push_str("BIGINT ");
68                                // table.push_str("PRIMARY KEY ");
69                            }
70                            else {
71                                panic!("please provide correct (uuid,cuid,auto)")
72                            }
73                        }
74
75                        // * ONE_TO_ONE
76                        else if value.starts_with("OneToOne"){
77                            let serialize = serde_json::to_string(&$value).unwrap();
78                            // println!("{:?}", serialize);
79                            let deserialize = serde_json::from_str::<OneToOne>(&serialize).unwrap();
80
81
82                            // * UUID
83                            if id.contains("UUID") {
84                                let line = format!("UUID UNIQUE ");
85                                table.push_str(&line);
86                                let line = format!("FOREIGN KEY ({}) REFERENCES {}({}) ON DELETE CASCADE ,\r\n",$billionaire.to_lowercase(),deserialize.table,deserialize.table_field);
87                                foriegn_key.push_str(&line);
88                                index_relation.push_str(&format!("{},",$billionaire.to_lowercase()))
89                            }
90                            // * AUTO
91                            else if id.contains("INT") {
92                                let line = format!("INT UNIQUE ");
93                                table.push_str(&line);
94                                let line = format!("FOREIGN KEY ({}) REFERENCES {}({}) ON DELETE CASCADE ,\r\n",$billionaire.to_lowercase(),deserialize.table,deserialize.table_field);
95                                foriegn_key.push_str(&line);
96                                index_relation.push_str(&format!("{},",$billionaire.to_lowercase()))
97                            }
98
99                            // * CUID
100                            else if id.contains("TEXT "){
101                                let line = format!("TEXT UNIQUE ");
102                                table.push_str(&line);
103                                let line = format!("FOREIGN KEY ({}) REFERENCES {}({}) ON DELETE CASCADE ,\r\n",$billionaire.to_lowercase(),deserialize.table,deserialize.table_field);
104                                foriegn_key.push_str(&line);
105                                index_relation.push_str(&format!("{},",$billionaire.to_lowercase()))
106                            }
107                            else {
108                                panic!("Provide correct variable in id")
109                            }
110                        }
111
112                        // * ONE_TO_MANY
113                        else if value.starts_with("OneToMany"){
114                            let serialize = serde_json::to_string(&$value).unwrap();
115                            // println!("{:?}", serialize);
116                            let deserialize = serde_json::from_str::<OneToMany>(&serialize).unwrap();
117
118                            // * UUID
119                            if id.contains("UUID") {
120                                let line = format!("UUID ");
121                                table.push_str(&line);
122                                let line = format!("FOREIGN KEY ({}) REFERENCES {}({}) ON DELETE CASCADE ,\r\n",$billionaire.to_lowercase(),deserialize.table,deserialize.table_field);
123                                foriegn_key.push_str(&line);
124                                index_relation.push_str(&format!("{},",$billionaire.to_lowercase()))
125                            }
126                            // * AUTO
127                            else if id.contains("INT") {
128                                let line = format!("INT ");
129                                table.push_str(&line);
130                                let line = format!("FOREIGN KEY ({}) REFERENCES {}({}) ON DELETE CASCADE ,\r\n",$billionaire.to_lowercase(),deserialize.table,deserialize.table_field);
131                                foriegn_key.push_str(&line);
132                                index_relation.push_str(&format!("{},",$billionaire.to_lowercase()))
133                            }
134
135                            // * CUID
136                            else if id.contains("TEXT "){
137                                let line = format!("TEXT ");
138                                table.push_str(&line);
139                                let line = format!("FOREIGN KEY ({}) REFERENCES {}({}) ON DELETE CASCADE ,\r\n",$billionaire.to_lowercase(),deserialize.table,deserialize.table_field);
140                                foriegn_key.push_str(&line);
141                                index_relation.push_str(&format!("{},",$billionaire.to_lowercase()))
142                            }
143
144                            else {
145                                panic!("Provide correct variable in id in ONE_TO_MANY")
146                            }
147
148                        }
149
150                        // * DATE
151                        else if value.starts_with("Date") && !value.starts_with("DateTime") {
152
153                            // * NOW
154                            if value == ("Date(NOW)") {
155                                // println!("{}","billionaire");
156                                table.push_str(&format!("{}","DATE DEFAULT CURRENT_DATE"))
157                            }
158                            // * CUSTOME
159                            else if value == "Date(CUSTOME)" {
160                                table.push_str(&format!("{}","DATE NOT NULL"))
161                            }
162                            else {
163                                panic!("{}","Provide correct method for DATE")
164                            }
165                        }
166
167                        // * TIME
168                        else if value.starts_with("Time") {
169
170                            // * NOW
171                            if value == ("Time(NOW)") {
172                                // println!("{}")
173                               table.push_str(&format!("{}","TIME DEFAULT CURRENT_TIME"))
174                            }
175
176                            // * CUSTOME
177                            else if value == ("Time(CUSTOME)") {
178                                table.push_str(&format!("{}","TIME NOT NULL"))
179                            }
180                            else {
181                                panic!("{}","Provide correct method for TIME")
182                            }
183                       }
184
185                        //  * date_time
186                       else if value.starts_with("DateTime") {
187                            if value == ("DateTime(NOW)") {
188                                table.push_str(&format!("{}","TIMESTAMP DEFAULT NOW()"))
189                            }
190                            else if value == ("DateTime(CUSTOME)") {
191                                table.push_str(&format!("{}","TIMESTAMP NOT NULL"))
192                            }
193                            else {
194                                panic!("{}","Provide correct method for DATETIME")
195                            }
196                       }
197                        else if value.starts_with("STRING"){
198                            table.push_str("TEXT ")
199                        }
200                        else if value.starts_with("FLOAT"){
201                            table.push_str("NUMERIC ")
202                        }
203                        else if value.starts_with("NUMBER"){
204                            table.push_str("INT ")
205                        }
206                        else if value.starts_with("BOOL"){
207                            table.push_str("BOOL ")
208                        }
209
210                        // * DEFAULT
211                        else if value.starts_with("DEFAULT"){
212                            // let value = $value;
213                            // println!("{:?}",value);
214                            let value = value.split("(").nth(1).unwrap().trim_end_matches(")");
215                            // println!("{}",value);
216                            if value.starts_with("\""){
217                                let value = format!("'{}' ",value);
218                                let value=  value.replace("\"","");
219                                let default = format!("DEFAULT {}", value);
220                                table.push_str(&default);
221                            }
222                            else {
223                                let value = value.replace("\"\"","");
224                                // println!("integers {}",value);
225                                // let value = format!("{}",value);
226                                let default = format!("DEFAULT {} ", value);
227                                table.push_str(&default);
228                            }
229                        }
230
231                        // * JSON
232                        else if value.starts_with("JSON"){
233                            table.push_str("JSONB ")
234                        }
235
236                        // * GEOGRAPHY
237                        else if value.starts_with("Geography("){
238                            if value.starts_with("Geography(POINT(Epsg3857))"){
239                                let value = format!("GEOGRAPHY(POINT,3857) ");
240                                table.push_str(&value);
241                            }
242                            else if value.starts_with("Geography(POINT(Epsg4326))"){
243                                let value = format!("GEOGRAPHY(POINT,4326) ");
244                                table.push_str(&value);
245                            }
246                            else if value.starts_with("Geography(POLYGON(Epsg3857))"){
247                                let value = format!("GEOGRAPHY(POLYGON,3857) ");
248                                table.push_str(&value);
249                            }
250                            else if value.starts_with("Geography(POLYGON(Epsg4326))"){
251                                let value = format!("GEOGRAPHY(POLYGON,4326) ");
252                                table.push_str(&value);
253                            }
254                            else {
255                                panic!("Please provide correct Geography in table {}",$model)
256                            }
257                        }
258
259                        else if value.starts_with("NOTNULL"){
260                            table.push_str(&format!("NOT NULL "))
261                        }
262                        // * UNIQUE
263                        else if value.starts_with("UNIQUE"){
264                            // println!("{}",$billionaire.to_lowercase());
265                            unique.push_str(&format!("{},",$billionaire.to_lowercase()))
266                        }
267                        else if value.starts_with("PRIMARY"){
268                            if !primary_key.contains(&$billionaire.to_lowercase()){
269                                primary_key.push_str(&format!("{},",$billionaire.to_lowercase()));
270                            }
271                        }
272                        else if value.starts_with("INDEX"){
273                            index.push_str(&format!("{},",$billionaire.to_lowercase()))
274                        }
275                        else {
276                            panic!("Provide Related Key at {} in table {}",stringify!($value),$model)
277                        }
278                        // println!("{:?}",$value);
279                    )*
280                    let mut table = table.trim_end_matches(" ").to_string();
281                    table.push_str(",");
282                    table.push_str("\n");
283                )*
284                // println!("{}",table);
285                if primary_key.len() != 0 {
286                    let mut primary_key = primary_key.trim_end_matches(",");
287                    let key = format!("PRIMARY KEY ({}),\r\n",primary_key);
288                    // println!("{:?}",key);
289                    table.push_str(&key);
290                }
291                if unique.len() != 0 {
292                    let mut unique = unique.trim_end_matches(",");
293                    let key = format!("UNIQUE ({}),\r\n",unique);
294                    // println!("{}",key);
295                    table.push_str(&key);
296                }
297                if foriegn_key.len() != 0 {
298                    // println!("{}",foriegn_key);
299                    let foriegn_key = format!("{}",foriegn_key);
300                    table.push_str(&foriegn_key);
301                }
302                let table = table.trim_end_matches(",\r\n");
303                let table = table.trim_end_matches("\n");
304                let mut table = table.trim_end_matches(",").to_string();
305                // println!("{}",tables);
306                table.push_str("\r\n);\r\n");
307                let index = index.trim_end_matches(",");
308                // println!("{}",index);
309                if index.len() != 0 {
310                    let random: String = rand::thread_rng()
311                    .sample_iter(&Alphanumeric)
312                    .take(6)
313                    .map(char::from)
314                    .collect();
315                    table.push_str(&format!("CREATE INDEX index_{} ON {} ({});\r\n",random,$model,index));
316                    table.push_str(&format!("CLUSTER {} USING index_{};\r\n",$model,random));
317                }
318                if index_relation.len() != 0 {
319                    let index_relation = index_relation.trim_end_matches(",");
320                    let random: String = rand::thread_rng()
321                    .sample_iter(&Alphanumeric)
322                    .take(6)
323                    .map(char::from)
324                    .collect();
325                    table.push_str(&format!("CREATE INDEX index_relation_{} ON {} ({});\r\n",random,$model,index_relation));
326                }
327                // println!("{}",foriegn_key);
328            // )*
329            table
330        }
331    };
332
333    ($model:expr => {$($billionaire:expr => {$($value:expr),*}),*},partition:{
334        type:$type:expr,
335        to:$to:expr
336    }) => {
337        {
338            use rusty_postgres::serde_json;
339            use std::panic;
340            use rusty_postgres::rand::Rng;
341            use rusty_postgres::rand;
342            //  use rusty_postgres::method::types::{OneToMany,OneToOne};
343            use rusty_postgres::method::types::{OneToMany, OneToOne};
344            use rusty_postgres::rand::distributions::Alphanumeric;
345
346            let mut table = String::new();
347            let mut primary_key = String::new();
348            let mut index = String::new();
349            let mut foriegn_key = String::new();
350            let mut index_relation = String::new();
351            let mut id = String::new();
352            let mut unique = String::new();
353            // $(
354                if $model.len() != 0 {
355                    table.push_str(&format!("\r\nCREATE TABLE IF NOT EXISTS {} (\r\n",$model));
356                }
357                else {
358                    panic!("Provide model")
359                }
360                // table.push_str(&$model.to_lowercase());
361                // println!("{}",$model);
362                $(
363                    if $billionaire.len() != 0 {
364                        table.push_str(&format!("{} ",$billionaire.to_lowercase()));
365                    }
366                    else {
367                        panic!("Provide model name c    use model name is unknown {}",$billionaire);
368                    }
369                    //
370                    $(
371                        let value = stringify!($value);
372                        // println!("{}",stringify!($value));
373                        // for id
374                        if value.starts_with("ID(") {
375                            if value == ("ID(UUID)") {
376                                primary_key.push_str(&format!("{},",$billionaire.to_lowercase()));
377                                table.push_str("UUID ");
378                                id.push_str("UUID");
379
380                                // table.push_str("PRIMARY KEY ");
381                                table.push_str("DEFAULT uuid_generate_v4() ");
382                            }
383                            else if value == ("ID(CUID)"){
384                                table.push_str("TEXT ");
385                                id.push_str("TEXT ");
386                                primary_key.push_str(&format!("{},",$billionaire.to_lowercase()));
387                                // table.push_str("PRIMARY KEY ");
388                                table.push_str("DEFAULT encode(gen_random_bytes(12),'hex') ");
389                            }
390                            else if value == ("ID(AUTO)") {
391                                id.push_str("INT ");
392                                primary_key.push_str(&format!("{},",$billionaire.to_lowercase()));
393                                table.push_str("INT GENERATED ALWAYS AS IDENTITY ");
394                                // table.push_str("PRIMARY KEY ");
395                            }
396                            else if value == ("ID(BIGINT)") {
397                                id.push_str("BIGINT ");
398                                primary_key.push_str(&format!("{},",$billionaire.to_lowercase()));
399                                table.push_str("BIGINT ");
400                                // table.push_str("PRIMARY KEY ");
401                            }
402                            else {
403                                panic!("please provide correct (uuid,cuid,auto)")
404                            }
405                        }
406
407                        // * ONE_TO_ONE
408                        else if value.starts_with("OneToOne"){
409                            let serialize = serde_json::to_string(&$value).unwrap();
410                            // println!("{:?}", serialize);
411                            let deserialize = serde_json::from_str::<OneToOne>(&serialize).unwrap();
412
413                             // * UUID
414                             if id.contains("UUID") {
415                                let line = format!("UUID UNIQUE ");
416                                table.push_str(&line);
417                                let line = format!("FOREIGN KEY ({}) REFERENCES {}({}) ON DELETE CASCADE ",$billionaire.to_lowercase(),deserialize.table,deserialize.table_field);
418                                foriegn_key.push_str(&line);
419                                index_relation.push_str(&format!("{},",$billionaire.to_lowercase()))
420                            }
421                            // * AUTO
422                            else if id.contains("INT") {
423                                let line = format!("INT UNIQUE");
424                                table.push_str(&line);
425                                let line = format!("FOREIGN KEY ({}) REFERENCES {}({}) ON DELETE CASCADE ",$billionaire.to_lowercase(),deserialize.table,deserialize.table_field);
426                                foriegn_key.push_str(&line);
427                                index_relation.push_str(&format!("{},",$billionaire.to_lowercase()))
428                            }
429
430                            // * CUID
431                            else if id.contains("TEXT "){
432                                let line = format!("TEXT UNIQUE");
433                                table.push_str(&line);
434                                let line = format!("FOREIGN KEY ({}) REFERENCES {}({}) ON DELETE CASCADE ",$billionaire.to_lowercase(),deserialize.table,deserialize.table_field);
435                                foriegn_key.push_str(&line);
436                                index_relation.push_str(&format!("{},",$billionaire.to_lowercase()))
437                            }
438
439                            else {
440                                panic!("Provide correct variable in id")
441                            }
442                        }
443
444                        // * ONE_TO_MANY
445                        else if value.starts_with("OneToMany"){
446                            let serialize = serde_json::to_string(&$value).unwrap();
447                            // println!("{:?}", serialize);
448                            let deserialize = serde_json::from_str::<OneToMany>(&serialize).unwrap();
449
450                            // * UUID
451                            if id.contains("UUID") {
452                                let line = format!("UUID ");
453                                table.push_str(&line);
454                                let line = format!("FOREIGN KEY ({}) REFERENCES {}({}) ON DELETE CASCADE ",$billionaire.to_lowercase(),deserialize.table,deserialize.table_field);
455                                foriegn_key.push_str(&line);
456                                index_relation.push_str(&format!("{},",$billionaire.to_lowercase()))
457                            }
458                            // * AUTO
459                            else if id.contains("INT") {
460                                let line = format!("INT ");
461                                table.push_str(&line);
462                                let line = format!("FOREIGN KEY ({}) REFERENCES {}({}) ON DELETE CASCADE ",$billionaire.to_lowercase(),deserialize.table,deserialize.table_field);
463                                foriegn_key.push_str(&line);
464                                index_relation.push_str(&format!("{},",$billionaire.to_lowercase()))
465                            }
466
467                            // * CUID
468                            else if id.contains("TEXT "){
469                                let line = format!("TEXT ");
470                                table.push_str(&line);
471                                let line = format!("FOREIGN KEY ({}) REFERENCES {}({}) ON DELETE CASCADE ",$billionaire.to_lowercase(),deserialize.table,deserialize.table_field);
472                                foriegn_key.push_str(&line);
473                                index_relation.push_str(&format!("{},",$billionaire.to_lowercase()))
474                            }
475
476                            else {
477                                panic!("Provide correct variable in id in ONE_TO_MANY")
478                            }
479
480                        }
481
482                        // * DATE
483                        else if value.starts_with("Date") && !value.starts_with("DateTime") {
484
485                            // * NOW
486                            if value == stringify!(Date(NOW)) {
487                                // println!("{}","billionaire");
488                                table.push_str(&format!("{}","DATE DEFAULT CURRENT_DATE"))
489                            }
490                            // * CUSTOME
491                            else if value == "Date(CUSTOME)" {
492                                table.push_str(&format!("{}","DATE NOT NULL"))
493                            }
494                            else {
495                                panic!("{}","Provide correct method for DATE")
496                            }
497                        }
498
499                        // * TIME
500                        else if value.starts_with("Time") {
501
502                            // * NOW
503                            if value == ("Time(NOW)") {
504                                // println!("{}")
505                               table.push_str(&format!("{}","TIME DEFAULT CURRENT_TIME"))
506                            }
507
508                            // * CUSTOME
509                            else if value == ("Time(CUSTOME)") {
510                                table.push_str(&format!("{}","TIME NOT NULL"))
511                            }
512                            else {
513                                panic!("{}","Provide correct method for TIME")
514                            }
515                       }
516
517                        //  * date_time
518                       else if value.starts_with("DateTime") {
519                            if value == ("DateTime(NOW)") {
520                                table.push_str(&format!("{}","TIMESTAMP DEFAULT NOW()"))
521                            }
522                            else if value == ("DateTime(CUSTOME)") {
523                                table.push_str(&format!("{}","TIMESTAMP NOT NULL"))
524                            }
525                            else {
526                                panic!("{}","Provide correct method for DATETIME")
527                            }
528                        }
529                        else if value.starts_with("STRING"){
530                            table.push_str("TEXT ")
531                        }
532                        else if value.starts_with("FLOAT"){
533                            table.push_str("NUMERIC ")
534                        }
535                        else if value.starts_with("NUMBER"){
536                            table.push_str("INT ")
537                        }
538                        else if value.starts_with("BOOL"){
539                            table.push_str("BOOL ")
540                        }
541
542                        // * DEFAULT
543                        else if value.starts_with("DEFAULT"){
544                            // let value = $value;
545                            // println!("{:?}",value);
546                            let value = value.split("(").nth(1).unwrap().trim_end_matches(")");
547                            // println!("{}",value);
548                            if value.starts_with("\""){
549                                let value = format!("'{}' ",value);
550                                let value=  value.replace("\"","");
551                                let default = format!("DEFAULT {}", value);
552                                table.push_str(&default);
553                            }
554                            else {
555                                let value = value.replace("\"\"","");
556                                // println!("integers {}",value);
557                                // let value = format!("{}",value);
558                                let default = format!("DEFAULT {} ", value);
559                                table.push_str(&default);
560                            }
561                        }
562
563                        else if value.starts_with("Geography("){
564                            if value.starts_with("Geography(POINT(Epsg3857))"){
565                                let value = format!("GEOGRAPHY(POINT,3857) ");
566                                table.push_str(&value);
567                            }
568                            else if value.starts_with("Geography(POINT(Epsg4326))"){
569                                let value = format!("GEOGRAPHY(POINT,4326) ");
570                                table.push_str(&value);
571                            }
572                            else if value.starts_with("Geography(POLYGON(Epsg3857))"){
573                                let value = format!("GEOGRAPHY(POLYGON,3857) ");
574                                table.push_str(&value);
575                            }
576                            else if value.starts_with("Geography(POLYGON(Epsg4326))"){
577                                let value = format!("GEOGRAPHY(POLYGON,4326) ");
578                                table.push_str(&value);
579                            }
580                            else {
581                                panic!("Please provide correct Geography in table {}",$model)
582                            }
583                        }
584
585                        // * UNIQUE
586                        else if value.starts_with("UNIQUE"){
587                            // println!("{}",$billionaire.to_lowercase());
588                            unique.push_str(&format!("{},",$billionaire.to_lowercase()));
589                        }
590
591                        // * JSON
592                        else if value.starts_with("JSON"){
593                            table.push_str("JSONB ")
594                        }
595                        // else if value == ("UUID"){
596                        //     table.push_str("UUID ");
597                        //     // table.push_str("PRIMARY KEY ");
598                        //     table.push_str("DEFAULT uuid_generate_v4() ");
599                        // }
600                        // else if value == ("CUID"){
601                        //     table.push_str("TEXT ");
602                        //     // table.push_str("PRIMARY KEY ");
603                        //     table.push_str("DEFAULT encode(gen_random_bytes(12),'hex') ");
604                        // }
605                        // else if value == ("AUTO") {
606                        //     table.push_str("INT GENERATED ALWAYS AS IDENTITY ");
607                        //     // table.push_str("PRIMARY KEY ");
608                        // }
609
610                        // * GEOGRAPHY
611                        else if value.starts_with("Geography"){
612                            table.push_str(&format!("GEOGRAPHY(POINT,4326)  "))
613                        }
614                        else if value.starts_with("NOTNULL"){
615                            table.push_str(&format!("NOT NULL "))
616                        }
617                        else if value.starts_with("PRIMARY"){
618                            primary_key.push_str(&format!("{},",$billionaire.to_lowercase()));
619                        }
620                        else if value.starts_with("INDEX"){
621                            index.push_str(&format!("{},",$billionaire.to_lowercase()))
622                        }
623                        else {
624                            panic!("Provide Related Key at {} in table {}",stringify!($value),$model)
625                        }
626                        // println!("{:?}",$value);
627                    )*
628                    let mut table = table.trim_end_matches(" ").to_string();
629                    table.push_str(",");
630                    table.push_str("\n");
631                )*
632                if unique.len() != 0 {
633                    let mut unique = unique.trim_end_matches(",");
634                    let key_unique = format!("UNIQUE ({}),\r\n",unique);
635                    // println!("{:?}",key_unique);
636                    table.push_str(&key_unique);
637                }
638                if primary_key.len() != 0 {
639                    let mut primary_key = primary_key.trim_end_matches(",");
640                    let key = format!("PRIMARY KEY ({}),\r\n",primary_key);
641                    // println!("{:?}",key);
642                    table.push_str(&key);
643                }
644                // println!("{}",table);
645                // table.push_str("PRIMARY KEY (id,story)");
646                // let mut primary_key = primary_key.trim_end_matches(",");
647                // println!("bbbbbbbbbbbbb {}",primary_key);
648                let table = table.trim_end_matches(",\r\n");
649                let index = index.trim_end_matches(",");
650                let mut table = table.trim_end_matches(",").to_string();
651
652                if $type.len() != 0 && $to.len() != 0 {
653                    if $type == "range" {
654                        table.push_str(&format!("\r\n) PARTITION BY RANGE ({});\r\n",$to));
655                    }
656                    else if $type == "list" {
657                        table.push_str(&format!("\r\n) PARTITION BY LIST ({});\r\n",$to));
658                    }
659                    else {
660                        panic!("Invalid partition type")
661                    }
662                }
663                if index.len() != 0 {
664                    let random: String = rand::thread_rng()
665                    .sample_iter(&Alphanumeric)
666                    .take(6)
667                    .map(char::from)
668                    .collect();
669                    table.push_str(&format!("CREATE INDEX index_{} ON {} ({});\r\n",random,$model,index));
670                    table.push_str(&format!("CLUSTER {} USING index_{};",$model,random));
671                }
672                // println!("{}",tables);
673                    // table.push_str(&format!("\r\n) PARTITION BY {} ({});\r\n",$type,$to));
674                    // table.push_str(&format!("\r\n);\r\n"));
675            // )*
676            table
677        }
678    };
679}
680#[cfg(not(feature = "async"))]
681#[macro_export]
682macro_rules! container {
683     (client => $url:expr ,models => { $($model:expr),*}) => {{
684        use std::fs::DirBuilder;
685        use std::fs::File;
686        use std::io::Write;
687
688        // let model = $model.clone()
689        let mut schema = String::new();
690        $(
691            let mut container = String::new();
692            let mut containers = String::new();
693
694            container.push_str(&format!("{}",$model));
695
696            if container.contains("GEOGRAPHY") {
697                containers.push_str("CREATE EXTENSION IF NOT EXISTS postgis;\r\n");
698                // containers.push_str(&container);
699            }
700            if container.contains("UUID") {
701                containers.push_str("CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\";\r\n");
702                // containers.push_str(&container);
703            }
704            if container.contains("encode(gen_random_bytes(12)") {
705                containers.push_str("CREATE EXTENSION IF NOT EXISTS \"pgcrypto\";\r\n");
706                // containers.push_str(&container);
707            }
708            containers.push_str(&container);
709            schema.push_str(&containers);
710            // let mut cluster = String::new();
711            // println!("{}",containers);
712            if let Some(cluster) = containers.find("CLUSTER") {
713                // println!("{}",containers);
714                let clusters = &containers[cluster..];
715                // println!("{}", clusters);
716                let containers = &containers[..cluster];
717                println!("{}", containers);
718                // println!("{}",&fresh);
719
720                let db = $url.batch_execute(&containers).unwrap();
721                $url.batch_execute(&clusters).unwrap();
722
723                let db = $url.batch_execute(&containers).unwrap();
724                $url.batch_execute(&clusters).unwrap();
725            } else {
726                let db = $url.batch_execute(&containers).unwrap();
727
728                let db = $url.batch_execute(&containers).unwrap();
729            }
730            println!("......................................................");
731        )*
732        DirBuilder::new()
733        .recursive(true)
734        .create("database")
735        .unwrap();
736        let mut sql = File::create("database/db.sql").unwrap();
737        sql.write_all(format!("/* Reference Schema */\r\n").as_bytes())
738            .unwrap();
739        sql.write_all(schema.as_bytes()).unwrap();
740    }};
741}
742
743#[cfg(feature = "async")]
744#[macro_export]
745macro_rules! container {
746     (client => $url:expr ,models => { $($model:expr),*}) => {
747        {
748        use rusty_postgres::tokio::fs::DirBuilder;
749        use rusty_postgres::tokio::fs::File;
750        use rusty_postgres::tokio::io::AsyncWriteExt;
751        use rusty_postgres::GenericClient;
752
753        // let model = $model.clone()
754        let mut schema = String::new();
755        $(
756            let mut container = String::new();
757            let mut containers = String::new();
758
759            container.push_str(&format!("{}",$model));
760
761            if container.contains("GEOGRAPHY") {
762                containers.push_str("CREATE EXTENSION IF NOT EXISTS postgis;\r\n");
763                // containers.push_str(&container);
764            }
765            if container.contains("UUID") {
766                containers.push_str("CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\";\r\n");
767                // containers.push_str(&container);
768            }
769            if container.contains("encode(gen_random_bytes(12)") {
770                containers.push_str("CREATE EXTENSION IF NOT EXISTS \"pgcrypto\";\r\n");
771                // containers.push_str(&container);
772            }
773            containers.push_str(&container);
774            schema.push_str(&containers);
775            // let mut cluster = String::new();
776            // println!("{}",containers);
777            if let Some(cluster) = containers.find("CLUSTER") {
778                // println!("{}",containers);
779                let clusters = &containers[cluster..];
780                // println!("{}", clusters);
781                let containers = &containers[..cluster];
782                println!("{}", containers);
783                // println!("{}",&fresh);
784
785
786                let db = $url.batch_execute(&containers).await;
787                match db {
788                    Ok(db) => {
789
790                    }
791                    Err(err) => {
792                        panic!("{:?}",err);
793                    }
794                }
795                // println!("{}","billionaire");
796                $url.batch_execute(&clusters).await.unwrap();
797            } else {
798                println!("{}","billionaire");
799                let db = $url.batch_execute(&containers).await.unwrap();
800
801            }
802            println!("......................................................");
803        )*
804        DirBuilder::new()
805        .recursive(true)
806        .create("database").await
807        .unwrap();
808        let mut sql = File::create("database/db.sql").await.unwrap();
809        sql.write_all(format!("/* Reference Schema */\r\n").as_bytes()).await
810            .unwrap();
811        sql.write_all(schema.as_bytes()).await.unwrap();
812    }};
813}
814#[macro_export]
815macro_rules! formats {
816    ($client:expr) => {{
817        use rusty_postgres::Uuid;
818        use rusty_postgres::{NaiveDate, NaiveDateTime, NaiveTime};
819        use std::collections::BTreeMap;
820        use std::panic;
821
822        let mut billionaires = Vec::new();
823        for billionaire in $client.iter() {
824            let mut collection = Vec::new();
825            let billionaire_column = billionaire.columns();
826            for billionaires in billionaire_column.iter() {
827                let mut map = BTreeMap::new();
828
829                let name = billionaires.name();
830                let billion = billionaires.type_().name();
831
832                // println!("{:?}", billion);
833
834                let value = match billion.clone() {
835                    "text" => {
836                        let value: String = billionaire.get(name);
837                        value
838                    }
839                    "date" => {
840                        let value: NaiveDate = billionaire.get(name);
841                        value.to_string()
842                    }
843                    "timestamp" => {
844                        let value: NaiveDateTime = billionaire.get(name);
845                        value.to_string()
846                    }
847                    "int4" => {
848                        let value: i32 = billionaire.get(name);
849                        value.to_string()
850                    }
851                    "int8" => {
852                        let value: i64 = billionaire.get(name);
853                        value.to_string()
854                    }
855                    "float4" => {
856                        let value: f32 = billionaire.get(name);
857                        value.to_string()
858                    }
859                    "time" => {
860                        let value: NaiveTime = billionaire.get(name);
861                        value.to_string()
862                    }
863                    "uuid" => {
864                        let value: Uuid = billionaire.get(name);
865                        value.to_string()
866                    }
867                    "bool" => {
868                        let value: bool = billionaire.get(name);
869                        value.to_string()
870                    }
871                    _ => {
872                        panic!("")
873                    }
874                };
875                map.insert(name.to_string(), value);
876                collection.push(map)
877            }
878            // println!("{:?}",collection);
879            billionaires.push(collection);
880        }
881        billionaires
882    }};
883}
884
885///
886/// # Usage
887///
888/// ```
889/// let find = find_one! {
890///     connection => postgres,
891///     model:"place",
892///     select:{
893///         "name"
894///     },
895///     conditions:{
896///         and => {
897///             "name" => "billionairehari"
898///         },
899///         or => {
900///             "name" => "billionairehari"
901///         }
902///     },
903///     order:{
904///         "name" => "asc"
905///     }
906/// };
907/// ```
908///
909///
910#[cfg(not(feature = "async"))]
911#[macro_export]
912macro_rules! find_one {
913    // * included and or order //completed
914    (connection => $connection:expr,
915            model:$model:expr
916            $(,select:{
917                $($select_value:expr),*
918            })?
919        $(,conditions:{
920            $(and => {
921                $($and_values:expr => $and_value:expr),*
922            })?
923            $(,)?
924            $(or =>  {
925                $($or_value1:expr => $or_value2:expr),*
926            })?
927        })?
928        $(,order : {$($target:expr => $order:expr),*})?
929    ) =>
930    {
931        {
932            use std::panic;
933            use rusty_postgres::ToSql;
934            use rusty_postgres::formats;
935            use std::io;
936
937            let mut selectvalue = String::new();
938            let mut conditions = String::new();
939            let mut and_value:Vec<&(dyn ToSql + Sync)> = Vec::new();
940            let mut order = String::new();
941            // let mut selection = String::new();
942            $(
943                $(
944                selectvalue.push_str(&format!("{},",$select_value));
945                // selection.push_str(&format!("'{}',",$select_value));
946                )*
947            )?
948            let select_value = selectvalue.trim_end_matches(",");
949            // let selection = selection.trim_end_matches(",");
950            // println!("{}",select_value);
951            let mut idx = 0;
952            $(
953                $(
954                $(
955                    idx+=1;
956                    conditions.push_str(&format!("{} = ${} AND ",$and_values,idx));
957                    and_value.push(&$and_value);
958                )*
959                )?
960            )?
961            // $()?
962            $(
963                $(
964                    $(
965                        idx+=1;
966                        conditions.push_str(&format!("{} = ${} OR ",$or_value1,idx));
967                        and_value.push(&$or_value2);
968                    )*
969                )?
970            )?
971            let conditions = conditions.trim_end_matches("AND ");
972            let conditions = conditions.trim_end_matches("OR ");
973            $(
974                $(
975                if !["asc","desc","ASC","DESC"].contains(&$order) {
976                    panic!("Provide correct order either \"asc\" nor \"desc\"");
977                }
978                else {
979                    let order_ = format!("{} {},",$target,$order.to_uppercase());
980                    order.push_str(&order_);
981                }
982                )*
983            )?
984            let order = order.trim_end_matches(",");
985            // println!("{}",and_values);
986            // println!("{:?}",and_value);
987            let mut select = format!("SELECT ");
988            if select_value.len() != 0 {
989                let selection = format!("{}",select_value);
990                select.push_str(&selection);
991            }
992            else {
993                let selection = format!("*");
994                select.push_str(&selection);
995            }
996            select.push_str(&format!(" FROM {}",$model));
997            if conditions.len() != 0 {
998                select.push_str(&format!(" WHERE {}",conditions));
999            }
1000            if order.len() != 0 {
1001                select.push_str(&format!(" ORDER BY {}",order));
1002            }
1003            select.push_str(" LIMIT 1");
1004            // println!("{}",select);
1005            // FROM {} WHERE {} ORDER BY {} LIMIT 1;
1006            let client = $connection.query(&select,&and_value);
1007            match client {
1008                Err(error) => {
1009                    Err(io::Error::new(io::ErrorKind::NotFound, error))
1010                },
1011                Ok(client) => {
1012                    let client = formats!{
1013                             client
1014                    };
1015                    Ok(client)
1016                }
1017            }
1018        }
1019    };
1020}
1021
1022///
1023/// # Usage
1024///
1025/// ```
1026/// let find = find_one! {
1027///     connection => postgres,
1028///     model:"place",
1029///     select:{
1030///         "name"
1031///     },
1032///     conditions:{
1033///         and => {
1034///             "name" => "billionairehari"
1035///         },
1036///         or => {
1037///             "name" => "billionairehari"
1038///         }
1039///     },
1040///     order:{
1041///         "name" => "asc"
1042///     }
1043/// };
1044/// ```
1045///
1046///
1047#[cfg(feature = "async")]
1048#[macro_export]
1049macro_rules! find_one {
1050    // * included and or order //completed
1051    (connection => $connection:expr,
1052            model:$model:expr
1053            $(,select:{
1054                $($select_value:expr),*
1055            })?
1056        $(,conditions:{
1057            $(and => {
1058                $($and_values:expr => $and_value:expr),*
1059            })?
1060            $(,)?
1061            $(or =>  {
1062                $($or_value1:expr => $or_value2:expr),*
1063            })?
1064        })?
1065        $(,order : {$($target:expr => $order:expr),*})?
1066    ) =>
1067    {
1068        {
1069            use std::panic;
1070            use rusty_postgres::AsyncToSql;
1071            use rusty_postgres::formats;
1072            use rusty_postgres::tokio::io;
1073
1074            let mut selectvalue = String::new();
1075            let mut conditions = String::new();
1076            let mut and_value:Vec<&(dyn AsyncToSql + Sync)> = Vec::new();
1077            let mut order = String::new();
1078            // let mut selection = String::new();
1079            $(
1080                $(
1081                selectvalue.push_str(&format!("{},",$select_value));
1082                // selection.push_str(&format!("'{}',",$select_value));
1083                )*
1084            )?
1085            let select_value = selectvalue.trim_end_matches(",");
1086            // let selection = selection.trim_end_matches(",");
1087            // println!("{}",select_value);
1088            let mut idx = 0;
1089            $(
1090                $(
1091                $(
1092                    idx+=1;
1093                    conditions.push_str(&format!("{} = ${} AND ",$and_values,idx));
1094                    and_value.push(&$and_value);
1095                )*
1096                )?
1097            )?
1098            // $()?
1099            $(
1100                $(
1101                    $(
1102                        idx+=1;
1103                        conditions.push_str(&format!("{} = ${} OR ",$or_value1,idx));
1104                        and_value.push(&$or_value2);
1105                    )*
1106                )?
1107            )?
1108            let conditions = conditions.trim_end_matches("AND ");
1109            let conditions = conditions.trim_end_matches("OR ");
1110            $(
1111                $(
1112                if !["asc","desc","ASC","DESC"].contains(&$order) {
1113                    panic!("Provide correct order either \"asc\" nor \"desc\"");
1114                }
1115                else {
1116                    let order_ = format!("{} {},",$target,$order.to_uppercase());
1117                    order.push_str(&order_);
1118                }
1119                )*
1120            )?
1121            let order = order.trim_end_matches(",");
1122            // println!("{}",and_values);
1123            // println!("{:?}",and_value);
1124            let mut select = format!("SELECT ");
1125            if select_value.len() != 0 {
1126                let selection = format!("{}",select_value);
1127                select.push_str(&selection);
1128            }
1129            else {
1130                let selection = format!("*");
1131                select.push_str(&selection);
1132            }
1133            select.push_str(&format!(" FROM {}",$model));
1134            if conditions.len() != 0 {
1135                select.push_str(&format!(" WHERE {}",conditions));
1136            }
1137            if order.len() != 0 {
1138                select.push_str(&format!(" ORDER BY {}",order));
1139            }
1140            select.push_str(" LIMIT 1");
1141            // println!("{}",select);
1142            // FROM {} WHERE {} ORDER BY {} LIMIT 1;
1143            let client = $connection.query(&select,&and_value).await;
1144            match client {
1145                Err(error) => {
1146                    Err(io::Error::new(io::ErrorKind::NotFound, error))
1147                },
1148                Ok(client) => {
1149                    let client = formats!{
1150                             client
1151                    };
1152                    Ok(client)
1153                }
1154            }
1155        }
1156    };
1157}
1158
1159#[cfg(not(feature = "async"))]
1160#[macro_export]
1161macro_rules! delete_table {
1162    (connection => $connection:expr,model => $model:expr) => {{
1163        let delete = format!("DROP TABLE IF EXISTS {} ;", $model);
1164        $connection.execute(&delete, &[])
1165    }};
1166    (connection => $connection:expr,model => $model:expr,cascade) => {{
1167        let delete = format!("DROP TABLE IF EXISTS {} CASCADE;", $model);
1168        $connection.execute(&delete, &[])
1169    }};
1170}
1171#[cfg(feature = "async")]
1172#[macro_export]
1173macro_rules! delete_table {
1174    (connection => $connection:expr,model => $model:expr) => {{
1175        let delete = format!("DROP TABLE IF EXISTS {} ;", $model);
1176        $connection.execute(&delete, &[]).await
1177    }};
1178    (connection => $connection:expr,model => $model:expr,cascade) => {{
1179        let delete = format!("DROP TABLE IF EXISTS {} CASCADE;", $model);
1180        $connection.execute(&delete, &[]).await
1181    }};
1182}
1183
1184/// ## Returns
1185/// ```
1186/// Result<Vec<Vec<std::collections::BTreeMap<String, String>>>, io::Error>
1187/// ```
1188/// # Example
1189/// ## Basic
1190/// ```
1191///  let find = find_many! {
1192///     connection => postgres,
1193///     model:"billionaires",
1194///     select:{               // optional
1195///         "place"
1196///     },
1197///     case:{              //optional
1198///     (
1199///         "place" => ">22",
1200///         "place" => "<22",
1201///         "place" => "=22"
1202///         ) => (ok:"billion_dollar",
1203///         ok:"billionaire",
1204///         ok:"billionaire"
1205///         ,else:"trillionaire"
1206///     ) => "status"
1207///     },
1208///     conditions:{           // optional
1209///         and => {
1210///             "place" => "san"
1211///         },
1212///         or => {
1213///             "place" => "san"
1214///         }
1215///     },      
1216///     between => {                //optional
1217///         and => {
1218///             "place" => {
1219///                 "20" => "22"
1220///             }
1221///         },
1222///         or => {
1223///             "place" => {
1224///                 "20" => "22"
1225///             }
1226///         }
1227///     },
1228///     like => {               //optional
1229///         and => {
1230///             "name" => "billionaire"
1231///         },
1232///         or => {
1233///             "billionaire" => "billionaire"
1234///         }
1235///     },
1236///     inside:{                //optional
1237///         "place" => {
1238///             match:  user_id",
1239///             select:{
1240///                 "name"
1241///             },
1242///             conditions:{
1243///                 and => {
1244///                     "name" => "billionaire"
1245///                 }
1246///             },
1247///             order:6,
1248///             limit:6
1249///         }
1250///     },               
1251///     order:{                // optional
1252///         "place" => "asc"
1253///     },
1254///     limit:24,              // optional
1255///     skip:24                // optional
1256///  };
1257///  println!("{:?}", find);
1258/// ```
1259///
1260///
1261/// ## Geography Search
1262///
1263/// ```
1264/// let find = find_many! {
1265///     connection => postgres,
1266///     model:"billionaires",
1267///     select:{            // optional
1268///         "place"
1269///     },
1270///     within:{
1271///         lattitude:"12.971599",
1272///         longitude:"77.594566",
1273///         within:6                // optional
1274///     },
1275///     also_include:{
1276///         "location"
1277///     },
1278///     limit:6             // optional
1279/// };
1280/// ```
1281
1282#[cfg(not(feature = "async"))]
1283#[macro_export]
1284macro_rules! find_many {
1285    (connection => $connection:expr,
1286        model:$model:expr
1287        $(,match:$model_value:expr)?
1288        $(,select:{$($select_value:expr),*})?
1289        $(
1290            ,case:{
1291                    $(($($key:expr => $value:expr),*) => ($(ok:$ok:expr),*,else:$else:expr) => $case:expr),*
1292            }
1293        )?
1294        $(,conditions : {
1295            $(and => {
1296                $($and_key:expr => $and_value:expr),*
1297                }
1298            )?
1299            $(,)?
1300            $(
1301                or => {
1302                    $($or_key:expr => $or_value:expr),*
1303                }
1304            )?
1305        }
1306        )?
1307        $(,)?
1308        $(
1309            ,between => {
1310                $(and => {
1311                    $($between:expr => {$between_value:expr => $between_value2:expr}),*
1312                })?
1313                $(,)?
1314                $(or => {
1315                    $($between_or:expr => {$between_value_or:expr => $between_value2_or:expr}),*
1316                })?
1317            }
1318        )?
1319        $(,)?
1320        $(
1321            ,like => {
1322                $(and => {
1323                    $($like:expr => $like_value:expr),*
1324                })?
1325                $(,)?
1326                $(or => {
1327                    $($like_or:expr => $like_value_or:expr),*
1328                })?
1329            }
1330        )?
1331        $(,inside:
1332        {
1333            // (
1334            $include:expr
1335                => {
1336                    match:$include_match:expr,
1337                    $(select:
1338                        {
1339                            $($select:expr),*
1340                        }
1341                    ),*
1342                        $(,)?
1343                        $(
1344                            ,conditions: {
1345                                $(
1346                                    and => {
1347                                        $(
1348                                            $condition_key:expr => $condition_value:expr
1349                                        ),*
1350                                    }
1351                                )?
1352                                $(,)?
1353                                $(
1354                                    or => {
1355                                        $(
1356                                            $condition_or_key:expr => $condition_or_value:expr
1357                                            ),*
1358                                    }
1359                                )?
1360                            }
1361                        )?
1362                        $(,)?
1363                        $(
1364                            ,order:
1365                                {
1366                                    $(
1367                                        $order_key:expr => $order_value:expr
1368                                    )*
1369                                }
1370                        )?
1371                        $(,)?
1372                        $(
1373                            ,limit:$limit:expr
1374                        )?
1375                    }
1376                // ),*
1377        })?
1378        $(,)?
1379        $(,order:{
1380            $(
1381                $order:expr => $orderby:expr
1382            ),*
1383        })?
1384        $(,)?
1385        $(,limit:$main_limit:expr)?
1386        $(,)?
1387        $(,skip:$main_skip:expr)?
1388    ) => {
1389        {
1390            use rusty_postgres::ToSql;
1391            use std::io;
1392            use rusty_postgres::formats;
1393
1394            let mut include = String::new();
1395            let mut relation = String::new();
1396            let mut selection = String::new();
1397            let mut case = String::new();
1398            let mut table_dots = String::new();
1399
1400            let bb = $model.chars().nth(0).unwrap();
1401            let table_name = format!("{} {}",$model,bb);
1402            $(
1403                let table_dot = format!("{}.{}",bb,$model_value);
1404                table_dots.push_str(&table_dot);
1405            )?
1406            let mut values:Vec<&(dyn ToSql + Sync)> = Vec::new();
1407
1408            let mut idx = 0;
1409            $(
1410                $(
1411                    let selections = format!("{}.{},",bb,$select_value);
1412                    selection.push_str(&selections);
1413                )*
1414            )?
1415
1416            $(
1417                $(
1418                    // $(
1419                        let mut cases = String::new();
1420                    $(
1421                            idx += 1;
1422
1423                            let values_ = $value.to_string();
1424                            let value =  if values_.starts_with(">"){
1425                                let value = values_.trim_start_matches(">");
1426                                let between_and = format!(" WHEN CAST({} AS text) > ${} THEN '{}'",$key,idx,$ok);
1427                                cases.push_str(&between_and);
1428                                value
1429                                // values.push(&value);
1430                            }
1431                            else if values_.starts_with("<"){
1432                                let value = values_.trim_start_matches("<");
1433                                let between_and = format!(" WHEN CAST({} AS text) < ${} THEN '{}'",$key,idx,$ok);
1434                                cases.push_str(&between_and);
1435                                value
1436                                // values.push(&value);
1437                            }
1438                            else if values_.starts_with("="){
1439                                let value = values_.trim_start_matches("=");
1440                                let between_and = format!(" WHEN CAST({} AS text) = ${} THEN '{}'",$key,idx,$ok);
1441                                cases.push_str(&between_and);
1442                                value
1443                                // values.push(&value);
1444                            }
1445                            else {
1446                                let between_and = format!(" WHEN CAST({} AS text) = ${} THEN '{}'",$key,idx,$ok);
1447                                cases.push_str(&between_and);
1448                                // values.push(&$value);
1449                                $value
1450                            };
1451                            values.push(&value);
1452
1453                        )*
1454                        let casey = format!(" CASE {} ELSE '{}' END AS {} ",cases,$else,$case);
1455                        case.push_str(&casey);
1456                    // )*
1457                )*
1458            )?
1459            // println!("{}",case);
1460            //inside
1461            $(
1462                let mut select = String::new();
1463                let mut inside_condition = String::new();
1464                let mut select = format!("(SELECT * FROM {}",$include);
1465
1466                $(
1467                    $(
1468                        $(
1469                            idx+=1;
1470                            let and = format!("CAST({} AS text) = ${} AND ",$condition_key,idx);
1471                            inside_condition.push_str(&and);
1472
1473                            values.push(&$condition_value);
1474                        )*
1475                    )*
1476                )?
1477                // let and = format!("({})",inside_condition);
1478                $(
1479                    $(
1480                        $(
1481                            idx+=1;
1482                            let or = format!("CAST({} AS text) = ${} OR ",$condition_or_key,idx);
1483                            inside_condition.push_str(&or);
1484
1485                            values.push(&$condition_or_value);
1486                        )*
1487                    )*
1488                )?
1489                let inside_condition = inside_condition.trim_end_matches("AND ");
1490                let inside_condition = inside_condition.trim_end_matches("OR ");
1491
1492                if inside_condition.len() != 0 {
1493                    let inside_condition = format!(" WHERE {}",inside_condition);
1494                    select.push_str(&inside_condition);
1495                }
1496                let mut order = String::new();
1497                $(
1498                    $(
1499                        if ["asc","desc","ASC","DESC"].contains(&$order_value){
1500                            let orders = format!("{} {},",$order_key,$order_value.to_uppercase());
1501                            order.push_str(&orders);
1502                        }
1503                        else {
1504                            panic!("Please Provide Corrent order either ASC nor DESC")
1505                        }
1506                    )*
1507                )?
1508
1509                if order.len() != 0 {
1510                    let order = format!(" ORDER BY {}",order.trim_end_matches(","));
1511                    select.push_str(&order);
1512                }
1513
1514                let b = $include.chars().nth(0).unwrap();
1515
1516                $(
1517                    $(
1518                        let r_select = format!("{}.{},",b,$select);
1519                        relation.push_str(&r_select);
1520                    )*
1521                )*
1522
1523
1524                let mut limit = String::new();
1525                $(
1526                    let limits = format!("{}",$limit);
1527                    limit.push_str(&limits);
1528                )?
1529
1530                if limit.len() != 0 {
1531                    let limit = format!(" LIMIT {}",limit);
1532                    select.push_str(&limit);
1533                }
1534
1535                select.push_str(")");
1536
1537                // let or = format!("({})",inside_condition);
1538                // println!("{}",select);
1539
1540                let b = $include.chars().nth(0).unwrap();
1541                let r1 = format!("{} {}",$include,b);
1542                let r2 = format!("{}.{}",b,$include_match);
1543                let inside = format!("LEFT JOIN {} {} ON {} = {}",select,b,table_dot,r2);
1544                // println!("{}",inside);
1545
1546                include.push_str(&inside);
1547            )?
1548
1549            // println!("{}",include);
1550            let mut conditions = String::new();
1551            $(
1552                $(
1553                    $(
1554                        idx += 1;
1555                        let and = format!("CAST({}.{} AS text) = ${} AND ",bb,$and_key,idx);
1556                        conditions.push_str(&and);
1557
1558                        values.push(&$and_value);
1559                    )*
1560                )?
1561            )?
1562            $(
1563                $(
1564                    $(
1565                        idx += 1;
1566                        let or = format!("CAST({}.{} AS text) = ${} OR ",bb,$or_key,idx);
1567                        conditions.push_str(&or);
1568
1569                        values.push(&$or_value);
1570                    )*
1571                )?
1572            )?
1573            $(
1574                $(
1575                    $(
1576                        idx+=1;
1577                        let first = format!("${}",idx);
1578                        values.push(&$between_value);
1579                        idx+=1;
1580                        let second = format!("${}",idx);
1581                        values.push(&$between_value2);
1582                        let between = format!(" CAST({} AS text) BETWEEN {} AND {} AND ",$between,first,second);
1583                        conditions.push_str(&between);
1584                    )*
1585                )*
1586            )?
1587            $(
1588                $(
1589                    $(
1590                        idx+=1;
1591                        let first = format!("${}",idx);
1592                        values.push(&$between_value_or);
1593                        idx+=1;
1594                        let second = format!("${}",idx);
1595                        values.push(&$between_value2_or);
1596                        let between = format!(" CAST({} AS text) BETWEEN {} AND {} OR ",$between_or,first,second);
1597                        conditions.push_str(&between);
1598                    )*
1599                )*
1600            )?
1601            $(
1602                $(
1603                    $(
1604                        idx+=1;
1605                        values.push(&$like_value);
1606                        let like = format!("CAST({} AS text) LIKE '%' || ${} || '%' AND ",$like,idx);
1607                        conditions.push_str(&like);
1608                    )*
1609                )*
1610            )?
1611            $(
1612                $(
1613                    $(
1614                        idx+=1;
1615                        values.push(&$like_value_or);
1616                        let like = format!("CAST({} AS text) LIKE '%' || ${} || '%' OR ",$like_or,idx);
1617                        conditions.push_str(&like);
1618                    )*
1619                )*
1620            )?
1621            let conditions = conditions.trim_end_matches("AND ");
1622            let conditions = conditions.trim_end_matches("OR ");
1623            // $(
1624                // let mut limit = String::new();
1625                // let mut order = String::new();
1626                // // let include_table = format!("{}.{}",b,$model_value);
1627                // // let relation_table = format!("{}.{}",b,$include);
1628
1629                // let r1 = format!("{} {}",$include,b);
1630                // let r2 = format!("{}.{}",b,$match);
1631
1632                // let order = order.trim_end_matches(",");
1633                // if !limit.is_empty() && !order.is_empty() {
1634                //     let include_format = format!("LEFT JOIN {} {} ON {} = {}\r\n",select,b,table_dot,r2);
1635                //     include.push_str(&include_format);
1636                // }
1637                // else if !limit.is_empty() && order.is_empty() {
1638                //     let select = format!("(SELECT * FROM {} LIMIT {})",$include,limit);
1639                //     let include_format = format!("LEFT JOIN {} {} ON {} = {}\r\n",select,b,table_dot,r2);
1640                //     include.push_str(&include_format);
1641                // }
1642                // else if limit.is_empty() && !order.is_empty() {
1643                //     let select = format!("(SELECT * FROM {} ORDER BY {})",$include,order);
1644                //     let include_format = format!("LEFT JOIN {} {} ON {} = {}\r\n",select,b,table_dot,r2);
1645                //     include.push_str(&include_format);
1646                // }
1647                // else  {
1648                //     let include_format = format!("LEFT JOIN {} ON {} = {}\r\n",r1,table_dot,r2);
1649                //     include.push_str(&include_format);
1650                // }
1651                // println!("{}",include_format);
1652
1653            // )*
1654
1655            let mut relation = relation.trim_end_matches(",").to_string();
1656            let selection = selection.trim_end_matches(",");
1657
1658            let mut query = format!("SELECT ");
1659            if selection.len() != 0 {
1660                query.push_str(&selection);
1661            }
1662            if case.len() != 0 {
1663                let case = format!("{},",case);
1664                query.push_str(&case);
1665            }
1666            // else {
1667            //     query.push_str(&format!("{}.*,",bb));
1668            // }
1669            if relation.len() != 0 {
1670                if selection.len() != 0 {
1671                    query.push_str(&format!(",{}",relation));
1672                }
1673                else {
1674                    query.push_str(&format!("{}",relation));
1675                }
1676            }
1677            // else {
1678            //     $(
1679            //         let b = $include.chars().nth(0).unwrap();
1680            //         let r_select = format!("{}.*,",b);
1681            //         relation.push_str(&r_select);
1682            //     )*
1683            //     let relation = relation.trim_end_matches(",");
1684            //     query.push_str(relation);
1685            // }
1686            if table_name.len() != 0 {
1687                let from = format!(" FROM {} ",table_name);
1688                query.push_str(&from);
1689            }
1690            if include.len() != 0 {
1691                query.push_str(&include);
1692            }
1693            if conditions.len() != 0 {
1694                let conditions = format!(" WHERE {}",conditions);
1695                query.push_str(&conditions)
1696            }
1697            $(
1698                $(
1699                    if !["asc","desc","ASC","DESC"].contains(&$orderby){
1700                        panic!("Please Provide Correct Order ASC DESC")
1701                    }
1702                    else {
1703                        let order = format!("{} {}",$order,$orderby);
1704                        query.push_str(&format!(" ORDER BY {} {}",$order,$orderby))
1705                    }
1706                )*
1707            )?
1708            $(
1709                query.push_str(&format!(" LIMIT {}",$main_limit));
1710            )?
1711            $(
1712                query.push_str(&format!(" OFFSET {}",$main_skip));
1713            )?
1714            // println!("{}",conditions);
1715            // println!("{}",relation);
1716            // println!("{}",query);
1717            // println!("{:?}",values);
1718            let client = $connection.query(&query,&values);
1719            match client {
1720                Err(error) => {
1721                    Err(io::Error::new(io::ErrorKind::NotFound, error))
1722                },
1723                Ok(client) => {
1724                    let client = formats!{
1725                             client
1726                    };
1727                    Ok(client)
1728                }
1729            }
1730        }
1731    };
1732    (connection => $connection:expr,model:$model:expr,select:{$($select_value:expr),*},
1733    within:{
1734        lattitude:$lattitude:expr,
1735        longitude:$longitude:expr
1736        $(,within:$within:expr)?
1737    },
1738    based_on:{
1739         $location:expr
1740    }$(,limit:$limit:expr)?) => {
1741        {
1742            use rusty_postgres::ToSql;
1743            use std::io;
1744
1745            let mut selection = String::new();
1746            let mut location_value = String::new();
1747            let mut condition:Vec<&(dyn ToSql + Sync)> = Vec::new();
1748            let mut select = String::new();
1749            let mut within = String::new();
1750            let mut limit = String::new();
1751
1752
1753            $(
1754                let select_value = format!("{},",$select_value);
1755                selection.push_str(&select_value);
1756
1757                let selects = select_value.trim_end_matches(",");
1758                select.push_str(&format!("'{}',",selects));
1759            )*
1760
1761            $(
1762                within.push_str(&$within.to_string());
1763            )?
1764            $(
1765                limit.push_str(&$limit.to_string());
1766            )?
1767
1768            let select_value = format!("ST_AsGeoJson({}),",$location);
1769            selection.push_str(&select_value);
1770            select.push_str(&format!("'{}'",$location));
1771
1772            // select.push_str(&format!("'ST_AsText({})'",$location));
1773
1774            let mut idx = 0;
1775            idx+=1;
1776            let condition_longitude = format!("${}",idx);
1777            idx+=1;
1778            let condition_lattitude = format!("${}",idx);
1779            // location_value.push_str(&format!("{} {}",condition_lattitude,condition_longitude));
1780
1781            condition.push(&$longitude);
1782            condition.push(&$lattitude);
1783
1784
1785            let selection = selection.trim_end_matches(",");
1786            let select = select.trim_end_matches(",");
1787
1788            if !within.is_empty() && !limit.is_empty() {
1789                let query = format!("SELECT {} FROM {} WHERE ST_DWIthin({},ST_GeogFromText('SRID=4326;POINT('||{}||' '||{}||')'),{}) LIMIT {};",selection,$model,$location,condition_longitude,condition_lattitude,within,limit);
1790                // println!("{}",query);
1791                // println!("{:?}",condition);
1792                let client = $connection.query(&query,&condition).unwrap();
1793                // client
1794                find_many!(@format client)
1795            }
1796            else if within.is_empty() && !limit.is_empty() {
1797                let query = format!("SELECT {} FROM {} WHERE ST_DWIthin({},ST_GeogFromText('SRID=4326;POINT('||{}||' '||{}||')'),0) LIMIT {};",selection,$model,$location,condition_longitude,condition_lattitude,limit);
1798                // println!("{}",query);
1799                // println!("{:?}",condition);
1800                let client = $connection.query(&query,&condition).unwrap();
1801                // client
1802                find_many!(@format client)
1803            }
1804            else if !within.is_empty() && limit.is_empty() {
1805                let query = format!("SELECT {} FROM {} WHERE ST_DWIthin({},ST_GeogFromText('SRID=4326;POINT('||{}||' '||{}||')'),{});",selection,$model,$location,condition_longitude,condition_lattitude,within);
1806                // println!("{}",query);
1807                // println!("{:?}",condition);
1808                let client = $connection.query(&query,&condition).unwrap();
1809                // client
1810                find_many!(@format client)
1811            }
1812            else  {
1813                let query = format!("SELECT {} FROM {} WHERE ST_DWIthin({},ST_GeogFromText('SRID=4326;POINT('||{}||' '||{}||')'),0);",selection,$model,$location,condition_longitude,condition_lattitude);
1814                // println!("{}",query);
1815                // println!("{:?}",condition);
1816                let client = $connection.query(&query,&condition);
1817                // client
1818                match client {
1819                    Err(error) => {
1820                        Err(io::Error::new(io::ErrorKind::NotFound, error))
1821                    },
1822                    Ok(client) => {
1823                        let client = formats!{
1824                                 client
1825                        };
1826                        Ok(client)
1827                    }
1828                }
1829            }
1830        }
1831    };
1832}
1833/// ## Returns
1834/// ```
1835/// Result<Vec<Vec<std::collections::BTreeMap<String, String>>>, io::Error>
1836/// ```
1837/// # Example
1838/// ## Basic
1839/// ```
1840///  let find = find_many! {
1841///     connection => postgres,
1842///     model:"billionaires",
1843///     select:{               // optional
1844///         "place"
1845///     },
1846///     case:{              //optional
1847///     (
1848///         "place" => ">22",
1849///         "place" => "<22",
1850///         "place" => "=22"
1851///         ) => (ok:"billion_dollar",
1852///         ok:"billionaire",
1853///         ok:"billionaire"
1854///         ,else:"trillionaire"
1855///     ) => "status"
1856///     },
1857///     conditions:{           // optional
1858///         and => {
1859///             "place" => "san"
1860///         },
1861///         or => {
1862///             "place" => "san"
1863///         }
1864///     },      
1865///     between => {                //optional
1866///         and => {
1867///             "place" => {
1868///                 "20" => "22"
1869///             }
1870///         },
1871///         or => {
1872///             "place" => {
1873///                 "20" => "22"
1874///             }
1875///         }
1876///     },
1877///     like => {               //optional
1878///         and => {
1879///             "name" => "billionaire"
1880///         },
1881///         or => {
1882///             "billionaire" => "billionaire"
1883///         }
1884///     },
1885///     inside:{                //optional
1886///         "place" => {
1887///             match:  user_id",
1888///             select:{
1889///                 "name"
1890///             },
1891///             conditions:{
1892///                 and => {
1893///                     "name" => "billionaire"
1894///                 }
1895///             },
1896///             order:6,
1897///             limit:6
1898///         }
1899///     },               
1900///     order:{                // optional
1901///         "place" => "asc"
1902///     },
1903///     limit:24,              // optional
1904///     skip:24                // optional
1905///  };
1906///  println!("{:?}", find);
1907/// ```
1908///
1909///
1910/// ## Geography Search
1911///
1912/// ```
1913/// let find = find_many! {
1914///     connection => postgres,
1915///     model:"billionaires",
1916///     select:{            // optional
1917///         "place"
1918///     },
1919///     within:{
1920///         lattitude:"12.971599",
1921///         longitude:"77.594566",
1922///         within:6                // optional
1923///     },
1924///     also_include:{
1925///         "location"
1926///     },
1927///     limit:6             // optional
1928/// };
1929/// ```
1930#[cfg(feature = "async")]
1931#[macro_export]
1932macro_rules! find_many {
1933    (connection => $connection:expr,
1934        model:$model:expr
1935        $(,match:$model_value:expr)?
1936        $(,select:{$($select_value:expr),*})?
1937        $(
1938            ,case:{
1939                    $(($($key:expr => $value:expr),*) => ($(ok:$ok:expr),*,else:$else:expr) => $case:expr),*
1940            }
1941        )?
1942        $(,conditions : {
1943            $(and => {
1944                $($and_key:expr => $and_value:expr),*
1945                }
1946            )?
1947            $(,)?
1948            $(
1949                or => {
1950                    $($or_key:expr => $or_value:expr),*
1951                }
1952            )?
1953        }
1954        )?
1955        $(,)?
1956        $(
1957            ,between => {
1958                $(and => {
1959                    $($between:expr => {$between_value:expr => $between_value2:expr}),*
1960                })?
1961                $(,)?
1962                $(or => {
1963                    $($between_or:expr => {$between_value_or:expr => $between_value2_or:expr}),*
1964                })?
1965            }
1966        )?
1967        $(,)?
1968        $(
1969            ,like => {
1970                $(and => {
1971                    $($like:expr => $like_value:expr),*
1972                })?
1973                $(,)?
1974                $(or => {
1975                    $($like_or:expr => $like_value_or:expr),*
1976                })?
1977            }
1978        )?
1979        $(,inside:
1980        {
1981            // (
1982            $include:expr
1983                => {
1984                    match:$include_match:expr,
1985                    $(select:
1986                        {
1987                            $($select:expr),*
1988                        }
1989                    ),*
1990                        $(,)?
1991                        $(
1992                            ,conditions: {
1993                                $(
1994                                    and => {
1995                                        $(
1996                                            $condition_key:expr => $condition_value:expr
1997                                        ),*
1998                                    }
1999                                )?
2000                                $(,)?
2001                                $(
2002                                    or => {
2003                                        $(
2004                                            $condition_or_key:expr => $condition_or_value:expr
2005                                            ),*
2006                                    }
2007                                )?
2008                            }
2009                        )?
2010                        $(,)?
2011                        $(
2012                            ,order:
2013                                {
2014                                    $(
2015                                        $order_key:expr => $order_value:expr
2016                                    )*
2017                                }
2018                        )?
2019                        $(,)?
2020                        $(
2021                            ,limit:$limit:expr
2022                        )?
2023                    }
2024                // ),*
2025        })?
2026        $(,)?
2027        $(,order:{
2028            $(
2029                $order:expr => $orderby:expr
2030            ),*
2031        })?
2032        $(,)?
2033        $(,limit:$main_limit:expr)?
2034        $(,)?
2035        $(,skip:$main_skip:expr)?
2036    ) => {
2037        {
2038            use rusty_postgres::ToSql;
2039            use std::io;
2040            use rusty_postgres::formats;
2041
2042            let mut include = String::new();
2043            let mut relation = String::new();
2044            let mut selection = String::new();
2045            let mut case = String::new();
2046            let mut table_dots = String::new();
2047
2048            let bb = $model.chars().nth(0).unwrap();
2049            let table_name = format!("{} {}",$model,bb);
2050            $(
2051                let table_dot = format!("{}.{}",bb,$model_value);
2052                table_dots.push_str(&table_dot);
2053            )?
2054            let mut values:Vec<&(dyn ToSql + Sync)> = Vec::new();
2055
2056            let mut idx = 0;
2057            $(
2058                $(
2059                    let selections = format!("{}.{},",bb,$select_value);
2060                    selection.push_str(&selections);
2061                )*
2062            )?
2063
2064            $(
2065                $(
2066                    // $(
2067                        let mut cases = String::new();
2068                    $(
2069                            idx += 1;
2070
2071                            let values_ = $value.to_string();
2072                            let value =  if values_.starts_with(">"){
2073                                let value = values_.trim_start_matches(">");
2074                                let between_and = format!(" WHEN CAST({} AS text) > ${} THEN '{}'",$key,idx,$ok);
2075                                cases.push_str(&between_and);
2076                                value
2077                                // values.push(&value);
2078                            }
2079                            else if values_.starts_with("<"){
2080                                let value = values_.trim_start_matches("<");
2081                                let between_and = format!(" WHEN CAST({} AS text) < ${} THEN '{}'",$key,idx,$ok);
2082                                cases.push_str(&between_and);
2083                                value
2084                                // values.push(&value);
2085                            }
2086                            else if values_.starts_with("="){
2087                                let value = values_.trim_start_matches("=");
2088                                let between_and = format!(" WHEN CAST({} AS text) = ${} THEN '{}'",$key,idx,$ok);
2089                                cases.push_str(&between_and);
2090                                value
2091                                // values.push(&value);
2092                            }
2093                            else {
2094                                let between_and = format!(" WHEN CAST({} AS text) = ${} THEN '{}'",$key,idx,$ok);
2095                                cases.push_str(&between_and);
2096                                // values.push(&$value);
2097                                $value
2098                            };
2099                            values.push(&value);
2100
2101                        )*
2102                        let casey = format!(" CASE {} ELSE '{}' END AS {} ",cases,$else,$case);
2103                        case.push_str(&casey);
2104                    // )*
2105                )*
2106            )?
2107            // println!("{}",case);
2108            //inside
2109            $(
2110                let mut select = String::new();
2111                let mut inside_condition = String::new();
2112                let mut select = format!("(SELECT * FROM {}",$include);
2113
2114                $(
2115                    $(
2116                        $(
2117                            idx+=1;
2118                            let and = format!("CAST({} AS text) = ${} AND ",$condition_key,idx);
2119                            inside_condition.push_str(&and);
2120
2121                            values.push(&$condition_value);
2122                        )*
2123                    )*
2124                )?
2125                // let and = format!("({})",inside_condition);
2126                $(
2127                    $(
2128                        $(
2129                            idx+=1;
2130                            let or = format!("CAST({} AS text) = ${} OR ",$condition_or_key,idx);
2131                            inside_condition.push_str(&or);
2132
2133                            values.push(&$condition_or_value);
2134                        )*
2135                    )*
2136                )?
2137                let inside_condition = inside_condition.trim_end_matches("AND ");
2138                let inside_condition = inside_condition.trim_end_matches("OR ");
2139
2140                if inside_condition.len() != 0 {
2141                    let inside_condition = format!(" WHERE {}",inside_condition);
2142                    select.push_str(&inside_condition);
2143                }
2144                let mut order = String::new();
2145                $(
2146                    $(
2147                        if ["asc","desc","ASC","DESC"].contains(&$order_value){
2148                            let orders = format!("{} {},",$order_key,$order_value.to_uppercase());
2149                            order.push_str(&orders);
2150                        }
2151                        else {
2152                            panic!("Please Provide Corrent order either ASC nor DESC")
2153                        }
2154                    )*
2155                )?
2156
2157                if order.len() != 0 {
2158                    let order = format!(" ORDER BY {}",order.trim_end_matches(","));
2159                    select.push_str(&order);
2160                }
2161
2162                let b = $include.chars().nth(0).unwrap();
2163                let b = match b == bb {
2164                    true  => $include.chars().nth(1).unwrap(),
2165                    false => $include.chars().nth(0).unwrap()
2166                };
2167
2168
2169                $(
2170                    $(
2171                        let r_select = format!("{}.{},",b,$select);
2172                        relation.push_str(&r_select);
2173                    )*
2174                )*
2175
2176
2177                let mut limit = String::new();
2178                $(
2179                    let limits = format!("{}",$limit);
2180                    limit.push_str(&limits);
2181                )?
2182
2183                if limit.len() != 0 {
2184                    let limit = format!(" LIMIT {}",limit);
2185                    select.push_str(&limit);
2186                }
2187
2188                select.push_str(")");
2189
2190                // let or = format!("({})",inside_condition);
2191                // println!("{}",select);
2192
2193                // let b = $include.chars().nth(0).unwrap();
2194                let r1 = format!("{} {}",$include,b);
2195                let r2 = format!("{}.{}",b,$include_match);
2196                let inside = format!("LEFT JOIN {} {} ON {} = {}",select,b,table_dots,r2);
2197                // println!("{}",inside);
2198
2199                include.push_str(&inside);
2200            )?
2201
2202            // println!("{}",include);
2203            let mut conditions = String::new();
2204            $(
2205                $(
2206                    $(
2207                        idx += 1;
2208                        let and = format!("CAST({}.{} AS text) = ${} AND ",bb,$and_key,idx);
2209                        conditions.push_str(&and);
2210
2211                        values.push(&$and_value);
2212                    )*
2213                )?
2214            )?
2215            $(
2216                $(
2217                    $(
2218                        idx += 1;
2219                        let or = format!("CAST({}.{} AS text) = ${} OR ",bb,$or_key,idx);
2220                        conditions.push_str(&or);
2221
2222                        values.push(&$or_value);
2223                    )*
2224                )?
2225            )?
2226            $(
2227                $(
2228                    $(
2229                        idx+=1;
2230                        let first = format!("${}",idx);
2231                        values.push(&$between_value);
2232                        idx+=1;
2233                        let second = format!("${}",idx);
2234                        values.push(&$between_value2);
2235                        let between = format!(" CAST({} AS text) BETWEEN {} AND {} AND ",$between,first,second);
2236                        conditions.push_str(&between);
2237                    )*
2238                )*
2239            )?
2240            $(
2241                $(
2242                    $(
2243                        idx+=1;
2244                        let first = format!("${}",idx);
2245                        values.push(&$between_value_or);
2246                        idx+=1;
2247                        let second = format!("${}",idx);
2248                        values.push(&$between_value2_or);
2249                        let between = format!(" CAST({} AS text) BETWEEN {} AND {} OR ",$between_or,first,second);
2250                        conditions.push_str(&between);
2251                    )*
2252                )*
2253            )?
2254            $(
2255                $(
2256                    $(
2257                        idx+=1;
2258                        values.push(&$like_value);
2259                        let like = format!("CAST({} AS text) LIKE '%' || ${} || '%' AND ",$like,idx);
2260                        conditions.push_str(&like);
2261                    )*
2262                )*
2263            )?
2264            $(
2265                $(
2266                    $(
2267                        idx+=1;
2268                        values.push(&$like_value_or);
2269                        let like = format!("CAST({} AS text) LIKE '%' || ${} || '%' OR ",$like_or,idx);
2270                        conditions.push_str(&like);
2271                    )*
2272                )*
2273            )?
2274            let conditions = conditions.trim_end_matches("AND ");
2275            let conditions = conditions.trim_end_matches("OR ");
2276            // $(
2277                // let mut limit = String::new();
2278                // let mut order = String::new();
2279                // // let include_table = format!("{}.{}",b,$model_value);
2280                // // let relation_table = format!("{}.{}",b,$include);
2281
2282                // let r1 = format!("{} {}",$include,b);
2283                // let r2 = format!("{}.{}",b,$match);
2284
2285                // let order = order.trim_end_matches(",");
2286                // if !limit.is_empty() && !order.is_empty() {
2287                //     let include_format = format!("LEFT JOIN {} {} ON {} = {}\r\n",select,b,table_dot,r2);
2288                //     include.push_str(&include_format);
2289                // }
2290                // else if !limit.is_empty() && order.is_empty() {
2291                //     let select = format!("(SELECT * FROM {} LIMIT {})",$include,limit);
2292                //     let include_format = format!("LEFT JOIN {} {} ON {} = {}\r\n",select,b,table_dot,r2);
2293                //     include.push_str(&include_format);
2294                // }
2295                // else if limit.is_empty() && !order.is_empty() {
2296                //     let select = format!("(SELECT * FROM {} ORDER BY {})",$include,order);
2297                //     let include_format = format!("LEFT JOIN {} {} ON {} = {}\r\n",select,b,table_dot,r2);
2298                //     include.push_str(&include_format);
2299                // }
2300                // else  {
2301                //     let include_format = format!("LEFT JOIN {} ON {} = {}\r\n",r1,table_dot,r2);
2302                //     include.push_str(&include_format);
2303                // }
2304                // println!("{}",include_format);
2305
2306            // )*
2307
2308            let mut relation = relation.trim_end_matches(",").to_string();
2309            let selection = selection.trim_end_matches(",");
2310
2311            let mut query = format!("SELECT ");
2312            if selection.len() != 0 {
2313                query.push_str(&selection);
2314            }
2315            if case.len() != 0 {
2316                let case = format!("{},",case);
2317                query.push_str(&case);
2318            }
2319            // else {
2320            //     query.push_str(&format!("{}.*,",bb));
2321            // }
2322            if relation.len() != 0 {
2323                if selection.len() != 0 {
2324                    query.push_str(&format!(",{}",relation));
2325                }
2326                else {
2327                    query.push_str(&format!("{}",relation));
2328                }
2329            }
2330            // else {
2331            //     $(
2332            //         let b = $include.chars().nth(0).unwrap();
2333            //         let r_select = format!("{}.*,",b);
2334            //         relation.push_str(&r_select);
2335            //     )*
2336            //     let relation = relation.trim_end_matches(",");
2337            //     query.push_str(relation);
2338            // }
2339            if table_name.len() != 0 {
2340                let from = format!(" FROM {} ",table_name);
2341                query.push_str(&from);
2342            }
2343            if include.len() != 0 {
2344                query.push_str(&include);
2345            }
2346            if conditions.len() != 0 {
2347                let conditions = format!(" WHERE {}",conditions);
2348                query.push_str(&conditions)
2349            }
2350            $(
2351                $(
2352                    if !["asc","desc","ASC","DESC"].contains(&$orderby){
2353                        panic!("Please Provide Correct Order ASC DESC")
2354                    }
2355                    else {
2356                        let order = format!("{} {}",$order,$orderby);
2357                        query.push_str(&format!(" ORDER BY {} {}",$order,$orderby))
2358                    }
2359                )*
2360            )?
2361            $(
2362                query.push_str(&format!(" LIMIT {}",$main_limit));
2363            )?
2364            $(
2365                query.push_str(&format!(" OFFSET {}",$main_skip));
2366            )?
2367            // println!("{}",conditions);
2368            // println!("{}",relation);
2369            println!("{}",query);
2370            // println!("{:?}",values);
2371            let client = $connection.query(&query,&values).await;
2372            match client {
2373                Err(error) => {
2374                    Err(io::Error::new(io::ErrorKind::NotFound, error))
2375                },
2376                Ok(client) => {
2377                    let client = formats!{
2378                             client
2379                    };
2380                    Ok(client)
2381                }
2382            }
2383        }
2384    };
2385    (connection => $connection:expr,model:$model:expr,select:{$($select_value:expr),*},
2386    within:{
2387        lattitude:$lattitude:expr,
2388        longitude:$longitude:expr
2389        $(,within:$within:expr)?
2390    },
2391    based_on:{
2392         $location:expr
2393    }$(,limit:$limit:expr)?) => {
2394        {
2395            use rusty_postgres::ToSql;
2396            use std::io;
2397
2398            let mut selection = String::new();
2399            let mut location_value = String::new();
2400            let mut condition:Vec<&(dyn ToSql + Sync)> = Vec::new();
2401            let mut select = String::new();
2402            let mut within = String::new();
2403            let mut limit = String::new();
2404
2405
2406            $(
2407                let select_value = format!("{},",$select_value);
2408                selection.push_str(&select_value);
2409
2410                let selects = select_value.trim_end_matches(",");
2411                select.push_str(&format!("'{}',",selects));
2412            )*
2413
2414            $(
2415                within.push_str(&$within.to_string());
2416            )?
2417            $(
2418                limit.push_str(&$limit.to_string());
2419            )?
2420
2421            let select_value = format!("ST_AsGeoJson({}),",$location);
2422            selection.push_str(&select_value);
2423            select.push_str(&format!("'{}'",$location));
2424
2425            // select.push_str(&format!("'ST_AsText({})'",$location));
2426
2427            let mut idx = 0;
2428            idx+=1;
2429            let condition_longitude = format!("${}",idx);
2430            idx+=1;
2431            let condition_lattitude = format!("${}",idx);
2432            // location_value.push_str(&format!("{} {}",condition_lattitude,condition_longitude));
2433
2434            condition.push(&$longitude);
2435            condition.push(&$lattitude);
2436
2437
2438            let selection = selection.trim_end_matches(",");
2439            let select = select.trim_end_matches(",");
2440
2441            if !within.is_empty() && !limit.is_empty() {
2442                let query = format!("SELECT {} FROM {} WHERE ST_DWIthin({},ST_GeogFromText('SRID=4326;POINT('||{}||' '||{}||')'),{}) LIMIT {};",selection,$model,$location,condition_longitude,condition_lattitude,within,limit);
2443                // println!("{}",query);
2444                // println!("{:?}",condition);
2445                let client = $connection.query(&query,&condition).unwrap();
2446                // client
2447                find_many!(@format client)
2448            }
2449            else if within.is_empty() && !limit.is_empty() {
2450                let query = format!("SELECT {} FROM {} WHERE ST_DWIthin({},ST_GeogFromText('SRID=4326;POINT('||{}||' '||{}||')'),0) LIMIT {};",selection,$model,$location,condition_longitude,condition_lattitude,limit);
2451                // println!("{}",query);
2452                // println!("{:?}",condition);
2453                let client = $connection.query(&query,&condition).unwrap();
2454                // client
2455                find_many!(@format client)
2456            }
2457            else if !within.is_empty() && limit.is_empty() {
2458                let query = format!("SELECT {} FROM {} WHERE ST_DWIthin({},ST_GeogFromText('SRID=4326;POINT('||{}||' '||{}||')'),{});",selection,$model,$location,condition_longitude,condition_lattitude,within);
2459                // println!("{}",query);
2460                // println!("{:?}",condition);
2461                let client = $connection.query(&query,&condition).unwrap();
2462                // client
2463                find_many!(@format client)
2464            }
2465            else  {
2466                let query = format!("SELECT {} FROM {} WHERE ST_DWIthin({},ST_GeogFromText('SRID=4326;POINT('||{}||' '||{}||')'),0);",selection,$model,$location,condition_longitude,condition_lattitude);
2467                // println!("{}",query);
2468                // println!("{:?}",condition);
2469                let client = $connection.query(&query,&condition).await;
2470                // client
2471                match client {
2472                    Err(error) => {
2473                        Err(io::Error::new(io::ErrorKind::NotFound, error))
2474                    },
2475                    Ok(client) => {
2476                        let client = formats!{
2477                                 client
2478                        };
2479                        Ok(client)
2480                    }
2481                }
2482            }
2483        }
2484    };
2485}
2486
2487///
2488/// # Usage
2489///
2490/// ```
2491/// let drop = delete_many!{
2492///     connection => postgres,
2493///     model:"place"
2494/// };
2495/// ```
2496///
2497///
2498#[cfg(not(feature = "async"))]
2499#[macro_export]
2500macro_rules! delete_many {
2501    // * all rows
2502    (connection => $connection:expr,model:$model:expr) => {{
2503        let delete = format!("DELETE FROM {};", $model);
2504        // println!("{}", delete);
2505        $connection.execute(&delete, &[])
2506    }};
2507}
2508
2509///
2510/// # Usage
2511///
2512/// ```
2513/// let drop = delete_many!{
2514///     connection => postgres,
2515///     model:"place"
2516/// };
2517/// ```
2518///
2519///
2520#[cfg(feature = "async")]
2521#[macro_export]
2522macro_rules! delete_many {
2523    // * all rows
2524    (connection => $connection:expr,model:$model:expr) => {{
2525        let delete = format!("DELETE FROM {};", $model);
2526        // println!("{}", delete);
2527        $connection.execute(&delete, &[]).await
2528    }};
2529}
2530
2531/// # Example
2532/// ```
2533/// let delete = delete! {
2534///     connection => postgres,
2535///     model:"billionaires",
2536///     select:{                // Optional
2537///         "place"
2538///     },
2539///     conditions:{            // Optional
2540///         and => {            // Optional
2541///             "place" => 24 as i32
2542///         },
2543///         or => {             // Optional
2544///             "place" => 24 as i32
2545///         }
2546///     },
2547///     cascade:true            // Optional
2548/// };
2549/// ```
2550#[cfg(not(feature = "async"))]
2551#[macro_export]
2552macro_rules! delete {
2553    // * and select
2554    (connection => $connection:expr,
2555        model:$model:expr
2556    $(,
2557        select:{
2558            $($value:expr),*
2559        }
2560    )?
2561    $(
2562        ,conditions:{
2563            $(and => {
2564                $($cak:expr => $cav:expr),*
2565            })?
2566            $(,)?
2567            $(or => {
2568                $($cok:expr => $cov:expr),*
2569            })?
2570        }
2571    )?
2572    $(
2573        ,between => {
2574            $(and => {
2575                $($between:expr => {$between_value:expr => $between_value2:expr}),*
2576            })?
2577            $(,)?
2578            $(or => {
2579                $($between_or:expr => {$between_value_or:expr => $between_value2_or:expr}),*
2580            })?
2581        }
2582    )?
2583    $(
2584        ,cascade:$cascade:expr
2585    )?
2586        ) => {{
2587        use rusty_postgres::ToSql;
2588        use rusty_postgres::formats;
2589        use std::io;
2590
2591        let mut value:Vec<&(dyn ToSql + Sync)> = Vec::new();
2592        let mut selection = String::new();
2593        let mut condition = String::new();
2594
2595        if $model.is_empty() {
2596            panic!("{}","Please Provide Table Name")
2597        }
2598
2599        let mut idx = 0;
2600
2601        // conditions
2602
2603        $(
2604            $(
2605                $(
2606                    if $cak.is_empty(){
2607                        panic!("{}","Please Provide Condition for AND Values")
2608                    }
2609                    idx += 1;
2610                    let and=  format!("{} = ${} AND ",$cak,idx);
2611                    condition.push_str(&and);
2612                    value.push(&$cav);
2613                )*
2614            )?
2615            $(
2616                $(
2617                    if $cok.is_empty(){
2618                        panic!("{}","Please Provide Condition for OR Values")
2619                    }
2620                    idx += 1;
2621                    let and=  format!("{} = ${} OR ",$cok,idx);
2622                    condition.push_str(&and);
2623                    value.push(&$cov);
2624                )*
2625            )?
2626        )?
2627        $(
2628            $(
2629                $(
2630                    idx+=1;
2631                    let first = format!("${}",idx);
2632                    value.push(&$between_value);
2633                    idx+=1;
2634                    let second = format!("${}",idx);
2635                    value.push(&$between_value2);
2636                    let between = format!(" CAST({} AS text) BETWEEN {} AND {} AND ",$between,first,second);
2637                    condition.push_str(&between);
2638                )*
2639            )*
2640        )?
2641        $(
2642            $(
2643                $(
2644                    idx+=1;
2645                    let first = format!("${}",idx);
2646                    value.push(&$between_value_or);
2647                    idx+=1;
2648                    let second = format!("${}",idx);
2649                    value.push(&$between_value2_or);
2650                    let between = format!(" CAST({} AS text) BETWEEN {} AND {} OR ",$between_or,first,second);
2651                    condition.push_str(&between);
2652                )*
2653            )*
2654        )?
2655        let condition = condition.trim_end_matches("OR ");
2656        let condition = condition.trim_end_matches("AND ");
2657
2658        $(
2659            $(
2660                if $value.is_empty(){
2661                    panic!("{}","Please Provide Select Values")
2662                }
2663                selection.push_str(&format!("{},",$value));
2664            )*
2665        )?
2666        let selection = selection.trim_end_matches(",");
2667
2668        let mut delete = format!("DELETE FROM {}",$model);
2669        if condition.len() != 0 {
2670            let condition = format!(" WHERE {}",condition);
2671            delete.push_str(&condition);
2672        }
2673        if selection.len() != 0 {
2674            let selection = format!(" RETURNING {}",selection);
2675            delete.push_str(&selection);
2676        }
2677        $(
2678            if $cascade {
2679                delete.push_str(" CASECADE");
2680            }
2681        )?
2682        delete.push_str(";");
2683        // println!("{}",delete);
2684        // println!("{:?}",value);
2685        let client = $connection.query(&delete,&value);
2686        // println!("{:?}",client);
2687        match client {
2688            Err(error) => {
2689                Err(io::Error::new(io::ErrorKind::NotFound, error))
2690            },
2691            Ok(client) => {
2692                let client = formats!{
2693                         client
2694                };
2695                Ok(client)
2696            }
2697        }
2698
2699    }};
2700}
2701/// # Example
2702/// ```
2703/// let delete = delete! {
2704///     connection => postgres,
2705///     model:"billionaires",
2706///     select:{                // Optional
2707///         "place"
2708///     },
2709///     conditions:{            // Optional
2710///         and => {            // Optional
2711///             "place" => 24 as i32
2712///         },
2713///         or => {             // Optional
2714///             "place" => 24 as i32
2715///         }
2716///     },
2717///     cascade:true            // Optional
2718/// };
2719/// ```
2720#[cfg(feature = "async")]
2721#[macro_export]
2722macro_rules! delete {
2723    // * and select
2724    (connection => $connection:expr,
2725        model:$model:expr
2726    $(,
2727        select:{
2728            $($value:expr),*
2729        }
2730    )?
2731    $(
2732        ,conditions:{
2733            $(and => {
2734                $($cak:expr => $cav:expr),*
2735            })?
2736            $(,)?
2737            $(or => {
2738                $($cok:expr => $cov:expr),*
2739            })?
2740        }
2741    )?
2742    $(
2743        ,between => {
2744            $(and => {
2745                $($between:expr => {$between_value:expr => $between_value2:expr}),*
2746            })?
2747            $(,)?
2748            $(or => {
2749                $($between_or:expr => {$between_value_or:expr => $between_value2_or:expr}),*
2750            })?
2751        }
2752    )?
2753    $(
2754        ,cascade:$cascade:expr
2755    )?
2756        ) => {{
2757        use rusty_postgres::ToSql;
2758        use rusty_postgres::formats;
2759        use std::io;
2760
2761        let mut value:Vec<&(dyn ToSql + Sync)> = Vec::new();
2762        let mut selection = String::new();
2763        let mut condition = String::new();
2764
2765        if $model.is_empty() {
2766            panic!("{}","Please Provide Table Name")
2767        }
2768
2769        let mut idx = 0;
2770
2771        // conditions
2772
2773        $(
2774            $(
2775                $(
2776                    if $cak.is_empty(){
2777                        panic!("{}","Please Provide Condition for AND Values")
2778                    }
2779                    idx += 1;
2780                    let and=  format!("{} = ${} AND ",$cak,idx);
2781                    condition.push_str(&and);
2782                    value.push(&$cav);
2783                )*
2784            )?
2785            $(
2786                $(
2787                    if $cok.is_empty(){
2788                        panic!("{}","Please Provide Condition for OR Values")
2789                    }
2790                    idx += 1;
2791                    let and=  format!("{} = ${} OR ",$cok,idx);
2792                    condition.push_str(&and);
2793                    value.push(&$cov);
2794                )*
2795            )?
2796        )?
2797        $(
2798            $(
2799                $(
2800                    idx+=1;
2801                    let first = format!("${}",idx);
2802                    value.push(&$between_value);
2803                    idx+=1;
2804                    let second = format!("${}",idx);
2805                    value.push(&$between_value2);
2806                    let between = format!(" CAST({} AS text) BETWEEN {} AND {} AND ",$between,first,second);
2807                    condition.push_str(&between);
2808                )*
2809            )*
2810        )?
2811        $(
2812            $(
2813                $(
2814                    idx+=1;
2815                    let first = format!("${}",idx);
2816                    value.push(&$between_value_or);
2817                    idx+=1;
2818                    let second = format!("${}",idx);
2819                    value.push(&$between_value2_or);
2820                    let between = format!(" CAST({} AS text) BETWEEN {} AND {} OR ",$between_or,first,second);
2821                    condition.push_str(&between);
2822                )*
2823            )*
2824        )?
2825        let condition = condition.trim_end_matches("OR ");
2826        let condition = condition.trim_end_matches("AND ");
2827
2828        $(
2829            $(
2830                if $value.is_empty(){
2831                    panic!("{}","Please Provide Select Values")
2832                }
2833                selection.push_str(&format!("{},",$value));
2834            )*
2835        )?
2836        let selection = selection.trim_end_matches(",");
2837
2838        let mut delete = format!("DELETE FROM {}",$model);
2839        if condition.len() != 0 {
2840            let condition = format!(" WHERE {}",condition);
2841            delete.push_str(&condition);
2842        }
2843        if selection.len() != 0 {
2844            let selection = format!(" RETURNING {}",selection);
2845            delete.push_str(&selection);
2846        }
2847        $(
2848            if $cascade {
2849                delete.push_str(" CASECADE");
2850            }
2851        )?
2852        delete.push_str(";");
2853        // println!("{}",delete);
2854        // println!("{:?}",value);
2855        let client = $connection.query(&delete,&value).await;
2856        // println!("{:?}",client);
2857        match client {
2858            Err(error) => {
2859                Err(io::Error::new(io::ErrorKind::NotFound, error))
2860            },
2861            Ok(client) => {
2862                let client = formats!{
2863                         client
2864                };
2865                Ok(client)
2866            }
2867        }
2868
2869    }};
2870}
2871
2872///
2873/// # Example
2874///
2875/// ```
2876/// let update = update! {
2877///     connection => postgres,
2878///     model:"place",
2879///     select:{
2880///         "id"
2881///     },
2882///     data:{
2883///         "name" => "billionairehari"
2884///     },
2885///     conditions:{
2886///         and => {
2887///             "name" => "billionairehari"
2888///         },
2889///         or => {
2890///             "" => ""
2891///         }
2892///     }
2893/// };
2894/// ```
2895///
2896/// ## Usage
2897/// ```
2898/// let update = update! {
2899///        connection => postgres,
2900///        model:"billionaires",
2901///        match:"id",
2902///        inside:{
2903///            "place"  => {
2904///                match:   user_id",
2905///                conditions:{
2906///                    and => {
2907///                        "name" => "billionaires",
2908///                         user_id" => "c4a97a50-8679-4f85-a1d8-5bba0113b596"
2909///                    }
2910///                },
2911///                data:{
2912///                    "name" => "billionairehari"
2913///                },
2914///                select:{
2915///                    "name"
2916///                }
2917///            }
2918///        }
2919///    };
2920/// ```
2921///
2922#[cfg(not(feature = "async"))]
2923#[macro_export]
2924// * data conditions
2925macro_rules! update {
2926    // * data select conditions
2927    (connection => $connection:expr,model : $model:expr
2928    $(,select:{
2929        $($select:expr),*
2930    })?
2931      ,data:{
2932        $($from:expr => $data:expr),*
2933    }
2934    $(,conditions:{
2935        $(and => {$($conditions:expr => $value:expr),*})?
2936        $(,)?
2937        $(or => {$($conditions_or:expr => $value_or:expr),*})?
2938    })?
2939    $(
2940        ,between => {
2941            $(and => {
2942                $($between:expr => {$between_value:expr => $between_value2:expr}),*
2943            })?
2944            $(,)?
2945            $(or => {
2946                $($between_or:expr => {$between_value_or:expr => $between_value2_or:expr}),*
2947            })?
2948        }
2949    )?
2950    ) => {{
2951        use rusty_postgres::ToSql;
2952        use rusty_postgres::formats;
2953        use std::io;
2954
2955        let mut condition = String::new();
2956        let mut set = String::new();
2957        let mut select = String::new();
2958        let mut idx = 0;
2959        let mut value:Vec<&(dyn ToSql + Sync)> = Vec::new();
2960
2961        $(
2962            idx+=1;
2963            let update = format!("{} = ${},",$from,idx);
2964            set.push_str(&update);
2965
2966            value.push(&$data);
2967        )*
2968        $(
2969            $(
2970                $(
2971                    idx+=1;
2972                    let and = format!("CAST({} AS TEXT) = ${} AND ",$conditions,idx);
2973                    condition.push_str(&and);
2974
2975                    value.push(&$value);
2976                )*
2977            )?
2978        )?
2979        $(
2980            $(
2981                $(
2982                    idx+=1;
2983                    let or = format!("CAST({} AS TEXT) = ${} OR ",$conditions_or,idx);
2984                    condition.push_str(&or);
2985
2986                    value.push(&$value_or);
2987                )*
2988            )?
2989        )?
2990        $(
2991            $(
2992                $(
2993                    idx+=1;
2994                    let first = format!("${}",idx);
2995                    value.push(&$between_value);
2996                    idx+=1;
2997                    let second = format!("${}",idx);
2998                    value.push(&$between_value2);
2999                    let between = format!(" CAST({} AS text) BETWEEN {} AND {} AND ",$between,first,second);
3000                    condition.push_str(&between);
3001                )*
3002            )*
3003        )?
3004        $(
3005            $(
3006                $(
3007                    idx+=1;
3008                    let first = format!("${}",idx);
3009                    value.push(&$between_value_or);
3010                    idx+=1;
3011                    let second = format!("${}",idx);
3012                    value.push(&$between_value2_or);
3013                    let between = format!(" CAST({} AS text) BETWEEN {} AND {} OR ",$between_or,first,second);
3014                    condition.push_str(&between);
3015                )*
3016            )*
3017        )?
3018        $(
3019            $(
3020                let selection = format!("{},",$select);
3021                select.push_str(&selection);
3022            )*
3023        )?
3024        let set = set.trim_end_matches(",");
3025        let select = select.trim_end_matches(",");
3026        let condition = condition.trim_end_matches("OR ");
3027        let condition = condition.trim_end_matches("AND ");
3028        // println!("{}",set);
3029        // println!("{}",select);
3030        // println!("{}",condition);
3031        // println!("{:?}",value);
3032        let mut query = format!("UPDATE {} SET {}",$model,set);
3033        if condition.len() != 0 {
3034            let condition = format!(" WHERE {}",condition);
3035            query.push_str(&condition);
3036        }
3037        if select.len() != 0 {
3038            let select = format!(" RETURNING {}",select);
3039            query.push_str(&select);
3040        }
3041        query.push_str(";");
3042        // println!("{}",query);
3043        let client = $connection.query(&query,&value);
3044        match client {
3045            Err(error) => {
3046                Err(io::Error::new(io::ErrorKind::NotFound, error))
3047            },
3048            Ok(client) => {
3049                let client = formats!{
3050                        client
3051                };
3052                Ok(client)
3053            }
3054        }
3055    }};
3056    (connection => $connection:expr,
3057        model:$model:expr,
3058        match:$model_value:expr
3059        $(,select:{
3060            $($select:expr),*
3061        })?
3062        $(,conditions:{
3063            $(and => {$($conditions:expr => $value:expr),*})?
3064            $(or => {$($conditions_or:expr => $value_or:expr),*})?
3065        })?
3066        $(
3067            ,between => {
3068                $(and => {
3069                    $($between:expr => {$between_value:expr => $between_value2:expr}),*
3070                })?
3071                $(,)?
3072                $(or => {
3073                    $($between_or:expr => {$between_value_or:expr => $between_value2_or:expr}),*
3074                })?
3075            }
3076        )?
3077        ,inside:
3078        {
3079            $from:expr => {
3080                match:$match:expr,
3081                data:{
3082                    $($data_from:expr => $data_value:expr),*
3083                }
3084                // $(,)?
3085                $(,conditions : {
3086                    $(and => {$($and_from_key:expr => $and_from_value:expr),*})?
3087                    $(,)?
3088                    $(or => {$($or_from_key:expr => $or_from_value:expr),*})?
3089                })?
3090                $(,)?
3091                $(
3092                    ,select:{
3093                    $(
3094                        $select_from:expr
3095                    ),*
3096                    }
3097                )?
3098                $(
3099                    ,between => {
3100                        $(and => {
3101                            $($from_between:expr => {$from_between_value:expr => $from_between_value2:expr}),*
3102                        })?
3103                        $(,)?
3104                        $(or => {
3105                            $($from_between_or:expr => {$from_between_value_or:expr => $from_between_value2_or:expr}),*
3106                        })?
3107                    }
3108                )?
3109            }
3110        }
3111        ) => {{
3112            use rusty_postgres::ToSql;
3113            use std::io;
3114            // use rusty_postgres::Uuid;
3115
3116
3117            let mut relation = String::new();
3118            let mut value:Vec<&(dyn ToSql + Sync)> = Vec::new();
3119            let mut updates = String::new();
3120            use rusty_postgres::formats;
3121
3122            // $(
3123                // $(
3124                let mut idx = 0;
3125            $(
3126                let from = $from;
3127                let mut selection = String::new();
3128                let mut set = String::new();
3129                let mut conditions = String::new();
3130
3131                idx +=1;
3132                let update = format!("{} = ${},",$data_from,idx);
3133                    // println!("{}",update);
3134                set.push_str(&update);
3135                value.push(&$data_value);
3136
3137            )*
3138            $(
3139                $(
3140                    $(
3141                        idx+=1;
3142                        // let b = $from.chars().nth(0).unwrap();
3143                        let condition = format!("CAST({}.{} AS text) = ${} AND ",$from,$and_from_key,idx);
3144                        conditions.push_str(&condition);
3145
3146                        value.push(&$and_from_value);
3147                    )*
3148                )?
3149                $(
3150                    $(
3151                        idx+=1;
3152                        let condition = format!("CAST({}.{} AS text) = ${} OR ",$from,$or_from_key,idx);
3153                        conditions.push_str(&condition);
3154
3155                        value.push(&$or_from_value);
3156                    )*
3157                )?
3158            )*
3159            $(
3160                $(
3161                    $(
3162                        idx+=1;
3163                        let and = format!("CAST({}.{} AS TEXT) = ${} AND ",$model,$conditions,idx);
3164                        conditions.push_str(&and);
3165
3166                        value.push(&$value);
3167                    )*
3168                )?
3169            )?
3170            $(
3171                $(
3172                    $(
3173                        idx+=1;
3174                        let or = format!("CAST({}.{} AS TEXT) = ${} OR ",$model,$conditions_or,idx);
3175                        conditions.push_str(&or);
3176
3177                        value.push(&$value_or);
3178                    )*
3179                )?
3180            )?
3181            $(
3182                $(
3183                    $(
3184                        idx+=1;
3185                        let first = format!("${}",idx);
3186                        value.push(&$between_value);
3187                        idx+=1;
3188                        let second = format!("${}",idx);
3189                        value.push(&$between_value2);
3190                        let between = format!(" CAST({}.{} AS text) BETWEEN {} AND {} AND ",$model,$between,first,second);
3191                        conditions.push_str(&between);
3192                    )*
3193                )*
3194            )?
3195            $(
3196                $(
3197                    $(
3198                        idx+=1;
3199                        let first = format!("${}",idx);
3200                        value.push(&$between_value_or);
3201                        idx+=1;
3202                        let second = format!("${}",idx);
3203                        value.push(&$between_value2_or);
3204                        let between = format!(" CAST({}.{} AS text) BETWEEN {} AND {} OR ",$model,$between_or,first,second);
3205                        conditions.push_str(&between);
3206                    )*
3207                )*
3208            )?
3209            $(
3210                $(
3211                    $(
3212                        idx+=1;
3213                        let first = format!("${}",idx);
3214                        value.push(&$from_between_value);
3215                        idx+=1;
3216                        let second = format!("${}",idx);
3217                        value.push(&$from_between_value2);
3218                        let between = format!(" CAST({}.{} AS text) BETWEEN {} AND {} AND ",$from,$from_between,first,second);
3219                        conditions.push_str(&between);
3220                    )*
3221                )*
3222            )?
3223            $(
3224                $(
3225                    $(
3226                        idx+=1;
3227                        let first = format!("${}",idx);
3228                        value.push(&$from_between_value_or);
3229                        idx+=1;
3230                        let second = format!("${}",idx);
3231                        value.push(&$from_between_value2_or);
3232                        let between = format!(" CAST({}.{} AS text) BETWEEN {} AND {} OR ",$from,$from_between_or,first,second);
3233                        conditions.push_str(&between);
3234                    )*
3235                )*
3236            )?
3237            $(
3238                $(
3239                    let select = format!("{},",$select_from);
3240                    selection.push_str(&select);
3241                )*
3242                let conditions = conditions.trim_end_matches("AND ");
3243                let conditions = conditions.trim_end_matches("OR ");
3244                let mut condition = format!("{}.{} = {}.{} AND ",$model,$model_value,$from,$match);
3245                if conditions.len() != 0 {
3246                    condition.push_str(&format!("({})",conditions));
3247                }
3248                let condition = condition.trim_end_matches("AND ");
3249                let condition = condition.trim_end_matches("OR ");
3250                let selection = selection.trim_end_matches(",");
3251                let set = set.trim_end_matches(",");
3252                // println!("{}",set);
3253                let mut update = format!("UPDATE {}",$from);
3254                if set.len() != 0 {
3255                    let set = format!(" SET {}",set);
3256                    update.push_str(&set);
3257                }
3258                update.push_str(&format!(" FROM {}",$model));
3259                if condition.len() != 0 {
3260                    let condition = format!(" WHERE {}",condition);
3261                    update.push_str(&condition);
3262                }
3263                if selection.len() != 0 {
3264                    let selection = format!(" RETURNING {}",selection);
3265                    update.push_str(&selection);
3266                }
3267                update.push_str(";");
3268                // println!("{}",update);
3269                updates.push_str(&update);
3270            )*
3271            // )*
3272            // let transactions = format!("{}",updates);
3273            // println!("{}",transactions);
3274                // )*
3275            // )?
3276            // println!("{}",updates);
3277            // println!("{:?}",value);
3278            let client = $connection.query(&updates,&value);
3279            // println!("{:?}",client);
3280            match client {
3281                Err(error) => {
3282                    Err(io::Error::new(io::ErrorKind::NotFound, error))
3283                },
3284                Ok(client) => {
3285                    let client = formats!{
3286                             client
3287                    };
3288                    Ok(client)
3289                }
3290            }
3291        }};
3292}
3293
3294///
3295/// # Example
3296///
3297/// ```
3298/// let update = update! {
3299///     connection => postgres,
3300///     model:"place",
3301///     select:{
3302///         "id"
3303///     },
3304///     data:{
3305///         "name" => "billionairehari"
3306///     },
3307///     conditions:{
3308///         and => {
3309///             "name" => "billionairehari"
3310///         },
3311///         or => {
3312///             "" => ""
3313///         }
3314///     }
3315/// };
3316/// ```
3317///
3318/// ## Usage
3319/// ```
3320/// let update = update! {
3321///        connection => postgres,
3322///        model:"billionaires",
3323///        match:"id",
3324///        inside:{
3325///            "place"  => {
3326///                match:   user_id",
3327///                conditions:{
3328///                    and => {
3329///                        "name" => "billionaires",
3330///                         user_id" => "c4a97a50-8679-4f85-a1d8-5bba0113b596"
3331///                    }
3332///                },
3333///                data:{
3334///                    "name" => "billionairehari"
3335///                },
3336///                select:{
3337///                    "name"
3338///                }
3339///            }
3340///        }
3341///    };
3342/// ```
3343///
3344#[cfg(feature = "async")]
3345#[macro_export]
3346// * data conditions
3347macro_rules! update {
3348    // * data select conditions
3349    (connection => $connection:expr,model : $model:expr
3350    $(,select:{
3351        $($select:expr),*
3352    })?
3353      ,data:{
3354        $($from:expr => $data:expr),*
3355    }
3356    $(,conditions:{
3357        $(and => {$($conditions:expr => $value:expr),*})?
3358        $(,)?
3359        $(or => {$($conditions_or:expr => $value_or:expr),*})?
3360    })?
3361    $(
3362        ,between => {
3363            $(and => {
3364                $($between:expr => {$between_value:expr => $between_value2:expr}),*
3365            })?
3366            $(,)?
3367            $(or => {
3368                $($between_or:expr => {$between_value_or:expr => $between_value2_or:expr}),*
3369            })?
3370        }
3371    )?
3372    ) => {{
3373        use rusty_postgres::ToSql;
3374        use rusty_postgres::formats;
3375        use std::io;
3376
3377        let mut condition = String::new();
3378        let mut set = String::new();
3379        let mut select = String::new();
3380        let mut idx = 0;
3381        let mut value:Vec<&(dyn ToSql + Sync)> = Vec::new();
3382
3383        $(
3384            idx+=1;
3385            let update = format!("{} = ${},",$from,idx);
3386            set.push_str(&update);
3387
3388            value.push(&$data);
3389        )*
3390        $(
3391            $(
3392                $(
3393                    idx+=1;
3394                    let and = format!("CAST({} AS TEXT) = ${} AND ",$conditions,idx);
3395                    condition.push_str(&and);
3396
3397                    value.push(&$value);
3398                )*
3399            )?
3400        )?
3401        $(
3402            $(
3403                $(
3404                    idx+=1;
3405                    let or = format!("CAST({} AS TEXT) = ${} OR ",$conditions_or,idx);
3406                    condition.push_str(&or);
3407
3408                    value.push(&$value_or);
3409                )*
3410            )?
3411        )?
3412        $(
3413            $(
3414                $(
3415                    idx+=1;
3416                    let first = format!("${}",idx);
3417                    value.push(&$between_value);
3418                    idx+=1;
3419                    let second = format!("${}",idx);
3420                    value.push(&$between_value2);
3421                    let between = format!(" CAST({} AS text) BETWEEN {} AND {} AND ",$between,first,second);
3422                    condition.push_str(&between);
3423                )*
3424            )*
3425        )?
3426        $(
3427            $(
3428                $(
3429                    idx+=1;
3430                    let first = format!("${}",idx);
3431                    value.push(&$between_value_or);
3432                    idx+=1;
3433                    let second = format!("${}",idx);
3434                    value.push(&$between_value2_or);
3435                    let between = format!(" CAST({} AS text) BETWEEN {} AND {} OR ",$between_or,first,second);
3436                    condition.push_str(&between);
3437                )*
3438            )*
3439        )?
3440        $(
3441            $(
3442                let selection = format!("{},",$select);
3443                select.push_str(&selection);
3444            )*
3445        )?
3446        let set = set.trim_end_matches(",");
3447        let select = select.trim_end_matches(",");
3448        let condition = condition.trim_end_matches("OR ");
3449        let condition = condition.trim_end_matches("AND ");
3450        // println!("{}",set);
3451        // println!("{}",select);
3452        // println!("{}",condition);
3453        // println!("{:?}",value);
3454        let mut query = format!("UPDATE {} SET {}",$model,set);
3455        if condition.len() != 0 {
3456            let condition = format!(" WHERE {}",condition);
3457            query.push_str(&condition);
3458        }
3459        if select.len() != 0 {
3460            let select = format!(" RETURNING {}",select);
3461            query.push_str(&select);
3462        }
3463        query.push_str(";");
3464        // println!("{}",query);
3465        let client = $connection.query(&query,&value).await;
3466        match client {
3467            Err(error) => {
3468                Err(io::Error::new(io::ErrorKind::NotFound, error))
3469            },
3470            Ok(client) => {
3471                let client = formats!{
3472                        client
3473                };
3474                Ok(client)
3475            }
3476        }
3477    }};
3478    (connection => $connection:expr,
3479        model:$model:expr,
3480        match:$model_value:expr
3481        $(,select:{
3482            $($select:expr),*
3483        })?
3484        $(,conditions:{
3485            $(and => {$($conditions:expr => $value:expr),*})?
3486            $(or => {$($conditions_or:expr => $value_or:expr),*})?
3487        })?
3488        $(
3489            ,between => {
3490                $(and => {
3491                    $($between:expr => {$between_value:expr => $between_value2:expr}),*
3492                })?
3493                $(,)?
3494                $(or => {
3495                    $($between_or:expr => {$between_value_or:expr => $between_value2_or:expr}),*
3496                })?
3497            }
3498        )?
3499        ,inside:
3500        {
3501            $from:expr => {
3502                match:$match:expr,
3503                data:{
3504                    $($data_from:expr => $data_value:expr),*
3505                }
3506                // $(,)?
3507                $(,conditions : {
3508                    $(and => {$($and_from_key:expr => $and_from_value:expr),*})?
3509                    $(,)?
3510                    $(or => {$($or_from_key:expr => $or_from_value:expr),*})?
3511                })?
3512                $(,)?
3513                $(
3514                    ,select:{
3515                    $(
3516                        $select_from:expr
3517                    ),*
3518                    }
3519                )?
3520                $(
3521                    ,between => {
3522                        $(and => {
3523                            $($from_between:expr => {$from_between_value:expr => $from_between_value2:expr}),*
3524                        })?
3525                        $(,)?
3526                        $(or => {
3527                            $($from_between_or:expr => {$from_between_value_or:expr => $from_between_value2_or:expr}),*
3528                        })?
3529                    }
3530                )?
3531            }
3532        }
3533        ) => {{
3534            use rusty_postgres::ToSql;
3535            use std::io;
3536            // use rusty_postgres::Uuid;
3537
3538
3539            let mut relation = String::new();
3540            let mut value:Vec<&(dyn ToSql + Sync)> = Vec::new();
3541            let mut updates = String::new();
3542            use rusty_postgres::formats;
3543
3544            // $(
3545                // $(
3546                let mut idx = 0;
3547            $(
3548                let from = $from;
3549                let mut selection = String::new();
3550                let mut set = String::new();
3551                let mut conditions = String::new();
3552
3553                idx +=1;
3554                let update = format!("{} = ${},",$data_from,idx);
3555                    // println!("{}",update);
3556                set.push_str(&update);
3557                value.push(&$data_value);
3558
3559            )*
3560            $(
3561                $(
3562                    $(
3563                        idx+=1;
3564                        // let b = $from.chars().nth(0).unwrap();
3565                        let condition = format!("CAST({}.{} AS text) = ${} AND ",$from,$and_from_key,idx);
3566                        conditions.push_str(&condition);
3567
3568                        value.push(&$and_from_value);
3569                    )*
3570                )?
3571                $(
3572                    $(
3573                        idx+=1;
3574                        let condition = format!("CAST({}.{} AS text) = ${} OR ",$from,$or_from_key,idx);
3575                        conditions.push_str(&condition);
3576
3577                        value.push(&$or_from_value);
3578                    )*
3579                )?
3580            )*
3581            $(
3582                $(
3583                    $(
3584                        idx+=1;
3585                        let and = format!("CAST({}.{} AS TEXT) = ${} AND ",$model,$conditions,idx);
3586                        conditions.push_str(&and);
3587
3588                        value.push(&$value);
3589                    )*
3590                )?
3591            )?
3592            $(
3593                $(
3594                    $(
3595                        idx+=1;
3596                        let or = format!("CAST({}.{} AS TEXT) = ${} OR ",$model,$conditions_or,idx);
3597                        conditions.push_str(&or);
3598
3599                        value.push(&$value_or);
3600                    )*
3601                )?
3602            )?
3603            $(
3604                $(
3605                    $(
3606                        idx+=1;
3607                        let first = format!("${}",idx);
3608                        value.push(&$between_value);
3609                        idx+=1;
3610                        let second = format!("${}",idx);
3611                        value.push(&$between_value2);
3612                        let between = format!(" CAST({}.{} AS text) BETWEEN {} AND {} AND ",$model,$between,first,second);
3613                        conditions.push_str(&between);
3614                    )*
3615                )*
3616            )?
3617            $(
3618                $(
3619                    $(
3620                        idx+=1;
3621                        let first = format!("${}",idx);
3622                        value.push(&$between_value_or);
3623                        idx+=1;
3624                        let second = format!("${}",idx);
3625                        value.push(&$between_value2_or);
3626                        let between = format!(" CAST({}.{} AS text) BETWEEN {} AND {} OR ",$model,$between_or,first,second);
3627                        conditions.push_str(&between);
3628                    )*
3629                )*
3630            )?
3631            $(
3632                $(
3633                    $(
3634                        idx+=1;
3635                        let first = format!("${}",idx);
3636                        value.push(&$from_between_value);
3637                        idx+=1;
3638                        let second = format!("${}",idx);
3639                        value.push(&$from_between_value2);
3640                        let between = format!(" CAST({}.{} AS text) BETWEEN {} AND {} AND ",$from,$from_between,first,second);
3641                        conditions.push_str(&between);
3642                    )*
3643                )*
3644            )?
3645            $(
3646                $(
3647                    $(
3648                        idx+=1;
3649                        let first = format!("${}",idx);
3650                        value.push(&$from_between_value_or);
3651                        idx+=1;
3652                        let second = format!("${}",idx);
3653                        value.push(&$from_between_value2_or);
3654                        let between = format!(" CAST({}.{} AS text) BETWEEN {} AND {} OR ",$from,$from_between_or,first,second);
3655                        conditions.push_str(&between);
3656                    )*
3657                )*
3658            )?
3659            $(
3660                $(
3661                    let select = format!("{},",$select_from);
3662                    selection.push_str(&select);
3663                )*
3664                let conditions = conditions.trim_end_matches("AND ");
3665                let conditions = conditions.trim_end_matches("OR ");
3666                let mut condition = format!("{}.{} = {}.{} AND ",$model,$model_value,$from,$match);
3667                if conditions.len() != 0 {
3668                    condition.push_str(&format!("({})",conditions));
3669                }
3670                let condition = condition.trim_end_matches("AND ");
3671                let condition = condition.trim_end_matches("OR ");
3672                let selection = selection.trim_end_matches(",");
3673                let set = set.trim_end_matches(",");
3674                // println!("{}",set);
3675                let mut update = format!("UPDATE {}",$from);
3676                if set.len() != 0 {
3677                    let set = format!(" SET {}",set);
3678                    update.push_str(&set);
3679                }
3680                update.push_str(&format!(" FROM {}",$model));
3681                if condition.len() != 0 {
3682                    let condition = format!(" WHERE {}",condition);
3683                    update.push_str(&condition);
3684                }
3685                if selection.len() != 0 {
3686                    let selection = format!(" RETURNING {}",selection);
3687                    update.push_str(&selection);
3688                }
3689                update.push_str(";");
3690                // println!("{}",update);
3691                updates.push_str(&update);
3692            )*
3693            // )*
3694            // let transactions = format!("{}",updates);
3695            // println!("{}",transactions);
3696                // )*
3697            // )?
3698            // println!("{}",updates);
3699            // println!("{:?}",value);
3700            let client = $connection.query(&updates,&value).await;
3701            // println!("{:?}",client);
3702            match client {
3703                Err(error) => {
3704                    Err(io::Error::new(io::ErrorKind::NotFound, error))
3705                },
3706                Ok(client) => {
3707                    let client = formats!{
3708                             client
3709                    };
3710                    Ok(client)
3711                }
3712            }
3713        }};
3714}
3715
3716///
3717/// # Example
3718///
3719/// ```
3720/// let create = create! {
3721///     connection => postgres,
3722///     model:"shop",
3723///     data:{
3724///         "place" => "san",
3725///         "age" => 24 as i32,
3726///         "bool" => true
3727///     }
3728/// };
3729/// ```
3730///
3731///```
3732/// let create = create! {
3733///     connection => postgres,
3734///     model:  user_",
3735///     data:{
3736///         "story" => "billionairehari",
3737///         "age" => 24 as i32
3738///     },
3739///     select:{
3740///         "id"
3741///     }
3742/// };
3743/// ```
3744#[cfg(not(feature = "async"))]
3745#[macro_export]
3746macro_rules! create {
3747    (connection => $connection:expr,model:$model:expr,data:{
3748        $($from:expr => $data:expr),*
3749    }
3750    $(
3751        ,select:{
3752            $($select_value:expr),*
3753        }
3754    )?) => {
3755        {
3756        use rusty_postgres::ToSql;
3757        use rusty_postgres::formats;
3758        use std::io;
3759
3760        let mut data = String::new();
3761        let mut data_value = String::new();
3762        let mut value:Vec<&(dyn ToSql + Sync)> = Vec::new();
3763        let mut select_value = String::new();
3764        let mut idx = 0;
3765        $(
3766            idx += 1;
3767            let create = format!("{},",$from);
3768            data.push_str(&create);
3769
3770            if $data.to_string().starts_with("SRID") {
3771                let datavalue = format!("ST_GeogFromText(${}),",idx);
3772                data_value.push_str(&datavalue);
3773            }
3774            else {
3775                let datavalue = format!("${},",idx);
3776                data_value.push_str(&datavalue);
3777            }
3778
3779                value.push(&$data);
3780        )*
3781        $(
3782            $(
3783                select_value.push_str(&format!("{},",$select_value));
3784            )*
3785        )?
3786        let data = data.trim_end_matches(",");
3787        let data_value = data_value.trim_end_matches(",");
3788        let select = select_value.trim_end_matches(",");
3789        let mut create = format!("INSERT INTO {} ({}) VALUES ({})",$model,data,data_value);
3790        // println!("{}",create);
3791        if select_value.len() != 0 {
3792            create.push_str(&format!(" RETURNING {};",select))
3793        }
3794        // println!("{:?}",create);
3795
3796        let client = $connection.query(&create,&value);
3797        match client {
3798            Err(error) => {
3799                Err(io::Error::new(io::ErrorKind::NotFound, error))
3800            },
3801            Ok(client) => {
3802                let client = formats!{
3803                         client
3804                };
3805                Ok(client)
3806            }
3807        }
3808    }
3809    }
3810}
3811
3812///
3813/// # Example
3814///
3815/// ```
3816/// let create = create! {
3817///     connection => postgres,
3818///     model:"shop",
3819///     data:{
3820///         "place" => "san",
3821///         "age" => 24 as i32,
3822///         "bool" => true
3823///     }
3824/// };
3825/// ```
3826///
3827///```
3828/// let create = create! {
3829///     connection => postgres,
3830///     model:  user_",
3831///     data:{
3832///         "story" => "billionairehari",
3833///         "age" => 24 as i32
3834///     },
3835///     select:{
3836///         "id"
3837///     }
3838/// };
3839/// ```
3840#[cfg(feature = "async")]
3841#[macro_export]
3842macro_rules! create {
3843    (connection => $connection:expr,model:$model:expr,data:{
3844        $($from:expr => $data:expr),*
3845    }
3846    $(
3847        ,select:{
3848            $($select_value:expr),*
3849        }
3850    )?) => {
3851        {
3852        use rusty_postgres::ToSql;
3853        use rusty_postgres::formats;
3854        use std::io;
3855
3856        let mut data = String::new();
3857        let mut data_value = String::new();
3858        let mut value:Vec<&(dyn ToSql + Sync)> = Vec::new();
3859        let mut select_value = String::new();
3860        let mut idx = 0;
3861        $(
3862            idx += 1;
3863            let create = format!("{},",$from);
3864            data.push_str(&create);
3865
3866            if $data.to_string().starts_with("SRID") {
3867                let datavalue = format!("ST_GeogFromText(${}),",idx);
3868                data_value.push_str(&datavalue);
3869            }
3870            else {
3871                let datavalue = format!("${},",idx);
3872                data_value.push_str(&datavalue);
3873            }
3874
3875                value.push(&$data);
3876        )*
3877        $(
3878            $(
3879                select_value.push_str(&format!("{},",$select_value));
3880            )*
3881        )?
3882        let data = data.trim_end_matches(",");
3883        let data_value = data_value.trim_end_matches(",");
3884        let select = select_value.trim_end_matches(",");
3885        let mut create = format!("INSERT INTO {} ({}) VALUES ({})",$model,data,data_value);
3886        // println!("{}",create);
3887        if select_value.len() != 0 {
3888            create.push_str(&format!(" RETURNING {};",select))
3889        }
3890        // println!("{:?}",create);
3891
3892        let client = $connection.query(&create,&value).await;
3893        match client {
3894            Err(error) => {
3895                Err(io::Error::new(io::ErrorKind::NotFound, error))
3896            },
3897            Ok(client) => {
3898                let client = formats!{
3899                         client
3900                };
3901                Ok(client)
3902            }
3903        }
3904    }
3905    }
3906}
3907
3908#[cfg(not(feature = "async"))]
3909#[macro_export]
3910macro_rules! transaction {
3911    (connection => $connection:expr,begin) => {
3912        let begin = $connection.execute("BEGIN;", &[]).unwrap();
3913        // println!("{}", begin);
3914    };
3915    (connection => $connection:expr,commit) => {
3916        let commit = $connection.execute("COMMIT;", &[]).unwrap();
3917        // println!("{}", commit);
3918    };
3919}
3920
3921#[cfg(feature = "async")]
3922#[macro_export]
3923macro_rules! transaction {
3924    (connection => $connection:expr,begin) => {
3925        let begin = $connection.execute("BEGIN;", &[]).await.unwrap();
3926        // println!("{}", begin);
3927    };
3928    (connection => $connection:expr,commit) => {
3929        let commit = $connection.execute("COMMIT;", &[]).await.unwrap();
3930        // println!("{}", commit);
3931    };
3932}
3933#[cfg(not(feature = "async"))]
3934#[macro_export]
3935macro_rules! show_index_list {
3936    (connection => $connection:expr,model:$model:expr) => {{
3937        use std::collections::HashMap;
3938
3939        let mut models = HashMap::new();
3940        let mut show = Vec::new();
3941        // let mut show = show.clone();
3942        let index = format!("SELECT * from pg_indexes where tablename = '{}'", $model);
3943        let result = $connection.query(&index, &[]).unwrap();
3944        for result in result.iter() {
3945            let mut models = models.clone();
3946            // let first: String = result.get(0);
3947            let second: String = result.get(1);
3948            let third: String = result.get(2);
3949            // println!("{} = {}", second, third);
3950            models.insert(second, third);
3951            show.push(models);
3952        }
3953        show
3954    }};
3955}
3956#[cfg(feature = "async")]
3957#[macro_export]
3958macro_rules! show_index_list {
3959    (connection => $connection:expr,model:$model:expr) => {{
3960        use std::collections::HashMap;
3961
3962        let mut models = HashMap::new();
3963        let mut show = Vec::new();
3964        // let mut show = show.clone();
3965        let index = format!("SELECT * from pg_indexes where tablename = '{}'", $model);
3966        let result = $connection.query(&index, &[]).await.unwrap();
3967        for result in result.iter() {
3968            let mut models = models.clone();
3969            // let first: String = result.get(0);
3970            let second: String = result.get(1);
3971            let third: String = result.get(2);
3972            // println!("{} = {}", second, third);
3973            models.insert(second, third);
3974            show.push(models);
3975        }
3976        show
3977    }};
3978}
3979
3980#[cfg(not(feature = "async"))]
3981#[macro_export]
3982macro_rules! create_index {
3983    (connection => $connection:expr,model:$model:expr,name:$name:expr,index:{$($value:expr),*}) => {
3984        {
3985            let mut index = String::new();
3986        $(
3987            index.push_str(&format!("{},",$value));
3988        )*
3989        let index = index.trim_end_matches(",");
3990        let value = format!("CREATE INDEX index_{} ON {} ({})",$name,$model,index);
3991        // println!("{}",value);
3992        $connection.execute(&value,&[])
3993    }
3994    };
3995}
3996#[cfg(feature = "async")]
3997#[macro_export]
3998macro_rules! create_index {
3999    (connection => $connection:expr,model:$model:expr,name:$name:expr,index:{$($value:expr),*}) => {
4000        {
4001            let mut index = String::new();
4002        $(
4003            index.push_str(&format!("{},",$value));
4004        )*
4005        let index = index.trim_end_matches(",");
4006        let value = format!("CREATE INDEX index_{} ON {} ({})",$name,$model,index);
4007        // println!("{}",value);
4008        $connection.execute(&value,&[]).await
4009    }
4010    };
4011}
4012
4013#[cfg(not(feature = "async"))]
4014#[cfg(feature = "brin_index")]
4015/// Used for time
4016#[macro_export]
4017macro_rules! create_brin_index {
4018    (connection => $connection:expr,model:$model:expr,name:$name:expr,index:{$($value:expr),*}) => {
4019        {
4020            let mut index = String::new();
4021        $(
4022            index.push_str(&format!("{},",$value));
4023        )*
4024        let index = index.trim_end_matches(",");
4025        let value = format!("CREATE INDEX index_{} ON {} USING brin({})",$name,$model,index);
4026        // println!("{}",value);
4027        $connection.execute(&value,&[])
4028    }
4029    };
4030}
4031#[cfg(feature = "async")]
4032#[cfg(feature = "async_brin_index")]
4033/// Used for time
4034#[macro_export]
4035macro_rules! create_brin_index {
4036    (connection => $connection:expr,model:$model:expr,name:$name:expr,index:{$($value:expr),*}) => {
4037        {
4038            let mut index = String::new();
4039        $(
4040            index.push_str(&format!("{},",$value));
4041        )*
4042        let index = index.trim_end_matches(",");
4043        let value = format!("CREATE INDEX index_{} ON {} USING brin({})",$name,$model,index);
4044        // println!("{}",value);
4045        $connection.execute(&value,&[]).await
4046    }
4047    };
4048}
4049
4050#[cfg(not(feature = "async"))]
4051#[cfg(feature = "geography")]
4052/// Used for json search
4053#[macro_export]
4054macro_rules! create_gin_index {
4055    (connection => $connection:expr,
4056        model:$model:expr,
4057        full_text:{
4058            name:$name:expr,index:{$($value:expr),*}
4059        }) => {
4060        {
4061            let mut index = String::new();
4062        $(
4063            index.push_str(&format!("{},",$value));
4064        )*
4065        let index = index.trim_end_matches(",");
4066        let value = format!("CREATE INDEX index_{} ON {} USING gin(to_tsvector('english',{}))",$name,$model,index);
4067        // println!("{}",value);
4068        $connection.execute(&value,&[])
4069    }
4070    };
4071    (connection => $connection:expr,
4072        model:$model:expr,
4073        pattern_match:{
4074            name:$name:expr,index:{$($value:expr),*}
4075        }) => {
4076        {
4077            let mut index = String::new();
4078        $(
4079            index.push_str(&format!("{},",$value));
4080        )*
4081        let index = index.trim_end_matches(",");
4082        let extension = format!("CREATE EXTENSION IF NOT EXISTS pg_trgm;");
4083        let value = format!("CREATE INDEX index_{} ON {} USING gin({} gin_trgm_ops);",$name,$model,index);
4084        // println!("{}",value);
4085        $connection.execute(&extension,&[]);
4086        $connection.execute(&value,&[])
4087    }
4088    };
4089}
4090
4091#[cfg(feature = "async")]
4092#[cfg(feature = "geography")]
4093/// Used for json search
4094#[macro_export]
4095macro_rules! create_gin_index {
4096    (connection => $connection:expr,
4097        model:$model:expr,
4098        full_text:{
4099            name:$name:expr,index:{$($value:expr),*}
4100        }) => {
4101        {
4102            let mut index = String::new();
4103        $(
4104            index.push_str(&format!("{},",$value));
4105        )*
4106        let index = index.trim_end_matches(",");
4107        let value = format!("CREATE INDEX index_{} ON {} USING gin(to_tsvector('english',{}))",$name,$model,index);
4108        // println!("{}",value);
4109        $connection.execute(&value,&[]).await
4110    }
4111    };
4112    (connection => $connection:expr,
4113        model:$model:expr,
4114        pattern_match:{
4115            name:$name:expr,index:{$($value:expr),*}
4116        }) => {
4117        {
4118            let mut index = String::new();
4119        $(
4120            index.push_str(&format!("{},",$value));
4121        )*
4122        let index = index.trim_end_matches(",");
4123        let extension = format!("CREATE EXTENSION IF NOT EXISTS pg_trgm;");
4124        let value = format!("CREATE INDEX index_{} ON {} USING gin({} gin_trgm_ops);",$name,$model,index);
4125        // println!("{}",value);
4126        $connection.execute(&extension,&[]).await;
4127        $connection.execute(&value,&[]).await
4128    }
4129    };
4130}
4131/// search
4132///
4133/// # Example
4134///
4135/// ```
4136/// let search = similar_search {
4137///     connection => postgres,
4138///     model:"place",
4139///     similarity:{
4140///         score:"0.6", //similarity score
4141///         believe:"name" //based_on
4142///         text:"san" //text
4143///     },
4144///     order_by:{              //optional
4145///         order:"asc",
4146///         believe:"name" //based
4147///     }
4148/// }
4149/// ```
4150///
4151#[cfg(not(feature = "async"))]
4152#[cfg(feature = "similar_search")]
4153#[macro_export]
4154macro_rules! similar_search {
4155    (connection => $connection:expr,
4156        model:$model:expr,
4157        similarity:{
4158        score:$score:expr,
4159        believe:$believe:expr,
4160        text:$text:expr
4161    }
4162    $(,order_by:{
4163        order:$order:expr,
4164        believe:$o_believe:expr,
4165        text:$o_text:expr
4166    })?
4167) => {{
4168        use rusty_postgres::{NaiveDate, NaiveDateTime, NaiveTime};
4169        use std::panic;
4170        use std::collections::{BTreeMap, HashMap};
4171        use rusty_postgres::Uuid;
4172        use rusty_postgres::formats;
4173        use std::io;
4174
4175        let mut search = format!(
4176            "SELECT * FROM {} WHERE similarity({},'{}') > {} ",
4177            $model, $believe, $text, $score
4178        );
4179        $(
4180            let order = format!("ORDER BY similarity({},'{}') {}", $o_believe, $o_text, $order);
4181            search.push_str(&order);
4182        )?
4183        // println!("{}", search);
4184        let client = $connection.query(&search, &[]);
4185        match client {
4186            Err(error) => {
4187                Err(io::Error::new(io::ErrorKind::NotFound, error))
4188            },
4189            Ok(client) => {
4190                let client = formats!{
4191                         client
4192                };
4193                Ok(client)
4194            }
4195        }
4196    }};
4197}
4198/// search
4199///
4200/// # Example
4201///
4202/// ```
4203/// let search = similar_search {
4204///     connection => postgres,
4205///     model:"place",
4206///     similarity:{
4207///         score:"0.6", //similarity score
4208///         believe:"name" //based_on
4209///         text:"san" //text
4210///     },
4211///     order_by:{              //optional
4212///         order:"asc",
4213///         believe:"name" //based
4214///     }
4215/// }
4216/// ```
4217///
4218#[cfg(feature = "async")]
4219#[cfg(feature = "async_similar_search")]
4220#[macro_export]
4221macro_rules! similar_search {
4222    (connection => $connection:expr,
4223        model:$model:expr,
4224        similarity:{
4225        score:$score:expr,
4226        believe:$believe:expr,
4227        text:$text:expr
4228    }
4229    $(,order_by:{
4230        order:$order:expr,
4231        believe:$o_believe:expr,
4232        text:$o_text:expr
4233    })?
4234) => {{
4235        use rusty_postgres::{NaiveDate, NaiveDateTime, NaiveTime};
4236        use std::panic;
4237        use std::collections::{BTreeMap, HashMap};
4238        use rusty_postgres::Uuid;
4239        use rusty_postgres::formats;
4240        use std::io;
4241
4242        let mut search = format!(
4243            "SELECT * FROM {} WHERE similarity({},'{}') > {} ",
4244            $model, $believe, $text, $score
4245        );
4246        $(
4247            let order = format!("ORDER BY similarity({},'{}') {}", $o_believe, $o_text, $order);
4248            search.push_str(&order);
4249        )?
4250        // println!("{}", search);
4251        let client = $connection.query(&search, &[]).await;
4252        match client {
4253            Err(error) => {
4254                Err(io::Error::new(io::ErrorKind::NotFound, error))
4255            },
4256            Ok(client) => {
4257                let client = formats!{
4258                         client
4259                };
4260                Ok(client)
4261            }
4262        }
4263    }};
4264}
4265
4266// macro_rules! geo_loc_search {
4267//     (connection => $connection:expr,mode:$mode:expr,radius:$radius:expr,) => {};
4268// }
4269
4270#[cfg(not(feature = "async"))]
4271#[macro_export]
4272macro_rules! table_structure {
4273    (connection =>  $connection:expr,model:$model:expr) => {{
4274        use std::collections::HashMap;
4275
4276        let table = format!(
4277            "SELECT column_name,data_type FROM information_schema.columns WHERE table_name = '{}';",
4278            $model
4279        );
4280        // println!("{}",table);
4281        let client = $connection.query(&table, &[]).unwrap();
4282        // println!("{:?}",client);
4283        let mut hashmap = HashMap::new();
4284        for client in client.iter() {
4285            let first: String = client.get(0);
4286            let second: String = client.get(1);
4287            // println!("{} = {}",first,second);
4288            hashmap.insert(first, second);
4289        }
4290        hashmap
4291    }};
4292}
4293
4294#[cfg(feature = "async")]
4295#[macro_export]
4296macro_rules! table_structure {
4297    (connection =>  $connection:expr,model:$model:expr) => {{
4298        use std::collections::HashMap;
4299
4300        let table = format!(
4301            "SELECT column_name,data_type FROM information_schema.columns WHERE table_name = '{}';",
4302            $model
4303        );
4304        // println!("{}",table);
4305        let client = $connection.query(&table, &[]).await.unwrap();
4306        // println!("{:?}",client);
4307        let mut hashmap = HashMap::new();
4308        for client in client.iter() {
4309            let first: String = client.get(0);
4310            let second: String = client.get(1);
4311            // println!("{} = {}",first,second);
4312            hashmap.insert(first, second);
4313        }
4314        hashmap
4315    }};
4316}
4317///
4318/// # Usage
4319///
4320/// ```
4321/// let count = count! {
4322///     connection => postgres,
4323///     model:"place",
4324///     count:{
4325///         "name"
4326///     },
4327///     conditions:{
4328///         and => {
4329///             "name" => "billionaires"
4330///         }
4331///     },
4332///     group_by:{
4333///         "name"
4334///     }
4335/// };
4336/// ```
4337///
4338///
4339#[cfg(not(feature = "async"))]
4340#[cfg(feature = "count")]
4341#[macro_export]
4342macro_rules! count {
4343    (connection => $connection:expr,
4344    model:$model:expr,
4345    count:{
4346        $($count_value:expr),*
4347    },
4348    $(
4349        conditions:{
4350            $(and => {$($condition:expr => $value:expr),*})?
4351            $(or => {$($or_condition:expr => $or_value:expr),*})?
4352        }
4353    )?
4354    $(
4355       ,group_by:{
4356            $($group_value:expr),*
4357         }
4358    )?
4359    ) => {{
4360        use std::collections::HashMap;
4361        use rusty_postgres::ToSql;
4362
4363         let mut value = String::new();
4364         let mut conditions = String::new();
4365         let mut values:Vec<&(dyn ToSql + Sync)> = Vec::new();
4366         let mut groupby = String::new();
4367         let mut idx = 0;
4368         $(
4369             value.push_str(&format!("{},",&$count_value));
4370         )*
4371        $(
4372            $(
4373                groupby.push_str(&format!("{},",&$group_value));
4374            )*
4375        )?
4376         $(
4377            $(
4378                $(
4379                    idx += 1;
4380                    conditions.push_str(&format!("CAST({} AS TEXT) = ${} AND ",$condition,idx));
4381                    values.push(&$value);
4382                )*
4383            )?
4384        )?
4385        $(
4386            $(
4387                $(
4388                idx += 1;
4389                conditions.push_str(&format!("CAST({} AS TEXT) = ${} OR ",$or_condition,idx));
4390                values.push(&$or_value);
4391                )*
4392            )?
4393        )?
4394         let value = value.trim_end_matches(",");
4395         let conditions = conditions.trim_end_matches("AND ");
4396         let conditions = conditions.trim_end_matches("OR ");
4397         let groupby = groupby.trim_end_matches(",");
4398         let mut count = format!("SELECT COUNT(DISTINCT({})) FROM {}", value,$model);
4399        //  println!("{}",count);
4400        //  println!("{:?}",values);
4401        if conditions.len() != 0 {
4402            count.push_str(&format!(" WHERE {}",conditions));
4403        }
4404        if groupby.len() != 0 {
4405            count.push_str(&format!(" GROUP BY {}",groupby));
4406        }
4407        count.push_str(";");
4408        // println!("{}",count);
4409         let result = $connection.query(&count, &values).unwrap();
4410        //  println!("{:?}",result);
4411         let mut z = HashMap::new();
4412         for count in result.iter() {
4413             let count: i64 = count.get(0);
4414             z.insert("count", count);
4415         }
4416        //  z.insert("c","c");
4417         z
4418     }};
4419}
4420///
4421/// # Usage
4422///
4423/// ```
4424/// let count = count! {
4425///     connection => postgres,
4426///     model:"place",
4427///     count:{
4428///         "name"
4429///     },
4430///     conditions:{
4431///         and => {
4432///             "name" => "billionaires"
4433///         }
4434///     },
4435///     group_by:{
4436///         "name"
4437///     }
4438/// };
4439/// ```
4440///
4441///
4442#[cfg(feature = "async")]
4443#[cfg(feature = "async_count")]
4444#[macro_export]
4445macro_rules! count {
4446    (connection => $connection:expr,
4447    model:$model:expr,
4448    count:{
4449        $($count_value:expr),*
4450    },
4451    $(
4452        conditions:{
4453            $(and => {$($condition:expr => $value:expr),*})?
4454            $(or => {$($or_condition:expr => $or_value:expr),*})?
4455        }
4456    )?
4457    $(
4458       ,group_by:{
4459            $($group_value:expr),*
4460         }
4461    )?
4462    ) => {{
4463        use std::collections::HashMap;
4464        use rusty_postgres::ToSql;
4465
4466         let mut value = String::new();
4467         let mut conditions = String::new();
4468         let mut values:Vec<&(dyn ToSql + Sync)> = Vec::new();
4469         let mut groupby = String::new();
4470         let mut idx = 0;
4471         $(
4472             value.push_str(&format!("{},",&$count_value));
4473         )*
4474        $(
4475            $(
4476                groupby.push_str(&format!("{},",&$group_value));
4477            )*
4478        )?
4479         $(
4480            $(
4481                $(
4482                    idx += 1;
4483                    conditions.push_str(&format!("CAST({} AS TEXT) = ${} AND ",$condition,idx));
4484                    values.push(&$value);
4485                )*
4486            )?
4487        )?
4488        $(
4489            $(
4490                $(
4491                idx += 1;
4492                conditions.push_str(&format!("CAST({} AS TEXT) = ${} OR ",$or_condition,idx));
4493                values.push(&$or_value);
4494                )*
4495            )?
4496        )?
4497         let value = value.trim_end_matches(",");
4498         let conditions = conditions.trim_end_matches("AND ");
4499         let conditions = conditions.trim_end_matches("OR ");
4500         let groupby = groupby.trim_end_matches(",");
4501         let mut count = format!("SELECT COUNT(DISTINCT({})) FROM {}", value,$model);
4502        //  println!("{}",count);
4503        //  println!("{:?}",values);
4504        if conditions.len() != 0 {
4505            count.push_str(&format!(" WHERE {}",conditions));
4506        }
4507        if groupby.len() != 0 {
4508            count.push_str(&format!(" GROUP BY {}",groupby));
4509        }
4510        count.push_str(";");
4511        // println!("{}",count);
4512         let result = $connection.query(&count, &values).await.unwrap();
4513        //  println!("{:?}",result);
4514         let mut z = HashMap::new();
4515         for count in result.iter() {
4516             let count: i64 = count.get(0);
4517             z.insert("count", count);
4518         }
4519        //  z.insert("c","c");
4520         z
4521     }};
4522}
4523
4524///
4525/// # Usage
4526///
4527/// ```
4528/// let search = full_search! {
4529///     connection => postgres,
4530///     model:"place",
4531///     based_on:"name",
4532///     search:{
4533///         value:"billionaire"
4534///     },
4535///     select:{
4536///         ,"name"
4537///     },
4538///     take:6,
4539///     skip:0
4540/// };
4541/// ```
4542///
4543#[cfg(not(feature = "async"))]
4544#[cfg(feature = "full_search")]
4545#[macro_export]
4546macro_rules! full_search {
4547    (connection => $connection:expr,model:$model:expr,based_on:$search:expr,search:{
4548        value:$value:expr
4549    }$(
4550        ,select:{
4551            $($select:expr),*
4552        }
4553    )?
4554    $(,take:$take:expr)?
4555    $(,skip:$skip:expr)?
4556    ) => {{
4557        use std::io;
4558        use rusty_postgres::formats;
4559        let mut selection = String::new();
4560        $(
4561            $(
4562                selection.push_str(&format!("{},",$select));
4563            )*
4564        )?
4565        let selection = selection.trim_end_matches(",");
4566
4567        let mut query = format!("SELECT ");
4568        // println!("{}",rank);
4569
4570        if selection.len() != 0 {
4571            query.push_str(&format!("{}",selection));
4572        }else {
4573            query.push_str("*");
4574        }
4575        query.push_str(&format!(" FROM {} WHERE to_tsvector('english',CAST({} AS TEXT)) @@  to_tsquery(CAST('{}' AS TEXT))",$model, $search, $value));
4576        $(
4577            query.push_str(&format!(" LIMIT {}",$take));
4578        )?
4579        $(
4580            query.push_str(&format!(" OFFSET {}",$skip));
4581        )?
4582        let client = $connection.query(&query, &[]);
4583        match client {
4584            Err(error) => {
4585                Err(io::Error::new(io::ErrorKind::NotFound, error))
4586            },
4587            Ok(client) => {
4588                let client = formats!{
4589                         client
4590                };
4591                Ok(client)
4592            }
4593        }
4594    }};
4595}
4596///
4597/// # Usage
4598///
4599/// ```
4600/// let search = full_search! {
4601///     connection => postgres,
4602///     model:"place",
4603///     based_on:"name",
4604///     search:{
4605///         value:"billionaire"
4606///     },
4607///     select:{
4608///         ,"name"
4609///     },
4610///     take:6,
4611///     skip:0
4612/// };
4613/// ```
4614///
4615#[cfg(feature = "async")]
4616#[cfg(feature = "async_full_search")]
4617#[macro_export]
4618macro_rules! full_search {
4619    (connection => $connection:expr,model:$model:expr,based_on:$search:expr,search:{
4620        value:$value:expr
4621    }$(
4622        ,select:{
4623            $($select:expr),*
4624        }
4625    )?
4626    $(,take:$take:expr)?
4627    $(,skip:$skip:expr)?
4628    ) => {{
4629        use std::io;
4630        use rusty_postgres::formats;
4631        let mut selection = String::new();
4632        $(
4633            $(
4634                selection.push_str(&format!("{},",$select));
4635            )*
4636        )?
4637        let selection = selection.trim_end_matches(",");
4638
4639        let mut query = format!("SELECT ");
4640        // println!("{}",rank);
4641
4642        if selection.len() != 0 {
4643            query.push_str(&format!("{}",selection));
4644        }else {
4645            query.push_str("*");
4646        }
4647        query.push_str(&format!(" FROM {} WHERE to_tsvector('english',CAST({} AS TEXT)) @@  to_tsquery(CAST('{}' AS TEXT))",$model, $search, $value));
4648        $(
4649            query.push_str(&format!(" LIMIT {}",$take));
4650        )?
4651        $(
4652            query.push_str(&format!(" OFFSET {}",$skip));
4653        )?
4654        let client = $connection.query(&query, &[]).await;
4655        match client {
4656            Err(error) => {
4657                Err(io::Error::new(io::ErrorKind::NotFound, error))
4658            },
4659            Ok(client) => {
4660                let client = formats!{
4661                         client
4662                };
4663                Ok(client)
4664            }
4665        }
4666    }};
4667}
4668
4669///
4670/// # Usage
4671///
4672/// ```
4673/// let search = ranked_search! {
4674///     connection => postgres,
4675///     model:"place",
4676///     based_on:"name",
4677///     search:{
4678///         value:"billionaire"
4679///     },
4680///     select:{
4681///         "name"
4682///     }
4683/// };
4684/// ```
4685///
4686///
4687#[cfg(not(feature = "async"))]
4688#[cfg(feature = "ranked_search")]
4689#[macro_export]
4690macro_rules! ranked_search {
4691    (connection => $connection:expr,model:$model:expr,based_on:$search:expr,search:{
4692        value:$value:expr
4693    },$(
4694        select:{
4695            $($select:expr),*
4696        }
4697    )?) => {{
4698        use std::io;
4699        use rusty_postgres::formats;
4700
4701        #[derive(Debug,Clone)]
4702        struct Score {
4703            score:f32,
4704            data:String
4705        };
4706        let mut select = String::new();
4707        let mut selection = String::new();
4708        $(
4709            $(
4710                select.push_str(&format!("{},",$select));
4711                selection.push_str(&format!("'{}',",$select));
4712            )*
4713        )?
4714        let select = select.trim_end_matches(",");
4715        let selection = selection.trim_end_matches(",");
4716
4717        if selection.len() != 0 {
4718            let rank = format!(
4719                "SELECT {} , ts_rank_cd(to_tsvector('english',{}),to_tsquery('{}')) FROM {} WHERE to_tsvector('english',CAST({} AS TEXT)) @@  to_tsquery(CAST('{}' AS TEXT))",
4720                select,$search,$value,$model, $search, $value
4721            );
4722            let client = $connection.query(&rank, &[]);
4723            // println!("{:?}",client);
4724            match client {
4725                Err(error) => {
4726                    Err(io::Error::new(io::ErrorKind::NotFound, error))
4727                },
4728                Ok(client) => {
4729                    let client = formats!{
4730                             client
4731                    };
4732                    Ok(client)
4733                }
4734            }
4735        }
4736        else {
4737            let rank = format!(
4738                "SELECT * , ts_rank_cd(to_tsvector('english',{}),to_tsquery('{}')) FROM {} WHERE to_tsvector('english',CAST({} AS TEXT)) @@  to_tsquery(CAST('{}' AS TEXT))",
4739                $search,$value,$model, $search, $value
4740            );
4741            let client = $connection.query(&rank, &[]);
4742            // println!("{:?}",client);
4743            match client {
4744                Err(error) => {
4745                    Err(io::Error::new(io::ErrorKind::NotFound, error))
4746                },
4747                Ok(client) => {
4748                    let client = formats!{
4749                             client
4750                    };
4751                    Ok(client)
4752                }
4753            }
4754        }
4755        // println!("{}",rank);
4756    }};
4757}
4758///
4759/// # Usage
4760///
4761/// ```
4762/// let search = ranked_search! {
4763///     connection => postgres,
4764///     model:"place",
4765///     based_on:"name",
4766///     search:{
4767///         value:"billionaire"
4768///     },
4769///     select:{
4770///         "name"
4771///     }
4772/// };
4773/// ```
4774///
4775///
4776#[cfg(feature = "async")]
4777#[cfg(feature = "async_ranked_search")]
4778#[macro_export]
4779macro_rules! ranked_search {
4780    (connection => $connection:expr,model:$model:expr,based_on:$search:expr,search:{
4781        value:$value:expr
4782    },$(
4783        select:{
4784            $($select:expr),*
4785        }
4786    )?) => {{
4787        use std::io;
4788        use rusty_postgres::formats;
4789
4790        #[derive(Debug,Clone)]
4791        struct Score {
4792            score:f32,
4793            data:String
4794        };
4795        let mut select = String::new();
4796        let mut selection = String::new();
4797        $(
4798            $(
4799                select.push_str(&format!("{},",$select));
4800                selection.push_str(&format!("'{}',",$select));
4801            )*
4802        )?
4803        let select = select.trim_end_matches(",");
4804        let selection = selection.trim_end_matches(",");
4805
4806        if selection.len() != 0 {
4807            let rank = format!(
4808                "SELECT {} , ts_rank_cd(to_tsvector('english',{}),to_tsquery('{}')) FROM {} WHERE to_tsvector('english',CAST({} AS TEXT)) @@  to_tsquery(CAST('{}' AS TEXT))",
4809                select,$search,$value,$model, $search, $value
4810            );
4811            let client = $connection.query(&rank, &[]).await;
4812            // println!("{:?}",client);
4813            match client {
4814                Err(error) => {
4815                    Err(io::Error::new(io::ErrorKind::NotFound, error))
4816                },
4817                Ok(client) => {
4818                    let client = formats!{
4819                             client
4820                    };
4821                    Ok(client)
4822                }
4823            }
4824        }
4825        else {
4826            let rank = format!(
4827                "SELECT * , ts_rank_cd(to_tsvector('english',{}),to_tsquery('{}')) FROM {} WHERE to_tsvector('english',CAST({} AS TEXT)) @@  to_tsquery(CAST('{}' AS TEXT))",
4828                $search,$value,$model, $search, $value
4829            );
4830            let client = $connection.query(&rank, &[]).await;
4831            // println!("{:?}",client);
4832            match client {
4833                Err(error) => {
4834                    Err(io::Error::new(io::ErrorKind::NotFound, error))
4835                },
4836                Ok(client) => {
4837                    let client = formats!{
4838                             client
4839                    };
4840                    Ok(client)
4841                }
4842            }
4843        }
4844        // println!("{}",rank);
4845    }};
4846}
4847///
4848/// # Usage
4849///
4850/// ```
4851/// let partition = create_partition {
4852///     connection => postgres,
4853///     model:"place",
4854///     name:"partition_name",
4855///     field:"value_to_match"
4856/// }
4857/// ```
4858#[cfg(not(feature = "async"))]
4859#[cfg(feature = "partition")]
4860#[macro_export]
4861macro_rules! create_partition {
4862    (connection => $connection:expr,model:$model:expr,name:$name:expr,field:$field:expr) => {{
4863        let partition = format!(
4864            "CREATE TABLE {} PARTITION OF {} FOR VALUES IN (\'{}\')",
4865            $name, $model, $field
4866        );
4867        // println!("{}", partition);
4868        $connection.execute(&partition, &[])
4869    }};
4870}
4871///
4872/// # Usage
4873///
4874/// ```
4875/// let partition = create_partition {
4876///     connection => postgres,
4877///     model:"place",
4878///     name:"partition_name",
4879///     field:"value_to_match"
4880/// }
4881/// ```
4882#[cfg(feature = "async")]
4883#[cfg(feature = "async_partition")]
4884#[macro_export]
4885macro_rules! create_partition {
4886    (connection => $connection:expr,model:$model:expr,name:$name:expr,field:$field:expr) => {{
4887        let partition = format!(
4888            "CREATE TABLE {} PARTITION OF {} FOR VALUES IN (\'{}\')",
4889            $name, $model, $field
4890        );
4891        // println!("{}", partition);
4892        $connection.execute(&partition, &[]).await
4893    }};
4894}
4895///
4896/// # Usage
4897///
4898/// ```
4899/// horizontal_splitting {
4900///     connection => postgres,
4901///     model:"",
4902///     name:"name_of_spllit",
4903///     based_on:{
4904///     "country" => "usa"    
4905///     }
4906/// }
4907/// ```
4908#[cfg(not(feature = "async"))]
4909#[cfg(feature = "horizontal_split")]
4910#[macro_export]
4911macro_rules! horizontal_splitting {
4912    (connection => $connection:expr,model:$model:expr,name:$name:expr,based_on:{$based_on:expr => $value:expr}) => {{
4913        use rand::Rng;
4914        use rusty_postgres::Alphanumeric;
4915
4916        let horizontal = format!(
4917            "CREATE TABLE {} AS SELECT * FROM {} WHERE {} = '{}';",
4918            $name, $model, $based_on, $value
4919        );
4920        // println!("{}", horizontal);
4921        let function = format!(
4922            "CREATE OR REPLACE FUNCTION copy_to_db()\r\n\
4923        RETURNS TRIGGER AS $$\r\n\
4924        BEGIN\r\n\
4925           IF NEW.{} = '{}' THEN\r\n\
4926                INSERT INTO {} VALUES (NEW.*);\r\n\
4927            END IF;\r\n\
4928            RETURN NEW;\r\n\
4929        END;\r\n\
4930        $$ LANGUAGE plpgsql;
4931         ",
4932            $based_on, $value, $model
4933        );
4934        let story: String = rand::thread_rng()
4935            .sample_iter(&Alphanumeric)
4936            .take(6)
4937            .map(char::from)
4938            .collect();
4939        let trigger = format!(
4940            "CREATE TRIGGER insert_to_story_{}\r\n\
4941        AFTER INSERT ON {}\r\n\
4942        FOR EACH ROW\r\n\
4943        EXECUTE FUNCTION copy_to_db();",
4944            story, $model
4945        );
4946        // println!("{}", trigger);
4947        $connection.execute(&horizontal, &[]).unwrap();
4948        $connection.execute(&trigger, &[]).unwrap();
4949        $connection.execute(&function, &[]).unwrap();
4950    }};
4951}
4952///
4953/// # Usage
4954///
4955/// ```
4956/// horizontal_splitting {
4957///     connection => postgres,
4958///     model:"",
4959///     name:"name_of_spllit",
4960///     based_on:{
4961///     "country" => "usa"    
4962///     }
4963/// }
4964/// ```
4965#[cfg(feature = "async")]
4966#[cfg(feature = "async_horizontal_split")]
4967#[macro_export]
4968macro_rules! horizontal_splitting {
4969    (connection => $connection:expr,model:$model:expr,name:$name:expr,based_on:{$based_on:expr => $value:expr}) => {{
4970        use rand::Rng;
4971        use rusty_postgres::Alphanumeric;
4972
4973        let horizontal = format!(
4974            "CREATE TABLE {} AS SELECT * FROM {} WHERE {} = '{}';",
4975            $name, $model, $based_on, $value
4976        );
4977        // println!("{}", horizontal);
4978        let function = format!(
4979            "CREATE OR REPLACE FUNCTION copy_to_db()\r\n\
4980        RETURNS TRIGGER AS $$\r\n\
4981        BEGIN\r\n\
4982           IF NEW.{} = '{}' THEN\r\n\
4983                INSERT INTO {} VALUES (NEW.*);\r\n\
4984            END IF;\r\n\
4985            RETURN NEW;\r\n\
4986        END;\r\n\
4987        $$ LANGUAGE plpgsql;
4988         ",
4989            $based_on, $value, $model
4990        );
4991        let story: String = rand::thread_rng()
4992            .sample_iter(&Alphanumeric)
4993            .take(6)
4994            .map(char::from)
4995            .collect();
4996        let trigger = format!(
4997            "CREATE TRIGGER insert_to_story_{}\r\n\
4998        AFTER INSERT ON {}\r\n\
4999        FOR EACH ROW\r\n\
5000        EXECUTE FUNCTION copy_to_db();",
5001            story, $model
5002        );
5003        // println!("{}", trigger);
5004        $connection.execute(&horizontal, &[]).await.unwrap();
5005        $connection.execute(&trigger, &[]).await.unwrap();
5006        $connection.execute(&function, &[]).await.unwrap();
5007    }};
5008}
5009
5010///
5011/// # Usage
5012///
5013/// ```
5014/// let query = custome_query {
5015///     connection => postgres,
5016///     query:{
5017///         "SELECT * FROM place WHERE name = $1"
5018///     },
5019///     value:{
5020///         "billionaires"
5021///     }
5022/// }
5023/// ```
5024// #[cfg(feature = "geography")]
5025#[cfg(not(feature = "async"))]
5026#[macro_export]
5027macro_rules! custome_query {
5028    (connection => $connection:expr,query:{$($query:expr),*} $(,value:{$($value:expr),*})?) => {{
5029        use rusty_postgres::{NaiveDate, NaiveDateTime, NaiveTime};
5030        use rusty_postgres::ToSql;
5031        use std::collections::BTreeMap;
5032        use std::panic;
5033        use rusty_postgres::uuid::Uuid;
5034
5035        let mut query = String::new();
5036        $(
5037            let format = format!("{}\r\n", $query);
5038            query.push_str(&format);
5039        )*
5040        let mut value: Vec<&(dyn ToSql + Sync)> = Vec::new();
5041        $(
5042            $(
5043                value.push(&$value);
5044            )*
5045        )?
5046        let client = $connection.query(&format, &value);
5047        match client {
5048            Err(error) => {
5049                Err(io::Error::new(io::ErrorKind::NotFound, error))
5050            },
5051            Ok(client) => {
5052                let client = formats!{
5053                         client
5054                };
5055                Ok(client)
5056            }
5057        }
5058    }};
5059}
5060///
5061/// # Usage
5062///
5063/// ```
5064/// let query = custome_query {
5065///     connection => postgres,
5066///     query:{
5067///         "SELECT * FROM place WHERE name = $1"
5068///     },
5069///     value:{
5070///         "billionaires"
5071///     }
5072/// }
5073/// ```
5074#[cfg(feature = "async")]
5075#[macro_export]
5076macro_rules! custome_query {
5077    (connection => $connection:expr,query:{$($query:expr),*} $(,value:{$($value:expr),*})?) => {{
5078        use rusty_postgres::{NaiveDate, NaiveDateTime, NaiveTime};
5079        use rusty_postgres::ToSql;
5080        use std::collections::BTreeMap;
5081        use std::panic;
5082        use rusty_postgres::uuid::Uuid;
5083
5084        let mut query = String::new();
5085        $(
5086            let format = format!("{}\r\n", $query);
5087            query.push_str(&format);
5088        )*
5089        let mut value: Vec<&(dyn ToSql + Sync)> = Vec::new();
5090        $(
5091            $(
5092                value.push(&$value);
5093            )*
5094        )?
5095        let client = $connection.query(&format, &value).await;
5096        match client {
5097            Err(error) => {
5098                Err(io::Error::new(io::ErrorKind::NotFound, error))
5099            },
5100            Ok(client) => {
5101                let client = formats!{
5102                         client
5103                };
5104                Ok(client)
5105            }
5106        }
5107    }};
5108}
5109///
5110/// # Usage
5111///
5112/// ```
5113/// let partition = custome_execute! {
5114///     connection => postgres,
5115///     query:{
5116///         "INSERT INTO place VALUES ($1)"
5117///     },
5118///     value:{
5119///         "billionaires"
5120///     }
5121/// };
5122/// ```
5123#[cfg(not(feature = "async"))]
5124#[macro_export]
5125macro_rules! custome_execute {
5126    (connection => $connection:expr,query:{$($query:expr),*} $(,value:{$($value:expr),*})?) => {
5127        {
5128            use rusty_postgres::ToSql;
5129
5130            let mut query = String::new();
5131            $(
5132                let format = format!("{}\r\n", $query);
5133                query.push_str(&format);
5134            )*
5135            let mut value: Vec<&(dyn ToSql + Sync)> = Vec::new();
5136            $(
5137                $(
5138                    value.push(&$value);
5139                )*
5140            )?
5141            let client = $connection.execute(&format, &value);
5142            client
5143        }
5144    };
5145}
5146///
5147/// # Usage
5148///
5149/// ```
5150/// let partition = custome_execute! {
5151///     connection => postgres,
5152///     query:{
5153///         "INSERT INTO place VALUES ($1)"
5154///     },
5155///     value:{
5156///         "billionaires"
5157///     }
5158/// };
5159/// ```
5160#[cfg(feature = "async")]
5161#[macro_export]
5162macro_rules! custome_execute {
5163    (connection => $connection:expr,query:{$($query:expr),*} $(,value:{$($value:expr),*})?) => {
5164        {
5165            use rusty_postgres::ToSql;
5166
5167            let mut query = String::new();
5168            $(
5169                let format = format!("{}\r\n", $query);
5170                query.push_str(&format);
5171            )*
5172            let mut value: Vec<&(dyn ToSql + Sync)> = Vec::new();
5173            $(
5174                $(
5175                    value.push(&$value);
5176                )*
5177            )?
5178            let client = $connection.execute(&format, &value).await;
5179            client
5180        }
5181    };
5182}
5183/// # Example
5184///
5185///
5186/// ```
5187/// let location = nearby_location! {
5188///     connection => postgres,
5189///     model:"billionaires",
5190///     select:{
5191///         "place"
5192///     },
5193///     location:{
5194///         lattitude:"12.971560",
5195///         longitude:"77.594560",
5196///         within:"4000"               //optional
5197///     },
5198///     select_from:{
5199///         "location"
5200///     },
5201///     order:{                 //optiona
5202///         location:"asc",     //optional
5203///         "place" => "asc"    //optional
5204///     }
5205/// };
5206/// ```
5207#[cfg(not(feature = "async"))]
5208#[macro_export]
5209#[cfg(feature = "geography")]
5210macro_rules! nearby_location {
5211    (connection => $connection:expr,model:$model:expr
5212        $(
5213            ,select:{
5214                $($select:expr),*
5215            }
5216        )?
5217        ,location:{
5218            lattitude:$lattitude:expr,
5219            longitude:$longitude:expr
5220            $(,within:$within:expr)?
5221    },select_from:{
5222        $select_location:expr
5223    }
5224    $(
5225        ,order:{
5226            $(location:$location_order:expr)?
5227            $(
5228                ,$(
5229                    $order:expr => $orderby:expr
5230                ),*
5231            )?
5232        }
5233    )?
5234) => {
5235    {
5236        use rusty_postgres::ToSql;
5237        use std::io;
5238        use rusty_postgres::formats;
5239
5240        if $lattitude.is_empty() {
5241            panic!("Provide Value for lattitude in float")
5242        }
5243        if $longitude.is_empty() {
5244            panic!("Provide Value for longitude in float")
5245        }
5246
5247        let mut selection = String::new();
5248        let mut value: Vec<&(dyn ToSql + Sync)> = Vec::new();
5249        let mut order = String::new();
5250
5251        let mut idx = 0;
5252        idx += 1;
5253        value.push(&$longitude);
5254        let longitude = format!("${}",idx);
5255        value.push(&$lattitude);
5256        idx += 1;
5257        let lattitude = format!("${}",idx);
5258
5259        $(
5260            $(
5261                let select = format!("{},",$select);
5262                selection.push_str(&select);
5263            )*
5264        )?
5265        $(
5266            $(
5267                $(
5268                    if !["asc","desc","ASC","DESC"].contains(&$orderby){
5269                        panic!("Provide Correct Order")
5270                    }
5271                    else {
5272                        let orders = format!("{} {},",$order,$orderby.to_uppercase());
5273                        order.push_str(&orders);
5274                    }
5275                )?
5276            )*
5277        )?
5278
5279        let selection = selection.trim_end_matches(",");
5280        let order = order.trim_end_matches(",");
5281
5282        let mut location = format!("WITH current_location AS (
5283            SELECT ST_GeogFromText('SRID=4326;POINT('||{}||' '||{}||')') AS c_location
5284        )
5285        SELECT {},ST_AsGeoJson({}) as location,ST_Distance({}, cl.c_location) as distance FROM {} , current_location cl WHERE ST_DWithin({},cl.c_location
5286        ",longitude,lattitude,selection,$select_location,$select_location,$model,$select_location);
5287        // ,{})
5288        $(
5289            location.push_str(&format!(",{})",$within));
5290        )?
5291        if !location.ends_with(")"){
5292            location.push_str(",0)");
5293        }
5294        $(
5295            $(
5296                let orders = format!(" ORDER BY distance {}",$location_order);
5297                location.push_str(&orders);
5298            )?
5299        )?
5300
5301        if order.len() != 0 {
5302            if location.contains("ORDER BY"){
5303                location.push_str(&format!(",{}",order));
5304            }
5305            else{
5306                location.push_str(&format!(" ORDER BY {}",order));
5307            }
5308        }
5309        // println!("{}",location);
5310        // println!("{:?}",value);
5311        let client = $connection.query(&location,&value);
5312        match client {
5313            Err(error) => {
5314                Err(io::Error::new(io::ErrorKind::NotFound, error))
5315            },
5316            Ok(client) => {
5317                let client = formats!{
5318                         client
5319                };
5320                Ok(client)
5321            }
5322        }
5323    }};
5324}
5325/// # Example
5326///
5327///
5328/// ```
5329/// let location = nearby_location! {
5330///     connection => postgres,
5331///     model:"billionaires",
5332///     select:{
5333///         "place"
5334///     },
5335///     location:{
5336///         lattitude:"12.971560",
5337///         longitude:"77.594560",
5338///         within:"4000"               //optional
5339///     },
5340///     select_from:{
5341///         "location"
5342///     },
5343///     order:{                 //optiona
5344///         location:"asc",     //optional
5345///         "place" => "asc"    //optional
5346///     }
5347/// };
5348/// ```
5349#[cfg(feature = "async")]
5350#[macro_export]
5351#[cfg(feature = "async_geography")]
5352macro_rules! nearby_location {
5353    (connection => $connection:expr,model:$model:expr
5354        $(
5355            ,select:{
5356                $($select:expr),*
5357            }
5358        )?
5359        ,location:{
5360            lattitude:$lattitude:expr,
5361            longitude:$longitude:expr
5362            $(,within:$within:expr)?
5363    },select_from:{
5364        $select_location:expr
5365    }
5366    $(
5367        ,order:{
5368            $(location:$location_order:expr)?
5369            $(
5370                ,$(
5371                    $order:expr => $orderby:expr
5372                ),*
5373            )?
5374        }
5375    )?
5376) => {
5377    {
5378        use rusty_postgres::ToSql;
5379        use std::io;
5380        use rusty_postgres::formats;
5381
5382        if $lattitude.is_empty() {
5383            panic!("Provide Value for lattitude in float")
5384        }
5385        if $longitude.is_empty() {
5386            panic!("Provide Value for longitude in float")
5387        }
5388
5389        let mut selection = String::new();
5390        let mut value: Vec<&(dyn ToSql + Sync)> = Vec::new();
5391        let mut order = String::new();
5392
5393        let mut idx = 0;
5394        idx += 1;
5395        value.push(&$longitude);
5396        let longitude = format!("${}",idx);
5397        value.push(&$lattitude);
5398        idx += 1;
5399        let lattitude = format!("${}",idx);
5400
5401        $(
5402            $(
5403                let select = format!("{},",$select);
5404                selection.push_str(&select);
5405            )*
5406        )?
5407        $(
5408            $(
5409                $(
5410                    if !["asc","desc","ASC","DESC"].contains(&$orderby){
5411                        panic!("Provide Correct Order")
5412                    }
5413                    else {
5414                        let orders = format!("{} {},",$order,$orderby.to_uppercase());
5415                        order.push_str(&orders);
5416                    }
5417                )?
5418            )*
5419        )?
5420
5421        let selection = selection.trim_end_matches(",");
5422        let order = order.trim_end_matches(",");
5423
5424        let mut location = format!("WITH current_location AS (
5425            SELECT ST_GeogFromText('SRID=4326;POINT('||{}||' '||{}||')') AS c_location
5426        )
5427        SELECT {},ST_AsGeoJson({}) as location,ST_Distance({}, cl.c_location) as distance FROM {} , current_location cl WHERE ST_DWithin({},cl.c_location
5428        ",longitude,lattitude,selection,$select_location,$select_location,$model,$select_location);
5429        // ,{})
5430        $(
5431            location.push_str(&format!(",{})",$within));
5432        )?
5433        if !location.ends_with(")"){
5434            location.push_str(",0)");
5435        }
5436        $(
5437            $(
5438                let orders = format!(" ORDER BY distance {}",$location_order);
5439                location.push_str(&orders);
5440            )?
5441        )?
5442
5443        if order.len() != 0 {
5444            if location.contains("ORDER BY"){
5445                location.push_str(&format!(",{}",order));
5446            }
5447            else{
5448                location.push_str(&format!(" ORDER BY {}",order));
5449            }
5450        }
5451        // println!("{}",location);
5452        // println!("{:?}",value);
5453        let client = $connection.query(&location,&value).await;
5454        match client {
5455            Err(error) => {
5456                Err(io::Error::new(io::ErrorKind::NotFound, error))
5457            },
5458            Ok(client) => {
5459                let client = formats!{
5460                         client
5461                };
5462                Ok(client)
5463            }
5464        }
5465    }};
5466}