The R Project SVN R-packages

Rev

Rev 3457 | Rev 3473 | 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]",
3255 mrmanese 137
                iname_src, factor_type, colname_src, iname_dst, factor_type,
138
                colname_dst);
139
        res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, 0);
3282 mrmanese 140
        if (res == SQLITE_OK) 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];
3255 mrmanese 487
 
3471 mrmanese 488
    if (!USE_SDF1(iname, TRUE, TRUE)) return R_NilValue;
489
 
3281 mrmanese 490
    sprintf(g_sql_buf[0], "select * from [%s].sdf_data ", iname);
3255 mrmanese 491
    res = sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, 0);
492
    if (_sqlite_error(res)) return R_NilValue;
493
 
494
    buflen = sprintf(g_sql_buf[0], "select [row name]");
495
    idxlen = LENGTH(col);
496
    col_cnt = sqlite3_column_count(stmt) - 1;
497
 
498
    /*
3457 mrmanese 499
     * PROCESS COLUMN INDEX: set columns in the select statement
3255 mrmanese 500
     */
3281 mrmanese 501
    if (col == R_NilValue) {
3255 mrmanese 502
        for (i = 1; i < col_cnt+1; i++) {
3281 mrmanese 503
            buflen += sprintf(g_sql_buf[0]+buflen, ",[%s]", 
3255 mrmanese 504
                    sqlite3_column_name(stmt, i)); 
505
        }
3281 mrmanese 506
        _expand_buf(0, buflen+20+strlen(iname));
507
        buflen += sprintf(g_sql_buf[0]+buflen, " from [%s].sdf_data", iname);
508
        col_index_len = col_cnt;
509
        col_indices = (int *)R_alloc(idxlen, sizeof(int));
510
        dup_indices = (int *)R_alloc(idxlen, sizeof(int));
511
        for (i = 0; i < col_cnt; i++) { col_indices[i] = i; dup_indices[i] = 0; }
3255 mrmanese 512
    } else if (col == R_NilValue || idxlen < 1) {
513
        sqlite3_finalize(stmt);
514
        return R_NilValue;
515
    } else if (IS_NUMERIC(col)) {
516
        col_indices = (int *)R_alloc(idxlen, sizeof(int));
517
        dup_indices = (int *)R_alloc(idxlen, sizeof(int));
518
        col_index_len = 0;
519
 
520
        for (i = 0; i < idxlen; i++) {
521
            /* no need to correct for 0 base because col 0 is [row name] */
522
            index = ((int) REAL(col)[i]); 
523
            if (index > col_cnt) {
524
                sqlite3_finalize(stmt);
525
                Rprintf("Error: undefined columns selected\n");
526
                return R_NilValue;
527
            } else if (index > 0) {
3281 mrmanese 528
                buflen += sprintf(g_sql_buf[0]+buflen, ",[%s]", 
3255 mrmanese 529
                        sqlite3_column_name(stmt,index));
530
                dup_indices[col_index_len] = 0;
531
                for (j = 0; j < col_index_len; j++) {
532
                    if (col_indices[j] == index) dup_indices[col_index_len]++;
533
                }
534
                col_indices[col_index_len++] = index;
535
            } else if (index < 0) {
536
                sqlite3_finalize(stmt);
537
                Rprintf("Error: negative indices not supported.\n");
538
                return R_NilValue;
539
            }
540
        }
541
 
542
        if (col_index_len == 0) {
543
            sqlite3_finalize(stmt);
544
            Rprintf("Error: no indices detected??\n");
545
            return R_NilValue;
3281 mrmanese 546
        } else { 
547
            _expand_buf(0, buflen+20+strlen(iname));
548
            buflen += sprintf(g_sql_buf[0]+buflen, " from [%s].sdf_data", iname);
3255 mrmanese 549
        }
550
    } else if (IS_INTEGER(col)) {
551
        /* identical logic with IS_NUMERIC, except that we don't have to cast
552
         * stuffs from SEXP col. the alternative is doing if idxlen times. */
553
        col_indices = (int *)R_alloc(idxlen, sizeof(int));
554
        dup_indices = (int *)R_alloc(idxlen, sizeof(int));
555
        col_index_len = 0;
556
 
557
        for (i = 0; i < idxlen; i++) {
558
            /* no need to correct for 0 base because col 0 is [row name] */
559
            index = INTEGER(col)[i];
560
            if (index > col_cnt) {
561
                sqlite3_finalize(stmt);
562
                Rprintf("Error: undefined columns selected\n");
563
                return R_NilValue;
564
            } else if (index > 0) {
3281 mrmanese 565
                buflen += sprintf(g_sql_buf[0]+buflen, ",[%s]", 
3255 mrmanese 566
                        sqlite3_column_name(stmt,index));
567
                dup_indices[col_index_len] = 0;
568
                for (j = 0; j < col_index_len; j++) {
569
                    if (col_indices[j] == index) dup_indices[col_index_len]++;
570
                }
571
                col_indices[col_index_len++] = index;
572
            } else if (index < 0) {
573
                sqlite3_finalize(stmt);
574
                Rprintf("Error: negative indices not supported.\n");
575
                return R_NilValue;
576
            }
577
        }
578
 
579
        if (col_index_len == 0) {
580
            sqlite3_finalize(stmt);
581
            Rprintf("Error: no indices detected??\n");
582
            return R_NilValue;
3281 mrmanese 583
        } else { 
584
            _expand_buf(0, buflen+20+strlen(iname));
585
            buflen += sprintf(g_sql_buf[0]+buflen, " from [%s].sdf_data", iname);
3255 mrmanese 586
        }
587
    } else if (IS_LOGICAL(col)) {
588
        /* recycling stuff, so max column output is the # of cols in the df */
589
        col_indices = (int *)R_alloc(col_cnt, sizeof(int));
590
        dup_indices = (int *)R_alloc(col_cnt, sizeof(int));
591
        col_index_len = 0;
592
        for (i = 0; i < col_cnt; i++) {
593
            if (LOGICAL(col)[i%idxlen]) {
3281 mrmanese 594
                buflen += sprintf(g_sql_buf[0]+buflen, ",[%s]", 
3255 mrmanese 595
                        sqlite3_column_name(stmt,i+1));
596
                dup_indices[col_index_len] = 0;
597
                col_indices[col_index_len++] = i;
598
            }
599
        }
600
 
601
        if (col_index_len == 0) {
602
            sqlite3_finalize(stmt);
603
            Rprintf("Warning: no column selected.\n");
604
            return R_NilValue;
3281 mrmanese 605
        } else { 
606
            _expand_buf(0, buflen+20+strlen(iname));
607
            buflen += sprintf(g_sql_buf[0]+buflen, " from [%s].sdf_data", iname);
3255 mrmanese 608
        }
609
    } else {
610
        sqlite3_finalize(stmt);
611
        Rprintf("Error: don't know how to handle column index.\n");
612
        return R_NilValue;
613
    }
614
 
615
    /* 
3457 mrmanese 616
     * PROCESS ROW INDEX: setup limit or where clause
3255 mrmanese 617
     */
618
    idxlen = LENGTH(row);
3281 mrmanese 619
    if (row == R_NilValue) {
3471 mrmanese 620
        if (col_index_len == 1 && !force_new_df) {
3281 mrmanese 621
            ret = sdf_get_variable(sdf, mkString(sqlite3_column_name(stmt,col_indices[0])));
622
            sqlite3_finalize(stmt);
623
            return ret;
3471 mrmanese 624
        } if (col_index_len > 1 || (force_new_df && col_index_len == 1)) {
3255 mrmanese 625
            /* create a new SDF, logic similar to sdf_create_sdf */
626
 
627
            /* find a new name. data<n> ? */
3307 mrmanese 628
            char *iname2;
3281 mrmanese 629
            const char *colname;
3307 mrmanese 630
            int namelen, sql_len, sql_len2;
3255 mrmanese 631
 
3419 mrmanese 632
            iname2 = _create_sdf_skeleton1(R_NilValue, &namelen, TRUE);
3255 mrmanese 633
 
634
            /* create sdf_data table */
3281 mrmanese 635
            sql_len = sprintf(g_sql_buf[1], "create table [%s].sdf_data ([row name] text", iname2);
636
            sql_len2 = 0;
3255 mrmanese 637
 
638
            for (i = 0; i < col_index_len; i++) {
639
                colname = sqlite3_column_name(stmt, col_indices[i]);
640
                if (dup_indices[i] == 0) {
3281 mrmanese 641
                    sql_len += sprintf(g_sql_buf[1]+sql_len, ", [%s] %s", colname,
3255 mrmanese 642
                            sqlite3_column_decltype(stmt, col_indices[i]));
643
                } else {
644
                    /* un-duplicate col names by appending num, just like R */
3281 mrmanese 645
                    sql_len += sprintf(g_sql_buf[1]+sql_len, ", [%s.%d] %s", colname,
3255 mrmanese 646
                            dup_indices[i], 
647
                            sqlite3_column_decltype(stmt, col_indices[i]));
648
                }
649
 
650
                /* deal with possibly factor columns */
651
                if (_is_factor2(iname, "factor", colname)) {
652
                    /* found a factor column */
3281 mrmanese 653
 
3255 mrmanese 654
                    if (dup_indices[i] == 0)  {
655
                        _copy_factor_levels2("factor", iname, colname, iname2, colname);
656
                    } else {
657
                        sprintf(g_sql_buf[3], "%s.%d", colname, dup_indices[i]);
658
                        _copy_factor_levels2("factor", iname, colname, iname2, 
659
                                g_sql_buf[3]);
660
                    }
661
                }
662
 
663
                /* and deal with ordered factors too... life is hard, then you die */
664
                if (_is_factor2(iname, "ordered", colname)) {
3281 mrmanese 665
 
3255 mrmanese 666
                    if (dup_indices[i] == 0)  {
667
                        _copy_factor_levels2("ordered", iname, colname, iname2, 
668
                                colname);
669
                    } else {
670
                        sprintf(g_sql_buf[3], "%s.%d", colname, dup_indices[i]);
671
                        _copy_factor_levels2("ordered", iname, colname, iname2, 
672
                                g_sql_buf[3]);
673
                    }
674
                }
675
 
676
            }
677
 
678
            /* don't need it anymore */
679
            sqlite3_finalize(stmt);
680
 
681
            /* no table index created, that's for v2 I hope*/
682
            sql_len += sprintf(g_sql_buf[1]+sql_len, ");");
683
            res = _sqlite_exec(g_sql_buf[1]);
3281 mrmanese 684
            if (_sqlite_error(res)) { Rprintf("here? %s\n", g_sql_buf[1]); return R_NilValue; }
3255 mrmanese 685
 
686
            /* insert data (with row names). buf[0] contains a select */
687
            sprintf(g_sql_buf[1], "insert into [%s].sdf_data %s", iname2,
688
                    g_sql_buf[0]);
689
            res = _sqlite_exec(g_sql_buf[1]);
690
            if (_sqlite_error(res)) return R_NilValue;
691
 
3419 mrmanese 692
            /* remove protection */
693
            UNUSE_SDF2(iname2);
694
 
3255 mrmanese 695
            /* create SEXP for the SDF */
696
            ret = _create_sdf_sexp(iname2);
3281 mrmanese 697
            return ret;
3255 mrmanese 698
        } else { sqlite3_finalize(stmt); return R_NilValue; }
699
    } else if (row == R_NilValue || idxlen < 1) {
700
        sqlite3_finalize(stmt);
701
        return R_NilValue;
702
    } else if (IS_NUMERIC(row)) {
703
        sqlite3_finalize(stmt);
704
 
3281 mrmanese 705
        sprintf(g_sql_buf[1], "[%s].sdf_data", iname);
3358 mrmanese 706
        row_cnt = _get_row_count2(g_sql_buf[1], 0);
3281 mrmanese 707
 
3255 mrmanese 708
        /* append " limit ?,1" to the formed select statement */
709
        _expand_buf(0, buflen+10);
3281 mrmanese 710
        buflen += sprintf(g_sql_buf[0]+buflen, " limit ?,1");
711
        /*Rprintf("sql [%d]: %s\n", buflen, g_sql_buf[0]); */
3255 mrmanese 712
 
3281 mrmanese 713
        index = ((int) REAL(row)[0]) - 1;
3255 mrmanese 714
        if (idxlen < 0 && idxlen == 1) return R_NilValue;
715
 
716
        res = sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, 0);
717
        if (_sqlite_error(res)) return R_NilValue;
718
 
719
        sqlite3_bind_int(stmt, 1, index);
720
        res = sqlite3_step(stmt);
721
 
722
        /* create data frame */
3281 mrmanese 723
        ret = _setup_df_sexp1(stmt, iname, col_index_len, idxlen, dup_indices);
724
        if (ret == R_NilValue) { sqlite3_finalize(stmt); return R_NilValue; }
3255 mrmanese 725
 
3281 mrmanese 726
        /* put data in it */
727
        if (index >= 0 && index < row_cnt) {
728
            _add_row_to_df(ret, stmt, row_index_len++, col_index_len);
729
        }
3255 mrmanese 730
 
3281 mrmanese 731
        for (i = 1; i < idxlen; i++) {
732
            sqlite3_reset(stmt);
733
            index = ((int) REAL(row)[i]) - 1;
734
            if (index >= 0 && index < row_cnt) {
735
                sqlite3_bind_int(stmt, 1, index);
736
                res = sqlite3_step(stmt);
737
                _add_row_to_df(ret, stmt, row_index_len++, col_index_len);
738
            }
739
        }
740
        sqlite3_finalize(stmt);
741
 
742
        /* shrink vectors */
743
        if (row_index_len < idxlen) {
744
            for (i = 0; i < col_index_len; i++) {
745
                SET_VECTOR_ELT(ret, i, 
746
                        _shrink_vector(VECTOR_ELT(ret, i), row_index_len));
747
            }
748
        }
749
 
750
        UNPROTECT(1); /* for the ret from _setup_df_sexp1 */
751
    } else if (IS_INTEGER(row)) {
752
        /* same stuff as with IS_INTEGER, except for setting of var index*/
753
        sqlite3_finalize(stmt);
754
 
755
        sprintf(g_sql_buf[1], "[%s].sdf_data", iname);
3358 mrmanese 756
        row_cnt = _get_row_count2(g_sql_buf[1], 0);
3281 mrmanese 757
 
758
        /* append " limit ?,1" to the formed select statement */
759
        _expand_buf(0, buflen+10);
760
        buflen += sprintf(g_sql_buf[0]+buflen, " limit ?,1");
761
 
762
        index = INTEGER(row)[0] - 1;
763
        if (idxlen < 0 && idxlen == 1) return R_NilValue;
764
 
765
        res = sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, 0);
766
        if (_sqlite_error(res)) return R_NilValue;
767
 
768
        sqlite3_bind_int(stmt, 1, index);
769
        res = sqlite3_step(stmt);
770
 
771
        /* create data frame */
772
        ret = _setup_df_sexp1(stmt, iname, col_index_len, idxlen, dup_indices);
773
        if (ret == R_NilValue) { sqlite3_finalize(stmt); return R_NilValue; }
774
 
3255 mrmanese 775
        /* put data in it */
3281 mrmanese 776
        if (index >= 0 && index < row_cnt) {
777
            _add_row_to_df(ret, stmt, row_index_len++, col_index_len);
778
        }
779
 
780
        for (i = 1; i < idxlen; i++) {
781
            sqlite3_reset(stmt);
782
            index = INTEGER(row)[i] - 1;
783
            if (index >= 0 && index < row_cnt) {
784
                sqlite3_bind_int(stmt, 1, index);
785
                res = sqlite3_step(stmt); 
786
                _add_row_to_df(ret, stmt, row_index_len++, col_index_len);
787
            }
788
        }
789
        sqlite3_finalize(stmt);
790
 
791
        /* shrink vectors */
792
        if (row_index_len < idxlen) {
793
            for (i = 0; i < col_index_len; i++) {
794
                SET_VECTOR_ELT(ret, i, 
795
                        _shrink_vector(VECTOR_ELT(ret, i), row_index_len));
796
            }
797
        }
798
        UNPROTECT(1); /* for the ret from _setup_df_sexp1 */
3255 mrmanese 799
    } else if (IS_LOGICAL(row)) {
800
        /* */
3281 mrmanese 801
        sqlite3_finalize(stmt);
802
        int est_row_cnt = 0;
803
 
804
        sprintf(g_sql_buf[1], "[%s].sdf_data", iname);
3358 mrmanese 805
        row_cnt = _get_row_count2(g_sql_buf[1], 0);
3281 mrmanese 806
 
807
        /* append " limit ?,1" to the formed select statement */
808
        _expand_buf(0, buflen+10);
809
        buflen += sprintf(g_sql_buf[0]+buflen, " limit ?,1");
810
 
811
        /* find if there is any TRUE element in the vector */
3282 mrmanese 812
        for (i = 0; i < idxlen && i < row_cnt; i++) {
3281 mrmanese 813
            if (LOGICAL(row)[i]) break;
814
        }
815
 
3282 mrmanese 816
        if (i < idxlen && i < row_cnt) {
3281 mrmanese 817
            est_row_cnt = (idxlen-i) * (row_cnt/idxlen);
818
            if (row_cnt%idxlen > i) est_row_cnt += (row_cnt%idxlen - i);
819
 
820
            res = sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, 0);
821
            if (_sqlite_error(res)) return R_NilValue;
822
 
823
            sqlite3_bind_int(stmt, 1, i);
824
            sqlite3_step(stmt);
825
            ret = _setup_df_sexp1(stmt, iname, col_index_len, est_row_cnt, dup_indices);
826
            _add_row_to_df(ret, stmt, row_index_len++, col_index_len);
827
 
828
            for (i++ ; i < row_cnt; i++) {
829
                if (LOGICAL(row)[i%idxlen]) {
830
                    sqlite3_reset(stmt);
831
                    sqlite3_bind_int(stmt, 1, i);
832
                    sqlite3_step(stmt);
833
                    _add_row_to_df(ret, stmt, row_index_len++, col_index_len);
834
                }
835
            }
836
        }
837
 
838
        sqlite3_finalize(stmt);
839
 
840
        /* shrink vectors */
841
        if (est_row_cnt > 0 && row_index_len < est_row_cnt) {
842
            for (i = 0; i < col_index_len; i++) {
843
                SET_VECTOR_ELT(ret, i, 
844
                        _shrink_vector(VECTOR_ELT(ret, i), row_index_len));
845
            }
846
        }
847
 
848
        UNPROTECT(1); /* for the ret from _setup_df_sexp1 */
3255 mrmanese 849
    }
850
 
3419 mrmanese 851
    UNUSE_SDF2(iname);
852
 
3281 mrmanese 853
    if (ret != R_NilValue && col_index_len > 1) {
3457 mrmanese 854
        SET_CLASS(ret, mkString("data.frame"));
3281 mrmanese 855
        _set_rownames2(ret);
856
    } else if (ret != R_NilValue && col_index_len == 1) {
857
        ret = VECTOR_ELT(ret, 0);
858
    }
3255 mrmanese 859
 
860
    return ret;
861
}
862
 
3324 mrmanese 863
SEXP sdf_rbind(SEXP sdf, SEXP data) {
3457 mrmanese 864
    char *class;
3471 mrmanese 865
    char *iname = SDF_INAME(sdf), *colname;
3358 mrmanese 866
    SEXP ret = R_NilValue, col, names, levels, rownames;
3457 mrmanese 867
    int ncols, buflen, buflen2, i, j, res, nrows, *types, rownames_type;
3324 mrmanese 868
    sqlite3_stmt *stmt;
3358 mrmanese 869
    const char *type;
3471 mrmanese 870
    char *rn_str; 
3281 mrmanese 871
 
3457 mrmanese 872
    class = CHAR_ELT(GET_CLASS(data), 0);
3324 mrmanese 873
    if (strcmp(class,"data.frame") == 0) {
874
        /* check table names, types. variables may not be in same order, as
875
         * long as names and types are identical. */
876
        names = GET_NAMES(data);
3358 mrmanese 877
        ncols = GET_LENGTH(names);
3324 mrmanese 878
 
879
        buflen = sprintf(g_sql_buf[0], "select 1");
3358 mrmanese 880
        for (i = 0; i < ncols; i++) {
3324 mrmanese 881
            _expand_buf(0, buflen + 100);
882
            buflen += sprintf(g_sql_buf[0]+buflen, ",[%s]", CHAR_ELT(names, i));
883
        }
884
        _expand_buf(0, buflen + 100);
3358 mrmanese 885
        sprintf(g_sql_buf[0]+buflen, " from [%s].sdf_data", iname);
3324 mrmanese 886
 
887
        res = sqlite3_prepare(g_workspace, g_sql_buf[0], -1, &stmt, NULL);
888
        if (res != SQLITE_OK) { /* column name mismatch */
3457 mrmanese 889
            _sqlite_error(res);
3324 mrmanese 890
            Rprintf("Error: column names should exactly match the names of the SDF.\n");
891
            return ret;
892
        }
893
 
894
        /* now check the type */
3358 mrmanese 895
        types = (int *)R_alloc(ncols, sizeof(int));
896
        for (i = 0; i< ncols; i++) {
897
            type = sqlite3_column_decltype(stmt, i+1); /* +1 bec 1st col is "1" */
3324 mrmanese 898
 
899
            col = VECTOR_ELT(data, i);
3457 mrmanese 900
            /* class = CHAR_ELT(GET_CLASS(col),0); */
3324 mrmanese 901
 
3358 mrmanese 902
            if (strcmp(type, "double") == 0 && IS_NUMERIC(col)) types[i] = SQLITE_FLOAT;
903
            else if (strcmp(type, "text") == 0 && IS_CHARACTER(col)) types[i] = SQLITE_TEXT;
904
            else if (strcmp(type, "int") == 0) { 
905
                types[i] = SQLITE_INTEGER;
906
                if (isUnordered(col)) {  /* test if factor */
907
                    colname = CHAR_ELT(names, i);
3324 mrmanese 908
                    sqlite3_stmt *stmt2;
909
                    if (!_is_factor2(iname, "factor", colname)) break;
910
                    sprintf(g_sql_buf[1], "[%s].[factor %s]", iname, colname);
3358 mrmanese 911
                    nrows = _get_row_count2(g_sql_buf[1], 0);
3324 mrmanese 912
 
3358 mrmanese 913
                    /* levels in sdf must be >= levels in df */
3324 mrmanese 914
                    levels = GET_LEVELS(col);
915
                    if (nrows < GET_LENGTH(levels)) {
916
                        Rprintf("Error: The data frame variable %s has more levels than"
917
                                " its SDF counterpart.\n", colname);
918
                        break;
919
                    }
920
 
3358 mrmanese 921
                    sprintf(g_sql_buf[2], "select label from %s order by level", g_sql_buf[1]);
922
                    res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt2, NULL);
923
                    _sqlite_error(res);
3324 mrmanese 924
 
3358 mrmanese 925
                    for (j = 0; j < GET_LENGTH(levels); j++)  {
3324 mrmanese 926
                        sqlite3_step(stmt2);
3358 mrmanese 927
                        if (strcmp((char *)sqlite3_column_text(stmt2, 0), CHAR_ELT(levels, j)) != 0) {
3324 mrmanese 928
                            Rprintf("Error: Level label mismatch in variable %s, [%s] in data frame"
929
                                    " vs [%s] in SDF.\n", colname, (char *)sqlite3_column_text(stmt2, 0),
930
                                    CHAR_ELT(levels, j));
3358 mrmanese 931
                            sqlite3_finalize(stmt2);
3324 mrmanese 932
                            break;
933
                        }
934
                    }
3358 mrmanese 935
                    sqlite3_finalize(stmt2);
936
                } else if (isOrdered(col)) { /* same with ordered */
937
                    colname = CHAR_ELT(names, i);
3324 mrmanese 938
                    sqlite3_stmt *stmt2;
939
                    if (!_is_factor2(iname, "ordered", colname)) break;
940
                    sprintf(g_sql_buf[1], "[%s].[ordered %s]", iname, colname);
3358 mrmanese 941
                    nrows = _get_row_count2(g_sql_buf[1], 0);
3324 mrmanese 942
 
3358 mrmanese 943
                    /* levels in sdf must be >= levels in df */
3324 mrmanese 944
                    levels = GET_LEVELS(col);
945
                    if (nrows < GET_LENGTH(levels)) {
946
                        Rprintf("Error: The data frame variable %s has more levels than"
947
                                " its SDF counterpart.\n", colname);
948
                        break;
949
                    }
950
 
3358 mrmanese 951
                    sprintf(g_sql_buf[2], "select label from %s order by level", g_sql_buf[1]);
3324 mrmanese 952
                    sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt2, NULL);
953
 
3358 mrmanese 954
                    for (j = 0; j < GET_LENGTH(levels); j++)  {
3324 mrmanese 955
                        sqlite3_step(stmt2);
3358 mrmanese 956
                        if (strcmp((char *)sqlite3_column_text(stmt2, 0), CHAR_ELT(levels, j)) != 0) {
3324 mrmanese 957
                            Rprintf("Error: Level label mismatch in variable %s, [%s] in data frame"
958
                                    " vs [%s] in SDF.\n", colname, (char *)sqlite3_column_text(stmt2, 0),
959
                                    CHAR_ELT(levels, j));
3358 mrmanese 960
                            sqlite3_finalize(stmt2);
3324 mrmanese 961
                            break;
962
                        }
963
                    }
3358 mrmanese 964
                    sqlite3_finalize(stmt2);
3324 mrmanese 965
                }  /* else if class == "ordered" */
966
            } /* if integer */
967
        } /* for loop for column type checking */
968
 
3358 mrmanese 969
        sqlite3_finalize(stmt);
970
        if (i < ncols) {
3324 mrmanese 971
            Rprintf("Error: type mismatch at variable %s\n", CHAR_ELT(names, i));
972
            return ret;
973
        }
974
 
975
        /* create the insert statement */
976
        buflen = sprintf(g_sql_buf[0], "insert into [%s].sdf_data([row name]", iname);
977
        buflen2 = sprintf(g_sql_buf[1], "values(?");
3358 mrmanese 978
        for (i = 0; i < ncols; i++) {
3324 mrmanese 979
            _expand_buf(0, buflen+100);
980
            buflen += sprintf(g_sql_buf[0]+buflen, ",[%s]", CHAR_ELT(names, i));
981
            _expand_buf(1, buflen2+5);
982
            buflen2 += sprintf(g_sql_buf[1]+buflen2, ",?");
983
        }
984
 
985
        _expand_buf(2, buflen + buflen2 + 10);
3358 mrmanese 986
        sprintf(g_sql_buf[2], "%s) %s)", g_sql_buf[0], g_sql_buf[1]);
3324 mrmanese 987
        res = sqlite3_prepare(g_workspace, g_sql_buf[2], -1, &stmt, NULL);
988
        if (_sqlite_error(res)) return ret;
989
 
990
        /* finally, add rows */
3457 mrmanese 991
        rownames = getAttrib(data, R_RowNamesSymbol); /* GET_ROWNAMES(data); */
992
        nrows = LENGTH(rownames);
993
        rownames_type = TYPEOF(rownames);
3324 mrmanese 994
 
3457 mrmanese 995
        _sqlite_begin;
3324 mrmanese 996
        for (i = 0; i < nrows; i++) {
3457 mrmanese 997
            sqlite3_reset(stmt);
998
            if (rownames_type == STRSXP) {
999
                rn_str = CHAR_ELT(rownames, i);
1000
            } else if (rownames_type == INTSXP) {
1001
                sprintf(g_sql_buf[1], "%d", INTEGER(rownames)[i]);
1002
                rn_str = g_sql_buf[1];
1003
            } else if (rownames_type == REALSXP) {
1004
                sprintf(g_sql_buf[1], "%f", REAL(rownames)[i]);
1005
                rn_str = g_sql_buf[1];
1006
            } else {
1007
                sprintf(g_sql_buf[1], "%d", i);
1008
                rn_str = g_sql_buf[1];
1009
            }
1010
            sqlite3_bind_text(stmt, 1, rn_str, -1, SQLITE_STATIC);
1011
 
3358 mrmanese 1012
            for (j = 0; j < ncols; j++) {
1013
                col = VECTOR_ELT(data, j);
1014
                switch(types[j]) {
1015
                    case SQLITE_FLOAT:
1016
                        sqlite3_bind_double(stmt, j+2, REAL(col)[i]); break;
1017
                    case SQLITE_TEXT:
1018
                        sqlite3_bind_text(stmt, j+2, CHAR_ELT(col, i), -1, SQLITE_STATIC); break;
1019
                    case SQLITE_INTEGER:
1020
                    default:  /* runtime error if we're wrong */
1021
                        sqlite3_bind_int(stmt, j+2, INTEGER(col)[i]); break;
1022
                }
1023
            }
1024
 
1025
            res = sqlite3_step(stmt);
1026
            if (res != SQLITE_DONE) { /* row name pk conflict */
1027
                for (j = 1; res != SQLITE_DONE; j++) { /* _normally_, j shouldn't overflow */
1028
                    sqlite3_reset(stmt);
3457 mrmanese 1029
                    sprintf(g_sql_buf[2], "%s-%d", rn_str, j);
3358 mrmanese 1030
                    sqlite3_bind_text(stmt, 1, g_sql_buf[2], -1, SQLITE_STATIC);
1031
                    res = sqlite3_step(stmt);
1032
                }
3457 mrmanese 1033
            } 
3324 mrmanese 1034
        }
1035
 
3358 mrmanese 1036
        sqlite3_finalize(stmt);
3457 mrmanese 1037
        _sqlite_commit;
3358 mrmanese 1038
        ret = sdf;
3324 mrmanese 1039
    } else if (strcmp(class,"sqlite.data.frame") == 0) {
1040
    }
1041
 
1042
    return ret;
1043
}
1044
 
1045
 
3358 mrmanese 1046
SEXP sdf_get_iname(SEXP sdf) {
3471 mrmanese 1047
    char *iname, *sql;
1048
    sqlite3_stmt *stmt;
1049
    SEXP ret, names;
1050
 
1051
    iname = SDF_INAME(sdf);
1052
    if (!USE_SDF1(iname, TRUE, FALSE)) return R_NilValue;
1053
 
1054
    sql = "select internal_name, rel_filename from workspace where internal_name=?";
1055
    sqlite3_prepare(g_workspace, sql, -1, &stmt, NULL);
1056
    sqlite3_bind_text(stmt, 1, iname, -1, SQLITE_STATIC);
1057
    sqlite3_step(stmt);
1058
 
1059
    PROTECT(ret = NEW_CHARACTER(2));
1060
    SET_STRING_ELT(ret, 0, mkChar((char *)sqlite3_column_text(stmt, 0)));
1061
    SET_STRING_ELT(ret, 1, mkChar((char *)sqlite3_column_text(stmt, 1)));
1062
 
1063
    PROTECT(names = NEW_CHARACTER(2));
1064
    SET_STRING_ELT(names, 0, mkChar("Internal Name"));
1065
    SET_STRING_ELT(names, 1, mkChar("File"));
1066
 
1067
    SET_NAMES(ret, names);
1068
 
1069
    sqlite3_finalize(stmt);
1070
    UNPROTECT(2);
1071
 
1072
    return ret;
3358 mrmanese 1073
}