The R Project SVN R-packages

Rev

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

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