pivot table procedure conceptually works
[pspp] / src / data / csv-file-writer.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 2010, 2011, 2012, 2013, 2014 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>. */
16
17 #include <config.h>
18
19 #include "data/csv-file-writer.h"
20
21 #include <ctype.h>
22 #include <errno.h>
23 #include <math.h>
24 #include <stdint.h>
25 #include <stdlib.h>
26 #include <sys/stat.h>
27 #include <time.h>
28
29 #include "data/calendar.h"
30 #include "data/case.h"
31 #include "data/casewriter-provider.h"
32 #include "data/casewriter.h"
33 #include "data/data-out.h"
34 #include "data/dictionary.h"
35 #include "data/file-handle-def.h"
36 #include "data/file-name.h"
37 #include "data/format.h"
38 #include "data/make-file.h"
39 #include "data/missing-values.h"
40 #include "data/settings.h"
41 #include "data/value-labels.h"
42 #include "data/variable.h"
43 #include "libpspp/assertion.h"
44 #include "libpspp/i18n.h"
45 #include "libpspp/message.h"
46 #include "libpspp/str.h"
47
48 #include "gl/ftoastr.h"
49 #include "gl/minmax.h"
50 #include "gl/unlocked-io.h"
51 #include "gl/xalloc.h"
52
53 #include "gettext.h"
54 #define _(msgid) gettext (msgid)
55 #define N_(msgid) (msgid)
56
57 /* A variable in a CSV file. */
58 struct csv_var
59   {
60     int width;                     /* Variable width (0 to 32767). */
61     int case_index;                /* Index into case. */
62     struct fmt_spec format;        /* Print format. */
63     struct missing_values missing; /* User-missing values, if recoding. */
64     struct val_labs *val_labs;  /* Value labels, if any and they are in use. */
65   };
66
67 /* Comma-separated value (CSV) file writer. */
68 struct csv_writer
69   {
70     struct file_handle *fh;     /* File handle. */
71     struct fh_lock *lock;       /* Mutual exclusion for file. */
72     FILE *file;                 /* File stream. */
73     struct replace_file *rf;    /* Ticket for replacing output file. */
74
75     struct csv_writer_options opts;
76
77     char *encoding;             /* Encoding used by variables. */
78
79     /* Variables. */
80     struct csv_var *csv_vars;   /* Variables. */
81     size_t n_csv_vars;         /* Number of variables. */
82   };
83
84 static const struct casewriter_class csv_file_casewriter_class;
85
86 static void write_var_names (struct csv_writer *, const struct dictionary *);
87
88 static bool write_error (const struct csv_writer *);
89 static bool close_writer (struct csv_writer *);
90
91 /* Initializes OPTS with default options for writing a CSV file. */
92 void
93 csv_writer_options_init (struct csv_writer_options *opts)
94 {
95   opts->recode_user_missing = false;
96   opts->include_var_names = false;
97   opts->use_value_labels = false;
98   opts->use_print_formats = false;
99   opts->decimal = settings_get_decimal_char (FMT_F);
100   opts->delimiter = ',';
101   opts->qualifier = '"';
102 }
103
104 /* Opens the CSV file designated by file handle FH for writing cases from
105    dictionary DICT according to the given OPTS.
106
107    No reference to D is retained, so it may be modified or
108    destroyed at will after this function returns. */
109 struct casewriter *
110 csv_writer_open (struct file_handle *fh, const struct dictionary *dict,
111                  const struct csv_writer_options *opts)
112 {
113   struct csv_writer *w;
114   int i;
115
116   /* Create and initialize writer. */
117   w = xmalloc (sizeof *w);
118   w->fh = fh_ref (fh);
119   w->lock = NULL;
120   w->file = NULL;
121   w->rf = NULL;
122
123   w->opts = *opts;
124
125   w->encoding = xstrdup (dict_get_encoding (dict));
126
127   w->n_csv_vars = dict_get_var_cnt (dict);
128   w->csv_vars = xnmalloc (w->n_csv_vars, sizeof *w->csv_vars);
129   for (i = 0; i < w->n_csv_vars; i++)
130     {
131       const struct variable *var = dict_get_var (dict, i);
132       struct csv_var *cv = &w->csv_vars[i];
133
134       cv->width = var_get_width (var);
135       cv->case_index = var_get_case_index (var);
136
137       cv->format = *var_get_print_format (var);
138       if (opts->recode_user_missing)
139         mv_copy (&cv->missing, var_get_missing_values (var));
140       else
141         mv_init (&cv->missing, cv->width);
142
143       if (opts->use_value_labels)
144         cv->val_labs = val_labs_clone (var_get_value_labels (var));
145       else
146         cv->val_labs = NULL;
147     }
148
149   /* Open file handle as an exclusive writer. */
150   /* TRANSLATORS: this fragment will be interpolated into messages in fh_lock()
151      that identify types of files. */
152   w->lock = fh_lock (fh, FH_REF_FILE, N_("CSV file"), FH_ACC_WRITE, true);
153   if (w->lock == NULL)
154     goto error;
155
156   /* Create the file on disk. */
157   w->rf = replace_file_start (fh_get_file_name (fh), "w", 0666,
158                               &w->file, NULL);
159   if (w->rf == NULL)
160     {
161       msg (ME, _("Error opening `%s' for writing as a system file: %s."),
162            fh_get_file_name (fh), strerror (errno));
163       goto error;
164     }
165
166   if (opts->include_var_names)
167     write_var_names (w, dict);
168
169   if (write_error (w))
170     goto error;
171
172   return casewriter_create (dict_get_proto (dict),
173                             &csv_file_casewriter_class, w);
174
175 error:
176   close_writer (w);
177   return NULL;
178 }
179
180 static bool
181 csv_field_needs_quoting (struct csv_writer *w, const char *s, size_t len)
182 {
183   const char *p;
184
185   for (p = s; p < &s[len]; p++)
186     if (*p == w->opts.qualifier || *p == w->opts.delimiter
187         || *p == '\n' || *p == '\r')
188       return true;
189
190   return false;
191 }
192
193 static void
194 csv_output_buffer (struct csv_writer *w, const char *s, size_t len)
195 {
196   if (csv_field_needs_quoting (w, s, len))
197     {
198       const char *p;
199
200       putc (w->opts.qualifier, w->file);
201       for (p = s; p < &s[len]; p++)
202         {
203           /* We are writing the output file in text mode, so transform any
204              explicit CR-LF line breaks into LF only, to allow the C library to
205              use correct system-specific new-lines. */
206           if (*p == '\r' && p[1] == '\n')
207             continue;
208
209           if (*p == w->opts.qualifier)
210             putc (w->opts.qualifier, w->file);
211           putc (*p, w->file);
212         }
213       putc (w->opts.qualifier, w->file);
214     }
215   else
216     fwrite (s, 1, len, w->file);
217 }
218
219 static void
220 csv_output_string (struct csv_writer *w, const char *s)
221 {
222   csv_output_buffer (w, s, strlen (s));
223 }
224
225 static void
226 write_var_names (struct csv_writer *w, const struct dictionary *d)
227 {
228   size_t i;
229
230   for (i = 0; i < w->n_csv_vars; i++)
231     {
232       if (i > 0)
233         putc (w->opts.delimiter, w->file);
234       csv_output_string (w, var_get_name (dict_get_var (d, i)));
235     }
236   putc ('\n', w->file);
237 }
238
239 static void
240 csv_output_format (struct csv_writer *w, const struct csv_var *cv,
241                    const union value *value)
242 {
243   char *s = data_out (value, w->encoding, &cv->format);
244   struct substring ss = ss_cstr (s);
245   if (cv->format.type != FMT_A)
246     ss_trim (&ss, ss_cstr (" "));
247   else
248     ss_rtrim (&ss, ss_cstr (" "));
249   csv_output_buffer (w, ss.string, ss.length);
250   free (s);
251 }
252
253 static double
254 extract_date (double number, int *y, int *m, int *d)
255 {
256   int yd;
257
258   calendar_offset_to_gregorian (number / 60. / 60. / 24., y, m, d, &yd);
259   return fmod (number, 60. * 60. * 24.);
260 }
261
262 static void
263 extract_time (double number, double *H, int *M, int *S)
264 {
265   *H = floor (number / 60. / 60.);
266   number = fmod (number, 60. * 60.);
267
268   *M = floor (number / 60.);
269   number = fmod (number, 60.);
270
271   *S = floor (number);
272 }
273
274 static void
275 csv_write_var__ (struct csv_writer *w, const struct csv_var *cv,
276                  const union value *value)
277 {
278   const char *label;
279
280   label = val_labs_find (cv->val_labs, value);
281   if (label != NULL)
282     csv_output_string (w, label);
283   else if (cv->width == 0 && value->f == SYSMIS)
284     csv_output_buffer (w, " ", 1);
285   else if (w->opts.use_print_formats)
286     csv_output_format (w, cv, value);
287   else
288     {
289       char s[MAX (DBL_STRLEN_BOUND, 128)];
290       char *cp;
291
292       switch (cv->format.type)
293         {
294         case FMT_F:
295         case FMT_COMMA:
296         case FMT_DOT:
297         case FMT_DOLLAR:
298         case FMT_PCT:
299         case FMT_E:
300         case FMT_CCA:
301         case FMT_CCB:
302         case FMT_CCC:
303         case FMT_CCD:
304         case FMT_CCE:
305         case FMT_N:
306         case FMT_Z:
307         case FMT_P:
308         case FMT_PK:
309         case FMT_IB:
310         case FMT_PIB:
311         case FMT_PIBHEX:
312         case FMT_RB:
313         case FMT_RBHEX:
314         case FMT_WKDAY:
315         case FMT_MONTH:
316           dtoastr (s, sizeof s, 0, 0, value->f);
317           cp = strpbrk (s, ".,");
318           if (cp != NULL)
319             *cp = w->opts.decimal;
320           break;
321
322         case FMT_DATE:
323         case FMT_ADATE:
324         case FMT_EDATE:
325         case FMT_JDATE:
326         case FMT_SDATE:
327         case FMT_QYR:
328         case FMT_MOYR:
329         case FMT_WKYR:
330           if (value->f < 0)
331             strcpy (s, " ");
332           else
333             {
334               int y, m, d;
335
336               extract_date (value->f, &y, &m, &d);
337               snprintf (s, sizeof s, "%02d/%02d/%04d", m, d, y);
338             }
339           break;
340
341         case FMT_DATETIME:
342           if (value->f < 0)
343             strcpy (s, " ");
344           else
345             {
346               int y, m, d, M, S;
347               double H;
348
349               extract_time (extract_date (value->f, &y, &m, &d), &H, &M, &S);
350               snprintf (s, sizeof s, "%02d/%02d/%04d %02.0f:%02d:%02d",
351                         m, d, y, H, M, S);
352             }
353           break;
354
355         case FMT_TIME:
356         case FMT_DTIME:
357           {
358             double H;
359             int M, S;
360
361             extract_time (fabs (value->f), &H, &M, &S);
362             snprintf (s, sizeof s, "%s%02.0f:%02d:%02d",
363                       value->f < 0 ? "-" : "", H, M, S);
364           }
365           break;
366
367         case FMT_A:
368         case FMT_AHEX:
369           csv_output_format (w, cv, value);
370           return;
371
372         case FMT_NUMBER_OF_FORMATS:
373           NOT_REACHED ();
374         }
375       csv_output_string (w, s);
376     }
377 }
378
379 static void
380 csv_write_var (struct csv_writer *w, const struct csv_var *cv,
381                const union value *value)
382 {
383   if (mv_is_value_missing (&cv->missing, value, MV_USER))
384     {
385       union value missing;
386
387       value_init (&missing, cv->width);
388       value_set_missing (&missing, cv->width);
389       csv_write_var__ (w, cv, &missing);
390       value_destroy (&missing, cv->width);
391     }
392   else
393     csv_write_var__ (w, cv, value);
394 }
395
396 static void
397 csv_write_case (struct csv_writer *w, const struct ccase *c)
398 {
399   size_t i;
400
401   for (i = 0; i < w->n_csv_vars; i++)
402     {
403       const struct csv_var *cv = &w->csv_vars[i];
404
405       if (i > 0)
406         putc (w->opts.delimiter, w->file);
407       csv_write_var (w, cv, case_data_idx (c, cv->case_index));
408     }
409   putc ('\n', w->file);
410 }
411 \f
412 /* Writes case C to CSV file W. */
413 static void
414 csv_file_casewriter_write (struct casewriter *writer, void *w_,
415                            struct ccase *c)
416 {
417   struct csv_writer *w = w_;
418
419   if (ferror (w->file))
420     {
421       casewriter_force_error (writer);
422       case_unref (c);
423       return;
424     }
425
426   csv_write_case (w, c);
427   case_unref (c);
428 }
429
430 /* Destroys CSV file writer W. */
431 static void
432 csv_file_casewriter_destroy (struct casewriter *writer, void *w_)
433 {
434   struct csv_writer *w = w_;
435   if (!close_writer (w))
436     casewriter_force_error (writer);
437 }
438
439 /* Returns true if an I/O error has occurred on WRITER, false otherwise. */
440 bool
441 write_error (const struct csv_writer *writer)
442 {
443   return ferror (writer->file);
444 }
445
446 /* Closes a CSV file after we're done with it.
447    Returns true if successful, false if an I/O error occurred. */
448 bool
449 close_writer (struct csv_writer *w)
450 {
451   size_t i;
452   bool ok;
453
454   if (w == NULL)
455     return true;
456
457   ok = true;
458   if (w->file != NULL)
459     {
460       if (write_error (w))
461         ok = false;
462       if (fclose (w->file) == EOF)
463         ok = false;
464
465       if (!ok)
466         msg (ME, _("An I/O error occurred writing CSV file `%s'."),
467              fh_get_file_name (w->fh));
468
469       if (ok ? !replace_file_commit (w->rf) : !replace_file_abort (w->rf))
470         ok = false;
471     }
472
473   fh_unlock (w->lock);
474   fh_unref (w->fh);
475
476   free (w->encoding);
477
478   for (i = 0; i < w->n_csv_vars; i++)
479     {
480       struct csv_var *cv = &w->csv_vars[i];
481       mv_destroy (&cv->missing);
482       val_labs_destroy (cv->val_labs);
483     }
484
485   free (w->csv_vars);
486   free (w);
487
488   return ok;
489 }
490
491 /* CSV file writer casewriter class. */
492 static const struct casewriter_class csv_file_casewriter_class =
493   {
494     csv_file_casewriter_write,
495     csv_file_casewriter_destroy,
496     NULL,
497   };