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