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