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