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