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