The R Project SVN R-packages

Rev

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