-
Notifications
You must be signed in to change notification settings - Fork 3
/
fits2db.c
3223 lines (2752 loc) · 101 KB
/
fits2db.c
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* FITS2DB -- Convert FITS Binary Tables to one or more database files.
*
* Usage:
* fits2db [<otps>] [ <input> ..... ]
*
* where <opts> include:
*
* -h,--help this message
* -d,--debug set debug flag
* -v,--verbose set verbose output flag
* -n,--noop set no-op flag
*
* INPUT PROCESSING OPTIONS
* -b,--bundle=<N> bundle <N> files at a time
* -c,--chunk=<N> process <N> rows at a time
* -e,--extnum=<N> process table in FITS extension number <N>
* -E,--extname=<name> process table in FITS extension name <name>
* -i,--input=<file> set input filename
* -o,--output=<file> set output filename
* -r,--rowrange=<range> convert rows within given <range>
* -s,--select=<expr> select rows based on <expr>
*
* PROCESSING OPTIONS
* -C,--concat concatenate all input files to output
* -H,--noheader suppress CSV column header
* -N,--nostrip don't strip strings of whitespace
* -Q,--noquote don't quote strings in text formats
* -S,--singlequote use single quotes for strings
* -X,--explode explode array cols to separate columns
*
* FORMAT OPTIONS
* --asv output an ascii-separated value table
* --bsv output a bar-separated value table
* --csv output a comma-separated value table
* --tsv output a tab-separated value table
* --ipac output an IPAC formatted table
*
* SQL OPTIONS
* -B,--binary output binary SQL
* -O,--oids create table with OIDs (Postgres only)
* -t,--table=<name> create table named <name>
* -Z,--noload don't create table load commands
* -l,--log create a logfile of rowcounts
*
* --add=<colname> Add the nameed column (needs type info)
* --sql=<db> output SQL correct for <db> type
* --drop drop existing DB table before conversion
* --dbname=<name> create DB of the given name
* --sid=<colname> add a sequential-ID column (integer)
* --rid=<colname> add a random-ID column (float: 0.0 -> 100.0)
*
* --create create DB table from input table structure
* --truncate truncate DB table before loading
* --pkey=<colname> create a serial ID column named <colname>
*
*
* @file fits2db.c
* @author Mike Fitzpatrick, NOAO Data Lab Project, Tucson, AZ, USA
* @date 10/1/16
* @version 1.0
*
* @brief Convert FITS Binary Tables to one or more database files.
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#include <fcntl.h>
#include <getopt.h>
#include <arpa/inet.h>
#include "fitsio.h"
// Utility values
#define MAX_CHUNK 100000
#define MAX_COLS 1024
#define SZ_RESBUF 8192
#define SZ_COLNAME 64
#define SZ_EXTNAME 64
#define SZ_COLVAL 1024
#define SZ_ESCBUF 1024
#define SZ_LINEBUF 10240
#define SZ_PATH 512
#define SZ_FNAME 256
#define SZ_VALBUF 256
#define PARG_ERR -512000000
#define RANDOM_SCALE 100.0 // scale for random numbers
#ifndef OK
#define OK 0
#endif
#ifndef ERR
#define ERR 1
#endif
#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#endif
// Output Format Codes
#define TAB_DELIMITED 000 // delimited ascii table
#define TAB_IPAC 001 // IPAC table format
#define TAB_POSTGRES 002 // SQL -- PostgreSQL
#define TAB_MYSQL 004 // SQL -- MySQL
#define TAB_SQLITE 010 // SQL -- SQLite
#define TAB_DBTYPE(t) (t>TAB_IPAC)
#define TAB_SERIAL 999 // Serial ID column type
// Default values
#define DEF_CHUNK 10000
#define DEF_ONAME "root"
#define DEF_FORMAT TAB_POSTGRES
#define DEF_DELIMITER ','
#define DEF_QUOTE '"'
#define DEF_MODE "w+"
/* Table column descriptor
*/
typedef struct {
int colnum;
int dispwidth;
int type;
int nelem;
int ndim;
int nrows;
int ncols;
long width;
long repeat;
char colname[SZ_COLNAME];
char coltype[SZ_COLNAME];
char colunits[SZ_COLNAME];
} Col, *ColPtr;
Col inColumns[MAX_COLS];
Col outColumns[MAX_COLS];
int numInCols = 0; // number of input columns
int numOutCols = 0; // number of output columns
char esc_buf[SZ_ESCBUF]; // escaped value buffer
char *obuf, *optr; // output buffer pointers
long olen = 0; // output buffer length
char *prog_name = NULL; // program name
char *extname = NULL; // extension name
char *iname = NULL; // input file name
char *oname = NULL; // output file name
char *basename = NULL; // base output file name
char *rows = NULL; // row selection string
char *expr = NULL; // selection expression string
char *tablename = NULL; // database table name
char *sidname = NULL; // serial ID column name
char *ridname = NULL; // random ID column name
char *dbname = NULL; // database name name (MySQL create)
char *addname = NULL; // column name to be added
char delimiter = DEF_DELIMITER;// default to CSV
char arr_delimiter = DEF_DELIMITER;// default to CSV
char quote_char = DEF_QUOTE; // string quote character
char *omode = DEF_MODE; // output file mode
int format = DEF_FORMAT; // default output format
int mach_swap = 0; // is machine swapped relative to FITS?
int do_binary = 0; // do binary SQL output
int do_quote = 1; // quote ascii values?
int do_escape = 0; // escape strings for quotes?
int do_strip = 1; // strip leading/trailing whitespace?
int do_drop = 0; // drop db table before creating new one
int do_create = 0; // create new db table
int do_truncate = 0; // truncate db table before load
int do_load = 1; // load db table
int do_oids = 0; // use table OID (Postgres only)?
int bundle = 1; // number of input files to bundle
int nfiles = 0; // number of input files
int noop = 0; // no-op ??
int concat = 0; // concat input file to single output?
int explode = 0; // explode arrays to new columns?
int extnum = -1; // extension number
int header = 1; // prepend column headers
int number = 0; // number rows ?
int single = 0; // load rows one at a time?
int chunk_size = DEF_CHUNK; // processing chunk size
int serial_number = 0; // ID serial number
int debug = 0; // debug flag
int verbose = 0; // verbose output flag
FILE *log_fd = (FILE *)NULL; // rowcount log file
char *pgcopy_hdr = "PGCOPY\n\377\r\n\0\0\0\0\0";
int len_pgcopy_hdr = 15;
size_t sz_char = sizeof (char);
size_t sz_short = sizeof (short);
size_t sz_int = sizeof (int);
size_t sz_long = sizeof (long);
size_t sz_longlong = sizeof (long long);
size_t sz_float = sizeof (float);
size_t sz_double = sizeof (double);
/* Task specific option declarations. Task options are declared using the
* getopt_long(3) syntax.
static Task self = { "fits2db", fits2db, 0, 0, 0 };
*/
static char *opts = "hdvnb:c:e:E:i:o:r:s:t:BCHNOQSXZ012345:678L:U:A:D:";
static struct option long_opts[] = {
{ "help", no_argument, NULL, 'h'},
{ "debug", no_argument, NULL, 'd'},
{ "verbose", no_argument, NULL, 'v'},
{ "noop", no_argument, NULL, 'n'},
{ "bundle", required_argument, NULL, 'b'},
{ "chunk", required_argument, NULL, 'c'},
{ "extnum", required_argument, NULL, 'e'},
{ "extname", required_argument, NULL, 'E'},
{ "input", required_argument, NULL, 'i'},
{ "output", required_argument, NULL, 'o'},
{ "rowrange", required_argument, NULL, 'r'},
{ "select", required_argument, NULL, 's'},
{ "table", required_argument, NULL, 't'},
{ "binary", no_argument, NULL, 'B'},
{ "concat", no_argument, NULL, 'C'},
{ "log", no_argument, NULL, 'l'},
{ "noheader", no_argument, NULL, 'H'},
{ "nostrip", no_argument, NULL, 'N'},
{ "oid", no_argument, NULL, 'O'},
{ "noquote", no_argument, NULL, 'Q'},
{ "singlequote", no_argument, NULL, 'S'},
{ "explode", no_argument, NULL, 'X'},
{ "noload", no_argument, NULL, 'Z'},
{ "asv", no_argument, NULL, '0'},
{ "bsv", no_argument, NULL, '1'},
{ "csv", no_argument, NULL, '2'},
{ "tsv", no_argument, NULL, '3'},
{ "ipac", no_argument, NULL, '4'},
{ "sql", required_argument, NULL, '5'},
{ "drop", no_argument, NULL, '6'},
{ "create", no_argument, NULL, '7'},
{ "truncate", no_argument, NULL, '8'},
{ "sid", required_argument, NULL, 'L'},
{ "rid", required_argument, NULL, 'U'},
{ "add", required_argument, NULL, 'A'},
{ "dbname", required_argument, NULL, 'D'},
{ NULL, 0, 0, 0 }
};
/* All tasks should declare a static Usage() method to print the help
* text in response to a '-h' or '--help' flag. The help text should
* include a usage summary, a description of options, and some examples.
*/
static void Usage (void);
static void dl_escapeCSV (char* in);
static void dl_quote (char* in);
static void dl_fits2db (char *iname, char *oname, int filenum,
int bnum, int nfiles);
static void dl_printHdr (int firstcol, int lastcol, FILE *ofd);
static void dl_printIPACTypes (char *tablename, fitsfile *fptr, int firstcol,
int lastcol, FILE *ofd);
static void dl_createSQLTable (char *tablename, fitsfile *fptr, int firstcol,
int lastcol, FILE *ofd);
static void dl_printSQLHdr (char *tablename, fitsfile *fptr, int firstcol,
int lastcol, FILE *ofd);
static void dl_printHdrString (char *tablename);
static void dl_getColInfo (fitsfile *fptr, int firstcol, int lastcol);
static int dl_validateColInfo (fitsfile *fptr, int firstcol, int lastcol);
static void dl_getOutputCols (fitsfile *fptr, int firstcol, int lastcol);
static unsigned char *dl_printCol (unsigned char *dp, ColPtr col, char end_ch);
static unsigned char *dl_printString (unsigned char *dp, ColPtr col);
static unsigned char *dl_printLogical (unsigned char *dp, ColPtr col);
static unsigned char *dl_printByte (unsigned char *dp, ColPtr col);
static unsigned char *dl_printShort (unsigned char *dp, ColPtr col);
static unsigned char *dl_printInt (unsigned char *dp, ColPtr col);
static unsigned char *dl_printLong (unsigned char *dp, ColPtr col);
static unsigned char *dl_printFloat (unsigned char *dp, ColPtr col);
static unsigned char *dl_printDouble (unsigned char *dp, ColPtr col);
static void dl_printSerial (void);
static void dl_printRandom (void);
static void dl_printValue (int value);
static int dl_atoi (char *v);
static int dl_isFITS (char *v);
static int dl_isGZip (char *v);
static void dl_error (int exit_code, char *error_message, char *tag);
static char *dl_colType (ColPtr col);
static char *dl_IPACType (ColPtr col);
static char *dl_SQLType (ColPtr col);
static char *dl_makeTableName (char *fname);
static char *dl_fextn (void);
static char **dl_paramInit (int argc, char *argv[], char *opts,
struct option long_opts[]);
static int dl_paramNext (char *opts, struct option long_opts[],
int argc, char *argv[], char *optval, int *posindex);
static void dl_paramFree (int argc, char *argv[]);
static void bswap2 (char *a, char *b, int nbytes);
static void bswap4 (char *a, int aoff, char *b, int boff, int nbytes);
static void bswap8 (char *a, int aoff, char *b, int boff, int nbytes);
static char *sstrip (char *s);
static char *time_stamp (void);
static int is_swapped (void);
#ifdef PYTHON_EXT
#define PY_SSIZE_T_CLEAN
#include <Python.h>
char *dl_fits2db_error; // Is there an error in dl_fits2db?
char *create_table_buffer = NULL;
size_t create_table_bufferSize = 0;
FILE *create_table_stream = (FILE *)NULL;
PyObject *Fits2dbException;
PyObject *Fits2dbArrayException;
static PyObject *method_fits2db(PyObject *self, PyObject *args) {
char *iname, *oname= NULL;
int bnum = 0;
int nfiles = 1;
do_binary = 1;
/* I can't not find a way to clean up after the return statement
* in this function.
* So if the fits2db is called many times from the python code,
* the create_table_buffer is probably allocated and not null
* In that case we need to free it before continuing.
*/
if (create_table_buffer != NULL) {
free(create_table_buffer);
}
/* Parse arguments */
if(!PyArg_ParseTuple(args, "sss|p", &iname, &oname, &tablename, &do_binary)) {
return NULL;
}
// We want the create table statement
do_create ++;
dl_fits2db(iname, oname, access(iname, F_OK), bnum, nfiles);
if (PyErr_Occurred() != NULL) {
return NULL;
}
// reset the do_create flag
do_create = 0;
if (create_table_stream != NULL) {
//printf("closing create_table_stream\n");
fclose(create_table_stream);
}
// return create table statement
return PyUnicode_DecodeUTF8(create_table_buffer, strlen(create_table_buffer), NULL);
}
static PyMethodDef Fits2dbMethods[] = {
{"fits2db", method_fits2db, METH_VARARGS,
"Python interface for fits2db C library function"},
{NULL, NULL, 0, NULL}
};
static struct PyModuleDef fits2dbmodule = {
PyModuleDef_HEAD_INIT,
"fits2db",
"Python interface for the fits2db C library function",
-1,
Fits2dbMethods
};
PyObject *m;
PyMODINIT_FUNC PyInit_fits2db(void) {
//PyObject *m;
m = PyModule_Create(&fits2dbmodule);
if (m == NULL) {
return NULL;
}
Fits2dbException = PyErr_NewExceptionWithDoc(
"fits2db.ExceptionBase",
"Base exception class for fitsdb.",
NULL, /* PyObject base */
NULL /* PyObject dict */);
if ( ! Fits2dbException ) {
return NULL;
} else {
//Py_XINCREF(Fits2dbException);
if (PyModule_AddObject(m, "ExceptionBase", Fits2dbException) < 0) {
Py_XDECREF(Fits2dbException);
Py_CLEAR(Fits2dbException);
Py_DECREF(m);
return NULL;
}
}
Fits2dbArrayException = PyErr_NewExceptionWithDoc("fits2db.ArrayException",
"Array not supported in binary mode exception",
Fits2dbException, /* PyObject base */
NULL /* PyObject dict */);
if ( ! Fits2dbArrayException ) {
return NULL;
} else {
//Py_XINCREF(Fits2dbArrayException);
if (PyModule_AddObject(m, "ArrayException", Fits2dbArrayException) < 0) {
Py_XDECREF(Fits2dbArrayException);
Py_CLEAR(Fits2dbArrayException);
Py_DECREF(m);
return NULL;
}
}
return m;
}
#endif
/**
* Application entry point. All DLApps tasks MUST contain this
* method signature.
*/
int
main (int argc, char **argv)
{
char **pargv, optval[SZ_FNAME], *prog_name;
char **iflist = NULL, **ifstart = NULL;
char *iname = NULL, *oname = NULL, tmp[2*SZ_PATH];
int i, ch = 0, status = 0, pos = 0;
/* Initialize local task values.
*/
ifstart = calloc (argc, sizeof (char *));
iflist = ifstart;
/* Initialize the randome number generator.
*/
srand ((unsigned int)time(NULL));
/* Parse the argument list. The use of dl_paramInit() is required to
* rewrite the argv[] strings in a way dl_paramNext() can be used to
* parse them. The programmatic interface allows "param=value" to
* be passed in, but the getopt_long() interface requires these to
* be written as "--param=value" so they are not confused with
* positional parameters (i.e. any param w/out a leading '-').
*/
prog_name = argv[0];
pargv = dl_paramInit (argc, argv, opts, long_opts);
memset (optval, 0, SZ_FNAME);
while ((ch = dl_paramNext(opts,long_opts,argc,pargv,optval,&pos)) != 0) {
if (ch == PARG_ERR)
continue;
if (ch > 0) {
/* If the 'ch' value is > 0 we are parsing a single letter
* flag as defined in the 'opts string.
*/
switch (ch) {
case 'h': Usage (); return (OK);
case 'd': debug++; break; // --debug
case 'v': verbose++; break; // --verbose
case 'n': noop++; break; // --noop
case 'b': bundle = dl_atoi (optval); break; // --bundle
case 'c': chunk_size = dl_atoi (optval); break; // --chunk_size
case 'e': extnum = dl_atoi (optval); break; // --extnum
case 'E': extname = strdup (optval); break; // --extname
case 'r': rows = strdup (optval); break; // --rows
case 's': expr = strdup (optval); break; // --select
case 't': tablename = strdup (optval); break; // --table
case 'B': do_binary++; break; // --binary
case 'C': concat++; break; // --concat
case 'X': explode++; break; // --explode
case 'H': header = 0; break; // --noheader
case 'Q': do_quote = 0; break; // --noquote
case 'N': do_strip = 0; break; // --nostrip
case 'O': do_oids = 0; break; // --oid
case 'Z': do_load = 0; break; // --noload
case 'S': quote_char = '\''; break; // --quote
case 'i': iname = strdup (optval); break; // --input
case 'o': oname = strdup (optval); break; // --output
case 'l':
if ((log_fd = fopen ("fits2db.log", "a+")) == (FILE *) NULL)
dl_error (3, "Error opening log file '%s'\n",
"fits2db.log");
case '0': delimiter = ' ';
arr_delimiter=' ';
break; // ASV
case '1': delimiter = '|';
arr_delimiter='|';
break; // BSV
case '2': delimiter = ',';
arr_delimiter=',';
break; // CSV
case '3': delimiter = '\t';
arr_delimiter='\t';
break; // TSV
case '4': delimiter = '|';
format = TAB_IPAC;
arr_delimiter='|';
break;
case '5': if (optval[0] == 'm') { // MySQL ouptut
format = TAB_MYSQL;
delimiter = ',';
arr_delimiter = ',';
do_quote = 1;
quote_char = '"';
} else if (optval[0] == 's') { // SQLite ouptut
format = TAB_SQLITE;
} else { // Postgres (default)
format = TAB_POSTGRES;
delimiter = ',';
arr_delimiter = ',';
do_quote = 0;
}
break;
case '6': do_drop++, do_create++; break; // --drop
case '7': do_create++; break; // --create
case '8': do_truncate++; break; // --truncate
case 'L': sidname = strdup (optval); break; // --sid
case 'U': ridname = strdup (optval); break; // --rid
case 'D': dbname = strdup (optval); break; // --dbname
case 'A': addname = strdup (optval); break; // --add
default:
fprintf (stderr, "%s: Invalid option '%s'\n",
prog_name, optval);
return (ERR);
}
} else {
/* All non-opt arguments are input files to process.
*/
*iflist++ = strdup (optval);
nfiles++;
}
memset (optval, 0, SZ_FNAME);
}
*iflist = NULL;
if (debug) {
fprintf (stderr, "do_create=%d do_drop=%d do_truncate=%d\n",
do_create, do_drop, do_truncate);
fprintf (stderr, "extnum=%d extname='%s' rows='%s' expr='%s'\n",
extnum, extname, rows, expr);
fprintf (stderr, "delim='%c' dbname='%s' sidname='%s' ridname='%s'\n",
delimiter, dbname, sidname, ridname);
fprintf (stderr, "table = '%s'\n", (tablename ? tablename : "<none>"));
for (i=0; i < nfiles; i++)
fprintf (stderr, "in[%d] = '%s'\n", i, ifstart[i]);
if (noop)
return (0);
}
/* Sanity checks. Tasks should validate input and accept stdin/stdout
* where it makes sense.
*/
if (iname && *ifstart == NULL)
*ifstart = *iflist = iname;
if (*ifstart == NULL) {
dl_error (2, "no input files specified", NULL);
return (ERR);
}
if (extnum >= 0 && extname) {
dl_error (3, "Only one of 'extname' or 'extnum' may be specified\n",
NULL);
return (ERR);
}
if (rows) {
fprintf (stderr,
"Warning: 'rows' option not yet implemented, skipping\n");
return (ERR);
}
if (do_binary)
bundle = 1;
if (explode && format == TAB_POSTGRES) {
delimiter = '\t';
arr_delimiter = '\t';
}
/* Generate the output file lists if needed.
*/
if (nfiles == 1 || concat) {
/* If we have 1 input file, output may be to stdout or to the named
* file only.
*/
if (oname && strcmp (oname, "-") == 0)
free (oname), oname = NULL;
if (oname == NULL)
oname = strdup ("stdout");
} else {
if (oname)
/* For multiple files, the output arg specifies a root filename.
* We append the file number and a ".csv" extension.
*/
basename = oname;
else
/* If we don't specify an output name, use the input filename
* and replace the extension.
*/
basename = NULL;
}
/* Compute and output the image metadata. */
if (*ifstart == NULL) {
dl_error (2, "no input source specified", NULL);
return (ERR);
} else {
char ofname[SZ_PATH], ifname[SZ_PATH];
int ndigits = (int) log10 (nfiles) + 1, bnum = 0;
if (debug) {
for (iflist=ifstart, i=0; *iflist; iflist++, i++) {
fprintf (stderr, "%d: '%s'\n", i, *iflist);
}
}
for (iflist=ifstart, i=0; *iflist; iflist++, i++) {
memset (ifname, 0, SZ_PATH);
memset (ofname, 0, SZ_PATH);
/* Construct the input filename and append filename modifiers
* to do table/row filtering.
*/
strcpy (ifname, *iflist);
i = access (ifname, F_OK);
if (strcmp(ifname,"stdin") == 0 || ifname[0] == '-') {
strcpy (ofname, "stdout");
oname = strdup ("stdout");
if (!noop)
dl_fits2db (ifname, oname, i, i, nfiles);
break;
} else if (access (ifname, F_OK) != 0) {
fprintf (stderr, "Error: Cannot access file '%s'\n", ifname);
continue;
}
if (extnum >= 0) {
memset (tmp, 0, SZ_PATH);
sprintf (tmp, "%s[%d]", ifname, extnum);
strcpy (ifname, tmp);
}
if (extname) {
memset (tmp, 0, SZ_PATH);
sprintf (tmp, "%s[%s]", ifname, extname);
strcpy (ifname, tmp);
}
if (expr) {
memset (tmp, 0, SZ_PATH);
sprintf (tmp, "%s[%s]", ifname, expr);
strcpy (ifname, tmp);
}
/* Construct the output filename.
*/
if (basename) {
if (concat && i == 0) {
sprintf (ofname, "%s.%s", basename, dl_fextn());
} else {
char fmt[SZ_PATH];
memset (fmt, 0, SZ_PATH);
sprintf (fmt, "%%s%%%dd.%%s", ndigits);
sprintf (ofname, fmt, basename, i, dl_fextn());
}
} else if (oname) {
strcpy (ofname, oname);
} else {
char *in = strdup (ifname);
char *ip = (in + strlen(in) - 1);
do {
*ip-- = '\0';
} while (*ip != '.' && ip > in);
*ip = '\0';
sprintf (ofname, "%s.%s", in, dl_fextn());
free ((char *) in);
}
omode = ((concat && i > 0) ? "a+" : "w+");
if (debug)
fprintf (stderr, "ifname='%s' ofname='%s'\n", ifname, ofname);
/* Do the conversion if we have a FITS file.
*/
if (strcmp(ifname,"stdin") == 0 && ifname[0] != '-')
continue;
if (dl_isFITS (ifname) || dl_isGZip (ifname)) {
if (verbose)
fprintf (stderr, "Processing file: %s\n", ifname);
if (!noop)
dl_fits2db (ifname, ofname, i, bnum, nfiles);
/* Increment the filenumber within the bundle so we can keep
* track of headers. */
bnum = ((bnum+1) == bundle ? 0 : (bnum+1));
} else
fprintf (stderr, "Error: Skipping non-FITS file '%s'.\n",
ifname);
}
}
if (status)
fits_report_error (stderr, status); // print any error message
/* Clean up. Rememebr to free whatever pointers were created when
* parsing arguments.
*/
for (iflist=ifstart; *iflist; iflist++) // free the file list
free ((void *) *iflist), *iflist = NULL;
if (rows) free (rows);
if (expr) free (expr);
if (iname) free (iname);
if (oname) free (oname);
if (extname) free (extname);
if (tablename) free (tablename);
if (ifstart) free ((void *) ifstart);
dl_paramFree (argc, pargv);
if (log_fd) fclose (log_fd);
return (status); /* status must be OK or ERR (i.e. 0 or 1) */
}
/**
* DL_FITS2DB -- Convert a FITS file to a database, i.e. actual SQL code or
* some ascii 'database' table like a CSV.
*/
static void
dl_fits2db (char *iname, char *oname, int filenum, int bnum, int nfiles)
{
fitsfile *fptr = (fitsfile *) NULL;
int status = 0;
long jj, nrows;
int hdunum, hdutype, ncols, i, j;
int firstcol = 1, lastcol = 0, firstrow = 1;
int nelem, chunk = chunk_size;
FILE *ofd = (FILE *) NULL;
//ColPtr col = (ColPtr) NULL;
unsigned char *data = NULL, *dp = NULL;
long naxis1, naxis2, rowsize = 0, nbytes = 0, firstchar = 1, totrows = 0;
mach_swap = is_swapped ();
if (!fits_open_file (&fptr, iname, READONLY, &status)) {
if ( fits_get_hdu_num (fptr, &hdunum) == 1 )
/* This is the primary array; try to move to the first extension
* and see if it is a table.
*/
fits_movabs_hdu (fptr, 2, &hdutype, &status);
else
fits_get_hdu_type (fptr, &hdutype, &status); /* Get the HDU type */
if (hdutype == IMAGE_HDU)
printf ("Error: this program only converts tables, not images\n");
else {
fits_get_num_rows (fptr, &nrows, &status);
fits_get_num_cols (fptr, &ncols, &status);
if (log_fd) {
char *ts = time_stamp();
fprintf (log_fd, "%s %s %ld rows %d cols\n",
ts, iname, nrows, ncols);
free ((void *) ts);
}
lastcol = ncols;
chunk = (chunk > nrows ? nrows : chunk);
nelem = chunk;
/* Get the optimal I/O row size.
*/
fits_get_rowsize (fptr, &rowsize, &status);
nelem = rowsize;
/* Open the output file.
*/
if (strcasecmp (oname, "stdout") == 0 || oname[0] == '-')
ofd = stdout;
else {
if ((ofd = fopen (oname, omode)) == (FILE *) NULL)
dl_error (3, "Error opening output file '%s'\n", oname);
}
/* Print column names as column headers when writing a new file,
* skip if we're appending output.
*
* FIXME -- Need to add a check that new file matches columns
* when we have multi-file input.
*/
fits_read_key (fptr, TLONG, "NAXIS1", &naxis1, NULL, &status);
fits_read_key (fptr, TLONG, "NAXIS2", &naxis2, NULL, &status);
if (filenum == 0 || !concat) {
dl_getColInfo (fptr, firstcol, lastcol);
if (!tablename)
tablename = dl_makeTableName (iname);
if (format == TAB_DELIMITED)
dl_printHdr (firstcol, lastcol, ofd);
else if (format == TAB_IPAC)
dl_printIPACTypes (iname, fptr, firstcol, lastcol, ofd);
else {
int c = 0;
/* Binary mode is only supported for Postgres, and not
* for array operations. Disable if needed but issue
* a warning.
*/
if (do_binary) {
for (c=firstcol; c <= lastcol; c++) {
ColPtr col = (ColPtr) &inColumns[c];
if (col->type != TSTRING && col->repeat > 1) {
#ifdef PYTHON_EXT
dl_fits2db_error = "binary mode not supported for array columns";
PyErr_SetString(Fits2dbArrayException, dl_fits2db_error);
#else
fprintf (stderr, "Warning: binary mode not "
"supported for array columns, disabling\n");
fflush (stderr);
#endif
do_binary = 0;
break;
}
}
}
// This is some sort of SQL output.
if (do_create) {
#ifdef PYTHON_EXT
create_table_stream = open_memstream(&create_table_buffer, &create_table_bufferSize);
dl_createSQLTable (tablename, fptr, firstcol, lastcol,
create_table_stream);
#else
dl_createSQLTable (tablename, fptr, firstcol, lastcol,
ofd);
#endif
}
if (do_truncate) {
fprintf (ofd, "TRUNCATE TABLE %s;\n", tablename);
fflush (ofd);
}
}
} else {
// Make sure this file has the same columns.
if (dl_validateColInfo (fptr, firstcol, lastcol)) {
fprintf (stderr, "Skipping unmatching table '%s'\n",
iname);
return;
}
}
/* If we're not loading the database, close the file and return.
*/
if (do_load == 0) {
fits_close_file (fptr, &status);
if (status) /* print any error message */
fits_report_error (stderr, status);
return;
}
/* At the beginning of each file bundle, print the appropriate
* COPY/INSERT statement. This helps avoid memory problems in
* the database clients we write to.
*/
if (bnum == 0 && TAB_DBTYPE(format))
dl_printSQLHdr (tablename, fptr, firstcol, lastcol, ofd);
/* Allocate the I/O buffer.
*/
nbytes = nelem * naxis1;
if (sidname) nbytes += (8 * naxis2);
if (ridname) nbytes += (8 * naxis2);
if (debug)
fprintf (stderr,
"nelem=%d naxis=[%ld,%ld] nbytes=%ld nrows=%d\n",
nelem, naxis1, naxis2, nbytes, (int)nrows);
data = (unsigned char *) calloc (1, nbytes * 8);
obuf = (char *) calloc (1, nbytes * 8);
olen = 0;
/* Loop over the rows in the table in optimal chunk sizes.
*/
for (jj=firstrow; jj <= nrows; jj += nelem) {
if ( (jj + nelem) >= nrows)
nelem = (nrows - jj + 1);
/* Read a chunk of data from the file.
*/
nbytes = nelem * naxis1;
fits_read_tblbytes (fptr, firstrow, firstchar, nbytes,
data, &status);
if (status) { /* print any error message */
fits_report_error (stderr, status);
break;
}
/* Process the chunk by parsing the binary data and printing
* out according to column type.
*/
dp = data;
optr = obuf;
olen = 0;
for (j=firstrow; j <= nelem; j++) {
if (format == TAB_POSTGRES && do_binary) {
unsigned short val = 0;
if (sidname) val++;
if (ridname) val++;
val = (explode ? htons ((short) numOutCols+val) :
htons ((short) ncols+val));
memcpy (optr, &val, sz_short);
optr += sz_short;
olen += sz_short;
} else if (single &&
(format == TAB_SQLITE || format == TAB_MYSQL)) {
// For SQLite we print the header for each row.
dl_printHdrString (tablename);
}
/* Print all the columns in the table.
*/
for (i=firstcol; i <= ncols; i++)
dp = dl_printCol (dp, &inColumns[i],
(i < ncols ? arr_delimiter : '\n'));
if (format == TAB_MYSQL || format == TAB_SQLITE) {
// Add a comma for all but the last row of a table.
if (j < nelem)