Line data Source code
1 : /* FreeTDS - Library of routines accessing Sybase and Microsoft databases
2 : * Copyright (C) 2008-2010 Frediano Ziglio
3 : *
4 : * This library is free software; you can redistribute it and/or
5 : * modify it under the terms of the GNU Library General Public
6 : * License as published by the Free Software Foundation; either
7 : * version 2 of the License, or (at your option) any later version.
8 : *
9 : * This library is distributed in the hope that it will be useful,
10 : * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 : * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 : * Library General Public License for more details.
13 : *
14 : * You should have received a copy of the GNU Library General Public
15 : * License along with this library; if not, write to the
16 : * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 : * Boston, MA 02111-1307, USA.
18 : */
19 :
20 : /**
21 : * \file
22 : * \brief Handle bulk copy
23 : */
24 :
25 : #include <config.h>
26 :
27 : #if HAVE_STRING_H
28 : #include <string.h>
29 : #endif /* HAVE_STRING_H */
30 :
31 : #if HAVE_ERRNO_H
32 : #include <errno.h>
33 : #endif /* HAVE_ERRNO_H */
34 :
35 : #if HAVE_STDLIB_H
36 : #include <stdlib.h>
37 : #endif /* HAVE_STDLIB_H */
38 :
39 : #include <assert.h>
40 :
41 : #include <freetds/tds.h>
42 : #include <freetds/checks.h>
43 : #include <freetds/bytes.h>
44 : #include <freetds/iconv.h>
45 : #include <freetds/stream.h>
46 : #include <freetds/convert.h>
47 : #include <freetds/utils/string.h>
48 : #include <freetds/replacements.h>
49 :
50 : /** \cond HIDDEN_SYMBOLS */
51 : #ifndef MAX
52 : #define MAX(a,b) ( (a) > (b) ? (a) : (b) )
53 : #endif
54 : /** \endcond */
55 :
56 : /**
57 : * Holds clause buffer
58 : */
59 : typedef struct tds_pbcb
60 : {
61 : /** buffer */
62 : char *pb;
63 : /** buffer length */
64 : unsigned int cb;
65 : /** true is buffer came from malloc */
66 : unsigned int from_malloc;
67 : } TDSPBCB;
68 :
69 : static TDSRET tds7_bcp_send_colmetadata(TDSSOCKET *tds, TDSBCPINFO *bcpinfo);
70 : static TDSRET tds_bcp_start_insert_stmt(TDSSOCKET *tds, TDSBCPINFO *bcpinfo);
71 : static int tds5_bcp_add_fixed_columns(TDSBCPINFO *bcpinfo, tds_bcp_get_col_data get_col_data, tds_bcp_null_error null_error,
72 : int offset, unsigned char * rowbuffer, int start);
73 : static int tds5_bcp_add_variable_columns(TDSBCPINFO *bcpinfo, tds_bcp_get_col_data get_col_data, tds_bcp_null_error null_error,
74 : int offset, TDS_UCHAR *rowbuffer, int start, int *pncols);
75 : static void tds_bcp_row_free(TDSRESULTINFO* result, unsigned char *row);
76 : static TDSRET tds5_process_insert_bulk_reply(TDSSOCKET * tds, TDSBCPINFO *bcpinfo);
77 :
78 : /**
79 : * Initialize BCP information.
80 : * Query structure of the table to server.
81 : * \tds
82 : * \param bcpinfo BCP information to initialize. Structure should be allocate
83 : * and table name and direction should be already set.
84 : */
85 : TDSRET
86 352 : tds_bcp_init(TDSSOCKET *tds, TDSBCPINFO *bcpinfo)
87 : {
88 : TDSRESULTINFO *resinfo;
89 352 : TDSRESULTINFO *bindinfo = NULL;
90 : TDSCOLUMN *curcol;
91 : TDS_INT result_type;
92 : int i;
93 : TDSRET rc;
94 : const char *fmt;
95 :
96 : /* FIXME don't leave state in processing state */
97 :
98 : /* TODO quote tablename if needed */
99 352 : if (bcpinfo->direction != TDS_BCP_QUERYOUT)
100 : fmt = "SET FMTONLY ON select * from %s SET FMTONLY OFF";
101 : else
102 8 : fmt = "SET FMTONLY ON %s SET FMTONLY OFF";
103 :
104 704 : if (TDS_FAILED(rc=tds_submit_queryf(tds, fmt, tds_dstr_cstr(&bcpinfo->tablename))))
105 : /* TODO return an error ?? */
106 : /* Attempt to use Bulk Copy with a non-existent Server table (might be why ...) */
107 : return rc;
108 :
109 : /* TODO possibly stop at ROWFMT and copy before going to idle */
110 : /* TODO check what happen if table is not present, cleanup on error */
111 1760 : while ((rc = tds_process_tokens(tds, &result_type, NULL, TDS_TOKEN_RESULTS))
112 : == TDS_SUCCESS)
113 1408 : continue;
114 352 : TDS_PROPAGATE(rc);
115 :
116 : /* copy the results info from the TDS socket */
117 352 : if (!tds->res_info)
118 : return TDS_FAIL;
119 :
120 352 : resinfo = tds->res_info;
121 352 : if ((bindinfo = tds_alloc_results(resinfo->num_cols)) == NULL) {
122 : rc = TDS_FAIL;
123 : goto cleanup;
124 : }
125 :
126 352 : bindinfo->row_size = resinfo->row_size;
127 :
128 : /* Copy the column metadata */
129 352 : rc = TDS_FAIL;
130 2786 : for (i = 0; i < bindinfo->num_cols; i++) {
131 :
132 2434 : curcol = bindinfo->columns[i];
133 :
134 : /*
135 : * TODO use memcpy ??
136 : * curcol and resinfo->columns[i] are both TDSCOLUMN.
137 : * Why not "curcol = resinfo->columns[i];"? Because the rest of TDSCOLUMN (below column_timestamp)
138 : * isn't being used. Perhaps this "upper" part of TDSCOLUMN should be a substructure.
139 : * Or, see if the "lower" part is unused (and zeroed out) at this point, and just do one assignment.
140 : */
141 2434 : curcol->funcs = resinfo->columns[i]->funcs;
142 2434 : curcol->column_type = resinfo->columns[i]->column_type;
143 2434 : curcol->column_usertype = resinfo->columns[i]->column_usertype;
144 2434 : curcol->column_flags = resinfo->columns[i]->column_flags;
145 2434 : if (curcol->column_varint_size == 0)
146 2434 : curcol->column_cur_size = resinfo->columns[i]->column_cur_size;
147 : else
148 0 : curcol->column_cur_size = -1;
149 2434 : curcol->column_size = resinfo->columns[i]->column_size;
150 2434 : curcol->column_varint_size = resinfo->columns[i]->column_varint_size;
151 2434 : curcol->column_prec = resinfo->columns[i]->column_prec;
152 2434 : curcol->column_scale = resinfo->columns[i]->column_scale;
153 2434 : curcol->on_server = resinfo->columns[i]->on_server;
154 2434 : curcol->char_conv = resinfo->columns[i]->char_conv;
155 2434 : if (!tds_dstr_dup(&curcol->column_name, &resinfo->columns[i]->column_name))
156 : goto cleanup;
157 2434 : if (!tds_dstr_dup(&curcol->table_column_name, &resinfo->columns[i]->table_column_name))
158 : goto cleanup;
159 2434 : curcol->column_nullable = resinfo->columns[i]->column_nullable;
160 2434 : curcol->column_identity = resinfo->columns[i]->column_identity;
161 2434 : curcol->column_timestamp = resinfo->columns[i]->column_timestamp;
162 2434 : curcol->column_computed = resinfo->columns[i]->column_computed;
163 :
164 2434 : memcpy(curcol->column_collation, resinfo->columns[i]->column_collation, 5);
165 :
166 2434 : if (is_numeric_type(curcol->column_type)) {
167 178 : curcol->bcp_column_data = tds_alloc_bcp_column_data(sizeof(TDS_NUMERIC));
168 178 : ((TDS_NUMERIC *) curcol->bcp_column_data->data)->precision = curcol->column_prec;
169 178 : ((TDS_NUMERIC *) curcol->bcp_column_data->data)->scale = curcol->column_scale;
170 : } else {
171 2256 : curcol->bcp_column_data =
172 2256 : tds_alloc_bcp_column_data(MAX(curcol->column_size,curcol->on_server.column_size));
173 : }
174 2434 : if (!curcol->bcp_column_data)
175 : goto cleanup;
176 : }
177 :
178 352 : if (!IS_TDS7_PLUS(tds->conn)) {
179 74 : bindinfo->current_row = tds_new(unsigned char, bindinfo->row_size);
180 74 : if (!bindinfo->current_row)
181 : goto cleanup;
182 74 : bindinfo->row_free = tds_bcp_row_free;
183 : }
184 :
185 352 : if (bcpinfo->identity_insert_on) {
186 :
187 0 : rc = tds_submit_queryf(tds, "set identity_insert %s on", tds_dstr_cstr(&bcpinfo->tablename));
188 0 : if (TDS_FAILED(rc))
189 : goto cleanup;
190 :
191 : /* TODO use tds_process_simple_query */
192 0 : while ((rc = tds_process_tokens(tds, &result_type, NULL, TDS_TOKEN_RESULTS))
193 : == TDS_SUCCESS) {
194 : }
195 0 : if (rc != TDS_NO_MORE_RESULTS)
196 : goto cleanup;
197 : }
198 :
199 352 : bcpinfo->bindinfo = bindinfo;
200 352 : bcpinfo->bind_count = 0;
201 352 : return TDS_SUCCESS;
202 :
203 0 : cleanup:
204 0 : tds_free_results(bindinfo);
205 0 : return rc;
206 : }
207 :
208 : /**
209 : * Help to build query to be sent to server.
210 : * Append column declaration to the query.
211 : * Only for TDS 7.0+.
212 : * \tds
213 : * \param[out] clause output string
214 : * \param bcpcol column to append
215 : * \param first true if column is the first
216 : * \return TDS_SUCCESS or TDS_FAIL.
217 : */
218 : static TDSRET
219 1244 : tds7_build_bulk_insert_stmt(TDSSOCKET * tds, TDSPBCB * clause, TDSCOLUMN * bcpcol, int first)
220 : {
221 : char column_type[40];
222 :
223 1244 : tdsdump_log(TDS_DBG_FUNC, "tds7_build_bulk_insert_stmt(%p, %p, %p, %d)\n", tds, clause, bcpcol, first);
224 :
225 1244 : if (TDS_FAILED(tds_get_column_declaration(tds, bcpcol, column_type))) {
226 0 : tdserror(tds_get_ctx(tds), tds, TDSEBPROBADTYP, errno);
227 0 : tdsdump_log(TDS_DBG_FUNC, "error: cannot build bulk insert statement. unrecognized server datatype %d\n",
228 0 : bcpcol->on_server.column_type);
229 : return TDS_FAIL;
230 : }
231 :
232 2488 : if (clause->cb < strlen(clause->pb)
233 3732 : + tds_quote_id(tds, NULL, tds_dstr_cstr(&bcpcol->column_name), tds_dstr_len(&bcpcol->column_name))
234 1244 : + strlen(column_type)
235 1244 : + ((first) ? 2u : 4u)) {
236 0 : char *temp = tds_new(char, 2 * clause->cb);
237 :
238 0 : if (!temp) {
239 0 : tdserror(tds_get_ctx(tds), tds, TDSEMEM, errno);
240 0 : return TDS_FAIL;
241 : }
242 0 : strcpy(temp, clause->pb);
243 0 : if (clause->from_malloc)
244 0 : free(clause->pb);
245 0 : clause->from_malloc = 1;
246 0 : clause->pb = temp;
247 0 : clause->cb *= 2;
248 : }
249 :
250 1244 : if (!first)
251 1062 : strcat(clause->pb, ", ");
252 :
253 3732 : tds_quote_id(tds, strchr(clause->pb, 0), tds_dstr_cstr(&bcpcol->column_name), tds_dstr_len(&bcpcol->column_name));
254 1244 : strcat(clause->pb, " ");
255 1244 : strcat(clause->pb, column_type);
256 :
257 1244 : return TDS_SUCCESS;
258 : }
259 :
260 : /**
261 : * Prepare the query to be sent to server to request BCP information
262 : * \tds
263 : * \param bcpinfo BCP information
264 : */
265 : static TDSRET
266 232 : tds_bcp_start_insert_stmt(TDSSOCKET * tds, TDSBCPINFO * bcpinfo)
267 : {
268 : char *query;
269 :
270 232 : if (IS_TDS7_PLUS(tds->conn)) {
271 : int i, firstcol, erc;
272 : char *hint;
273 : TDSCOLUMN *bcpcol;
274 : TDSPBCB colclause;
275 182 : char clause_buffer[4096] = { 0 };
276 :
277 182 : colclause.pb = clause_buffer;
278 182 : colclause.cb = sizeof(clause_buffer);
279 182 : colclause.from_malloc = 0;
280 :
281 : /* TODO avoid asprintf, use always malloc-ed buffer */
282 182 : firstcol = 1;
283 :
284 1426 : for (i = 0; i < bcpinfo->bindinfo->num_cols; i++) {
285 1244 : bcpcol = bcpinfo->bindinfo->columns[i];
286 :
287 1244 : if (bcpcol->column_timestamp)
288 0 : continue;
289 1244 : if (!bcpinfo->identity_insert_on && bcpcol->column_identity)
290 0 : continue;
291 1244 : if (bcpcol->column_computed)
292 0 : continue;
293 1244 : tds7_build_bulk_insert_stmt(tds, &colclause, bcpcol, firstcol);
294 1244 : firstcol = 0;
295 : }
296 :
297 364 : if (!tds_dstr_isempty(&bcpinfo->hint)) {
298 124 : if (asprintf(&hint, " with (%s)", tds_dstr_cstr(&bcpinfo->hint)) < 0)
299 0 : hint = NULL;
300 : } else {
301 120 : hint = strdup("");
302 : }
303 182 : if (!hint) {
304 0 : if (colclause.from_malloc)
305 0 : TDS_ZERO_FREE(colclause.pb);
306 0 : return TDS_FAIL;
307 : }
308 :
309 364 : erc = asprintf(&query, "insert bulk %s (%s)%s", tds_dstr_cstr(&bcpinfo->tablename), colclause.pb, hint);
310 :
311 182 : free(hint);
312 182 : if (colclause.from_malloc)
313 0 : TDS_ZERO_FREE(colclause.pb); /* just for good measure; not used beyond this point */
314 :
315 182 : if (erc < 0)
316 : return TDS_FAIL;
317 : } else {
318 : /* NOTE: if we use "with nodescribe" for following inserts server do not send describe */
319 100 : if (asprintf(&query, "insert bulk %s", tds_dstr_cstr(&bcpinfo->tablename)) < 0)
320 : return TDS_FAIL;
321 : }
322 :
323 : /* save the statement for later... */
324 232 : bcpinfo->insert_stmt = query;
325 :
326 232 : return TDS_SUCCESS;
327 : }
328 :
329 : static TDSRET
330 520 : tds7_send_record(TDSSOCKET *tds, TDSBCPINFO *bcpinfo, tds_bcp_get_col_data get_col_data, int offset)
331 : {
332 : int i;
333 :
334 520 : tds_put_byte(tds, TDS_ROW_TOKEN); /* 0xd1 */
335 9116 : for (i = 0; i < bcpinfo->bindinfo->num_cols; i++) {
336 :
337 : TDS_INT save_size;
338 : unsigned char *save_data;
339 : TDSBLOB blob;
340 : TDSCOLUMN *bindcol;
341 : TDSRET rc;
342 :
343 8596 : bindcol = bcpinfo->bindinfo->columns[i];
344 :
345 : /*
346 : * Don't send the (meta)data for timestamp columns or
347 : * identity columns unless indentity_insert is enabled.
348 : */
349 :
350 8596 : if ((!bcpinfo->identity_insert_on && bindcol->column_identity) ||
351 8596 : bindcol->column_timestamp ||
352 : bindcol->column_computed) {
353 0 : continue;
354 : }
355 :
356 8596 : rc = get_col_data(bcpinfo, bindcol, offset);
357 8596 : if (TDS_FAILED(rc)) {
358 0 : tdsdump_log(TDS_DBG_INFO1, "get_col_data (column %d) failed\n", i + 1);
359 0 : return rc;
360 : }
361 8596 : tdsdump_log(TDS_DBG_INFO1, "gotten column %d length %d null %d\n",
362 0 : i + 1, bindcol->bcp_column_data->datalen, bindcol->bcp_column_data->is_null);
363 :
364 8596 : save_size = bindcol->column_cur_size;
365 8596 : save_data = bindcol->column_data;
366 8596 : assert(bindcol->column_data == NULL);
367 8596 : if (bindcol->bcp_column_data->is_null) {
368 3340 : bindcol->column_cur_size = -1;
369 5256 : } else if (is_blob_col(bindcol)) {
370 54 : bindcol->column_cur_size = bindcol->bcp_column_data->datalen;
371 54 : memset(&blob, 0, sizeof(blob));
372 54 : blob.textvalue = (TDS_CHAR *) bindcol->bcp_column_data->data;
373 54 : bindcol->column_data = (unsigned char *) &blob;
374 : } else {
375 5202 : bindcol->column_cur_size = bindcol->bcp_column_data->datalen;
376 5202 : bindcol->column_data = bindcol->bcp_column_data->data;
377 : }
378 8596 : rc = bindcol->funcs->put_data(tds, bindcol, 1);
379 8596 : bindcol->column_cur_size = save_size;
380 8596 : bindcol->column_data = save_data;
381 :
382 8596 : TDS_PROPAGATE(rc);
383 : }
384 : return TDS_SUCCESS;
385 : }
386 :
387 : static TDSRET
388 154 : tds5_send_record(TDSSOCKET *tds, TDSBCPINFO *bcpinfo,
389 : tds_bcp_get_col_data get_col_data, tds_bcp_null_error null_error, int offset)
390 : {
391 : int row_pos;
392 : int row_sz_pos;
393 154 : int blob_cols = 0;
394 154 : int var_cols_written = 0;
395 154 : TDS_INT old_record_size = bcpinfo->bindinfo->row_size;
396 154 : unsigned char *record = bcpinfo->bindinfo->current_row;
397 : int i;
398 :
399 154 : memset(record, '\0', old_record_size); /* zero the rowbuffer */
400 :
401 : /*
402 : * offset 0 = number of var columns
403 : * offset 1 = row number. zeroed (datasever assigns)
404 : */
405 154 : row_pos = 2;
406 :
407 154 : if ((row_pos = tds5_bcp_add_fixed_columns(bcpinfo, get_col_data, null_error, offset, record, row_pos)) < 0)
408 : return TDS_FAIL;
409 :
410 152 : row_sz_pos = row_pos;
411 :
412 : /* potential variable columns to write */
413 :
414 152 : row_pos = tds5_bcp_add_variable_columns(bcpinfo, get_col_data, null_error, offset, record, row_pos, &var_cols_written);
415 152 : if (row_pos < 0)
416 : return TDS_FAIL;
417 :
418 :
419 152 : if (var_cols_written) {
420 134 : TDS_PUT_UA2LE(&record[row_sz_pos], row_pos);
421 134 : record[0] = var_cols_written;
422 : }
423 :
424 152 : tdsdump_log(TDS_DBG_INFO1, "old_record_size = %d new size = %d \n", old_record_size, row_pos);
425 :
426 152 : tds_put_smallint(tds, row_pos);
427 152 : tds_put_n(tds, record, row_pos);
428 :
429 : /* row is done, now handle any text/image data */
430 :
431 152 : blob_cols = 0;
432 :
433 2926 : for (i = 0; i < bcpinfo->bindinfo->num_cols; i++) {
434 2774 : TDSCOLUMN *bindcol = bcpinfo->bindinfo->columns[i];
435 2774 : if (is_blob_type(bindcol->on_server.column_type)) {
436 10 : TDS_PROPAGATE(get_col_data(bcpinfo, bindcol, offset));
437 : /* unknown but zero */
438 10 : tds_put_smallint(tds, 0);
439 10 : tds_put_byte(tds, bindcol->on_server.column_type);
440 10 : tds_put_byte(tds, 0xff - blob_cols);
441 : /*
442 : * offset of txptr we stashed during variable
443 : * column processing
444 : */
445 10 : tds_put_smallint(tds, bindcol->column_textpos);
446 10 : tds_put_int(tds, bindcol->bcp_column_data->datalen);
447 10 : tds_put_n(tds, bindcol->bcp_column_data->data, bindcol->bcp_column_data->datalen);
448 10 : blob_cols++;
449 :
450 : }
451 : }
452 : return TDS_SUCCESS;
453 : }
454 :
455 : /**
456 : * Send one row of data to server
457 : * \tds
458 : * \param bcpinfo BCP information
459 : * \param get_col_data function to call to retrieve data to be sent
460 : * \param ignored function to call if we try to send NULL if not allowed (not used)
461 : * \param offset passed to get_col_data and null_error to specify the row to get
462 : * \return TDS_SUCCESS or TDS_FAIL.
463 : */
464 : TDSRET
465 674 : tds_bcp_send_record(TDSSOCKET *tds, TDSBCPINFO *bcpinfo,
466 : tds_bcp_get_col_data get_col_data, tds_bcp_null_error null_error, int offset)
467 : {
468 : TDSRET rc;
469 :
470 674 : tdsdump_log(TDS_DBG_FUNC, "tds_bcp_send_bcp_record(%p, %p, %p, %p, %d)\n",
471 : tds, bcpinfo, get_col_data, null_error, offset);
472 :
473 674 : if (tds->out_flag != TDS_BULK || tds_set_state(tds, TDS_WRITING) != TDS_WRITING)
474 : return TDS_FAIL;
475 :
476 674 : if (IS_TDS7_PLUS(tds->conn))
477 520 : rc = tds7_send_record(tds, bcpinfo, get_col_data, offset);
478 : else
479 154 : rc = tds5_send_record(tds, bcpinfo, get_col_data, null_error, offset);
480 :
481 674 : tds_set_state(tds, TDS_SENDING);
482 674 : return rc;
483 : }
484 :
485 : static inline void
486 : tds5_swap_data(const TDSCOLUMN *col TDS_UNUSED, void *p TDS_UNUSED)
487 : {
488 : #ifdef WORDS_BIGENDIAN
489 : tds_swap_datatype(tds_get_conversion_type(col->on_server.column_type, col->column_size), p);
490 : #endif
491 : }
492 :
493 : /**
494 : * Add fixed size columns to the row
495 : * \param bcpinfo BCP information
496 : * \param get_col_data function to call to retrieve data to be sent
497 : * \param ignored function to call if we try to send NULL if not allowed (not used)
498 : * \param offset passed to get_col_data and null_error to specify the row to get
499 : * \param rowbuffer row buffer to write to
500 : * \param start row buffer last end position
501 : * \returns new row length or -1 on error.
502 : */
503 : static int
504 154 : tds5_bcp_add_fixed_columns(TDSBCPINFO *bcpinfo, tds_bcp_get_col_data get_col_data, tds_bcp_null_error null_error,
505 : int offset, unsigned char * rowbuffer, int start)
506 : {
507 : TDS_NUMERIC *num;
508 154 : int row_pos = start;
509 : int cpbytes;
510 : int i;
511 154 : int bitleft = 0, bitpos = 0;
512 :
513 154 : assert(bcpinfo);
514 154 : assert(rowbuffer);
515 :
516 154 : tdsdump_log(TDS_DBG_FUNC, "tds5_bcp_add_fixed_columns(%p, %p, %p, %d, %p, %d)\n",
517 : bcpinfo, get_col_data, null_error, offset, rowbuffer, start);
518 :
519 2776 : for (i = 0; i < bcpinfo->bindinfo->num_cols; i++) {
520 :
521 2778 : TDSCOLUMN *const bcpcol = bcpinfo->bindinfo->columns[i];
522 2778 : const TDS_INT column_size = bcpcol->on_server.column_size;
523 :
524 : /* if possible check information from server */
525 2778 : if (bcpinfo->sybase_count > i) {
526 2778 : if (bcpinfo->sybase_colinfo[i].offset < 0)
527 1488 : continue;
528 : } else {
529 0 : if (is_nullable_type(bcpcol->on_server.column_type) || bcpcol->column_nullable)
530 0 : continue;
531 : }
532 :
533 1290 : tdsdump_log(TDS_DBG_FUNC, "tds5_bcp_add_fixed_columns column %d (%s) is a fixed column\n", i + 1, tds_dstr_cstr(&bcpcol->column_name));
534 :
535 1290 : if (TDS_FAILED(get_col_data(bcpinfo, bcpcol, offset))) {
536 0 : tdsdump_log(TDS_DBG_INFO1, "get_col_data (column %d) failed\n", i + 1);
537 : return -1;
538 : }
539 :
540 : /* We have no way to send a NULL at this point, return error to client */
541 1290 : if (bcpcol->bcp_column_data->is_null) {
542 2 : tdsdump_log(TDS_DBG_ERROR, "tds5_bcp_add_fixed_columns column %d is a null column\n", i + 1);
543 : /* No value or default value available and NULL not allowed. */
544 2 : if (null_error)
545 2 : null_error(bcpinfo, i, offset);
546 : return -1;
547 : }
548 :
549 1288 : if (is_numeric_type(bcpcol->on_server.column_type)) {
550 180 : num = (TDS_NUMERIC *) bcpcol->bcp_column_data->data;
551 180 : cpbytes = tds_numeric_bytes_per_prec[num->precision];
552 180 : memcpy(&rowbuffer[row_pos], num->array, cpbytes);
553 1108 : } else if (bcpcol->column_type == SYBBIT) {
554 : /* all bit are collapsed together */
555 158 : if (!bitleft) {
556 106 : bitpos = row_pos++;
557 106 : bitleft = 8;
558 106 : rowbuffer[bitpos] = 0;
559 : }
560 158 : if (bcpcol->bcp_column_data->data[0])
561 126 : rowbuffer[bitpos] |= 256 >> bitleft;
562 158 : --bitleft;
563 158 : continue;
564 : } else {
565 950 : cpbytes = bcpcol->bcp_column_data->datalen > column_size ?
566 : column_size : bcpcol->bcp_column_data->datalen;
567 950 : memcpy(&rowbuffer[row_pos], bcpcol->bcp_column_data->data, cpbytes);
568 950 : tds5_swap_data(bcpcol, &rowbuffer[row_pos]);
569 :
570 : /* CHAR data may need padding out to the database length with blanks */
571 : /* TODO check binary !!! */
572 950 : if (bcpcol->column_type == SYBCHAR && cpbytes < column_size)
573 98 : memset(rowbuffer + row_pos + cpbytes, ' ', column_size - cpbytes);
574 : }
575 :
576 1130 : row_pos += column_size;
577 : }
578 : return row_pos;
579 : }
580 :
581 : /**
582 : * Add variable size columns to the row
583 : *
584 : * \param bcpinfo BCP information already prepared
585 : * \param get_col_data function to call to retrieve data to be sent
586 : * \param null_error function to call if we try to send NULL if not allowed
587 : * \param offset passed to get_col_data and null_error to specify the row to get
588 : * \param rowbuffer The row image that will be sent to the server.
589 : * \param start Where to begin copying data into the rowbuffer.
590 : * \param pncols Address of output variable holding the count of columns added to the rowbuffer.
591 : *
592 : * \return length of (potentially modified) rowbuffer, or -1.
593 : */
594 : static int
595 152 : tds5_bcp_add_variable_columns(TDSBCPINFO *bcpinfo, tds_bcp_get_col_data get_col_data, tds_bcp_null_error null_error,
596 : int offset, TDS_UCHAR* rowbuffer, int start, int *pncols)
597 : {
598 : TDS_USMALLINT offsets[256];
599 : unsigned int i, row_pos;
600 152 : unsigned int ncols = 0;
601 :
602 152 : assert(bcpinfo);
603 152 : assert(rowbuffer);
604 152 : assert(pncols);
605 :
606 152 : tdsdump_log(TDS_DBG_FUNC, "%4s %8s %18s %18s %8s\n", "col",
607 : "type",
608 : "is_nullable_type",
609 : "column_nullable",
610 : "is null" );
611 2774 : for (i = 0; i < bcpinfo->bindinfo->num_cols; i++) {
612 2774 : TDSCOLUMN *bcpcol = bcpinfo->bindinfo->columns[i];
613 2774 : tdsdump_log(TDS_DBG_FUNC, "%4d %8d %18s %18s %8s\n", i,
614 : bcpcol->on_server.column_type,
615 0 : is_nullable_type(bcpcol->on_server.column_type)? "yes" : "no",
616 0 : bcpcol->column_nullable? "yes" : "no",
617 0 : bcpcol->bcp_column_data->is_null? "yes" : "no" );
618 : }
619 :
620 : /* the first two bytes of the rowbuffer are reserved to hold the entire record length */
621 152 : row_pos = start + 2;
622 152 : offsets[0] = row_pos;
623 :
624 152 : tdsdump_log(TDS_DBG_FUNC, "%4s %8s %8s %8s\n", "col", "ncols", "row_pos", "cpbytes");
625 :
626 2774 : for (i = 0; i < bcpinfo->bindinfo->num_cols; i++) {
627 2774 : unsigned int cpbytes = 0;
628 2774 : TDSCOLUMN *bcpcol = bcpinfo->bindinfo->columns[i];
629 :
630 : /*
631 : * Is this column of "variable" type, i.e. NULLable
632 : * or naturally variable length e.g. VARCHAR
633 : */
634 2774 : if (bcpinfo->sybase_count > i) {
635 2774 : if (bcpinfo->sybase_colinfo[i].offset >= 0)
636 1286 : continue;
637 : } else {
638 0 : if (!is_nullable_type(bcpcol->on_server.column_type) && !bcpcol->column_nullable)
639 0 : continue;
640 : }
641 :
642 1488 : tdsdump_log(TDS_DBG_FUNC, "%4d %8d %8d %8d\n", i, ncols, row_pos, cpbytes);
643 :
644 1488 : if (TDS_FAILED(get_col_data(bcpinfo, bcpcol, offset)))
645 : return -1;
646 :
647 : /* If it's a NOT NULL column, and we have no data, throw an error.
648 : * This is the behavior for Sybase, this function is only used for Sybase */
649 1488 : if (!bcpcol->column_nullable && bcpcol->bcp_column_data->is_null) {
650 : /* No value or default value available and NULL not allowed. */
651 0 : if (null_error)
652 0 : null_error(bcpinfo, i, offset);
653 : return -1;
654 : }
655 :
656 : /* move the column buffer into the rowbuffer */
657 1488 : if (!bcpcol->bcp_column_data->is_null) {
658 406 : if (is_blob_type(bcpcol->on_server.column_type)) {
659 10 : cpbytes = 16;
660 10 : bcpcol->column_textpos = row_pos; /* save for data write */
661 396 : } else if (is_numeric_type(bcpcol->on_server.column_type)) {
662 24 : TDS_NUMERIC *num = (TDS_NUMERIC *) bcpcol->bcp_column_data->data;
663 24 : cpbytes = tds_numeric_bytes_per_prec[num->precision];
664 24 : memcpy(&rowbuffer[row_pos], num->array, cpbytes);
665 : } else {
666 744 : cpbytes = bcpcol->bcp_column_data->datalen > bcpcol->column_size ?
667 372 : bcpcol->column_size : bcpcol->bcp_column_data->datalen;
668 372 : memcpy(&rowbuffer[row_pos], bcpcol->bcp_column_data->data, cpbytes);
669 372 : tds5_swap_data(bcpcol, &rowbuffer[row_pos]);
670 : }
671 : }
672 :
673 1488 : row_pos += cpbytes;
674 1488 : offsets[++ncols] = row_pos;
675 1488 : tdsdump_dump_buf(TDS_DBG_NETWORK, "BCP row buffer so far", rowbuffer, row_pos);
676 : }
677 :
678 152 : tdsdump_log(TDS_DBG_FUNC, "%4d %8d %8d\n", i, ncols, row_pos);
679 :
680 : /*
681 : * The rowbuffer ends with an offset table and, optionally, an adjustment table.
682 : * The offset table has 1-byte elements that describe the locations of the start of each column in
683 : * the rowbuffer. If the largest offset is greater than 255, another table -- the adjustment table --
684 : * is inserted just before the offset table. It holds the high bytes.
685 : *
686 : * Both tables are laid out in reverse:
687 : * #elements, offset N+1, offset N, offset N-1, ... offset 0
688 : * E.g. for 2 columns you have 4 data points:
689 : * 1. How many elements (4)
690 : * 2. Start of column 3 (non-existent, "one off the end")
691 : * 3. Start of column 2
692 : * 4. Start of column 1
693 : * The length of each column is computed by subtracting its start from the its successor's start.
694 : *
695 : * The algorithm below computes both tables. If the adjustment table isn't needed, the
696 : * effect is to overwrite it with the offset table.
697 : */
698 1234 : while (ncols && offsets[ncols] == offsets[ncols-1])
699 : ncols--; /* trailing NULL columns are not sent and are not included in the offset table */
700 :
701 152 : if (ncols) {
702 134 : TDS_UCHAR *poff = rowbuffer + row_pos;
703 134 : unsigned int pfx_top = offsets[ncols] >> 8;
704 :
705 134 : tdsdump_log(TDS_DBG_FUNC, "ncols=%u poff=%p [%u]\n", ncols, poff, offsets[ncols]);
706 :
707 134 : *poff++ = ncols + 1;
708 : /* this is some kind of run-length-prefix encoding */
709 274 : while (pfx_top) {
710 : unsigned int n_pfx = 1;
711 :
712 126 : for (i = 0; i <= ncols ; ++i)
713 126 : if ((offsets[i] >> 8) < pfx_top)
714 80 : ++n_pfx;
715 6 : *poff++ = n_pfx;
716 6 : --pfx_top;
717 : }
718 :
719 134 : tdsdump_log(TDS_DBG_FUNC, "poff=%p\n", poff);
720 :
721 540 : for (i=0; i <= ncols; i++)
722 540 : *poff++ = offsets[ncols-i] & 0xFF;
723 134 : row_pos = (unsigned int)(poff - rowbuffer);
724 : }
725 :
726 152 : tdsdump_log(TDS_DBG_FUNC, "%4d %8d %8d\n", i, ncols, row_pos);
727 152 : tdsdump_dump_buf(TDS_DBG_NETWORK, "BCP row buffer", rowbuffer, row_pos);
728 :
729 152 : *pncols = ncols;
730 :
731 152 : return ncols == 0? start : row_pos;
732 : }
733 :
734 : /**
735 : * Send BCP metadata to server.
736 : * Only for TDS 7.0+.
737 : * \tds
738 : * \param bcpinfo BCP information
739 : * \return TDS_SUCCESS or TDS_FAIL.
740 : */
741 : static TDSRET
742 202 : tds7_bcp_send_colmetadata(TDSSOCKET *tds, TDSBCPINFO *bcpinfo)
743 : {
744 : TDSCOLUMN *bcpcol;
745 : int i, num_cols;
746 :
747 202 : tdsdump_log(TDS_DBG_FUNC, "tds7_bcp_send_colmetadata(%p, %p)\n", tds, bcpinfo);
748 202 : assert(tds && bcpinfo);
749 :
750 202 : if (tds->out_flag != TDS_BULK || tds_set_state(tds, TDS_WRITING) != TDS_WRITING)
751 : return TDS_FAIL;
752 :
753 : /*
754 : * Deep joy! For TDS 7 we have to send a colmetadata message followed by row data
755 : */
756 202 : tds_put_byte(tds, TDS7_RESULT_TOKEN); /* 0x81 */
757 :
758 202 : num_cols = 0;
759 1968 : for (i = 0; i < bcpinfo->bindinfo->num_cols; i++) {
760 1766 : bcpcol = bcpinfo->bindinfo->columns[i];
761 1766 : if ((!bcpinfo->identity_insert_on && bcpcol->column_identity) ||
762 1766 : bcpcol->column_timestamp ||
763 : bcpcol->column_computed) {
764 0 : continue;
765 : }
766 1766 : num_cols++;
767 : }
768 :
769 202 : tds_put_smallint(tds, num_cols);
770 :
771 1968 : for (i = 0; i < bcpinfo->bindinfo->num_cols; i++) {
772 : size_t converted_len;
773 : const char *converted_name;
774 :
775 1766 : bcpcol = bcpinfo->bindinfo->columns[i];
776 :
777 : /*
778 : * dont send the (meta)data for timestamp columns, or
779 : * identity columns (unless indentity_insert is enabled
780 : */
781 :
782 1766 : if ((!bcpinfo->identity_insert_on && bcpcol->column_identity) ||
783 1766 : bcpcol->column_timestamp ||
784 : bcpcol->column_computed) {
785 0 : continue;
786 : }
787 :
788 1766 : if (IS_TDS72_PLUS(tds->conn))
789 608 : tds_put_int(tds, bcpcol->column_usertype);
790 : else
791 1158 : tds_put_smallint(tds, bcpcol->column_usertype);
792 1766 : tds_put_smallint(tds, bcpcol->column_flags);
793 1766 : tds_put_byte(tds, bcpcol->on_server.column_type);
794 :
795 1766 : assert(bcpcol->funcs);
796 1766 : bcpcol->funcs->put_info(tds, bcpcol);
797 :
798 : /* TODO put this in put_info. It seems that parameter format is
799 : * different from BCP format
800 : */
801 1766 : if (is_blob_type(bcpcol->on_server.column_type)) {
802 96 : converted_name = tds_convert_string(tds, tds->conn->char_convs[client2ucs2],
803 32 : tds_dstr_cstr(&bcpinfo->tablename),
804 32 : (int) tds_dstr_len(&bcpinfo->tablename), &converted_len);
805 32 : if (!converted_name) {
806 0 : tds_connection_close(tds->conn);
807 0 : return TDS_FAIL;
808 : }
809 :
810 : /* UTF-16 length is always size / 2 even for 4 byte letters (yes, 1 letter of length 2) */
811 32 : TDS_PUT_SMALLINT(tds, converted_len / 2);
812 32 : tds_put_n(tds, converted_name, converted_len);
813 :
814 64 : tds_convert_string_free(tds_dstr_cstr(&bcpinfo->tablename), converted_name);
815 : }
816 :
817 5298 : converted_name = tds_convert_string(tds, tds->conn->char_convs[client2ucs2],
818 1766 : tds_dstr_cstr(&bcpcol->column_name),
819 1766 : (int) tds_dstr_len(&bcpcol->column_name), &converted_len);
820 1766 : if (!converted_name) {
821 0 : tds_connection_close(tds->conn);
822 0 : return TDS_FAIL;
823 : }
824 :
825 : /* UTF-16 length is always size / 2 even for 4 byte letters (yes, 1 letter of length 2) */
826 1766 : TDS_PUT_BYTE(tds, converted_len / 2);
827 1766 : tds_put_n(tds, converted_name, converted_len);
828 :
829 3532 : tds_convert_string_free(tds_dstr_cstr(&bcpcol->column_name), converted_name);
830 : }
831 :
832 202 : tds_set_state(tds, TDS_SENDING);
833 202 : return TDS_SUCCESS;
834 : }
835 :
836 : /**
837 : * Tell we finished sending BCP data to server
838 : * \tds
839 : * \param[out] rows_copied number of rows copied to server
840 : */
841 : TDSRET
842 266 : tds_bcp_done(TDSSOCKET *tds, int *rows_copied)
843 : {
844 266 : tdsdump_log(TDS_DBG_FUNC, "tds_bcp_done(%p, %p)\n", tds, rows_copied);
845 :
846 266 : if (tds->out_flag != TDS_BULK || tds_set_state(tds, TDS_WRITING) != TDS_WRITING)
847 : return TDS_FAIL;
848 :
849 258 : tds_flush_packet(tds);
850 :
851 258 : tds_set_state(tds, TDS_PENDING);
852 :
853 258 : TDS_PROPAGATE(tds_process_simple_query(tds));
854 :
855 252 : if (rows_copied)
856 252 : *rows_copied = tds->rows_affected;
857 :
858 : return TDS_SUCCESS;
859 : }
860 :
861 : /**
862 : * Start sending BCP data to server.
863 : * Initialize stream to accept data.
864 : * \tds
865 : * \param bcpinfo BCP information already prepared
866 : */
867 : TDSRET
868 258 : tds_bcp_start(TDSSOCKET *tds, TDSBCPINFO *bcpinfo)
869 : {
870 : TDSRET rc;
871 :
872 258 : tdsdump_log(TDS_DBG_FUNC, "tds_bcp_start(%p, %p)\n", tds, bcpinfo);
873 :
874 258 : if (!IS_TDS50_PLUS(tds->conn))
875 : return TDS_FAIL;
876 :
877 258 : TDS_PROPAGATE(tds_submit_query(tds, bcpinfo->insert_stmt));
878 :
879 : /* set we want to switch to bulk state */
880 258 : tds->bulk_query = true;
881 :
882 : /*
883 : * In TDS 5 we get the column information as a result set from the "insert bulk" command.
884 : */
885 258 : if (IS_TDS50(tds->conn))
886 56 : rc = tds5_process_insert_bulk_reply(tds, bcpinfo);
887 : else
888 202 : rc = tds_process_simple_query(tds);
889 258 : TDS_PROPAGATE(rc);
890 :
891 258 : tds->out_flag = TDS_BULK;
892 258 : if (tds_set_state(tds, TDS_SENDING) != TDS_SENDING)
893 : return TDS_FAIL;
894 :
895 258 : if (IS_TDS7_PLUS(tds->conn))
896 202 : tds7_bcp_send_colmetadata(tds, bcpinfo);
897 :
898 : return TDS_SUCCESS;
899 : }
900 :
901 : enum {
902 : /* list of columns we need, 0-nnn */
903 : BULKCOL_colcnt,
904 : BULKCOL_colid,
905 : BULKCOL_type,
906 : BULKCOL_length,
907 : BULKCOL_status,
908 : BULKCOL_offset,
909 :
910 : /* number of columns needed */
911 : BULKCOL_COUNT,
912 :
913 : /* bitmask to have them all */
914 : BULKCOL_ALL = (1 << BULKCOL_COUNT) -1,
915 : };
916 :
917 : static int
918 672 : tds5_bulk_insert_column(const char *name)
919 : {
920 : #define BULKCOL(n) do {\
921 : if (strcmp(name, #n) == 0) \
922 : return BULKCOL_ ## n; \
923 : } while(0)
924 :
925 672 : switch (name[0]) {
926 112 : case 'c':
927 112 : BULKCOL(colcnt);
928 56 : BULKCOL(colid);
929 : break;
930 56 : case 't':
931 56 : BULKCOL(type);
932 : break;
933 56 : case 'l':
934 56 : BULKCOL(length);
935 : break;
936 112 : case 's':
937 112 : BULKCOL(status);
938 : break;
939 56 : case 'o':
940 56 : BULKCOL(offset);
941 : break;
942 : }
943 : #undef BULKCOL
944 336 : return -1;
945 : }
946 :
947 : static TDSRET
948 56 : tds5_process_insert_bulk_reply(TDSSOCKET * tds, TDSBCPINFO *bcpinfo)
949 : {
950 : TDS_INT res_type;
951 : TDS_INT done_flags;
952 : TDSRET rc;
953 56 : TDSRET ret = TDS_SUCCESS;
954 56 : bool row_match = false;
955 : TDSRESULTINFO *res_info;
956 : int icol;
957 : unsigned col_flags;
958 : /* position of the columns in the row */
959 : int cols_pos[BULKCOL_COUNT];
960 : int cols_values[BULKCOL_COUNT];
961 : TDS5COLINFO *colinfo;
962 :
963 56 : CHECK_TDS_EXTRA(tds);
964 :
965 706 : while ((rc = tds_process_tokens(tds, &res_type, &done_flags, TDS_RETURN_DONE|TDS_RETURN_ROWFMT|TDS_RETURN_ROW)) == TDS_SUCCESS) {
966 650 : switch (res_type) {
967 56 : case TDS_ROWFMT_RESULT:
968 : /* check if it's the resultset with column information and save column positions */
969 56 : row_match = false;
970 56 : col_flags = 0;
971 56 : res_info = tds->current_results;
972 56 : if (!res_info)
973 0 : continue;
974 672 : for (icol = 0; icol < res_info->num_cols; ++icol) {
975 672 : const TDSCOLUMN *col = res_info->columns[icol];
976 1344 : int scol = tds5_bulk_insert_column(tds_dstr_cstr(&col->column_name));
977 672 : if (scol < 0)
978 336 : continue;
979 336 : cols_pos[scol] = icol;
980 336 : col_flags |= 1 << scol;
981 : }
982 56 : if (col_flags == BULKCOL_ALL)
983 56 : row_match = true;
984 : break;
985 538 : case TDS_ROW_RESULT:
986 : /* get the results */
987 538 : col_flags = 0;
988 538 : if (!row_match)
989 0 : continue;
990 538 : res_info = tds->current_results;
991 538 : if (!res_info)
992 0 : continue;
993 3228 : for (icol = 0; icol < BULKCOL_COUNT; ++icol) {
994 3228 : const TDSCOLUMN *col = res_info->columns[cols_pos[icol]];
995 3228 : int ctype = tds_get_conversion_type(col->on_server.column_type, col->column_size);
996 3228 : unsigned char *src = col->column_data;
997 3228 : int srclen = col->column_cur_size;
998 : CONV_RESULT dres;
999 :
1000 3228 : if (tds_convert(tds_get_ctx(tds), ctype, src, srclen, SYBINT4, &dres) < 0)
1001 : break;
1002 3228 : col_flags |= 1 << icol;
1003 3228 : cols_values[icol] = dres.i;
1004 : }
1005 : /* save information */
1006 1076 : if (col_flags != BULKCOL_ALL ||
1007 1076 : cols_values[BULKCOL_colcnt] < 1 ||
1008 538 : cols_values[BULKCOL_colcnt] > 4096 || /* limit of columns accepted */
1009 1076 : cols_values[BULKCOL_colid] < 1 ||
1010 : cols_values[BULKCOL_colid] > cols_values[BULKCOL_colcnt]) {
1011 : rc = TDS_FAIL;
1012 : break;
1013 : }
1014 538 : if (bcpinfo->sybase_colinfo == NULL) {
1015 50 : bcpinfo->sybase_colinfo = calloc(cols_values[BULKCOL_colcnt], sizeof(*bcpinfo->sybase_colinfo));
1016 50 : if (bcpinfo->sybase_colinfo == NULL) {
1017 : rc = TDS_FAIL;
1018 : break;
1019 : }
1020 50 : bcpinfo->sybase_count = cols_values[BULKCOL_colcnt];
1021 : }
1022 : /* bound check, colcnt could have changed from row to row */
1023 538 : if (cols_values[BULKCOL_colid] > bcpinfo->sybase_count) {
1024 : rc = TDS_FAIL;
1025 : break;
1026 : }
1027 538 : colinfo = &bcpinfo->sybase_colinfo[cols_values[BULKCOL_colid] - 1];
1028 538 : colinfo->type = cols_values[BULKCOL_type];
1029 538 : colinfo->status = cols_values[BULKCOL_status];
1030 538 : colinfo->offset = cols_values[BULKCOL_offset];
1031 538 : colinfo->length = cols_values[BULKCOL_length];
1032 538 : tdsdump_log(TDS_DBG_INFO1, "gotten row information %d type %d length %d status %d offset %d\n",
1033 : cols_values[BULKCOL_colid],
1034 : colinfo->type,
1035 : colinfo->length,
1036 : colinfo->status,
1037 : colinfo->offset);
1038 : break;
1039 56 : case TDS_DONE_RESULT:
1040 : case TDS_DONEPROC_RESULT:
1041 : case TDS_DONEINPROC_RESULT:
1042 56 : if ((done_flags & TDS_DONE_ERROR) != 0)
1043 0 : ret = TDS_FAIL;
1044 : default:
1045 : break;
1046 : }
1047 : }
1048 56 : if (TDS_FAILED(rc))
1049 0 : ret = rc;
1050 :
1051 56 : return ret;
1052 : }
1053 :
1054 : /**
1055 : * Free row data allocated in the result set.
1056 : */
1057 : static void
1058 74 : tds_bcp_row_free(TDSRESULTINFO* result, unsigned char *row TDS_UNUSED)
1059 : {
1060 74 : result->row_size = 0;
1061 74 : TDS_ZERO_FREE(result->current_row);
1062 74 : }
1063 :
1064 : /**
1065 : * Start bulk copy to server
1066 : * \tds
1067 : * \param bcpinfo BCP information already prepared
1068 : */
1069 : TDSRET
1070 232 : tds_bcp_start_copy_in(TDSSOCKET *tds, TDSBCPINFO *bcpinfo)
1071 : {
1072 : TDSCOLUMN *bcpcol;
1073 : int i;
1074 232 : int fixed_col_len_tot = 0;
1075 232 : int variable_col_len_tot = 0;
1076 232 : int column_bcp_data_size = 0;
1077 232 : int bcp_record_size = 0;
1078 : TDSRET rc;
1079 : TDS_INT var_cols;
1080 :
1081 232 : tdsdump_log(TDS_DBG_FUNC, "tds_bcp_start_copy_in(%p, %p)\n", tds, bcpinfo);
1082 :
1083 232 : TDS_PROPAGATE(tds_bcp_start_insert_stmt(tds, bcpinfo));
1084 :
1085 232 : rc = tds_bcp_start(tds, bcpinfo);
1086 232 : if (TDS_FAILED(rc)) {
1087 : /* TODO, in CTLib was _ctclient_msg(blkdesc->con, "blk_rowxfer", 2, 5, 1, 140, ""); */
1088 : return rc;
1089 : }
1090 :
1091 : /*
1092 : * Work out the number of "variable" columns. These are either nullable or of
1093 : * varying length type e.g. varchar.
1094 : */
1095 232 : var_cols = 0;
1096 :
1097 232 : if (IS_TDS50(tds->conn)) {
1098 368 : for (i = 0; i < bcpinfo->bindinfo->num_cols; i++) {
1099 :
1100 368 : bcpcol = bcpinfo->bindinfo->columns[i];
1101 :
1102 : /*
1103 : * work out storage required for this datatype
1104 : * blobs always require 16, numerics vary, the
1105 : * rest can be taken from the server
1106 : */
1107 :
1108 368 : if (is_blob_type(bcpcol->on_server.column_type))
1109 : column_bcp_data_size = 16;
1110 362 : else if (is_numeric_type(bcpcol->on_server.column_type))
1111 34 : column_bcp_data_size = tds_numeric_bytes_per_prec[bcpcol->column_prec];
1112 : else
1113 328 : column_bcp_data_size = bcpcol->column_size;
1114 :
1115 : /*
1116 : * now add that size into either fixed or variable
1117 : * column totals...
1118 : */
1119 :
1120 368 : if (is_nullable_type(bcpcol->on_server.column_type) || bcpcol->column_nullable) {
1121 206 : var_cols++;
1122 206 : variable_col_len_tot += column_bcp_data_size;
1123 : }
1124 : else {
1125 162 : fixed_col_len_tot += column_bcp_data_size;
1126 : }
1127 : }
1128 :
1129 : /* this formula taken from sybase manual... */
1130 :
1131 100 : bcp_record_size = 4 +
1132 50 : fixed_col_len_tot +
1133 50 : variable_col_len_tot +
1134 100 : ( (int)(variable_col_len_tot / 256 ) + 1 ) +
1135 50 : (var_cols + 1) +
1136 : 2;
1137 :
1138 50 : tdsdump_log(TDS_DBG_FUNC, "current_record_size = %d\n", bcpinfo->bindinfo->row_size);
1139 50 : tdsdump_log(TDS_DBG_FUNC, "bcp_record_size = %d\n", bcp_record_size);
1140 :
1141 50 : if (bcp_record_size > bcpinfo->bindinfo->row_size) {
1142 20 : if (!TDS_RESIZE(bcpinfo->bindinfo->current_row, bcp_record_size)) {
1143 0 : tdsdump_log(TDS_DBG_FUNC, "could not realloc current_row\n");
1144 : return TDS_FAIL;
1145 : }
1146 20 : bcpinfo->bindinfo->row_free = tds_bcp_row_free;
1147 20 : bcpinfo->bindinfo->row_size = bcp_record_size;
1148 : }
1149 : }
1150 :
1151 : return TDS_SUCCESS;
1152 : }
1153 :
1154 : /** input stream to read a file */
1155 : typedef struct tds_file_stream {
1156 : /** common fields, must be the first field */
1157 : TDSINSTREAM stream;
1158 : /** file to read from */
1159 : FILE *f;
1160 :
1161 : /** terminator */
1162 : const char *terminator;
1163 : /** terminator length in bytes */
1164 : size_t term_len;
1165 :
1166 : /** buffer for store bytes readed that could be the terminator */
1167 : char *left;
1168 : size_t left_pos;
1169 : } TDSFILESTREAM;
1170 :
1171 : /** \cond HIDDEN_SYMBOLS */
1172 : #if defined(_WIN32) && defined(HAVE__LOCK_FILE) && defined(HAVE__UNLOCK_FILE)
1173 : #define TDS_HAVE_STDIO_LOCKED 1
1174 : #define flockfile(s) _lock_file(s)
1175 : #define funlockfile(s) _unlock_file(s)
1176 : #define getc_unlocked(s) _getc_nolock(s)
1177 : #define feof_unlocked(s) _feof_nolock(s)
1178 : #endif
1179 :
1180 : #ifndef TDS_HAVE_STDIO_LOCKED
1181 : #undef getc_unlocked
1182 : #undef feof_unlocked
1183 : #undef flockfile
1184 : #undef funlockfile
1185 : #define getc_unlocked(s) getc(s)
1186 : #define feof_unlocked(s) feof(s)
1187 : #define flockfile(s) do { } while(0)
1188 : #define funlockfile(s) do { } while(0)
1189 : #endif
1190 : /** \endcond */
1191 :
1192 : /**
1193 : * Reads a chunk of data from file stream checking for terminator
1194 : * \param stream file stream
1195 : * \param ptr buffer where to read data
1196 : * \param len length of buffer
1197 : */
1198 : static int
1199 3736 : tds_file_stream_read(TDSINSTREAM *stream, void *ptr, size_t len)
1200 : {
1201 3736 : TDSFILESTREAM *s = (TDSFILESTREAM *) stream;
1202 : int c;
1203 3736 : char *p = (char *) ptr;
1204 :
1205 1514414 : while (len) {
1206 1510318 : if (memcmp(s->left, s->terminator - s->left_pos, s->term_len) == 0)
1207 3376 : return p - (char *) ptr;
1208 :
1209 3013884 : c = getc_unlocked(s->f);
1210 1506942 : if (c == EOF)
1211 : return -1;
1212 :
1213 1506942 : *p++ = s->left[s->left_pos];
1214 1506942 : --len;
1215 :
1216 1506942 : s->left[s->left_pos++] = c;
1217 1506942 : s->left_pos %= s->term_len;
1218 : }
1219 360 : return p - (char *) ptr;
1220 : }
1221 :
1222 : /**
1223 : * Read a data file, passing the data through iconv().
1224 : * \retval TDS_SUCCESS success
1225 : * \retval TDS_FAIL error reading the column
1226 : * \retval TDS_NO_MORE_RESULTS end of file detected
1227 : */
1228 : TDSRET
1229 1828 : tds_bcp_fread(TDSSOCKET * tds, TDSICONV * char_conv, FILE * stream, const char *terminator, size_t term_len, char **outbuf, size_t * outbytes)
1230 : {
1231 : TDSRET res;
1232 : TDSFILESTREAM r;
1233 : TDSDYNAMICSTREAM w;
1234 : size_t readed;
1235 :
1236 : /* prepare streams */
1237 1828 : r.stream.read = tds_file_stream_read;
1238 1828 : r.f = stream;
1239 1828 : r.term_len = term_len;
1240 1828 : r.left = tds_new0(char, term_len*3);
1241 1828 : r.left_pos = 0;
1242 1828 : if (!r.left) return TDS_FAIL;
1243 :
1244 : /* copy terminator twice, let terminator points to second copy */
1245 1828 : memcpy(r.left + term_len, terminator, term_len);
1246 1828 : memcpy(r.left + term_len*2u, terminator, term_len);
1247 1828 : r.terminator = r.left + term_len*2u;
1248 :
1249 : /* read initial buffer to test with terminator */
1250 1828 : readed = fread(r.left, 1, term_len, stream);
1251 1828 : if (readed != term_len) {
1252 96 : free(r.left);
1253 96 : if (readed == 0 && feof(stream))
1254 : return TDS_NO_MORE_RESULTS;
1255 : return TDS_FAIL;
1256 : }
1257 :
1258 1732 : res = tds_dynamic_stream_init(&w, (void**) outbuf, 0);
1259 1732 : if (TDS_FAILED(res)) {
1260 0 : free(r.left);
1261 0 : return res;
1262 : }
1263 :
1264 : /* convert/copy from input stream to output one */
1265 1732 : flockfile(stream);
1266 1732 : if (char_conv == NULL)
1267 640 : res = tds_copy_stream(&r.stream, &w.stream);
1268 : else
1269 1092 : res = tds_convert_stream(tds, char_conv, to_server, &r.stream, &w.stream);
1270 1732 : funlockfile(stream);
1271 1732 : free(r.left);
1272 :
1273 1732 : TDS_PROPAGATE(res);
1274 :
1275 1732 : *outbytes = w.size;
1276 :
1277 : /* terminate buffer */
1278 1732 : if (!w.stream.buf_len)
1279 : return TDS_FAIL;
1280 :
1281 1732 : ((char *) w.stream.buffer)[0] = 0;
1282 1732 : w.stream.write(&w.stream, 1);
1283 :
1284 1732 : return res;
1285 : }
1286 :
1287 : /**
1288 : * Start writing writetext request.
1289 : * This request start a bulk session.
1290 : * \tds
1291 : * \param objname table name
1292 : * \param textptr TEXTPTR (see sql documentation)
1293 : * \param timestamp data timestamp
1294 : * \param with_log is log is enabled during insert
1295 : * \param size bytes to be inserted
1296 : */
1297 : TDSRET
1298 54 : tds_writetext_start(TDSSOCKET *tds, const char *objname, const char *textptr, const char *timestamp, int with_log, TDS_UINT size)
1299 : {
1300 : TDSRET rc;
1301 :
1302 : /* TODO mssql does not like timestamp */
1303 54 : rc = tds_submit_queryf(tds,
1304 : "writetext bulk %s 0x%s timestamp = 0x%s%s",
1305 : objname, textptr, timestamp, with_log ? " with log" : "");
1306 54 : TDS_PROPAGATE(rc);
1307 :
1308 : /* set we want to switch to bulk state */
1309 54 : tds->bulk_query = true;
1310 :
1311 : /* read the end token */
1312 54 : TDS_PROPAGATE(tds_process_simple_query(tds));
1313 :
1314 54 : tds->out_flag = TDS_BULK;
1315 54 : if (tds_set_state(tds, TDS_WRITING) != TDS_WRITING)
1316 : return TDS_FAIL;
1317 :
1318 54 : tds_put_int(tds, size);
1319 :
1320 54 : tds_set_state(tds, TDS_SENDING);
1321 54 : return TDS_SUCCESS;
1322 : }
1323 :
1324 : /**
1325 : * Send some data in the writetext request started by tds_writetext_start.
1326 : * You should write in total (with multiple calls to this function) all
1327 : * bytes declared calling tds_writetext_start.
1328 : * \tds
1329 : * \param text data to write
1330 : * \param size data size in bytes
1331 : */
1332 : TDSRET
1333 408 : tds_writetext_continue(TDSSOCKET *tds, const TDS_UCHAR *text, TDS_UINT size)
1334 : {
1335 408 : if (tds->out_flag != TDS_BULK || tds_set_state(tds, TDS_WRITING) != TDS_WRITING)
1336 : return TDS_FAIL;
1337 :
1338 : /* TODO check size left */
1339 408 : tds_put_n(tds, text, size);
1340 :
1341 408 : tds_set_state(tds, TDS_SENDING);
1342 408 : return TDS_SUCCESS;
1343 : }
1344 :
1345 : /**
1346 : * Finish sending writetext data.
1347 : * \tds
1348 : */
1349 : TDSRET
1350 54 : tds_writetext_end(TDSSOCKET *tds)
1351 : {
1352 54 : if (tds->out_flag != TDS_BULK || tds_set_state(tds, TDS_WRITING) != TDS_WRITING)
1353 : return TDS_FAIL;
1354 :
1355 54 : tds_flush_packet(tds);
1356 54 : tds_set_state(tds, TDS_PENDING);
1357 54 : return TDS_SUCCESS;
1358 : }
|