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