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 : /**
51 : * Holds clause buffer
52 : */
53 : typedef struct tds_pbcb
54 : {
55 : /** buffer */
56 : char *pb;
57 : /** buffer length */
58 : unsigned int cb;
59 : /** true is buffer came from malloc */
60 : bool from_malloc;
61 : } TDSPBCB;
62 :
63 : static TDSRET tds7_bcp_send_colmetadata(TDSSOCKET *tds, TDSBCPINFO *bcpinfo);
64 : static TDSRET tds_bcp_start_insert_stmt(TDSSOCKET *tds, TDSBCPINFO *bcpinfo);
65 : static int tds5_bcp_add_fixed_columns(TDSBCPINFO *bcpinfo, tds_bcp_get_col_data get_col_data, tds_bcp_null_error null_error,
66 : int offset, unsigned char * rowbuffer, int start);
67 : static int tds5_bcp_add_variable_columns(TDSBCPINFO *bcpinfo, tds_bcp_get_col_data get_col_data, tds_bcp_null_error null_error,
68 : int offset, TDS_UCHAR *rowbuffer, int start, int *pncols);
69 : static void tds_bcp_row_free(TDSRESULTINFO* result, unsigned char *row);
70 : static TDSRET tds5_process_insert_bulk_reply(TDSSOCKET * tds, TDSBCPINFO *bcpinfo);
71 :
72 : /**
73 : * Initialize BCP information.
74 : * Query structure of the table to server.
75 : * \tds
76 : * \param bcpinfo BCP information to initialize. Structure should be allocate
77 : * and table name and direction should be already set.
78 : */
79 : TDSRET
80 460 : tds_bcp_init(TDSSOCKET *tds, TDSBCPINFO *bcpinfo)
81 : {
82 : TDSRESULTINFO *resinfo;
83 460 : TDSRESULTINFO *bindinfo = NULL;
84 : TDSCOLUMN *curcol;
85 : TDS_INT result_type;
86 : int i;
87 : TDSRET rc;
88 : const char *fmt;
89 :
90 : /* FIXME don't leave state in processing state */
91 :
92 : /* TODO quote tablename if needed */
93 460 : if (bcpinfo->direction != TDS_BCP_QUERYOUT)
94 : fmt = "SET FMTONLY ON select * from %s SET FMTONLY OFF";
95 : else
96 10 : fmt = "SET FMTONLY ON %s SET FMTONLY OFF";
97 :
98 920 : if (TDS_FAILED(rc=tds_submit_queryf(tds, fmt, tds_dstr_cstr(&bcpinfo->tablename))))
99 : /* TODO return an error ?? */
100 : /* Attempt to use Bulk Copy with a non-existent Server table (might be why ...) */
101 : return rc;
102 :
103 : /* TODO possibly stop at ROWFMT and copy before going to idle */
104 : /* TODO check what happen if table is not present, cleanup on error */
105 2300 : while ((rc = tds_process_tokens(tds, &result_type, NULL, TDS_TOKEN_RESULTS))
106 : == TDS_SUCCESS)
107 1840 : continue;
108 460 : TDS_PROPAGATE(rc);
109 :
110 : /* copy the results info from the TDS socket */
111 460 : if (!tds->res_info)
112 : return TDS_FAIL;
113 :
114 460 : resinfo = tds->res_info;
115 460 : if ((bindinfo = tds_alloc_results(resinfo->num_cols)) == NULL) {
116 : rc = TDS_FAIL;
117 : goto cleanup;
118 : }
119 :
120 460 : bindinfo->row_size = resinfo->row_size;
121 :
122 : /* Copy the column metadata */
123 460 : rc = TDS_FAIL;
124 3548 : for (i = 0; i < bindinfo->num_cols; i++) {
125 :
126 3088 : curcol = bindinfo->columns[i];
127 :
128 : /*
129 : * TODO use memcpy ??
130 : * curcol and resinfo->columns[i] are both TDSCOLUMN.
131 : * Why not "curcol = resinfo->columns[i];"? Because the rest of TDSCOLUMN (below column_timestamp)
132 : * isn't being used. Perhaps this "upper" part of TDSCOLUMN should be a substructure.
133 : * Or, see if the "lower" part is unused (and zeroed out) at this point, and just do one assignment.
134 : */
135 3088 : curcol->funcs = resinfo->columns[i]->funcs;
136 3088 : curcol->column_type = resinfo->columns[i]->column_type;
137 3088 : curcol->column_usertype = resinfo->columns[i]->column_usertype;
138 3088 : curcol->column_flags = resinfo->columns[i]->column_flags;
139 3088 : if (curcol->column_varint_size == 0)
140 3088 : curcol->column_cur_size = resinfo->columns[i]->column_cur_size;
141 : else
142 0 : curcol->column_cur_size = -1;
143 3088 : curcol->column_size = resinfo->columns[i]->column_size;
144 3088 : curcol->column_varint_size = resinfo->columns[i]->column_varint_size;
145 3088 : curcol->column_prec = resinfo->columns[i]->column_prec;
146 3088 : curcol->column_scale = resinfo->columns[i]->column_scale;
147 3088 : curcol->on_server = resinfo->columns[i]->on_server;
148 3088 : curcol->char_conv = resinfo->columns[i]->char_conv;
149 3088 : if (!tds_dstr_dup(&curcol->column_name, &resinfo->columns[i]->column_name))
150 : goto cleanup;
151 3088 : if (!tds_dstr_dup(&curcol->table_column_name, &resinfo->columns[i]->table_column_name))
152 : goto cleanup;
153 3088 : curcol->column_nullable = resinfo->columns[i]->column_nullable;
154 3088 : curcol->column_identity = resinfo->columns[i]->column_identity;
155 3088 : curcol->column_timestamp = resinfo->columns[i]->column_timestamp;
156 3088 : curcol->column_computed = resinfo->columns[i]->column_computed;
157 :
158 3088 : memcpy(curcol->column_collation, resinfo->columns[i]->column_collation, 5);
159 :
160 3088 : if (is_numeric_type(curcol->column_type)) {
161 224 : curcol->bcp_column_data = tds_alloc_bcp_column_data(sizeof(TDS_NUMERIC));
162 224 : ((TDS_NUMERIC *) curcol->bcp_column_data->data)->precision = curcol->column_prec;
163 224 : ((TDS_NUMERIC *) curcol->bcp_column_data->data)->scale = curcol->column_scale;
164 : } else {
165 2864 : curcol->bcp_column_data =
166 2864 : tds_alloc_bcp_column_data(TDS_MAX(curcol->column_size,curcol->on_server.column_size));
167 : }
168 3088 : if (!curcol->bcp_column_data)
169 : goto cleanup;
170 : }
171 :
172 460 : if (!IS_TDS7_PLUS(tds->conn)) {
173 76 : bindinfo->current_row = tds_new(unsigned char, bindinfo->row_size);
174 76 : if (!bindinfo->current_row)
175 : goto cleanup;
176 76 : bindinfo->row_free = tds_bcp_row_free;
177 : }
178 :
179 460 : if (bcpinfo->identity_insert_on) {
180 :
181 0 : rc = tds_submit_queryf(tds, "set identity_insert %s on", tds_dstr_cstr(&bcpinfo->tablename));
182 0 : if (TDS_FAILED(rc))
183 : goto cleanup;
184 :
185 : /* TODO use tds_process_simple_query */
186 0 : while ((rc = tds_process_tokens(tds, &result_type, NULL, TDS_TOKEN_RESULTS))
187 : == TDS_SUCCESS) {
188 : }
189 0 : if (rc != TDS_NO_MORE_RESULTS)
190 : goto cleanup;
191 : }
192 :
193 460 : bcpinfo->bindinfo = bindinfo;
194 460 : bcpinfo->bind_count = 0;
195 460 : return TDS_SUCCESS;
196 :
197 0 : cleanup:
198 0 : tds_free_results(bindinfo);
199 0 : return rc;
200 : }
201 :
202 : /**
203 : * Help to build query to be sent to server.
204 : * Append column declaration to the query.
205 : * Only for TDS 7.0+.
206 : * \tds
207 : * \param[out] clause output string
208 : * \param bcpcol column to append
209 : * \param first true if column is the first
210 : * \return TDS_SUCCESS or TDS_FAIL.
211 : */
212 : static TDSRET
213 1678 : tds7_build_bulk_insert_stmt(TDSSOCKET * tds, TDSPBCB * clause, TDSCOLUMN * bcpcol, int first)
214 : {
215 : char column_type[40];
216 :
217 1678 : tdsdump_log(TDS_DBG_FUNC, "tds7_build_bulk_insert_stmt(%p, %p, %p, %d)\n", tds, clause, bcpcol, first);
218 :
219 1678 : if (TDS_FAILED(tds_get_column_declaration(tds, bcpcol, column_type))) {
220 0 : tdserror(tds_get_ctx(tds), tds, TDSEBPROBADTYP, errno);
221 0 : tdsdump_log(TDS_DBG_FUNC, "error: cannot build bulk insert statement. unrecognized server datatype %d\n",
222 0 : bcpcol->on_server.column_type);
223 : return TDS_FAIL;
224 : }
225 :
226 3356 : if (clause->cb < strlen(clause->pb)
227 5034 : + tds_quote_id(tds, NULL, tds_dstr_cstr(&bcpcol->column_name), tds_dstr_len(&bcpcol->column_name))
228 1678 : + strlen(column_type)
229 1678 : + ((first) ? 2u : 4u)) {
230 0 : char *temp = tds_new(char, 2 * clause->cb);
231 :
232 0 : if (!temp) {
233 0 : tdserror(tds_get_ctx(tds), tds, TDSEMEM, errno);
234 0 : return TDS_FAIL;
235 : }
236 0 : strcpy(temp, clause->pb);
237 0 : if (clause->from_malloc)
238 0 : free(clause->pb);
239 0 : clause->from_malloc = true;
240 0 : clause->pb = temp;
241 0 : clause->cb *= 2;
242 : }
243 :
244 1678 : if (!first)
245 1424 : strcat(clause->pb, ", ");
246 :
247 5034 : tds_quote_id(tds, strchr(clause->pb, 0), tds_dstr_cstr(&bcpcol->column_name), tds_dstr_len(&bcpcol->column_name));
248 1678 : strcat(clause->pb, " ");
249 1678 : strcat(clause->pb, column_type);
250 :
251 1678 : return TDS_SUCCESS;
252 : }
253 :
254 : /**
255 : * Prepare the query to be sent to server to request BCP information
256 : * \tds
257 : * \param bcpinfo BCP information
258 : */
259 : static TDSRET
260 306 : tds_bcp_start_insert_stmt(TDSSOCKET * tds, TDSBCPINFO * bcpinfo)
261 : {
262 : char *query;
263 :
264 306 : if (IS_TDS7_PLUS(tds->conn)) {
265 : int i, firstcol, erc;
266 : char *hint;
267 : TDSCOLUMN *bcpcol;
268 : TDSPBCB colclause;
269 254 : char clause_buffer[4096] = { 0 };
270 :
271 254 : colclause.pb = clause_buffer;
272 254 : colclause.cb = sizeof(clause_buffer);
273 254 : colclause.from_malloc = false;
274 :
275 : /* TODO avoid asprintf, use always malloc-ed buffer */
276 254 : firstcol = 1;
277 :
278 1932 : for (i = 0; i < bcpinfo->bindinfo->num_cols; i++) {
279 1678 : bcpcol = bcpinfo->bindinfo->columns[i];
280 :
281 1678 : if (bcpcol->column_timestamp)
282 0 : continue;
283 1678 : if (!bcpinfo->identity_insert_on && bcpcol->column_identity)
284 0 : continue;
285 1678 : if (bcpcol->column_computed)
286 0 : continue;
287 1678 : tds7_build_bulk_insert_stmt(tds, &colclause, bcpcol, firstcol);
288 1678 : firstcol = 0;
289 : }
290 :
291 508 : if (!tds_dstr_isempty(&bcpinfo->hint)) {
292 168 : if (asprintf(&hint, " with (%s)", tds_dstr_cstr(&bcpinfo->hint)) < 0)
293 0 : hint = NULL;
294 : } else {
295 170 : hint = strdup("");
296 : }
297 254 : if (!hint) {
298 0 : if (colclause.from_malloc)
299 0 : TDS_ZERO_FREE(colclause.pb);
300 0 : return TDS_FAIL;
301 : }
302 :
303 508 : erc = asprintf(&query, "insert bulk %s (%s)%s", tds_dstr_cstr(&bcpinfo->tablename), colclause.pb, hint);
304 :
305 254 : free(hint);
306 254 : if (colclause.from_malloc)
307 0 : TDS_ZERO_FREE(colclause.pb); /* just for good measure; not used beyond this point */
308 :
309 254 : if (erc < 0)
310 : return TDS_FAIL;
311 : } else {
312 : /* NOTE: if we use "with nodescribe" for following inserts server do not send describe */
313 104 : if (asprintf(&query, "insert bulk %s", tds_dstr_cstr(&bcpinfo->tablename)) < 0)
314 : return TDS_FAIL;
315 : }
316 :
317 : /* save the statement for later... */
318 306 : bcpinfo->insert_stmt = query;
319 :
320 306 : return TDS_SUCCESS;
321 : }
322 :
323 : static TDSRET
324 780 : tds7_send_record(TDSSOCKET *tds, TDSBCPINFO *bcpinfo,
325 : tds_bcp_get_col_data get_col_data, tds_bcp_null_error null_error, int offset)
326 : {
327 : int i;
328 :
329 780 : tds_put_byte(tds, TDS_ROW_TOKEN); /* 0xd1 */
330 12340 : for (i = 0; i < bcpinfo->bindinfo->num_cols; i++) {
331 :
332 : TDS_INT save_size;
333 : unsigned char *save_data;
334 : TDSBLOB blob;
335 : TDSCOLUMN *bindcol;
336 : TDSRET rc;
337 :
338 11560 : bindcol = bcpinfo->bindinfo->columns[i];
339 :
340 : /*
341 : * Don't send the (meta)data for timestamp columns or
342 : * identity columns unless indentity_insert is enabled.
343 : */
344 :
345 11560 : if ((!bcpinfo->identity_insert_on && bindcol->column_identity) ||
346 11560 : bindcol->column_timestamp ||
347 : bindcol->column_computed) {
348 0 : continue;
349 : }
350 :
351 11560 : rc = get_col_data(bcpinfo, bindcol, offset);
352 11560 : if (TDS_FAILED(rc)) {
353 0 : tdsdump_log(TDS_DBG_INFO1, "get_col_data (column %d) failed\n", i + 1);
354 0 : return rc;
355 : }
356 11560 : tdsdump_log(TDS_DBG_INFO1, "gotten column %d length %d null %d\n",
357 0 : i + 1, bindcol->bcp_column_data->datalen, bindcol->bcp_column_data->is_null);
358 :
359 11560 : save_size = bindcol->column_cur_size;
360 11560 : save_data = bindcol->column_data;
361 11560 : assert(bindcol->column_data == NULL);
362 11560 : if (bindcol->bcp_column_data->is_null) {
363 4458 : if (!bindcol->column_nullable && !is_nullable_type(bindcol->on_server.column_type)) {
364 0 : if (null_error)
365 0 : null_error(bcpinfo, i, offset);
366 : return TDS_FAIL;
367 : }
368 4458 : bindcol->column_cur_size = -1;
369 7102 : } else if (is_blob_col(bindcol)) {
370 74 : bindcol->column_cur_size = bindcol->bcp_column_data->datalen;
371 74 : memset(&blob, 0, sizeof(blob));
372 74 : blob.textvalue = (TDS_CHAR *) bindcol->bcp_column_data->data;
373 74 : bindcol->column_data = (unsigned char *) &blob;
374 : } else {
375 7028 : bindcol->column_cur_size = bindcol->bcp_column_data->datalen;
376 7028 : bindcol->column_data = bindcol->bcp_column_data->data;
377 : }
378 11560 : rc = bindcol->funcs->put_data(tds, bindcol, 1);
379 11560 : bindcol->column_cur_size = save_size;
380 11560 : bindcol->column_data = save_data;
381 :
382 11560 : TDS_PROPAGATE(rc);
383 : }
384 : return TDS_SUCCESS;
385 : }
386 :
387 : static TDSRET
388 174 : 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 174 : int blob_cols = 0;
394 174 : int var_cols_written = 0;
395 174 : TDS_INT old_record_size = bcpinfo->bindinfo->row_size;
396 174 : unsigned char *record = bcpinfo->bindinfo->current_row;
397 : int i;
398 :
399 174 : 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 174 : row_pos = 2;
406 :
407 174 : 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 172 : row_sz_pos = row_pos;
411 :
412 : /* potential variable columns to write */
413 :
414 172 : row_pos = tds5_bcp_add_variable_columns(bcpinfo, get_col_data, null_error, offset, record, row_pos, &var_cols_written);
415 172 : if (row_pos < 0)
416 : return TDS_FAIL;
417 :
418 :
419 172 : if (var_cols_written) {
420 154 : TDS_PUT_UA2LE(&record[row_sz_pos], row_pos);
421 154 : record[0] = var_cols_written;
422 : }
423 :
424 172 : tdsdump_log(TDS_DBG_INFO1, "old_record_size = %d new size = %d \n", old_record_size, row_pos);
425 :
426 172 : tds_put_smallint(tds, row_pos);
427 172 : tds_put_n(tds, record, row_pos);
428 :
429 : /* row is done, now handle any text/image data */
430 :
431 172 : blob_cols = 0;
432 :
433 2966 : for (i = 0; i < bcpinfo->bindinfo->num_cols; i++) {
434 2794 : TDSCOLUMN *bindcol = bcpinfo->bindinfo->columns[i];
435 2794 : 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 954 : 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 954 : 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 954 : if (tds->out_flag != TDS_BULK || tds_set_state(tds, TDS_WRITING) != TDS_WRITING)
474 : return TDS_FAIL;
475 :
476 954 : if (IS_TDS7_PLUS(tds->conn))
477 780 : rc = tds7_send_record(tds, bcpinfo, get_col_data, null_error, offset);
478 : else
479 174 : rc = tds5_send_record(tds, bcpinfo, get_col_data, null_error, offset);
480 :
481 954 : tds_set_state(tds, TDS_SENDING);
482 954 : 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 174 : 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 174 : int row_pos = start;
509 : int cpbytes;
510 : int i;
511 174 : int bitleft = 0, bitpos = 0;
512 :
513 174 : assert(bcpinfo);
514 174 : assert(rowbuffer);
515 :
516 174 : 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 2796 : for (i = 0; i < bcpinfo->bindinfo->num_cols; i++) {
520 :
521 2798 : TDSCOLUMN *const bcpcol = bcpinfo->bindinfo->columns[i];
522 2798 : const TDS_INT column_size = bcpcol->on_server.column_size;
523 :
524 : /* if possible check information from server */
525 2798 : if (bcpinfo->sybase_count > i) {
526 2798 : if (bcpinfo->sybase_colinfo[i].offset < 0)
527 1508 : 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 172 : 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 172 : unsigned int ncols = 0;
601 :
602 172 : assert(bcpinfo);
603 172 : assert(rowbuffer);
604 172 : assert(pncols);
605 :
606 172 : 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 2794 : for (i = 0; i < bcpinfo->bindinfo->num_cols; i++) {
612 2794 : TDSCOLUMN *bcpcol = bcpinfo->bindinfo->columns[i];
613 2794 : 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 172 : row_pos = start + 2;
622 172 : offsets[0] = row_pos;
623 :
624 172 : tdsdump_log(TDS_DBG_FUNC, "%4s %8s %8s %8s\n", "col", "ncols", "row_pos", "cpbytes");
625 :
626 2794 : for (i = 0; i < bcpinfo->bindinfo->num_cols; i++) {
627 2794 : unsigned int cpbytes = 0;
628 2794 : 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 2794 : if (bcpinfo->sybase_count > (TDS_INT) i) {
635 2794 : 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 1508 : tdsdump_log(TDS_DBG_FUNC, "%4d %8d %8d %8d\n", i, ncols, row_pos, cpbytes);
643 :
644 1508 : 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 1508 : 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 1508 : if (!bcpcol->bcp_column_data->is_null) {
658 426 : 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 416 : } 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 784 : cpbytes = bcpcol->bcp_column_data->datalen > bcpcol->column_size ?
667 392 : bcpcol->column_size : bcpcol->bcp_column_data->datalen;
668 392 : memcpy(&rowbuffer[row_pos], bcpcol->bcp_column_data->data, cpbytes);
669 392 : tds5_swap_data(bcpcol, &rowbuffer[row_pos]);
670 : }
671 : }
672 :
673 1508 : row_pos += cpbytes;
674 1508 : offsets[++ncols] = row_pos;
675 1508 : tdsdump_dump_buf(TDS_DBG_NETWORK, "BCP row buffer so far", rowbuffer, row_pos);
676 : }
677 :
678 172 : 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 1254 : 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 172 : if (ncols) {
702 154 : TDS_UCHAR *poff = rowbuffer + row_pos;
703 154 : unsigned int pfx_top = offsets[ncols] >> 8;
704 :
705 154 : tdsdump_log(TDS_DBG_FUNC, "ncols=%u poff=%p [%u]\n", ncols, poff, offsets[ncols]);
706 :
707 154 : *poff++ = ncols + 1;
708 : /* this is some kind of run-length-prefix encoding */
709 314 : 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 154 : tdsdump_log(TDS_DBG_FUNC, "poff=%p\n", poff);
720 :
721 580 : for (i=0; i <= ncols; i++)
722 580 : *poff++ = offsets[ncols-i] & 0xFF;
723 154 : row_pos = (unsigned int)(poff - rowbuffer);
724 : }
725 :
726 172 : tdsdump_log(TDS_DBG_FUNC, "%4d %8d %8d\n", i, ncols, row_pos);
727 172 : tdsdump_dump_buf(TDS_DBG_NETWORK, "BCP row buffer", rowbuffer, row_pos);
728 :
729 172 : *pncols = ncols;
730 :
731 172 : 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 282 : tds7_bcp_send_colmetadata(TDSSOCKET *tds, TDSBCPINFO *bcpinfo)
743 : {
744 : TDSCOLUMN *bcpcol;
745 : int i, num_cols;
746 :
747 282 : tdsdump_log(TDS_DBG_FUNC, "tds7_bcp_send_colmetadata(%p, %p)\n", tds, bcpinfo);
748 282 : assert(tds && bcpinfo);
749 :
750 282 : 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 282 : tds_put_byte(tds, TDS7_RESULT_TOKEN); /* 0x81 */
757 :
758 282 : num_cols = 0;
759 2664 : for (i = 0; i < bcpinfo->bindinfo->num_cols; i++) {
760 2382 : bcpcol = bcpinfo->bindinfo->columns[i];
761 2382 : if ((!bcpinfo->identity_insert_on && bcpcol->column_identity) ||
762 2382 : bcpcol->column_timestamp ||
763 : bcpcol->column_computed) {
764 0 : continue;
765 : }
766 2382 : num_cols++;
767 : }
768 :
769 282 : tds_put_smallint(tds, num_cols);
770 :
771 2664 : for (i = 0; i < bcpinfo->bindinfo->num_cols; i++) {
772 : size_t converted_len;
773 : const char *converted_name;
774 :
775 2382 : 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 2382 : if ((!bcpinfo->identity_insert_on && bcpcol->column_identity) ||
783 2382 : bcpcol->column_timestamp ||
784 : bcpcol->column_computed) {
785 0 : continue;
786 : }
787 :
788 2382 : if (IS_TDS72_PLUS(tds->conn))
789 1220 : tds_put_int(tds, bcpcol->column_usertype);
790 : else
791 1162 : tds_put_smallint(tds, bcpcol->column_usertype);
792 2382 : tds_put_smallint(tds, bcpcol->column_flags);
793 2382 : TDS_PUT_BYTE(tds, bcpcol->on_server.column_type);
794 :
795 2382 : assert(bcpcol->funcs);
796 2382 : 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 2382 : if (is_blob_type(bcpcol->on_server.column_type)) {
802 126 : converted_name = tds_convert_string(tds, tds->conn->char_convs[client2ucs2],
803 42 : tds_dstr_cstr(&bcpinfo->tablename),
804 84 : (int) tds_dstr_len(&bcpinfo->tablename), &converted_len);
805 42 : 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 42 : TDS_PUT_SMALLINT(tds, converted_len / 2);
812 42 : tds_put_n(tds, converted_name, converted_len);
813 :
814 84 : tds_convert_string_free(tds_dstr_cstr(&bcpinfo->tablename), converted_name);
815 : }
816 :
817 7146 : converted_name = tds_convert_string(tds, tds->conn->char_convs[client2ucs2],
818 2382 : tds_dstr_cstr(&bcpcol->column_name),
819 4764 : (int) tds_dstr_len(&bcpcol->column_name), &converted_len);
820 2382 : 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 2382 : TDS_PUT_BYTE(tds, converted_len / 2);
827 2382 : tds_put_n(tds, converted_name, converted_len);
828 :
829 4764 : tds_convert_string_free(tds_dstr_cstr(&bcpcol->column_name), converted_name);
830 : }
831 :
832 282 : tds_set_state(tds, TDS_SENDING);
833 282 : 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 350 : tds_bcp_done(TDSSOCKET *tds, int *rows_copied)
843 : {
844 350 : tdsdump_log(TDS_DBG_FUNC, "tds_bcp_done(%p, %p)\n", tds, rows_copied);
845 :
846 350 : if (tds->out_flag != TDS_BULK || tds_set_state(tds, TDS_WRITING) != TDS_WRITING)
847 : return TDS_FAIL;
848 :
849 340 : tds_flush_packet(tds);
850 :
851 340 : tds_set_state(tds, TDS_PENDING);
852 :
853 340 : TDS_PROPAGATE(tds_process_simple_query(tds));
854 :
855 332 : if (rows_copied)
856 332 : *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 340 : tds_bcp_start(TDSSOCKET *tds, TDSBCPINFO *bcpinfo)
869 : {
870 : TDSRET rc;
871 :
872 340 : tdsdump_log(TDS_DBG_FUNC, "tds_bcp_start(%p, %p)\n", tds, bcpinfo);
873 :
874 340 : if (!IS_TDS50_PLUS(tds->conn))
875 : return TDS_FAIL;
876 :
877 340 : TDS_PROPAGATE(tds_submit_query(tds, bcpinfo->insert_stmt));
878 :
879 : /* set we want to switch to bulk state */
880 340 : 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 340 : if (IS_TDS50(tds->conn))
886 58 : rc = tds5_process_insert_bulk_reply(tds, bcpinfo);
887 : else
888 282 : rc = tds_process_simple_query(tds);
889 340 : TDS_PROPAGATE(rc);
890 :
891 340 : tds->out_flag = TDS_BULK;
892 340 : if (tds_set_state(tds, TDS_SENDING) != TDS_SENDING)
893 : return TDS_FAIL;
894 :
895 340 : if (IS_TDS7_PLUS(tds->conn))
896 282 : 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 696 : 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 696 : switch (name[0]) {
926 116 : case 'c':
927 116 : BULKCOL(colcnt);
928 58 : BULKCOL(colid);
929 : break;
930 58 : case 't':
931 58 : BULKCOL(type);
932 : break;
933 58 : case 'l':
934 58 : BULKCOL(length);
935 : break;
936 116 : case 's':
937 116 : BULKCOL(status);
938 : break;
939 58 : case 'o':
940 58 : BULKCOL(offset);
941 : break;
942 : }
943 : #undef BULKCOL
944 348 : return -1;
945 : }
946 :
947 : static TDSRET
948 58 : tds5_process_insert_bulk_reply(TDSSOCKET * tds, TDSBCPINFO *bcpinfo)
949 : {
950 : TDS_INT res_type;
951 : TDS_INT done_flags;
952 : TDSRET rc;
953 58 : TDSRET ret = TDS_SUCCESS;
954 58 : 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 58 : CHECK_TDS_EXTRA(tds);
964 :
965 714 : while ((rc = tds_process_tokens(tds, &res_type, &done_flags, TDS_RETURN_DONE|TDS_RETURN_ROWFMT|TDS_RETURN_ROW)) == TDS_SUCCESS) {
966 656 : switch (res_type) {
967 58 : case TDS_ROWFMT_RESULT:
968 : /* check if it's the resultset with column information and save column positions */
969 58 : row_match = false;
970 58 : col_flags = 0;
971 58 : res_info = tds->current_results;
972 58 : if (!res_info)
973 0 : continue;
974 696 : for (icol = 0; icol < res_info->num_cols; ++icol) {
975 696 : const TDSCOLUMN *col = res_info->columns[icol];
976 1392 : int scol = tds5_bulk_insert_column(tds_dstr_cstr(&col->column_name));
977 696 : if (scol < 0)
978 348 : continue;
979 348 : cols_pos[scol] = icol;
980 348 : col_flags |= 1 << scol;
981 : }
982 58 : if (col_flags == BULKCOL_ALL)
983 58 : row_match = true;
984 : break;
985 540 : case TDS_ROW_RESULT:
986 : /* get the results */
987 540 : col_flags = 0;
988 540 : if (!row_match)
989 0 : continue;
990 540 : res_info = tds->current_results;
991 540 : if (!res_info)
992 0 : continue;
993 3240 : for (icol = 0; icol < BULKCOL_COUNT; ++icol) {
994 3240 : const TDSCOLUMN *col = res_info->columns[cols_pos[icol]];
995 3240 : int ctype = tds_get_conversion_type(col->on_server.column_type, col->column_size);
996 3240 : unsigned char *src = col->column_data;
997 3240 : int srclen = col->column_cur_size;
998 : CONV_RESULT dres;
999 :
1000 3240 : if (tds_convert(tds_get_ctx(tds), ctype, src, srclen, SYBINT4, &dres) < 0)
1001 : break;
1002 3240 : col_flags |= 1 << icol;
1003 3240 : cols_values[icol] = dres.i;
1004 : }
1005 : /* save information */
1006 1080 : if (col_flags != BULKCOL_ALL ||
1007 1080 : cols_values[BULKCOL_colcnt] < 1 ||
1008 540 : cols_values[BULKCOL_colcnt] > 4096 || /* limit of columns accepted */
1009 1080 : cols_values[BULKCOL_colid] < 1 ||
1010 : cols_values[BULKCOL_colid] > cols_values[BULKCOL_colcnt]) {
1011 : rc = TDS_FAIL;
1012 : break;
1013 : }
1014 540 : if (bcpinfo->sybase_colinfo == NULL) {
1015 52 : bcpinfo->sybase_colinfo = calloc(cols_values[BULKCOL_colcnt], sizeof(*bcpinfo->sybase_colinfo));
1016 52 : if (bcpinfo->sybase_colinfo == NULL) {
1017 : rc = TDS_FAIL;
1018 : break;
1019 : }
1020 52 : bcpinfo->sybase_count = cols_values[BULKCOL_colcnt];
1021 : }
1022 : /* bound check, colcnt could have changed from row to row */
1023 540 : if (cols_values[BULKCOL_colid] > bcpinfo->sybase_count) {
1024 : rc = TDS_FAIL;
1025 : break;
1026 : }
1027 540 : colinfo = &bcpinfo->sybase_colinfo[cols_values[BULKCOL_colid] - 1];
1028 540 : colinfo->type = cols_values[BULKCOL_type];
1029 540 : colinfo->status = cols_values[BULKCOL_status];
1030 540 : colinfo->offset = cols_values[BULKCOL_offset];
1031 540 : colinfo->length = cols_values[BULKCOL_length];
1032 540 : 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 58 : case TDS_DONE_RESULT:
1040 : case TDS_DONEPROC_RESULT:
1041 : case TDS_DONEINPROC_RESULT:
1042 58 : if ((done_flags & TDS_DONE_ERROR) != 0)
1043 0 : ret = TDS_FAIL;
1044 : default:
1045 : break;
1046 : }
1047 : }
1048 58 : if (TDS_FAILED(rc))
1049 0 : ret = rc;
1050 :
1051 58 : return ret;
1052 : }
1053 :
1054 : /**
1055 : * Free row data allocated in the result set.
1056 : */
1057 : static void
1058 76 : tds_bcp_row_free(TDSRESULTINFO* result, unsigned char *row TDS_UNUSED)
1059 : {
1060 76 : result->row_size = 0;
1061 76 : TDS_ZERO_FREE(result->current_row);
1062 76 : }
1063 :
1064 : /**
1065 : * Start bulk copy to server
1066 : * \tds
1067 : * \param bcpinfo BCP information already prepared
1068 : */
1069 : TDSRET
1070 306 : tds_bcp_start_copy_in(TDSSOCKET *tds, TDSBCPINFO *bcpinfo)
1071 : {
1072 : TDSCOLUMN *bcpcol;
1073 : int i;
1074 306 : int fixed_col_len_tot = 0;
1075 306 : int variable_col_len_tot = 0;
1076 306 : int column_bcp_data_size = 0;
1077 306 : int bcp_record_size = 0;
1078 : TDSRET rc;
1079 : TDS_INT var_cols;
1080 :
1081 306 : tdsdump_log(TDS_DBG_FUNC, "tds_bcp_start_copy_in(%p, %p)\n", tds, bcpinfo);
1082 :
1083 306 : TDS_PROPAGATE(tds_bcp_start_insert_stmt(tds, bcpinfo));
1084 :
1085 306 : rc = tds_bcp_start(tds, bcpinfo);
1086 306 : 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 306 : var_cols = 0;
1096 :
1097 306 : if (IS_TDS50(tds->conn)) {
1098 370 : for (i = 0; i < bcpinfo->bindinfo->num_cols; i++) {
1099 :
1100 370 : 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 370 : if (is_blob_type(bcpcol->on_server.column_type))
1109 : column_bcp_data_size = 16;
1110 364 : 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 330 : 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 370 : if (is_nullable_type(bcpcol->on_server.column_type) || bcpcol->column_nullable) {
1121 208 : var_cols++;
1122 208 : variable_col_len_tot += column_bcp_data_size;
1123 : } else {
1124 162 : fixed_col_len_tot += column_bcp_data_size;
1125 : }
1126 : }
1127 :
1128 : /* this formula taken from sybase manual... */
1129 :
1130 104 : bcp_record_size = 4 +
1131 52 : fixed_col_len_tot +
1132 52 : variable_col_len_tot +
1133 104 : ( (int)(variable_col_len_tot / 256 ) + 1 ) +
1134 52 : (var_cols + 1) +
1135 : 2;
1136 :
1137 52 : tdsdump_log(TDS_DBG_FUNC, "current_record_size = %d\n", bcpinfo->bindinfo->row_size);
1138 52 : tdsdump_log(TDS_DBG_FUNC, "bcp_record_size = %d\n", bcp_record_size);
1139 :
1140 52 : if (bcp_record_size > bcpinfo->bindinfo->row_size) {
1141 22 : if (!TDS_RESIZE(bcpinfo->bindinfo->current_row, bcp_record_size)) {
1142 0 : tdsdump_log(TDS_DBG_FUNC, "could not realloc current_row\n");
1143 : return TDS_FAIL;
1144 : }
1145 22 : bcpinfo->bindinfo->row_free = tds_bcp_row_free;
1146 22 : bcpinfo->bindinfo->row_size = bcp_record_size;
1147 : }
1148 : }
1149 :
1150 : return TDS_SUCCESS;
1151 : }
1152 :
1153 : /** input stream to read a file */
1154 : typedef struct tds_file_stream {
1155 : /** common fields, must be the first field */
1156 : TDSINSTREAM stream;
1157 : /** file to read from */
1158 : FILE *f;
1159 :
1160 : /** terminator */
1161 : const char *terminator;
1162 : /** terminator length in bytes */
1163 : size_t term_len;
1164 :
1165 : /** buffer for store bytes readed that could be the terminator */
1166 : char *left;
1167 : size_t left_pos;
1168 : } TDSFILESTREAM;
1169 :
1170 : /** \cond HIDDEN_SYMBOLS */
1171 : #if defined(_WIN32) && defined(HAVE__LOCK_FILE) && defined(HAVE__UNLOCK_FILE)
1172 : #define TDS_HAVE_STDIO_LOCKED 1
1173 : #define flockfile(s) _lock_file(s)
1174 : #define funlockfile(s) _unlock_file(s)
1175 : #define getc_unlocked(s) _getc_nolock(s)
1176 : #define feof_unlocked(s) _feof_nolock(s)
1177 : #endif
1178 :
1179 : #ifndef TDS_HAVE_STDIO_LOCKED
1180 : #undef getc_unlocked
1181 : #undef feof_unlocked
1182 : #undef flockfile
1183 : #undef funlockfile
1184 : #define getc_unlocked(s) getc(s)
1185 : #define feof_unlocked(s) feof(s)
1186 : #define flockfile(s) do { } while(0)
1187 : #define funlockfile(s) do { } while(0)
1188 : #endif
1189 : /** \endcond */
1190 :
1191 : /**
1192 : * Reads a chunk of data from file stream checking for terminator
1193 : * \param stream file stream
1194 : * \param ptr buffer where to read data
1195 : * \param len length of buffer
1196 : */
1197 : static int
1198 4722 : tds_file_stream_read(TDSINSTREAM *stream, void *ptr, size_t len)
1199 : {
1200 4722 : TDSFILESTREAM *s = (TDSFILESTREAM *) stream;
1201 : int c;
1202 4722 : char *p = (char *) ptr;
1203 :
1204 1893300 : while (len) {
1205 1888128 : if (memcmp(s->left, s->terminator - s->left_pos, s->term_len) == 0)
1206 4272 : return p - (char *) ptr;
1207 :
1208 3767712 : c = getc_unlocked(s->f);
1209 1883856 : if (c == EOF)
1210 : return -1;
1211 :
1212 1883856 : *p++ = s->left[s->left_pos];
1213 1883856 : --len;
1214 :
1215 1883856 : s->left[s->left_pos++] = c;
1216 1883856 : s->left_pos %= s->term_len;
1217 : }
1218 450 : return p - (char *) ptr;
1219 : }
1220 :
1221 : /**
1222 : * Read a data file, passing the data through iconv().
1223 : * \retval TDS_SUCCESS success
1224 : * \retval TDS_FAIL error reading the column
1225 : * \retval TDS_NO_MORE_RESULTS end of file detected
1226 : */
1227 : TDSRET
1228 2320 : tds_bcp_fread(TDSSOCKET * tds, TDSICONV * char_conv, FILE * stream, const char *terminator, size_t term_len, char **outbuf, size_t * outbytes)
1229 : {
1230 : TDSRET res;
1231 : TDSFILESTREAM r;
1232 : TDSDYNAMICSTREAM w;
1233 : size_t readed;
1234 :
1235 : /* prepare streams */
1236 2320 : r.stream.read = tds_file_stream_read;
1237 2320 : r.f = stream;
1238 2320 : r.term_len = term_len;
1239 2320 : r.left = tds_new0(char, term_len*3);
1240 2320 : r.left_pos = 0;
1241 2320 : if (!r.left) return TDS_FAIL;
1242 :
1243 : /* copy terminator twice, let terminator points to second copy */
1244 2320 : memcpy(r.left + term_len, terminator, term_len);
1245 2320 : memcpy(r.left + term_len*2u, terminator, term_len);
1246 2320 : r.terminator = r.left + term_len*2u;
1247 :
1248 : /* read initial buffer to test with terminator */
1249 2320 : readed = fread(r.left, 1, term_len, stream);
1250 2320 : if (readed != term_len) {
1251 124 : free(r.left);
1252 124 : if (readed == 0 && feof(stream))
1253 : return TDS_NO_MORE_RESULTS;
1254 : return TDS_FAIL;
1255 : }
1256 :
1257 2196 : res = tds_dynamic_stream_init(&w, (void**) outbuf, 0);
1258 2196 : if (TDS_FAILED(res)) {
1259 0 : free(r.left);
1260 0 : return res;
1261 : }
1262 :
1263 : /* convert/copy from input stream to output one */
1264 2196 : flockfile(stream);
1265 2196 : if (char_conv == NULL)
1266 820 : res = tds_copy_stream(&r.stream, &w.stream);
1267 : else
1268 1376 : res = tds_convert_stream(tds, char_conv, to_server, &r.stream, &w.stream);
1269 2196 : funlockfile(stream);
1270 2196 : free(r.left);
1271 :
1272 2196 : TDS_PROPAGATE(res);
1273 :
1274 2196 : *outbytes = w.size;
1275 :
1276 : /* terminate buffer */
1277 2196 : if (!w.stream.buf_len)
1278 : return TDS_FAIL;
1279 :
1280 2196 : ((char *) w.stream.buffer)[0] = 0;
1281 2196 : w.stream.write(&w.stream, 1);
1282 :
1283 2196 : return res;
1284 : }
1285 :
1286 : /**
1287 : * Start writing writetext request.
1288 : * This request start a bulk session.
1289 : * \tds
1290 : * \param objname table name
1291 : * \param textptr TEXTPTR (see sql documentation)
1292 : * \param timestamp data timestamp
1293 : * \param with_log is log is enabled during insert
1294 : * \param size bytes to be inserted
1295 : */
1296 : TDSRET
1297 54 : tds_writetext_start(TDSSOCKET *tds, const char *objname, const char *textptr, const char *timestamp, int with_log, TDS_UINT size)
1298 : {
1299 : TDSRET rc;
1300 :
1301 : /* TODO mssql does not like timestamp */
1302 54 : rc = tds_submit_queryf(tds,
1303 : "writetext bulk %s 0x%s timestamp = 0x%s%s",
1304 : objname, textptr, timestamp, with_log ? " with log" : "");
1305 54 : TDS_PROPAGATE(rc);
1306 :
1307 : /* set we want to switch to bulk state */
1308 54 : tds->bulk_query = true;
1309 :
1310 : /* read the end token */
1311 54 : TDS_PROPAGATE(tds_process_simple_query(tds));
1312 :
1313 54 : tds->out_flag = TDS_BULK;
1314 54 : if (tds_set_state(tds, TDS_WRITING) != TDS_WRITING)
1315 : return TDS_FAIL;
1316 :
1317 54 : tds_put_int(tds, size);
1318 :
1319 54 : tds_set_state(tds, TDS_SENDING);
1320 54 : return TDS_SUCCESS;
1321 : }
1322 :
1323 : /**
1324 : * Send some data in the writetext request started by tds_writetext_start.
1325 : * You should write in total (with multiple calls to this function) all
1326 : * bytes declared calling tds_writetext_start.
1327 : * \tds
1328 : * \param text data to write
1329 : * \param size data size in bytes
1330 : */
1331 : TDSRET
1332 408 : tds_writetext_continue(TDSSOCKET *tds, const TDS_UCHAR *text, TDS_UINT size)
1333 : {
1334 408 : if (tds->out_flag != TDS_BULK || tds_set_state(tds, TDS_WRITING) != TDS_WRITING)
1335 : return TDS_FAIL;
1336 :
1337 : /* TODO check size left */
1338 408 : tds_put_n(tds, text, size);
1339 :
1340 408 : tds_set_state(tds, TDS_SENDING);
1341 408 : return TDS_SUCCESS;
1342 : }
1343 :
1344 : /**
1345 : * Finish sending writetext data.
1346 : * \tds
1347 : */
1348 : TDSRET
1349 54 : tds_writetext_end(TDSSOCKET *tds)
1350 : {
1351 54 : if (tds->out_flag != TDS_BULK || tds_set_state(tds, TDS_WRITING) != TDS_WRITING)
1352 : return TDS_FAIL;
1353 :
1354 54 : tds_flush_packet(tds);
1355 54 : tds_set_state(tds, TDS_PENDING);
1356 54 : return TDS_SUCCESS;
1357 : }
|