The R Project SVN R-packages

Rev

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

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