The R Project SVN R-packages

Rev

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

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