The R Project SVN R-packages

Rev

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

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