The R Project SVN R-packages

Rev

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

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