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