The R Project SVN R-packages

Rev

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