/** * Generic function that loads a given list of BAM files according to * the values of the other parameters. It starts with creating the * bam schema and the header tables if these do not exist yet. Then * it initializes bam_wrapper structs for all bam files and reads the * headers for all BAM files. If the pairwise storage schema has to * be used, It then creates a thread for every file that reads all * alignments for this file. * */ static str bam_loader(Client cntxt, MalBlkPtr mb, str * filenames, int nr_files, sht dbschema, sht nr_threads) { bam_wrapper *bws = NULL; MT_Id *reader_threads = NULL; reader_thread_data *r_thread_data = NULL; mvc *m = NULL; sql_schema *s = NULL; sql_table *files_table = NULL; lng cur_file_id; char buf_threads_msg[4096] = "There were reader threads that contained errors:\n"; int threads_msg_len = strlen(buf_threads_msg); int i, errnr; str msg = MAL_SUCCEED; TO_LOG("<bam_loader>: Loader started for %d BAM file%s...\n", nr_files, (nr_files != 1 ? "s" : "")); /* Check sanity of input */ if (dbschema != 0 && dbschema != 1) { msg = createException(MAL, "bam_loader", "Wrong value for dbschema: '%d' (0=straightforward storage schema, 1=pairwise storage schema)", dbschema); goto cleanup; } if (nr_threads <= 0) { nr_threads = 1; } else if(nr_threads > 4) { nr_threads = 4; } /* Get SQL context */ if ((msg = getSQLContext(cntxt, mb, &m, NULL)) != MAL_SUCCEED) { /* Here, and in multiple other locations in this code, * new message is stored in tmp var, since the old msg * needs to be freed after construction of the new * msg */ REUSE_EXCEPTION(msg, MAL, "bam_loader", "Could not retrieve SQLContext: %s", msg); goto cleanup; } /* Start with binding bam schema and the files table */ if ((msg = bind_bam_schema(m, &s)) != MAL_SUCCEED) goto cleanup; if((msg = bind_table(m, s, "files", &files_table)) != MAL_SUCCEED) goto cleanup; /* Get next file id from files table */ TO_LOG("<bam_loader> Retrieving next file id...\n"); if ((msg = next_file_id(m, files_table, &cur_file_id)) != MAL_SUCCEED) { goto cleanup; } /* Init bam_wrapper structs */ if ((bws = (bam_wrapper *) GDKmalloc(nr_files * sizeof(bam_wrapper))) == NULL) { msg = createException(MAL, "bam_loader", MAL_MALLOC_FAIL); goto cleanup; } /* Enables cleanup to check which bam_wrappers to clear */ memset(bws, 0, nr_files * sizeof(bam_wrapper)); for (i = 0; i < nr_files; ++i) { int fln = strlen(filenames[i]); TO_LOG("<bam_loader> Initializing BAM wrapper for file '%s'...\n", filenames[i]); if ((msg = init_bam_wrapper(bws + i, (IS_BAM(filenames[i], fln) ? BAM : SAM), filenames[i], cur_file_id++, dbschema)) != MAL_SUCCEED) { goto cleanup; } } /* Parse all headers */ for (i = 0; i < nr_files; ++i) { TO_LOG("<bam_loader> Parsing header for file '%s'...\n", filenames[i]); if ((msg = process_header(bws + i)) != MAL_SUCCEED) { goto cleanup; } } /* If we have to load the BAM data into the pairwise storage * schema, make sure that all input BAM files are sorted on * QNAME */ if (dbschema == 1) { for (i = 0; i < nr_files; ++i) { TO_LOG("<bam_loader> Checking sortedness for BAM file '%s'...\n", filenames[i]); if (bws[i].ord != ORDERING_QUERYNAME) { msg = createException(MAL, "bam_loader", "Only BAM files that are sorted on queryname can be inserted into the pairwise storage schema; " "BAM file '%s' has ordering '%s'", bws[i].file_location, ordering_str(bws[i]. ord)); goto cleanup; } } } /* Create alignment storage */ for (i = 0; i < nr_files; ++i) { TO_LOG("<bam_loader> Creating alignment tables for file '%s'...\n", filenames[i]); if ((dbschema == 0 && (msg = create_alignment_storage_0(cntxt, "bam.create_storage_0", bws + i)) != MAL_SUCCEED) || (dbschema == 1 && (msg = create_alignment_storage_1(cntxt, "bam.create_storage_1", bws + i)) != MAL_SUCCEED)) { goto cleanup; } } /* Now create threads to read alignment data of different files */ TO_LOG("<bam_loader> Creating reader threads...\n"); if ((reader_threads = (MT_Id *) GDKmalloc(nr_threads * sizeof(MT_Id))) == NULL) { msg = createException(MAL, "bam_loader", MAL_MALLOC_FAIL); goto cleanup; } if ((r_thread_data = create_reader_thread_data(bws, nr_files, nr_threads)) == NULL) { msg = createException(MAL, "bam_loader", MAL_MALLOC_FAIL); goto cleanup; } for (i = 0; i < nr_threads; ++i) { if ((errnr = MT_create_thread(&reader_threads[i], run_process_bam_alignments, &r_thread_data[i], MT_THR_JOINABLE)) != 0) { msg = createException(MAL, "bam_loader", "Could not create thread to process alignments (errnr %d)", errnr); goto cleanup; } } TO_LOG("<bam_loader> Waiting for reader threads to finish...\n"); /* Wait until all threads finish and collect their * messages. Though it is not very likely, it could be the * case that more than 1 thread generates an error message (not * likely because threads exit once they notice that another * thread has failed). Therefore, we collect all error * messages in one big error string */ for (i = 0; i < nr_threads; ++i) { if ((errnr = MT_join_thread(reader_threads[i])) != 0) { msg = createException(MAL, "bam_loader", "Could not join alignment processing thread (errnr %d)", errnr); goto cleanup; } /* Thread finished ok, append its error message, if any */ if (r_thread_data[i].msg != MAL_SUCCEED) { int step; if (msg == MAL_SUCCEED) { /* First encountered thread error, * indicate this by pointing to error * buf */ msg = buf_threads_msg; } /* snprintf returns -1 on failure; since we * don't want to fail when snprintf fails, we * use MAX to make sure we don't add a * negative amount to threads_msg_len */ step = snprintf(msg + threads_msg_len, 4096 - threads_msg_len, "* %s\n", r_thread_data[i].msg); threads_msg_len += MAX(0, step); GDKfree(r_thread_data[i].msg); } } /* Fail if any thread has failed */ if (msg != MAL_SUCCEED) { /* Do not use REUSE_EXCEPTION here, since msg was not * malloced. Instead, just copy buffer contents to * malloced buffer */ msg = GDKstrdup(msg); goto cleanup; } TO_LOG("<bam_loader> Copying data into DB...\n"); /* All threads finished succesfully, copy all data into DB */ for (i = 0; i < nr_files; ++i) { if ((msg = copy_into_db(cntxt, bws + i)) != MAL_SUCCEED) { goto cleanup; } } cleanup: if (bws) { for (i = 0; i < nr_files; ++i) { if (bws + i) clear_bam_wrapper(bws + i); } GDKfree(bws); } if (reader_threads) GDKfree(reader_threads); if (r_thread_data) destroy_reader_thread_data(r_thread_data); if (msg != MAL_SUCCEED) { TO_LOG("<bam_loader> Error on processing BAM files: %s\n", msg); } TO_LOG("<bam_loader>: Loader finished processing %d BAM file%s...\n", nr_files, (nr_files != 1 ? "s" : "")); return msg; }
str NCDFattach(Client cntxt, MalBlkPtr mb, MalStkPtr stk, InstrPtr pci) { mvc *m = NULL; sql_schema *sch = NULL; sql_table *tfiles = NULL, *tdims = NULL, *tvars = NULL, *tvardim = NULL, *tattrs = NULL; sql_column *col; str msg = MAL_SUCCEED; str fname = *(str*)getArgReference(stk, pci, 1); char buf[BUFSIZ], *s= buf; oid fid, rid = oid_nil; sql_trans *tr; int ncid; /* dataset id */ int ndims, nvars, ngatts, unlimdim; int didx, vidx, vndims, vnatts, i, aidx, coord_dim_id = -1; int vdims[NC_MAX_VAR_DIMS]; size_t dlen, alen; char dname[NC_MAX_NAME+1], vname[NC_MAX_NAME+1], aname[NC_MAX_NAME +1], abuf[80], *aval; char **dims = NULL; nc_type vtype, atype; /* == int */ int retval, avalint; float avalfl; double avaldbl; msg = getSQLContext(cntxt, mb, &m, NULL); if (msg) return msg; tr = m->session->tr; sch = mvc_bind_schema(m, "sys"); if ( !sch ) return createException(MAL, "netcdf.attach", "Cannot get schema sys\n"); tfiles = mvc_bind_table(m, sch, "netcdf_files"); tdims = mvc_bind_table(m, sch, "netcdf_dims"); tvars = mvc_bind_table(m, sch, "netcdf_vars"); tvardim = mvc_bind_table(m, sch, "netcdf_vardim"); tattrs = mvc_bind_table(m, sch, "netcdf_attrs"); if (tfiles == NULL || tdims == NULL || tvars == NULL || tvardim == NULL || tattrs == NULL) return createException(MAL, "netcdf.attach", "Catalog table missing\n"); /* check if the file is already attached */ col = mvc_bind_column(m, tfiles, "location"); rid = table_funcs.column_find_row(m->session->tr, col, fname, NULL); if (rid != oid_nil) return createException(SQL, "netcdf.attach", "File %s is already attached\n", fname); /* Open NetCDF file */ if ((retval = nc_open(fname, NC_NOWRITE, &ncid))) return createException(MAL, "netcdf.test", "Cannot open NetCDF \ file %s: %s", fname, nc_strerror(retval)); if ((retval = nc_inq(ncid, &ndims, &nvars, &ngatts, &unlimdim))) return createException(MAL, "netcdf.test", "Cannot read NetCDF \ header: %s", nc_strerror(retval)); /* Insert row into netcdf_files table */ col = mvc_bind_column(m, tfiles, "file_id"); fid = store_funcs.count_col(tr, col, 1) + 1; snprintf(buf, BUFSIZ, INSFILE, (int)fid, fname); if ( ( msg = SQLstatementIntern(cntxt, &s, "netcdf.attach", TRUE, FALSE, NULL)) != MAL_SUCCEED ) goto finish; /* Read dimensions from NetCDF header and insert a row for each one into netcdf_dims table */ dims = (char **)GDKzalloc(sizeof(char *) * ndims); for (didx = 0; didx < ndims; didx++){ if ((retval = nc_inq_dim(ncid, didx, dname, &dlen))) return createException(MAL, "netcdf.attach", "Cannot read dimension %d : %s", didx, nc_strerror(retval)); snprintf(buf, BUFSIZ, INSDIM, didx, (int)fid, dname, (int)dlen); if ( ( msg = SQLstatementIntern(cntxt, &s, "netcdf.attach", TRUE, FALSE, NULL)) != MAL_SUCCEED ) goto finish; dims[didx] = GDKstrdup(dname); } /* Read variables and attributes from the header and insert rows in netcdf_vars, netcdf_vardims, and netcdf_attrs tables */ for (vidx = 0; vidx < nvars; vidx++){ if ( (retval = nc_inq_var(ncid, vidx, vname, &vtype, &vndims, vdims, &vnatts))) return createException(MAL, "netcdf.attach", "Cannot read variable %d : %s", vidx, nc_strerror(retval)); /* Check if this is coordinate variable */ if ( (vndims == 1) && ( strcmp(vname, dims[vdims[0]]) == 0 )) coord_dim_id = vdims[0]; else coord_dim_id = -1; snprintf(buf, BUFSIZ, INSVAR, vidx, (int)fid, vname, prim_type_name(vtype), vndims, coord_dim_id); if ( ( msg = SQLstatementIntern(cntxt, &s, "netcdf.attach", TRUE, FALSE, NULL)) != MAL_SUCCEED ) goto finish; if ( coord_dim_id < 0 ){ for (i = 0; i < vndims; i++){ snprintf(buf, BUFSIZ, INSVARDIM, vidx, vdims[i], (int)fid, i); if ( ( msg = SQLstatementIntern(cntxt, &s, "netcdf.attach", TRUE, FALSE, NULL)) != MAL_SUCCEED ) goto finish; } } if ( vnatts > 0 ) { /* fill in netcdf_attrs table */ for (aidx = 0; aidx < vnatts; aidx++){ if ((retval = nc_inq_attname(ncid,vidx,aidx,aname))) return createException(MAL, "netcdf.attach", "Cannot read attribute %d of variable %d: %s", aidx, vidx, nc_strerror(retval)); if ((retval = nc_inq_att(ncid,vidx,aname,&atype,&alen))) return createException(MAL, "netcdf.attach", "Cannot read attribute %s type and length: %s", aname, nc_strerror(retval)); switch ( atype ) { case NC_CHAR: aval = (char *) GDKzalloc(alen + 1); if ((retval = nc_get_att_text(ncid,vidx,aname,aval))) return createException(MAL, "netcdf.attach", "Cannot read attribute %s value: %s", aname, nc_strerror(retval)); fix_quote(aval, alen); aval[alen] = '\0'; snprintf(buf, BUFSIZ, INSATTR, vname, aname, "string", aval, (int)fid, "root"); GDKfree(aval); break; case NC_INT: if ((retval = nc_get_att_int(ncid,vidx,aname,&avalint))) return createException(MAL, "netcdf.attach", "Cannot read attribute %s value: %s", aname, nc_strerror(retval)); snprintf(abuf,80,"%d",avalint); snprintf(buf, BUFSIZ, INSATTR, vname, aname, prim_type_name(atype), abuf, (int)fid, "root"); break; case NC_FLOAT: if ((retval = nc_get_att_float(ncid,vidx,aname,&avalfl))) return createException(MAL, "netcdf.attach", "Cannot read attribute %s value: %s", aname, nc_strerror(retval)); snprintf(abuf,80,"%7.2f",avalfl); snprintf(buf, BUFSIZ, INSATTR, vname, aname, prim_type_name(atype), abuf, (int)fid, "root"); break; case NC_DOUBLE: if ((retval = nc_get_att_double(ncid,vidx,aname,&avaldbl))) return createException(MAL, "netcdf.attach", "Cannot read attribute %s value: %s", aname, nc_strerror(retval)); snprintf(abuf,80,"%7.2e",avaldbl); snprintf(buf, BUFSIZ, INSATTR, vname, aname, prim_type_name(atype), abuf, (int)fid, "root"); break; default: continue; /* next attribute */ } printf("statement: '%s'\n", s); if ( ( msg = SQLstatementIntern(cntxt, &s, "netcdf.attach", TRUE, FALSE, NULL)) != MAL_SUCCEED ) goto finish; } /* attr loop */ } } /* var loop */ /* Extract global attributes */ for (aidx = 0; aidx < ngatts; aidx++){ if ((retval = nc_inq_attname(ncid,NC_GLOBAL,aidx,aname))) return createException(MAL, "netcdf.attach", "Cannot read global attribute %d: %s", aidx, nc_strerror(retval)); if ((retval = nc_inq_att(ncid,NC_GLOBAL,aname,&atype,&alen))) return createException(MAL, "netcdf.attach", "Cannot read global attribute %s type and length: %s", aname, nc_strerror(retval)); switch ( atype ) { case NC_CHAR: aval = (char *) GDKzalloc(alen + 1); if ((retval = nc_get_att_text(ncid,NC_GLOBAL,aname,aval))) return createException(MAL, "netcdf.attach", "Cannot read global attribute %s value: %s", aname, nc_strerror(retval)); fix_quote(aval, alen); aval[alen] = '\0'; snprintf(buf, BUFSIZ, INSATTR, "GLOBAL", aname, "string", aval, (int)fid, "root"); GDKfree(aval); break; case NC_INT: if ((retval = nc_get_att_int(ncid,NC_GLOBAL,aname,&avalint))) return createException(MAL, "netcdf.attach", "Cannot read global attribute %s of type %s : %s", aname, prim_type_name(atype), nc_strerror(retval)); snprintf(abuf,80,"%d",avalint); snprintf(buf, BUFSIZ, INSATTR, "GLOBAL", aname, prim_type_name(atype), abuf, (int)fid, "root"); break; case NC_FLOAT: if ((retval = nc_get_att_float(ncid,NC_GLOBAL,aname,&avalfl))) return createException(MAL, "netcdf.attach", "Cannot read global attribute %s of type %s: %s", aname, prim_type_name(atype), nc_strerror(retval)); snprintf(abuf,80,"%7.2f",avalfl); snprintf(buf, BUFSIZ, INSATTR, "GLOBAL", aname, prim_type_name(atype), abuf, (int)fid, "root"); break; case NC_DOUBLE: if ((retval = nc_get_att_double(ncid,NC_GLOBAL,aname,&avaldbl))) return createException(MAL, "netcdf.attach", "Cannot read global attribute %s value: %s", aname, nc_strerror(retval)); snprintf(abuf,80,"%7.2e",avaldbl); snprintf(buf, BUFSIZ, INSATTR, "GLOBAL", aname, prim_type_name(atype), abuf, (int)fid, "root"); break; default: continue; /* next attribute */ } printf("global: '%s'\n", s); if ( ( msg = SQLstatementIntern(cntxt, &s, "netcdf.attach", TRUE, FALSE, NULL)) != MAL_SUCCEED ) goto finish; } /* global attr loop */ finish: nc_close(ncid); if (dims != NULL ){ for (didx = 0; didx < ndims; didx++) GDKfree(dims[didx]); GDKfree(dims); } return msg; }
/* import variable given file id and variable name */ str NCDFimportVariable(Client cntxt, MalBlkPtr mb, MalStkPtr stk, InstrPtr pci) { mvc *m = NULL; sql_schema *sch = NULL; sql_table *tfiles = NULL, *arr_table = NULL; sql_column *col; str msg = MAL_SUCCEED, vname = *(str*)getArgReference(stk, pci, 2); str fname = NULL, dimtype = NULL, aname_sys = NULL; int fid = *(int*)getArgReference(stk, pci, 1); int varid, vndims, vnatts, i, j, retval; char buf[BUFSIZ], *s= buf, aname[256], **dname; oid rid = oid_nil; int vdims[NC_MAX_VAR_DIMS]; nc_type vtype; int ncid; /* dataset id */ size_t dlen; bat vbatid = 0, *dim_bids; BAT *vbat = NULL, *dimbat; msg = getSQLContext(cntxt, mb, &m, NULL); if (msg) return msg; sch = mvc_bind_schema(m, "sys"); if ( !sch ) return createException(MAL, "netcdf.importvar", "Cannot get schema sys\n"); tfiles = mvc_bind_table(m, sch, "netcdf_files"); if (tfiles == NULL) return createException(MAL, "netcdf.importvar", "Catalog table missing\n"); /* get the name of the attached NetCDF file */ col = mvc_bind_column(m, tfiles, "file_id"); if (col == NULL) return createException(MAL, "netcdf.importvar", "Could not find \"netcdf_files\".\"file_id\"\n"); rid = table_funcs.column_find_row(m->session->tr, col, (void *)&fid, NULL); if (rid == oid_nil) return createException(MAL, "netcdf.importvar", "File %d not in the NetCDF vault\n", fid); col = mvc_bind_column(m, tfiles, "location"); fname = (str)table_funcs.column_find_value(m->session->tr, col, rid); /* Open NetCDF file */ if ((retval = nc_open(fname, NC_NOWRITE, &ncid))) return createException(MAL, "netcdf.importvar", "Cannot open NetCDF file %s: %s", fname, nc_strerror(retval)); /* Get info for variable vname from NetCDF file */ if ( (retval = nc_inq_varid(ncid, vname, &varid)) ) return createException(MAL, "netcdf.importvar", "Cannot read variable %s: %s", vname, nc_strerror(retval)); if ( (retval = nc_inq_var(ncid, varid, vname, &vtype, &vndims, vdims, &vnatts))) return createException(MAL, "netcdf.importvar", "Cannot read variable %d : %s", varid, nc_strerror(retval)); /* compose 'create table' statement in the buffer */ dname = (char **) GDKzalloc( sizeof(char *) * vndims); for (i = 0; i < vndims; i++) dname[i] = (char *) GDKzalloc(NC_MAX_NAME + 1); snprintf(aname, 256, "%s%d", vname, fid); j = snprintf(buf, BUFSIZ,"create table %s.%s( ", sch->base.name, aname); for (i = 0; i < vndims; i++){ if ((retval = nc_inq_dim(ncid, vdims[i], dname[i], &dlen))) return createException(MAL, "netcdf.importvar", "Cannot read dimension %d : %s", vdims[i], nc_strerror(retval)); if ( dlen <= (int) GDK_bte_max ) dimtype = "TINYINT"; else if ( dlen <= (int) GDK_sht_max ) dimtype = "SMALLINT"; else dimtype = "INT"; (void)dlen; j += snprintf(buf + j, BUFSIZ - j, "%s %s, ", dname[i], dimtype); } j += snprintf(buf + j, BUFSIZ - j, "value %s);", NCDF2SQL(vtype)); /* execute 'create table ' */ msg = SQLstatementIntern(cntxt, &s, "netcdf.importvar", TRUE, FALSE, NULL); if (msg != MAL_SUCCEED) return msg; /* load variable data */ dim_bids = (bat *)GDKmalloc(sizeof(bat) * vndims); msg = NCDFloadVar(&dim_bids, &vbatid, ncid, varid, vtype, vndims, vdims); if ( msg != MAL_SUCCEED ) return msg; /* associate columns in the table with loaded variable data */ aname_sys = toLower(aname); arr_table = mvc_bind_table(m, sch, aname_sys); if (arr_table == NULL) return createException(MAL, "netcdf.importvar", "netcdf table %s missing\n", aname_sys); col = mvc_bind_column(m, arr_table, "value"); if (col == NULL) return createException(MAL, "netcdf.importvar", "Cannot find column %s.value\n", aname_sys); vbat = BATdescriptor(vbatid); store_funcs.append_col(m->session->tr, col, vbat, TYPE_bat); BBPunfix(vbatid); BBPdecref(vbatid, 1); vbat = NULL; /* associate dimension bats */ for (i = 0; i < vndims; i++){ col = mvc_bind_column(m, arr_table, dname[i]); if (col == NULL) return createException(MAL, "netcdf.importvar", "Cannot find column %s.%s\n", aname_sys, dname[i]); dimbat = BATdescriptor(dim_bids[i]); store_funcs.append_col(m->session->tr, col, dimbat, TYPE_bat); BBPunfix(dim_bids[i]); /* phys. ref from BATdescriptor */ BBPdecref(dim_bids[i], 1); /* log. ref. from loadVar */ dimbat = NULL; } for (i = 0; i < vndims; i++) GDKfree(dname[i]); GDKfree(dname); GDKfree(dim_bids); nc_close(ncid); return msg; }
str FITSloadTable(Client cntxt, MalBlkPtr mb, MalStkPtr stk, InstrPtr pci) { mvc *m = NULL; sql_schema *sch; sql_table *fits_fl, *fits_tbl, *tbl = NULL; sql_column *col; sql_subtype tpe; fitsfile *fptr; str tname = *(str*)getArgReference(stk, pci, 1); str fname; str msg = MAL_SUCCEED; oid rid = oid_nil, frid = oid_nil; int status = 0, cnum = 0, fid, hdu, hdutype, i, j, anynull = 0, mtype; int *tpcode = NULL; long *rep = NULL, *wid = NULL, rows; char keywrd[80], **cname, nm[FLEN_VALUE]; ptr nilptr; msg = getSQLContext(cntxt, mb, &m, NULL); if (msg) return msg; sch = mvc_bind_schema(m, "sys"); fits_tbl = mvc_bind_table(m, sch, "fits_tables"); if (fits_tbl == NULL) { msg = createException(MAL, "fits.loadtable", "FITS catalog is missing.\n"); return msg; } tbl = mvc_bind_table(m, sch, tname); if (tbl) { msg = createException(MAL, "fits.loadtable", "Table %s is already created.\n", tname); return msg; } col = mvc_bind_column(m, fits_tbl, "name"); rid = table_funcs.column_find_row(m->session->tr, col, tname, NULL); if (rid == oid_nil) { msg = createException(MAL, "fits.loadtable", "Table %s is unknown in FITS catalog. Attach first the containing file\n", tname); return msg; } /* Open FITS file and move to the table HDU */ col = mvc_bind_column(m, fits_tbl, "file_id"); fid = *(int*)table_funcs.column_find_value(m->session->tr, col, rid); fits_fl = mvc_bind_table(m, sch, "fits_files"); col = mvc_bind_column(m, fits_fl, "id"); frid = table_funcs.column_find_row(m->session->tr, col, (void *)&fid, NULL); col = mvc_bind_column(m, fits_fl, "name"); fname = (char *)table_funcs.column_find_value(m->session->tr, col, frid); if (fits_open_file(&fptr, fname, READONLY, &status)) { msg = createException(MAL, "fits.loadtable", "Missing FITS file %s.\n", fname); return msg; } col = mvc_bind_column(m, fits_tbl, "hdu"); hdu = *(int*)table_funcs.column_find_value(m->session->tr, col, rid); fits_movabs_hdu(fptr, hdu, &hdutype, &status); if (hdutype != ASCII_TBL && hdutype != BINARY_TBL) { msg = createException(MAL, "fits.loadtable", "HDU %d is not a table.\n", hdu); fits_close_file(fptr, &status); return msg; } /* create a SQL table to hold the FITS table */ /* col = mvc_bind_column(m, fits_tbl, "columns"); cnum = *(int*) table_funcs.column_find_value(m->session->tr, col, rid); */ fits_get_num_cols(fptr, &cnum, &status); tbl = mvc_create_table(m, sch, tname, tt_table, 0, SQL_PERSIST, 0, cnum); tpcode = (int *)GDKzalloc(sizeof(int) * cnum); rep = (long *)GDKzalloc(sizeof(long) * cnum); wid = (long *)GDKzalloc(sizeof(long) * cnum); cname = (char **)GDKzalloc(sizeof(char *) * cnum); for (j = 1; j <= cnum; j++) { /* fits_get_acolparms(fptr, j, cname, &tbcol, tunit, tform, &tscal, &tzero, tnull, tdisp, &status); */ snprintf(keywrd, 80, "TTYPE%d", j); fits_read_key(fptr, TSTRING, keywrd, nm, NULL, &status); if (status) { snprintf(nm, FLEN_VALUE, "column_%d", j); status = 0; } cname[j - 1] = GDKstrdup(toLower(nm)); fits_get_coltype(fptr, j, &tpcode[j - 1], &rep[j - 1], &wid[j - 1], &status); fits2subtype(&tpe, tpcode[j - 1], rep[j - 1], wid[j - 1]); /* mnstr_printf(cntxt->fdout,"#%d %ld %ld - M: %s\n", tpcode[j-1], rep[j-1], wid[j-1], tpe.type->sqlname); */ mvc_create_column(m, tbl, cname[j - 1], &tpe); } /* data load */ fits_get_num_rows(fptr, &rows, &status); mnstr_printf(cntxt->fdout,"#Loading %ld rows in table %s\n", rows, tname); for (j = 1; j <= cnum; j++) { BAT *tmp = NULL; int time0 = GDKms(); mtype = fits2mtype(tpcode[j - 1]); nilptr = ATOMnil(mtype); col = mvc_bind_column(m, tbl, cname[j - 1]); tmp = BATnew(TYPE_void, mtype, rows); if ( tmp == NULL){ GDKfree(tpcode); GDKfree(rep); GDKfree(wid); GDKfree(cname); throw(MAL,"fits.load", MAL_MALLOC_FAIL); } BATseqbase(tmp, 0); if (rows > (long)REMAP_PAGE_MAXSIZE) BATmmap(tmp, STORE_MMAP, STORE_MMAP, STORE_MMAP, STORE_MMAP, 0); if (mtype != TYPE_str) { fits_read_col(fptr, tpcode[j - 1], j, 1, 1, rows, nilptr, (void *)BUNtloc(bat_iterator(tmp), BUNfirst(tmp)), &anynull, &status); BATsetcount(tmp, rows); tmp->tsorted = 0; tmp->trevsorted = 0; } else { /* char *v = GDKzalloc(wid[j-1]);*/ int bsize = 50; int tm0, tloadtm = 0, tattachtm = 0; int batch = bsize, k; char **v = (char **) GDKzalloc(sizeof(char *) * bsize); for(i = 0; i < bsize; i++) v[i] = GDKzalloc(wid[j-1]); for(i = 0; i < rows; i += batch) { batch = rows - i < bsize ? rows - i: bsize; tm0 = GDKms(); fits_read_col(fptr, tpcode[j - 1], j, 1 + i, 1, batch, nilptr, (void *)v, &anynull, &status); tloadtm += GDKms() - tm0; tm0 = GDKms(); for(k = 0; k < batch ; k++) BUNappend(tmp, v[k], TRUE); tattachtm += GDKms() - tm0; } for(i = 0; i < bsize ; i++) GDKfree(v[i]); GDKfree(v); mnstr_printf(cntxt->fdout,"#String column load %d ms, BUNappend %d ms\n", tloadtm, tattachtm); } if (status) { char buf[FLEN_ERRMSG + 1]; fits_read_errmsg(buf); msg = createException(MAL, "fits.loadtable", "Cannot load column %s of %s table: %s.\n", cname[j - 1], tname, buf); break; } mnstr_printf(cntxt->fdout,"#Column %s loaded for %d ms\t", cname[j-1], GDKms() - time0); store_funcs.append_col(m->session->tr, col, tmp, TYPE_bat); mnstr_printf(cntxt->fdout,"#Total %d ms\n", GDKms() - time0); BBPunfix(tmp->batCacheid); } GDKfree(tpcode); GDKfree(rep); GDKfree(wid); GDKfree(cname); fits_close_file(fptr, &status); return msg; }
str FITSattach(Client cntxt, MalBlkPtr mb, MalStkPtr stk, InstrPtr pci) { mvc *m = NULL; sql_trans *tr; sql_schema *sch; sql_table *fits_tp, *fits_fl, *fits_tbl, *fits_col, *tbl = NULL; sql_column *col; str msg = MAL_SUCCEED; str fname = *(str*)getArgReference(stk, pci, 1); fitsfile *fptr; /* pointer to the FITS file */ int status = 0, i, j, hdutype, hdunum = 1, cnum = 0, bitpixnumber = 0; oid fid, tid, cid, rid = oid_nil; char tname[BUFSIZ], *tname_low = NULL, *s, bname[BUFSIZ], stmt[BUFSIZ]; long tbcol; char cname[BUFSIZ], tform[BUFSIZ], tunit[BUFSIZ], tnull[BUFSIZ], tdisp[BUFSIZ]; double tscal, tzero; char xtensionname[BUFSIZ] = "", stilversion[BUFSIZ] = ""; char stilclass[BUFSIZ] = "", tdate[BUFSIZ] = "", orig[BUFSIZ] = "", comm[BUFSIZ] = ""; msg = getSQLContext(cntxt, mb, &m, NULL); if (msg) return msg; if (fits_open_file(&fptr, fname, READONLY, &status)) { msg = createException(MAL, "fits.attach", "Missing FITS file %s.\n", fname); return msg; } tr = m->session->tr; sch = mvc_bind_schema(m, "sys"); fits_fl = mvc_bind_table(m, sch, "fits_files"); if (fits_fl == NULL) FITSinitCatalog(m); fits_fl = mvc_bind_table(m, sch, "fits_files"); fits_tbl = mvc_bind_table(m, sch, "fits_tables"); fits_col = mvc_bind_table(m, sch, "fits_columns"); fits_tp = mvc_bind_table(m, sch, "fits_table_properties"); /* check if the file is already attached */ col = mvc_bind_column(m, fits_fl, "name"); rid = table_funcs.column_find_row(m->session->tr, col, fname, NULL); if (rid != oid_nil) { fits_close_file(fptr, &status); msg = createException(SQL, "fits.attach", "File %s already attached\n", fname); return msg; } /* add row in the fits_files catalog table */ col = mvc_bind_column(m, fits_fl, "id"); fid = store_funcs.count_col(tr, col, 1) + 1; store_funcs.append_col(m->session->tr, mvc_bind_column(m, fits_fl, "id"), &fid, TYPE_int); store_funcs.append_col(m->session->tr, mvc_bind_column(m, fits_fl, "name"), fname, TYPE_str); col = mvc_bind_column(m, fits_tbl, "id"); tid = store_funcs.count_col(tr, col, 1) + 1; if ((s = strrchr(fname, DIR_SEP)) == NULL) s = fname; else s++; strcpy(bname, s); s = strrchr(bname, '.'); if (s) *s = 0; fits_get_num_hdus(fptr, &hdunum, &status); for (i = 1; i <= hdunum; i++) { fits_movabs_hdu(fptr, i, &hdutype, &status); if (hdutype != ASCII_TBL && hdutype != BINARY_TBL) continue; /* SQL table name - the name of FITS extention */ fits_read_key(fptr, TSTRING, "EXTNAME", tname, NULL, &status); if (status) { snprintf(tname, BUFSIZ, "%s_%d", bname, i); tname_low = toLower(tname); status = 0; }else { /* check table name for existence in the fits catalog */ tname_low = toLower(tname); col = mvc_bind_column(m, fits_tbl, "name"); rid = table_funcs.column_find_row(m->session->tr, col, tname_low, NULL); /* or as regular SQL table */ tbl = mvc_bind_table(m, sch, tname_low); if (rid != oid_nil || tbl) { snprintf(tname, BUFSIZ, "%s_%d", bname, i); tname_low = toLower(tname); } } fits_read_key(fptr, TSTRING, "BITPIX", &bitpixnumber, NULL, &status); if (status) { status = 0; } fits_read_key(fptr, TSTRING, "DATE-HDU", tdate, NULL, &status); if (status) { status = 0; } fits_read_key(fptr, TSTRING, "XTENSION", xtensionname, NULL, &status); if (status) { status = 0; } fits_read_key(fptr, TSTRING, "STILVERS", stilversion, NULL, &status); if (status) { status = 0; } fits_read_key(fptr, TSTRING, "STILCLAS", stilclass, NULL, &status); if (status) { status = 0; } fits_read_key(fptr, TSTRING, "ORIGIN", orig, NULL, &status); if (status) { status = 0; } fits_read_key(fptr, TSTRING, "COMMENT", comm, NULL, &status); if (status) { status = 0; } fits_get_num_cols(fptr, &cnum, &status); store_funcs.append_col(m->session->tr, mvc_bind_column(m, fits_tbl, "id"), &tid, TYPE_int); store_funcs.append_col(m->session->tr, mvc_bind_column(m, fits_tbl, "name"), tname_low, TYPE_str); store_funcs.append_col(m->session->tr, mvc_bind_column(m, fits_tbl, "columns"), &cnum, TYPE_int); store_funcs.append_col(m->session->tr, mvc_bind_column(m, fits_tbl, "file_id"), &fid, TYPE_int); store_funcs.append_col(m->session->tr, mvc_bind_column(m, fits_tbl, "hdu"), &i, TYPE_int); store_funcs.append_col(m->session->tr, mvc_bind_column(m, fits_tbl, "date"), tdate, TYPE_str); store_funcs.append_col(m->session->tr, mvc_bind_column(m, fits_tbl, "origin"), orig, TYPE_str); store_funcs.append_col(m->session->tr, mvc_bind_column(m, fits_tbl, "comment"), comm, TYPE_str); store_funcs.append_col(m->session->tr, mvc_bind_column(m, fits_tp, "table_id"), &tid, TYPE_int); store_funcs.append_col(m->session->tr, mvc_bind_column(m, fits_tp, "xtension"), xtensionname, TYPE_str); store_funcs.append_col(m->session->tr, mvc_bind_column(m, fits_tp, "bitpix"), &bitpixnumber, TYPE_int); store_funcs.append_col(m->session->tr, mvc_bind_column(m, fits_tp, "stilvers"), stilversion, TYPE_str); store_funcs.append_col(m->session->tr, mvc_bind_column(m, fits_tp, "stilclas"), stilclass, TYPE_str); /* read columns description */ s = stmt; col = mvc_bind_column(m, fits_col, "id"); cid = store_funcs.count_col(tr, col, 1) + 1; for (j = 1; j <= cnum; j++, cid++) { fits_get_acolparms(fptr, j, cname, &tbcol, tunit, tform, &tscal, &tzero, tnull, tdisp, &status); snprintf(stmt, BUFSIZ, FITS_INS_COL, (int)cid, cname, tform, tunit, j, (int)tid); msg = SQLstatementIntern(cntxt, &s, "fits.attach", TRUE, FALSE); if (msg != MAL_SUCCEED) { fits_close_file(fptr, &status); return msg; } } tid++; } fits_close_file(fptr, &status); return MAL_SUCCEED; }
str FITSexportTable(Client cntxt, MalBlkPtr mb, MalStkPtr stk, InstrPtr pci) { str msg = MAL_SUCCEED; str tname = *(str*) getArgReference(stk, pci, 1); mvc *m = NULL; sql_trans *tr; sql_schema *sch; sql_table *tbl, *column, *tables = NULL; sql_column *col; oid rid = oid_nil; str type, name, *colname, *tform; fitsfile *fptr; char filename[BUFSIZ]; long nrows = 0, optimal; rids * rs; int tm0, texportboolean=0, texportchar=0, texportstring=0, texportshort=0, texportint=0, texportlong=0, texportfloat=0, texportdouble=0; int numberrow = 0, cc = 0, status = 0, j = 0, columns, fid, dimension = 0, block = 0; int boolcols = 0, charcols = 0, strcols = 0, shortcols = 0, intcols = 0, longcols = 0, floatcols = 0, doublecols = 0; int hdutype; char charvalue, *readcharrows; str strvalue; char **readstrrows; short shortvalue, *readshortrows; int intvalue, *readintrows; long longvalue, *readlongrows; float realvalue, *readfloatrows; double doublevalue, *readdoublerows; _Bool boolvalue, *readboolrows; struct list * set; msg = getSQLContext(cntxt, mb, &m, NULL); if (msg) return msg; tr = m->session->tr; sch = mvc_bind_schema(m, "sys"); /* First step: look if the table exists in the database. If the table is not in the database, the export function cannot continue */ tbl = mvc_bind_table(m, sch, tname); if (tbl == NULL) { msg = createException (MAL, "fits.exporttable", "Table %s is missing.\n", tname); return msg; } set = (*tbl).columns.set; columns = list_length(set); colname = (str *) GDKmalloc(columns * sizeof(str)); tform = (str *) GDKmalloc(columns * sizeof(str)); /* mnstr_printf(GDKout,"Number of columns: %d\n", columns);*/ tables = mvc_bind_table(m, sch, "_tables"); col = mvc_bind_column(m, tables, "name"); rid = table_funcs.column_find_row(m->session->tr, col, tname, NULL); col = mvc_bind_column(m, tables, "id"); fid = *(int*) table_funcs.column_find_value(m->session->tr, col, rid); column = mvc_bind_table(m, sch, "_columns"); col = mvc_bind_column(m, column, "table_id"); rs = table_funcs.rids_select(m->session->tr, col, (void *) &fid, (void *) &fid, NULL); while ((rid = table_funcs.rids_next(rs)) != oid_nil) { col = mvc_bind_column(m, column, "name"); name = (char *) table_funcs.column_find_value(m->session->tr, col, rid); colname[j] = toLower(name); col = mvc_bind_column(m, column, "type"); type = (char *) table_funcs.column_find_value(m->session->tr, col, rid); if (strcmp(type,"boolean")==0) tform[j] = "1L"; if (strcmp(type,"char")==0) tform[j] = "1S"; if (strcmp(type,"varchar")==0) tform[j] = "8A"; if (strcmp(type,"smallint")==0) tform[j] = "1I"; if (strcmp(type,"int")==0) tform[j] = "1J"; if (strcmp(type,"bigint")==0) tform[j] = "1K"; if (strcmp(type,"real")==0) tform[j] = "1E"; if (strcmp(type,"double")==0) tform[j] = "1D"; j++; } col = mvc_bind_column(m, tbl, colname[0]); nrows = store_funcs.count_col(tr, col, 1); snprintf(filename,BUFSIZ,"\n%s.fit",tname); mnstr_printf(GDKout, "Filename: %s\n", filename); remove(filename); status=0; fits_create_file(&fptr, filename, &status); fits_create_img(fptr, USHORT_IMG, 0, NULL, &status); fits_close_file(fptr, &status); fits_open_file(&fptr, filename, READWRITE, &status); fits_movabs_hdu(fptr, 1, &hdutype, &status); fits_create_tbl( fptr, BINARY_TBL, 0, columns, colname, tform, NULL, tname, &status); for (cc = 0; cc < columns; cc++) { char * columntype; col = mvc_bind_column(m, tbl, colname[cc]); columntype = col -> type.type->sqlname; if (strcmp(columntype,"boolean")==0) { boolcols++; dimension = 0; block = 0; fits_get_rowsize(fptr,&optimal,&status); readboolrows = (_Bool *) GDKmalloc (sizeof(_Bool) * optimal); for (numberrow = 0; numberrow < nrows ; numberrow++) { boolvalue = *(_Bool*) table_funcs.column_find_value(m->session->tr, col, numberrow); readboolrows[dimension] = boolvalue; dimension++; if (dimension == optimal) { dimension = 0; tm0 = GDKms(); fits_write_col(fptr, TLOGICAL, cc+1, (optimal*block)+1, 1, optimal, readboolrows, &status); texportboolean += GDKms() - tm0; GDKfree(readboolrows); readboolrows = (_Bool *) GDKmalloc (sizeof(_Bool) * optimal); block++; } } tm0 = GDKms(); fits_write_col(fptr, TLOGICAL, cc+1, (optimal*block)+1, 1, dimension, readboolrows, &status); texportboolean += GDKms() - tm0; GDKfree(readboolrows); } if (strcmp(columntype,"char")==0) { charcols++; dimension = 0; block = 0; fits_get_rowsize(fptr,&optimal,&status); readcharrows = (char *) GDKmalloc (sizeof(char) * optimal); for (numberrow = 0; numberrow < nrows ; numberrow++) { charvalue = *(char*) table_funcs.column_find_value(m->session->tr, col, numberrow); readcharrows[dimension] = charvalue; dimension++; if (dimension == optimal) { dimension = 0; tm0 = GDKms(); fits_write_col(fptr, TBYTE, cc+1, (optimal*block)+1, 1, optimal, readcharrows, &status); texportchar += GDKms() - tm0; GDKfree(readcharrows); readcharrows = (char *) GDKmalloc (sizeof(char) * optimal); block++; } } tm0 = GDKms(); fits_write_col(fptr, TBYTE, cc+1, (optimal*block)+1, 1, dimension, readcharrows, &status); texportchar += GDKms() - tm0; GDKfree(readcharrows); } if (strcmp(columntype,"varchar")==0) { strcols++; dimension=0; block=0; fits_get_rowsize(fptr,&optimal,&status); readstrrows = (char **) GDKmalloc (sizeof(char *) * optimal); for (numberrow = 0; numberrow < nrows ; numberrow++) { strvalue = (char *) table_funcs.column_find_value(m->session->tr, col, numberrow); readstrrows[dimension] = strvalue; dimension++; if (dimension == optimal) { dimension = 0; tm0 = GDKms(); fits_write_col_str(fptr, cc+1, (optimal*block)+1, 1, optimal, readstrrows, &status); texportstring += GDKms() - tm0; GDKfree(readstrrows); readstrrows = (char **) GDKmalloc(sizeof(char *) * optimal); block++; } } tm0 = GDKms(); fits_write_col_str(fptr, cc+1, (optimal*block)+1, 1, dimension, readstrrows, &status); texportstring += GDKms() - tm0; GDKfree(readstrrows); } if (strcmp(columntype,"smallint")==0) { shortcols++; dimension = 0; block = 0; fits_get_rowsize(fptr,&optimal,&status); readshortrows = (short *) GDKmalloc (sizeof(short) * optimal); for (numberrow = 0; numberrow < nrows ; numberrow++) { shortvalue = *(short*) table_funcs.column_find_value(m->session->tr, col, numberrow); readshortrows[dimension] = shortvalue; dimension++; if (dimension == optimal) { dimension = 0; tm0 = GDKms(); fits_write_col(fptr, TSHORT, cc+1, (optimal*block)+1, 1, optimal, readshortrows, &status); texportshort += GDKms() - tm0; GDKfree(readshortrows); readshortrows = (short *) GDKmalloc (sizeof(short) * optimal); block++; } } tm0 = GDKms(); fits_write_col(fptr, TSHORT, cc+1, (optimal*block)+1, 1, dimension, readshortrows, &status); texportshort += GDKms() - tm0; GDKfree(readshortrows); } if (strcmp(columntype,"int")==0) { intcols++; dimension = 0; block = 0; fits_get_rowsize(fptr,&optimal,&status); readintrows = (int *) GDKmalloc (sizeof(int) * optimal); for (numberrow = 0; numberrow < nrows ; numberrow++) { intvalue = *(int*) table_funcs.column_find_value(m->session->tr, col, numberrow); readintrows[dimension] = intvalue; dimension++; if (dimension == optimal) { dimension = 0; tm0 = GDKms(); fits_write_col(fptr, TINT, cc+1, (optimal*block)+1, 1, optimal, readintrows, &status); texportint += GDKms() - tm0; GDKfree(readintrows); readintrows = (int *) GDKmalloc (sizeof(int) * optimal); block++; } } tm0 = GDKms(); fits_write_col(fptr, TINT, cc+1, (optimal*block)+1, 1, dimension, readintrows, &status); texportint += GDKms() - tm0; GDKfree(readintrows); } if (strcmp(columntype,"bigint")==0) { longcols++; dimension = 0; block = 0; fits_get_rowsize(fptr,&optimal,&status); readlongrows = (long *) GDKmalloc (sizeof(long) * optimal); for (numberrow = 0; numberrow < nrows ; numberrow++) { longvalue = *(long*) table_funcs.column_find_value(m->session->tr, col, numberrow); readlongrows[dimension] = longvalue; dimension++; if (dimension == optimal) { dimension = 0; tm0 = GDKms(); fits_write_col(fptr, TLONG, cc+1, (optimal*block)+1, 1, optimal, readlongrows, &status); texportlong += GDKms() - tm0; GDKfree(readlongrows); readlongrows = (long *) GDKmalloc (sizeof(long) * optimal); block++; } } tm0 = GDKms(); fits_write_col(fptr, TLONG, cc+1, (optimal*block)+1, 1, dimension, readlongrows, &status); texportlong += GDKms() - tm0; GDKfree(readlongrows); } if (strcmp(columntype,"real")==0) { floatcols++; dimension = 0; block = 0; fits_get_rowsize(fptr,&optimal,&status); readfloatrows = (float *) GDKmalloc (sizeof(float) * optimal); for (numberrow = 0; numberrow < nrows ; numberrow++) { realvalue = *(float*) table_funcs.column_find_value(m->session->tr, col, numberrow); readfloatrows[dimension] = realvalue; dimension++; if (dimension == optimal) { dimension = 0; tm0 = GDKms(); fits_write_col(fptr, TFLOAT, cc+1, (optimal*block)+1, 1, optimal, readfloatrows, &status); texportfloat += GDKms() - tm0; GDKfree(readfloatrows); readfloatrows = (float *) GDKmalloc (sizeof(float) * optimal); block++; } } tm0 = GDKms(); fits_write_col(fptr, TFLOAT, cc+1, (optimal*block)+1, 1, dimension, readfloatrows, &status); texportfloat += GDKms() - tm0; GDKfree(readfloatrows); } if (strcmp(columntype,"double")==0) { doublecols++; dimension = 0; block = 0; fits_get_rowsize(fptr,&optimal,&status); readdoublerows = (double *) GDKmalloc (sizeof(double) * optimal); for (numberrow = 0; numberrow < nrows ; numberrow++) { doublevalue = *(double*) table_funcs.column_find_value(m->session->tr, col, numberrow); readdoublerows[dimension] = doublevalue; dimension++; if (dimension == optimal) { dimension = 0; tm0 = GDKms(); fits_write_col(fptr, TDOUBLE, cc+1, (optimal*block)+1, 1, optimal, readdoublerows, &status); texportdouble += GDKms() - tm0; GDKfree(readdoublerows); readdoublerows = (double *) GDKmalloc (sizeof(double) * optimal); block++; } } tm0 = GDKms(); fits_write_col(fptr, TDOUBLE, cc+1, (optimal*block)+1, 1, optimal, readdoublerows, &status); texportdouble += GDKms() - tm0; GDKfree(readdoublerows); } } /* print all the times that were needed to export each one of the columns mnstr_printf(GDKout, "\n\n"); if (texportboolean > 0) mnstr_printf(GDKout, "%d Boolean\tcolumn(s) exported in %d ms\n", boolcols, texportboolean); if (texportchar > 0) mnstr_printf(GDKout, "%d Char\t\tcolumn(s) exported in %d ms\n", charcols, texportchar); if (texportstring > 0) mnstr_printf(GDKout, "%d String\tcolumn(s) exported in %d ms\n", strcols, texportstring); if (texportshort > 0) mnstr_printf(GDKout, "%d Short\t\tcolumn(s) exported in %d ms\n", shortcols, texportshort); if (texportint > 0) mnstr_printf(GDKout, "%d Integer\tcolumn(s) exported in %d ms\n", intcols, texportint); if (texportlong > 0) mnstr_printf(GDKout, "%d Long\t\tcolumn(s) exported in %d ms\n", longcols, texportlong); if (texportfloat > 0) mnstr_printf(GDKout, "%d Float\t\tcolumn(s) exported in %d ms\n", floatcols, texportfloat); if (texportdouble > 0) mnstr_printf(GDKout, "%d Double\tcolumn(s) exported in %d ms\n", doublecols, texportdouble); */ fits_close_file(fptr, &status); return msg; }
static str SHPimportFile(Client cntxt, MalBlkPtr mb, MalStkPtr stk, InstrPtr pci, bool partial) { mvc *m = NULL; sql_schema *sch = NULL; char *sch_name = "sys"; sql_table *shps_table = NULL, *fls_table = NULL, *data_table = NULL; char *shps_table_name = "shapefiles"; char *fls_table_name = "files"; char *data_table_name = NULL; sql_column *col; sql_column **cols; BAT **colsBAT; int colsNum = 2; //we will have at least the gid column and a geometry column int rowsNum = 0; //the number of rows in the shape file that will be imported //GIntBig rowsNum = 0; int gidNum = 0; char *nameToLowerCase = NULL; str msg = MAL_SUCCEED; str fname = NULL; int vid = *(int*)getArgReference(stk, pci, 1); ptr *p; wkb *g; OGRGeometryH geom; OGREnvelope *mbb; /* SHP-level descriptor */ OGRFieldDefnH hFieldDefn; int i=0; oid irid; GDALWConnection shp_conn; GDALWConnection * shp_conn_ptr = NULL; GDALWSimpleFieldDef * field_definitions; OGRFeatureH feature; OGRFeatureDefnH featureDefn; /* get table columns from shp and create the table */ if((msg = getSQLContext(cntxt, mb, &m, NULL)) != MAL_SUCCEED) return msg; if((msg = checkSQLContext(cntxt)) != MAL_SUCCEED) return msg; if(!(sch = mvc_bind_schema(m, sch_name))) return createException(MAL, "shp.import", SQLSTATE(38000) "Schema '%s' missing", sch_name); /* find the name of the shape file corresponding to the given id */ if(!(fls_table = mvc_bind_table(m, sch, fls_table_name))) return createException(MAL, "shp.import", SQLSTATE(38000) "Table '%s.%s' missing", sch_name, fls_table_name); if(!(col = mvc_bind_column(m, fls_table, "id"))) return createException(MAL, "shp.import", SQLSTATE(38000) "Column '%s.%s(id)' missing", sch_name, fls_table_name); irid = table_funcs.column_find_row(m->session->tr, col, (void *)&vid, NULL); if (is_oid_nil(irid)) return createException(MAL, "shp.import", SQLSTATE(38000) "Shapefile with id %d not in the %s.%s table\n", vid, sch_name, fls_table_name); if(!(col = mvc_bind_column(m, fls_table, "path"))) return createException(MAL, "shp.import", SQLSTATE(38000) "Column '%s.%s(path)' missing", sch_name, fls_table_name); fname = (str)table_funcs.column_find_value(m->session->tr, col, irid); /* find the name of the table that has been reserved for this shape file */ if(!(shps_table = mvc_bind_table(m, sch, shps_table_name))) return createException(MAL, "shp.import", SQLSTATE(38000) "Table '%s.%s' missing", sch_name, shps_table_name); if(!(col = mvc_bind_column(m, shps_table, "fileid"))) return createException(MAL, "shp.import", SQLSTATE(38000) "Column '%s.%s(fileid)' missing", sch_name, shps_table_name); irid = table_funcs.column_find_row(m->session->tr, col, (void *)&vid, NULL); if (is_oid_nil(irid)) return createException(MAL, "shp.import", SQLSTATE(38000) "Shapefile with id %d not in the Shapefile catalog\n", vid); if(!(col = mvc_bind_column(m, shps_table, "datatable"))) return createException(MAL, "shp.import", SQLSTATE(38000) "Column '%s.%s(datatable)' missing", sch_name, shps_table_name); data_table_name = (str)table_funcs.column_find_value(m->session->tr, col, irid); /* add the data on the file to the table */ if(!(shp_conn_ptr = GDALWConnect((char *) fname))) return createException(MAL, "shp.import", SQLSTATE(38000) "Missing shape file %s\n", fname); shp_conn = *shp_conn_ptr; /*count the number of lines in the shape file */ if ((rowsNum = OGR_L_GetFeatureCount(shp_conn.layer, false)) == -1) { if ((rowsNum = OGR_L_GetFeatureCount(shp_conn.layer, true)) == -1) { OGR_L_ResetReading(shp_conn.layer); rowsNum = 0; while ((feature = OGR_L_GetNextFeature(shp_conn.layer)) != NULL ) { rowsNum++; OGR_F_Destroy(feature); } } } /* calculate the mbb of the query geometry */ if (partial) { p = (ptr*)getArgReference(stk, pci, 2); g = (wkb*)*p; geom = OGR_G_CreateGeometry(wkbPolygon); if (OGR_G_ImportFromWkb(geom, (unsigned char*)g->data, g->len) != OGRERR_NONE) { msg = createException(MAL, "shp.import", SQLSTATE(38000) "Could not intantiate the query polygon."); OGR_F_Destroy(geom); goto final; } if (!(mbb = (OGREnvelope*)GDKmalloc(sizeof(OGREnvelope)))) { msg = createException(MAL, "shp.import", SQLSTATE(HY001) MAL_MALLOC_FAIL); OGR_F_Destroy(geom); goto final; }
/* attach a single shp file given its name, fill in shp catalog tables */ str SHPattach(Client cntxt, MalBlkPtr mb, MalStkPtr stk, InstrPtr pci) { mvc *m = NULL; sql_schema *sch = NULL; sql_table *fls = NULL, *shps = NULL, *shps_dbf = NULL; sql_column *col; str msg = MAL_SUCCEED; str fname = *(str*)getArgReference(stk, pci, 1); /* SHP-level descriptor */ char buf[BUFSIZ], temp_buf[BUFSIZ], *s=buf; int i=0, shpid = 0; oid fid, rid = oid_nil; GDALWConnection shp_conn; GDALWConnection * shp_conn_ptr = NULL; GDALWSimpleFieldDef * field_definitions; GDALWSpatialInfo spatial_info; char *nameToLowerCase = NULL; if((msg = getSQLContext(cntxt, mb, &m, NULL)) != MAL_SUCCEED) return msg; if((msg = checkSQLContext(cntxt)) != MAL_SUCCEED) return msg; if(!(sch = mvc_bind_schema(m, "sys"))) return createException(MAL, "shp.attach", SQLSTATE(38000) "Schema sys missing\n"); fls = mvc_bind_table(m, sch, "files"); shps = mvc_bind_table(m, sch, "shapefiles"); shps_dbf = mvc_bind_table(m, sch, "shapefiles_dbf"); if (fls == NULL || shps == NULL || shps_dbf == NULL ) return createException(MAL, "shp.attach", SQLSTATE(38000) "Catalog table missing\n"); if ((shp_conn_ptr = GDALWConnect((char *) fname)) == NULL) { return createException(MAL, "shp.attach", SQLSTATE(38000) "Missing shape file %s\n", fname); } shp_conn = *shp_conn_ptr; /* check if the file is already attached */ col = mvc_bind_column(m, fls, "path"); rid = table_funcs.column_find_row(m->session->tr, col, fname, NULL); if (!is_oid_nil(rid)) { GDALWClose(shp_conn_ptr); return createException(MAL, "shp.attach", SQLSTATE(38000) "File %s already attached\n", fname); } /* add row in the files(id, path) catalog table */ col = mvc_bind_column(m, fls, "id"); fid = store_funcs.count_col(m->session->tr, col, 1) + 1; snprintf(buf, BUFSIZ, INSFILE, (int)fid, fname); if ( ( msg = SQLstatementIntern(cntxt, &s,"shp.attach",TRUE,FALSE,NULL)) != MAL_SUCCEED) goto finish; /*if (shp_conn.layer == NULL || shp_conn.source == NULL || shp_conn.handler == NULL || shp_conn.driver == NULL) { msg = createException(MAL, "shp.attach", SQLSTATE(38000) "lol-1\n"); return msg; }*/ /* add row in the shapefiles catalog table (e.g. the name of the table that will store tha data of the shapefile) */ spatial_info = GDALWGetSpatialInfo(shp_conn); col = mvc_bind_column(m, shps, "shapefileid"); shpid = store_funcs.count_col(m->session->tr, col, 1) + 1; nameToLowerCase = toLower(shp_conn.layername); snprintf(buf, BUFSIZ, INSSHP, shpid, (int)fid, spatial_info.epsg, nameToLowerCase); GDKfree(nameToLowerCase); if ( ( msg = SQLstatementIntern(cntxt, &s,"shp.attach",TRUE,FALSE,NULL)) != MAL_SUCCEED) goto finish; /* add information about the fields of the shape file * one row for each field with info (shapefile_id, field_name, field_type) */ field_definitions = GDALWGetSimpleFieldDefinitions(shp_conn); if (field_definitions == NULL) { GDALWClose(&shp_conn); return createException(MAL, "shp.attach", SQLSTATE(HY001) MAL_MALLOC_FAIL); } for (i=0 ; i<shp_conn.numFieldDefinitions ; i++) { snprintf(buf, BUFSIZ, INSSHPDBF, shpid, field_definitions[i].fieldName, field_definitions[i].fieldType); if ( ( msg = SQLstatementIntern(cntxt, &s,"shp.attach",TRUE,FALSE,NULL)) != MAL_SUCCEED) goto fin; } /* create the table that will store the data of the shape file */ temp_buf[0]='\0'; for (i=0 ; i<shp_conn.numFieldDefinitions ; i++) { nameToLowerCase = toLower(field_definitions[i].fieldName); if (strcmp(field_definitions[i].fieldType, "Integer") == 0) { sprintf(temp_buf + strlen(temp_buf), "\"%s\" INT, ", nameToLowerCase); } else if (strcmp(field_definitions[i].fieldType, "Real") == 0) { sprintf(temp_buf + strlen(temp_buf), "\"%s\" FLOAT, ", nameToLowerCase); #if 0 } else if (strcmp(field_definitions[i].fieldType, "Date") == 0) { sprintf(temp_buf + strlen(temp_buf), "\"%s\" STRING, ", nameToLowerCase); #endif } else sprintf(temp_buf + strlen(temp_buf), "\"%s\" STRING, ", nameToLowerCase); GDKfree(nameToLowerCase); } sprintf(temp_buf + strlen(temp_buf), "geom GEOMETRY "); snprintf(buf, BUFSIZ, CRTTBL, shp_conn.layername, temp_buf); if ( ( msg = SQLstatementIntern(cntxt, &s,"shp.import",TRUE,FALSE,NULL)) != MAL_SUCCEED) goto fin; fin: free(field_definitions); finish: /* if (msg != MAL_SUCCEED){ snprintf(buf, BUFSIZ,"ROLLBACK;"); SQLstatementIntern(cntxt,&s,"geotiff.attach",TRUE,FALSE)); }*/ GDALWClose(&shp_conn); return msg; }