The R Project SVN R-packages

Rev

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

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