Line data Source code
1 : /* FreeTDS - Library of routines accessing Sybase and Microsoft databases
2 : * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005 Brian Bruns
3 : * Copyright (C) 2010, 2011 Frediano Ziglio
4 : *
5 : * This library is free software; you can redistribute it and/or
6 : * modify it under the terms of the GNU Library General Public
7 : * License as published by the Free Software Foundation; either
8 : * version 2 of the License, or (at your option) any later version.
9 : *
10 : * This library is distributed in the hope that it will be useful,
11 : * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 : * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 : * Library General Public License for more details.
14 : *
15 : * You should have received a copy of the GNU Library General Public
16 : * License along with this library; if not, write to the
17 : * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 : * Boston, MA 02111-1307, USA.
19 : */
20 :
21 : #include <config.h>
22 :
23 : #include <stdarg.h>
24 : #include <stdio.h>
25 : #include <assert.h>
26 :
27 : #if HAVE_STRING_H
28 : #include <string.h>
29 : #endif /* HAVE_STRING_H */
30 :
31 : #if HAVE_STDLIB_H
32 : #include <stdlib.h>
33 : #endif /* HAVE_STDLIB_H */
34 :
35 : #if HAVE_UNISTD_H
36 : #include <unistd.h>
37 : #endif /* HAVE_UNISTD_H */
38 :
39 : #ifdef _WIN32
40 : #include <io.h>
41 : #endif
42 :
43 : #include <freetds/tds.h>
44 : #include <freetds/tds/checks.h>
45 : #include <freetds/tds/iconv.h>
46 : #include <freetds/tds/convert.h>
47 : #include <freetds/bytes.h>
48 : #include <freetds/tds/stream.h>
49 : #include <freetds/utils/string.h>
50 : #include <freetds/encodings.h>
51 : #include <freetds/replacements.h>
52 : #include <sybfront.h>
53 : #include <sybdb.h>
54 : #include <syberror.h>
55 : #include <dblib.h>
56 :
57 : #define BCP_DEFAULT_DATEFMT "%Y-%m-%d %H:%M:%S.%z"
58 :
59 : #define HOST_COL_CONV_ERROR 1
60 : #define HOST_COL_NULL_ERROR 2
61 :
62 : static void _bcp_free_storage(DBPROCESS * dbproc);
63 : static void _bcp_free_columns(DBPROCESS * dbproc);
64 : static void _bcp_null_error(TDSBCPINFO * bcpinfo, int index, int offset);
65 : static TDSRET _bcp_get_col_data(TDSBCPINFO * bcpinfo, TDSCOLUMN * bindcol, int index, int offset);
66 : static TDSRET _bcp_no_get_col_data(TDSBCPINFO * bcpinfo, TDSCOLUMN * bindcol, int index, int offset);
67 :
68 : static int rtrim(char *, int);
69 : static int rtrim_u16(uint16_t * str, int len, uint16_t space);
70 : static STATUS _bcp_read_hostfile(DBPROCESS * dbproc, TDSFILESTREAM * hostfile, bool *row_error, bool skip);
71 : static int _bcp_readfmt_colinfo(DBPROCESS * dbproc, char *buf, BCP_HOSTCOLINFO * ci);
72 : static int _bcp_get_term_var(const BYTE * pdata, const BYTE * term, int term_len);
73 : static int _bcp_strftime(char *buf, size_t maxsize, const char *format, const TDSDATEREC * dr, int prec);
74 :
75 : /*
76 : * "If a host file is being used ... the default data formats are as follows:
77 : *
78 : * > The order, type, length and number of the columns in the host file are
79 : * assumed to be identical to the order, type and number of the columns in the database table.
80 : * > If a given database column's data is fixed-length,
81 : * then the host file's data column will also be fixed-length.
82 : * > If a given database column's data is variable-length or may contain null values,
83 : * the host file's data column will be prefixed by
84 : * a 4-byte length value for SYBTEXT and SYBIMAGE data types, and
85 : * a 1-byte length value for all other types.
86 : * > There are no terminators of any kind between host file columns."
87 : */
88 :
89 : static void
90 422 : init_hostfile_columns(DBPROCESS *dbproc)
91 : {
92 422 : const int ncols = dbproc->bcpinfo->bindinfo->num_cols;
93 : RETCODE erc;
94 : int icol;
95 :
96 422 : if (ncols == 0)
97 : return;
98 :
99 422 : if ((erc = bcp_columns(dbproc, ncols)) != SUCCEED) {
100 0 : assert(erc == SUCCEED);
101 : return;
102 : }
103 :
104 2528 : for (icol = 0; icol < ncols; icol++) {
105 2106 : const TDSCOLUMN *pcol = dbproc->bcpinfo->bindinfo->columns[icol];
106 2106 : int prefixlen = 0, termlen = 0;
107 :
108 2106 : switch (pcol->column_type) {
109 : case SYBTEXT:
110 : case SYBIMAGE:
111 : prefixlen = 4;
112 : break;
113 1966 : default:
114 1966 : prefixlen = dbvarylen(dbproc, icol+1)? 1 : 0;
115 : }
116 :
117 2106 : erc = bcp_colfmt(dbproc, icol+1, pcol->column_type, prefixlen, pcol->column_size, NULL, termlen, icol+1);
118 :
119 2106 : assert(erc == SUCCEED);
120 : if (erc != SUCCEED)
121 : return;
122 : }
123 : }
124 :
125 :
126 : /**
127 : * \ingroup dblib_bcp
128 : * \brief Prepare for bulk copy operation on a table
129 : *
130 : * \param dbproc contains all information needed by db-lib to manage communications with the server.
131 : * \param tblname the name of the table receiving or providing the data.
132 : * \param hfile the data file opposite the table, if any.
133 : * \param errfile the "error file" captures messages and, if errors are encountered,
134 : * copies of any rows that could not be written to the table.
135 : * \param direction one of
136 : * - \b DB_IN writing to the table
137 : * - \b DB_OUT writing to the host file
138 : * .
139 : * \remarks bcp_init() sets the host file data format and acquires the table metadata.
140 : * It is called before the other bulk copy functions.
141 : *
142 : * When writing to a table, bcp can use as its data source a data file (\a hfile),
143 : * or program data in an application's variables. In the latter case, call bcp_bind()
144 : * to associate your data with the appropriate table column.
145 : * \return SUCCEED or FAIL.
146 : * \sa BCP_SETL(), bcp_bind(), bcp_done(), bcp_exec()
147 : */
148 : RETCODE
149 890 : bcp_init(DBPROCESS * dbproc, const char *tblname, const char *hfile, const char *errfile, int direction)
150 : {
151 890 : tdsdump_log(TDS_DBG_FUNC, "bcp_init(%p, %s, %s, %s, %d)\n",
152 : dbproc, tblname? tblname:"NULL", hfile? hfile:"NULL", errfile? errfile:"NULL", direction);
153 890 : CHECK_CONN(FAIL);
154 :
155 : /*
156 : * Validate other parameters
157 : */
158 890 : if (dbproc->tds_socket->conn->tds_version < 0x500) {
159 0 : dbperror(dbproc, SYBETDSVER, 0);
160 0 : return FAIL;
161 : }
162 :
163 890 : if (tblname == NULL) {
164 0 : dbperror(dbproc, SYBEBCITBNM, 0);
165 0 : return FAIL;
166 : }
167 :
168 1054 : if (direction != DB_QUERYOUT && !IS_TDS7_PLUS(dbproc->tds_socket->conn) &&
169 164 : strlen(tblname) > 92) { /* 30.30.30 for Sybase */
170 0 : dbperror(dbproc, SYBEBCITBLEN, 0);
171 0 : return FAIL;
172 : }
173 :
174 890 : if (direction != DB_IN && direction != DB_OUT && direction != DB_QUERYOUT) {
175 0 : dbperror(dbproc, SYBEBDIO, 0);
176 0 : return FAIL;
177 : }
178 :
179 : /* Free previously allocated storage in dbproc & initialise flags, etc. */
180 890 : _bcp_free_storage(dbproc);
181 :
182 : /* Allocate storage */
183 890 : dbproc->bcpinfo = tds_alloc_bcpinfo();
184 890 : if (dbproc->bcpinfo == NULL)
185 : goto memory_error;
186 :
187 890 : if (!tds_dstr_copy(&dbproc->bcpinfo->tablename, tblname))
188 : goto memory_error;
189 :
190 890 : dbproc->bcpinfo->direction = direction;
191 :
192 890 : dbproc->bcpinfo->xfer_init = false;
193 890 : dbproc->bcpinfo->bind_count = 0;
194 :
195 890 : if (TDS_FAILED(tds_bcp_init(dbproc->tds_socket, dbproc->bcpinfo))) {
196 : /* TODO return proper error */
197 : /* Attempt to use Bulk Copy with a non-existent Server table (might be why ...) */
198 0 : dbperror(dbproc, SYBEBCNT, 0);
199 0 : return FAIL;
200 : }
201 :
202 : /* Prepare default hostfile columns */
203 :
204 890 : if (hfile == NULL) {
205 468 : dbproc->hostfileinfo = NULL;
206 468 : return SUCCEED;
207 : }
208 :
209 422 : dbproc->hostfileinfo = tds_new0(BCP_HOSTFILEINFO, 1);
210 :
211 422 : if (dbproc->hostfileinfo == NULL)
212 : goto memory_error;
213 422 : dbproc->hostfileinfo->maxerrs = 10;
214 422 : dbproc->hostfileinfo->firstrow = 1;
215 422 : if ((dbproc->hostfileinfo->hostfile = strdup(hfile)) == NULL)
216 : goto memory_error;
217 :
218 422 : if (errfile != NULL)
219 422 : if ((dbproc->hostfileinfo->errorfile = strdup(errfile)) == NULL)
220 : goto memory_error;
221 :
222 422 : init_hostfile_columns(dbproc);
223 :
224 422 : return SUCCEED;
225 :
226 0 : memory_error:
227 0 : _bcp_free_storage(dbproc);
228 0 : dbperror(dbproc, SYBEMEM, ENOMEM);
229 0 : return FAIL;
230 : }
231 :
232 :
233 : /**
234 : * \ingroup dblib_bcp
235 : * \brief Set the length of a host variable to be written to a table.
236 : *
237 : * \param dbproc contains all information needed by db-lib to manage communications with the server.
238 : * \param varlen size of the variable, in bytes, or
239 : * - \b 0 indicating NULL
240 : * - \b -1 indicating size is determined by the prefix or terminator.
241 : * (If both a prefix and a terminator are present, bcp is supposed to use the smaller of the
242 : * two. This feature might or might not actually work.)
243 : * \param table_column the number of the column in the table (starting with 1, not zero).
244 : *
245 : * \return SUCCEED or FAIL.
246 : * \sa bcp_bind(), bcp_colptr(), bcp_sendrow()
247 : */
248 : RETCODE
249 130 : bcp_collen(DBPROCESS * dbproc, DBINT varlen, int table_column)
250 : {
251 : TDSCOLUMN *bcpcol;
252 :
253 130 : tdsdump_log(TDS_DBG_FUNC, "bcp_collen(%p, %d, %d)\n", dbproc, varlen, table_column);
254 :
255 130 : CHECK_CONN(FAIL);
256 130 : CHECK_PARAMETER(dbproc->bcpinfo, SYBEBCPI, FAIL); /* not initialized */
257 130 : DBPERROR_RETURN(dbproc->bcpinfo->direction != DB_IN, SYBEBCPN) /* not inbound */
258 130 : DBPERROR_RETURN(dbproc->hostfileinfo != NULL, SYBEBCPI) /* cannot have data file */
259 130 : CHECK_PARAMETER(0 < table_column &&
260 : table_column <= dbproc->bcpinfo->bindinfo->num_cols, SYBECNOR, FAIL);
261 :
262 130 : bcpcol = dbproc->bcpinfo->bindinfo->columns[table_column - 1];
263 :
264 : /* Sybase library does not check for NULL here, only sending, so don't
265 : * check and send SYBEBCNN */
266 130 : bcpcol->column_bindlen = varlen;
267 :
268 130 : return SUCCEED;
269 : }
270 :
271 : /**
272 : * \ingroup dblib_bcp
273 : * \brief Indicate how many columns are to be found in the datafile.
274 : *
275 : * \param dbproc contains all information needed by db-lib to manage communications with the server.
276 : * \param host_colcount count of columns in the datafile, irrespective of how many you intend to use.
277 : * \remarks This function describes the file as it is, not how it will be used.
278 : *
279 : * \return SUCCEED or FAIL. It's hard to see how it could fail.
280 : * \sa bcp_colfmt()
281 : */
282 : RETCODE
283 834 : bcp_columns(DBPROCESS * dbproc, int host_colcount)
284 : {
285 : int i;
286 :
287 834 : tdsdump_log(TDS_DBG_FUNC, "bcp_columns(%p, %d)\n", dbproc, host_colcount);
288 834 : CHECK_CONN(FAIL);
289 834 : CHECK_PARAMETER(dbproc->bcpinfo, SYBEBCPI, FAIL);
290 834 : CHECK_PARAMETER(dbproc->hostfileinfo, SYBEBIVI, FAIL);
291 :
292 834 : if (host_colcount < 1) {
293 0 : dbperror(dbproc, SYBEBCFO, 0);
294 0 : return FAIL;
295 : }
296 :
297 834 : _bcp_free_columns(dbproc);
298 :
299 834 : dbproc->hostfileinfo->host_columns = tds_new0(BCP_HOSTCOLINFO *, host_colcount);
300 834 : if (dbproc->hostfileinfo->host_columns == NULL) {
301 0 : dbperror(dbproc, SYBEMEM, ENOMEM);
302 0 : return FAIL;
303 : }
304 :
305 834 : dbproc->hostfileinfo->host_colcount = host_colcount;
306 :
307 5032 : for (i = 0; i < host_colcount; i++) {
308 4198 : dbproc->hostfileinfo->host_columns[i] = tds_new0(BCP_HOSTCOLINFO, 1);
309 4198 : if (dbproc->hostfileinfo->host_columns[i] == NULL) {
310 0 : dbproc->hostfileinfo->host_colcount = i;
311 0 : _bcp_free_columns(dbproc);
312 0 : dbperror(dbproc, SYBEMEM, ENOMEM);
313 0 : return FAIL;
314 : }
315 : }
316 :
317 : return SUCCEED;
318 : }
319 :
320 : /**
321 : * \ingroup dblib_bcp
322 : * \brief Specify the format of a datafile prior to writing to a table.
323 : *
324 : * \param dbproc contains all information needed by db-lib to manage communications with the server.
325 : * \param host_colnum datafile column number (starting with 1, not zero).
326 : * \param host_type dataype token describing the data type in \a host_colnum. E.g. SYBCHAR for character data.
327 : * \param host_prefixlen size of the prefix in the datafile column, if any. For delimited files: zero.
328 : * May be 0, 1, 2, or 4 bytes. The prefix will be read as an integer (not a character string) from the
329 : * data file, and will be interpreted the data size of that column, in bytes.
330 : * The value -1 means to use the default recommended prefix size for the datatype.
331 : * \param host_collen maximum size of datafile column exclusive of any prefix/terminator. Just the data, ma'am.
332 : * Special values:
333 : * - \b 0 indicates a null value for a variable-length field with no prefix/terminator.
334 : * - \b -1 for fixed-length non-null datatypes
335 : * - \b -1 for variable-length datatypes (e.g. SYBCHAR) where the length is established
336 : * by a prefix/terminator.
337 : * \param host_term the sequence of characters that will serve as a column terminator (delimiter) in the datafile.
338 : * Often a tab character, but can be any string of any length. Zero indicates no terminator.
339 : * Special characters:
340 : * - \b '\\0' terminator is an ASCII NUL.
341 : * - \b '\\t' terminator is an ASCII TAB.
342 : * - \b '\\n' terminator is an ASCII NL.
343 : * \param host_termlen the length of \a host_term, in bytes.
344 : * \param table_colnum Nth column, starting at 1, in the table that maps to \a host_colnum.
345 : * If there is a column in the datafile that does not map to a table column, set \a table_colnum to zero.
346 : *
347 : *\remarks bcp_colfmt() is called once for each column in the datafile, as specified with bcp_columns().
348 : * In so doing, you describe to FreeTDS how to parse each line of your datafile, and where to send each field.
349 : *
350 : * When a prefix or terminator is used with variable-length data, \a host_collen may have one of three values:
351 : * - \b positive indicating the maximum number of bytes to be used
352 : * - \b 0 indicating NULL
353 : * - \b -1 indicating no maximum; all data, as described by the prefix/terminator will be used.
354 : * .
355 : * \return SUCCEED or FAIL.
356 : * \sa bcp_batch(), bcp_bind(), bcp_colfmt_ps(), bcp_collen(), bcp_colptr(), bcp_columns(),
357 : * bcp_control(), bcp_done(), bcp_exec(), bcp_init(), bcp_sendrow
358 : */
359 : RETCODE
360 4208 : bcp_colfmt(DBPROCESS * dbproc, int host_colnum, int host_type, int host_prefixlen, DBINT host_collen, const BYTE * host_term,
361 : int host_termlen, int table_colnum)
362 : {
363 : BCP_HOSTCOLINFO *hostcol;
364 4208 : BYTE *terminator = NULL;
365 :
366 4208 : tdsdump_log(TDS_DBG_FUNC, "bcp_colfmt(%p, %d, %d, %d, %d, %p, %d, %d)\n",
367 : dbproc, host_colnum, host_type, host_prefixlen, (int) host_collen, host_term, host_termlen, table_colnum);
368 4208 : CHECK_CONN(FAIL);
369 4208 : CHECK_PARAMETER(dbproc->bcpinfo, SYBEBCPI, FAIL);
370 4208 : CHECK_PARAMETER(dbproc->hostfileinfo, SYBEBIVI, FAIL);
371 :
372 : /* Microsoft specifies a "file_termlen" of zero if there's no terminator */
373 4208 : if (dbproc->msdblib && host_termlen == 0)
374 : host_termlen = -1;
375 :
376 4208 : if (host_termlen < 0)
377 0 : host_termlen = -1;
378 :
379 4208 : if (dbproc->hostfileinfo->host_colcount == 0) {
380 0 : dbperror(dbproc, SYBEBCBC, 0);
381 0 : return FAIL;
382 : }
383 :
384 4208 : if (host_colnum < 1) {
385 0 : dbperror(dbproc, SYBEBCFO, 0);
386 0 : return FAIL;
387 : }
388 :
389 4208 : if (host_colnum > dbproc->hostfileinfo->host_colcount) {
390 0 : dbperror(dbproc, SYBECNOR, 0);
391 0 : return FAIL;
392 : }
393 :
394 : /* Note: MS bcp supports 1, 2, 4, and 8; but not 3; but returns SYBEVDPT on error.
395 : * -1 is a special value that will be resolved after database connection. */
396 4208 : if (host_prefixlen != 0 && host_prefixlen != 1 && host_prefixlen != 2 && host_prefixlen != 4 && host_prefixlen != -1) {
397 0 : dbperror(dbproc, SYBEBCPREF, 0);
398 0 : return FAIL;
399 : }
400 :
401 : /* if column is not copied you cannot specify destination type */
402 4208 : if (table_colnum <= 0 && host_type == 0) {
403 0 : dbperror(dbproc, SYBEBCPCTYP, 0);
404 0 : return FAIL;
405 : }
406 :
407 8416 : if (table_colnum > 0 && !is_tds_type_valid(host_type)) {
408 0 : dbperror(dbproc, SYBEUDTY, 0);
409 0 : return FAIL;
410 : }
411 :
412 4208 : if (host_collen < -1) {
413 0 : dbperror(dbproc, SYBEBCHLEN, 0);
414 0 : return FAIL;
415 : }
416 :
417 : /* No official error message. Fix and warn. */
418 4208 : if (is_fixed_type(host_type) && (host_collen != -1 && host_collen != 0)) {
419 854 : tdsdump_log(TDS_DBG_FUNC,
420 : "bcp_colfmt: changing host_collen to -1 from %d for fixed type %d.\n",
421 : host_collen, host_type);
422 : host_collen = -1;
423 : }
424 :
425 : /*
426 : * If there's a positive terminator length, we need a valid terminator pointer.
427 : * If the terminator length is 0 or -1, then there's no terminator.
428 : */
429 4208 : if (host_term == NULL && host_termlen > 0) {
430 0 : dbperror(dbproc, SYBEVDPT, 0); /* "all variable-length data must have either a length-prefix ..." */
431 0 : return FAIL;
432 : }
433 :
434 : /* Does not make sense to have a prefix and a terminator. */
435 4208 : if (host_prefixlen != 0 && host_termlen > 0) {
436 0 : tdsdump_log(TDS_DBG_FUNC, "bcp_colfmt: host column %d has a prefix and a terminator.\n", host_colnum);
437 0 : dbperror(dbproc, SYBEVDPT, 0);
438 0 : return FAIL;
439 : }
440 :
441 4208 : hostcol = dbproc->hostfileinfo->host_columns[host_colnum - 1];
442 :
443 : /* TODO add precision scale and join with bcp_colfmt_ps */
444 4208 : if (host_term && host_termlen > 0) {
445 1962 : if ((terminator = tds_new(BYTE, host_termlen)) == NULL) {
446 0 : dbperror(dbproc, SYBEMEM, errno);
447 0 : return FAIL;
448 : }
449 1962 : memcpy(terminator, host_term, host_termlen);
450 : }
451 4208 : hostcol->host_column = host_colnum;
452 4208 : hostcol->datatype = host_type ? (TDS_SERVER_TYPE) host_type : TDS_INVALID_TYPE;
453 4208 : hostcol->prefix_len = host_prefixlen;
454 4208 : hostcol->column_len = host_collen;
455 4208 : free(hostcol->terminator);
456 4208 : hostcol->terminator = terminator;
457 4208 : hostcol->term_len = host_termlen;
458 4208 : hostcol->tab_colnum = table_colnum;
459 :
460 4208 : return SUCCEED;
461 : }
462 :
463 : /**
464 : * \ingroup dblib_bcp
465 : * \brief Specify the format of a host file for bulk copy purposes,
466 : * with precision and scale support for numeric and decimal columns.
467 : *
468 : * \param dbproc contains all information needed by db-lib to manage communications with the server.
469 : * \param host_colnum datafile column number (starting with 1, not zero).
470 : * \param host_type dataype token describing the data type in \a host_colnum. E.g. SYBCHAR for character data.
471 : * \param host_prefixlen size of the prefix in the datafile column, if any. For delimited files: zero.
472 : * May be 0, 1, 2, or 4 bytes. The prefix will be read as an integer (not a character string) from the
473 : * data file, and will be interpreted the data size of that column, in bytes.
474 : * \param host_collen maximum size of datafile column, exclusive of any prefix/terminator. Just the data, ma'am.
475 : * Special values:
476 : * - \b 0 indicates NULL.
477 : * - \b -1 for fixed-length non-null datatypes
478 : * - \b -1 for variable-length datatypes (e.g. SYBCHAR) where the length is established
479 : * by a prefix/terminator.
480 : * \param host_term the sequence of characters that will serve as a column terminator (delimiter) in the datafile.
481 : * Often a tab character, but can be any string of any length. Zero indicates no terminator.
482 : * Special characters:
483 : * - \b '\\0' terminator is an ASCII NUL.
484 : * - \b '\\t' terminator is an ASCII TAB.
485 : * - \b '\\n' terminator is an ASCII NL.
486 : * \param host_termlen the length of \a host_term, in bytes.
487 : * \param table_colnum Nth column, starting at 1, in the table that maps to \a host_colnum.
488 : * If there is a column in the datafile that does not map to a table column, set \a table_colnum to zero.
489 : * \param typeinfo something
490 : * \todo Not implemented.
491 : * \return SUCCEED or FAIL.
492 : * \sa bcp_batch(), bcp_bind(), bcp_colfmt(), bcp_collen(), bcp_colptr(), bcp_columns(),
493 : * bcp_control(), bcp_done(), bcp_exec(), bcp_init(), bcp_sendrow
494 : */
495 : RETCODE
496 0 : bcp_colfmt_ps(DBPROCESS * dbproc, int host_colnum, int host_type,
497 : int host_prefixlen, DBINT host_collen, BYTE * host_term, int host_termlen, int table_colnum, DBTYPEINFO * typeinfo)
498 : {
499 0 : tdsdump_log(TDS_DBG_FUNC, "UNIMPLEMENTED: bcp_colfmt_ps(%p, %d, %d, %d, %d, %p, %d, %d, %p)\n",
500 : dbproc, host_colnum, host_type, host_prefixlen, (int) host_collen,
501 : host_term, host_termlen, table_colnum, typeinfo);
502 0 : CHECK_CONN(FAIL);
503 0 : CHECK_PARAMETER(dbproc->bcpinfo, SYBEBCPI, FAIL);
504 :
505 : /* dbperror(dbproc, , 0); Illegal precision specified */
506 :
507 : /* TODO see bcp_colfmt */
508 : return FAIL;
509 : }
510 :
511 :
512 : /**
513 : * \ingroup dblib_bcp
514 : * \brief Set BCP options for uploading a datafile
515 : *
516 : * \param dbproc contains all information needed by db-lib to manage communications with the server.
517 : * \param field symbolic constant indicating the option to be set, one of:
518 : * - \b BCPMAXERRS Maximum errors tolerated before quitting. The default is 10.
519 : * - \b BCPFIRST The first row to read in the datafile. The default is 1.
520 : * - \b BCPLAST The last row to read in the datafile. The default is to copy all rows. A value of
521 : * -1 resets this field to its default?
522 : * - \b BCPBATCH The number of rows per batch. Default is 0, meaning a single batch.
523 : * \param value The value for \a field.
524 : *
525 : * \remarks These options control the behavior of bcp_exec().
526 : * When writing to a table from application host memory variables,
527 : * program logic controls error tolerance and batch size.
528 : *
529 : * \return SUCCEED or FAIL.
530 : * \sa bcp_batch(), bcp_bind(), bcp_colfmt(), bcp_collen(), bcp_colptr(), bcp_columns(), bcp_done(), bcp_exec(), bcp_options()
531 : */
532 : RETCODE
533 50 : bcp_control(DBPROCESS * dbproc, int field, DBINT value)
534 : {
535 50 : tdsdump_log(TDS_DBG_FUNC, "bcp_control(%p, %d, %d)\n", dbproc, field, value);
536 50 : CHECK_CONN(FAIL);
537 50 : CHECK_PARAMETER(dbproc->bcpinfo, SYBEBCPI, FAIL);
538 :
539 50 : if (field == BCPKEEPIDENTITY) {
540 0 : dbproc->bcpinfo->identity_insert_on = (value != 0);
541 0 : return SUCCEED;
542 : }
543 :
544 50 : CHECK_PARAMETER(dbproc->hostfileinfo, SYBEBIVI, FAIL);
545 :
546 50 : switch (field) {
547 :
548 10 : case BCPMAXERRS:
549 10 : if (value < 1)
550 0 : value = 10;
551 10 : dbproc->hostfileinfo->maxerrs = value;
552 10 : break;
553 10 : case BCPFIRST:
554 10 : if (value < 1)
555 10 : value = 1;
556 10 : dbproc->hostfileinfo->firstrow = value;
557 10 : break;
558 10 : case BCPLAST:
559 10 : dbproc->hostfileinfo->lastrow = value;
560 10 : break;
561 10 : case BCPBATCH:
562 10 : dbproc->hostfileinfo->batch = value;
563 10 : break;
564 10 : case BCPDRYRUN:
565 10 : dbproc->bcpinfo->dry_run = value;
566 10 : break;
567 :
568 0 : default:
569 0 : dbperror(dbproc, SYBEIFNB, 0);
570 0 : return FAIL;
571 : }
572 : return SUCCEED;
573 : }
574 :
575 : /*
576 : * \ingroup dblib_bcp
577 : * \brief Get BCP batch option
578 : *
579 : * \param dbproc contains all information needed by db-lib to manage communications with the server.
580 : * \remarks This function is specific to FreeTDS.
581 : *
582 : * \return the value that was set by bcp_control.
583 : * \sa bcp_batch(), bcp_control()
584 : */
585 : int
586 0 : bcp_getbatchsize(DBPROCESS * dbproc)
587 : {
588 0 : CHECK_CONN(-1);
589 0 : CHECK_PARAMETER(dbproc->hostfileinfo, SYBEBCPI, -1);
590 0 : return dbproc->hostfileinfo->batch;
591 : }
592 :
593 : /*
594 : * \ingroup dblib_bcp
595 : * \brief Get number of columns in the BCP data file
596 : *
597 : * \param dbproc contains all information needed by db-lib to manage communications with the server.
598 : * \remarks This function is specific to FreeTDS.
599 : *
600 : * \return the value that was set by bcp_columns(). This represents the number
601 : * of columns of data in the saved data file. Usually the same as the number
602 : * of columns in the database table, but could be fewer if a Format File is
603 : * in use which only selects a subset of the table columns.
604 : *
605 : * \sa bcp_columns()
606 : */
607 : int
608 10 : bcp_gethostcolcount(DBPROCESS *dbproc)
609 : {
610 10 : CHECK_CONN(-1);
611 10 : CHECK_PARAMETER(dbproc->hostfileinfo, SYBEBCPI, -1);
612 10 : return dbproc->hostfileinfo->host_colcount;
613 : }
614 :
615 : /**
616 : * \ingroup dblib_bcp
617 : * \brief Set bulk copy options.
618 : *
619 : * \param dbproc contains all information needed by db-lib to manage communications with the server.
620 : * \param option symbolic constant indicating the option to be set, one of:
621 : * - \b BCPLABELED Not implemented.
622 : * - \b BCPHINTS The hint to be passed when the bulk-copy begins.
623 : * \param value The string constant for \a option a/k/a the hint. One of:
624 : * - \b ORDER The data are ordered in accordance with the table's clustered index.
625 : * - \b ROWS_PER_BATCH The batch size
626 : * - \b KILOBYTES_PER_BATCH The approximate number of kilobytes to use for a batch size
627 : * - \b TABLOCK Lock the table
628 : * - \b CHECK_CONSTRAINTS Apply constraints
629 : * - \b FIRE_TRIGGERS Fire any INSERT triggers on the target table
630 : * \param valuelen The length of \a value. Ignored for fixed-length option types.
631 : *
632 : * \return SUCCEED or FAIL.
633 : * \sa bcp_control(),
634 : * bcp_exec(),
635 : * \todo Simplify.
636 : */
637 : RETCODE
638 12 : bcp_options(DBPROCESS *dbproc, int option, BYTE *value, int valuelen)
639 : {
640 12 : tdsdump_log(TDS_DBG_FUNC, "bcp_options(%p, %d, %p, %d)\n", dbproc, option, value, valuelen);
641 12 : CHECK_CONN(FAIL);
642 12 : CHECK_PARAMETER(dbproc->bcpinfo, SYBEBCPI, FAIL);
643 12 : CHECK_NULP(value, "bcp_options", 3, FAIL);
644 :
645 12 : switch (option) {
646 0 : case BCPLABELED:
647 0 : tdsdump_log(TDS_DBG_FUNC, "UNIMPLEMENTED bcp option: BCPLABELED\n");
648 : break;
649 12 : case BCPHINTS:
650 12 : if (!value || valuelen <= 0)
651 : break;
652 :
653 : /* Hint documentation: https://learn.microsoft.com/en-us/sql/t-sql/statements/bulk-insert-transact-sql */
654 12 : if (tds_dstr_copyn(&dbproc->bcpinfo->hint, (char *) value, valuelen))
655 : return SUCCEED;
656 : break;
657 :
658 0 : default:
659 0 : tdsdump_log(TDS_DBG_FUNC, "UNIMPLEMENTED bcp option: %u\n", option);
660 : break;
661 : }
662 0 : return FAIL;
663 : }
664 :
665 : /**
666 : * \ingroup dblib_bcp
667 : * \brief Override bcp_bind() by pointing to a different host variable.
668 : *
669 : * \param dbproc contains all information needed by db-lib to manage communications with the server.
670 : * \param colptr The pointer, the address of your variable.
671 : * \param table_column The 1-based column ordinal in the table.
672 : * \remarks Use between calls to bcp_sendrow(). After calling bcp_colptr(),
673 : * subsequent calls to bcp_sendrow() will bind to the new address.
674 : * \return SUCCEED or FAIL.
675 : * \sa bcp_bind(), bcp_collen(), bcp_sendrow()
676 : */
677 : RETCODE
678 0 : bcp_colptr(DBPROCESS * dbproc, BYTE * colptr, int table_column)
679 : {
680 : TDSCOLUMN *curcol;
681 :
682 0 : tdsdump_log(TDS_DBG_FUNC, "bcp_colptr(%p, %p, %d)\n", dbproc, colptr, table_column);
683 0 : CHECK_CONN(FAIL);
684 0 : CHECK_PARAMETER(dbproc->bcpinfo, SYBEBCPI, FAIL);
685 0 : CHECK_PARAMETER(dbproc->bcpinfo->bindinfo, SYBEBCPI, FAIL);
686 : /* colptr can be NULL */
687 :
688 0 : if (dbproc->bcpinfo->direction != DB_IN) {
689 0 : dbperror(dbproc, SYBEBCPN, 0);
690 0 : return FAIL;
691 : }
692 0 : if (table_column <= 0 || table_column > dbproc->bcpinfo->bindinfo->num_cols) {
693 0 : dbperror(dbproc, SYBEBCPN, 0);
694 0 : return FAIL;
695 : }
696 :
697 0 : curcol = dbproc->bcpinfo->bindinfo->columns[table_column - 1];
698 0 : curcol->column_varaddr = (TDS_CHAR *)colptr;
699 :
700 0 : return SUCCEED;
701 : }
702 :
703 :
704 : /**
705 : * \ingroup dblib_bcp
706 : * \brief See if BCP_SETL() was used to set the LOGINREC for BCP work.
707 : *
708 : * \param login Address of the LOGINREC variable to be passed to dbopen().
709 : *
710 : * \return TRUE or FALSE.
711 : * \sa BCP_SETL(), bcp_init(), dblogin(), dbopen()
712 : */
713 : DBBOOL
714 10 : bcp_getl(LOGINREC * login)
715 : {
716 10 : TDSLOGIN *tdsl = login->tds_login;
717 :
718 10 : tdsdump_log(TDS_DBG_FUNC, "bcp_getl(%p)\n", login);
719 :
720 10 : return (tdsl->bulk_copy);
721 : }
722 :
723 : /**
724 : * Convert column for output (usually to a file)
725 : * Conversion is slightly different from input as:
726 : * - date is formatted differently;
727 : * - you have to set properly numeric while on input the column metadata are
728 : * used;
729 : * - we need to make sure buffer is always at least a minimum bytes.
730 : */
731 : static int
732 2046 : _bcp_convert_out(DBPROCESS * dbproc, TDSCOLUMN *curcol, BCP_HOSTCOLINFO *hostcol, TDS_UCHAR **p_data, const char *bcpdatefmt)
733 : {
734 : BYTE *src;
735 : int srclen;
736 : int buflen;
737 2046 : int srctype = tds_get_conversion_type(curcol->column_type, curcol->column_size);
738 :
739 2046 : src = curcol->column_data;
740 2046 : if (is_blob_col(curcol))
741 122 : src = (BYTE *) ((TDSBLOB *) src)->textvalue;
742 :
743 2046 : srclen = curcol->column_cur_size;
744 :
745 : /*
746 : * if we are converting datetime to string, need to override any
747 : * date time formats already established
748 : */
749 2046 : if (is_datetime_type(srctype) && is_ascii_type(hostcol->datatype)) {
750 : TDSDATEREC when;
751 :
752 : /* Some date/time types have variable precision (e.g. MS datetime2),
753 : * and set curcol->column_prec with that precision.
754 : * DATETIME is printed with precision 3 by MS BCP & ASE BCP however
755 : * curcol->column_prec is not set for that type.
756 : * (It might be better to set column_prec at load time for all
757 : * of the datetime types...)
758 : */
759 80 : int prec = curcol->column_prec ? curcol->column_prec : 3;
760 :
761 80 : tds_datecrack(srctype, src, &when);
762 80 : buflen = _bcp_strftime((char *) *p_data, 256, bcpdatefmt, &when, prec);
763 1966 : } else if (srclen == 0 && is_variable_type(curcol->column_type)
764 46 : && is_ascii_type(hostcol->datatype)) {
765 : /*
766 : * An empty string is denoted in the output file by a single ASCII NUL
767 : * byte that we request by specifying a destination length of -1. (Not
768 : * to be confused with a database NULL, which is denoted in the output
769 : * file with an empty string!)
770 : */
771 46 : (*p_data)[0] = 0;
772 46 : buflen = 1;
773 1920 : } else if (is_numeric_type(hostcol->datatype)) {
774 0 : TDS_NUMERIC *num = (TDS_NUMERIC *) (*p_data);
775 0 : if (is_numeric_type(srctype)) {
776 0 : TDS_NUMERIC *nsrc = (TDS_NUMERIC *) src;
777 0 : num->precision = nsrc->precision;
778 0 : num->scale = nsrc->scale;
779 : } else {
780 0 : num->precision = 18;
781 0 : num->scale = 0;
782 : }
783 0 : buflen = tds_convert(dbproc->tds_socket->conn->tds_ctx, srctype, src, srclen, hostcol->datatype, (CONV_RESULT *) num);
784 0 : if (buflen > 0)
785 0 : buflen = tds_numeric_bytes_per_prec[num->precision] + 2;
786 1920 : } else if (!is_variable_type(hostcol->datatype)) {
787 30 : buflen = tds_convert(dbproc->tds_socket->conn->tds_ctx, srctype, src, srclen, hostcol->datatype, (CONV_RESULT *) (*p_data));
788 : } else {
789 : CONV_RESULT cr;
790 :
791 : /*
792 : * For null columns, the above work to determine the output buffer size is moot,
793 : * because bcpcol->data_size is zero, so dbconvert() won't write anything,
794 : * and returns zero.
795 : */
796 1890 : buflen = tds_convert(dbproc->tds_socket->conn->tds_ctx, srctype, src, srclen, hostcol->datatype, (CONV_RESULT *) &cr);
797 1890 : if (buflen < 0)
798 0 : return buflen;
799 :
800 1890 : if (buflen >= 256) {
801 30 : free(*p_data);
802 30 : *p_data = (TDS_UCHAR *) cr.c;
803 : } else {
804 1860 : memcpy(*p_data, cr.c, buflen);
805 1860 : free(cr.c);
806 : }
807 :
808 : /*
809 : * Special case: When outputting database varchar data
810 : * (either varchar or nullable char) conversion may have
811 : * trimmed trailing blanks such that nothing is left.
812 : * In this case we need to put a single blank to the output file.
813 : */
814 1890 : if (is_char_type(curcol->column_type) && srclen > 0 && buflen == 0) {
815 0 : strcpy ((char *) (*p_data), " ");
816 0 : buflen = 1;
817 : }
818 : }
819 : return buflen;
820 : }
821 :
822 : static int
823 : bcp_cache_prefix_len(BCP_HOSTCOLINFO *hostcol, const TDSCOLUMN *curcol)
824 : {
825 : int plen;
826 :
827 0 : if (type_has_textptr(hostcol->datatype))
828 : plen = 4;
829 0 : else if (is_numeric_type(hostcol->datatype))
830 : plen = 1;
831 0 : else if (!is_fixed_type(hostcol->datatype))
832 : plen = 2;
833 0 : else if (curcol->column_nullable)
834 : plen = 1;
835 : else
836 0 : plen = 0;
837 : /* cache */
838 0 : return hostcol->prefix_len = plen;
839 : }
840 :
841 : static RETCODE
842 2336 : bcp_write_prefix(TDSFILEOUTSTREAM *hoststream, BCP_HOSTCOLINFO *hostcol, TDSCOLUMN *curcol, int buflen)
843 : {
844 : union {
845 : TDS_TINYINT ti;
846 : TDS_SMALLINT si;
847 : TDS_INT li;
848 : } u;
849 : int plen;
850 :
851 : /* compute prefix len if needed */
852 2336 : if ((plen = hostcol->prefix_len) == -1)
853 0 : plen = bcp_cache_prefix_len(hostcol, curcol);
854 :
855 : /* output prefix to file */
856 2336 : switch (plen) {
857 : default:
858 : return SUCCEED;
859 50 : case 1:
860 50 : u.ti = buflen;
861 50 : break;
862 0 : case 2:
863 0 : u.si = buflen;
864 0 : break;
865 10 : case 4:
866 10 : u.li = buflen;
867 10 : break;
868 : }
869 60 : return TDS_SUCCEED(tds_fileout_stream_put(hoststream, &u, plen)) ? SUCCEED : FAIL;
870 : }
871 :
872 : /**
873 : * \ingroup dblib_bcp_internal
874 : * \brief
875 : *
876 : *
877 : * \param dbproc contains all information needed by db-lib to manage communications with the server.
878 : * \param rows_copied
879 : *
880 : * \return SUCCEED or FAIL.
881 : * \sa BCP_SETL(), bcp_batch(), bcp_bind(), bcp_colfmt(), bcp_colfmt_ps(), bcp_collen(), bcp_colptr(), bcp_columns(), bcp_control(), bcp_done(), bcp_exec(), bcp_getl(), bcp_init(), bcp_moretext(), bcp_options(), bcp_readfmt(), bcp_sendrow()
882 : */
883 : static RETCODE
884 206 : _bcp_exec_out(DBPROCESS * dbproc, DBINT * rows_copied)
885 : {
886 : TDSFILEOUTSTREAM hoststream;
887 206 : FILE *hostfp = NULL;
888 206 : TDS_UCHAR *data = NULL;
889 : int i;
890 :
891 : TDSSOCKET *tds;
892 : TDSRESULTINFO *resinfo;
893 206 : TDSCOLUMN *curcol = NULL;
894 : BCP_HOSTCOLINFO *hostcol;
895 : int buflen;
896 :
897 : TDS_INT result_type;
898 :
899 : TDS_INT row_of_query;
900 : DBINT rows_written;
901 : const char *bcpdatefmt;
902 : TDSRET tdsret;
903 :
904 206 : tdsdump_log(TDS_DBG_FUNC, "_bcp_exec_out(%p, %p)\n", dbproc, rows_copied);
905 206 : assert(dbproc);
906 206 : assert(rows_copied);
907 :
908 206 : tds = dbproc->tds_socket;
909 206 : assert(tds);
910 :
911 : /* See if they want a BCP date format different from the default.
912 : * The ASE bcp client does use the locale for bcp out; but all bcp clients
913 : * appear to successfully read this format for input, regardless of locale.
914 : */
915 206 : bcpdatefmt = getenv("FREEBCP_DATEFMT");
916 206 : if (bcpdatefmt && !strcmp(bcpdatefmt, BCP_DEFAULT_DATEFMT))
917 0 : bcpdatefmt = NULL;
918 :
919 206 : if (dbproc->bcpinfo->direction == DB_QUERYOUT ) {
920 0 : if (TDS_FAILED(tds_submit_query(tds, tds_dstr_cstr(&dbproc->bcpinfo->tablename))))
921 : return FAIL;
922 : } else {
923 : /* TODO quote if needed */
924 412 : if (TDS_FAILED(tds_submit_queryf(tds, "select * from %s", tds_dstr_cstr(&dbproc->bcpinfo->tablename))))
925 : return FAIL;
926 : }
927 :
928 206 : tdsret = tds_process_tokens(tds, &result_type, NULL, TDS_TOKEN_RESULTS);
929 206 : if (TDS_FAILED(tdsret))
930 : return FAIL;
931 :
932 206 : if (!tds->res_info) {
933 : /* TODO flush/cancel to keep consistent state */
934 : return FAIL;
935 : }
936 :
937 206 : resinfo = tds->res_info;
938 :
939 206 : row_of_query = 0;
940 206 : rows_written = 0;
941 :
942 : /* allocate at least 256 bytes */
943 : /* allocate data for buffer conversion */
944 206 : data = tds_new(TDS_UCHAR, 256);
945 206 : if (!data) {
946 0 : dbperror(dbproc, SYBEMEM, errno);
947 : goto Cleanup;
948 : }
949 :
950 : /*
951 : * TODO above we allocate many buffer just to convert and store
952 : * to file.. avoid all that passages...
953 : */
954 206 : if (!(hostfp = fopen(dbproc->hostfileinfo->hostfile, "w" TDS_FOPEN_BINARY))) {
955 0 : dbperror(dbproc, SYBEBCUO, errno);
956 0 : goto Cleanup;
957 : }
958 206 : tds_fileout_stream_init(&hoststream, hostfp, _IOFBF);
959 :
960 : /* fetch a row of data from the server */
961 :
962 888 : while (tds_process_tokens(tds, &result_type, NULL, TDS_STOPAT_ROWFMT|TDS_RETURN_DONE|TDS_RETURN_ROW|TDS_RETURN_COMPUTE)
963 : == TDS_SUCCESS) {
964 :
965 682 : if (result_type != TDS_ROW_RESULT && result_type != TDS_COMPUTE_RESULT)
966 : break;
967 :
968 476 : row_of_query++;
969 :
970 : /* skip rows outside of the firstrow/lastrow range, if specified */
971 476 : if (dbproc->hostfileinfo->firstrow > row_of_query)
972 0 : continue;
973 476 : if (dbproc->hostfileinfo->lastrow > 0 && row_of_query > dbproc->hostfileinfo->lastrow) {
974 : /* TODO: If this is freebcp we could now just return success,
975 : * rather than waste time processing the rest of data.
976 : * In other cases we could perhaps send a cancel request.
977 : */
978 0 : continue;
979 : }
980 :
981 : /* Go through the hostfile columns, finding those that relate to database columns. */
982 2336 : for (i = 0; i < dbproc->hostfileinfo->host_colcount; i++) {
983 2336 : hostcol = dbproc->hostfileinfo->host_columns[i];
984 2336 : if (hostcol->tab_colnum < 1 || hostcol->tab_colnum > resinfo->num_cols)
985 0 : continue;
986 :
987 2336 : curcol = resinfo->columns[hostcol->tab_colnum - 1];
988 :
989 2336 : if (curcol->column_cur_size < 0) {
990 : buflen = 0;
991 : } else {
992 2046 : buflen = _bcp_convert_out(dbproc, curcol, hostcol, &data, bcpdatefmt);
993 : }
994 2046 : if (buflen < 0) {
995 0 : _dblib_convert_err(dbproc, buflen);
996 0 : goto Cleanup;
997 : }
998 :
999 : /* The prefix */
1000 2336 : if (bcp_write_prefix(&hoststream, hostcol, curcol, buflen) != SUCCEED)
1001 : goto write_error;
1002 :
1003 : /* The data */
1004 2336 : if (hostcol->column_len != -1) {
1005 40 : buflen = TDS_MIN(buflen, hostcol->column_len);
1006 : }
1007 :
1008 2336 : if (buflen > 0) {
1009 2046 : if (!TDS_SUCCEED(tds_fileout_stream_put(&hoststream, data, buflen)))
1010 : goto write_error;
1011 : }
1012 :
1013 : /* The terminator */
1014 2336 : if (hostcol->terminator && hostcol->term_len > 0) {
1015 2246 : if (!TDS_SUCCEED(tds_fileout_stream_put(&hoststream, hostcol->terminator, hostcol->term_len)))
1016 : goto write_error;
1017 : }
1018 : }
1019 476 : rows_written++;
1020 : }
1021 :
1022 206 : if (TDS_FAILED(tds_fileout_stream_flush(&hoststream)) || fclose(hostfp) != 0) {
1023 0 : dbperror(dbproc, SYBEBCUC, errno);
1024 0 : goto Cleanup;
1025 : }
1026 206 : hostfp = NULL;
1027 :
1028 206 : if (row_of_query + 1 < dbproc->hostfileinfo->firstrow) {
1029 : /*
1030 : * The table which bulk-copy is attempting to
1031 : * copy to a host-file is shorter than the
1032 : * number of rows which bulk-copy was instructed to skip.
1033 : */
1034 : /* TODO reset TDSSOCKET state */
1035 0 : dbperror(dbproc, SYBETTS, 0);
1036 : goto Cleanup;
1037 : }
1038 :
1039 206 : *rows_copied = rows_written;
1040 206 : free(data);
1041 206 : return SUCCEED;
1042 :
1043 0 : write_error:
1044 0 : dbperror(dbproc, SYBEBCWE, errno);
1045 :
1046 0 : Cleanup:
1047 0 : if (hostfp)
1048 0 : fclose(hostfp);
1049 0 : free(data);
1050 0 : return FAIL;
1051 : }
1052 :
1053 : static STATUS
1054 216 : _bcp_check_eof(DBPROCESS * dbproc, TDSFILESTREAM* stream, int icol)
1055 : {
1056 216 : int errnum = errno;
1057 : FILE *file;
1058 :
1059 216 : tdsdump_log(TDS_DBG_FUNC, "_bcp_check_eof(%p, %p, %d)\n", dbproc, stream, icol);
1060 216 : assert(dbproc);
1061 216 : assert(stream);
1062 :
1063 216 : file = stream->f;
1064 216 : assert(file);
1065 :
1066 216 : if (stream->inpos == stream->inlen && feof(file)) {
1067 216 : if (icol == 0) {
1068 216 : tdsdump_log(TDS_DBG_FUNC, "Normal end-of-file reached while loading bcp data file.\n");
1069 : return NO_MORE_ROWS;
1070 : }
1071 0 : dbperror(dbproc, SYBEBEOF, errnum);
1072 0 : return FAIL;
1073 : }
1074 0 : dbperror(dbproc, SYBEBCRE, errnum);
1075 0 : return FAIL;
1076 : }
1077 :
1078 : /**
1079 : * Convert column for input to a table
1080 : *
1081 : * Character data copied to a character column, or binary data copied to a
1082 : * binary column, which is too long for the server column is truncated and
1083 : * SYBEBCOR is reported, as Sybase library does. Any other conversion
1084 : * producing data too long is an error (SYBECOFL).
1085 : *
1086 : * \param truncated if not NULL, set to true if data were truncated, false otherwise.
1087 : */
1088 : static TDSRET
1089 5118 : _bcp_convert_in(DBPROCESS *dbproc, TDS_SERVER_TYPE srctype, const TDS_CHAR *src, TDS_UINT srclen,
1090 : TDS_SERVER_TYPE desttype, TDSCOLUMN *col, bool *truncated)
1091 : {
1092 5118 : bool variable = true;
1093 : CONV_RESULT cr, *p_cr;
1094 : TDS_INT len;
1095 5118 : BCPCOLDATA *coldata = col->bcp_column_data;
1096 :
1097 5118 : coldata->is_null = false;
1098 5118 : if (truncated)
1099 2018 : *truncated = false;
1100 :
1101 5118 : if (!is_variable_type(desttype)) {
1102 3464 : variable = false;
1103 3464 : p_cr = (CONV_RESULT *) coldata->data;
1104 : } else {
1105 : p_cr = &cr;
1106 : }
1107 :
1108 5118 : len = tds_convert(dbproc->tds_socket->conn->tds_ctx, srctype, src, srclen, desttype, p_cr);
1109 5118 : if (len < 0) {
1110 20 : _dblib_convert_err(dbproc, len);
1111 : return TDS_FAIL;
1112 : }
1113 :
1114 5098 : if (variable && len > col->on_server.column_size) {
1115 50 : if ((is_char_type(srctype) && is_char_type(desttype))
1116 10 : || (is_binary_type(srctype) && is_binary_type(desttype))) {
1117 : /* not an error, data are truncated */
1118 50 : dbperror(dbproc, SYBEBCOR, 0);
1119 50 : len = col->on_server.column_size;
1120 50 : if (truncated)
1121 40 : *truncated = true;
1122 : } else {
1123 0 : free(cr.c);
1124 0 : dbperror(dbproc, SYBECOFL, 0);
1125 : return TDS_FAIL;
1126 : }
1127 : }
1128 :
1129 5098 : coldata->datalen = len;
1130 5098 : if (variable) {
1131 1654 : free(coldata->data);
1132 1654 : coldata->data = (TDS_UCHAR *) cr.c;
1133 : }
1134 : return TDS_SUCCESS;
1135 : }
1136 :
1137 : static void
1138 5118 : rtrim_bcpcol(TDSCOLUMN *bcpcol)
1139 : {
1140 : /* trim trailing blanks from character data */
1141 5118 : if (is_ascii_type(bcpcol->on_server.column_type)) {
1142 : /* A single NUL byte indicates an empty string. */
1143 1472 : if (bcpcol->bcp_column_data->datalen == 1
1144 256 : && bcpcol->bcp_column_data->data[0] == '\0') {
1145 0 : bcpcol->bcp_column_data->datalen = 0;
1146 0 : return;
1147 : }
1148 2944 : bcpcol->bcp_column_data->datalen = rtrim((char *) bcpcol->bcp_column_data->data,
1149 : bcpcol->bcp_column_data->datalen);
1150 1472 : return;
1151 : }
1152 :
1153 : /* unicode part */
1154 3646 : if (is_unicode_type(bcpcol->on_server.column_type)) {
1155 : uint16_t *data, space;
1156 :
1157 68 : if (!bcpcol->char_conv || bcpcol->char_conv->to.charset.min_bytes_per_char != 2)
1158 6 : return;
1159 :
1160 68 : data = (uint16_t *) bcpcol->bcp_column_data->data;
1161 : /* A single NUL byte indicates an empty string. */
1162 68 : if (bcpcol->bcp_column_data->datalen == 2 && data[0] == 0) {
1163 6 : bcpcol->bcp_column_data->datalen = 0;
1164 6 : return;
1165 : }
1166 62 : switch (bcpcol->char_conv->to.charset.canonic) {
1167 0 : case TDS_CHARSET_UTF_16BE:
1168 : case TDS_CHARSET_UCS_2BE:
1169 0 : TDS_PUT_A2BE(&space, 0x20);
1170 0 : break;
1171 62 : case TDS_CHARSET_UTF_16LE:
1172 : case TDS_CHARSET_UCS_2LE:
1173 62 : TDS_PUT_A2LE(&space, 0x20);
1174 62 : break;
1175 : default:
1176 : return;
1177 : }
1178 124 : bcpcol->bcp_column_data->datalen = rtrim_u16(data, bcpcol->bcp_column_data->datalen, space);
1179 : }
1180 : }
1181 :
1182 : /**
1183 : * \ingroup dblib_bcp_internal
1184 : * \brief
1185 : *
1186 : * \param dbproc contains all information needed by db-lib to manage communications with the server.
1187 : * \param hostfile
1188 : * \param row_error set to true if an error is detected in the row
1189 : * \param skip skip the row
1190 : *
1191 : * \return MORE_ROWS, NO_MORE_ROWS, or FAIL.
1192 : * \sa BCP_SETL(), bcp_batch(), bcp_bind(), bcp_colfmt(), bcp_colfmt_ps(), bcp_collen(), bcp_colptr(), bcp_columns(), bcp_control(), bcp_done(), bcp_exec(), bcp_getl(), bcp_init(), bcp_moretext(), bcp_options(), bcp_readfmt(), bcp_sendrow()
1193 : */
1194 : static STATUS
1195 722 : _bcp_read_hostfile(DBPROCESS *dbproc, TDSFILESTREAM *stream, bool *row_error, bool skip)
1196 : {
1197 : int i;
1198 722 : bool truncation_warning = false;
1199 :
1200 722 : tdsdump_log(TDS_DBG_FUNC, "_bcp_read_hostfile(%p, %p, %p, %d)\n", dbproc, stream, row_error, skip);
1201 722 : assert(dbproc);
1202 722 : assert(row_error);
1203 :
1204 : /* for each host file column defined by calls to bcp_colfmt */
1205 :
1206 5446 : for (i = 0; i < dbproc->hostfileinfo->host_colcount; i++) {
1207 2578 : TDSCOLUMN *bcpcol = NULL;
1208 : BCP_HOSTCOLINFO *hostcol;
1209 2578 : TDS_CHAR *coldata = NULL;
1210 2578 : int collen = 0; /* How many bytes to read from hostfile */
1211 2578 : bool data_is_null = false;
1212 : offset_type col_start;
1213 :
1214 2578 : tdsdump_log(TDS_DBG_FUNC, "parsing host column %d\n", i + 1);
1215 2578 : hostcol = dbproc->hostfileinfo->host_columns[i];
1216 :
1217 2578 : hostcol->column_error = 0;
1218 :
1219 : /*
1220 : * If this host file column contains table data,
1221 : * find the right element in the table/column list.
1222 : */
1223 2578 : if (hostcol->tab_colnum > 0) {
1224 2578 : if (hostcol->tab_colnum > dbproc->bcpinfo->bindinfo->num_cols) {
1225 0 : tdsdump_log(TDS_DBG_FUNC, "error: file wider than table: %d/%d\n",
1226 : i+1, dbproc->bcpinfo->bindinfo->num_cols);
1227 0 : dbperror(dbproc, SYBEBEOF, 0);
1228 0 : return FAIL;
1229 : }
1230 2578 : tdsdump_log(TDS_DBG_FUNC, "host column %d uses bcpcol %d (%p)\n",
1231 : i+1, hostcol->tab_colnum, bcpcol);
1232 2578 : bcpcol = dbproc->bcpinfo->bindinfo->columns[hostcol->tab_colnum - 1];
1233 2578 : assert(bcpcol != NULL);
1234 : }
1235 :
1236 : /* detect prefix len. NOTE: requires server connection, because
1237 : * it will add a prefix to a prefix-less fixed type if the column
1238 : * is nullable. */
1239 2578 : if (bcpcol && hostcol->prefix_len == -1)
1240 0 : bcp_cache_prefix_len(hostcol, bcpcol);
1241 :
1242 : /* If a variable field has no prefix or terminator, its length can
1243 : * only be set by hostcol->column_len.
1244 : *
1245 : * NOTE: Must check do this after bcp_cache_prefix_len() as that
1246 : * could set or unset the prefix_len. */
1247 2578 : if (hostcol->prefix_len == 0 && hostcol->term_len <= 0 && !is_fixed_type(hostcol->datatype)) {
1248 20 : if (hostcol->column_len == -1) {
1249 : /* If no column max size given either, we can't know how much to read. */
1250 0 : dbperror(dbproc, SYBEVDPT, 0);
1251 0 : return FAIL;
1252 : }
1253 :
1254 : /* Column size 0, special case to indicate null field. */
1255 20 : if (hostcol->column_len == 0)
1256 10 : data_is_null = true;
1257 :
1258 : collen = hostcol->column_len;
1259 : }
1260 :
1261 : /* a prefix length, if extant, specifies how many bytes to read */
1262 2578 : if (hostcol->prefix_len > 0) {
1263 : union {
1264 : TDS_TINYINT ti;
1265 : TDS_SMALLINT si;
1266 : TDS_INT li;
1267 : } u;
1268 :
1269 : /* note: prefixes are in native endianness. */
1270 70 : switch (hostcol->prefix_len) {
1271 60 : case 1:
1272 60 : if (tds_file_stream_read_raw(stream, &u.ti, 1) != 1)
1273 20 : return _bcp_check_eof(dbproc, stream, i);
1274 50 : collen = u.ti ? u.ti : -1;
1275 50 : break;
1276 0 : case 2:
1277 0 : if (tds_file_stream_read_raw(stream, &u.si, 2) != 2)
1278 0 : return _bcp_check_eof(dbproc, stream, i);
1279 0 : collen = u.si;
1280 0 : break;
1281 10 : case 4:
1282 10 : if (tds_file_stream_read_raw(stream, &u.li, 4) != 4)
1283 0 : return _bcp_check_eof(dbproc, stream, i);
1284 10 : collen = u.li;
1285 10 : break;
1286 0 : default:
1287 : /* Should be unreachable - bcp_colfmt() also checked this. */
1288 0 : dbperror(dbproc, SYBEBCPREF, 0);
1289 0 : return FAIL;
1290 : }
1291 :
1292 : /* TODO test all NULL types */
1293 : /* Length prefix of -1 means a null value. */
1294 60 : if (collen <= -1)
1295 : data_is_null = true;
1296 : }
1297 :
1298 : /* Report an error if a fixed-width type has mismatching prefix.
1299 : * Note: fixed-width types are allowed a prefix in order to be nullable.
1300 : */
1301 2568 : if (!data_is_null && is_fixed_type(hostcol->datatype)) {
1302 40 : int fixed_size = tds_get_size_by_type(hostcol->datatype);
1303 :
1304 40 : if (collen > 0 && collen != fixed_size) {
1305 0 : tdsdump_log(TDS_DBG_FUNC,
1306 : "bcp_colfmt: invalid collen %d for fixed type %d.\n", collen, hostcol->datatype);
1307 0 : dbperror(dbproc, SYBECSYN, 0);
1308 0 : return FAIL;
1309 : }
1310 :
1311 : collen = fixed_size;
1312 : }
1313 :
1314 2568 : tdsdump_log(TDS_DBG_FUNC, "prefix_len = %d, term_len = %d, collen = %d\n", hostcol->prefix_len, hostcol->term_len,
1315 : collen);
1316 :
1317 2568 : col_start = tds_file_stream_tell(stream);
1318 :
1319 : /* We will perform iconv on hostfile text only when the field has a
1320 : * terminator, because that indicates it's a text file and would be
1321 : * in the client charset. Prefixed fields indicate a host-native
1322 : * file, and our tds_bcp_fread() function doesn't support
1323 : * reading an exact number of bytes anyway.
1324 : *
1325 : * NOTE: bcp_colfmt() prevents field having both prefix and terminator.
1326 : */
1327 2568 : if (data_is_null)
1328 : collen = 0;
1329 2558 : else if (hostcol->term_len > 0) {
1330 : size_t col_bytes;
1331 : TDSRET conv_res;
1332 :
1333 : /* Note: Important to not stop reading early based on a field width
1334 : * setting (this would cause hostfile to get out of sync). */
1335 2468 : coldata = NULL;
1336 4936 : conv_res = tds_bcp_fread(dbproc->tds_socket, bcpcol ? bcpcol->char_conv : NULL, stream,
1337 2468 : (const char *) hostcol->terminator, hostcol->term_len, &coldata, &col_bytes);
1338 :
1339 2468 : if (TDS_FAILED(conv_res)) {
1340 0 : tdsdump_log(TDS_DBG_FUNC, "col %d: error converting %ld bytes!\n",
1341 : (i+1), (long) collen);
1342 0 : *row_error = true;
1343 0 : free(coldata);
1344 : /* This case can include columns missing a terminator, and
1345 : * wrong number of columns in the row, as well as the data not
1346 : * being of valid form for the column type. */
1347 0 : dbperror(dbproc, SYBECSYN, 0);
1348 0 : return FAIL;
1349 : }
1350 :
1351 2468 : if (conv_res == TDS_NO_MORE_RESULTS) {
1352 196 : free(coldata);
1353 196 : return _bcp_check_eof(dbproc, stream, i);
1354 : }
1355 :
1356 2272 : if (col_bytes > 0x7fffffffl) {
1357 0 : free(coldata);
1358 0 : *row_error = true;
1359 0 : tdsdump_log(TDS_DBG_FUNC, "data from file is too large!\n");
1360 0 : dbperror(dbproc, SYBEBCOR, 0);
1361 0 : return FAIL;
1362 : }
1363 :
1364 : /* collen is the post-iconv size of the field here */
1365 2272 : collen = (int) col_bytes;
1366 2272 : if (collen == 0)
1367 334 : data_is_null = true;
1368 :
1369 : /* To support empty strings and keep compatibility with older files empty strings
1370 : * are encoded as a single NUL byte. */
1371 2272 : if (collen == 1 && coldata[0] == '\0')
1372 40 : collen = 0;
1373 :
1374 : /*
1375 : * TODO:
1376 : * Dates are a problem. In theory, we should be able to read non-English dates, which
1377 : * would contain non-ASCII characters. One might suppose we should convert date
1378 : * strings to ISO-8859-1 (or another canonical form) here, because tds_convert() can't be
1379 : * expected to deal with encodings. But instead date strings are read verbatim and
1380 : * passed to tds_convert() without even waving to iconv(). For English dates, this works,
1381 : * because English dates expressed as UTF-8 strings are indistinguishable from the ASCII.
1382 : */
1383 : } else { /* Length known due to being a fixed field and/or prefixed. */
1384 90 : assert(collen > 0); // The above logic should guarantee this.
1385 :
1386 90 : coldata = tds_new(TDS_CHAR, 1 + collen);
1387 90 : if (coldata == NULL) {
1388 0 : *row_error = true;
1389 0 : dbperror(dbproc, SYBEMEM, errno);
1390 0 : return FAIL;
1391 : }
1392 :
1393 90 : tdsdump_log(TDS_DBG_FUNC, "Reading %d bytes from hostfile.\n", collen);
1394 90 : if (tds_file_stream_read_raw(stream, coldata, collen) != collen) {
1395 10 : free(coldata);
1396 10 : return _bcp_check_eof(dbproc, stream, i);
1397 : }
1398 :
1399 : /* Not sure why this is here, the terminated-read branch doesn't do it. */
1400 80 : coldata[collen] = 0;
1401 : }
1402 :
1403 : /*
1404 : * At this point, however the field was read, however big it was, its
1405 : * address is coldata (which is a dynamically allocated buffer or NULL),
1406 : * and its size is collen.
1407 : * NOTE: we intentionally do not force truncation to hostcol->column_len
1408 : * if a prefix/terminator specified longer data; matching behaviour of MS BCP 16.0.
1409 : */
1410 2362 : tdsdump_log(TDS_DBG_FUNC, "Data read from hostfile: collen is now %d, data_is_null is %d\n", collen, data_is_null);
1411 2362 : if (!skip && bcpcol) {
1412 2362 : if (data_is_null) {
1413 344 : bcpcol->bcp_column_data->is_null = true;
1414 344 : bcpcol->bcp_column_data->datalen = 0;
1415 : } else {
1416 : TDSRET rc;
1417 : TDS_SERVER_TYPE desttype;
1418 : bool truncated;
1419 :
1420 2018 : desttype = tds_get_conversion_type(bcpcol->column_type, bcpcol->column_size);
1421 :
1422 : /* _bcp_convert_in truncates data too long for the server column */
1423 2018 : rc = _bcp_convert_in(dbproc, hostcol->datatype, (const TDS_CHAR *) coldata, collen,
1424 : desttype, bcpcol, &truncated);
1425 2018 : if (truncated) {
1426 40 : tdsdump_log(TDS_DBG_INFO1,
1427 : "Warning: _bcp_read_hostfile: %d bytes at offset 0x%" PRIx64
1428 : " in the data file: truncated to server size %d.\n",
1429 : collen, (TDS_INT8) col_start, (int) bcpcol->on_server.column_size);
1430 : truncation_warning = true;
1431 : }
1432 2018 : if (TDS_FAILED(rc)) {
1433 20 : hostcol->column_error = HOST_COL_CONV_ERROR;
1434 20 : *row_error = true;
1435 20 : tdsdump_log(TDS_DBG_FUNC,
1436 : "_bcp_read_hostfile failed to convert %d bytes at offset 0x%" PRIx64
1437 : " in the data file.\n", collen, (TDS_INT8) col_start);
1438 : }
1439 :
1440 2018 : rtrim_bcpcol(bcpcol);
1441 : }
1442 : #if USING_SYBEBCNN
1443 : if (!hostcol->column_error) {
1444 : if (bcpcol->bcp_column_data->datalen <= 0) { /* Are we trying to insert a NULL ? */
1445 : if (!bcpcol->column_nullable) {
1446 : /* too bad if the column is not nullable */
1447 : hostcol->column_error = HOST_COL_NULL_ERROR;
1448 : *row_error = true;
1449 : dbperror(dbproc, SYBEBCNN, 0);
1450 : }
1451 : }
1452 : }
1453 : #endif
1454 : }
1455 2362 : free(coldata);
1456 : }
1457 :
1458 506 : if (dbproc->bcpinfo->dry_run && truncation_warning)
1459 0 : printf("Warning: data truncated due to server column being too small; see log file for detail.\n");
1460 :
1461 : return MORE_ROWS;
1462 : }
1463 :
1464 : /**
1465 : * \ingroup dblib_bcp
1466 : * \brief Write data in host variables to the table.
1467 : *
1468 : * \param dbproc contains all information needed by db-lib to manage communications with the server.
1469 : *
1470 : * \remarks Call bcp_bind() first to describe the variables to be used.
1471 : * Use bcp_batch() to commit sets of rows.
1472 : * After sending the last row call bcp_done().
1473 : * \return SUCCEED or FAIL.
1474 : * \sa bcp_batch(), bcp_bind(), bcp_colfmt(), bcp_collen(), bcp_colptr(), bcp_columns(),
1475 : * bcp_control(), bcp_done(), bcp_exec(), bcp_init(), bcp_moretext(), bcp_options()
1476 : */
1477 : RETCODE
1478 510 : bcp_sendrow(DBPROCESS * dbproc)
1479 : {
1480 : TDSSOCKET *tds;
1481 :
1482 510 : tdsdump_log(TDS_DBG_FUNC, "bcp_sendrow(%p)\n", dbproc);
1483 510 : CHECK_CONN(FAIL);
1484 510 : CHECK_PARAMETER(dbproc->bcpinfo, SYBEBCPI, FAIL);
1485 :
1486 510 : tds = dbproc->tds_socket;
1487 :
1488 510 : if (dbproc->bcpinfo->direction != DB_IN) {
1489 0 : dbperror(dbproc, SYBEBCPN, 0);
1490 0 : return FAIL;
1491 : }
1492 :
1493 510 : if (dbproc->hostfileinfo != NULL) {
1494 0 : dbperror(dbproc, SYBEBCPB, 0);
1495 0 : return FAIL;
1496 : }
1497 :
1498 : /*
1499 : * The first time sendrow is called after bcp_init,
1500 : * there is a certain amount of initialisation to be done.
1501 : */
1502 510 : if (!dbproc->bcpinfo->xfer_init) {
1503 :
1504 : /* The start_copy function retrieves details of the table's columns */
1505 348 : if (TDS_FAILED(tds_bcp_start_copy_in(tds, dbproc->bcpinfo))) {
1506 0 : dbperror(dbproc, SYBEBULKINSERT, 0);
1507 0 : return FAIL;
1508 : }
1509 :
1510 348 : dbproc->bcpinfo->xfer_init = true;
1511 :
1512 : }
1513 :
1514 510 : dbproc->bcpinfo->parent = dbproc;
1515 510 : return TDS_FAILED(tds_bcp_send_record(dbproc->tds_socket, dbproc->bcpinfo,
1516 510 : _bcp_get_col_data, _bcp_null_error, 0)) ? FAIL : SUCCEED;
1517 : }
1518 :
1519 :
1520 : /**
1521 : * \ingroup dblib_bcp_internal
1522 : * \brief
1523 : *
1524 : * \param dbproc contains all information needed by db-lib to manage communications with the server.
1525 : * \param rows_copied
1526 : *
1527 : * \return SUCCEED or FAIL.
1528 : * \sa BCP_SETL(), bcp_batch(), bcp_bind(), bcp_colfmt(), bcp_colfmt_ps(), bcp_collen(), bcp_colptr(), bcp_columns(), bcp_control(), bcp_done(), bcp_exec(), bcp_getl(), bcp_init(), bcp_moretext(), bcp_options(), bcp_readfmt(), bcp_sendrow()
1529 : */
1530 : static RETCODE
1531 216 : _bcp_exec_in(DBPROCESS *dbproc, DBINT *rows_copied)
1532 : {
1533 216 : FILE *errfile = NULL;
1534 : TDSFILESTREAM hoststream;
1535 216 : TDSSOCKET *tds = dbproc->tds_socket;
1536 : BCP_HOSTCOLINFO *hostcol;
1537 : STATUS ret;
1538 :
1539 : int i, rows_written_so_far;
1540 : TDS_INT row_of_hostfile;
1541 : int row_error_count;
1542 : bool row_error;
1543 : offset_type row_start, row_end;
1544 : offset_type error_row_size;
1545 216 : const size_t chunk_size = 0x20000u;
1546 :
1547 216 : tdsdump_log(TDS_DBG_FUNC, "_bcp_exec_in(%p, %p)\n", dbproc, rows_copied);
1548 : assert(dbproc);
1549 216 : assert(rows_copied);
1550 :
1551 216 : *rows_copied = 0;
1552 :
1553 216 : if (!TDS_SUCCEED(tds_file_stream_init(&hoststream, fopen(dbproc->hostfileinfo->hostfile, "r" TDS_FOPEN_BINARY)))) {
1554 0 : tdsdump_log(TDS_DBG_FUNC, "error: cannot initialize hostfile stream");
1555 0 : dbperror(dbproc, SYBEBCUO, 0);
1556 0 : return FAIL;
1557 : }
1558 :
1559 216 : if (TDS_FAILED(tds_bcp_start_copy_in(tds, dbproc->bcpinfo))) {
1560 0 : tds_file_stream_close(&hoststream);
1561 0 : return FAIL;
1562 : }
1563 :
1564 216 : row_of_hostfile = 0;
1565 216 : rows_written_so_far = 0;
1566 :
1567 216 : row_error_count = 0;
1568 216 : dbproc->bcpinfo->parent = dbproc;
1569 :
1570 : for (;;) {
1571 : bool skip;
1572 :
1573 722 : row_start = tds_file_stream_tell(&hoststream);
1574 722 : row_error = false;
1575 :
1576 722 : row_of_hostfile++;
1577 :
1578 722 : if (dbproc->hostfileinfo->lastrow > 0 && row_of_hostfile > dbproc->hostfileinfo->lastrow)
1579 : break;
1580 :
1581 722 : skip = dbproc->hostfileinfo->firstrow > row_of_hostfile;
1582 722 : ret = _bcp_read_hostfile(dbproc, &hoststream, &row_error, skip);
1583 722 : if (ret != MORE_ROWS)
1584 : break;
1585 :
1586 506 : if (row_error) {
1587 : int count;
1588 :
1589 20 : if (errfile == NULL && dbproc->hostfileinfo->errorfile) {
1590 10 : if (!(errfile = fopen(dbproc->hostfileinfo->errorfile, "w" TDS_FOPEN_BINARY))) {
1591 0 : tds_file_stream_close(&hoststream);
1592 0 : dbperror(dbproc, SYBEBUOE, 0);
1593 0 : return FAIL;
1594 : }
1595 : }
1596 :
1597 20 : if (errfile != NULL) {
1598 : char *row_in_error = NULL;
1599 :
1600 : #ifdef _WIN32
1601 : #define TDS_EOL "\r\n"
1602 : #else
1603 : #define TDS_EOL "\n"
1604 : #endif
1605 :
1606 20 : for (i = 0; i < dbproc->hostfileinfo->host_colcount; i++) {
1607 20 : hostcol = dbproc->hostfileinfo->host_columns[i];
1608 20 : if (hostcol->column_error == HOST_COL_CONV_ERROR) {
1609 20 : count = fprintf(errfile,
1610 : "#@ data conversion error on host data file "
1611 : "Row %d Column %d" TDS_EOL, (int) row_of_hostfile, i + 1);
1612 20 : if (count < 0) {
1613 0 : dbperror(dbproc, SYBEBWEF, errno);
1614 : }
1615 0 : } else if (hostcol->column_error == HOST_COL_NULL_ERROR) {
1616 0 : count = fprintf(errfile, "#@ Attempt to bulk-copy a NULL value into Server column"
1617 : " which does not accept NULL values. Row %d, Column %d" TDS_EOL,
1618 : row_of_hostfile, i + 1);
1619 0 : if (count < 0)
1620 0 : dbperror(dbproc, SYBEBWEF, errno);
1621 : }
1622 : }
1623 :
1624 20 : row_end = tds_file_stream_tell(&hoststream);
1625 :
1626 : /* error data can be very long so split in chunks */
1627 20 : error_row_size = row_end - row_start;
1628 20 : tds_file_stream_seek_set(&hoststream, row_start);
1629 :
1630 60 : while (error_row_size > 0) {
1631 20 : size_t chunk = TDS_MIN((size_t) error_row_size, chunk_size);
1632 : size_t written;
1633 :
1634 20 : if (!row_in_error) {
1635 20 : if ((row_in_error = tds_new(char, chunk)) == NULL) {
1636 0 : dbperror(dbproc, SYBEMEM, errno);
1637 : }
1638 : }
1639 :
1640 20 : if (tds_file_stream_read_raw(&hoststream, row_in_error, chunk) != chunk)
1641 0 : tdsdump_log(TDS_DBG_ERROR, "BILL fread failed after fseek\n");
1642 :
1643 20 : written = fwrite(row_in_error, 1, chunk, errfile);
1644 20 : if (written < chunk)
1645 0 : dbperror(dbproc, SYBEBWEF, errno);
1646 :
1647 20 : error_row_size -= chunk;
1648 : }
1649 20 : free(row_in_error);
1650 :
1651 20 : tds_file_stream_seek_set(&hoststream, row_end);
1652 20 : count = fprintf(errfile, TDS_EOL);
1653 20 : if (count < 0)
1654 0 : dbperror(dbproc, SYBEBWEF, errno);
1655 : }
1656 20 : row_error_count++;
1657 20 : if (row_error_count >= dbproc->hostfileinfo->maxerrs)
1658 : break;
1659 20 : continue;
1660 : }
1661 :
1662 486 : if (skip)
1663 0 : continue;
1664 :
1665 486 : if (dbproc->bcpinfo->dry_run) {
1666 0 : ++rows_written_so_far;
1667 0 : continue;
1668 : }
1669 :
1670 486 : if (TDS_SUCCEED(tds_bcp_send_record(dbproc->tds_socket, dbproc->bcpinfo, _bcp_no_get_col_data, _bcp_null_error, 0))) {
1671 :
1672 486 : rows_written_so_far++;
1673 :
1674 486 : if (dbproc->hostfileinfo->batch > 0 && rows_written_so_far == dbproc->hostfileinfo->batch) {
1675 0 : if (TDS_FAILED(tds_bcp_done(tds, &rows_written_so_far))) {
1676 0 : if (errfile)
1677 0 : fclose(errfile);
1678 0 : tds_file_stream_close(&hoststream);
1679 0 : return FAIL;
1680 : }
1681 :
1682 0 : *rows_copied += rows_written_so_far;
1683 0 : rows_written_so_far = 0;
1684 :
1685 0 : dbperror(dbproc, SYBEBBCI, 0); /* batch copied to server */
1686 :
1687 0 : tds_bcp_start(tds, dbproc->bcpinfo);
1688 : }
1689 : }
1690 : }
1691 :
1692 216 : if (row_error_count == 0 && row_of_hostfile < dbproc->hostfileinfo->firstrow) {
1693 : /* "The BCP hostfile '%1!' contains only %2! rows. */
1694 0 : dbperror(dbproc, SYBEBCSA, 0, dbproc->hostfileinfo->hostfile, row_of_hostfile);
1695 : }
1696 :
1697 216 : if (errfile && 0 != fclose(errfile) ) {
1698 0 : dbperror(dbproc, SYBEBUCE, 0);
1699 : }
1700 :
1701 216 : if (TDS_FAILED(tds_file_stream_close(&hoststream))) {
1702 0 : dbperror(dbproc, SYBEBCUC, 0);
1703 0 : ret = FAIL;
1704 : }
1705 :
1706 216 : if (!dbproc->bcpinfo->dry_run)
1707 216 : tds_bcp_done(tds, &rows_written_so_far);
1708 :
1709 216 : *rows_copied += rows_written_so_far;
1710 :
1711 216 : return ret == NO_MORE_ROWS ? SUCCEED : FAIL; /* (ret is returned from _bcp_read_hostfile) */
1712 : }
1713 :
1714 : /**
1715 : * \ingroup dblib_bcp
1716 : * \brief Write a datafile to a table.
1717 : *
1718 : *
1719 : * \param dbproc contains all information needed by db-lib to manage communications with the server.
1720 : * \param rows_copied bcp_exec will write the count of rows successfully written to this address.
1721 : * If \a rows_copied is NULL, it will be ignored by db-lib.
1722 : *
1723 : * \return SUCCEED or FAIL.
1724 : * \sa bcp_batch(), bcp_bind(), bcp_colfmt(), bcp_collen(), bcp_colptr(), bcp_columns(),
1725 : * bcp_control(), bcp_done(), bcp_init(), bcp_sendrow()
1726 : */
1727 : RETCODE
1728 422 : bcp_exec(DBPROCESS * dbproc, DBINT *rows_copied)
1729 : {
1730 : DBINT dummy_copied;
1731 422 : RETCODE ret = FAIL;
1732 :
1733 422 : tdsdump_log(TDS_DBG_FUNC, "bcp_exec(%p, %p)\n", dbproc, rows_copied);
1734 422 : CHECK_CONN(FAIL);
1735 422 : CHECK_PARAMETER(dbproc->bcpinfo, SYBEBCPI, FAIL);
1736 422 : CHECK_PARAMETER(dbproc->hostfileinfo, SYBEBCVH, FAIL);
1737 :
1738 422 : if (rows_copied == NULL) /* NULL means we should ignore it */
1739 0 : rows_copied = &dummy_copied;
1740 :
1741 422 : if (dbproc->bcpinfo->direction == DB_OUT || dbproc->bcpinfo->direction == DB_QUERYOUT) {
1742 206 : ret = _bcp_exec_out(dbproc, rows_copied);
1743 216 : } else if (dbproc->bcpinfo->direction == DB_IN) {
1744 216 : ret = _bcp_exec_in(dbproc, rows_copied);
1745 : }
1746 422 : _bcp_free_storage(dbproc);
1747 :
1748 422 : return ret;
1749 : }
1750 :
1751 : /**
1752 : * \ingroup dblib_bcp_internal
1753 : * \brief
1754 : *
1755 : * \param buffer
1756 : * \param size
1757 : * \param f
1758 : *
1759 : * \return SUCCEED or FAIL.
1760 : * \sa BCP_SETL(), bcp_batch(), bcp_bind(), bcp_colfmt(), bcp_colfmt_ps(), bcp_collen(), bcp_colptr(), bcp_columns(), bcp_control(), bcp_done(), bcp_exec(), bcp_getl(), bcp_init(), bcp_moretext(), bcp_options(), bcp_readfmt(), bcp_sendrow()
1761 : */
1762 : static char *
1763 280 : _bcp_fgets(char *buffer, int size, FILE *f)
1764 : {
1765 280 : char *p = fgets(buffer, size, f);
1766 280 : if (p == NULL)
1767 : return p;
1768 :
1769 : /* discard newline */
1770 280 : p = strchr(buffer, 0) - 1;
1771 280 : if (p >= buffer && *p == '\n')
1772 280 : *p = 0;
1773 : return buffer;
1774 : }
1775 :
1776 : /**
1777 : * \ingroup dblib_bcp
1778 : * \brief Read a format definition file.
1779 : *
1780 : * \param dbproc contains all information needed by db-lib to manage communications with the server.
1781 : * \param filename Name that will be passed to fopen(3).
1782 : *
1783 : * \remarks Reads a format file and calls bcp_columns() and bcp_colfmt() as needed.
1784 : *
1785 : * \return SUCCEED or FAIL.
1786 : * \sa bcp_colfmt(), bcp_colfmt_ps(), bcp_columns(), bcp_writefmt()
1787 : */
1788 : RETCODE
1789 40 : bcp_readfmt(DBPROCESS * dbproc, const char filename[])
1790 : {
1791 : BCP_HOSTCOLINFO hostcol[1];
1792 : FILE *ffile;
1793 : char buffer[1024];
1794 40 : float lf_version = 0.0;
1795 40 : int li_numcols = 0;
1796 40 : int colinfo_count = 0;
1797 :
1798 40 : tdsdump_log(TDS_DBG_FUNC, "bcp_readfmt(%p, %s)\n", dbproc, filename? filename:"NULL");
1799 40 : CHECK_CONN(FAIL);
1800 40 : CHECK_PARAMETER(dbproc->bcpinfo, SYBEBCPI, FAIL);
1801 40 : CHECK_NULP(filename, "bcp_readfmt", 2, FAIL);
1802 :
1803 40 : memset(hostcol, 0, sizeof(hostcol));
1804 :
1805 40 : if ((ffile = fopen(filename, "r")) == NULL) {
1806 0 : dbperror(dbproc, SYBEBUOF, 0);
1807 0 : goto Cleanup;
1808 : }
1809 :
1810 40 : if ((_bcp_fgets(buffer, sizeof(buffer), ffile)) != NULL) {
1811 40 : lf_version = (float)atof(buffer);
1812 0 : } else if (ferror(ffile)) {
1813 0 : dbperror(dbproc, SYBEBRFF, errno);
1814 0 : goto Cleanup;
1815 : }
1816 :
1817 40 : if ((_bcp_fgets(buffer, sizeof(buffer), ffile)) != NULL) {
1818 40 : li_numcols = atoi(buffer);
1819 0 : } else if (ferror(ffile)) {
1820 0 : dbperror(dbproc, SYBEBRFF, errno);
1821 0 : goto Cleanup;
1822 : }
1823 :
1824 40 : if (li_numcols <= 0)
1825 : goto Cleanup;
1826 :
1827 40 : if (bcp_columns(dbproc, li_numcols) == FAIL)
1828 : goto Cleanup;
1829 :
1830 : do {
1831 200 : memset(hostcol, 0, sizeof(hostcol));
1832 :
1833 200 : if (_bcp_fgets(buffer, sizeof(buffer), ffile) == NULL)
1834 : goto Cleanup;
1835 :
1836 200 : if (!_bcp_readfmt_colinfo(dbproc, buffer, hostcol))
1837 : goto Cleanup;
1838 :
1839 400 : if (bcp_colfmt(dbproc, hostcol->host_column, hostcol->datatype,
1840 : hostcol->prefix_len, hostcol->column_len,
1841 200 : hostcol->terminator, hostcol->term_len, hostcol->tab_colnum) == FAIL) {
1842 : goto Cleanup;
1843 : }
1844 :
1845 200 : TDS_ZERO_FREE(hostcol->terminator);
1846 200 : } while (++colinfo_count < li_numcols);
1847 :
1848 40 : if (ferror(ffile)) {
1849 0 : dbperror(dbproc, SYBEBRFF, errno);
1850 0 : goto Cleanup;
1851 : }
1852 :
1853 40 : if (fclose(ffile) != 0) {
1854 0 : dbperror(dbproc, SYBEBUCF, 0);
1855 : /* even if failure is returned ffile is no more valid */
1856 0 : ffile = NULL;
1857 0 : goto Cleanup;
1858 : }
1859 40 : ffile = NULL;
1860 :
1861 40 : if (colinfo_count != li_numcols)
1862 : goto Cleanup;
1863 :
1864 : return SUCCEED;
1865 :
1866 0 : Cleanup:
1867 0 : TDS_ZERO_FREE(hostcol->terminator);
1868 0 : _bcp_free_columns(dbproc);
1869 0 : if (ffile)
1870 0 : fclose(ffile);
1871 : return FAIL;
1872 : }
1873 :
1874 : /**
1875 : * \ingroup dblib_bcp_internal
1876 : * \brief
1877 : *
1878 : * \param dbproc contains all information needed by db-lib to manage communications with the server.
1879 : * \param buf
1880 : * \param ci
1881 : *
1882 : * \return SUCCEED or FAIL.
1883 : * \sa BCP_SETL(), bcp_batch(), bcp_bind(), bcp_colfmt(), bcp_colfmt_ps(), bcp_collen(), bcp_colptr(), bcp_columns(), bcp_control(), bcp_done(), bcp_exec(), bcp_getl(), bcp_init(), bcp_moretext(), bcp_options(), bcp_readfmt(), bcp_sendrow()
1884 : */
1885 : static int
1886 200 : _bcp_readfmt_colinfo(DBPROCESS * dbproc, char *buf, BCP_HOSTCOLINFO * ci)
1887 : {
1888 : char *tok;
1889 : int whichcol;
1890 : char term[30];
1891 : int i;
1892 : char *lasts;
1893 :
1894 : enum nextcol
1895 : {
1896 : HOST_COLUMN,
1897 : DATATYPE,
1898 : PREFIX_LEN,
1899 : COLUMN_LEN,
1900 : TERMINATOR,
1901 : TAB_COLNUM,
1902 : NO_MORE_COLS
1903 : };
1904 :
1905 200 : assert(dbproc);
1906 200 : assert(buf);
1907 200 : assert(ci);
1908 200 : tdsdump_log(TDS_DBG_FUNC, "_bcp_readfmt_colinfo(%p, %s, %p)\n", dbproc, buf, ci);
1909 :
1910 200 : tok = strtok_r(buf, " \t", &lasts);
1911 200 : whichcol = HOST_COLUMN;
1912 :
1913 : /* TODO use a better way to get an int atoi is very error prone */
1914 1600 : while (tok != NULL && whichcol != NO_MORE_COLS) {
1915 1200 : switch (whichcol) {
1916 :
1917 200 : case HOST_COLUMN:
1918 200 : ci->host_column = atoi(tok);
1919 :
1920 200 : if (ci->host_column < 1) {
1921 0 : dbperror(dbproc, SYBEBIHC, 0);
1922 0 : return (FALSE);
1923 : }
1924 :
1925 : whichcol = DATATYPE;
1926 : break;
1927 :
1928 200 : case DATATYPE:
1929 200 : if (strcmp(tok, "SYBCHAR") == 0)
1930 140 : ci->datatype = SYBCHAR;
1931 60 : else if (strcmp(tok, "SYBTEXT") == 0)
1932 0 : ci->datatype = SYBTEXT;
1933 60 : else if (strcmp(tok, "SYBBINARY") == 0)
1934 20 : ci->datatype = SYBBINARY;
1935 40 : else if (strcmp(tok, "SYBIMAGE") == 0)
1936 0 : ci->datatype = SYBIMAGE;
1937 40 : else if (strcmp(tok, "SYBINT1") == 0)
1938 0 : ci->datatype = SYBINT1;
1939 40 : else if (strcmp(tok, "SYBINT2") == 0)
1940 0 : ci->datatype = SYBINT2;
1941 40 : else if (strcmp(tok, "SYBINT4") == 0)
1942 40 : ci->datatype = SYBINT4;
1943 0 : else if (strcmp(tok, "SYBINT8") == 0)
1944 0 : ci->datatype = SYBINT8;
1945 0 : else if (strcmp(tok, "SYBFLT8") == 0)
1946 0 : ci->datatype = SYBFLT8;
1947 0 : else if (strcmp(tok, "SYBREAL") == 0)
1948 0 : ci->datatype = SYBREAL;
1949 0 : else if (strcmp(tok, "SYBBIT") == 0)
1950 0 : ci->datatype = SYBBIT;
1951 0 : else if (strcmp(tok, "SYBNUMERIC") == 0)
1952 0 : ci->datatype = SYBNUMERIC;
1953 0 : else if (strcmp(tok, "SYBDECIMAL") == 0)
1954 0 : ci->datatype = SYBDECIMAL;
1955 0 : else if (strcmp(tok, "SYBMONEY") == 0)
1956 0 : ci->datatype = SYBMONEY;
1957 0 : else if (strcmp(tok, "SYBMONEY4") == 0)
1958 0 : ci->datatype = SYBMONEY4;
1959 0 : else if (strcmp(tok, "SYBDATETIME") == 0)
1960 0 : ci->datatype = SYBDATETIME;
1961 0 : else if (strcmp(tok, "SYBDATETIME4") == 0)
1962 0 : ci->datatype = SYBDATETIME4;
1963 : /* TODO SQL* for MS
1964 : SQLNCHAR SQLBIGINT SQLTINYINT SQLSMALLINT
1965 : SQLUNIQUEID SQLVARIANT SQLUDT */
1966 : else {
1967 0 : dbperror(dbproc, SYBEBUDF, 0);
1968 0 : return (FALSE);
1969 : }
1970 :
1971 : whichcol = PREFIX_LEN;
1972 : break;
1973 :
1974 200 : case PREFIX_LEN:
1975 200 : ci->prefix_len = atoi(tok);
1976 200 : whichcol = COLUMN_LEN;
1977 200 : break;
1978 200 : case COLUMN_LEN:
1979 200 : ci->column_len = atoi(tok);
1980 200 : whichcol = TERMINATOR;
1981 200 : break;
1982 200 : case TERMINATOR:
1983 :
1984 200 : if (*tok++ != '\"')
1985 : return (FALSE);
1986 :
1987 100 : for (i = 0; *tok != '\"' && i < sizeof(term); i++) {
1988 100 : if (*tok == '\\') {
1989 100 : tok++;
1990 100 : switch (*tok) {
1991 60 : case 't':
1992 60 : term[i] = '\t';
1993 60 : break;
1994 40 : case 'n':
1995 40 : term[i] = '\n';
1996 40 : break;
1997 0 : case 'r':
1998 0 : term[i] = '\r';
1999 0 : break;
2000 0 : case '\\':
2001 0 : term[i] = '\\';
2002 0 : break;
2003 0 : case '0':
2004 0 : term[i] = '\0';
2005 0 : break;
2006 : default:
2007 : return (FALSE);
2008 : }
2009 100 : tok++;
2010 : } else
2011 0 : term[i] = *tok++;
2012 : }
2013 :
2014 200 : if (*tok != '\"')
2015 : return (FALSE);
2016 :
2017 200 : ci->term_len = i;
2018 200 : TDS_ZERO_FREE(ci->terminator);
2019 200 : if (i > 0) {
2020 100 : if ((ci->terminator = tds_new(BYTE, i)) == NULL) {
2021 0 : dbperror(dbproc, SYBEMEM, errno);
2022 0 : return FALSE;
2023 : }
2024 100 : memcpy(ci->terminator, term, i);
2025 : }
2026 :
2027 : whichcol = TAB_COLNUM;
2028 : break;
2029 :
2030 200 : case TAB_COLNUM:
2031 200 : ci->tab_colnum = atoi(tok);
2032 200 : whichcol = NO_MORE_COLS;
2033 200 : break;
2034 :
2035 : }
2036 1200 : tok = strtok_r(NULL, " \t", &lasts);
2037 : }
2038 200 : if (whichcol == NO_MORE_COLS)
2039 : return (TRUE);
2040 : else
2041 0 : return (FALSE);
2042 : }
2043 :
2044 : #if defined(DBLIB_UNIMPLEMENTED)
2045 : /**
2046 : * \ingroup dblib_bcp
2047 : * \brief Write a format definition file. Not Implemented.
2048 : *
2049 : * \param dbproc contains all information needed by db-lib to manage communications with the server.
2050 : * \param filename Name that would be passed to fopen(3).
2051 : *
2052 : * \remarks Reads a format file and calls bcp_columns() and bcp_colfmt() as needed.
2053 : * \a FreeTDS includes freebcp, a utility to copy data to or from a host file.
2054 : *
2055 : * \todo For completeness, \a freebcp ought to be able to create format files, but that functionality
2056 : * is currently lacking, as is bcp_writefmt().
2057 : * \todo See the vendors' documentation for the format of these files.
2058 : *
2059 : * \return SUCCEED or FAIL.
2060 : * \sa bcp_colfmt(), bcp_colfmt_ps(), bcp_columns(), bcp_readfmt()
2061 : */
2062 : RETCODE
2063 : bcp_writefmt(DBPROCESS * dbproc, const char filename[])
2064 : {
2065 : tdsdump_log(TDS_DBG_FUNC, "UNIMPLEMENTED: bcp_writefmt(%p, %s)\n", dbproc, filename? filename:"NULL");
2066 : CHECK_CONN(FAIL);
2067 : CHECK_PARAMETER(dbproc->bcpinfo, SYBEBCPI, FAIL);
2068 : CHECK_NULP(filename, "bcp_writefmt", 2, FAIL);
2069 :
2070 : #if 0
2071 : dbperror(dbproc, SYBEBUFF, errno); /* bcp: Unable to create format file */
2072 : dbperror(dbproc, SYBEBWFF, errno); /* I/O error while writing bcp format file */
2073 : #endif
2074 :
2075 : return FAIL;
2076 : }
2077 :
2078 : /**
2079 : * \ingroup dblib_bcp
2080 : * \brief Write some text or image data to the server. Not implemented, sadly.
2081 : *
2082 : * \param dbproc contains all information needed by db-lib to manage communications with the server.
2083 : * \param size How much to write, in bytes.
2084 : * \param text Address of the data to be written.
2085 : * \remarks For a SYBTEXT or SYBIMAGE column, bcp_bind() can be called with
2086 : * a NULL varaddr parameter. If it is, bcp_sendrow() will return control
2087 : * to the application after the non-text data have been sent. The application then calls
2088 : * bcp_moretext() -- usually in a loop -- to send the text data in manageable chunks.
2089 : * \todo implement bcp_moretext().
2090 : * \return SUCCEED or FAIL.
2091 : * \sa bcp_bind(), bcp_sendrow(), dbmoretext(), dbwritetext()
2092 : */
2093 : RETCODE
2094 : bcp_moretext(DBPROCESS * dbproc, DBINT size, BYTE * text)
2095 : {
2096 : tdsdump_log(TDS_DBG_FUNC, "UNIMPLEMENTED: bcp_moretext(%p, %d, %p)\n", dbproc, size, text);
2097 : CHECK_CONN(FAIL);
2098 : CHECK_PARAMETER(dbproc->bcpinfo, SYBEBCPI, FAIL);
2099 : CHECK_NULP(text, "bcp_moretext", 3, FAIL);
2100 :
2101 : #if 0
2102 : dbperror(dbproc, SYBEBCMTXT, 0);
2103 : /* bcp_moretext may be used only when there is at least one text or image column in the server table */
2104 : dbperror(dbproc, SYBEBTMT, 0);
2105 : /* Attempt to send too much text data via the bcp_moretext call */
2106 : #endif
2107 : return FAIL;
2108 : }
2109 : #endif
2110 :
2111 : /**
2112 : * \ingroup dblib_bcp
2113 : * \brief Commit a set of rows to the table.
2114 : *
2115 : * \param dbproc contains all information needed by db-lib to manage communications with the server.
2116 : * \remarks If not called, bcp_done() will cause the rows to be saved.
2117 : * \return Count of rows saved, or -1 on error.
2118 : * \sa bcp_bind(), bcp_done(), bcp_sendrow()
2119 : */
2120 : DBINT
2121 10 : bcp_batch(DBPROCESS * dbproc)
2122 : {
2123 10 : int rows_copied = 0;
2124 :
2125 10 : tdsdump_log(TDS_DBG_FUNC, "bcp_batch(%p)\n", dbproc);
2126 10 : CHECK_CONN(-1);
2127 10 : CHECK_PARAMETER(dbproc->bcpinfo, SYBEBCPI, -1);
2128 :
2129 10 : if (TDS_FAILED(tds_bcp_done(dbproc->tds_socket, &rows_copied)))
2130 : return -1;
2131 :
2132 10 : tds_bcp_start(dbproc->tds_socket, dbproc->bcpinfo);
2133 :
2134 10 : return rows_copied;
2135 : }
2136 :
2137 : /**
2138 : * \ingroup dblib_bcp
2139 : * \brief Conclude the transfer of data from program variables.
2140 : *
2141 : * \param dbproc contains all information needed by db-lib to manage communications with the server.
2142 : * \remarks Do not overlook this function. According to Sybase, failure to call bcp_done()
2143 : * "will result in unpredictable errors".
2144 : * \return As with bcp_batch(), the count of rows saved, or -1 on error.
2145 : * \sa bcp_batch(), bcp_bind(), bcp_moretext(), bcp_sendrow()
2146 : */
2147 : DBINT
2148 588 : bcp_done(DBPROCESS * dbproc)
2149 : {
2150 : int rows_copied;
2151 :
2152 588 : tdsdump_log(TDS_DBG_FUNC, "bcp_done(%p)\n", dbproc);
2153 588 : CHECK_CONN(-1);
2154 :
2155 588 : if (!(dbproc->bcpinfo))
2156 : return -1;
2157 :
2158 468 : if (TDS_FAILED(tds_bcp_done(dbproc->tds_socket, &rows_copied)))
2159 : return -1;
2160 :
2161 340 : _bcp_free_storage(dbproc);
2162 :
2163 340 : return rows_copied;
2164 : }
2165 :
2166 : /**
2167 : * \ingroup dblib_bcp
2168 : * \brief Bind a program host variable to a database column
2169 : *
2170 : * \param dbproc contains all information needed by db-lib to manage communications with the server.
2171 : * \param varaddr address of host variable
2172 : * \param prefixlen length of any prefix found at the beginning of \a varaddr, in bytes.
2173 : Use zero for fixed-length datatypes.
2174 : * \param varlen bytes of data in \a varaddr. Zero for NULL, -1 for fixed-length datatypes.
2175 : * \param terminator byte sequence that marks the end of the data in \a varaddr
2176 : * \param termlen length of \a terminator
2177 : * \param vartype datatype of the host variable
2178 : * \param table_column Nth column, starting at 1, in the table.
2179 : *
2180 : * \remarks The order of operation is:
2181 : * - bcp_init() with \a hfile == NULL and \a direction == DB_IN.
2182 : * - bcp_bind(), once per column you want to write to
2183 : * - bcp_batch(), optionally, to commit a set of rows
2184 : * - bcp_done()
2185 : * \return SUCCEED or FAIL.
2186 : * \sa bcp_batch(), bcp_colfmt(), bcp_collen(), bcp_colptr(), bcp_columns(), bcp_control(),
2187 : * bcp_done(), bcp_exec(), bcp_moretext(), bcp_sendrow()
2188 : */
2189 : RETCODE
2190 774 : bcp_bind(DBPROCESS * dbproc, BYTE * varaddr, int prefixlen, DBINT varlen,
2191 : BYTE * terminator, int termlen, int db_vartype, int table_column)
2192 : {
2193 : TDS_SERVER_TYPE vartype, vartype_check;
2194 : TDSCOLUMN *colinfo;
2195 :
2196 774 : tdsdump_log(TDS_DBG_FUNC, "bcp_bind(%p, %p, %d, %d -- %p, %d, %s, %d)\n",
2197 : dbproc, varaddr, prefixlen, varlen,
2198 : terminator, termlen, dbprtype(db_vartype), table_column);
2199 774 : CHECK_CONN(FAIL);
2200 774 : CHECK_PARAMETER(dbproc->bcpinfo, SYBEBCPI, FAIL);
2201 1548 : DBPERROR_RETURN(db_vartype != 0 && !is_tds_type_valid(db_vartype), SYBEUDTY);
2202 774 : vartype = (TDS_SERVER_TYPE) db_vartype;
2203 :
2204 774 : if (dbproc->hostfileinfo != NULL) {
2205 0 : dbperror(dbproc, SYBEBCPB, 0);
2206 0 : return FAIL;
2207 : }
2208 :
2209 774 : if (dbproc->bcpinfo->direction != DB_IN) {
2210 0 : dbperror(dbproc, SYBEBCPN, 0);
2211 0 : return FAIL;
2212 : }
2213 :
2214 774 : if (varlen < -1) {
2215 0 : dbperror(dbproc, SYBEBCVLEN, 0);
2216 0 : return FAIL;
2217 : }
2218 :
2219 774 : if (prefixlen != 0 && prefixlen != 1 && prefixlen != 2 && prefixlen != 4) {
2220 0 : dbperror(dbproc, SYBEBCBPREF, 0);
2221 0 : return FAIL;
2222 : }
2223 :
2224 774 : if (table_column <= 0 || table_column > dbproc->bcpinfo->bindinfo->num_cols) {
2225 0 : dbperror(dbproc, SYBECNOR, 0);
2226 0 : return FAIL;
2227 : }
2228 :
2229 774 : if (varaddr == NULL && (prefixlen != 0 || termlen != 0)) {
2230 0 : dbperror(dbproc, SYBEBCBNPR, 0);
2231 0 : return FAIL;
2232 : }
2233 :
2234 774 : colinfo = dbproc->bcpinfo->bindinfo->columns[table_column - 1];
2235 :
2236 : /* type 0 means the program variable has the same type as the column */
2237 774 : vartype_check = vartype;
2238 774 : if (vartype_check == 0)
2239 0 : vartype_check = tds_get_conversion_type(colinfo->column_type, colinfo->column_size);
2240 :
2241 : /*
2242 : * Like MS, a terminator is accepted (and ignored) for types other
2243 : * than character and binary, but, like Sybase, not a NULL one.
2244 : */
2245 774 : if (termlen > 0 && terminator == NULL && !is_char_type(vartype_check) && !is_binary_type(vartype_check)) {
2246 30 : tdsdump_log(TDS_DBG_FUNC, "bcp_bind(): terminator not allowed for type %d\n", vartype_check);
2247 30 : dbperror(dbproc, SYBEBCIT, 0);
2248 30 : return FAIL;
2249 : }
2250 :
2251 : /* A NULL terminator or a non-positive termlen means no terminator. */
2252 744 : if (terminator == NULL || termlen <= 0)
2253 560 : termlen = 0;
2254 :
2255 : /*
2256 : * Character and binary data need a way to know their length.
2257 : * Note that a varlen for fixed types is checked by bcp_sendrow(), as
2258 : * it can be changed by bcp_collen().
2259 : */
2260 744 : if (prefixlen == 0 && varlen == -1 && termlen == 0 && (is_char_type(vartype_check) || is_binary_type(vartype_check))) {
2261 80 : tdsdump_log(TDS_DBG_FUNC, "bcp_bind(): type %d requires prefix, length or terminator\n", vartype_check);
2262 80 : dbperror(dbproc, SYBEVDPT, 0);
2263 80 : return FAIL;
2264 : }
2265 :
2266 : /* If varaddr is NULL and varlen greater than 0, the table column type must be SYBTEXT or SYBIMAGE
2267 : and the program variable type must be SYBTEXT, SYBCHAR, SYBIMAGE or SYBBINARY */
2268 664 : if (varaddr == NULL && varlen > 0) {
2269 0 : int fOK = (colinfo->column_type == SYBTEXT || colinfo->column_type == SYBIMAGE) &&
2270 0 : (vartype == SYBTEXT || vartype == SYBCHAR || vartype == SYBIMAGE || vartype == SYBBINARY );
2271 : if( !fOK ) {
2272 0 : dbperror(dbproc, SYBEBCBNTYP, 0);
2273 0 : tdsdump_log(TDS_DBG_FUNC, "bcp_bind: SYBEBCBNTYP: column=%d and vartype=%d (should fail?)\n",
2274 : colinfo->column_type, vartype);
2275 : /* return FAIL; */
2276 : }
2277 : }
2278 :
2279 664 : colinfo->column_varaddr = (char *)varaddr;
2280 664 : colinfo->column_bindtype = vartype;
2281 664 : colinfo->column_bindlen = varlen;
2282 664 : colinfo->bcp_prefix_len = prefixlen;
2283 :
2284 664 : TDS_ZERO_FREE(colinfo->bcp_terminator);
2285 664 : colinfo->bcp_term_len = 0;
2286 664 : if (termlen > 0) {
2287 184 : if ((colinfo->bcp_terminator = tds_new(TDS_CHAR, termlen)) == NULL) {
2288 0 : dbperror(dbproc, SYBEMEM, errno);
2289 0 : return FAIL;
2290 : }
2291 184 : memcpy(colinfo->bcp_terminator, terminator, termlen);
2292 184 : colinfo->bcp_term_len = termlen;
2293 : }
2294 :
2295 : return SUCCEED;
2296 : }
2297 :
2298 : static void
2299 0 : _bcp_null_error(TDSBCPINFO *bcpinfo, int index TDS_UNUSED, int offset TDS_UNUSED)
2300 : {
2301 0 : DBPROCESS *dbproc = (DBPROCESS *) bcpinfo->parent;
2302 0 : dbperror(dbproc, SYBEBCNN, 0);
2303 0 : }
2304 :
2305 : /**
2306 : * \ingroup dblib_bcp_internal
2307 : * \brief For a bcp in from program variables, get the data from the host variable
2308 : *
2309 : * \param dbproc contains all information needed by db-lib to manage communications with the server.
2310 : * \param bindcol
2311 : *
2312 : * \return TDS_SUCCESS or TDS_FAIL.
2313 : * \sa _bcp_add_fixed_columns, _bcp_add_variable_columns, _bcp_send_bcp_record
2314 : */
2315 : static TDSRET
2316 4488 : _bcp_get_col_data(TDSBCPINFO *bcpinfo, TDSCOLUMN *bindcol, int index TDS_UNUSED, int offset TDS_UNUSED)
2317 : {
2318 : TDS_SERVER_TYPE coltype, desttype;
2319 : int collen;
2320 : int bytes_read;
2321 : BYTE *dataptr;
2322 4488 : DBPROCESS *dbproc = (DBPROCESS *) bcpinfo->parent;
2323 : TDSRET rc;
2324 :
2325 4488 : tdsdump_log(TDS_DBG_FUNC, "_bcp_get_col_data(%p, %p)\n", bcpinfo, bindcol);
2326 4488 : CHECK_CONN(TDS_FAIL);
2327 4488 : CHECK_NULP(bindcol, "_bcp_get_col_data", 2, TDS_FAIL);
2328 :
2329 4488 : dataptr = (BYTE *) bindcol->column_varaddr;
2330 :
2331 4488 : collen = 0;
2332 :
2333 : /* If a prefix length specified, read the correct amount of data. */
2334 :
2335 4488 : if (bindcol->bcp_prefix_len > 0) {
2336 :
2337 90 : switch (bindcol->bcp_prefix_len) {
2338 90 : case 1:
2339 90 : collen = TDS_GET_UA1(dataptr);
2340 90 : dataptr += 1;
2341 90 : break;
2342 0 : case 2:
2343 0 : collen = (TDS_SMALLINT) TDS_GET_UA2(dataptr);
2344 0 : dataptr += 2;
2345 0 : break;
2346 0 : case 4:
2347 0 : collen = (TDS_INT) TDS_GET_UA4(dataptr);
2348 0 : dataptr += 4;
2349 0 : break;
2350 : }
2351 90 : if (collen <= 0)
2352 : goto null_data;
2353 : }
2354 :
2355 4488 : desttype = tds_get_conversion_type(bindcol->column_type, bindcol->column_size);
2356 :
2357 4488 : coltype = bindcol->column_bindtype == 0 ? desttype : (TDS_SERVER_TYPE) bindcol->column_bindtype;
2358 :
2359 : /*
2360 : * If (Max) column length specified take that into consideration.
2361 : * Like MS, for variable types a prefix takes precedence.
2362 : */
2363 4488 : if (bindcol->column_bindlen >= 0) {
2364 2960 : if (bindcol->column_bindlen == 0)
2365 : goto null_data;
2366 1630 : if (!collen)
2367 : collen = bindcol->column_bindlen;
2368 50 : else if (is_fixed_type(coltype))
2369 30 : collen = TDS_MIN(bindcol->column_bindlen, collen);
2370 : }
2371 :
2372 : /* Fixed Length data - this overrides anything else specified */
2373 3158 : if (is_fixed_type(coltype)) {
2374 900 : int fixed_size = tds_get_size_by_type(coltype);
2375 :
2376 : /*
2377 : * Like Sybase, a given length must match the type size.
2378 : * A larger length is accepted only if it came from a prefix.
2379 : */
2380 900 : if (collen > 0 && (collen < fixed_size || (collen > fixed_size && bindcol->bcp_prefix_len <= 0))) {
2381 30 : tdsdump_log(TDS_DBG_FUNC, "_bcp_get_col_data: length %d invalid for fixed type %d\n", collen, coltype);
2382 30 : dbperror(dbproc, SYBEBCIS, 0);
2383 30 : return TDS_FAIL;
2384 : }
2385 : collen = fixed_size;
2386 : }
2387 :
2388 : /* read the data, finally */
2389 :
2390 : /* terminators are used only for character and binary types */
2391 3128 : if (bindcol->bcp_term_len > 0 && (is_char_type(coltype) || is_binary_type(coltype))) { /* terminated field */
2392 168 : bytes_read = _bcp_get_term_var(dataptr, (BYTE *)bindcol->bcp_terminator, bindcol->bcp_term_len);
2393 :
2394 168 : if (collen <= 0 || bytes_read < collen)
2395 158 : collen = bytes_read;
2396 :
2397 168 : if (collen == 0)
2398 : goto null_data;
2399 : }
2400 :
2401 3100 : if (collen < 0)
2402 0 : collen = (int) strlen((char *) dataptr);
2403 :
2404 : /*
2405 : * Like MS, binary data is copied as is to character columns, not
2406 : * converted to hexadecimal. Unicode columns are not changed.
2407 : */
2408 3100 : if (is_binary_type(coltype) && is_ascii_type(desttype))
2409 40 : coltype = SYBCHAR;
2410 :
2411 3100 : rc = _bcp_convert_in(dbproc, coltype, (const TDS_CHAR *) dataptr, collen, desttype, bindcol, NULL);
2412 3100 : if (TDS_FAILED(rc))
2413 : return rc;
2414 3100 : rtrim_bcpcol(bindcol);
2415 :
2416 3100 : return TDS_SUCCESS;
2417 :
2418 1358 : null_data:
2419 1358 : bindcol->bcp_column_data->datalen = 0;
2420 1358 : bindcol->bcp_column_data->is_null = true;
2421 1358 : return TDS_SUCCESS;
2422 : }
2423 :
2424 : /**
2425 : * Function to read data from file. In this case is empty as data
2426 : * are already on bcp_column_data
2427 : */
2428 : static TDSRET
2429 2362 : _bcp_no_get_col_data(TDSBCPINFO *bcpinfo TDS_UNUSED, TDSCOLUMN *bindcol TDS_UNUSED, int index TDS_UNUSED, int offset TDS_UNUSED)
2430 : {
2431 2362 : return TDS_SUCCESS;
2432 : }
2433 :
2434 : /**
2435 : * Get the data for bcp-in from program variables, where the program data
2436 : * have been identified as character terminated,
2437 : * This is a low-level, internal function. Call it correctly.
2438 : */
2439 : /**
2440 : * \ingroup dblib_bcp_internal
2441 : * \brief
2442 : *
2443 : * \param pdata
2444 : * \param term
2445 : * \param term_len
2446 : *
2447 : * \return data length.
2448 : */
2449 : static int
2450 168 : _bcp_get_term_var(const BYTE * pdata, const BYTE * term, int term_len)
2451 : {
2452 : int bufpos;
2453 :
2454 168 : assert(term_len > 0);
2455 :
2456 : /* if bufpos becomes negative, we probably failed to find the terminator */
2457 1130 : for (bufpos = 0; bufpos >= 0 && memcmp(pdata, term, term_len) != 0; pdata++) {
2458 1130 : bufpos++;
2459 : }
2460 :
2461 : assert(bufpos >= 0);
2462 168 : return bufpos;
2463 : }
2464 :
2465 : /**
2466 : * \ingroup dblib_bcp_internal
2467 : * \brief trim a string of trailing blanks
2468 : *
2469 : * Replaces spaces at the end of a string with NULs
2470 : * \param str pointer to a character buffer (not null-terminated)
2471 : * \param len size of the \a str in bytes
2472 : *
2473 : * \return modified length
2474 : */
2475 : static int
2476 : rtrim(char *str, int len)
2477 : {
2478 1472 : char *p = str + len - 1;
2479 :
2480 1976 : while (p > str && *p == ' ') {
2481 504 : *p-- = '\0';
2482 : }
2483 1472 : return (int)(1 + p - str);
2484 : }
2485 :
2486 : static int
2487 : rtrim_u16(uint16_t *str, int len, uint16_t space)
2488 : {
2489 62 : uint16_t *p = str + len / 2 - 1;
2490 :
2491 62 : while (p > str && *p == space) {
2492 0 : *p-- = '\0';
2493 : }
2494 62 : return (int)(1 + p - str) * 2;
2495 : }
2496 :
2497 : /**
2498 : * \ingroup dblib_bcp_internal
2499 : * \brief
2500 : *
2501 : * \param dbproc contains all information needed by db-lib to manage communications with the server.
2502 : */
2503 : static void
2504 1256 : _bcp_free_columns(DBPROCESS * dbproc)
2505 : {
2506 : int i;
2507 :
2508 1256 : tdsdump_log(TDS_DBG_FUNC, "_bcp_free_columns(%p)\n", dbproc);
2509 1256 : assert(dbproc && dbproc->hostfileinfo);
2510 :
2511 1256 : if (dbproc->hostfileinfo->host_columns) {
2512 4198 : for (i = 0; i < dbproc->hostfileinfo->host_colcount; i++) {
2513 4198 : TDS_ZERO_FREE(dbproc->hostfileinfo->host_columns[i]->terminator);
2514 4198 : TDS_ZERO_FREE(dbproc->hostfileinfo->host_columns[i]);
2515 : }
2516 834 : TDS_ZERO_FREE(dbproc->hostfileinfo->host_columns);
2517 834 : dbproc->hostfileinfo->host_colcount = 0;
2518 : }
2519 1256 : }
2520 :
2521 : /**
2522 : * \ingroup dblib_bcp_internal
2523 : * \brief
2524 : *
2525 : * \param dbproc contains all information needed by db-lib to manage communications with the server.
2526 : *
2527 : * \sa bcp_done(), bcp_exec(), bcp_init()
2528 : */
2529 : static void
2530 1652 : _bcp_free_storage(DBPROCESS * dbproc)
2531 : {
2532 1652 : tdsdump_log(TDS_DBG_FUNC, "_bcp_free_storage(%p)\n", dbproc);
2533 1652 : assert(dbproc);
2534 :
2535 1652 : if (dbproc->hostfileinfo) {
2536 422 : TDS_ZERO_FREE(dbproc->hostfileinfo->hostfile);
2537 422 : TDS_ZERO_FREE(dbproc->hostfileinfo->errorfile);
2538 422 : _bcp_free_columns(dbproc);
2539 422 : TDS_ZERO_FREE(dbproc->hostfileinfo);
2540 : }
2541 :
2542 1652 : tds_free_bcpinfo(dbproc->bcpinfo);
2543 1652 : dbproc->bcpinfo = NULL;
2544 1652 : }
2545 :
2546 : /** Fast strftime for default bcp format */
2547 : static int
2548 80 : _bcp_strftime(char *buf, size_t maxsize, const char *format, const TDSDATEREC *dr, int prec)
2549 : {
2550 80 : char *pbuf = buf;
2551 :
2552 80 : if (format)
2553 0 : return (int) tds_strftime(pbuf, maxsize, format, dr, prec);
2554 :
2555 80 : pbuf += tds_u32toa_fast(pbuf, dr->year);
2556 :
2557 : /* The following "& 63" are to avoid overflows if values are corrupted */
2558 :
2559 80 : *pbuf++ = '-';
2560 80 : tds_02d_fast(pbuf, (dr->month + 1) & 63);
2561 80 : pbuf += 2;
2562 :
2563 80 : *pbuf++ = '-';
2564 80 : tds_02d_fast(pbuf, dr->day & 63);
2565 80 : pbuf += 2;
2566 :
2567 80 : *pbuf++ = ' ';
2568 80 : tds_02d_fast(pbuf, dr->hour & 63);
2569 80 : pbuf += 2;
2570 :
2571 80 : *pbuf++ = ':';
2572 80 : tds_02d_fast(pbuf, dr->minute & 63);
2573 80 : pbuf += 2;
2574 :
2575 80 : *pbuf++ = ':';
2576 80 : tds_02d_fast(pbuf, dr->second & 63);
2577 80 : pbuf += 2;
2578 :
2579 80 : if (prec > 0) {
2580 : char ibuf[10];
2581 :
2582 80 : *pbuf++ = '.';
2583 :
2584 80 : memset(ibuf, '0', sizeof(ibuf));
2585 : /* Mask off a negative sign (input should not contain this anyway) */
2586 80 : tds_u32toa_fast_right(ibuf, dr->decimicrosecond & 0x7FFFFFFF);
2587 : /* Skip first 3 digits here, as decimicrosecond should not exceed 9,999,999 */
2588 80 : memcpy(pbuf, ibuf + 3, prec);
2589 80 : pbuf += prec;
2590 : }
2591 80 : *pbuf = '\0';
2592 :
2593 : #if ENABLE_EXTRA_CHECKS
2594 : {
2595 : char tbuf[256];
2596 :
2597 80 : tds_strftime(tbuf, sizeof(tbuf), BCP_DEFAULT_DATEFMT, dr, prec);
2598 80 : if (strcmp(tbuf, (char *) buf)) {
2599 0 : fprintf(stderr, "_bcp_strftime(%s) does not match tds_strftime(%s)\n", tbuf, (char *) buf);
2600 0 : tds_extra_assert(!"_bcp_strftime mismatch");
2601 : }
2602 : }
2603 : #endif
2604 80 : return (int) (pbuf - buf);
2605 : }
|