The R Project SVN R-packages

Rev

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

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