Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

db.rs 6.0 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
  1. use error::{Result, err};
  2. use std::io::prelude::*;
  3. use os_pipe::{pipe, PipeWriter};
  4. use postgres::{Connection, TlsMode};
  5. use structopt::StructOpt;
  6. use std::thread;
  7. pub trait ConnectInfo {
  8. fn db_url(&self) -> Result<String>;
  9. }
  10. impl ConnectInfo for String {
  11. fn db_url(&self) -> Result<String> {
  12. Ok(self.clone())
  13. }
  14. }
  15. impl ConnectInfo for Option<String> {
  16. fn db_url(&self) -> Result<String> {
  17. match self {
  18. Some(ref s) => Ok(s.clone()),
  19. None => Err(err("no URL provided"))
  20. }
  21. }
  22. }
  23. /// Database options
  24. #[derive(StructOpt, Debug, Clone)]
  25. pub struct DbOpts {
  26. /// Database URL to connect to
  27. #[structopt(long="db-url")]
  28. db_url: Option<String>,
  29. /// Database schema
  30. #[structopt(long="db-schema")]
  31. db_schema: Option<String>
  32. }
  33. impl DbOpts {
  34. /// Open the database connection
  35. pub fn open(&self) -> Result<Connection> {
  36. let url = self.url()?;
  37. connect(&url)
  38. }
  39. pub fn url<'a>(&'a self) -> Result<String> {
  40. Ok(match self.db_url {
  41. Some(ref s) => s.clone(),
  42. None => std::env::var("DB_URL")?
  43. })
  44. }
  45. /// Get the DB schema
  46. pub fn schema<'a>(&'a self) -> &'a str {
  47. match self.db_schema {
  48. Some(ref s) => s,
  49. None => "public"
  50. }
  51. }
  52. /// Change the default schema
  53. pub fn default_schema(self, default: &str) -> DbOpts {
  54. DbOpts {
  55. db_url: self.db_url,
  56. db_schema: self.db_schema.or_else(|| Some(default.to_string()))
  57. }
  58. }
  59. }
  60. impl ConnectInfo for DbOpts {
  61. fn db_url(&self) -> Result<String> {
  62. self.url()
  63. }
  64. }
  65. pub fn connect(url: &str) -> Result<Connection> {
  66. Ok(Connection::connect(url, TlsMode::None)?)
  67. }
  68. pub struct CopyRequest {
  69. db_url: String,
  70. schema: Option<String>,
  71. table: String,
  72. columns: Option<Vec<String>>,
  73. truncate: bool,
  74. name: String
  75. }
  76. impl CopyRequest {
  77. pub fn new<C: ConnectInfo>(db: &C, table: &str) -> Result<CopyRequest> {
  78. Ok(CopyRequest {
  79. db_url: db.db_url()?,
  80. schema: None,
  81. table: table.to_string(),
  82. columns: None,
  83. truncate: false,
  84. name: "copy".to_string()
  85. })
  86. }
  87. pub fn with_schema(self, schema: &str) -> CopyRequest {
  88. CopyRequest {
  89. schema: Some(schema.to_string()),
  90. ..self
  91. }
  92. }
  93. pub fn with_columns(self, columns: &[&str]) -> CopyRequest {
  94. let mut cvec = Vec::with_capacity(columns.len());
  95. for c in columns {
  96. cvec.push(c.to_string());
  97. }
  98. CopyRequest {
  99. columns: Some(cvec),
  100. ..self
  101. }
  102. }
  103. pub fn with_name(self, name: &str) -> CopyRequest {
  104. CopyRequest {
  105. name: name.to_string(),
  106. ..self
  107. }
  108. }
  109. pub fn truncate(self, trunc: bool) -> CopyRequest {
  110. CopyRequest {
  111. truncate: trunc,
  112. ..self
  113. }
  114. }
  115. pub fn table(&self) -> String {
  116. match self.schema {
  117. Some(ref s) => format!("{}.{}", s, self.table),
  118. None => self.table.clone()
  119. }
  120. }
  121. fn query(&self) -> String {
  122. let mut query = format!("COPY {}", self.table());
  123. if let Some(ref cs) = self.columns {
  124. let s = format!(" ({})", cs.join(", "));
  125. query.push_str(&s);
  126. }
  127. query.push_str(" FROM STDIN");
  128. query
  129. }
  130. /// Open a writer for a copy request
  131. pub fn open(self) -> Result<CopyTarget> {
  132. let query = self.query();
  133. let (mut reader, writer) = pipe()?;
  134. let name = self.name.clone();
  135. let tb = thread::Builder::new().name(name.clone());
  136. let jh = tb.spawn(move || {
  137. let query = query;
  138. let db = connect(&self.db_url).unwrap();
  139. let mut cfg = postgres::transaction::Config::new();
  140. cfg.isolation_level(postgres::transaction::IsolationLevel::ReadUncommitted);
  141. let tx = db.transaction_with(&cfg).unwrap();
  142. if self.truncate {
  143. let tq = format!("TRUNCATE {}", self.table());
  144. info!("running {}", tq);
  145. tx.execute(&tq, &[]).unwrap();
  146. }
  147. info!("preparing {}", query);
  148. let stmt = tx.prepare(&query).unwrap();
  149. let n = stmt.copy_in(&[], &mut reader).unwrap();
  150. info!("committing copy");
  151. tx.commit().unwrap();
  152. n
  153. })?;
  154. Ok(CopyTarget {
  155. writer: Some(writer),
  156. name: name,
  157. thread: Some(jh)
  158. })
  159. }
  160. }
  161. /// Writer for copy-in operations
  162. ///
  163. /// This writer writes to the copy-in for PostgreSQL. It is unbuffered; you usually
  164. /// want to wrap it in a `BufWriter`.
  165. pub struct CopyTarget {
  166. writer: Option<PipeWriter>,
  167. name: String,
  168. thread: Option<thread::JoinHandle<u64>>
  169. }
  170. impl Write for CopyTarget {
  171. fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
  172. self.writer.as_ref().expect("writer missing").write(buf)
  173. }
  174. fn flush(&mut self) -> std::io::Result<()> {
  175. self.writer.as_ref().expect("writer missing").flush()
  176. }
  177. }
  178. impl Drop for CopyTarget {
  179. fn drop(&mut self) {
  180. if let Some(w) = self.writer.take() {
  181. std::mem::drop(w);
  182. }
  183. if let Some(thread) = self.thread.take() {
  184. match thread.join() {
  185. Ok(n) => info!("{}: wrote {} lines", self.name, n),
  186. Err(e) => error!("{}: error: {:?}", self.name, e)
  187. };
  188. } else {
  189. error!("{} already shut down", self.name);
  190. }
  191. }
  192. }
  193. #[test]
  194. fn cr_initial_correct() {
  195. let cr = CopyRequest::new(&("foo".to_string()), "wombat").unwrap();
  196. assert_eq!(cr.name, "copy");
  197. assert_eq!(cr.db_url, "foo");
  198. assert_eq!(cr.table, "wombat");
  199. assert!(cr.columns.is_none());
  200. assert!(cr.schema.is_none());
  201. assert!(!cr.truncate);
  202. assert_eq!(cr.query(), "COPY wombat FROM STDIN");
  203. }
  204. #[test]
  205. fn cr_set_name() {
  206. let cr = CopyRequest::new(&("foo".to_string()), "wombat").unwrap();
  207. let cr = cr.with_name("bob");
  208. assert_eq!(cr.name, "bob");
  209. assert_eq!(cr.db_url, "foo");
  210. assert_eq!(cr.table, "wombat");
  211. assert!(cr.columns.is_none());
  212. assert!(cr.schema.is_none());
  213. assert!(!cr.truncate);
  214. }
  215. #[test]
  216. fn cr_schema_propagated() {
  217. let cr = CopyRequest::new(&("foo".to_string()), "wombat").unwrap();
  218. let cr = cr.with_schema("pizza");
  219. assert_eq!(cr.name, "copy");
  220. assert_eq!(cr.db_url, "foo");
  221. assert_eq!(cr.table, "wombat");
  222. assert!(cr.columns.is_none());
  223. assert_eq!(cr.schema.as_ref().expect("no schema"), "pizza");
  224. assert!(!cr.truncate);
  225. assert_eq!(cr.query(), "COPY pizza.wombat FROM STDIN");
  226. }
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...