The R Project SVN R-packages

Rev

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