The R Project SVN R-packages

Rev

Rev 3281 | Rev 3284 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
3251 mrmanese 1
#include <stdio.h>
2
#include <string.h>
3252 mrmanese 3
#include "sqlite_dataframe.h"
3251 mrmanese 4
 
3255 mrmanese 5
/****************************************************************************
6
 * UTILITY FUNCTIONS
7
 ****************************************************************************/
3251 mrmanese 8
 
3255 mrmanese 9
/* if user supplied a name, return that name. otherwise, use the 
10
 * default "data" */
11
int _check_sdf_name(SEXP name, char **rname, char **iname, int *file_idx) {
12
    int namelen = 0;
13
 
3252 mrmanese 14
    /* check if arg name is supplied */
3251 mrmanese 15
    if (IS_CHARACTER(name)) {
3255 mrmanese 16
        *rname = CHAR_ELT(name,0);
17
        if (!_is_r_sym(*rname)) { 
18
            Rprintf("Error: supplied name \"%s\"is not a valid R symbol.\n", 
19
                    *rname); 
20
            return FALSE; 
21
        }
22
        namelen = strlen(*rname);
23
        *iname = (char*)R_alloc(namelen + 9, sizeof(char)); /* <name>10000.db\0 */
24
        sprintf(*iname, "%s.db", *rname);
3251 mrmanese 25
    } else if (name == R_NilValue) {
3255 mrmanese 26
        *rname = "data";
3252 mrmanese 27
        namelen = 5;
3255 mrmanese 28
        *iname = (char*)R_alloc(13, sizeof(char)); /* data10000.db\0 */
29
        *file_idx = 1;
30
        sprintf(*iname, "%s%d.db", *rname, *file_idx);
3251 mrmanese 31
    } else {
3255 mrmanese 32
        Rprintf("Error: the supplied value for arg name is not a string.\n");
3251 mrmanese 33
    }
3255 mrmanese 34
    return namelen;
35
}
3251 mrmanese 36
 
3255 mrmanese 37
int _find_free_filename(char *rname, char **iname, int *namelen, int *file_idx) {
3251 mrmanese 38
    do {
3255 mrmanese 39
        if (!_file_exists(*iname)) break;
40
        *namelen = sprintf(*iname, "%s%d.db", rname, ++(*file_idx)) - 3;
41
    } while (*file_idx < 10000);
42
 
43
    return *file_idx;
44
}
45
 
46
/* creates an sdf attribute table */
47
static int _create_sdf_attribute2(const char *iname) {
48
    sprintf(g_sql_buf[2], "create table [%s].sdf_attributes(attr text, "
49
            "value text, primary key (attr))", iname);
50
    int res = _sqlite_exec(g_sql_buf[2]);
51
    if (res == SQLITE_OK) {
52
        sprintf(g_sql_buf[2], "insert into [%s].sdf_attributes values ('name',"
53
                "'%s');", iname, iname);
54
        res = _sqlite_exec(g_sql_buf[2]);
55
    }
56
    return res;
57
}
58
 
59
/* checks if a column has a corresponding factor|ordered table */
60
static int _is_factor2(const char *iname, const char *factor_type, const char *colname) {
3281 mrmanese 61
    sqlite3_stmt *stmt;
3255 mrmanese 62
    sprintf(g_sql_buf[2], "select * from [%s].[%s %s]", iname, factor_type,
63
            colname);
64
    int res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, 0);
3282 mrmanese 65
    sqlite3_finalize(stmt);
3255 mrmanese 66
    return res == SQLITE_OK;
67
}
68
 
69
/* create a factor|ordered table */
70
static int _create_factor_table2(const char *iname, const char *factor_type, 
71
        const char *colname) {
72
    sqlite3_stmt *stmt;
73
    sprintf(g_sql_buf[2], "create table [%s].[%s %s] (level int, label text, "
74
            "primary key(level), unique(label));", iname, factor_type, colname);
75
    int res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, 0);
3282 mrmanese 76
    if (res == SQLITE_OK) sqlite3_step(stmt);
3255 mrmanese 77
    sqlite3_finalize(stmt);
78
    return res; /* error on dup name? */
79
}
80
 
81
/* copy a factor|ordered table from a sdf(db) to another sdf(db) */
82
static int _copy_factor_levels2(const char *factor_type, const char *iname_src,
83
        const char *colname_src, const char *iname_dst, const char *colname_dst) {
84
    sqlite3_stmt *stmt;
85
    int res;
86
    res = _create_factor_table2(iname_dst, factor_type, colname_dst);
87
    if (res == SQLITE_OK) {
3281 mrmanese 88
        sprintf(g_sql_buf[2], "insert into [%s].[%s %s] select * from [%s].[%s %s]",
3255 mrmanese 89
                iname_src, factor_type, colname_src, iname_dst, factor_type,
90
                colname_dst);
91
        res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, 0);
3282 mrmanese 92
        if (res == SQLITE_OK) sqlite3_step(stmt);
3255 mrmanese 93
        sqlite3_finalize(stmt);
3281 mrmanese 94
    }
3255 mrmanese 95
    return res; /* error on dup name? */
96
}
97
 
98
 
99
/* assumes stmt has col_cnt + 1 columns, col 0 is [row name]. returned SEXP is 
100
 * not UNPROTECT-ed, user will have to do that. will create the names &
101
 * attach factor infos */
3281 mrmanese 102
static SEXP _setup_df_sexp1(sqlite3_stmt *stmt, const char *iname, 
103
        int col_cnt, int row_cnt, int *dup_indices) {
104
    SEXP ret, names, value, class = R_NilValue;
105
    int i, type;
106
    const char *colname, *coltype;
3255 mrmanese 107
 
108
    PROTECT(ret = NEW_LIST(col_cnt));
109
 
3281 mrmanese 110
    /* set up names. */
111
    PROTECT(names = NEW_CHARACTER(col_cnt));
3255 mrmanese 112
    for (i = 0; i < col_cnt; i++) {
3281 mrmanese 113
        colname = sqlite3_column_name(stmt, i+1);  /* +1 bec [row name is 0] */
114
        coltype = sqlite3_column_decltype(stmt, i+1);
115
 
3255 mrmanese 116
        if (dup_indices[i] == 0) {
117
            strcpy(g_sql_buf[1], colname);
118
        } else {
119
            sprintf(g_sql_buf[1], "%s.%d", colname, dup_indices[i]);
120
        }
121
 
3281 mrmanese 122
        SET_STRING_ELT(names, i, mkChar(g_sql_buf[1]));
123
 
124
        if (strcmp(coltype, "text") == 0) {
125
            PROTECT(value = NEW_CHARACTER(row_cnt));
126
        } else if (strcmp(coltype, "double") == 0) {
127
            PROTECT(value = NEW_NUMERIC(row_cnt));
128
        } else if (strcmp(coltype, "bit") == 0) {
129
            PROTECT(value = NEW_LOGICAL(row_cnt));
130
        } else if (strcmp(coltype, "integer") == 0 || 
131
                   strcmp(coltype, "int") == 0) {
132
            PROTECT(value = NEW_INTEGER(row_cnt));
133
            type = _get_factor_levels1(iname, colname, value);
134
            if (type == VAR_FACTOR) {
135
                PROTECT(class = mkString("factor"));
136
                SET_CLASS(value, class);
137
                UNPROTECT(1);
138
            } else if (type == VAR_ORDERED) {
139
                PROTECT(class = NEW_CHARACTER(2));
140
                SET_STRING_ELT(class, 0, mkChar("ordered"));
141
                SET_STRING_ELT(class, 1, mkChar("factor"));
142
                SET_CLASS(value, class);
143
                UNPROTECT(1);
144
            }
145
        } else {
146
            Rprintf("Error: not supported type %s for %s\n", coltype, colname);
147
            UNPROTECT(2); /* unprotect ret, names */
148
            return R_NilValue;
149
        }
150
 
151
        SET_VECTOR_ELT(ret, i, value);
152
        UNPROTECT(1); /* unprotect value */
3255 mrmanese 153
 
154
    }
3281 mrmanese 155
    SET_NAMES(ret, names);
156
    UNPROTECT(1); /* unprotect names only */
3255 mrmanese 157
    return ret;
158
}
159
 
3281 mrmanese 160
/* expected that 1st col of stmt is [row name], so we start with index 1 */
161
static int _add_row_to_df(SEXP df, sqlite3_stmt *stmt, int row, int ncols) {
162
    SEXP vec;
3282 mrmanese 163
    int type = -1, is_null, i;
3281 mrmanese 164
    for (i = 1; i <= ncols; i++) {
165
        vec = VECTOR_ELT(df, i-1);
166
        type = TYPEOF(vec);
167
 
168
        is_null = (sqlite3_column_type(stmt, row) == SQLITE_NULL);
169
 
170
        if (type == CHARSXP) {
171
            SET_STRING_ELT(vec, row, mkChar(sqlite3_column_text(stmt, i)));
172
        } else if (type == INTSXP) {
173
            INTEGER(vec)[row] = sqlite3_column_int(stmt, i);
174
        } else if (type == REALSXP) {
175
            REAL(vec)[row] = sqlite3_column_double(stmt, i);
176
        } else if (type == LGLSXP) {
177
            LOGICAL(vec)[row] = sqlite3_column_int(stmt, i);
178
        }
179
    }
3282 mrmanese 180
    return type;
3281 mrmanese 181
}
182
 
183
static void _set_rownames2(SEXP df) {
184
    SEXP value = VECTOR_ELT(df, 0);
185
    int len = LENGTH(value), i;
186
    PROTECT(value = NEW_CHARACTER(len));
187
    for (i = 0; i < len; i++) {
188
        sprintf(g_sql_buf[2], "%d", i+1);
189
        SET_STRING_ELT(value, i, mkChar(g_sql_buf[2]));
190
    }
191
 
192
    SET_ROWNAMES(df, value);
193
    UNPROTECT(1);
194
}
195
 
196
 
3255 mrmanese 197
/****************************************************************************
198
 * SDF FUNCTIONS
199
 ****************************************************************************/
200
 
201
SEXP sdf_create_sdf(SEXP df, SEXP name) {
202
    SEXP ret;
3281 mrmanese 203
    char *rname, *iname; 
3255 mrmanese 204
    int file_idx = 0, namelen, res, i, j;
205
 
206
    namelen = _check_sdf_name(name, &rname, &iname, &file_idx);
207
    if (!namelen) return R_NilValue;
208
 
209
 
210
    /* at this point, iname will contain #{iname}.db */
211
    _find_free_filename(rname, &iname, &namelen, &file_idx);
3251 mrmanese 212
 
213
    /* found a free number */
214
    if (file_idx < 10000) {
3252 mrmanese 215
        /* create a sdf db file by running "attach" statement to non-existent
216
         * db file
217
         */
3255 mrmanese 218
        int sql_len, sql_len2;
3252 mrmanese 219
        sqlite3_stmt *stmt;
220
 
221
        iname[namelen] = 0;  /* remove ".db" */
222
        sql_len = sprintf(g_sql_buf[0], "attach '%s.db' as %s", iname, iname);
223
 
224
        res = _sqlite_exec(g_sql_buf[0]);
225
        if (_sqlite_error(res)) return R_NilValue; /* duplicate dbname */
226
 
227
 
228
        /* 
229
         * create tables for the sdf db
230
         */
3255 mrmanese 231
 
232
        /* create sdf_attributes table */
233
        res = _create_sdf_attribute2(iname);
234
        if (_sqlite_error(res)) return R_NilValue;
235
 
236
        /* create sdf_data table */
3252 mrmanese 237
        SEXP names = GET_NAMES(df), variable, levels;
238
        int ncols = GET_LENGTH(names), type, *types;
239
        char *col_name, *class, *factor;
240
 
241
        /* TODO: put constraints on table after inserting everything? */
242
 
243
 
244
        /* 
245
         * create the create table and insert sql scripts by looping through
246
         * the columns of df
247
         */
248
        types = (int *)R_alloc(ncols, sizeof(int));
249
        sql_len = sprintf(g_sql_buf[0], "create table [%s].sdf_data ([row name] text", iname);
250
        sql_len2 = sprintf(g_sql_buf[1], "insert into [%s].sdf_data values(?", iname);
251
 
252
        for (i = 0; i < ncols; i++) {
253
            col_name = CHAR(STRING_ELT(names, i));
254
 
255
            /* add column definition to the create table sql */
256
            _expand_buf(0, sql_len+strlen(col_name)+10);
257
 
258
            variable = _getListElement(df, col_name);
259
            class = CHAR(STRING_ELT(GET_CLASS(variable), 0));
260
            type = TYPEOF(variable);
261
            types[i] = type;
262
 
263
            sql_len += sprintf(g_sql_buf[0]+sql_len, ", [%s] %s", col_name, 
264
                    _get_column_type(class, type));
265
 
266
            /* add handler to insert table sql */
267
            _expand_buf(1, sql_len+5);
268
            strcpy(g_sql_buf[1]+sql_len2, ",?");
269
            sql_len2 += 2; 
270
 
271
            /* create separate table for factors decode */
272
            if (strcmp(class, "factor") == 0 || strcmp(class, "ordered") == 0){
3255 mrmanese 273
                if (_create_factor_table2(iname, class, col_name)) 
274
                    return R_NilValue; /* dup tbl name? */
3252 mrmanese 275
 
276
                levels = GET_LEVELS(variable);
3255 mrmanese 277
                sprintf(g_sql_buf[2], "insert into [%s].[%s %s] values(?, ?);",
278
                        iname, class, col_name);
279
                res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, NULL);
3252 mrmanese 280
                if (_sqlite_error(res)) return R_NilValue; /* dup tbl name? */
281
 
282
                for (j = 0; j < GET_LENGTH(levels); j++) {
283
                    sqlite3_reset(stmt);
284
                    factor = CHAR(STRING_ELT(levels, j));
285
                    sqlite3_bind_int(stmt, 1, j+1);
286
                    sqlite3_bind_text(stmt, 2, factor, strlen(factor), SQLITE_STATIC);
287
                    sqlite3_step(stmt);
288
                }
289
                sqlite3_finalize(stmt);
290
            }
291
        }
292
 
293
        _expand_buf(0,sql_len+35);
294
        /* sql_len += sprintf(g_sql_buf[0]+sql_len, ", primary key([row name]));");*/
295
        sql_len += sprintf(g_sql_buf[0]+sql_len, ");");
296
        res = _sqlite_exec(g_sql_buf[0]);
297
        if (_sqlite_error(res)) return R_NilValue; /* why? */
298
 
299
        /*
300
         * add the data in df to the sdf
301
         */
302
        SEXP rownames = getAttrib(df, R_RowNamesSymbol);
303
        int nrows = GET_LENGTH(rownames);
304
        char *row_name;
305
 
3255 mrmanese 306
        sprintf(g_sql_buf[1]+sql_len2, ")");
307
        res = sqlite3_prepare(g_workspace, g_sql_buf[1], -1, &stmt, NULL);
3252 mrmanese 308
 
309
        for (i = 0; i < nrows; i++) {
310
            row_name = CHAR(STRING_ELT(rownames, i));
311
            sqlite3_reset(stmt);
312
 
313
            if (*row_name)
314
                sqlite3_bind_text(stmt, 1, row_name, strlen(row_name), SQLITE_STATIC);
315
            else
316
                sqlite3_bind_int(stmt, 1, i);
317
 
318
            for (j = 0; j < ncols; j++) {
319
                variable = VECTOR_ELT(df, j);
320
                switch(types[j]) {
321
                    case INTSXP : 
322
                        sqlite3_bind_int(stmt, j+2, INTEGER(variable)[i]);
323
                        break;
324
                    case REALSXP:
325
                        sqlite3_bind_double(stmt, j+2, REAL(variable)[i]);
326
                        break;
327
                    case CHARSXP:
328
                        col_name = CHAR(STRING_ELT(variable,i));
329
                        sqlite3_bind_text(stmt, j+2, col_name, strlen(col_name), SQLITE_STATIC);
330
                }
331
                /* TODO: handle NA's & NULL's */
332
            }
333
 
334
            res = sqlite3_step(stmt);
335
            if (res != SQLITE_DONE) { 
336
                sqlite3_finalize(stmt);
337
                Rprintf("ERROR: %s\n", sqlite3_errmsg(g_workspace));
338
                return R_NilValue; /* why? */
339
            }
340
        }
341
 
342
        sqlite3_finalize(stmt);
343
 
344
        /*
345
         * add the new sdf to the workspace
346
         */
3282 mrmanese 347
        iname[namelen] = '.';
3255 mrmanese 348
        strcpy(g_sql_buf[0], iname);
3282 mrmanese 349
        iname[namelen] = 0;
3255 mrmanese 350
        res = _add_sdf1(iname, g_sql_buf[0]);
3252 mrmanese 351
        if (_sqlite_error(res)) return R_NilValue; /* why? */
352
 
353
        /*
354
         * create a new object representing the sdf
355
         */
356
        ret = _create_sdf_sexp(iname);
357
 
358
    } else {
359
        Rprintf("ERROR: cannot find a free internal name for %s", rname);
360
        ret = R_NilValue;
3251 mrmanese 361
    }
362
 
3252 mrmanese 363
    return ret;
364
}
365
 
366
SEXP sdf_get_names(SEXP sdf) {
3255 mrmanese 367
    char *iname = SDF_INAME(sdf);
3252 mrmanese 368
    int len = sprintf(g_sql_buf[0], "select * from [%s].sdf_data;", iname);
369
 
370
    sqlite3_stmt *stmt;
371
    int res;
372
 
373
    res = sqlite3_prepare(g_workspace, g_sql_buf[0], len, &stmt, NULL);
374
    if (_sqlite_error(res)) return R_NilValue;
375
 
376
    SEXP ret;
377
 
378
    len = sqlite3_column_count(stmt)-1;
379
    PROTECT(ret = NEW_CHARACTER(len));
380
 
381
    for (int i = 0; i < len; i++) {
382
        SET_STRING_ELT(ret, i, mkChar(sqlite3_column_name(stmt, i+1)));
383
    }
384
 
385
    sqlite3_finalize(stmt);
3251 mrmanese 386
    UNPROTECT(1);
387
    return ret;
388
}
389
 
3252 mrmanese 390
SEXP sdf_get_length(SEXP sdf) {
391
    char *iname = CHAR(STRING_ELT(_getListElement(sdf, "iname"),0));
392
    int len = sprintf(g_sql_buf[0], "select * from [%s].sdf_data;", iname);
3251 mrmanese 393
 
3252 mrmanese 394
    sqlite3_stmt *stmt;
395
    int res;
396
 
397
    res = sqlite3_prepare(g_workspace, g_sql_buf[0], len, &stmt, NULL);
398
    if (_sqlite_error(res)) return R_NilValue;
399
 
400
    SEXP ret;
401
 
402
    len = sqlite3_column_count(stmt)-1;
403
    PROTECT(ret = NEW_INTEGER(1));
404
    INTEGER(ret)[0] = len;
405
 
406
    sqlite3_finalize(stmt);
407
    UNPROTECT(1);
408
    return ret;
409
}
410
 
3255 mrmanese 411
/* get row count */
412
SEXP sdf_get_row_count(SEXP sdf) {
3252 mrmanese 413
    char *iname = CHAR(STRING_ELT(_getListElement(sdf, "iname"),0));
414
    char **out;
415
    int res, ncol, nrow;
416
    SEXP ret;
417
 
418
    sprintf(g_sql_buf[0], "select count(*) from [%s].sdf_data;", iname);
419
    res = sqlite3_get_table(g_workspace, g_sql_buf[0], &out, &nrow, &ncol, NULL);
420
    if (_sqlite_error(res)) return R_NilValue;
421
 
422
 
423
    if (nrow != 1) ret = R_NilValue;
424
    else {
425
        PROTECT(ret = NEW_INTEGER(1));
426
        INTEGER(ret)[0] = atoi(out[1]);
427
        UNPROTECT(1);
428
    }
429
 
430
    sqlite3_free_table(out);
431
    return ret;
432
}
433
 
434
 
3255 mrmanese 435
SEXP sdf_import_table(SEXP _filename, SEXP _name, SEXP _sep, SEXP _quote, 
436
        SEXP _rownames, SEXP _colnames) {
437
    char *filename = CHAR_ELT(_filename, 0);
438
    FILE *f = fopen(filename, "r");
3252 mrmanese 439
 
3255 mrmanese 440
    if (f == NULL) {
441
        Rprintf("Error: File %s does not exist.", filename);
442
        return R_NilValue;
443
    }
3252 mrmanese 444
 
3282 mrmanese 445
    /*char *sep = CHAR_ELT(_sep, 0), *quote = CHAR_ELT(_quote,0);
446
    char *name = CHAR_ELT(_name, 0);*/
3252 mrmanese 447
 
3255 mrmanese 448
    /* create the table */
449
    /* insert the stuffs */
450
    /* register to workspace */
451
 
452
    return R_NilValue;
453
}
454
 
455
SEXP sdf_get_index(SEXP sdf, SEXP row, SEXP col) {
3282 mrmanese 456
    SEXP ret = R_NilValue;
3255 mrmanese 457
    char *iname = SDF_INAME(sdf);
3282 mrmanese 458
    sqlite3_stmt *stmt;
3281 mrmanese 459
    int buflen = 0, idxlen, col_cnt, row_cnt, index;
3255 mrmanese 460
    int i, j,res;
461
    int *col_indices, col_index_len, *dup_indices;
3282 mrmanese 462
    int row_index_len = 0;
3255 mrmanese 463
 
3281 mrmanese 464
    sprintf(g_sql_buf[0], "select * from [%s].sdf_data ", iname);
3255 mrmanese 465
    res = sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, 0);
466
    if (_sqlite_error(res)) return R_NilValue;
467
 
468
    buflen = sprintf(g_sql_buf[0], "select [row name]");
469
    idxlen = LENGTH(col);
470
    col_cnt = sqlite3_column_count(stmt) - 1;
471
 
472
    /*
473
     * PROCESS COLUMN INDEX
474
     */
3281 mrmanese 475
    if (col == R_NilValue) {
3255 mrmanese 476
        for (i = 1; i < col_cnt+1; i++) {
3281 mrmanese 477
            buflen += sprintf(g_sql_buf[0]+buflen, ",[%s]", 
3255 mrmanese 478
                    sqlite3_column_name(stmt, i)); 
479
        }
3281 mrmanese 480
        _expand_buf(0, buflen+20+strlen(iname));
481
        buflen += sprintf(g_sql_buf[0]+buflen, " from [%s].sdf_data", iname);
482
        col_index_len = col_cnt;
483
        col_indices = (int *)R_alloc(idxlen, sizeof(int));
484
        dup_indices = (int *)R_alloc(idxlen, sizeof(int));
485
        for (i = 0; i < col_cnt; i++) { col_indices[i] = i; dup_indices[i] = 0; }
3255 mrmanese 486
    } else if (col == R_NilValue || idxlen < 1) {
487
        sqlite3_finalize(stmt);
488
        return R_NilValue;
489
    } else if (IS_NUMERIC(col)) {
490
        col_indices = (int *)R_alloc(idxlen, sizeof(int));
491
        dup_indices = (int *)R_alloc(idxlen, sizeof(int));
492
        col_index_len = 0;
493
 
494
        for (i = 0; i < idxlen; i++) {
495
            /* no need to correct for 0 base because col 0 is [row name] */
496
            index = ((int) REAL(col)[i]); 
497
            if (index > col_cnt) {
498
                sqlite3_finalize(stmt);
499
                Rprintf("Error: undefined columns selected\n");
500
                return R_NilValue;
501
            } else if (index > 0) {
3281 mrmanese 502
                buflen += sprintf(g_sql_buf[0]+buflen, ",[%s]", 
3255 mrmanese 503
                        sqlite3_column_name(stmt,index));
504
                dup_indices[col_index_len] = 0;
505
                for (j = 0; j < col_index_len; j++) {
506
                    if (col_indices[j] == index) dup_indices[col_index_len]++;
507
                }
508
                col_indices[col_index_len++] = index;
509
            } else if (index < 0) {
510
                sqlite3_finalize(stmt);
511
                Rprintf("Error: negative indices not supported.\n");
512
                return R_NilValue;
513
            }
514
        }
515
 
516
        if (col_index_len == 0) {
517
            sqlite3_finalize(stmt);
518
            Rprintf("Error: no indices detected??\n");
519
            return R_NilValue;
3281 mrmanese 520
        } else { 
521
            _expand_buf(0, buflen+20+strlen(iname));
522
            buflen += sprintf(g_sql_buf[0]+buflen, " from [%s].sdf_data", iname);
3255 mrmanese 523
        }
524
    } else if (IS_INTEGER(col)) {
525
        /* identical logic with IS_NUMERIC, except that we don't have to cast
526
         * stuffs from SEXP col. the alternative is doing if idxlen times. */
527
        col_indices = (int *)R_alloc(idxlen, sizeof(int));
528
        dup_indices = (int *)R_alloc(idxlen, sizeof(int));
529
        col_index_len = 0;
530
 
531
        for (i = 0; i < idxlen; i++) {
532
            /* no need to correct for 0 base because col 0 is [row name] */
533
            index = INTEGER(col)[i];
534
            if (index > col_cnt) {
535
                sqlite3_finalize(stmt);
536
                Rprintf("Error: undefined columns selected\n");
537
                return R_NilValue;
538
            } else if (index > 0) {
3281 mrmanese 539
                buflen += sprintf(g_sql_buf[0]+buflen, ",[%s]", 
3255 mrmanese 540
                        sqlite3_column_name(stmt,index));
541
                dup_indices[col_index_len] = 0;
542
                for (j = 0; j < col_index_len; j++) {
543
                    if (col_indices[j] == index) dup_indices[col_index_len]++;
544
                }
545
                col_indices[col_index_len++] = index;
546
            } else if (index < 0) {
547
                sqlite3_finalize(stmt);
548
                Rprintf("Error: negative indices not supported.\n");
549
                return R_NilValue;
550
            }
551
        }
552
 
553
        if (col_index_len == 0) {
554
            sqlite3_finalize(stmt);
555
            Rprintf("Error: no indices detected??\n");
556
            return R_NilValue;
3281 mrmanese 557
        } else { 
558
            _expand_buf(0, buflen+20+strlen(iname));
559
            buflen += sprintf(g_sql_buf[0]+buflen, " from [%s].sdf_data", iname);
3255 mrmanese 560
        }
561
    } else if (IS_LOGICAL(col)) {
562
        /* recycling stuff, so max column output is the # of cols in the df */
563
        col_indices = (int *)R_alloc(col_cnt, sizeof(int));
564
        dup_indices = (int *)R_alloc(col_cnt, sizeof(int));
565
        col_index_len = 0;
566
        for (i = 0; i < col_cnt; i++) {
567
            if (LOGICAL(col)[i%idxlen]) {
3281 mrmanese 568
                buflen += sprintf(g_sql_buf[0]+buflen, ",[%s]", 
3255 mrmanese 569
                        sqlite3_column_name(stmt,i+1));
570
                dup_indices[col_index_len] = 0;
571
                col_indices[col_index_len++] = i;
572
            }
573
        }
574
 
575
        if (col_index_len == 0) {
576
            sqlite3_finalize(stmt);
577
            Rprintf("Warning: no column selected.\n");
578
            return R_NilValue;
3281 mrmanese 579
        } else { 
580
            _expand_buf(0, buflen+20+strlen(iname));
581
            buflen += sprintf(g_sql_buf[0]+buflen, " from [%s].sdf_data", iname);
3255 mrmanese 582
        }
583
    } else {
584
        sqlite3_finalize(stmt);
585
        Rprintf("Error: don't know how to handle column index.\n");
586
        return R_NilValue;
587
    }
588
 
589
    /* 
590
     * PROCESS ROW INDEX
591
     */
592
    idxlen = LENGTH(row);
3281 mrmanese 593
    if (row == R_NilValue) {
594
        if (col_index_len == 1) {
595
            ret = sdf_get_variable(sdf, mkString(sqlite3_column_name(stmt,col_indices[0])));
596
            sqlite3_finalize(stmt);
597
            return ret;
598
        } if (col_index_len > 1) {
3255 mrmanese 599
            /* create a new SDF, logic similar to sdf_create_sdf */
600
 
3281 mrmanese 601
            /* we have to close the current statement so we can do
602
             * edits in the db */
603
            /* sqlite3_finalize(stmt); */
604
 
3255 mrmanese 605
            /* find a new name. data<n> ? */
606
            char *iname2, *rname2;
3281 mrmanese 607
            const char *colname;
3282 mrmanese 608
            int namelen, file_idx = 0, sql_len, sql_len2;
3255 mrmanese 609
            namelen = _check_sdf_name(R_NilValue, &rname2, &iname2, &file_idx);
610
 
3281 mrmanese 611
            if (!namelen) return R_NilValue; 
3255 mrmanese 612
 
613
            _find_free_filename(rname2, &iname2, &namelen, &file_idx);
614
 
615
            if (file_idx >= 10000) { 
616
                Rprintf("Error: cannot find free SDF name.\n");
617
                return R_NilValue;
618
            }
619
 
3281 mrmanese 620
 
3255 mrmanese 621
            /* create new db by attaching a non-existent file */
3281 mrmanese 622
            iname2[namelen] = 0; /* remove ".db" */
623
            sprintf(g_sql_buf[1], "attach '%s.db' as %s", iname2, iname2);
3255 mrmanese 624
            res = _sqlite_exec(g_sql_buf[1]);
3281 mrmanese 625
            if (_sqlite_error(res)) return R_NilValue; 
3255 mrmanese 626
 
627
            /* create attributes table */
3281 mrmanese 628
            res = _create_sdf_attribute2(iname2);
629
            if (_sqlite_error(res)) return R_NilValue; 
3255 mrmanese 630
 
631
            /* create sdf_data table */
3281 mrmanese 632
            sql_len = sprintf(g_sql_buf[1], "create table [%s].sdf_data ([row name] text", iname2);
633
            sql_len2 = 0;
3255 mrmanese 634
 
635
            for (i = 0; i < col_index_len; i++) {
636
                colname = sqlite3_column_name(stmt, col_indices[i]);
637
                if (dup_indices[i] == 0) {
3281 mrmanese 638
                    sql_len += sprintf(g_sql_buf[1]+sql_len, ", [%s] %s", colname,
3255 mrmanese 639
                            sqlite3_column_decltype(stmt, col_indices[i]));
640
                } else {
641
                    /* un-duplicate col names by appending num, just like R */
3281 mrmanese 642
                    sql_len += sprintf(g_sql_buf[1]+sql_len, ", [%s.%d] %s", colname,
3255 mrmanese 643
                            dup_indices[i], 
644
                            sqlite3_column_decltype(stmt, col_indices[i]));
645
                }
646
 
647
                /* deal with possibly factor columns */
648
                if (_is_factor2(iname, "factor", colname)) {
649
                    /* found a factor column */
3281 mrmanese 650
 
3255 mrmanese 651
                    if (dup_indices[i] == 0)  {
652
                        _copy_factor_levels2("factor", iname, colname, iname2, colname);
653
                    } else {
654
                        sprintf(g_sql_buf[3], "%s.%d", colname, dup_indices[i]);
655
                        _copy_factor_levels2("factor", iname, colname, iname2, 
656
                                g_sql_buf[3]);
657
                    }
658
                }
659
 
660
                /* and deal with ordered factors too... life is hard, then you die */
661
                if (_is_factor2(iname, "ordered", colname)) {
3281 mrmanese 662
 
3255 mrmanese 663
                    if (dup_indices[i] == 0)  {
664
                        _copy_factor_levels2("ordered", iname, colname, iname2, 
665
                                colname);
666
                    } else {
667
                        sprintf(g_sql_buf[3], "%s.%d", colname, dup_indices[i]);
668
                        _copy_factor_levels2("ordered", iname, colname, iname2, 
669
                                g_sql_buf[3]);
670
                    }
671
                }
672
 
673
            }
674
 
675
            /* don't need it anymore */
676
            sqlite3_finalize(stmt);
677
 
678
            /* no table index created, that's for v2 I hope*/
679
            sql_len += sprintf(g_sql_buf[1]+sql_len, ");");
680
            res = _sqlite_exec(g_sql_buf[1]);
3281 mrmanese 681
            if (_sqlite_error(res)) { Rprintf("here? %s\n", g_sql_buf[1]); return R_NilValue; }
3255 mrmanese 682
 
683
            /* insert data (with row names). buf[0] contains a select */
684
            sprintf(g_sql_buf[1], "insert into [%s].sdf_data %s", iname2,
685
                    g_sql_buf[0]);
686
            res = _sqlite_exec(g_sql_buf[1]);
687
            if (_sqlite_error(res)) return R_NilValue;
688
 
689
            /* add new sdf to workspace */
690
            sprintf(g_sql_buf[0], "%s.db", iname2);
3281 mrmanese 691
            res = _add_sdf1(g_sql_buf[0], iname2);
3255 mrmanese 692
            if (_sqlite_error(res)) return R_NilValue;
693
 
694
            /* create SEXP for the SDF */
695
            ret = _create_sdf_sexp(iname2);
3281 mrmanese 696
            return ret;
3255 mrmanese 697
        } else { sqlite3_finalize(stmt); return R_NilValue; }
698
    } else if (row == R_NilValue || idxlen < 1) {
699
        sqlite3_finalize(stmt);
700
        return R_NilValue;
701
    } else if (IS_NUMERIC(row)) {
702
        sqlite3_finalize(stmt);
703
 
3281 mrmanese 704
        sprintf(g_sql_buf[1], "[%s].sdf_data", iname);
705
        row_cnt = _get_row_count2(g_sql_buf[1]);
706
 
3255 mrmanese 707
        /* append " limit ?,1" to the formed select statement */
708
        _expand_buf(0, buflen+10);
3281 mrmanese 709
        buflen += sprintf(g_sql_buf[0]+buflen, " limit ?,1");
710
        /*Rprintf("sql [%d]: %s\n", buflen, g_sql_buf[0]); */
3255 mrmanese 711
 
3281 mrmanese 712
        index = ((int) REAL(row)[0]) - 1;
3255 mrmanese 713
        if (idxlen < 0 && idxlen == 1) return R_NilValue;
714
 
715
        res = sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, 0);
716
        if (_sqlite_error(res)) return R_NilValue;
717
 
718
        sqlite3_bind_int(stmt, 1, index);
719
        res = sqlite3_step(stmt);
720
 
721
        /* create data frame */
3281 mrmanese 722
        ret = _setup_df_sexp1(stmt, iname, col_index_len, idxlen, dup_indices);
723
        if (ret == R_NilValue) { sqlite3_finalize(stmt); return R_NilValue; }
3255 mrmanese 724
 
3281 mrmanese 725
        /* put data in it */
726
        if (index >= 0 && index < row_cnt) {
727
            _add_row_to_df(ret, stmt, row_index_len++, col_index_len);
728
        }
3255 mrmanese 729
 
3281 mrmanese 730
        for (i = 1; i < idxlen; i++) {
731
            sqlite3_reset(stmt);
732
            index = ((int) REAL(row)[i]) - 1;
733
            if (index >= 0 && index < row_cnt) {
734
                sqlite3_bind_int(stmt, 1, index);
735
                res = sqlite3_step(stmt);
736
                _add_row_to_df(ret, stmt, row_index_len++, col_index_len);
737
            }
738
        }
739
        sqlite3_finalize(stmt);
740
 
741
        /* shrink vectors */
742
        if (row_index_len < idxlen) {
743
            for (i = 0; i < col_index_len; i++) {
744
                SET_VECTOR_ELT(ret, i, 
745
                        _shrink_vector(VECTOR_ELT(ret, i), row_index_len));
746
            }
747
        }
748
 
749
        UNPROTECT(1); /* for the ret from _setup_df_sexp1 */
750
    } else if (IS_INTEGER(row)) {
751
        /* same stuff as with IS_INTEGER, except for setting of var index*/
752
        sqlite3_finalize(stmt);
753
 
754
        sprintf(g_sql_buf[1], "[%s].sdf_data", iname);
755
        row_cnt = _get_row_count2(g_sql_buf[1]);
756
 
757
        /* append " limit ?,1" to the formed select statement */
758
        _expand_buf(0, buflen+10);
759
        buflen += sprintf(g_sql_buf[0]+buflen, " limit ?,1");
760
 
761
        index = INTEGER(row)[0] - 1;
762
        if (idxlen < 0 && idxlen == 1) return R_NilValue;
763
 
764
        res = sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, 0);
765
        if (_sqlite_error(res)) return R_NilValue;
766
 
767
        sqlite3_bind_int(stmt, 1, index);
768
        res = sqlite3_step(stmt);
769
 
770
        /* create data frame */
771
        ret = _setup_df_sexp1(stmt, iname, col_index_len, idxlen, dup_indices);
772
        if (ret == R_NilValue) { sqlite3_finalize(stmt); return R_NilValue; }
773
 
3255 mrmanese 774
        /* put data in it */
3281 mrmanese 775
        if (index >= 0 && index < row_cnt) {
776
            _add_row_to_df(ret, stmt, row_index_len++, col_index_len);
777
        }
778
 
779
        for (i = 1; i < idxlen; i++) {
780
            sqlite3_reset(stmt);
781
            index = INTEGER(row)[i] - 1;
782
            if (index >= 0 && index < row_cnt) {
783
                sqlite3_bind_int(stmt, 1, index);
784
                res = sqlite3_step(stmt); 
785
                _add_row_to_df(ret, stmt, row_index_len++, col_index_len);
786
            }
787
        }
788
        sqlite3_finalize(stmt);
789
 
790
        /* shrink vectors */
791
        if (row_index_len < idxlen) {
792
            for (i = 0; i < col_index_len; i++) {
793
                SET_VECTOR_ELT(ret, i, 
794
                        _shrink_vector(VECTOR_ELT(ret, i), row_index_len));
795
            }
796
        }
797
        UNPROTECT(1); /* for the ret from _setup_df_sexp1 */
3255 mrmanese 798
    } else if (IS_LOGICAL(row)) {
799
        /* */
3281 mrmanese 800
        sqlite3_finalize(stmt);
801
        int est_row_cnt = 0;
802
 
803
        sprintf(g_sql_buf[1], "[%s].sdf_data", iname);
804
        row_cnt = _get_row_count2(g_sql_buf[1]);
805
 
806
        /* append " limit ?,1" to the formed select statement */
807
        _expand_buf(0, buflen+10);
808
        buflen += sprintf(g_sql_buf[0]+buflen, " limit ?,1");
809
 
810
        /* find if there is any TRUE element in the vector */
3282 mrmanese 811
        for (i = 0; i < idxlen && i < row_cnt; i++) {
3281 mrmanese 812
            if (LOGICAL(row)[i]) break;
813
        }
814
 
3282 mrmanese 815
        if (i < idxlen && i < row_cnt) {
3281 mrmanese 816
            est_row_cnt = (idxlen-i) * (row_cnt/idxlen);
817
            if (row_cnt%idxlen > i) est_row_cnt += (row_cnt%idxlen - i);
818
 
819
            res = sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, 0);
820
            if (_sqlite_error(res)) return R_NilValue;
821
 
822
            sqlite3_bind_int(stmt, 1, i);
823
            sqlite3_step(stmt);
824
            ret = _setup_df_sexp1(stmt, iname, col_index_len, est_row_cnt, dup_indices);
825
            _add_row_to_df(ret, stmt, row_index_len++, col_index_len);
826
 
827
            for (i++ ; i < row_cnt; i++) {
828
                if (LOGICAL(row)[i%idxlen]) {
829
                    sqlite3_reset(stmt);
830
                    sqlite3_bind_int(stmt, 1, i);
831
                    sqlite3_step(stmt);
832
                    _add_row_to_df(ret, stmt, row_index_len++, col_index_len);
833
                }
834
            }
835
        }
836
 
837
        sqlite3_finalize(stmt);
838
 
839
        /* shrink vectors */
840
        if (est_row_cnt > 0 && row_index_len < est_row_cnt) {
841
            for (i = 0; i < col_index_len; i++) {
842
                SET_VECTOR_ELT(ret, i, 
843
                        _shrink_vector(VECTOR_ELT(ret, i), row_index_len));
844
            }
845
        }
846
 
847
        UNPROTECT(1); /* for the ret from _setup_df_sexp1 */
3255 mrmanese 848
    }
849
 
3281 mrmanese 850
    if (ret != R_NilValue && col_index_len > 1) {
851
        SEXP class = mkString("data.frame");
852
        SET_CLASS(ret, class);
853
        _set_rownames2(ret);
854
    } else if (ret != R_NilValue && col_index_len == 1) {
855
        ret = VECTOR_ELT(ret, 0);
856
    }
3255 mrmanese 857
 
858
    return ret;
859
}
860
 
3281 mrmanese 861
 
3251 mrmanese 862
SEXP sopen(SEXP name) {
863
    char *filename;
864
 
865
    if (IS_CHARACTER(name)) {
866
        filename = CHAR(STRING_ELT(name,0));
867
        Rprintf("%s\n", filename);
868
    }
869
    /* sqlite3 *db;
870
    int res = sqlite3_open(filename, &db); */
871
    SEXP ret;
872
    PROTECT(ret = NEW_LOGICAL(1));
873
    LOGICAL(ret)[0] = IS_CHARACTER(name);
874
    /* sqlite3_close(db); */ 
875
    UNPROTECT(1);
876
    return ret;
877
}