1#[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};
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 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 $(
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 $(
39 let value = stringify!($value);
40 if value.starts_with("ID(") {
43 if value == ("ID(UUID)") {
44 table.push_str("UUID ");
46 id.push_str("UUID");
47 primary_key.push_str(&format!("{},",$billionaire.to_lowercase()));
48 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("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 }
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 }
70 else {
71 panic!("please provide correct (uuid,cuid,auto)")
72 }
73 }
74
75 else if value.starts_with("OneToOne"){
77 let serialize = serde_json::to_string(&$value).unwrap();
78 let deserialize = serde_json::from_str::<OneToOne>(&serialize).unwrap();
80
81
82 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 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 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 else if value.starts_with("OneToMany"){
114 let serialize = serde_json::to_string(&$value).unwrap();
115 let deserialize = serde_json::from_str::<OneToMany>(&serialize).unwrap();
117
118 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 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 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 else if value.starts_with("Date") && !value.starts_with("DateTime") {
152
153 if value == ("Date(NOW)") {
155 table.push_str(&format!("{}","DATE DEFAULT CURRENT_DATE"))
157 }
158 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 else if value.starts_with("Time") {
169
170 if value == ("Time(NOW)") {
172 table.push_str(&format!("{}","TIME DEFAULT CURRENT_TIME"))
174 }
175
176 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 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 else if value.starts_with("DEFAULT"){
212 let value = value.split("(").nth(1).unwrap().trim_end_matches(")");
215 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 let default = format!("DEFAULT {} ", value);
227 table.push_str(&default);
228 }
229 }
230
231 else if value.starts_with("JSON"){
233 table.push_str("JSONB ")
234 }
235
236 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 else if value.starts_with("UNIQUE"){
264 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 )*
280 let mut table = table.trim_end_matches(" ").to_string();
281 table.push_str(",");
282 table.push_str("\n");
283 )*
284 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 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 table.push_str(&key);
296 }
297 if foriegn_key.len() != 0 {
298 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 table.push_str("\r\n);\r\n");
307 let index = index.trim_end_matches(",");
308 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 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};
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 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 $(
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 $(
371 let value = stringify!($value);
372 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("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("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 }
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 }
402 else {
403 panic!("please provide correct (uuid,cuid,auto)")
404 }
405 }
406
407 else if value.starts_with("OneToOne"){
409 let serialize = serde_json::to_string(&$value).unwrap();
410 let deserialize = serde_json::from_str::<OneToOne>(&serialize).unwrap();
412
413 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 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 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 else if value.starts_with("OneToMany"){
446 let serialize = serde_json::to_string(&$value).unwrap();
447 let deserialize = serde_json::from_str::<OneToMany>(&serialize).unwrap();
449
450 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 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 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 else if value.starts_with("Date") && !value.starts_with("DateTime") {
484
485 if value == stringify!(Date(NOW)) {
487 table.push_str(&format!("{}","DATE DEFAULT CURRENT_DATE"))
489 }
490 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 else if value.starts_with("Time") {
501
502 if value == ("Time(NOW)") {
504 table.push_str(&format!("{}","TIME DEFAULT CURRENT_TIME"))
506 }
507
508 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 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 else if value.starts_with("DEFAULT"){
544 let value = value.split("(").nth(1).unwrap().trim_end_matches(")");
547 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 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 else if value.starts_with("UNIQUE"){
587 unique.push_str(&format!("{},",$billionaire.to_lowercase()));
589 }
590
591 else if value.starts_with("JSON"){
593 table.push_str("JSONB ")
594 }
595 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 )*
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 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 table.push_str(&key);
643 }
644 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 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 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 }
700 if container.contains("UUID") {
701 containers.push_str("CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\";\r\n");
702 }
704 if container.contains("encode(gen_random_bytes(12)") {
705 containers.push_str("CREATE EXTENSION IF NOT EXISTS \"pgcrypto\";\r\n");
706 }
708 containers.push_str(&container);
709 schema.push_str(&containers);
710 if let Some(cluster) = containers.find("CLUSTER") {
713 let clusters = &containers[cluster..];
715 let containers = &containers[..cluster];
717 println!("{}", containers);
718 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 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 }
765 if container.contains("UUID") {
766 containers.push_str("CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\";\r\n");
767 }
769 if container.contains("encode(gen_random_bytes(12)") {
770 containers.push_str("CREATE EXTENSION IF NOT EXISTS \"pgcrypto\";\r\n");
771 }
773 containers.push_str(&container);
774 schema.push_str(&containers);
775 if let Some(cluster) = containers.find("CLUSTER") {
778 let clusters = &containers[cluster..];
780 let containers = &containers[..cluster];
782 println!("{}", containers);
783 let db = $url.batch_execute(&containers).await;
787 match db {
788 Ok(db) => {
789
790 }
791 Err(err) => {
792 panic!("{:?}",err);
793 }
794 }
795 $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 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 billionaires.push(collection);
880 }
881 billionaires
882 }};
883}
884
885#[cfg(not(feature = "async"))]
911#[macro_export]
912macro_rules! find_one {
913 (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 $(
943 $(
944 selectvalue.push_str(&format!("{},",$select_value));
945 )*
947 )?
948 let select_value = selectvalue.trim_end_matches(",");
949 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 $(
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 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 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#[cfg(feature = "async")]
1048#[macro_export]
1049macro_rules! find_one {
1050 (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 $(
1080 $(
1081 selectvalue.push_str(&format!("{},",$select_value));
1082 )*
1084 )?
1085 let select_value = selectvalue.trim_end_matches(",");
1086 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 $(
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 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 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#[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 $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 })?
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 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 }
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 }
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 }
1445 else {
1446 let between_and = format!(" WHEN CAST({} AS text) = ${} THEN '{}'",$key,idx,$ok);
1447 cases.push_str(&between_and);
1448 $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 )*
1458 )?
1459 $(
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 $(
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 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 include.push_str(&inside);
1547 )?
1548
1549 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 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 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 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 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 let mut idx = 0;
1775 idx+=1;
1776 let condition_longitude = format!("${}",idx);
1777 idx+=1;
1778 let condition_lattitude = format!("${}",idx);
1779 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 let client = $connection.query(&query,&condition).unwrap();
1793 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 let client = $connection.query(&query,&condition).unwrap();
1801 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 let client = $connection.query(&query,&condition).unwrap();
1809 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 let client = $connection.query(&query,&condition);
1817 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#[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 $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 })?
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 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 }
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 }
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 }
2093 else {
2094 let between_and = format!(" WHEN CAST({} AS text) = ${} THEN '{}'",$key,idx,$ok);
2095 cases.push_str(&between_and);
2096 $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 )*
2106 )?
2107 $(
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 $(
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 r1 = format!("{} {}",$include,b);
2195 let r2 = format!("{}.{}",b,$include_match);
2196 let inside = format!("LEFT JOIN {} {} ON {} = {}",select,b,table_dots,r2);
2197 include.push_str(&inside);
2200 )?
2201
2202 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 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 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 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!("{}",query);
2370 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 let mut idx = 0;
2428 idx+=1;
2429 let condition_longitude = format!("${}",idx);
2430 idx+=1;
2431 let condition_lattitude = format!("${}",idx);
2432 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 let client = $connection.query(&query,&condition).unwrap();
2446 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 let client = $connection.query(&query,&condition).unwrap();
2454 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 let client = $connection.query(&query,&condition).unwrap();
2462 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 let client = $connection.query(&query,&condition).await;
2470 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#[cfg(not(feature = "async"))]
2499#[macro_export]
2500macro_rules! delete_many {
2501 (connection => $connection:expr,model:$model:expr) => {{
2503 let delete = format!("DELETE FROM {};", $model);
2504 $connection.execute(&delete, &[])
2506 }};
2507}
2508
2509#[cfg(feature = "async")]
2521#[macro_export]
2522macro_rules! delete_many {
2523 (connection => $connection:expr,model:$model:expr) => {{
2525 let delete = format!("DELETE FROM {};", $model);
2526 $connection.execute(&delete, &[]).await
2528 }};
2529}
2530
2531#[cfg(not(feature = "async"))]
2551#[macro_export]
2552macro_rules! delete {
2553 (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 $(
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 let client = $connection.query(&delete,&value);
2686 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#[cfg(feature = "async")]
2721#[macro_export]
2722macro_rules! delete {
2723 (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 $(
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 let client = $connection.query(&delete,&value).await;
2856 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#[cfg(not(feature = "async"))]
2923#[macro_export]
2924macro_rules! update {
2926 (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 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 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 $(,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 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 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 set.push_str(&update);
3135 value.push(&$data_value);
3136
3137 )*
3138 $(
3139 $(
3140 $(
3141 idx+=1;
3142 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 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 updates.push_str(&update);
3270 )*
3271 let client = $connection.query(&updates,&value);
3279 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#[cfg(feature = "async")]
3345#[macro_export]
3346macro_rules! update {
3348 (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 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 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 $(,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 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 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 set.push_str(&update);
3557 value.push(&$data_value);
3558
3559 )*
3560 $(
3561 $(
3562 $(
3563 idx+=1;
3564 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 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 updates.push_str(&update);
3692 )*
3693 let client = $connection.query(&updates,&value).await;
3701 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#[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 if select_value.len() != 0 {
3792 create.push_str(&format!(" RETURNING {};",select))
3793 }
3794 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#[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 if select_value.len() != 0 {
3888 create.push_str(&format!(" RETURNING {};",select))
3889 }
3890 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 };
3915 (connection => $connection:expr,commit) => {
3916 let commit = $connection.execute("COMMIT;", &[]).unwrap();
3917 };
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 };
3928 (connection => $connection:expr,commit) => {
3929 let commit = $connection.execute("COMMIT;", &[]).await.unwrap();
3930 };
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 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 second: String = result.get(1);
3948 let third: String = result.get(2);
3949 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 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 second: String = result.get(1);
3971 let third: String = result.get(2);
3972 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 $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 $connection.execute(&value,&[]).await
4009 }
4010 };
4011}
4012
4013#[cfg(not(feature = "async"))]
4014#[cfg(feature = "brin_index")]
4015#[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 $connection.execute(&value,&[])
4028 }
4029 };
4030}
4031#[cfg(feature = "async")]
4032#[cfg(feature = "async_brin_index")]
4033#[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 $connection.execute(&value,&[]).await
4046 }
4047 };
4048}
4049
4050#[cfg(not(feature = "async"))]
4051#[cfg(feature = "geography")]
4052#[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 $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 $connection.execute(&extension,&[]);
4086 $connection.execute(&value,&[])
4087 }
4088 };
4089}
4090
4091#[cfg(feature = "async")]
4092#[cfg(feature = "geography")]
4093#[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 $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 $connection.execute(&extension,&[]).await;
4127 $connection.execute(&value,&[]).await
4128 }
4129 };
4130}
4131#[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 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#[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 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#[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 let client = $connection.query(&table, &[]).unwrap();
4282 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 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 let client = $connection.query(&table, &[]).await.unwrap();
4306 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 hashmap.insert(first, second);
4313 }
4314 hashmap
4315 }};
4316}
4317#[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 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 let result = $connection.query(&count, &values).unwrap();
4410 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
4418 }};
4419}
4420#[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 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 let result = $connection.query(&count, &values).await.unwrap();
4513 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
4521 }};
4522}
4523
4524#[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 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#[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 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#[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 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 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 }};
4757}
4758#[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 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 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 }};
4846}
4847#[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 $connection.execute(&partition, &[])
4869 }};
4870}
4871#[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 $connection.execute(&partition, &[]).await
4893 }};
4894}
4895#[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 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 $connection.execute(&horizontal, &[]).unwrap();
4948 $connection.execute(&trigger, &[]).unwrap();
4949 $connection.execute(&function, &[]).unwrap();
4950 }};
4951}
4952#[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 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 $connection.execute(&horizontal, &[]).await.unwrap();
5005 $connection.execute(&trigger, &[]).await.unwrap();
5006 $connection.execute(&function, &[]).await.unwrap();
5007 }};
5008}
5009
5010#[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#[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#[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#[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#[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 $(
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 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#[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 $(
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 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}