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

parse-marc.js 6.3 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
  1. const assert = require('assert');
  2. const stream = require('stream');
  3. const events = require('events');
  4. const expat = require('node-expat');
  5. const miss = require('mississippi');
  6. const log = require('gulplog');
  7. const io = require('./io');
  8. function createMarcParser() {
  9. var data, record, field, dfld, subfld;
  10. const parser = new expat.Parser('UTF-8');
  11. parser.on('startElement', start);
  12. parser.on('endElement', end);
  13. parser.on('text', text);
  14. return parser;
  15. function start(name, attrs) {
  16. if (name.startsWith('mx:')) name = name.slice(3);
  17. if (name === 'record') {
  18. record = {control: [], data: []};
  19. } else if (name === 'leader') {
  20. data = '';
  21. } else if (name === 'controlfield') {
  22. field = {tag: attrs.tag};
  23. data = '';
  24. } else if (name === 'datafield') {
  25. dfld = {tag: attrs.tag, ind1: attrs.ind1, ind2: attrs.ind2, subfields: []};
  26. } else if (name === 'subfield') {
  27. subfld = {code: attrs.code};
  28. data = '';
  29. }
  30. }
  31. function end(name) {
  32. if (name.startsWith('mx:')) name = name.slice(3);
  33. if (name === 'subfield') {
  34. subfld.data = data;
  35. dfld.subfields.push(subfld);
  36. data = undefined;
  37. subfld = undefined;
  38. } else if (name === 'datafield') {
  39. record.data.push(dfld);
  40. dfld = undefined;
  41. } else if (name === 'controlfield') {
  42. field.data = data;
  43. record.control.push(field);
  44. if (field.tag === '001') {
  45. record.cn = field.data.trim();
  46. }
  47. data = undefined;
  48. field = undefined;
  49. } else if (name === 'leader') {
  50. record.leader = data;
  51. data = undefined;
  52. } else if (name === 'record') {
  53. parser.emit('record', record);
  54. record = undefined;
  55. }
  56. }
  57. function text(txt) {
  58. if (data !== undefined) {
  59. data += txt;
  60. }
  61. }
  62. }
  63. class XMLToMarc extends stream.Transform {
  64. constructor() {
  65. super({objectMode: true});
  66. this.parser = createMarcParser();
  67. this.parser.on('error', (err) => this.destroy(err));
  68. this.parser.on('record', (rec) => {
  69. this.push(rec);
  70. });
  71. }
  72. _transform(chunk, enc, cb) {
  73. if (!this.parser.parse(chunk, false)) {
  74. return cb(this.parser.getError());
  75. } else {
  76. return cb();
  77. }
  78. }
  79. _final(cb) {
  80. if (!this.parser.parse('', true)) {
  81. return cb(this.parser.getError());
  82. } else {
  83. return cb();
  84. }
  85. }
  86. }
  87. /**
  88. * Create a stream parser for a MARC-XML 'collection'.
  89. */
  90. function parseCollection() {
  91. return new XMLToMarc();
  92. }
  93. module.exports.parseCollection = parseCollection;
  94. function decodeIDLine(buf) {
  95. let ltab = buf.indexOf('\t');
  96. if (ltab < 0) {
  97. throw new Error("no tab found in line");
  98. }
  99. let id = buf.slice(0, ltab).toString();
  100. let data = buf.slice(ltab + 1);
  101. return {id: id, xml: data};
  102. }
  103. /**
  104. * Create a stream parser for VIAF-style MARC lines.
  105. */
  106. function parseVIAFLines() {
  107. let lines = io.decodeLines(decodeIDLine);
  108. function parseRecord(line, enc, cb) {
  109. log.debug('parsing record %s: %d bytes', line.id, line.xml.length)
  110. let parser = createMarcParser();
  111. parser.on('error', (err) => {
  112. log.error('failed to parse viaf record %s: %s', line.id, err);
  113. return cb(err);
  114. });
  115. parser.on('record', (rec) => {
  116. log.debug('finished record %s', line.id);
  117. rec.id = line.id;
  118. process.nextTick(cb, null, rec);
  119. });
  120. parser.write(line.xml);
  121. }
  122. let parse = miss.through.obj(parseRecord);
  123. lines.pipe(parse);
  124. return miss.duplex.obj(lines, parse);
  125. }
  126. module.exports.parseVIAFLines = parseVIAFLines;
  127. function importMarc(db, options) {
  128. let recKeys = [];
  129. Object.entries(options.keys).forEach(([k, v], i) => {
  130. recKeys.push({field: k, attr: v, num: i + 1});
  131. })
  132. let recQuery = {
  133. name: 'add-record',
  134. text: `INSERT INTO ${options.records} (${recKeys.map((k) => k.field).join(',')}) VALUES (${recKeys.map((k) => '$' + k.num).join(',')}) RETURNING rec_id`
  135. };
  136. let fldQuery = {
  137. name: 'add-field',
  138. text: `INSERT INTO ${options.fields} (rec_id, fld_no, tag, ind1, ind2, sf_code, contents) VALUES ($1, $2, $3, $4, $5, $6, $7)`
  139. };
  140. let n = 0;
  141. async function addRecord(rec) {
  142. if (n % 1000 == 0) {
  143. if (n > 0) {
  144. await db.query('COMMIT');
  145. }
  146. await db.query({
  147. name: 'begin',
  148. text: 'BEGIN ISOLATION LEVEL READ UNCOMMITTED'
  149. });
  150. }
  151. n += 1;
  152. let rvs = recKeys.map((k) => rec[k.attr]);
  153. let recResult = await db.query(Object.assign({values: rvs}, recQuery));
  154. let recId = recResult.rows[0].rec_id;
  155. let fno = 0;
  156. let fps = [];
  157. for (let cf of rec.control) {
  158. fno += 1;
  159. let values = [recId, fno, cf.tag, null, null, null, cf.data];
  160. fps.push(db.query(Object.assign({values: values}, fldQuery)));
  161. }
  162. for (let df of rec.data) {
  163. fno += 1;
  164. for (let sf of df.subfields) {
  165. let values = [recId, fno, df.tag, df.ind1, df.ind2, sf.code, sf.data];
  166. fps.push(db.query(Object.assign({values: values}, fldQuery)));
  167. }
  168. }
  169. await Promise.all(fps);
  170. log.debug('committed %s', rec.cn);
  171. }
  172. return miss.to.obj((rec, enc, cb) => {
  173. addRecord(rec).then(() => cb(), (err) => cb(err));
  174. }, (cb) => {
  175. db.query('COMMIT', cb);
  176. });
  177. }
  178. module.exports.importMarc = importMarc;
  179. /**
  180. * Render MARC data to a PostgreSQL text file suitable for COPY FROM.
  181. */
  182. function renderPostgresText(options) {
  183. let nextId = (options && options.initialId) || 1;
  184. function escape(txt) {
  185. if (txt == null) return '\\N';
  186. return txt.replace(/\\/g, '\\\\')
  187. .replace(/\r/g, '')
  188. .replace(/\n/g, '\\n')
  189. .replace(/\t/g, '\\t');
  190. }
  191. return new stream.Transform({
  192. objectMode: true,
  193. transform(rec, encoding, cb) {
  194. let id = nextId;
  195. log.debug('rendering record %s with id %s', rec.cn, id);
  196. nextId += 1;
  197. let fno = 0;
  198. if (rec.leader) {
  199. this.push([id, fno, 'LDR', null, null, null, escape(rec.leader)].join('\t') + '\n');
  200. }
  201. for (let cf of rec.control) {
  202. fno += 1;
  203. this.push([id, fno, cf.tag, null, null, null, escape(cf.data)].join('\t') + '\n');
  204. }
  205. for (let df of rec.data) {
  206. fno += 1;
  207. for (let sf of df.subfields) {
  208. this.push([id, fno, df.tag, df.ind1, df.ind2, sf.code, escape(sf.data)].join('\t') + '\n');
  209. }
  210. }
  211. cb();
  212. }
  213. });
  214. }
  215. module.exports.renderPostgresText = renderPostgresText;
Tip!

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

Comments

Loading...