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