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

mod.rs 5.7 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
  1. use std::io::prelude::*;
  2. use std::path::{Path,PathBuf};
  3. use std::fs::{File, OpenOptions};
  4. use std::io::{BufReader, BufWriter};
  5. use std::mem::drop;
  6. use anyhow::{Result, anyhow};
  7. use postgres::Connection;
  8. use log::*;
  9. use structopt::{StructOpt};
  10. use fallible_iterator::FallibleIterator;
  11. use super::Command;
  12. use crate::db::DbOpts;
  13. use crate::tracking::{StageOpts};
  14. mod parsers;
  15. mod sources;
  16. mod sinks;
  17. use parsers::*;
  18. use sources::*;
  19. use sinks::*;
  20. /// Parse MARC files into records for a PostgreSQL table.
  21. #[derive(StructOpt, Debug)]
  22. #[structopt(name="parse-isbns")]
  23. pub struct ParseISBNs {
  24. #[structopt(flatten)]
  25. db: DbOpts,
  26. #[structopt(flatten)]
  27. stage: StageOpts,
  28. /// The table from which to parse ISBNs.
  29. #[structopt(long="src-table")]
  30. src_table: Option<String>,
  31. /// The file from which to parse ISBNs.
  32. #[structopt(short="-f", long="src-file")]
  33. src_file: Option<PathBuf>,
  34. // The file to write the parsed ISBNs.
  35. #[structopt(short="-o", long="out-file")]
  36. out_file: Option<PathBuf>,
  37. // The table to write the parsed ISBNs.
  38. #[structopt(long="out-table")]
  39. out_table: Option<String>,
  40. /// Print unmatched entries
  41. #[structopt(short="-U", long="print-unmatched")]
  42. print_unmatched: bool,
  43. /// Print ignored entries
  44. #[structopt(short="-I", long="print-ignored")]
  45. print_ignored: bool,
  46. /// Print trails
  47. #[structopt(short="-L", long="print-trail")]
  48. print_trail: bool,
  49. /// Skip ISBN diagnostics
  50. #[structopt(long="no-diagnostics")]
  51. skip_diagnostics: bool
  52. }
  53. struct MatchStats {
  54. total: usize,
  55. valid: usize,
  56. ignored: usize,
  57. unmatched: usize,
  58. hash: Option<String>
  59. }
  60. impl Default for MatchStats {
  61. fn default() -> MatchStats {
  62. MatchStats {
  63. total: 0,
  64. valid: 0,
  65. ignored: 0,
  66. unmatched: 0,
  67. hash: None
  68. }
  69. }
  70. }
  71. impl ParseISBNs {
  72. fn scan_source<R>(&self, iter: &mut R, writer: Box<dyn WriteISBNs>) -> Result<MatchStats>
  73. where R: FallibleIterator<Item = IdPR, Error = anyhow::Error> {
  74. let mut stats = MatchStats::default();
  75. let mut w = writer; // we need a mutable writer
  76. while let Some((id, result)) = iter.next()? {
  77. debug!("{}: {:?}", id, result);
  78. match result {
  79. ParseResult::Valid(isbns, trail) => {
  80. for isbn in &isbns {
  81. self.check_isbn(id, isbn, &trail);
  82. w.write_isbn(id, isbn)?;
  83. }
  84. let trail = trail.trim();
  85. if trail.len() > 0 && self.print_trail {
  86. println!("trail for {}: {}", id, trail);
  87. }
  88. stats.valid += isbns.len();
  89. },
  90. ParseResult::Ignored (s)=> {
  91. stats.ignored += 1;
  92. if self.print_ignored {
  93. println!("ignored {}: {}", id, s);
  94. }
  95. },
  96. ParseResult::Unmatched(s) => {
  97. stats.unmatched += 1;
  98. warn!("unmatched {}: {}", id, s);
  99. if self.print_unmatched {
  100. println!("unmatched {}: {}", id, s);
  101. }
  102. }
  103. }
  104. stats.total += 1;
  105. }
  106. let hash = w.finish()?;
  107. if hash.len() > 0 {
  108. stats.hash = Some(hash);
  109. }
  110. Ok(stats)
  111. }
  112. fn check_isbn(&self, id: i64, isbn: &ISBN, trail: &str) {
  113. if self.skip_diagnostics {
  114. return;
  115. }
  116. if isbn.text.len() > 15 {
  117. warn!("{}: isbn {} {} chars long", id, isbn.text, isbn.text.len());
  118. }
  119. if isbn.text.len() < 8 {
  120. warn!("{}: isbn {} shorter than 8 characters (trail: ‘{}’)", id, isbn.text, trail);
  121. }
  122. }
  123. fn scan_file(&self, file: &Path, writer: Box<dyn WriteISBNs>) -> Result<MatchStats> {
  124. let input = File::open(file)?;
  125. let input = BufReader::new(input);
  126. let mut src = FileSource::create(input)?;
  127. self.scan_source(&mut src, writer)
  128. }
  129. fn scan_db(&self, db: &Connection, table: &str, writer: Box<dyn WriteISBNs>) -> Result<MatchStats> {
  130. let query = format!("SELECT * FROM {}", table);
  131. let txn = db.transaction()?;
  132. let stmt = txn.prepare(&query)?;
  133. let rows = stmt.lazy_query(&txn, &[], 1000)?;
  134. let mut src = DBSource::create(rows)?;
  135. let stats = self.scan_source(&mut src, writer)?;
  136. drop(src);
  137. drop(stmt);
  138. txn.commit()?;
  139. Ok(stats)
  140. }
  141. }
  142. impl Command for ParseISBNs {
  143. fn exec(self) -> Result<()> {
  144. let db = self.db.open()?;
  145. let mut stage = self.stage.begin_stage(&db)?;
  146. let writer: Box<dyn WriteISBNs> = if let Some(ref tbl) = self.out_table {
  147. info!("opening output table {}", tbl);
  148. writeln!(stage, "DEST TABLE {}", tbl)?;
  149. Box::new(DBWriter::new(&self.db, tbl)?)
  150. } else if let Some(ref path) = self.out_file {
  151. info!("opening output file {:?}", path);
  152. writeln!(stage, "DEST FILE {:?}", path)?;
  153. let out = OpenOptions::new().write(true).create(true).truncate(true).open(path)?;
  154. let buf = BufWriter::new(out);
  155. Box::new(FileWriter {
  156. write: Box::new(buf)
  157. })
  158. } else {
  159. Box::new(NullWriter {})
  160. };
  161. let stats = if let Some(ref tbl) = self.src_table {
  162. writeln!(stage, "SOURCE TABLE {}", tbl)?;
  163. let n = self.scan_db(&db, tbl, writer)?;
  164. n
  165. } else if let Some(ref path) = self.src_file {
  166. writeln!(stage, "SOURCE FILE {:?}", path)?;
  167. self.scan_file(&path, writer)?
  168. } else {
  169. error!("no source data specified");
  170. return Err(anyhow!("no source data"));
  171. };
  172. writeln!(stage, "{} RECORDS", stats.total)?;
  173. writeln!(stage, "{} IMPORTED", stats.valid)?;
  174. writeln!(stage, "{} UNMATCHED", stats.unmatched)?;
  175. writeln!(stage, "{} IGNORED", stats.ignored)?;
  176. if let Some(ref h) = stats.hash {
  177. writeln!(stage, "OUT HASH {}", h)?;
  178. }
  179. stage.end(&stats.hash)?;
  180. info!("processed {} ISBN records", stats.total);
  181. info!("matched {}, ignored {}, and {} were unmatched",
  182. stats.valid, stats.ignored, stats.unmatched);
  183. Ok(())
  184. }
  185. }
Tip!

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

Comments

Loading...