The R Project SVN R-packages

Rev

Rev 3808 | Rev 4160 | 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 &
154
 * attach factor infos */
3281 mrmanese 155
static SEXP _setup_df_sexp1(sqlite3_stmt *stmt, const char *iname, 
156
        int col_cnt, int row_cnt, int *dup_indices) {
157
    SEXP ret, names, value, class = R_NilValue;
158
    int i, type;
159
    const char *colname, *coltype;
3255 mrmanese 160
 
161
    PROTECT(ret = NEW_LIST(col_cnt));
162
 
3281 mrmanese 163
    /* set up names. */
164
    PROTECT(names = NEW_CHARACTER(col_cnt));
3255 mrmanese 165
    for (i = 0; i < col_cnt; i++) {
3281 mrmanese 166
        colname = sqlite3_column_name(stmt, i+1);  /* +1 bec [row name is 0] */
167
        coltype = sqlite3_column_decltype(stmt, i+1);
168
 
3255 mrmanese 169
        if (dup_indices[i] == 0) {
170
            strcpy(g_sql_buf[1], colname);
171
        } else {
172
            sprintf(g_sql_buf[1], "%s.%d", colname, dup_indices[i]);
173
        }
174
 
3281 mrmanese 175
        SET_STRING_ELT(names, i, mkChar(g_sql_buf[1]));
176
 
177
        if (strcmp(coltype, "text") == 0) {
178
            PROTECT(value = NEW_CHARACTER(row_cnt));
179
        } else if (strcmp(coltype, "double") == 0) {
180
            PROTECT(value = NEW_NUMERIC(row_cnt));
181
        } else if (strcmp(coltype, "bit") == 0) {
182
            PROTECT(value = NEW_LOGICAL(row_cnt));
183
        } else if (strcmp(coltype, "integer") == 0 || 
184
                   strcmp(coltype, "int") == 0) {
185
            PROTECT(value = NEW_INTEGER(row_cnt));
186
            type = _get_factor_levels1(iname, colname, value);
187
            if (type == VAR_FACTOR) {
188
                PROTECT(class = mkString("factor"));
189
                SET_CLASS(value, class);
190
                UNPROTECT(1);
191
            } else if (type == VAR_ORDERED) {
192
                PROTECT(class = NEW_CHARACTER(2));
193
                SET_STRING_ELT(class, 0, mkChar("ordered"));
194
                SET_STRING_ELT(class, 1, mkChar("factor"));
195
                SET_CLASS(value, class);
196
                UNPROTECT(1);
197
            }
198
        } else {
199
            UNPROTECT(2); /* unprotect ret, names */
3808 mrmanese 200
            error("not supported type %s for %s\n", coltype, colname);
3281 mrmanese 201
        }
202
 
203
        SET_VECTOR_ELT(ret, i, value);
204
        UNPROTECT(1); /* unprotect value */
3255 mrmanese 205
 
206
    }
3281 mrmanese 207
    SET_NAMES(ret, names);
208
    UNPROTECT(1); /* unprotect names only */
3255 mrmanese 209
    return ret;
210
}
211
 
3281 mrmanese 212
/* expected that 1st col of stmt is [row name], so we start with index 1 */
213
static int _add_row_to_df(SEXP df, sqlite3_stmt *stmt, int row, int ncols) {
214
    SEXP vec;
3282 mrmanese 215
    int type = -1, is_null, i;
3281 mrmanese 216
    for (i = 1; i <= ncols; i++) {
217
        vec = VECTOR_ELT(df, i-1);
218
        type = TYPEOF(vec);
219
 
220
        is_null = (sqlite3_column_type(stmt, row) == SQLITE_NULL);
221
 
3457 mrmanese 222
        if (type == STRSXP || type == CHARSXP) {
3284 mrmanese 223
            SET_STRING_ELT(vec, row, mkChar((char *)sqlite3_column_text(stmt, i)));
3281 mrmanese 224
        } else if (type == INTSXP) {
225
            INTEGER(vec)[row] = sqlite3_column_int(stmt, i);
226
        } else if (type == REALSXP) {
227
            REAL(vec)[row] = sqlite3_column_double(stmt, i);
228
        } else if (type == LGLSXP) {
229
            LOGICAL(vec)[row] = sqlite3_column_int(stmt, i);
230
        }
231
    }
3282 mrmanese 232
    return type;
3281 mrmanese 233
}
234
 
3457 mrmanese 235
/* set ordinary df row name as numbers */
3281 mrmanese 236
static void _set_rownames2(SEXP df) {
237
    SEXP value = VECTOR_ELT(df, 0);
238
    int len = LENGTH(value), i;
239
    PROTECT(value = NEW_CHARACTER(len));
240
    for (i = 0; i < len; i++) {
241
        sprintf(g_sql_buf[2], "%d", i+1);
242
        SET_STRING_ELT(value, i, mkChar(g_sql_buf[2]));
243
    }
244
 
245
    SET_ROWNAMES(df, value);
246
    UNPROTECT(1);
247
}
248
 
249
 
3255 mrmanese 250
/****************************************************************************
251
 * SDF FUNCTIONS
252
 ****************************************************************************/
253
 
254
SEXP sdf_create_sdf(SEXP df, SEXP name) {
255
    SEXP ret;
3307 mrmanese 256
    char *iname; 
257
    int namelen, res, i, j;
3255 mrmanese 258
 
3307 mrmanese 259
    /* find free name, attach sdf, create sdf_attributes */
3419 mrmanese 260
    iname = _create_sdf_skeleton1(name, &namelen, FALSE);
3251 mrmanese 261
 
3307 mrmanese 262
    if (iname != NULL) {
3255 mrmanese 263
        int sql_len, sql_len2;
3252 mrmanese 264
        sqlite3_stmt *stmt;
265
 
3255 mrmanese 266
        /* create sdf_data table */
3426 mrmanese 267
        SEXP names = GET_NAMES(df), variable, levels, var_class;
3252 mrmanese 268
        int ncols = GET_LENGTH(names), type, *types;
269
        char *col_name, *class, *factor;
270
 
3324 mrmanese 271
        /* variables for adding rownames */
272
        SEXP rownames;
273
        int nrows;
274
        char *row_name;
275
 
3252 mrmanese 276
        /* TODO: put constraints on table after inserting everything? */
277
 
278
 
279
        /* 
280
         * create the create table and insert sql scripts by looping through
281
         * the columns of df
282
         */
283
        types = (int *)R_alloc(ncols, sizeof(int));
284
        sql_len = sprintf(g_sql_buf[0], "create table [%s].sdf_data ([row name] text", iname);
285
        sql_len2 = sprintf(g_sql_buf[1], "insert into [%s].sdf_data values(?", iname);
286
 
287
        for (i = 0; i < ncols; i++) {
288
            col_name = CHAR(STRING_ELT(names, i));
289
 
290
            /* add column definition to the create table sql */
291
            _expand_buf(0, sql_len+strlen(col_name)+10);
292
 
293
            variable = _getListElement(df, col_name);
3426 mrmanese 294
            var_class = GET_CLASS(variable);
295
            class = (var_class == R_NilValue) ? NULL : CHAR(STRING_ELT(var_class, 0));
3252 mrmanese 296
            type = TYPEOF(variable);
297
            types[i] = type;
298
 
299
            sql_len += sprintf(g_sql_buf[0]+sql_len, ", [%s] %s", col_name, 
300
                    _get_column_type(class, type));
301
 
302
            /* add handler to insert table sql */
303
            _expand_buf(1, sql_len+5);
304
            strcpy(g_sql_buf[1]+sql_len2, ",?");
305
            sql_len2 += 2; 
306
 
307
            /* create separate table for factors decode */
3426 mrmanese 308
            if (class != NULL && (strcmp(class, "factor") == 0 || strcmp(class, "ordered") == 0)){
3255 mrmanese 309
                if (_create_factor_table2(iname, class, col_name)) 
310
                    return R_NilValue; /* dup tbl name? */
3252 mrmanese 311
 
3397 mrmanese 312
                _sqlite_exec("begin");
3252 mrmanese 313
                levels = GET_LEVELS(variable);
3255 mrmanese 314
                sprintf(g_sql_buf[2], "insert into [%s].[%s %s] values(?, ?);",
315
                        iname, class, col_name);
316
                res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, NULL);
3252 mrmanese 317
                if (_sqlite_error(res)) return R_NilValue; /* dup tbl name? */
318
 
319
                for (j = 0; j < GET_LENGTH(levels); j++) {
320
                    sqlite3_reset(stmt);
321
                    factor = CHAR(STRING_ELT(levels, j));
322
                    sqlite3_bind_int(stmt, 1, j+1);
3307 mrmanese 323
                    sqlite3_bind_text(stmt, 2, factor, -1, SQLITE_STATIC);
3252 mrmanese 324
                    sqlite3_step(stmt);
325
                }
326
                sqlite3_finalize(stmt);
3397 mrmanese 327
                _sqlite_exec("commit");
3252 mrmanese 328
            }
329
        }
330
 
331
        _expand_buf(0,sql_len+35);
3419 mrmanese 332
        sql_len += sprintf(g_sql_buf[0]+sql_len, ", primary key([row name]));");
333
        /* sql_len += sprintf(g_sql_buf[0]+sql_len, ");"); */
3252 mrmanese 334
        res = _sqlite_exec(g_sql_buf[0]);
335
        if (_sqlite_error(res)) return R_NilValue; /* why? */
336
 
337
        /*
338
         * add the data in df to the sdf
339
         */
3324 mrmanese 340
        rownames = getAttrib(df, R_RowNamesSymbol);
341
        nrows = GET_LENGTH(rownames);
3252 mrmanese 342
 
3397 mrmanese 343
        _sqlite_error(_sqlite_exec("begin"));
3255 mrmanese 344
        sprintf(g_sql_buf[1]+sql_len2, ")");
345
        res = sqlite3_prepare(g_workspace, g_sql_buf[1], -1, &stmt, NULL);
3252 mrmanese 346
 
347
        for (i = 0; i < nrows; i++) {
348
            sqlite3_reset(stmt);
349
 
3324 mrmanese 350
            /* since this is coming from a real dataframe, we're assured that
351
             * the rownames are unique */
352
            if (IS_CHARACTER(rownames)) {
353
                row_name = CHAR(STRING_ELT(rownames, i));
354
                if (*row_name) /* if not empty string */
355
                    sqlite3_bind_text(stmt, 1, row_name, strlen(row_name), SQLITE_STATIC);
356
                else sqlite3_bind_int(stmt, 1, i);
357
            } else if (IS_INTEGER(rownames)) {
358
                sqlite3_bind_int(stmt, 1, INTEGER(rownames)[i]);
359
            } else sqlite3_bind_int(stmt, 1, i);
3252 mrmanese 360
 
361
            for (j = 0; j < ncols; j++) {
362
                variable = VECTOR_ELT(df, j);
363
                switch(types[j]) {
364
                    case INTSXP : 
365
                        sqlite3_bind_int(stmt, j+2, INTEGER(variable)[i]);
366
                        break;
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) {
3308 mrmanese 401
    char *iname;
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) {
3308 mrmanese 429
    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) {
3252 mrmanese 448
    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) {
465
    char *filename = CHAR_ELT(_filename, 0);
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;
3255 mrmanese 485
    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) {
3821 mrmanese 512
        int len;
3255 mrmanese 513
        for (i = 1; i < col_cnt+1; i++) {
3473 mrmanese 514
            colname = sqlite3_column_name(stmt, i);
515
            buflen += sprintf(g_sql_buf[0]+buflen, ",[%s]", colname);
3821 mrmanese 516
            _expand_buf(0, buflen + 100);
3255 mrmanese 517
        }
3281 mrmanese 518
        buflen += sprintf(g_sql_buf[0]+buflen, " from [%s].sdf_data", iname);
519
        col_index_len = col_cnt;
3473 mrmanese 520
        col_indices = (int *)R_alloc(col_cnt, sizeof(int));
521
        dup_indices = (int *)R_alloc(col_cnt, sizeof(int));
3281 mrmanese 522
        for (i = 0; i < col_cnt; i++) { col_indices[i] = i; dup_indices[i] = 0; }
3255 mrmanese 523
    } else if (col == R_NilValue || idxlen < 1) {
524
        sqlite3_finalize(stmt);
525
        return R_NilValue;
526
    } else if (IS_NUMERIC(col)) {
527
        col_indices = (int *)R_alloc(idxlen, sizeof(int));
528
        dup_indices = (int *)R_alloc(idxlen, sizeof(int));
529
        col_index_len = 0;
530
 
531
        for (i = 0; i < idxlen; i++) {
532
            /* no need to correct for 0 base because col 0 is [row name] */
533
            index = ((int) REAL(col)[i]); 
534
            if (index > col_cnt) {
535
                sqlite3_finalize(stmt);
3473 mrmanese 536
                error("undefined columns selected\n");
3255 mrmanese 537
            } else if (index > 0) {
3473 mrmanese 538
                colname = sqlite3_column_name(stmt,index);
539
                buflen += sprintf(g_sql_buf[0]+buflen, ",[%s]", colname);
3821 mrmanese 540
                _expand_buf(0, buflen + 100);
3255 mrmanese 541
                dup_indices[col_index_len] = 0;
542
                for (j = 0; j < col_index_len; j++) {
543
                    if (col_indices[j] == index) dup_indices[col_index_len]++;
544
                }
545
                col_indices[col_index_len++] = index;
546
            } else if (index < 0) {
547
                sqlite3_finalize(stmt);
3473 mrmanese 548
                error("negative indices not supported.\n");
3255 mrmanese 549
            }
550
        }
551
 
552
        if (col_index_len == 0) {
553
            sqlite3_finalize(stmt);
554
            Rprintf("Error: no indices detected??\n");
555
            return R_NilValue;
3281 mrmanese 556
        } else { 
557
            _expand_buf(0, buflen+20+strlen(iname));
558
            buflen += sprintf(g_sql_buf[0]+buflen, " from [%s].sdf_data", iname);
3255 mrmanese 559
        }
560
    } else if (IS_INTEGER(col)) {
561
        /* identical logic with IS_NUMERIC, except that we don't have to cast
562
         * stuffs from SEXP col. the alternative is doing if idxlen times. */
563
        col_indices = (int *)R_alloc(idxlen, sizeof(int));
564
        dup_indices = (int *)R_alloc(idxlen, sizeof(int));
565
        col_index_len = 0;
566
 
567
        for (i = 0; i < idxlen; i++) {
568
            /* no need to correct for 0 base because col 0 is [row name] */
569
            index = INTEGER(col)[i];
570
            if (index > col_cnt) {
571
                sqlite3_finalize(stmt);
3473 mrmanese 572
                error("undefined columns selected\n");
3255 mrmanese 573
            } else if (index > 0) {
3473 mrmanese 574
                colname = sqlite3_column_name(stmt,index);
575
                buflen += sprintf(g_sql_buf[0]+buflen, ",[%s]", colname);
3821 mrmanese 576
                _expand_buf(0, buflen + 100);
3255 mrmanese 577
                dup_indices[col_index_len] = 0;
578
                for (j = 0; j < col_index_len; j++) {
579
                    if (col_indices[j] == index) dup_indices[col_index_len]++;
580
                }
581
                col_indices[col_index_len++] = index;
582
            } else if (index < 0) {
583
                sqlite3_finalize(stmt);
3473 mrmanese 584
                error("negative indices not supported.\n");
3255 mrmanese 585
            }
586
        }
587
 
588
        if (col_index_len == 0) {
589
            sqlite3_finalize(stmt);
3821 mrmanese 590
            error("no valid indices detected");
3281 mrmanese 591
        } else { 
3821 mrmanese 592
            /*Rprintf("debug: col_index_len: %d, idxlen: %d, buf 0: %s\n", col_index_len, idxlen, g_sql_buf[0]);*/
3281 mrmanese 593
            _expand_buf(0, buflen+20+strlen(iname));
594
            buflen += sprintf(g_sql_buf[0]+buflen, " from [%s].sdf_data", iname);
3255 mrmanese 595
        }
596
    } else if (IS_LOGICAL(col)) {
597
        /* recycling stuff, so max column output is the # of cols in the df */
598
        col_indices = (int *)R_alloc(col_cnt, sizeof(int));
599
        dup_indices = (int *)R_alloc(col_cnt, sizeof(int));
600
        col_index_len = 0;
601
        for (i = 0; i < col_cnt; i++) {
602
            if (LOGICAL(col)[i%idxlen]) {
3281 mrmanese 603
                buflen += sprintf(g_sql_buf[0]+buflen, ",[%s]", 
3255 mrmanese 604
                        sqlite3_column_name(stmt,i+1));
3473 mrmanese 605
 
3255 mrmanese 606
                dup_indices[col_index_len] = 0;
607
                col_indices[col_index_len++] = i;
608
            }
3473 mrmanese 609
 
3255 mrmanese 610
        }
611
 
612
        if (col_index_len == 0) {
613
            sqlite3_finalize(stmt);
3473 mrmanese 614
            warning("no column selected.\n");
3255 mrmanese 615
            return R_NilValue;
3281 mrmanese 616
        } else { 
617
            _expand_buf(0, buflen+20+strlen(iname));
618
            buflen += sprintf(g_sql_buf[0]+buflen, " from [%s].sdf_data", iname);
3255 mrmanese 619
        }
620
    } else {
621
        sqlite3_finalize(stmt);
3473 mrmanese 622
        error("don't know how to handle column index.\n");
3255 mrmanese 623
    }
624
 
625
    /* 
3457 mrmanese 626
     * PROCESS ROW INDEX: setup limit or where clause
3255 mrmanese 627
     */
628
    idxlen = LENGTH(row);
3281 mrmanese 629
    if (row == R_NilValue) {
3471 mrmanese 630
        if (col_index_len == 1 && !force_new_df) {
3281 mrmanese 631
            ret = sdf_get_variable(sdf, mkString(sqlite3_column_name(stmt,col_indices[0])));
632
            sqlite3_finalize(stmt);
633
            return ret;
3821 mrmanese 634
        } else if (col_index_len > 1 || (force_new_df && col_index_len == 1)) {
3255 mrmanese 635
            /* create a new SDF, logic similar to sdf_create_sdf */
636
 
637
            /* find a new name. data<n> ? */
3307 mrmanese 638
            char *iname2;
639
            int namelen, sql_len, sql_len2;
3255 mrmanese 640
 
3419 mrmanese 641
            iname2 = _create_sdf_skeleton1(R_NilValue, &namelen, TRUE);
3255 mrmanese 642
 
643
            /* create sdf_data table */
3281 mrmanese 644
            sql_len = sprintf(g_sql_buf[1], "create table [%s].sdf_data ([row name] text", iname2);
645
            sql_len2 = 0;
3255 mrmanese 646
 
647
            for (i = 0; i < col_index_len; i++) {
648
                colname = sqlite3_column_name(stmt, col_indices[i]);
649
                if (dup_indices[i] == 0) {
3281 mrmanese 650
                    sql_len += sprintf(g_sql_buf[1]+sql_len, ", [%s] %s", colname,
3255 mrmanese 651
                            sqlite3_column_decltype(stmt, col_indices[i]));
652
                } else {
653
                    /* un-duplicate col names by appending num, just like R */
3281 mrmanese 654
                    sql_len += sprintf(g_sql_buf[1]+sql_len, ", [%s.%d] %s", colname,
3255 mrmanese 655
                            dup_indices[i], 
656
                            sqlite3_column_decltype(stmt, col_indices[i]));
657
                }
3821 mrmanese 658
                _expand_buf(1, sql_len + 100);
3255 mrmanese 659
 
660
                /* deal with possibly factor columns */
661
                if (_is_factor2(iname, "factor", colname)) {
662
                    /* found a factor column */
3281 mrmanese 663
 
3255 mrmanese 664
                    if (dup_indices[i] == 0)  {
665
                        _copy_factor_levels2("factor", iname, colname, iname2, colname);
666
                    } else {
667
                        sprintf(g_sql_buf[3], "%s.%d", colname, dup_indices[i]);
668
                        _copy_factor_levels2("factor", iname, colname, iname2, 
669
                                g_sql_buf[3]);
670
                    }
671
                }
672
 
673
                /* and deal with ordered factors too... life is hard, then you die */
674
                if (_is_factor2(iname, "ordered", colname)) {
3281 mrmanese 675
 
3255 mrmanese 676
                    if (dup_indices[i] == 0)  {
677
                        _copy_factor_levels2("ordered", iname, colname, iname2, 
678
                                colname);
679
                    } else {
680
                        sprintf(g_sql_buf[3], "%s.%d", colname, dup_indices[i]);
681
                        _copy_factor_levels2("ordered", iname, colname, iname2, 
682
                                g_sql_buf[3]);
683
                    }
684
                }
685
 
686
            }
687
 
688
            /* don't need it anymore */
689
            sqlite3_finalize(stmt);
690
 
691
            /* no table index created, that's for v2 I hope*/
692
            sql_len += sprintf(g_sql_buf[1]+sql_len, ");");
693
            res = _sqlite_exec(g_sql_buf[1]);
3281 mrmanese 694
            if (_sqlite_error(res)) { Rprintf("here? %s\n", g_sql_buf[1]); return R_NilValue; }
3255 mrmanese 695
 
696
            /* insert data (with row names). buf[0] contains a select */
3821 mrmanese 697
            _expand_buf(1, g_sql_buf_sz[0] + 32);
3255 mrmanese 698
            sprintf(g_sql_buf[1], "insert into [%s].sdf_data %s", iname2,
699
                    g_sql_buf[0]);
700
            res = _sqlite_exec(g_sql_buf[1]);
701
            if (_sqlite_error(res)) return R_NilValue;
702
 
3419 mrmanese 703
            /* remove protection */
704
            UNUSE_SDF2(iname2);
705
 
3255 mrmanese 706
            /* create SEXP for the SDF */
707
            ret = _create_sdf_sexp(iname2);
3281 mrmanese 708
            return ret;
3255 mrmanese 709
        } else { sqlite3_finalize(stmt); return R_NilValue; }
710
    } else if (row == R_NilValue || idxlen < 1) {
711
        sqlite3_finalize(stmt);
712
        return R_NilValue;
713
    } else if (IS_NUMERIC(row)) {
714
        sqlite3_finalize(stmt);
715
 
3281 mrmanese 716
        sprintf(g_sql_buf[1], "[%s].sdf_data", iname);
3358 mrmanese 717
        row_cnt = _get_row_count2(g_sql_buf[1], 0);
3281 mrmanese 718
 
3255 mrmanese 719
        /* append " limit ?,1" to the formed select statement */
720
        _expand_buf(0, buflen+10);
3281 mrmanese 721
        buflen += sprintf(g_sql_buf[0]+buflen, " limit ?,1");
722
        /*Rprintf("sql [%d]: %s\n", buflen, g_sql_buf[0]); */
3255 mrmanese 723
 
3281 mrmanese 724
        index = ((int) REAL(row)[0]) - 1;
3255 mrmanese 725
        if (idxlen < 0 && idxlen == 1) return R_NilValue;
726
 
727
        res = sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, 0);
728
        if (_sqlite_error(res)) return R_NilValue;
729
 
730
        sqlite3_bind_int(stmt, 1, index);
731
        res = sqlite3_step(stmt);
732
 
733
        /* create data frame */
3281 mrmanese 734
        ret = _setup_df_sexp1(stmt, iname, col_index_len, idxlen, dup_indices);
735
        if (ret == R_NilValue) { sqlite3_finalize(stmt); return R_NilValue; }
3255 mrmanese 736
 
3281 mrmanese 737
        /* put data in it */
738
        if (index >= 0 && index < row_cnt) {
739
            _add_row_to_df(ret, stmt, row_index_len++, col_index_len);
740
        }
3255 mrmanese 741
 
3281 mrmanese 742
        for (i = 1; i < idxlen; i++) {
743
            sqlite3_reset(stmt);
744
            index = ((int) REAL(row)[i]) - 1;
745
            if (index >= 0 && index < row_cnt) {
746
                sqlite3_bind_int(stmt, 1, index);
747
                res = sqlite3_step(stmt);
748
                _add_row_to_df(ret, stmt, row_index_len++, col_index_len);
749
            }
750
        }
751
        sqlite3_finalize(stmt);
752
 
753
        /* shrink vectors */
754
        if (row_index_len < idxlen) {
755
            for (i = 0; i < col_index_len; i++) {
756
                SET_VECTOR_ELT(ret, i, 
757
                        _shrink_vector(VECTOR_ELT(ret, i), row_index_len));
758
            }
759
        }
760
 
761
        UNPROTECT(1); /* for the ret from _setup_df_sexp1 */
762
    } else if (IS_INTEGER(row)) {
763
        /* same stuff as with IS_INTEGER, except for setting of var index*/
764
        sqlite3_finalize(stmt);
765
 
766
        sprintf(g_sql_buf[1], "[%s].sdf_data", iname);
3358 mrmanese 767
        row_cnt = _get_row_count2(g_sql_buf[1], 0);
3281 mrmanese 768
 
769
        /* append " limit ?,1" to the formed select statement */
770
        _expand_buf(0, buflen+10);
771
        buflen += sprintf(g_sql_buf[0]+buflen, " limit ?,1");
772
 
773
        index = INTEGER(row)[0] - 1;
774
        if (idxlen < 0 && idxlen == 1) return R_NilValue;
775
 
776
        res = sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, 0);
777
        if (_sqlite_error(res)) return R_NilValue;
778
 
779
        sqlite3_bind_int(stmt, 1, index);
780
        res = sqlite3_step(stmt);
781
 
782
        /* create data frame */
783
        ret = _setup_df_sexp1(stmt, iname, col_index_len, idxlen, dup_indices);
784
        if (ret == R_NilValue) { sqlite3_finalize(stmt); return R_NilValue; }
785
 
3255 mrmanese 786
        /* put data in it */
3281 mrmanese 787
        if (index >= 0 && index < row_cnt) {
788
            _add_row_to_df(ret, stmt, row_index_len++, col_index_len);
789
        }
790
 
791
        for (i = 1; i < idxlen; i++) {
792
            sqlite3_reset(stmt);
793
            index = INTEGER(row)[i] - 1;
794
            if (index >= 0 && index < row_cnt) {
795
                sqlite3_bind_int(stmt, 1, index);
796
                res = sqlite3_step(stmt); 
797
                _add_row_to_df(ret, stmt, row_index_len++, col_index_len);
798
            }
799
        }
800
        sqlite3_finalize(stmt);
801
 
802
        /* shrink vectors */
803
        if (row_index_len < idxlen) {
804
            for (i = 0; i < col_index_len; i++) {
805
                SET_VECTOR_ELT(ret, i, 
806
                        _shrink_vector(VECTOR_ELT(ret, i), row_index_len));
807
            }
808
        }
809
        UNPROTECT(1); /* for the ret from _setup_df_sexp1 */
3255 mrmanese 810
    } else if (IS_LOGICAL(row)) {
811
        /* */
3281 mrmanese 812
        sqlite3_finalize(stmt);
813
        int est_row_cnt = 0;
814
 
815
        sprintf(g_sql_buf[1], "[%s].sdf_data", iname);
3358 mrmanese 816
        row_cnt = _get_row_count2(g_sql_buf[1], 0);
3281 mrmanese 817
 
818
        /* append " limit ?,1" to the formed select statement */
819
        _expand_buf(0, buflen+10);
820
        buflen += sprintf(g_sql_buf[0]+buflen, " limit ?,1");
821
 
822
        /* find if there is any TRUE element in the vector */
3282 mrmanese 823
        for (i = 0; i < idxlen && i < row_cnt; i++) {
3281 mrmanese 824
            if (LOGICAL(row)[i]) break;
825
        }
826
 
3282 mrmanese 827
        if (i < idxlen && i < row_cnt) {
3281 mrmanese 828
            est_row_cnt = (idxlen-i) * (row_cnt/idxlen);
829
            if (row_cnt%idxlen > i) est_row_cnt += (row_cnt%idxlen - i);
830
 
831
            res = sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, 0);
832
            if (_sqlite_error(res)) return R_NilValue;
833
 
834
            sqlite3_bind_int(stmt, 1, i);
835
            sqlite3_step(stmt);
836
            ret = _setup_df_sexp1(stmt, iname, col_index_len, est_row_cnt, dup_indices);
837
            _add_row_to_df(ret, stmt, row_index_len++, col_index_len);
838
 
839
            for (i++ ; i < row_cnt; i++) {
840
                if (LOGICAL(row)[i%idxlen]) {
841
                    sqlite3_reset(stmt);
842
                    sqlite3_bind_int(stmt, 1, i);
843
                    sqlite3_step(stmt);
844
                    _add_row_to_df(ret, stmt, row_index_len++, col_index_len);
845
                }
846
            }
847
        }
848
 
849
        sqlite3_finalize(stmt);
850
 
851
        /* shrink vectors */
852
        if (est_row_cnt > 0 && row_index_len < est_row_cnt) {
853
            for (i = 0; i < col_index_len; i++) {
854
                SET_VECTOR_ELT(ret, i, 
855
                        _shrink_vector(VECTOR_ELT(ret, i), row_index_len));
856
            }
857
        }
858
 
859
        UNPROTECT(1); /* for the ret from _setup_df_sexp1 */
3255 mrmanese 860
    }
861
 
3419 mrmanese 862
    UNUSE_SDF2(iname);
863
 
3281 mrmanese 864
    if (ret != R_NilValue && col_index_len > 1) {
3457 mrmanese 865
        SET_CLASS(ret, mkString("data.frame"));
3281 mrmanese 866
        _set_rownames2(ret);
867
    } else if (ret != R_NilValue && col_index_len == 1) {
868
        ret = VECTOR_ELT(ret, 0);
869
    }
3255 mrmanese 870
 
871
    return ret;
872
}
873
 
3324 mrmanese 874
SEXP sdf_rbind(SEXP sdf, SEXP data) {
3457 mrmanese 875
    char *class;
3471 mrmanese 876
    char *iname = SDF_INAME(sdf), *colname;
3358 mrmanese 877
    SEXP ret = R_NilValue, col, names, levels, rownames;
3457 mrmanese 878
    int ncols, buflen, buflen2, i, j, res, nrows, *types, rownames_type;
3324 mrmanese 879
    sqlite3_stmt *stmt;
3358 mrmanese 880
    const char *type;
3471 mrmanese 881
    char *rn_str; 
3281 mrmanese 882
 
3457 mrmanese 883
    class = CHAR_ELT(GET_CLASS(data), 0);
3324 mrmanese 884
    if (strcmp(class,"data.frame") == 0) {
885
        /* check table names, types. variables may not be in same order, as
886
         * long as names and types are identical. */
887
        names = GET_NAMES(data);
3358 mrmanese 888
        ncols = GET_LENGTH(names);
3324 mrmanese 889
 
890
        buflen = sprintf(g_sql_buf[0], "select 1");
3358 mrmanese 891
        for (i = 0; i < ncols; i++) {
3324 mrmanese 892
            _expand_buf(0, buflen + 100);
893
            buflen += sprintf(g_sql_buf[0]+buflen, ",[%s]", CHAR_ELT(names, i));
894
        }
895
        _expand_buf(0, buflen + 100);
3358 mrmanese 896
        sprintf(g_sql_buf[0]+buflen, " from [%s].sdf_data", iname);
3324 mrmanese 897
 
898
        res = sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, NULL);
899
        if (res != SQLITE_OK) { /* column name mismatch */
3457 mrmanese 900
            _sqlite_error(res);
3324 mrmanese 901
            Rprintf("Error: column names should exactly match the names of the SDF.\n");
902
            return ret;
903
        }
904
 
905
        /* now check the type */
3358 mrmanese 906
        types = (int *)R_alloc(ncols, sizeof(int));
907
        for (i = 0; i< ncols; i++) {
908
            type = sqlite3_column_decltype(stmt, i+1); /* +1 bec 1st col is "1" */
3324 mrmanese 909
 
910
            col = VECTOR_ELT(data, i);
3457 mrmanese 911
            /* class = CHAR_ELT(GET_CLASS(col),0); */
3324 mrmanese 912
 
3358 mrmanese 913
            if (strcmp(type, "double") == 0 && IS_NUMERIC(col)) types[i] = SQLITE_FLOAT;
914
            else if (strcmp(type, "text") == 0 && IS_CHARACTER(col)) types[i] = SQLITE_TEXT;
915
            else if (strcmp(type, "int") == 0) { 
916
                types[i] = SQLITE_INTEGER;
917
                if (isUnordered(col)) {  /* test if factor */
918
                    colname = CHAR_ELT(names, i);
3324 mrmanese 919
                    sqlite3_stmt *stmt2;
920
                    if (!_is_factor2(iname, "factor", colname)) break;
921
                    sprintf(g_sql_buf[1], "[%s].[factor %s]", iname, colname);
3358 mrmanese 922
                    nrows = _get_row_count2(g_sql_buf[1], 0);
3324 mrmanese 923
 
3358 mrmanese 924
                    /* levels in sdf must be >= levels in df */
3324 mrmanese 925
                    levels = GET_LEVELS(col);
926
                    if (nrows < GET_LENGTH(levels)) {
927
                        Rprintf("Error: The data frame variable %s has more levels than"
928
                                " its SDF counterpart.\n", colname);
929
                        break;
930
                    }
931
 
3358 mrmanese 932
                    sprintf(g_sql_buf[2], "select label from %s order by level", g_sql_buf[1]);
933
                    res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt2, NULL);
934
                    _sqlite_error(res);
3324 mrmanese 935
 
3358 mrmanese 936
                    for (j = 0; j < GET_LENGTH(levels); j++)  {
3324 mrmanese 937
                        sqlite3_step(stmt2);
3358 mrmanese 938
                        if (strcmp((char *)sqlite3_column_text(stmt2, 0), CHAR_ELT(levels, j)) != 0) {
3324 mrmanese 939
                            Rprintf("Error: Level label mismatch in variable %s, [%s] in data frame"
940
                                    " vs [%s] in SDF.\n", colname, (char *)sqlite3_column_text(stmt2, 0),
941
                                    CHAR_ELT(levels, j));
3358 mrmanese 942
                            sqlite3_finalize(stmt2);
3324 mrmanese 943
                            break;
944
                        }
945
                    }
3358 mrmanese 946
                    sqlite3_finalize(stmt2);
947
                } else if (isOrdered(col)) { /* same with ordered */
948
                    colname = CHAR_ELT(names, i);
3324 mrmanese 949
                    sqlite3_stmt *stmt2;
950
                    if (!_is_factor2(iname, "ordered", colname)) break;
951
                    sprintf(g_sql_buf[1], "[%s].[ordered %s]", iname, colname);
3358 mrmanese 952
                    nrows = _get_row_count2(g_sql_buf[1], 0);
3324 mrmanese 953
 
3358 mrmanese 954
                    /* levels in sdf must be >= levels in df */
3324 mrmanese 955
                    levels = GET_LEVELS(col);
956
                    if (nrows < GET_LENGTH(levels)) {
957
                        Rprintf("Error: The data frame variable %s has more levels than"
958
                                " its SDF counterpart.\n", colname);
959
                        break;
960
                    }
961
 
3358 mrmanese 962
                    sprintf(g_sql_buf[2], "select label from %s order by level", g_sql_buf[1]);
3324 mrmanese 963
                    sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt2, NULL);
964
 
3358 mrmanese 965
                    for (j = 0; j < GET_LENGTH(levels); j++)  {
3324 mrmanese 966
                        sqlite3_step(stmt2);
3358 mrmanese 967
                        if (strcmp((char *)sqlite3_column_text(stmt2, 0), CHAR_ELT(levels, j)) != 0) {
3324 mrmanese 968
                            Rprintf("Error: Level label mismatch in variable %s, [%s] in data frame"
969
                                    " vs [%s] in SDF.\n", colname, (char *)sqlite3_column_text(stmt2, 0),
970
                                    CHAR_ELT(levels, j));
3358 mrmanese 971
                            sqlite3_finalize(stmt2);
3324 mrmanese 972
                            break;
973
                        }
974
                    }
3358 mrmanese 975
                    sqlite3_finalize(stmt2);
3324 mrmanese 976
                }  /* else if class == "ordered" */
977
            } /* if integer */
978
        } /* for loop for column type checking */
979
 
3358 mrmanese 980
        sqlite3_finalize(stmt);
981
        if (i < ncols) {
3324 mrmanese 982
            Rprintf("Error: type mismatch at variable %s\n", CHAR_ELT(names, i));
983
            return ret;
984
        }
985
 
986
        /* create the insert statement */
987
        buflen = sprintf(g_sql_buf[0], "insert into [%s].sdf_data([row name]", iname);
988
        buflen2 = sprintf(g_sql_buf[1], "values(?");
3358 mrmanese 989
        for (i = 0; i < ncols; i++) {
3324 mrmanese 990
            _expand_buf(0, buflen+100);
991
            buflen += sprintf(g_sql_buf[0]+buflen, ",[%s]", CHAR_ELT(names, i));
992
            _expand_buf(1, buflen2+5);
993
            buflen2 += sprintf(g_sql_buf[1]+buflen2, ",?");
994
        }
995
 
996
        _expand_buf(2, buflen + buflen2 + 10);
3358 mrmanese 997
        sprintf(g_sql_buf[2], "%s) %s)", g_sql_buf[0], g_sql_buf[1]);
3324 mrmanese 998
        res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, NULL);
999
        if (_sqlite_error(res)) return ret;
1000
 
1001
        /* finally, add rows */
3457 mrmanese 1002
        rownames = getAttrib(data, R_RowNamesSymbol); /* GET_ROWNAMES(data); */
1003
        nrows = LENGTH(rownames);
1004
        rownames_type = TYPEOF(rownames);
3324 mrmanese 1005
 
3457 mrmanese 1006
        _sqlite_begin;
3324 mrmanese 1007
        for (i = 0; i < nrows; i++) {
3457 mrmanese 1008
            sqlite3_reset(stmt);
1009
            if (rownames_type == STRSXP) {
1010
                rn_str = CHAR_ELT(rownames, i);
1011
            } else if (rownames_type == INTSXP) {
1012
                sprintf(g_sql_buf[1], "%d", INTEGER(rownames)[i]);
1013
                rn_str = g_sql_buf[1];
1014
            } else if (rownames_type == REALSXP) {
1015
                sprintf(g_sql_buf[1], "%f", REAL(rownames)[i]);
1016
                rn_str = g_sql_buf[1];
1017
            } else {
1018
                sprintf(g_sql_buf[1], "%d", i);
1019
                rn_str = g_sql_buf[1];
1020
            }
1021
            sqlite3_bind_text(stmt, 1, rn_str, -1, SQLITE_STATIC);
1022
 
3358 mrmanese 1023
            for (j = 0; j < ncols; j++) {
1024
                col = VECTOR_ELT(data, j);
1025
                switch(types[j]) {
1026
                    case SQLITE_FLOAT:
1027
                        sqlite3_bind_double(stmt, j+2, REAL(col)[i]); break;
1028
                    case SQLITE_TEXT:
1029
                        sqlite3_bind_text(stmt, j+2, CHAR_ELT(col, i), -1, SQLITE_STATIC); break;
1030
                    case SQLITE_INTEGER:
1031
                    default:  /* runtime error if we're wrong */
1032
                        sqlite3_bind_int(stmt, j+2, INTEGER(col)[i]); break;
1033
                }
1034
            }
1035
 
1036
            res = sqlite3_step(stmt);
1037
            if (res != SQLITE_DONE) { /* row name pk conflict */
1038
                for (j = 1; res != SQLITE_DONE; j++) { /* _normally_, j shouldn't overflow */
1039
                    sqlite3_reset(stmt);
3457 mrmanese 1040
                    sprintf(g_sql_buf[2], "%s-%d", rn_str, j);
3358 mrmanese 1041
                    sqlite3_bind_text(stmt, 1, g_sql_buf[2], -1, SQLITE_STATIC);
1042
                    res = sqlite3_step(stmt);
1043
                }
3457 mrmanese 1044
            } 
3324 mrmanese 1045
        }
1046
 
3358 mrmanese 1047
        sqlite3_finalize(stmt);
3457 mrmanese 1048
        _sqlite_commit;
3358 mrmanese 1049
        ret = sdf;
3324 mrmanese 1050
    } else if (strcmp(class,"sqlite.data.frame") == 0) {
1051
    }
1052
 
1053
    return ret;
1054
}
1055
 
1056
 
3358 mrmanese 1057
SEXP sdf_get_iname(SEXP sdf) {
3471 mrmanese 1058
    char *iname, *sql;
1059
    sqlite3_stmt *stmt;
1060
    SEXP ret, names;
1061
 
1062
    iname = SDF_INAME(sdf);
1063
    if (!USE_SDF1(iname, TRUE, FALSE)) return R_NilValue;
1064
 
1065
    sql = "select internal_name, rel_filename from workspace where internal_name=?";
1066
    sqlite3_prepare(g_workspace, sql, -1, &stmt, NULL);
1067
    sqlite3_bind_text(stmt, 1, iname, -1, SQLITE_STATIC);
1068
    sqlite3_step(stmt);
1069
 
1070
    PROTECT(ret = NEW_CHARACTER(2));
1071
    SET_STRING_ELT(ret, 0, mkChar((char *)sqlite3_column_text(stmt, 0)));
1072
    SET_STRING_ELT(ret, 1, mkChar((char *)sqlite3_column_text(stmt, 1)));
1073
 
1074
    PROTECT(names = NEW_CHARACTER(2));
1075
    SET_STRING_ELT(names, 0, mkChar("Internal Name"));
1076
    SET_STRING_ELT(names, 1, mkChar("File"));
1077
 
1078
    SET_NAMES(ret, names);
1079
 
1080
    sqlite3_finalize(stmt);
1081
    UNPROTECT(2);
1082
 
1083
    return ret;
3358 mrmanese 1084
}