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