The R Project SVN R-packages

Rev

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

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