The R Project SVN R-packages

Rev

Rev 3446 | Rev 3471 | Go to most recent revision | Only display areas with differences | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

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