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