File: recsel.c

package info (click to toggle)
recutils 1.9-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 15,328 kB
  • sloc: ansic: 80,756; sh: 11,649; yacc: 1,978; makefile: 323; lex: 225; sed: 16
file content (442 lines) | stat: -rw-r--r-- 12,913 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
/* recsel.c - Selecting records.  */

/* Copyright (C) 2010-2022 Jose E. Marchesi */

/* This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <config.h>

#include <getopt.h>
#include <string.h>
#include <stdlib.h>
#include <xalloc.h>
#include <gettext.h>
#define _(str) gettext (str)

#include <rec.h>
#include <recutl.h>

/*
 * Global variables
 */

char      *recutl_sex_str      = NULL;
rec_sex_t  recutl_sex          = NULL;
char      *recutl_quick_str    = NULL;
char      *recsel_fex_str      = NULL;
rec_fex_t  recsel_fex          = NULL;
char      *recutl_type         = NULL;
bool       recsel_collapse     = false;
bool       recsel_count        = false;
bool       recutl_insensitive  = false;
bool       recsel_descriptors  = false;
rec_fex_t  recutl_sort_by_fields  = NULL;
rec_fex_t  recsel_group_by_fields = NULL;
rec_writer_mode_t recsel_write_mode = REC_WRITER_NORMAL;
char      *recsel_password     = NULL;
bool       recsel_uniq         = false;
size_t     recutl_random       = 0;
char      *recsel_join         = NULL;

/*
 * Command line options management.
 */

enum
{
  COMMON_ARGS,
  RECORD_SELECTION_ARGS,
  PRINT_ARG,
  PRINT_VALUES_ARG,
  PRINT_IN_A_ROW_ARG,
  COLLAPSE_ARG,
  COUNT_ARG,
  DESCRIPTOR_ARG,
  PRINT_SEXPS_ARG,
  SORT_ARG,
#if defined REC_CRYPT_SUPPORT
  PASSWORD_ARG,
#endif
  UNIQ_ARG,
  GROUP_BY_ARG,
  JOIN_ARG
};

static const struct option GNU_longOptions[] =
  {
    COMMON_LONG_ARGS,
    RECORD_SELECTION_LONG_ARGS,
    {"print", required_argument, NULL, PRINT_ARG},
    {"print-values", required_argument, NULL, PRINT_VALUES_ARG},
    {"print-row", required_argument, NULL, PRINT_IN_A_ROW_ARG},
    {"collapse", no_argument, NULL, COLLAPSE_ARG},
    {"count", no_argument, NULL, COUNT_ARG},
    {"include-descriptors", no_argument, NULL, DESCRIPTOR_ARG},
    {"print-sexps", no_argument, NULL, PRINT_SEXPS_ARG},
    {"sort", required_argument, NULL, SORT_ARG},
#if defined REC_CRYPT_SUPPORT
    {"password", required_argument, NULL, PASSWORD_ARG},
#endif
    {"uniq", no_argument, NULL, UNIQ_ARG},
    {"group-by", required_argument, NULL, GROUP_BY_ARG},
    {"join", required_argument, NULL, JOIN_ARG},
    {NULL, 0, NULL, 0}
  };

/*
 * Functions.
 */

void
recutl_print_help (void)
{
  /* TRANSLATORS: --help output, recsel synopsis.
     no-wrap */
  printf (_("\
Usage: recsel [OPTION]... [-t TYPE] [-j FIELD] [-n INDEXES | -e RECORD_EXPR | -q STR | -m NUM] [-c | (-p|-P) FIELD_EXPR] [FILE]...\n"));

  /* TRANSLATORS: --help output, recsel arguments.
     no-wrap */
  fputs(_("\
Select and print rec data.\n"), stdout);

  puts ("");
  /* TRANSLATORS: --help output, recsel arguments.
     no-wrap */
  fputs (_("\
  -d, --include-descriptors           print record descriptors along with the matched\n\
                                        records.\n\
  -C, --collapse                      do not section the result in records with newlines.\n\
  -S, --sort=FIELD,...                sort the output by the specified fields.\n\
  -G, --group-by=FIELD,...            group records by the specified fields.\n\
  -U, --uniq                          remove duplicated fields in the output records.\n"),
         stdout);

#if defined REC_CRYPT_SUPPORT
  /* TRANSLATORS: --help output, encryption related options.
     no-wrap */
  fputs (_("\
  -s, --password=STR                  decrypt confidential fields with the given password.\n"),
         stdout);
#endif

  recutl_print_help_common ();

  puts ("");
  recutl_print_help_record_selection ();
  fputs (_("\
  -j, --join=FIELD                    perform an inner join using the specified field.\n"),
         stdout);

  puts ("");
  /* TRANSLATORS: --help output, recsel output options.
     no-wrap */
  fputs (_("\
Output options:\n\
  -p, --print=FIELDS                  comma-separated list of fields to print for each\n\
                                        matching record.\n\
  -P, --print-values=FIELDS           as -p, but print only the values of the selected\n\
                                        fields.\n\
  -R, --print-row=FIELDS              as -P, but separate the values with spaces instead\n\
                                        of newlines.\n\
  -c, --count                         print a count of the matching records instead of\n\
                                        the records themselves.\n"), stdout);

  puts ("");
  /* TRANSLATORS: --help output, recsel special options.
     no-wrap */
  fputs (_("\
Special options:\n\
      --print-sexps                   print the data in sexps instead of rec format.\n"),
         stdout);

  puts ("");
  recutl_print_help_footer ();
}

void
recsel_parse_args (int argc,
                   char **argv)
{
  char c;
  int ret;

  while ((ret = getopt_long (argc,
                             argv,
                             RECORD_SELECTION_SHORT_ARGS
                             ENCRYPTION_SHORT_ARGS
                             "S:Cdcp:P:R:UG:j:",
                             GNU_longOptions,
                             NULL)) != -1)
    {
      c = ret;
      switch (c)
        {
        COMMON_ARGS_CASES
        RECORD_SELECTION_ARGS_CASES
        case DESCRIPTOR_ARG:
        case 'd':
          recsel_descriptors = true;
          break;
        case PRINT_SEXPS_ARG:
          recsel_write_mode = REC_WRITER_SEXP;
          break;
        case UNIQ_ARG:
        case 'U':
          recsel_uniq = true;
          break;
#if defined REC_CRYPT_SUPPORT
        case PASSWORD_ARG:
        case 's':
          if (recsel_password != NULL)
            recutl_fatal (_("more than one password was specified\n"));

          recsel_password = xstrdup (optarg);
          break;
#endif
        case SORT_ARG:
        case 'S':
          if (recutl_sort_by_fields)
            recutl_fatal (_("only one field list can be specified\
 as a sorting criteria.\n"));

          /* Parse the field name.  */
          if (!rec_fex_check (optarg, REC_FEX_CSV))
            recutl_fatal (_("invalid field names in -S.\n"));

          recutl_sort_by_fields = rec_fex_new (optarg, REC_FEX_CSV);
          if (!recutl_sort_by_fields)
            recutl_fatal (_("internal error creating fex.\n"));
          break;
        case JOIN_ARG:
        case 'j':
          if (recsel_join)
            recutl_fatal (_("only one field can be specified as join criteria.\n"));

          if (!rec_field_name_p (optarg))
            recutl_fatal (_("please specify a correct field name to -j|--join.\n"));

          recsel_join = xstrdup (optarg);
          break;
        case GROUP_BY_ARG:
        case 'G':
          if (recsel_group_by_fields)
            recutl_fatal (_("only one field list can be specified as\
 a grouping criteria.\n"));

          /* Parse the field name.  */
          if (!rec_fex_check (optarg, REC_FEX_CSV))
            recutl_fatal (_("invalid field names in -G.\n"));

          recsel_group_by_fields = rec_fex_new (optarg, REC_FEX_CSV);
          if (!recsel_group_by_fields)
            recutl_fatal (_("internal error creating fex.\n"));

          break;
        case PRINT_ARG:
        case PRINT_VALUES_ARG:
        case PRINT_IN_A_ROW_ARG:
        case 'p':
        case 'P':
        case 'R':
          if (recsel_count)
            recutl_fatal (_("cannot specify -[pPR] and also -c.\n"));

          if ((c == 'P') || (c == PRINT_VALUES_ARG))
            recsel_write_mode = REC_WRITER_VALUES;

          if ((c == 'R') || (c == PRINT_IN_A_ROW_ARG))
            recsel_write_mode = REC_WRITER_VALUES_ROW;

          recsel_fex_str = xstrdup (optarg);

          if (!rec_fex_check (recsel_fex_str, REC_FEX_SUBSCRIPTS))
            recutl_fatal (_("invalid list of fields in -%c\n"), c);

          /* Create the field expresion.  */
          recsel_fex = rec_fex_new (recsel_fex_str,
                                    REC_FEX_SUBSCRIPTS);
          if (!recsel_fex)
            recutl_fatal (_("internal error creating the field expression.\n"));

          /* Check that all the functions called in the fex exist.
             Otherwise raise an error.  */
          {
            size_t i = 0;
            for (i = 0; i < rec_fex_size (recsel_fex); i++)
              {
                rec_fex_elem_t elem = rec_fex_get (recsel_fex, i);
                const char *fname = rec_fex_elem_function_name (elem);

                if (fname && !rec_aggregate_std_p (fname))
                  recutl_fatal (_("invalid aggregate function '%s'\n"), fname);
              }
          }
          break;
        case COLLAPSE_ARG:
        case 'C':
          recsel_collapse = true;
          break;
        case COUNT_ARG:
        case 'c':
          if (recsel_fex_str)
            {
              recutl_fatal (_("cannot specify -c and also -p.\n"));
              exit (EXIT_FAILURE);
            }

          recsel_count = true;
          break;
        default:
          exit (EXIT_FAILURE);
        }
    }

  /* Global checks on the parameters.  */
  if (!recutl_type && recsel_join)
    recutl_fatal (_("joins can only be used when a named record\
 set is selected.\n"));
}

bool
recsel_process_data (rec_db_t db)
{
  int rset_size = 0;
  rec_rset_t rset = NULL;
  rec_writer_t writer = NULL;


#if defined REC_CRYPT_SUPPORT

  /* If recsel was called interactively and with an empty -s, was not
     used then prompt the user for it.  Otherwise use the password
     specified in the command line if any.  */

  if (!recsel_password
      && (recutl_type || (rec_db_size (db) == 1))
      && recutl_interactive ())
    {
      rec_rset_t rset;
      rec_fex_t confidential_fields;

      if (recutl_type)
        rset = rec_db_get_rset_by_type (db, recutl_type);
      else
        rset = rec_db_get_rset (db, 0);

      if (rset)
        {
          confidential_fields = rec_rset_confidential (rset);
          if (rec_fex_size (confidential_fields) > 0)
            recsel_password = recutl_getpass (false);

          rec_fex_destroy (confidential_fields);
        }
    }

  /* Note that the password must be at least one character long.  */

  if (recsel_password && (strlen (recsel_password) == 0))
    {
      free (recsel_password);
      recsel_password = NULL;
    }

#endif /* REC_CRYPT_SUPPORT */

  /* If the database contains more than one type of records and the
     user did'nt specify the recutl_type then ask the user to clarify
     the request.  */
  if (!recutl_type && (rec_db_size (db) > 1))
    recutl_fatal (_("several record types found.  Please use -t to specify one.\n"));


  /* Query the database using the criteria specified by the user in
     the command line.  */
  {
    int flags = 0;

    if (recutl_insensitive)
      flags = flags | REC_F_ICASE;

    if (recsel_descriptors)
      flags = flags | REC_F_DESCRIPTOR;

    if (recsel_uniq)
      flags = flags | REC_F_UNIQ;

    rset = rec_db_query (db,
                         recutl_type,
                         recsel_join,
                         recutl_index(),
                         recutl_sex,
                         recutl_quick_str,
                         recutl_random,
                         recsel_fex,
                         recsel_password,
                         recsel_group_by_fields,
                         recutl_sort_by_fields,
                         flags);
    if (!rset)
      recutl_out_of_memory ();
  }

  if (recsel_count)
    /* Write the number of matching records.  */
    fprintf (stdout, "%d\n", rec_rset_num_records (rset));
  else
    {
      /* Write the resulting record set to the standard output.  */
      writer = rec_writer_new (stdout);
      rec_writer_set_collapse (writer, recsel_collapse);
      rec_writer_set_skip_comments (writer, true);
      rec_writer_set_mode (writer, recsel_write_mode);
      rec_write_rset (writer, rset);
      rec_writer_destroy (writer);
    }

  rec_rset_destroy (rset);

  return true;
}

int
main (int argc, char *argv[])
{
  int res;
  rec_db_t db;

  res = 0;

  recutl_init ("recsel");

  /* Parse arguments.  */
  recsel_parse_args (argc, argv);

  /* Get the input data.  */
  db = recutl_build_db (argc, argv);
  if (!db)
    {
      res = 1;
      return res;
    }

  /* Process the data.  */
  if (!recsel_process_data (db))
    res = 1;

  rec_db_destroy (db);
  return res;
}