The R Project SVN R-packages

Rev

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

Rev Author Line No. Line
3251 mrmanese 1
#include <string.h>
3252 mrmanese 2
#include "sqlite_dataframe.h"
3251 mrmanese 3
 
3255 mrmanese 4
/****************************************************************************
5
 * UTILITY FUNCTIONS
6
 ****************************************************************************/
3251 mrmanese 7
 
3684 mrmanese 8
/* if user supplied a name (1st arg), return that name. otherwise, use the 
9
 * default "data". rname is R name, iname is internal name */
3307 mrmanese 10
static int _check_sdf_name(SEXP name, char **rname, char **iname, int *file_idx) {
3255 mrmanese 11
    int namelen = 0;
12
 
3252 mrmanese 13
    /* check if arg name is supplied */
3426 mrmanese 14
    if (name == R_NilValue) {
15
        *rname = "data";
16
        namelen = 5;
3684 mrmanese 17
        *iname = (char*)R_alloc(13, sizeof(char)); /* .SQLiteDF/data10000.db\0 */
3426 mrmanese 18
        *file_idx = 1;
19
        sprintf(*iname, "%s%d.db", *rname, *file_idx);
20
    } else if (IS_CHARACTER(name)) {
3255 mrmanese 21
        *rname = CHAR_ELT(name,0);
22
        if (!_is_r_sym(*rname)) { 
3684 mrmanese 23
            error("supplied name \"%s\"is not a valid R symbol.", *rname); 
3255 mrmanese 24
        }
25
        namelen = strlen(*rname);
3684 mrmanese 26
        *iname = (char*)R_alloc(namelen + 9, sizeof(char)); /* .SQLiteDF/<name>10000.db\0 */
3255 mrmanese 27
        sprintf(*iname, "%s.db", *rname);
3251 mrmanese 28
    } else {
3255 mrmanese 29
        Rprintf("Error: the supplied value for arg name is not a string.\n");
3251 mrmanese 30
    }
3255 mrmanese 31
    return namelen;
32
}
3251 mrmanese 33
 
3684 mrmanese 34
static int _find_free_filename2(char *rname, char *dirname, char **iname, int *namelen, int *file_idx) {
3471 mrmanese 35
    sqlite3_stmt *stmt;
3684 mrmanese 36
    char *tmp_iname;
3471 mrmanese 37
    sqlite3_prepare(g_workspace, "select 1 from workspace where internal_name=?", -1,
38
            &stmt, NULL);
3251 mrmanese 39
    do {
3684 mrmanese 40
        if (dirname != NULL) {
41
            sprintf(g_sql_buf[2], "%s/%s", dirname, *iname);
42
            tmp_iname = g_sql_buf[2];
43
        } else {
44
            tmp_iname = *iname;
45
        }
46
 
47
        if (!_file_exists(tmp_iname)) {
3471 mrmanese 48
            sqlite3_reset(stmt);
3684 mrmanese 49
            sqlite3_bind_text(stmt, 1, tmp_iname, -1, SQLITE_STATIC);
3471 mrmanese 50
            if (sqlite3_step(stmt) != SQLITE_ROW) break;
51
        }
3255 mrmanese 52
        *namelen = sprintf(*iname, "%s%d.db", rname, ++(*file_idx)) - 3;
53
    } while (*file_idx < 10000);
54
 
3471 mrmanese 55
    sqlite3_finalize(stmt);
3255 mrmanese 56
    return *file_idx;
57
}
58
 
59
/* creates an sdf attribute table */
60
static int _create_sdf_attribute2(const char *iname) {
61
    sprintf(g_sql_buf[2], "create table [%s].sdf_attributes(attr text, "
62
            "value text, primary key (attr))", iname);
3284 mrmanese 63
    int res;
64
    res = _sqlite_exec(g_sql_buf[2]);
3255 mrmanese 65
    if (res == SQLITE_OK) {
66
        sprintf(g_sql_buf[2], "insert into [%s].sdf_attributes values ('name',"
67
                "'%s');", iname, iname);
68
        res = _sqlite_exec(g_sql_buf[2]);
69
    }
70
    return res;
71
}
72
 
3419 mrmanese 73
char *_create_sdf_skeleton1(SEXP name, int *onamelen, int protect) {
3307 mrmanese 74
    char *iname, *rname;
75
    int namelen, file_idx = 0, res;
76
 
77
    namelen = _check_sdf_name(name, &rname, &iname, &file_idx);
78
 
79
    if (!namelen) return NULL;
80
 
3684 mrmanese 81
    _find_free_filename2(rname, ".SQLiteDF", &iname, &namelen, &file_idx);
3307 mrmanese 82
 
83
    if (file_idx >= 10000) { 
84
        Rprintf("Error: cannot find free SDF name.\n");
85
        return NULL;
86
    }
87
 
3308 mrmanese 88
    /* add to workspace */
3684 mrmanese 89
    sprintf(g_sql_buf[3], ".SQLiteDF/%s", iname);
3307 mrmanese 90
    iname[namelen] = 0; /* remove ".db" */
3308 mrmanese 91
    res = _add_sdf1(g_sql_buf[3], iname);
92
    if (_sqlite_error(res)) return NULL;
3307 mrmanese 93
 
3308 mrmanese 94
    /* detach SDF's if necessary to attach this one. if file does not
95
     * exist, then a sqlite db will be created after we make our 1st table */
3419 mrmanese 96
    if (!USE_SDF1(iname, FALSE, protect)) { /* _delete_sdf2(iname); */ return NULL; }
3308 mrmanese 97
 
98
 
3307 mrmanese 99
    /* create attributes table */
100
    res = _create_sdf_attribute2(iname);
101
    if (_sqlite_error(res)) {
102
        sprintf(g_sql_buf[2], "detach '%s'", iname);
3308 mrmanese 103
        _delete_sdf2(iname);
3307 mrmanese 104
        return NULL; 
105
    }
106
 
3397 mrmanese 107
    if (onamelen) *onamelen = namelen;
3307 mrmanese 108
    return iname;
109
}
3255 mrmanese 110
/* checks if a column has a corresponding factor|ordered table */
3419 mrmanese 111
int _is_factor2(const char *iname, const char *factor_type, const char *colname) {
3281 mrmanese 112
    sqlite3_stmt *stmt;
3255 mrmanese 113
    sprintf(g_sql_buf[2], "select * from [%s].[%s %s]", iname, factor_type,
114
            colname);
3284 mrmanese 115
    int res;
116
    res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, 0);
3282 mrmanese 117
    sqlite3_finalize(stmt);
3255 mrmanese 118
    return res == SQLITE_OK;
119
}
120
 
121
/* create a factor|ordered table */
3397 mrmanese 122
int _create_factor_table2(const char *iname, const char *factor_type, 
3255 mrmanese 123
        const char *colname) {
124
    sqlite3_stmt *stmt;
125
    sprintf(g_sql_buf[2], "create table [%s].[%s %s] (level int, label text, "
126
            "primary key(level), unique(label));", iname, factor_type, colname);
3284 mrmanese 127
    int res;
128
    res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, 0);
3282 mrmanese 129
    if (res == SQLITE_OK) sqlite3_step(stmt);
3255 mrmanese 130
    sqlite3_finalize(stmt);
131
    return res; /* error on dup name? */
132
}
133
 
134
/* copy a factor|ordered table from a sdf(db) to another sdf(db) */
3358 mrmanese 135
int _copy_factor_levels2(const char *factor_type, const char *iname_src,
3255 mrmanese 136
        const char *colname_src, const char *iname_dst, const char *colname_dst) {
137
    sqlite3_stmt *stmt;
138
    int res;
139
    res = _create_factor_table2(iname_dst, factor_type, colname_dst);
140
    if (res == SQLITE_OK) {
3281 mrmanese 141
        sprintf(g_sql_buf[2], "insert into [%s].[%s %s] select * from [%s].[%s %s]",
3473 mrmanese 142
                iname_dst, factor_type, colname_dst, iname_src, factor_type,
143
                colname_src);
3255 mrmanese 144
        res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, 0);
3473 mrmanese 145
        if (res == SQLITE_OK) res = sqlite3_step(stmt);
3255 mrmanese 146
        sqlite3_finalize(stmt);
3281 mrmanese 147
    }
3255 mrmanese 148
    return res; /* error on dup name? */
149
}
150
 
151
 
152
/* assumes stmt has col_cnt + 1 columns, col 0 is [row name]. returned SEXP is 
153
 * not UNPROTECT-ed, user will have to do that. will create the names &
4160 mrmanese 154
 * attach factor infos.
155
 * not that this will only create the data frame, not pull data from sqlite */
3281 mrmanese 156
static SEXP _setup_df_sexp1(sqlite3_stmt *stmt, const char *iname, 
157
        int col_cnt, int row_cnt, int *dup_indices) {
4160 mrmanese 158
    SEXP ret, names, value = R_NilValue;
159
    int i;
3281 mrmanese 160
    const char *colname, *coltype;
3255 mrmanese 161
 
162
    PROTECT(ret = NEW_LIST(col_cnt));
163
 
3281 mrmanese 164
    /* set up names. */
165
    PROTECT(names = NEW_CHARACTER(col_cnt));
3255 mrmanese 166
    for (i = 0; i < col_cnt; i++) {
3281 mrmanese 167
        colname = sqlite3_column_name(stmt, i+1);  /* +1 bec [row name is 0] */
168
        coltype = sqlite3_column_decltype(stmt, i+1);
169
 
4160 mrmanese 170
        if (dup_indices == NULL || dup_indices[i] == 0) {
3255 mrmanese 171
            strcpy(g_sql_buf[1], colname);
172
        } else {
173
            sprintf(g_sql_buf[1], "%s.%d", colname, dup_indices[i]);
174
        }
175
 
3281 mrmanese 176
        SET_STRING_ELT(names, i, mkChar(g_sql_buf[1]));
177
 
178
        if (strcmp(coltype, "text") == 0) {
179
            PROTECT(value = NEW_CHARACTER(row_cnt));
180
        } else if (strcmp(coltype, "double") == 0) {
181
            PROTECT(value = NEW_NUMERIC(row_cnt));
182
        } else if (strcmp(coltype, "bit") == 0) {
183
            PROTECT(value = NEW_LOGICAL(row_cnt));
184
        } else if (strcmp(coltype, "integer") == 0 || 
185
                   strcmp(coltype, "int") == 0) {
186
            PROTECT(value = NEW_INTEGER(row_cnt));
4160 mrmanese 187
 
188
            /* attach level values, & set class of factor/ordered if
189
             * value is a factor/ordered */
190
            _get_factor_levels1(iname, colname, value, TRUE);
3281 mrmanese 191
        } else {
192
            UNPROTECT(2); /* unprotect ret, names */
3808 mrmanese 193
            error("not supported type %s for %s\n", coltype, colname);
3281 mrmanese 194
        }
195
 
196
        SET_VECTOR_ELT(ret, i, value);
197
        UNPROTECT(1); /* unprotect value */
3255 mrmanese 198
 
199
    }
3281 mrmanese 200
    SET_NAMES(ret, names);
201
    UNPROTECT(1); /* unprotect names only */
3255 mrmanese 202
    return ret;
203
}
204
 
3281 mrmanese 205
/* expected that 1st col of stmt is [row name], so we start with index 1 */
206
static int _add_row_to_df(SEXP df, sqlite3_stmt *stmt, int row, int ncols) {
207
    SEXP vec;
3282 mrmanese 208
    int type = -1, is_null, i;
3281 mrmanese 209
    for (i = 1; i <= ncols; i++) {
210
        vec = VECTOR_ELT(df, i-1);
211
        type = TYPEOF(vec);
212
 
213
        is_null = (sqlite3_column_type(stmt, row) == SQLITE_NULL);
214
 
3457 mrmanese 215
        if (type == STRSXP || type == CHARSXP) {
3284 mrmanese 216
            SET_STRING_ELT(vec, row, mkChar((char *)sqlite3_column_text(stmt, i)));
3281 mrmanese 217
        } else if (type == INTSXP) {
218
            INTEGER(vec)[row] = sqlite3_column_int(stmt, i);
219
        } else if (type == REALSXP) {
220
            REAL(vec)[row] = sqlite3_column_double(stmt, i);
221
        } else if (type == LGLSXP) {
222
            LOGICAL(vec)[row] = sqlite3_column_int(stmt, i);
223
        }
224
    }
3282 mrmanese 225
    return type;
3281 mrmanese 226
}
227
 
3457 mrmanese 228
/* set ordinary df row name as numbers */
3281 mrmanese 229
static void _set_rownames2(SEXP df) {
230
    SEXP value = VECTOR_ELT(df, 0);
231
    int len = LENGTH(value), i;
232
    PROTECT(value = NEW_CHARACTER(len));
233
    for (i = 0; i < len; i++) {
234
        sprintf(g_sql_buf[2], "%d", i+1);
235
        SET_STRING_ELT(value, i, mkChar(g_sql_buf[2]));
236
    }
237
 
238
    SET_ROWNAMES(df, value);
239
    UNPROTECT(1);
240
}
241
 
242
 
3255 mrmanese 243
/****************************************************************************
244
 * SDF FUNCTIONS
245
 ****************************************************************************/
246
 
247
SEXP sdf_create_sdf(SEXP df, SEXP name) {
248
    SEXP ret;
3307 mrmanese 249
    char *iname; 
250
    int namelen, res, i, j;
3255 mrmanese 251
 
3307 mrmanese 252
    /* find free name, attach sdf, create sdf_attributes */
3419 mrmanese 253
    iname = _create_sdf_skeleton1(name, &namelen, FALSE);
3251 mrmanese 254
 
3307 mrmanese 255
    if (iname != NULL) {
3255 mrmanese 256
        int sql_len, sql_len2;
3252 mrmanese 257
        sqlite3_stmt *stmt;
258
 
3255 mrmanese 259
        /* create sdf_data table */
3426 mrmanese 260
        SEXP names = GET_NAMES(df), variable, levels, var_class;
3252 mrmanese 261
        int ncols = GET_LENGTH(names), type, *types;
262
        char *col_name, *class, *factor;
263
 
3324 mrmanese 264
        /* variables for adding rownames */
265
        SEXP rownames;
266
        int nrows;
267
        char *row_name;
268
 
3252 mrmanese 269
        /* TODO: put constraints on table after inserting everything? */
270
 
271
 
272
        /* 
273
         * create the create table and insert sql scripts by looping through
274
         * the columns of df
275
         */
276
        types = (int *)R_alloc(ncols, sizeof(int));
277
        sql_len = sprintf(g_sql_buf[0], "create table [%s].sdf_data ([row name] text", iname);
278
        sql_len2 = sprintf(g_sql_buf[1], "insert into [%s].sdf_data values(?", iname);
279
 
280
        for (i = 0; i < ncols; i++) {
281
            col_name = CHAR(STRING_ELT(names, i));
282
 
283
            /* add column definition to the create table sql */
284
            _expand_buf(0, sql_len+strlen(col_name)+10);
285
 
286
            variable = _getListElement(df, col_name);
3426 mrmanese 287
            var_class = GET_CLASS(variable);
288
            class = (var_class == R_NilValue) ? NULL : CHAR(STRING_ELT(var_class, 0));
3252 mrmanese 289
            type = TYPEOF(variable);
290
            types[i] = type;
291
 
292
            sql_len += sprintf(g_sql_buf[0]+sql_len, ", [%s] %s", col_name, 
293
                    _get_column_type(class, type));
294
 
295
            /* add handler to insert table sql */
296
            _expand_buf(1, sql_len+5);
297
            strcpy(g_sql_buf[1]+sql_len2, ",?");
298
            sql_len2 += 2; 
299
 
300
            /* create separate table for factors decode */
3426 mrmanese 301
            if (class != NULL && (strcmp(class, "factor") == 0 || strcmp(class, "ordered") == 0)){
3255 mrmanese 302
                if (_create_factor_table2(iname, class, col_name)) 
303
                    return R_NilValue; /* dup tbl name? */
3252 mrmanese 304
 
3397 mrmanese 305
                _sqlite_exec("begin");
3252 mrmanese 306
                levels = GET_LEVELS(variable);
3255 mrmanese 307
                sprintf(g_sql_buf[2], "insert into [%s].[%s %s] values(?, ?);",
308
                        iname, class, col_name);
309
                res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, NULL);
3252 mrmanese 310
                if (_sqlite_error(res)) return R_NilValue; /* dup tbl name? */
311
 
312
                for (j = 0; j < GET_LENGTH(levels); j++) {
313
                    sqlite3_reset(stmt);
314
                    factor = CHAR(STRING_ELT(levels, j));
315
                    sqlite3_bind_int(stmt, 1, j+1);
3307 mrmanese 316
                    sqlite3_bind_text(stmt, 2, factor, -1, SQLITE_STATIC);
3252 mrmanese 317
                    sqlite3_step(stmt);
318
                }
319
                sqlite3_finalize(stmt);
3397 mrmanese 320
                _sqlite_exec("commit");
3252 mrmanese 321
            }
322
        }
323
 
324
        _expand_buf(0,sql_len+35);
3419 mrmanese 325
        sql_len += sprintf(g_sql_buf[0]+sql_len, ", primary key([row name]));");
326
        /* sql_len += sprintf(g_sql_buf[0]+sql_len, ");"); */
3252 mrmanese 327
        res = _sqlite_exec(g_sql_buf[0]);
328
        if (_sqlite_error(res)) return R_NilValue; /* why? */
329
 
330
        /*
331
         * add the data in df to the sdf
332
         */
3324 mrmanese 333
        rownames = getAttrib(df, R_RowNamesSymbol);
334
        nrows = GET_LENGTH(rownames);
3252 mrmanese 335
 
3397 mrmanese 336
        _sqlite_error(_sqlite_exec("begin"));
3255 mrmanese 337
        sprintf(g_sql_buf[1]+sql_len2, ")");
338
        res = sqlite3_prepare(g_workspace, g_sql_buf[1], -1, &stmt, NULL);
3252 mrmanese 339
 
340
        for (i = 0; i < nrows; i++) {
341
            sqlite3_reset(stmt);
342
 
3324 mrmanese 343
            /* since this is coming from a real dataframe, we're assured that
344
             * the rownames are unique */
345
            if (IS_CHARACTER(rownames)) {
346
                row_name = CHAR(STRING_ELT(rownames, i));
347
                if (*row_name) /* if not empty string */
348
                    sqlite3_bind_text(stmt, 1, row_name, strlen(row_name), SQLITE_STATIC);
349
                else sqlite3_bind_int(stmt, 1, i);
350
            } else if (IS_INTEGER(rownames)) {
351
                sqlite3_bind_int(stmt, 1, INTEGER(rownames)[i]);
352
            } else sqlite3_bind_int(stmt, 1, i);
3252 mrmanese 353
 
354
            for (j = 0; j < ncols; j++) {
355
                variable = VECTOR_ELT(df, j);
356
                switch(types[j]) {
357
                    case INTSXP : 
358
                        sqlite3_bind_int(stmt, j+2, INTEGER(variable)[i]);
359
                        break;
4160 mrmanese 360
                    case LGLSXP : 
361
                        /* they might make it a bit although currentLY 
362
                         * LOGICAL==INTEGER macro */
363
                        sqlite3_bind_int(stmt, j+2, LOGICAL(variable)[i]);
364
                        break;
3252 mrmanese 365
                    case REALSXP:
366
                        sqlite3_bind_double(stmt, j+2, REAL(variable)[i]);
367
                        break;
368
                    case CHARSXP:
3457 mrmanese 369
                    case STRSXP:
370
                        sqlite3_bind_text(stmt, j+2, CHAR_ELT(variable, i), -1, SQLITE_STATIC);
3252 mrmanese 371
                }
372
                /* TODO: handle NA's & NULL's */
373
            }
374
 
375
            res = sqlite3_step(stmt);
376
            if (res != SQLITE_DONE) { 
3397 mrmanese 377
                _sqlite_exec("ROLLBACK");
3252 mrmanese 378
                sqlite3_finalize(stmt);
3397 mrmanese 379
                Rprintf("SQLITE ERROR: %s\n", sqlite3_errmsg(g_workspace));
3252 mrmanese 380
                return R_NilValue; /* why? */
381
            }
382
        }
383
 
384
        sqlite3_finalize(stmt);
3397 mrmanese 385
        _sqlite_error(_sqlite_exec("COMMIT"));
3252 mrmanese 386
 
3308 mrmanese 387
        /* create a new object representing the sdf */
3252 mrmanese 388
        ret = _create_sdf_sexp(iname);
389
 
390
    } else {
3308 mrmanese 391
        Rprintf("ERROR: unable to create a sqlite data frame.\n");
3252 mrmanese 392
        ret = R_NilValue;
3251 mrmanese 393
    }
394
 
3252 mrmanese 395
    return ret;
396
}
397
 
398
SEXP sdf_get_names(SEXP sdf) {
3308 mrmanese 399
    char *iname;
400
    iname = SDF_INAME(sdf);
3419 mrmanese 401
    if (!USE_SDF1(iname, TRUE, FALSE)) return R_NilValue;
3252 mrmanese 402
 
3308 mrmanese 403
    int len;
404
    len = sprintf(g_sql_buf[0], "select * from [%s].sdf_data;", iname);
405
 
3252 mrmanese 406
    sqlite3_stmt *stmt;
3284 mrmanese 407
    int res, i;
3252 mrmanese 408
 
409
    res = sqlite3_prepare(g_workspace, g_sql_buf[0], len, &stmt, NULL);
410
    if (_sqlite_error(res)) return R_NilValue;
411
 
412
    SEXP ret;
413
 
414
    len = sqlite3_column_count(stmt)-1;
415
    PROTECT(ret = NEW_CHARACTER(len));
416
 
3284 mrmanese 417
    for (i = 0; i < len; i++) {
3252 mrmanese 418
        SET_STRING_ELT(ret, i, mkChar(sqlite3_column_name(stmt, i+1)));
419
    }
420
 
421
    sqlite3_finalize(stmt);
3251 mrmanese 422
    UNPROTECT(1);
423
    return ret;
424
}
425
 
3252 mrmanese 426
SEXP sdf_get_length(SEXP sdf) {
3308 mrmanese 427
    char *iname;
3446 mrmanese 428
    int len;
429
    sqlite3_stmt *stmt;
430
    int res;
431
 
3821 mrmanese 432
    iname  = SDF_INAME(sdf); 
3446 mrmanese 433
    sprintf(g_sql_buf[0], "select * from [%s].sdf_data;", iname);
3419 mrmanese 434
    if (!USE_SDF1(iname, TRUE, FALSE)) return R_NilValue;
3308 mrmanese 435
 
3446 mrmanese 436
    res = sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, NULL);
3252 mrmanese 437
    if (_sqlite_error(res)) return R_NilValue;
438
 
439
    len = sqlite3_column_count(stmt)-1;
440
    sqlite3_finalize(stmt);
3446 mrmanese 441
    return ScalarInteger(len);
3252 mrmanese 442
}
443
 
3255 mrmanese 444
/* get row count */
445
SEXP sdf_get_row_count(SEXP sdf) {
3252 mrmanese 446
    char *iname = CHAR(STRING_ELT(_getListElement(sdf, "iname"),0));
3419 mrmanese 447
    if (!USE_SDF1(iname, TRUE, FALSE)) return R_NilValue;
3308 mrmanese 448
 
3358 mrmanese 449
    int nrow;
3252 mrmanese 450
    SEXP ret;
451
 
3358 mrmanese 452
    nrow = _get_row_count2(iname, TRUE);
3252 mrmanese 453
 
3358 mrmanese 454
    if (nrow < 1) ret = R_NilValue;
3446 mrmanese 455
    else ret = ScalarInteger(nrow);
3252 mrmanese 456
 
457
    return ret;
458
}
459
 
460
 
3255 mrmanese 461
SEXP sdf_import_table(SEXP _filename, SEXP _name, SEXP _sep, SEXP _quote, 
462
        SEXP _rownames, SEXP _colnames) {
463
    char *filename = CHAR_ELT(_filename, 0);
464
    FILE *f = fopen(filename, "r");
3252 mrmanese 465
 
3255 mrmanese 466
    if (f == NULL) {
467
        Rprintf("Error: File %s does not exist.", filename);
468
        return R_NilValue;
469
    }
3252 mrmanese 470
 
3282 mrmanese 471
    /*char *sep = CHAR_ELT(_sep, 0), *quote = CHAR_ELT(_quote,0);
472
    char *name = CHAR_ELT(_name, 0);*/
3252 mrmanese 473
 
3255 mrmanese 474
    /* create the table */
475
    /* insert the stuffs */
476
    /* register to workspace */
477
 
478
    return R_NilValue;
479
}
480
 
3471 mrmanese 481
SEXP sdf_get_index(SEXP sdf, SEXP row, SEXP col, SEXP new_sdf) {
3282 mrmanese 482
    SEXP ret = R_NilValue;
3255 mrmanese 483
    char *iname = SDF_INAME(sdf);
3282 mrmanese 484
    sqlite3_stmt *stmt;
3281 mrmanese 485
    int buflen = 0, idxlen, col_cnt, row_cnt, index;
3255 mrmanese 486
    int i, j,res;
3700 mrmanese 487
    int *col_indices = NULL, col_index_len = 0, *dup_indices = NULL;
3471 mrmanese 488
    int row_index_len = 0, force_new_df = LOGICAL(new_sdf)[0];
3473 mrmanese 489
    const char *colname;
3255 mrmanese 490
 
3473 mrmanese 491
    /* dup_indices is used to handle when same column chosen more than once.
492
     * e.g. iris[,c(1,1)] have names Sepal.Length, Sepal.Length.1 *
493
     * col_indices is used to store the column index of selected columns
494
     * in the sdf_data table */
495
 
3471 mrmanese 496
    if (!USE_SDF1(iname, TRUE, TRUE)) return R_NilValue;
497
 
3281 mrmanese 498
    sprintf(g_sql_buf[0], "select * from [%s].sdf_data ", iname);
3255 mrmanese 499
    res = sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, 0);
500
    if (_sqlite_error(res)) return R_NilValue;
501
 
502
    buflen = sprintf(g_sql_buf[0], "select [row name]");
503
    idxlen = LENGTH(col);
504
    col_cnt = sqlite3_column_count(stmt) - 1;
505
 
506
    /*
3457 mrmanese 507
     * PROCESS COLUMN INDEX: set columns in the select statement
3255 mrmanese 508
     */
3281 mrmanese 509
    if (col == R_NilValue) {
3255 mrmanese 510
        for (i = 1; i < col_cnt+1; i++) {
3473 mrmanese 511
            colname = sqlite3_column_name(stmt, i);
512
            buflen += sprintf(g_sql_buf[0]+buflen, ",[%s]", colname);
3821 mrmanese 513
            _expand_buf(0, buflen + 100);
3255 mrmanese 514
        }
3281 mrmanese 515
        buflen += sprintf(g_sql_buf[0]+buflen, " from [%s].sdf_data", iname);
516
        col_index_len = col_cnt;
3473 mrmanese 517
        col_indices = (int *)R_alloc(col_cnt, sizeof(int));
518
        dup_indices = (int *)R_alloc(col_cnt, sizeof(int));
3281 mrmanese 519
        for (i = 0; i < col_cnt; i++) { col_indices[i] = i; dup_indices[i] = 0; }
3255 mrmanese 520
    } else if (col == R_NilValue || idxlen < 1) {
521
        sqlite3_finalize(stmt);
522
        return R_NilValue;
523
    } else if (IS_NUMERIC(col)) {
524
        col_indices = (int *)R_alloc(idxlen, sizeof(int));
525
        dup_indices = (int *)R_alloc(idxlen, sizeof(int));
526
        col_index_len = 0;
527
 
528
        for (i = 0; i < idxlen; i++) {
529
            /* no need to correct for 0 base because col 0 is [row name] */
530
            index = ((int) REAL(col)[i]); 
531
            if (index > col_cnt) {
532
                sqlite3_finalize(stmt);
3473 mrmanese 533
                error("undefined columns selected\n");
3255 mrmanese 534
            } else if (index > 0) {
3473 mrmanese 535
                colname = sqlite3_column_name(stmt,index);
536
                buflen += sprintf(g_sql_buf[0]+buflen, ",[%s]", colname);
3821 mrmanese 537
                _expand_buf(0, buflen + 100);
3255 mrmanese 538
                dup_indices[col_index_len] = 0;
539
                for (j = 0; j < col_index_len; j++) {
540
                    if (col_indices[j] == index) dup_indices[col_index_len]++;
541
                }
542
                col_indices[col_index_len++] = index;
543
            } else if (index < 0) {
544
                sqlite3_finalize(stmt);
3473 mrmanese 545
                error("negative indices not supported.\n");
3255 mrmanese 546
            }
547
        }
548
 
549
        if (col_index_len == 0) {
550
            sqlite3_finalize(stmt);
551
            Rprintf("Error: no indices detected??\n");
552
            return R_NilValue;
3281 mrmanese 553
        } else { 
554
            _expand_buf(0, buflen+20+strlen(iname));
555
            buflen += sprintf(g_sql_buf[0]+buflen, " from [%s].sdf_data", iname);
3255 mrmanese 556
        }
557
    } else if (IS_INTEGER(col)) {
558
        /* identical logic with IS_NUMERIC, except that we don't have to cast
559
         * stuffs from SEXP col. the alternative is doing if idxlen times. */
560
        col_indices = (int *)R_alloc(idxlen, sizeof(int));
561
        dup_indices = (int *)R_alloc(idxlen, sizeof(int));
562
        col_index_len = 0;
563
 
564
        for (i = 0; i < idxlen; i++) {
565
            /* no need to correct for 0 base because col 0 is [row name] */
566
            index = INTEGER(col)[i];
567
            if (index > col_cnt) {
568
                sqlite3_finalize(stmt);
3473 mrmanese 569
                error("undefined columns selected\n");
3255 mrmanese 570
            } else if (index > 0) {
3473 mrmanese 571
                colname = sqlite3_column_name(stmt,index);
572
                buflen += sprintf(g_sql_buf[0]+buflen, ",[%s]", colname);
3821 mrmanese 573
                _expand_buf(0, buflen + 100);
3255 mrmanese 574
                dup_indices[col_index_len] = 0;
575
                for (j = 0; j < col_index_len; j++) {
576
                    if (col_indices[j] == index) dup_indices[col_index_len]++;
577
                }
578
                col_indices[col_index_len++] = index;
579
            } else if (index < 0) {
580
                sqlite3_finalize(stmt);
3473 mrmanese 581
                error("negative indices not supported.\n");
3255 mrmanese 582
            }
583
        }
584
 
585
        if (col_index_len == 0) {
586
            sqlite3_finalize(stmt);
3821 mrmanese 587
            error("no valid indices detected");
3281 mrmanese 588
        } else { 
3821 mrmanese 589
            /*Rprintf("debug: col_index_len: %d, idxlen: %d, buf 0: %s\n", col_index_len, idxlen, g_sql_buf[0]);*/
3281 mrmanese 590
            _expand_buf(0, buflen+20+strlen(iname));
591
            buflen += sprintf(g_sql_buf[0]+buflen, " from [%s].sdf_data", iname);
3255 mrmanese 592
        }
593
    } else if (IS_LOGICAL(col)) {
594
        /* recycling stuff, so max column output is the # of cols in the df */
595
        col_indices = (int *)R_alloc(col_cnt, sizeof(int));
596
        dup_indices = (int *)R_alloc(col_cnt, sizeof(int));
597
        col_index_len = 0;
598
        for (i = 0; i < col_cnt; i++) {
599
            if (LOGICAL(col)[i%idxlen]) {
3281 mrmanese 600
                buflen += sprintf(g_sql_buf[0]+buflen, ",[%s]", 
3255 mrmanese 601
                        sqlite3_column_name(stmt,i+1));
3473 mrmanese 602
 
3255 mrmanese 603
                dup_indices[col_index_len] = 0;
604
                col_indices[col_index_len++] = i;
605
            }
3473 mrmanese 606
 
3255 mrmanese 607
        }
608
 
609
        if (col_index_len == 0) {
610
            sqlite3_finalize(stmt);
3473 mrmanese 611
            warning("no column selected.\n");
3255 mrmanese 612
            return R_NilValue;
3281 mrmanese 613
        } else { 
614
            _expand_buf(0, buflen+20+strlen(iname));
615
            buflen += sprintf(g_sql_buf[0]+buflen, " from [%s].sdf_data", iname);
3255 mrmanese 616
        }
617
    } else {
618
        sqlite3_finalize(stmt);
3473 mrmanese 619
        error("don't know how to handle column index.\n");
3255 mrmanese 620
    }
621
 
622
    /* 
3457 mrmanese 623
     * PROCESS ROW INDEX: setup limit or where clause
3255 mrmanese 624
     */
625
    idxlen = LENGTH(row);
3281 mrmanese 626
    if (row == R_NilValue) {
3471 mrmanese 627
        if (col_index_len == 1 && !force_new_df) {
3281 mrmanese 628
            ret = sdf_get_variable(sdf, mkString(sqlite3_column_name(stmt,col_indices[0])));
629
            sqlite3_finalize(stmt);
630
            return ret;
3821 mrmanese 631
        } else if (col_index_len > 1 || (force_new_df && col_index_len == 1)) {
3255 mrmanese 632
            /* create a new SDF, logic similar to sdf_create_sdf */
633
 
634
            /* find a new name. data<n> ? */
3307 mrmanese 635
            char *iname2;
636
            int namelen, sql_len, sql_len2;
3255 mrmanese 637
 
3419 mrmanese 638
            iname2 = _create_sdf_skeleton1(R_NilValue, &namelen, TRUE);
3255 mrmanese 639
 
640
            /* create sdf_data table */
3281 mrmanese 641
            sql_len = sprintf(g_sql_buf[1], "create table [%s].sdf_data ([row name] text", iname2);
642
            sql_len2 = 0;
3255 mrmanese 643
 
644
            for (i = 0; i < col_index_len; i++) {
645
                colname = sqlite3_column_name(stmt, col_indices[i]);
646
                if (dup_indices[i] == 0) {
3281 mrmanese 647
                    sql_len += sprintf(g_sql_buf[1]+sql_len, ", [%s] %s", colname,
3255 mrmanese 648
                            sqlite3_column_decltype(stmt, col_indices[i]));
649
                } else {
650
                    /* un-duplicate col names by appending num, just like R */
3281 mrmanese 651
                    sql_len += sprintf(g_sql_buf[1]+sql_len, ", [%s.%d] %s", colname,
3255 mrmanese 652
                            dup_indices[i], 
653
                            sqlite3_column_decltype(stmt, col_indices[i]));
654
                }
3821 mrmanese 655
                _expand_buf(1, sql_len + 100);
3255 mrmanese 656
 
657
                /* deal with possibly factor columns */
658
                if (_is_factor2(iname, "factor", colname)) {
659
                    /* found a factor column */
3281 mrmanese 660
 
3255 mrmanese 661
                    if (dup_indices[i] == 0)  {
662
                        _copy_factor_levels2("factor", iname, colname, iname2, colname);
663
                    } else {
664
                        sprintf(g_sql_buf[3], "%s.%d", colname, dup_indices[i]);
665
                        _copy_factor_levels2("factor", iname, colname, iname2, 
666
                                g_sql_buf[3]);
667
                    }
668
                }
669
 
670
                /* and deal with ordered factors too... life is hard, then you die */
671
                if (_is_factor2(iname, "ordered", colname)) {
3281 mrmanese 672
 
3255 mrmanese 673
                    if (dup_indices[i] == 0)  {
674
                        _copy_factor_levels2("ordered", iname, colname, iname2, 
675
                                colname);
676
                    } else {
677
                        sprintf(g_sql_buf[3], "%s.%d", colname, dup_indices[i]);
678
                        _copy_factor_levels2("ordered", iname, colname, iname2, 
679
                                g_sql_buf[3]);
680
                    }
681
                }
682
 
683
            }
684
 
685
            /* don't need it anymore */
686
            sqlite3_finalize(stmt);
687
 
688
            /* no table index created, that's for v2 I hope*/
689
            sql_len += sprintf(g_sql_buf[1]+sql_len, ");");
690
            res = _sqlite_exec(g_sql_buf[1]);
3281 mrmanese 691
            if (_sqlite_error(res)) { Rprintf("here? %s\n", g_sql_buf[1]); return R_NilValue; }
3255 mrmanese 692
 
693
            /* insert data (with row names). buf[0] contains a select */
3821 mrmanese 694
            _expand_buf(1, g_sql_buf_sz[0] + 32);
3255 mrmanese 695
            sprintf(g_sql_buf[1], "insert into [%s].sdf_data %s", iname2,
696
                    g_sql_buf[0]);
697
            res = _sqlite_exec(g_sql_buf[1]);
698
            if (_sqlite_error(res)) return R_NilValue;
699
 
3419 mrmanese 700
            /* remove protection */
701
            UNUSE_SDF2(iname2);
702
 
3255 mrmanese 703
            /* create SEXP for the SDF */
704
            ret = _create_sdf_sexp(iname2);
3281 mrmanese 705
            return ret;
3255 mrmanese 706
        } else { sqlite3_finalize(stmt); return R_NilValue; }
707
    } else if (row == R_NilValue || idxlen < 1) {
708
        sqlite3_finalize(stmt);
709
        return R_NilValue;
710
    } else if (IS_NUMERIC(row)) {
711
        sqlite3_finalize(stmt);
712
 
3281 mrmanese 713
        sprintf(g_sql_buf[1], "[%s].sdf_data", iname);
3358 mrmanese 714
        row_cnt = _get_row_count2(g_sql_buf[1], 0);
3281 mrmanese 715
 
3255 mrmanese 716
        /* append " limit ?,1" to the formed select statement */
717
        _expand_buf(0, buflen+10);
3281 mrmanese 718
        buflen += sprintf(g_sql_buf[0]+buflen, " limit ?,1");
719
        /*Rprintf("sql [%d]: %s\n", buflen, g_sql_buf[0]); */
3255 mrmanese 720
 
3281 mrmanese 721
        index = ((int) REAL(row)[0]) - 1;
3255 mrmanese 722
        if (idxlen < 0 && idxlen == 1) return R_NilValue;
723
 
724
        res = sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, 0);
725
        if (_sqlite_error(res)) return R_NilValue;
726
 
727
        sqlite3_bind_int(stmt, 1, index);
728
        res = sqlite3_step(stmt);
729
 
730
        /* create data frame */
3281 mrmanese 731
        ret = _setup_df_sexp1(stmt, iname, col_index_len, idxlen, dup_indices);
732
        if (ret == R_NilValue) { sqlite3_finalize(stmt); return R_NilValue; }
3255 mrmanese 733
 
3281 mrmanese 734
        /* put data in it */
735
        if (index >= 0 && index < row_cnt) {
736
            _add_row_to_df(ret, stmt, row_index_len++, col_index_len);
737
        }
3255 mrmanese 738
 
3281 mrmanese 739
        for (i = 1; i < idxlen; i++) {
740
            sqlite3_reset(stmt);
741
            index = ((int) REAL(row)[i]) - 1;
742
            if (index >= 0 && index < row_cnt) {
743
                sqlite3_bind_int(stmt, 1, index);
744
                res = sqlite3_step(stmt);
745
                _add_row_to_df(ret, stmt, row_index_len++, col_index_len);
746
            }
747
        }
748
        sqlite3_finalize(stmt);
749
 
750
        /* shrink vectors */
751
        if (row_index_len < idxlen) {
752
            for (i = 0; i < col_index_len; i++) {
753
                SET_VECTOR_ELT(ret, i, 
754
                        _shrink_vector(VECTOR_ELT(ret, i), row_index_len));
755
            }
756
        }
757
 
758
        UNPROTECT(1); /* for the ret from _setup_df_sexp1 */
759
    } else if (IS_INTEGER(row)) {
760
        /* same stuff as with IS_INTEGER, except for setting of var index*/
761
        sqlite3_finalize(stmt);
762
 
763
        sprintf(g_sql_buf[1], "[%s].sdf_data", iname);
3358 mrmanese 764
        row_cnt = _get_row_count2(g_sql_buf[1], 0);
3281 mrmanese 765
 
766
        /* append " limit ?,1" to the formed select statement */
767
        _expand_buf(0, buflen+10);
768
        buflen += sprintf(g_sql_buf[0]+buflen, " limit ?,1");
769
 
770
        index = INTEGER(row)[0] - 1;
771
        if (idxlen < 0 && idxlen == 1) return R_NilValue;
772
 
773
        res = sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, 0);
774
        if (_sqlite_error(res)) return R_NilValue;
775
 
776
        sqlite3_bind_int(stmt, 1, index);
777
        res = sqlite3_step(stmt);
778
 
779
        /* create data frame */
780
        ret = _setup_df_sexp1(stmt, iname, col_index_len, idxlen, dup_indices);
781
        if (ret == R_NilValue) { sqlite3_finalize(stmt); return R_NilValue; }
782
 
3255 mrmanese 783
        /* put data in it */
3281 mrmanese 784
        if (index >= 0 && index < row_cnt) {
785
            _add_row_to_df(ret, stmt, row_index_len++, col_index_len);
786
        }
787
 
788
        for (i = 1; i < idxlen; i++) {
789
            sqlite3_reset(stmt);
790
            index = INTEGER(row)[i] - 1;
791
            if (index >= 0 && index < row_cnt) {
792
                sqlite3_bind_int(stmt, 1, index);
793
                res = sqlite3_step(stmt); 
794
                _add_row_to_df(ret, stmt, row_index_len++, col_index_len);
795
            }
796
        }
797
        sqlite3_finalize(stmt);
798
 
799
        /* shrink vectors */
800
        if (row_index_len < idxlen) {
801
            for (i = 0; i < col_index_len; i++) {
802
                SET_VECTOR_ELT(ret, i, 
803
                        _shrink_vector(VECTOR_ELT(ret, i), row_index_len));
804
            }
805
        }
806
        UNPROTECT(1); /* for the ret from _setup_df_sexp1 */
3255 mrmanese 807
    } else if (IS_LOGICAL(row)) {
808
        /* */
3281 mrmanese 809
        sqlite3_finalize(stmt);
810
        int est_row_cnt = 0;
811
 
812
        sprintf(g_sql_buf[1], "[%s].sdf_data", iname);
3358 mrmanese 813
        row_cnt = _get_row_count2(g_sql_buf[1], 0);
3281 mrmanese 814
 
815
        /* append " limit ?,1" to the formed select statement */
816
        _expand_buf(0, buflen+10);
817
        buflen += sprintf(g_sql_buf[0]+buflen, " limit ?,1");
818
 
819
        /* find if there is any TRUE element in the vector */
3282 mrmanese 820
        for (i = 0; i < idxlen && i < row_cnt; i++) {
3281 mrmanese 821
            if (LOGICAL(row)[i]) break;
822
        }
823
 
3282 mrmanese 824
        if (i < idxlen && i < row_cnt) {
3281 mrmanese 825
            est_row_cnt = (idxlen-i) * (row_cnt/idxlen);
826
            if (row_cnt%idxlen > i) est_row_cnt += (row_cnt%idxlen - i);
827
 
828
            res = sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, 0);
829
            if (_sqlite_error(res)) return R_NilValue;
830
 
831
            sqlite3_bind_int(stmt, 1, i);
832
            sqlite3_step(stmt);
833
            ret = _setup_df_sexp1(stmt, iname, col_index_len, est_row_cnt, dup_indices);
834
            _add_row_to_df(ret, stmt, row_index_len++, col_index_len);
835
 
836
            for (i++ ; i < row_cnt; i++) {
837
                if (LOGICAL(row)[i%idxlen]) {
838
                    sqlite3_reset(stmt);
839
                    sqlite3_bind_int(stmt, 1, i);
840
                    sqlite3_step(stmt);
841
                    _add_row_to_df(ret, stmt, row_index_len++, col_index_len);
842
                }
843
            }
844
        }
845
 
846
        sqlite3_finalize(stmt);
847
 
848
        /* shrink vectors */
849
        if (est_row_cnt > 0 && row_index_len < est_row_cnt) {
850
            for (i = 0; i < col_index_len; i++) {
851
                SET_VECTOR_ELT(ret, i, 
852
                        _shrink_vector(VECTOR_ELT(ret, i), row_index_len));
853
            }
854
        }
855
 
856
        UNPROTECT(1); /* for the ret from _setup_df_sexp1 */
3255 mrmanese 857
    }
858
 
3419 mrmanese 859
    UNUSE_SDF2(iname);
860
 
3281 mrmanese 861
    if (ret != R_NilValue && col_index_len > 1) {
3457 mrmanese 862
        SET_CLASS(ret, mkString("data.frame"));
3281 mrmanese 863
        _set_rownames2(ret);
864
    } else if (ret != R_NilValue && col_index_len == 1) {
865
        ret = VECTOR_ELT(ret, 0);
866
    }
3255 mrmanese 867
 
868
    return ret;
869
}
870
 
3324 mrmanese 871
SEXP sdf_rbind(SEXP sdf, SEXP data) {
3457 mrmanese 872
    char *class;
3471 mrmanese 873
    char *iname = SDF_INAME(sdf), *colname;
3358 mrmanese 874
    SEXP ret = R_NilValue, col, names, levels, rownames;
3457 mrmanese 875
    int ncols, buflen, buflen2, i, j, res, nrows, *types, rownames_type;
3324 mrmanese 876
    sqlite3_stmt *stmt;
3358 mrmanese 877
    const char *type;
3471 mrmanese 878
    char *rn_str; 
3281 mrmanese 879
 
3457 mrmanese 880
    class = CHAR_ELT(GET_CLASS(data), 0);
3324 mrmanese 881
    if (strcmp(class,"data.frame") == 0) {
882
        /* check table names, types. variables may not be in same order, as
883
         * long as names and types are identical. */
884
        names = GET_NAMES(data);
3358 mrmanese 885
        ncols = GET_LENGTH(names);
3324 mrmanese 886
 
887
        buflen = sprintf(g_sql_buf[0], "select 1");
3358 mrmanese 888
        for (i = 0; i < ncols; i++) {
3324 mrmanese 889
            _expand_buf(0, buflen + 100);
890
            buflen += sprintf(g_sql_buf[0]+buflen, ",[%s]", CHAR_ELT(names, i));
891
        }
892
        _expand_buf(0, buflen + 100);
3358 mrmanese 893
        sprintf(g_sql_buf[0]+buflen, " from [%s].sdf_data", iname);
3324 mrmanese 894
 
895
        res = sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, NULL);
896
        if (res != SQLITE_OK) { /* column name mismatch */
3457 mrmanese 897
            _sqlite_error(res);
3324 mrmanese 898
            Rprintf("Error: column names should exactly match the names of the SDF.\n");
899
            return ret;
900
        }
901
 
902
        /* now check the type */
3358 mrmanese 903
        types = (int *)R_alloc(ncols, sizeof(int));
904
        for (i = 0; i< ncols; i++) {
905
            type = sqlite3_column_decltype(stmt, i+1); /* +1 bec 1st col is "1" */
3324 mrmanese 906
 
907
            col = VECTOR_ELT(data, i);
3457 mrmanese 908
            /* class = CHAR_ELT(GET_CLASS(col),0); */
3324 mrmanese 909
 
3358 mrmanese 910
            if (strcmp(type, "double") == 0 && IS_NUMERIC(col)) types[i] = SQLITE_FLOAT;
911
            else if (strcmp(type, "text") == 0 && IS_CHARACTER(col)) types[i] = SQLITE_TEXT;
912
            else if (strcmp(type, "int") == 0) { 
913
                types[i] = SQLITE_INTEGER;
914
                if (isUnordered(col)) {  /* test if factor */
915
                    colname = CHAR_ELT(names, i);
3324 mrmanese 916
                    sqlite3_stmt *stmt2;
917
                    if (!_is_factor2(iname, "factor", colname)) break;
918
                    sprintf(g_sql_buf[1], "[%s].[factor %s]", iname, colname);
3358 mrmanese 919
                    nrows = _get_row_count2(g_sql_buf[1], 0);
3324 mrmanese 920
 
3358 mrmanese 921
                    /* levels in sdf must be >= levels in df */
3324 mrmanese 922
                    levels = GET_LEVELS(col);
923
                    if (nrows < GET_LENGTH(levels)) {
924
                        Rprintf("Error: The data frame variable %s has more levels than"
925
                                " its SDF counterpart.\n", colname);
926
                        break;
927
                    }
928
 
3358 mrmanese 929
                    sprintf(g_sql_buf[2], "select label from %s order by level", g_sql_buf[1]);
930
                    res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt2, NULL);
931
                    _sqlite_error(res);
3324 mrmanese 932
 
3358 mrmanese 933
                    for (j = 0; j < GET_LENGTH(levels); j++)  {
3324 mrmanese 934
                        sqlite3_step(stmt2);
3358 mrmanese 935
                        if (strcmp((char *)sqlite3_column_text(stmt2, 0), CHAR_ELT(levels, j)) != 0) {
3324 mrmanese 936
                            Rprintf("Error: Level label mismatch in variable %s, [%s] in data frame"
937
                                    " vs [%s] in SDF.\n", colname, (char *)sqlite3_column_text(stmt2, 0),
938
                                    CHAR_ELT(levels, j));
3358 mrmanese 939
                            sqlite3_finalize(stmt2);
3324 mrmanese 940
                            break;
941
                        }
942
                    }
3358 mrmanese 943
                    sqlite3_finalize(stmt2);
944
                } else if (isOrdered(col)) { /* same with ordered */
945
                    colname = CHAR_ELT(names, i);
3324 mrmanese 946
                    sqlite3_stmt *stmt2;
947
                    if (!_is_factor2(iname, "ordered", colname)) break;
948
                    sprintf(g_sql_buf[1], "[%s].[ordered %s]", iname, colname);
3358 mrmanese 949
                    nrows = _get_row_count2(g_sql_buf[1], 0);
3324 mrmanese 950
 
3358 mrmanese 951
                    /* levels in sdf must be >= levels in df */
3324 mrmanese 952
                    levels = GET_LEVELS(col);
953
                    if (nrows < GET_LENGTH(levels)) {
954
                        Rprintf("Error: The data frame variable %s has more levels than"
955
                                " its SDF counterpart.\n", colname);
956
                        break;
957
                    }
958
 
3358 mrmanese 959
                    sprintf(g_sql_buf[2], "select label from %s order by level", g_sql_buf[1]);
3324 mrmanese 960
                    sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt2, NULL);
961
 
3358 mrmanese 962
                    for (j = 0; j < GET_LENGTH(levels); j++)  {
3324 mrmanese 963
                        sqlite3_step(stmt2);
3358 mrmanese 964
                        if (strcmp((char *)sqlite3_column_text(stmt2, 0), CHAR_ELT(levels, j)) != 0) {
3324 mrmanese 965
                            Rprintf("Error: Level label mismatch in variable %s, [%s] in data frame"
966
                                    " vs [%s] in SDF.\n", colname, (char *)sqlite3_column_text(stmt2, 0),
967
                                    CHAR_ELT(levels, j));
3358 mrmanese 968
                            sqlite3_finalize(stmt2);
3324 mrmanese 969
                            break;
970
                        }
971
                    }
3358 mrmanese 972
                    sqlite3_finalize(stmt2);
3324 mrmanese 973
                }  /* else if class == "ordered" */
974
            } /* if integer */
975
        } /* for loop for column type checking */
976
 
3358 mrmanese 977
        sqlite3_finalize(stmt);
978
        if (i < ncols) {
3324 mrmanese 979
            Rprintf("Error: type mismatch at variable %s\n", CHAR_ELT(names, i));
980
            return ret;
981
        }
982
 
983
        /* create the insert statement */
984
        buflen = sprintf(g_sql_buf[0], "insert into [%s].sdf_data([row name]", iname);
985
        buflen2 = sprintf(g_sql_buf[1], "values(?");
3358 mrmanese 986
        for (i = 0; i < ncols; i++) {
3324 mrmanese 987
            _expand_buf(0, buflen+100);
988
            buflen += sprintf(g_sql_buf[0]+buflen, ",[%s]", CHAR_ELT(names, i));
989
            _expand_buf(1, buflen2+5);
990
            buflen2 += sprintf(g_sql_buf[1]+buflen2, ",?");
991
        }
992
 
993
        _expand_buf(2, buflen + buflen2 + 10);
3358 mrmanese 994
        sprintf(g_sql_buf[2], "%s) %s)", g_sql_buf[0], g_sql_buf[1]);
3324 mrmanese 995
        res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, NULL);
996
        if (_sqlite_error(res)) return ret;
997
 
998
        /* finally, add rows */
3457 mrmanese 999
        rownames = getAttrib(data, R_RowNamesSymbol); /* GET_ROWNAMES(data); */
1000
        nrows = LENGTH(rownames);
1001
        rownames_type = TYPEOF(rownames);
3324 mrmanese 1002
 
3457 mrmanese 1003
        _sqlite_begin;
3324 mrmanese 1004
        for (i = 0; i < nrows; i++) {
3457 mrmanese 1005
            sqlite3_reset(stmt);
1006
            if (rownames_type == STRSXP) {
1007
                rn_str = CHAR_ELT(rownames, i);
1008
            } else if (rownames_type == INTSXP) {
1009
                sprintf(g_sql_buf[1], "%d", INTEGER(rownames)[i]);
1010
                rn_str = g_sql_buf[1];
1011
            } else if (rownames_type == REALSXP) {
1012
                sprintf(g_sql_buf[1], "%f", REAL(rownames)[i]);
1013
                rn_str = g_sql_buf[1];
1014
            } else {
1015
                sprintf(g_sql_buf[1], "%d", i);
1016
                rn_str = g_sql_buf[1];
1017
            }
1018
            sqlite3_bind_text(stmt, 1, rn_str, -1, SQLITE_STATIC);
1019
 
3358 mrmanese 1020
            for (j = 0; j < ncols; j++) {
1021
                col = VECTOR_ELT(data, j);
1022
                switch(types[j]) {
1023
                    case SQLITE_FLOAT:
1024
                        sqlite3_bind_double(stmt, j+2, REAL(col)[i]); break;
1025
                    case SQLITE_TEXT:
1026
                        sqlite3_bind_text(stmt, j+2, CHAR_ELT(col, i), -1, SQLITE_STATIC); break;
1027
                    case SQLITE_INTEGER:
1028
                    default:  /* runtime error if we're wrong */
1029
                        sqlite3_bind_int(stmt, j+2, INTEGER(col)[i]); break;
1030
                }
1031
            }
1032
 
1033
            res = sqlite3_step(stmt);
1034
            if (res != SQLITE_DONE) { /* row name pk conflict */
1035
                for (j = 1; res != SQLITE_DONE; j++) { /* _normally_, j shouldn't overflow */
1036
                    sqlite3_reset(stmt);
3457 mrmanese 1037
                    sprintf(g_sql_buf[2], "%s-%d", rn_str, j);
3358 mrmanese 1038
                    sqlite3_bind_text(stmt, 1, g_sql_buf[2], -1, SQLITE_STATIC);
1039
                    res = sqlite3_step(stmt);
1040
                }
3457 mrmanese 1041
            } 
3324 mrmanese 1042
        }
1043
 
3358 mrmanese 1044
        sqlite3_finalize(stmt);
3457 mrmanese 1045
        _sqlite_commit;
3358 mrmanese 1046
        ret = sdf;
3324 mrmanese 1047
    } else if (strcmp(class,"sqlite.data.frame") == 0) {
1048
    }
1049
 
1050
    return ret;
1051
}
1052
 
1053
 
3358 mrmanese 1054
SEXP sdf_get_iname(SEXP sdf) {
3471 mrmanese 1055
    char *iname, *sql;
1056
    sqlite3_stmt *stmt;
1057
    SEXP ret, names;
1058
 
1059
    iname = SDF_INAME(sdf);
1060
    if (!USE_SDF1(iname, TRUE, FALSE)) return R_NilValue;
1061
 
1062
    sql = "select internal_name, rel_filename from workspace where internal_name=?";
1063
    sqlite3_prepare(g_workspace, sql, -1, &stmt, NULL);
1064
    sqlite3_bind_text(stmt, 1, iname, -1, SQLITE_STATIC);
1065
    sqlite3_step(stmt);
1066
 
1067
    PROTECT(ret = NEW_CHARACTER(2));
1068
    SET_STRING_ELT(ret, 0, mkChar((char *)sqlite3_column_text(stmt, 0)));
1069
    SET_STRING_ELT(ret, 1, mkChar((char *)sqlite3_column_text(stmt, 1)));
1070
 
1071
    PROTECT(names = NEW_CHARACTER(2));
1072
    SET_STRING_ELT(names, 0, mkChar("Internal Name"));
1073
    SET_STRING_ELT(names, 1, mkChar("File"));
1074
 
1075
    SET_NAMES(ret, names);
1076
 
1077
    sqlite3_finalize(stmt);
1078
    UNPROTECT(2);
1079
 
1080
    return ret;
3358 mrmanese 1081
}
4160 mrmanese 1082
 
1083
SEXP sdf_select(SEXP sdf, SEXP select, SEXP where, SEXP limit, SEXP debug) {
1084
    char *iname, *tmp;
1085
    sqlite3_stmt *stmt;
1086
    int buflen0 = 0, buflen1 = 0, len, nrows, res;
1087
    SEXP ret = NULL;
1088
    int dbg = LOGICAL(debug)[0];
1089
 
1090
    iname = SDF_INAME(sdf);
1091
    if (!USE_SDF1(iname, TRUE, FALSE)) return R_NilValue;
1092
 
1093
    /* create the sql to be executed */
1094
 
1095
    /* process select stmt */
1096
    if (select == R_NilValue) {
1097
        buflen0 = sprintf(g_sql_buf[0], "select * from [%s].sdf_data", iname);
1098
    } else if (!IS_CHARACTER(select)) {
1099
        error("select argument is not a string");
1100
    } else {
1101
        tmp = CHAR_ELT(select, 0);
1102
        _expand_buf(0, strlen(tmp)+100);
1103
        buflen0 = sprintf(g_sql_buf[0], "select [row name], %s from [%s].sdf_data", 
1104
                tmp, iname);
1105
    }
1106
 
1107
    /* create separate count() statement, to determine number of rows */
1108
    buflen1 = sprintf(g_sql_buf[1], "select count([row name]) from [%s].sdf_data", iname);
1109
 
1110
    /* process where clause */
1111
    if (where == R_NilValue) {
1112
        /* do nothing */
1113
    } else if (!IS_CHARACTER(where)) {
1114
        error("where argument is not a string");
1115
    } else {
1116
        tmp = CHAR_ELT(where, 0);
1117
        len = strlen(tmp);
1118
        _expand_buf(0, buflen0+len+10);
1119
        buflen0 += sprintf(g_sql_buf[0]+buflen0, " where %s", tmp);
1120
        _expand_buf(1, buflen1+len+10);
1121
        buflen1 += sprintf(g_sql_buf[1]+buflen1, " where %s", tmp);
1122
    }
1123
 
1124
    /* process limit clause */
1125
    if (limit == R_NilValue) {
1126
        /* do nothing */
1127
    } else if (!IS_CHARACTER(limit)) {
1128
        error("limit argument is not a string");
1129
    } else {
1130
        tmp = CHAR_ELT(limit, 0);
1131
        len = strlen(tmp);
1132
        _expand_buf(0, buflen0+len+10);
1133
        buflen0 += sprintf(g_sql_buf[0]+buflen0, " limit %s", tmp);
1134
        _expand_buf(1, buflen1+len+10);
1135
 
1136
        /* limit xxx happens after everything has been selected, and so
1137
         * limit actually limits the count(*) result! not the rows to
1138
         * be counted */
1139
    }
1140
 
1141
    /* test if the "select count(*) " is a valid sql statement */
1142
    res = sqlite3_prepare(g_workspace, g_sql_buf[1], -1, &stmt, NULL);
1143
    if (_sqlite_error(res)) error("Error in SQL select statement.");
1144
 
1145
    /* get the number of rows from the "select count(*) " query */
1146
    sqlite3_step(stmt);
1147
    nrows = sqlite3_column_int(stmt, 0);
1148
    sqlite3_finalize(stmt);
1149
 
1150
    if (nrows == 0) return R_NilValue;
1151
 
1152
    /* test again if actual select stmt is a valid sql statement */
1153
    res = sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, NULL);
1154
    if (_sqlite_error(res)) error("Error in SQL select statement.");
1155
    len = sqlite3_column_count(stmt);
1156
 
1157
    if (dbg)
1158
        Rprintf("sql: %s\nncols: %d, nrows: %d\n", g_sql_buf[0], len, nrows);
1159
 
1160
    if (len < 2) { sqlite3_finalize(stmt); return R_NilValue; }
1161
    else if (len == 2) { /* return a vector */
1162
        int coltype, idx = 0;
1163
        const char *colname;
1164
 
1165
        /* initialize R vector */
1166
        res = sqlite3_step(stmt);
1167
        if (res == SQLITE_ROW)
1168
            idx = _get_vector_index_typed_result(stmt, &ret, 1, nrows, &coltype);
1169
 
1170
        while ((res = sqlite3_step(stmt)) == SQLITE_ROW) {
1171
            idx += _get_vector_index_typed_result(stmt, &ret, 1, idx, &coltype);
1172
        }
1173
 
1174
        if (ret != R_NilValue) {
1175
            if (idx < nrows) ret = _shrink_vector(ret, idx);
1176
            if (coltype == SQLITE_INTEGER) {
1177
                colname = sqlite3_column_name(stmt, 1);
1178
                _get_factor_levels1(iname, colname, ret, TRUE);
1179
            }
1180
            /*UNPROTECT(1); _get_vector_index_typed_result UNPROTECTs already*/
1181
        }
1182
    } else { /* return a data frame */
1183
        --len;  /* _setup_df_sexp1 does not count the preceding [row name] */
1184
        ret = _setup_df_sexp1(stmt, iname, len, nrows, NULL);
1185
        if (ret != R_NilValue) {
1186
            int idx;
1187
 
1188
            for (idx = 0; sqlite3_step(stmt) == SQLITE_ROW && idx < nrows; idx++) {
1189
                _add_row_to_df(ret, stmt, idx, len);
1190
            }
1191
 
1192
            if (idx < nrows) {
1193
                for (int i = 0; i < len; i++) {
1194
                    SET_VECTOR_ELT(ret, i, 
1195
                            _shrink_vector(VECTOR_ELT(ret, i), idx));
1196
                }
1197
            }
1198
 
1199
            SET_CLASS(ret, mkString("data.frame"));
1200
            _set_rownames2(ret);
1201
 
1202
            UNPROTECT(1);
1203
        }
1204
    }
1205
 
1206
    sqlite3_finalize(stmt);
1207
    return ret;
1208
}