Fixed some more errors in the spreadsheet readers
[pspp] / src / language / data-io / get-data.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 2007, 2008, 2009, 2010, 2011, 2012,
3                  2013 Free Software Foundation, Inc.
4
5    This program is free software: you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation, either version 3 of the License, or
8    (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program.  If not, see <http://www.gnu.org/licenses/>. */
17
18 #include <config.h>
19
20 #include <stdlib.h>
21
22 #include <string.h>
23
24 #include "data/dataset.h"
25 #include "data/dictionary.h"
26 #include "data/format.h"
27 #include "data/gnumeric-reader.h"
28 #include "data/ods-reader.h"
29 #include "data/spreadsheet-reader.h"
30 #include "data/psql-reader.h"
31 #include "data/settings.h"
32 #include "language/command.h"
33 #include "language/data-io/data-parser.h"
34 #include "language/data-io/data-reader.h"
35 #include "language/data-io/file-handle.h"
36 #include "language/data-io/placement-parser.h"
37 #include "language/lexer/format-parser.h"
38 #include "language/lexer/lexer.h"
39 #include "libpspp/cast.h"
40 #include "libpspp/i18n.h"
41 #include "libpspp/message.h"
42
43 #include "gl/xalloc.h"
44
45 #include "gettext.h"
46 #define _(msgid) gettext (msgid)
47 #define N_(msgid) (msgid)
48
49 static bool parse_spreadsheet (struct lexer *lexer, char **filename,
50                                struct spreadsheet_read_options *opts);
51
52 static void destroy_spreadsheet_read_info (struct spreadsheet_read_options *);
53
54 static int parse_get_txt (struct lexer *lexer, struct dataset *);
55 static int parse_get_psql (struct lexer *lexer, struct dataset *);
56
57 int
58 cmd_get_data (struct lexer *lexer, struct dataset *ds)
59 {
60   struct spreadsheet_read_options opts;
61   char *tok = NULL;
62   lex_force_match (lexer, T_SLASH);
63
64   if (!lex_force_match_id (lexer, "TYPE"))
65     goto error;
66
67   lex_force_match (lexer, T_EQUALS);
68
69   tok = strdup (lex_tokcstr (lexer));
70   if (lex_match_id (lexer, "TXT"))
71     {
72       free (tok);
73       return parse_get_txt (lexer, ds);
74     }
75   else if (lex_match_id (lexer, "PSQL"))
76     {
77       free (tok);
78       return parse_get_psql (lexer, ds);
79     }
80   else if (lex_match_id (lexer, "GNM") || 
81       lex_match_id (lexer, "ODS"))
82     {
83       char *filename = NULL;
84       struct casereader *reader = NULL;
85       struct dictionary *dict = NULL;
86
87       if (!parse_spreadsheet (lexer, &filename, &opts))
88         goto error;
89
90       if ( 0 == strncasecmp (tok, "GNM", 3))
91         {
92           struct spreadsheet *spreadsheet = gnumeric_probe (filename, true);
93           if (spreadsheet == NULL)
94             goto error;
95           reader = gnumeric_make_reader (spreadsheet, &opts);
96           dict = spreadsheet->dict;
97         }
98       else if (0 == strncasecmp (tok, "ODS", 3))
99         {
100           struct spreadsheet *spreadsheet = ods_probe (filename, true);
101           if (spreadsheet == NULL)
102             goto error;
103           reader = ods_make_reader (spreadsheet, &opts);
104           dict = spreadsheet->dict;
105           ods_destroy (spreadsheet);
106         }
107
108       free (filename);
109
110       if (reader)
111         {
112           dataset_set_dict (ds, dict);
113           dataset_set_source (ds, reader);
114           free (tok);
115           destroy_spreadsheet_read_info (&opts);
116           return CMD_SUCCESS;
117         }
118     }
119   else
120     msg (SE, _("Unsupported TYPE %s."), tok);
121
122
123  error:
124   destroy_spreadsheet_read_info (&opts);
125   free (tok);
126   return CMD_FAILURE;
127 }
128
129 static int
130 parse_get_psql (struct lexer *lexer, struct dataset *ds)
131 {
132   struct psql_read_info psql;
133   psql.allow_clear = false;
134   psql.conninfo = NULL;
135   psql.str_width = -1;
136   psql.bsize = -1;
137   ds_init_empty (&psql.sql);
138
139   lex_force_match (lexer, T_SLASH);
140
141   if (!lex_force_match_id (lexer, "CONNECT"))
142     goto error;
143
144   lex_force_match (lexer, T_EQUALS);
145
146   if (!lex_force_string (lexer))
147     goto error;
148
149   psql.conninfo = ss_xstrdup (lex_tokss (lexer));
150
151   lex_get (lexer);
152
153   while (lex_match (lexer, T_SLASH) )
154     {
155       if ( lex_match_id (lexer, "ASSUMEDSTRWIDTH"))
156         {
157           lex_match (lexer, T_EQUALS);
158           psql.str_width = lex_integer (lexer);
159           lex_get (lexer);
160         }
161       else if ( lex_match_id (lexer, "BSIZE"))
162         {
163           lex_match (lexer, T_EQUALS);
164           psql.bsize = lex_integer (lexer);
165           lex_get (lexer);
166         }
167       else if ( lex_match_id (lexer, "UNENCRYPTED"))
168         {
169           psql.allow_clear = true;
170         }
171       else if (lex_match_id (lexer, "SQL"))
172         {
173           lex_match (lexer, T_EQUALS);
174           if ( ! lex_force_string (lexer) )
175             goto error;
176
177           ds_put_substring (&psql.sql, lex_tokss (lexer));
178           lex_get (lexer);
179         }
180      }
181   {
182     struct dictionary *dict = NULL;
183     struct casereader *reader = psql_open_reader (&psql, &dict);
184
185     if ( reader )
186       {
187         dataset_set_dict (ds, dict);
188         dataset_set_source (ds, reader);
189       }
190   }
191
192   ds_destroy (&psql.sql);
193   free (psql.conninfo);
194
195   return CMD_SUCCESS;
196
197  error:
198
199   ds_destroy (&psql.sql);
200   free (psql.conninfo);
201
202   return CMD_FAILURE;
203 }
204
205 static bool
206 parse_spreadsheet (struct lexer *lexer, char **filename, 
207                    struct spreadsheet_read_options *opts)
208 {
209   opts->sheet_index = 1;
210   opts->sheet_name = NULL;
211   opts->cell_range = NULL;
212   opts->read_names = true;
213   opts->asw = -1;
214
215   lex_force_match (lexer, T_SLASH);
216
217   if (!lex_force_match_id (lexer, "FILE"))
218     goto error;
219
220   lex_force_match (lexer, T_EQUALS);
221
222   if (!lex_force_string (lexer))
223     goto error;
224
225   *filename  = utf8_to_filename (lex_tokcstr (lexer));
226
227   lex_get (lexer);
228
229   while (lex_match (lexer, T_SLASH) )
230     {
231       if ( lex_match_id (lexer, "ASSUMEDSTRWIDTH"))
232         {
233           lex_match (lexer, T_EQUALS);
234           opts->asw = lex_integer (lexer);
235           lex_get (lexer);
236         }
237       else if (lex_match_id (lexer, "SHEET"))
238         {
239           lex_match (lexer, T_EQUALS);
240           if (lex_match_id (lexer, "NAME"))
241             {
242               if ( ! lex_force_string (lexer) )
243                 goto error;
244
245               opts->sheet_name = ss_xstrdup (lex_tokss (lexer));
246               opts->sheet_index = -1;
247
248               lex_get (lexer);
249             }
250           else if (lex_match_id (lexer, "INDEX"))
251             {
252               opts->sheet_index = lex_integer (lexer);
253               if (opts->sheet_index <= 0)
254                 {
255                   msg (SE, _("The sheet index must be greater than or equal to 1"));
256                   goto error;
257                 }
258               lex_get (lexer);
259             }
260           else
261             {
262               msg (SE, _("%s must be followed by either \"%s\" or \"%s\"."),
263                    "/SHEET", "NAME", "INDEX");
264               goto error;
265             }
266         }
267       else if (lex_match_id (lexer, "CELLRANGE"))
268         {
269           lex_match (lexer, T_EQUALS);
270
271           if (lex_match_id (lexer, "FULL"))
272             {
273               opts->cell_range = NULL;
274             }
275           else if (lex_match_id (lexer, "RANGE"))
276             {
277               if ( ! lex_force_string (lexer) )
278                 goto error;
279
280               opts->cell_range = ss_xstrdup (lex_tokss (lexer));
281               lex_get (lexer);
282             }
283           else
284             {
285               msg (SE, _("%s must be followed by either \"%s\" or \"%s\"."),
286                    "/CELLRANGE", "FULL", "RANGE");
287               goto error;
288             }
289         }
290       else if (lex_match_id (lexer, "READNAMES"))
291         {
292           lex_match (lexer, T_EQUALS);
293
294           if ( lex_match_id (lexer, "ON"))
295             {
296               opts->read_names = true;
297             }
298           else if (lex_match_id (lexer, "OFF"))
299             {
300               opts->read_names = false;
301             }
302           else
303             {
304               msg (SE, _("%s must be followed by either \"%s\" or \"%s\"."),
305                    "/READNAMES", "ON", "OFF");
306               goto error;
307             }
308         }
309       else
310         {
311           lex_error (lexer, NULL);
312           goto error;
313         }
314     }
315
316   return true;
317
318  error:
319   return false;
320 }
321
322
323 static bool
324 set_type (struct data_parser *parser, const char *subcommand,
325           enum data_parser_type type, bool *has_type)
326 {
327   if (!*has_type)
328     {
329       data_parser_set_type (parser, type);
330       *has_type = true;
331     }
332   else if (type != data_parser_get_type (parser))
333     {
334       msg (SE, _("%s is allowed only with %s arrangement, but %s arrangement "
335                  "was stated or implied earlier in this command."),
336            subcommand,
337            type == DP_FIXED ? "FIXED" : "DELIMITED",
338            type == DP_FIXED ? "DELIMITED" : "FIXED");
339       return false;
340     }
341   return true;
342 }
343
344 static int
345 parse_get_txt (struct lexer *lexer, struct dataset *ds)
346 {
347   struct data_parser *parser = NULL;
348   struct dictionary *dict = dict_create (get_default_encoding ());
349   struct file_handle *fh = NULL;
350   struct dfm_reader *reader = NULL;
351   char *encoding = NULL;
352   char *name = NULL;
353
354   int record;
355   enum data_parser_type type;
356   bool has_type;
357
358   lex_force_match (lexer, T_SLASH);
359
360   if (!lex_force_match_id (lexer, "FILE"))
361     goto error;
362   lex_force_match (lexer, T_EQUALS);
363   fh = fh_parse (lexer, FH_REF_FILE | FH_REF_INLINE, NULL);
364   if (fh == NULL)
365     goto error;
366
367   parser = data_parser_create (dict);
368   has_type = false;
369   data_parser_set_type (parser, DP_DELIMITED);
370   data_parser_set_span (parser, false);
371   data_parser_set_quotes (parser, ss_empty ());
372   data_parser_set_empty_line_has_field (parser, true);
373
374   for (;;)
375     {
376       if (!lex_force_match (lexer, T_SLASH))
377         goto error;
378
379       if (lex_match_id (lexer, "ENCODING"))
380         {
381           lex_match (lexer, T_EQUALS);
382           if (!lex_force_string (lexer))
383             goto error;
384
385           free (encoding);
386           encoding = ss_xstrdup (lex_tokss (lexer));
387
388           lex_get (lexer);
389         }
390       else if (lex_match_id (lexer, "ARRANGEMENT"))
391         {
392           bool ok;
393
394           lex_match (lexer, T_EQUALS);
395           if (lex_match_id (lexer, "FIXED"))
396             ok = set_type (parser, "ARRANGEMENT=FIXED", DP_FIXED, &has_type);
397           else if (lex_match_id (lexer, "DELIMITED"))
398             ok = set_type (parser, "ARRANGEMENT=DELIMITED",
399                            DP_DELIMITED, &has_type);
400           else
401             {
402               lex_error_expecting (lexer, "FIXED", "DELIMITED", NULL_SENTINEL);
403               goto error;
404             }
405           if (!ok)
406             goto error;
407         }
408       else if (lex_match_id (lexer, "FIRSTCASE"))
409         {
410           lex_match (lexer, T_EQUALS);
411           if (!lex_force_int (lexer))
412             goto error;
413           if (lex_integer (lexer) < 1)
414             {
415               msg (SE, _("Value of FIRSTCASE must be 1 or greater."));
416               goto error;
417             }
418           data_parser_set_skip (parser, lex_integer (lexer) - 1);
419           lex_get (lexer);
420         }
421       else if (lex_match_id_n (lexer, "DELCASE", 4))
422         {
423           if (!set_type (parser, "DELCASE", DP_DELIMITED, &has_type))
424             goto error;
425           lex_match (lexer, T_EQUALS);
426           if (lex_match_id (lexer, "LINE"))
427             data_parser_set_span (parser, false);
428           else if (lex_match_id (lexer, "VARIABLES"))
429             {
430               data_parser_set_span (parser, true);
431
432               /* VARIABLES takes an integer argument, but for no
433                  good reason.  We just ignore it. */
434               if (!lex_force_int (lexer))
435                 goto error;
436               lex_get (lexer);
437             }
438           else
439             {
440               lex_error_expecting (lexer, "LINE", "VARIABLES", NULL_SENTINEL);
441               goto error;
442             }
443         }
444       else if (lex_match_id (lexer, "FIXCASE"))
445         {
446           if (!set_type (parser, "FIXCASE", DP_FIXED, &has_type))
447             goto error;
448           lex_match (lexer, T_EQUALS);
449           if (!lex_force_int (lexer))
450             goto error;
451           if (lex_integer (lexer) < 1)
452             {
453               msg (SE, _("Value of FIXCASE must be at least 1."));
454               goto error;
455             }
456           data_parser_set_records (parser, lex_integer (lexer));
457           lex_get (lexer);
458         }
459       else if (lex_match_id (lexer, "IMPORTCASES"))
460         {
461           lex_match (lexer, T_EQUALS);
462           if (lex_match (lexer, T_ALL))
463             {
464               data_parser_set_case_limit (parser, -1);
465               data_parser_set_case_percent (parser, 100);
466             }
467           else if (lex_match_id (lexer, "FIRST"))
468             {
469               if (!lex_force_int (lexer))
470                 goto error;
471               if (lex_integer (lexer) < 1)
472                 {
473                   msg (SE, _("Value of FIRST must be at least 1."));
474                   goto error;
475                 }
476               data_parser_set_case_limit (parser, lex_integer (lexer));
477               lex_get (lexer);
478             }
479           else if (lex_match_id (lexer, "PERCENT"))
480             {
481               if (!lex_force_int (lexer))
482                 goto error;
483               if (lex_integer (lexer) < 1 || lex_integer (lexer) > 100)
484                 {
485                   msg (SE, _("Value of PERCENT must be between 1 and 100."));
486                   goto error;
487                 }
488               data_parser_set_case_percent (parser, lex_integer (lexer));
489               lex_get (lexer);
490             }
491         }
492       else if (lex_match_id_n (lexer, "DELIMITERS", 4))
493         {
494           struct string hard_seps = DS_EMPTY_INITIALIZER;
495           const char *soft_seps = "";
496           struct substring s;
497           int c;
498
499           if (!set_type (parser, "DELIMITERS", DP_DELIMITED, &has_type))
500             goto error;
501           lex_match (lexer, T_EQUALS);
502
503           if (!lex_force_string (lexer))
504             goto error;
505
506           /* XXX should support multibyte UTF-8 characters */
507           s = lex_tokss (lexer);
508           if (ss_match_string (&s, ss_cstr ("\\t")))
509             ds_put_cstr (&hard_seps, "\t");
510           if (ss_match_string (&s, ss_cstr ("\\\\")))
511             ds_put_cstr (&hard_seps, "\\");
512           while ((c = ss_get_byte (&s)) != EOF)
513             if (c == ' ')
514               soft_seps = " ";
515             else
516               ds_put_byte (&hard_seps, c);
517           data_parser_set_soft_delimiters (parser, ss_cstr (soft_seps));
518           data_parser_set_hard_delimiters (parser, ds_ss (&hard_seps));
519           ds_destroy (&hard_seps);
520
521           lex_get (lexer);
522         }
523       else if (lex_match_id (lexer, "QUALIFIERS"))
524         {
525           if (!set_type (parser, "QUALIFIERS", DP_DELIMITED, &has_type))
526             goto error;
527           lex_match (lexer, T_EQUALS);
528
529           if (!lex_force_string (lexer))
530             goto error;
531
532           /* XXX should support multibyte UTF-8 characters */
533           if (settings_get_syntax () == COMPATIBLE
534               && ss_length (lex_tokss (lexer)) != 1)
535             {
536               msg (SE, _("In compatible syntax mode, the QUALIFIER string "
537                          "must contain exactly one character."));
538               goto error;
539             }
540
541           data_parser_set_quotes (parser, lex_tokss (lexer));
542           lex_get (lexer);
543         }
544       else if (settings_get_syntax () == ENHANCED
545                && lex_match_id (lexer, "ESCAPE"))
546         data_parser_set_quote_escape (parser, true);
547       else if (lex_match_id (lexer, "VARIABLES"))
548         break;
549       else
550         {
551           lex_error_expecting (lexer, "VARIABLES", NULL_SENTINEL);
552           goto error;
553         }
554     }
555   lex_match (lexer, T_EQUALS);
556
557   record = 1;
558   type = data_parser_get_type (parser);
559   do
560     {
561       struct fmt_spec input, output;
562       struct variable *v;
563       int fc, lc;
564
565       while (type == DP_FIXED && lex_match (lexer, T_SLASH))
566         {
567           if (!lex_force_int (lexer))
568             goto error;
569           if (lex_integer (lexer) < record)
570             {
571               msg (SE, _("The record number specified, %ld, is at or "
572                          "before the previous record, %d.  Data "
573                          "fields must be listed in order of "
574                          "increasing record number."),
575                    lex_integer (lexer), record);
576               goto error;
577             }
578           if (lex_integer (lexer) > data_parser_get_records (parser))
579             {
580               msg (SE, _("The record number specified, %ld, exceeds "
581                          "the number of records per case specified "
582                          "on FIXCASE, %d."),
583                    lex_integer (lexer), data_parser_get_records (parser));
584               goto error;
585             }
586           record = lex_integer (lexer);
587           lex_get (lexer);
588         }
589
590       if (!lex_force_id (lexer)
591           || !dict_id_is_valid (dict, lex_tokcstr (lexer), true))
592         goto error;
593       name = xstrdup (lex_tokcstr (lexer));
594       lex_get (lexer);
595
596       if (type == DP_DELIMITED)
597         {
598           if (!parse_format_specifier (lexer, &input)
599               || !fmt_check_input (&input))
600             goto error;
601
602           output = fmt_for_output_from_input (&input);
603         }
604       else
605         {
606           char fmt_type_name[FMT_TYPE_LEN_MAX + 1];
607           enum fmt_type fmt_type;
608           int w, d;
609
610           if (!parse_column_range (lexer, 0, &fc, &lc, NULL))
611             goto error;
612
613           /* Accept a format (e.g. F8.2) or just a type name (e.g. DOLLAR).  */
614           if (!parse_abstract_format_specifier (lexer, fmt_type_name, &w, &d))
615             goto error;
616           if (!fmt_from_name (fmt_type_name, &fmt_type))
617             {
618               msg (SE, _("Unknown format type `%s'."), fmt_type_name);
619               goto error;
620             }
621
622           /* Compose input format. */
623           input.type = fmt_type;
624           input.w = lc - fc + 1;
625           input.d = 0;
626           if (!fmt_check_input (&input))
627             goto error;
628
629           /* Compose output format. */
630           if (w != 0)
631             {
632               output.type = fmt_type;
633               output.w = w;
634               output.d = d;
635               if (!fmt_check_output (&output))
636                 goto error;
637             }
638           else
639             output = fmt_for_output_from_input (&input);
640         }
641
642       v = dict_create_var (dict, name, fmt_var_width (&input));
643       if (v == NULL)
644         {
645           msg (SE, _("%s is a duplicate variable name."), name);
646           goto error;
647         }
648       var_set_both_formats (v, &output);
649
650       if (type == DP_DELIMITED)
651         data_parser_add_delimited_field (parser, &input,
652                                          var_get_case_index (v),
653                                          name);
654       else
655         data_parser_add_fixed_field (parser, &input, var_get_case_index (v),
656                                      name, record, fc);
657       free (name);
658       name = NULL;
659     }
660   while (lex_token (lexer) != T_ENDCMD);
661
662   reader = dfm_open_reader (fh, lexer, encoding);
663   if (reader == NULL)
664     goto error;
665
666   data_parser_make_active_file (parser, ds, reader, dict);
667   fh_unref (fh);
668   free (encoding);
669   return CMD_SUCCESS;
670
671  error:
672   data_parser_destroy (parser);
673   dict_destroy (dict);
674   fh_unref (fh);
675   free (name);
676   free (encoding);
677   return CMD_CASCADING_FAILURE;
678 }
679
680
681 static void 
682 destroy_spreadsheet_read_info (struct spreadsheet_read_options *opts)
683 {
684   free (opts->cell_range);
685   free (opts->sheet_name);
686 }