Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtp (Exim 4.80) (envelope-from ) id 1WFqWJ-0002qR-QM for pgsql-odbc@arkaria.postgresql.org; Tue, 18 Feb 2014 19:39:56 +0000 Received: from localhost ([127.0.0.1] helo=postgresql.org) by malur.postgresql.org with smtp (Exim 4.80) (envelope-from ) id 1WFqWI-0004M9-Uv for pgsql-odbc@arkaria.postgresql.org; Tue, 18 Feb 2014 19:39:55 +0000 Received: from magus.postgresql.org ([2a02:c0:301:0:ffff::29]) by malur.postgresql.org with esmtp (Exim 4.80) (envelope-from ) id 1WFqWH-0004Kg-Gq for pgsql-odbc@postgresql.org; Tue, 18 Feb 2014 19:39:53 +0000 Received: from moutng.kundenserver.de ([212.227.17.9]) by magus.postgresql.org with esmtp (Exim 4.80) (envelope-from ) id 1WFqWD-0000j9-C9 for pgsql-odbc@postgresql.org; Tue, 18 Feb 2014 19:39:53 +0000 Received: from Endor (mail.luratech.com [212.202.239.23]) by mrelayeu.kundenserver.de (node=mreue103) with ESMTP (Nemesis) id 0MQLgi-1WjaE30F0m-00To37; Tue, 18 Feb 2014 20:39:47 +0100 From: =?utf-8?Q?Nils_G=C3=B6sche?= To: "'Heikki Linnakangas'" Cc: References: <006a01cf28e4$7c425450$74c6fcf0$@de> <003201cf2ccb$c5d6ddd0$51849970$@de> <5303960F.3050706@vmware.com> In-Reply-To: <5303960F.3050706@vmware.com> Subject: Re: Null Characters in Strings, Version 9.3.1 Date: Tue, 18 Feb 2014 20:39:46 +0100 Message-ID: <003b01cf2ce1$2e33bc80$8a9b3580$@de> MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="----=_NextPart_000_003C_01CF2CE9.8FF82480" X-Mailer: Microsoft Office Outlook 12.0 Thread-Index: Ac8szZBsbBAyGpfXS5iHSWE860nAXgAEXuKA Content-Language: de X-Provags-ID: V02:K0:9gOhyNtIKr2u0ljnamCSIHrmoSV/GxM4rEjXS3P7Mcl 5A6gISDoc82V2QcShkttFBMrRLdg6VCe97blKmoPvnC3Go97vq AhRHakgff9F5qwZialLCS1hSradPZ09teRdn+tyaAlgdSexA78 I3TvNgFnWAJeZC0oO816CjLGGMJzx/38JdUEDM3zihFB7Kht42 QY5DbsoD7I/FaLa6PRGfHTUViY5EKx+2cEwU9A97jRCISaCivC ZPn6i75U1NyjsexCppZ5cQIdha8fxhPJFIf40X3WgXFs9uU6J+ W3AP56HSTI9s4lI53i2qrONx5hrme7n3UFyVBo1C3pNzH3XCSO Tgtb2Z/p8EPzuKxetL5g= X-Pg-Spam-Score: -1.9 (-) List-Archive: List-Help: List-ID: List-Owner: List-Post: List-Subscribe: List-Unsubscribe: X-Mailing-List: pgsql-odbc Precedence: bulk Sender: pgsql-odbc-owner@postgresql.org This is a multi-part message in MIME format. ------=_NextPart_000_003C_01CF2CE9.8FF82480 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Heikki wrote: > On 02/18/2014 07:06 PM, Nils G=C3=B6sche wrote: > > I wrote: > > > >> If I retrieve the value in a C# program using the ODBC driver, I get > >> a string that has a null character at position 459, but a total > >> length of 487! The string up to position 458 is correct, but has > now > >> been extended with a null character and a few junk characters. > > > > Am I the only one thinking this is a serious bug? >=20 > Maybe.. I don't have a C# environment to test this with; if you can > write a small stand-alone C program to reproduce this and post it, I'll > take a look. Thanks! I have never written an ODBC program in C before. Wow, what a PITA.= .. ;-). I took a little example program from Microsoft's site and adapted = it. The code is attached. The essential point is at line 353: if (wcslen(pThisBinding->wszBuffer) * sizeof(wchar_t) !=3D pThisBinding= ->indPtr) { wprintf(L"2 * wcslen =3D %d, indPtr =3D %d\n", wcslen(pThisBinding-= >wszBuffer) * sizeof(wchar_t), pThisBinding->indPtr); } else { wprintf(pThisBinding->fChar ? DISPLAY_FORMAT_C:DISPLAY_FORMAT, PIPE, pThisBinding->cDisplaySize, pThisBinding->cDisplaySize, pThisBinding->wszBuffer); } If I run this with version 9.2.1 of the driver (I am using 32 Bit here), it= will go to the else clause and print the value of the text column. However= , if I run this with the latest version, I get the following output: Connected! Enter SQL commands, type (control)Z to exit SQL COMMAND>| body | 2 * wcslen =3D 918, indPtr =3D 974 | SQL COMMAND> Disconnected. (indPtr is what we got in the last parameter of SQLBindCol) The numeric values here are consistent with the result I am getting in the = C# program: There is a null character at character index 459, but the retur= ned value is actually larger than that (974 bytes), resulting in a C# strin= g with 487 characters! Regards, --=20 Nils G=C3=B6sche "Don't ask for whom the tolls." ------=_NextPart_000_003C_01CF2CE9.8FF82480 Content-Type: text/plain; name="CODBCHello.cpp" Content-Transfer-Encoding: quoted-printable Content-Disposition: attachment; filename="CODBCHello.cpp" /**************************************************************************= ***** /* ODBCSQL: a sample program that implements an ODBC command line interpret= er. /* /* USAGE: ODBCSQL DSN=3D or /* ODBCSQL FILEDSN=3D or /* ODBCSQL DRIVER=3D{driver name} /* /* /* Copyright(c) Microsoft Corporation. This is a WDAC sample program and /* is not suitable for use in production environments.=20=20=20 /* /**************************************************************************= ****/ /* Modules: /* Main Main driver loop, executes queries. /* DisplayResults Display the results of the query if any /* AllocateBindings Bind column data /* DisplayTitles Print column titles /* SetConsole Set console display mode /* HandleError Show ODBC error messages /**************************************************************************= ****/ #include #include #include #include #include #include #include #include /*******************************************/ /* Macro to call ODBC functions and */ /* report an error on failure. */ /* Takes handle, handle type, and stmt */ /*******************************************/ #define TRYODBC(h, ht, x) { RETCODE rc =3D x;\ if (rc !=3D SQL_SUCCESS) \ { \ HandleDiagnosticRecord (h, ht, rc); \ } \ if (rc =3D=3D SQL_ERROR) \ { \ fwprintf(stderr, L"Error in " L#x L"\n"= ); \ goto Exit; \ } \ } /******************************************/ /* Structure to store information about */ /* a column. /******************************************/ typedef struct STR_BINDING { SQLSMALLINT cDisplaySize; /* size to display */ WCHAR *wszBuffer; /* display buffer */ SQLLEN indPtr; /* size or null */ BOOL fChar; /* character col? */ struct STR_BINDING *sNext; /* linked list */ } BINDING; /******************************************/ /* Forward references */ /******************************************/ void HandleDiagnosticRecord (SQLHANDLE hHandle,=20=20=20=20 SQLSMALLINT hType,=20=20 RETCODE RetCode); void DisplayResults(HSTMT hStmt, SQLSMALLINT cCols); void AllocateBindings(HSTMT hStmt, SQLSMALLINT cCols, BINDING** ppBinding, SQLSMALLINT* pDisplay); void DisplayTitles(HSTMT hStmt, DWORD cDisplaySize, BINDING* pBinding); void SetConsole(DWORD cDisplaySize, BOOL fInvert); /*****************************************/ /* Some constants */ /*****************************************/ #if 0 # define DISPLAY_MAX 50 // Arbitrary limit on column width to disp= lay #else # define DISPLAY_MAX 8192 // Arbitrary limit on column width to di= splay #endif #define DISPLAY_FORMAT_EXTRA 3 // Per column extra display bytes (| = ) #define DISPLAY_FORMAT L"%c %*.*s " #define DISPLAY_FORMAT_C L"%c %-*.*s " #define NULL_SIZE 6 // #define SQL_QUERY_SIZE 1000 // Max. Num characters for SQL Query passe= d in. #define PIPE L'|' SHORT gHeight =3D 80; // Users screen height int __cdecl wmain(int argc, WCHAR **argv) { SQLHENV hEnv =3D NULL; SQLHDBC hDbc =3D NULL; SQLHSTMT hStmt =3D NULL; WCHAR* pwszConnStr; WCHAR wszInput[SQL_QUERY_SIZE]; // Allocate an environment if (SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &hEnv) =3D=3D SQL_E= RROR) { fwprintf(stderr, L"Unable to allocate an environment handle\n"); exit(-1); } // Register this as an application that expects 3.x behavior, // you must register something if you use AllocHandle TRYODBC(hEnv, SQL_HANDLE_ENV, SQLSetEnvAttr(hEnv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, 0)); // Allocate a connection TRYODBC(hEnv, SQL_HANDLE_ENV, SQLAllocHandle(SQL_HANDLE_DBC, hEnv, &hDbc)); if (argc > 1) { pwszConnStr =3D *++argv; }=20 else { pwszConnStr =3D L""; } // Connect to the driver. Use the connection string if supplied // on the input, otherwise let the driver manager prompt for input. TRYODBC(hDbc, SQL_HANDLE_DBC, SQLDriverConnect(hDbc, GetDesktopWindow(), pwszConnStr, SQL_NTS, NULL, 0, NULL, SQL_DRIVER_COMPLETE)); fwprintf(stderr, L"Connected!\n"); TRYODBC(hDbc, SQL_HANDLE_DBC, SQLAllocHandle(SQL_HANDLE_STMT, hDbc, &hStmt)); wprintf(L"Enter SQL commands, type (control)Z to exit\nSQL COMMAND>"); // Loop to get input and execute queries #if 0 while(_fgetts(wszInput, SQL_QUERY_SIZE-1, stdin)) #else wcscpy(wszInput, L"SELECT body FROM macros WHERE name =3D 'check_pruefziff= er'"); #endif { RETCODE RetCode; SQLSMALLINT sNumResults; // Execute the query if (!(*wszInput)) { wprintf(L"SQL COMMAND>"); #if 0 continue; #else goto Exit; #endif } RetCode =3D SQLExecDirect(hStmt,wszInput, SQL_NTS); switch(RetCode) { case SQL_SUCCESS_WITH_INFO: { HandleDiagnosticRecord(hStmt, SQL_HANDLE_STMT, RetCode); // fall through } case SQL_SUCCESS: { // If this is a row-returning query, display // results TRYODBC(hStmt, SQL_HANDLE_STMT, SQLNumResultCols(hStmt,&sNumResults)); if (sNumResults > 0) { DisplayResults(hStmt,sNumResults); }=20 else { SQLLEN cRowCount; TRYODBC(hStmt, SQL_HANDLE_STMT, SQLRowCount(hStmt,&cRowCount)); if (cRowCount >=3D 0) { wprintf(L"%Id %s affected\n", cRowCount, cRowCount =3D=3D 1 ? L"row" : L"rows"); } } break; } case SQL_ERROR: { HandleDiagnosticRecord(hStmt, SQL_HANDLE_STMT, RetCode); break; } default: fwprintf(stderr, L"Unexpected return code %hd!\n", RetCode); } TRYODBC(hStmt, SQL_HANDLE_STMT, SQLFreeStmt(hStmt, SQL_CLOSE)); wprintf(L"SQL COMMAND>"); } Exit: // Free ODBC handles and exit if (hStmt) { SQLFreeHandle(SQL_HANDLE_STMT, hStmt); } if (hDbc) { SQLDisconnect(hDbc); SQLFreeHandle(SQL_HANDLE_DBC, hDbc); } if (hEnv) { SQLFreeHandle(SQL_HANDLE_ENV, hEnv); } wprintf(L"\nDisconnected."); wprintf(L"\nPress any key to exit..."); _getch(); return 0; } /************************************************************************ /* DisplayResults: display results of a select query /* /* Parameters: /* hStmt ODBC statement handle /* cCols Count of columns /************************************************************************/ void DisplayResults(HSTMT hStmt, SQLSMALLINT cCols) { BINDING *pFirstBinding, *pThisBinding;=20=20=20=20=20=20=20=20= =20=20 SQLSMALLINT cDisplaySize; RETCODE RetCode =3D SQL_SUCCESS; int iCount =3D 0; // Allocate memory for each column=20 AllocateBindings(hStmt, cCols, &pFirstBinding, &cDisplaySize); // Set the display mode and write the titles DisplayTitles(hStmt, cDisplaySize+1, pFirstBinding); // Fetch and display the data bool fNoData =3D false; do { // Fetch a row if (iCount++ >=3D gHeight - 2) { int nInputChar; bool fEnterReceived =3D false; while(!fEnterReceived) {=20=20=20 wprintf(L" "); SetConsole(cDisplaySize+2, TRUE); wprintf(L" Press ENTER to continue, Q to quit (height:%hd= )", gHeight); SetConsole(cDisplaySize+2, FALSE); nInputChar =3D _getch(); wprintf(L"\n"); if ((nInputChar =3D=3D 'Q') || (nInputChar =3D=3D 'q')) { goto Exit; } else if ('\r' =3D=3D nInputChar) { fEnterReceived =3D true; } // else loop back to display prompt again } iCount =3D 1; DisplayTitles(hStmt, cDisplaySize+1, pFirstBinding); } TRYODBC(hStmt, SQL_HANDLE_STMT, RetCode =3D SQLFetch(hStmt)); if (RetCode =3D=3D SQL_NO_DATA_FOUND) { fNoData =3D true; } else { // Display the data. Ignore truncations for (pThisBinding =3D pFirstBinding; pThisBinding; pThisBinding =3D pThisBinding->sNext) { if (pThisBinding->indPtr !=3D SQL_NULL_DATA) { if (wcslen(pThisBinding->wszBuffer) * sizeof(wchar_t) !=3D pThisBindin= g->indPtr) { wprintf(L"2 * wcslen =3D %d, indPtr =3D %d\n", wcslen(pThisBinding->w= szBuffer) * sizeof(wchar_t), pThisBinding->indPtr); } else { wprintf(pThisBinding->fChar ? DISPLAY_FORMAT_C:DISPLAY= _FORMAT, PIPE, pThisBinding->cDisplaySize, pThisBinding->cDisplaySize, pThisBinding->wszBuffer); } }=20 else { wprintf(DISPLAY_FORMAT_C, PIPE, pThisBinding->cDisplaySize, pThisBinding->cDisplaySize, L""); } } wprintf(L" %c\n",PIPE); } } while (!fNoData); SetConsole(cDisplaySize+2, TRUE); wprintf(L"%*.*s", cDisplaySize+2, cDisplaySize+2, L" "); SetConsole(cDisplaySize+2, FALSE); wprintf(L"\n"); Exit: // Clean up the allocated buffers while (pFirstBinding) { pThisBinding =3D pFirstBinding->sNext; free(pFirstBinding->wszBuffer); free(pFirstBinding); pFirstBinding =3D pThisBinding; } } /************************************************************************ /* AllocateBindings: Get column information and allocate bindings /* for each column.=20=20 /* /* Parameters: /* hStmt Statement handle /* cCols Number of columns in the result set /* *lppBinding Binding pointer (returned) /* lpDisplay Display size of one line /************************************************************************/ void AllocateBindings(HSTMT hStmt, SQLSMALLINT cCols, BINDING **ppBinding, SQLSMALLINT *pDisplay) { SQLSMALLINT iCol; BINDING *pThisBinding, *pLastBinding =3D NULL; SQLLEN cchDisplay, ssType; SQLSMALLINT cchColumnNameLength; *pDisplay =3D 0; for (iCol =3D 1; iCol <=3D cCols; iCol++) { pThisBinding =3D (BINDING *)(malloc(sizeof(BINDING))); if (!(pThisBinding)) { fwprintf(stderr, L"Out of memory!\n"); exit(-100); } if (iCol =3D=3D 1) { *ppBinding =3D pThisBinding; } else { pLastBinding->sNext =3D pThisBinding; } pLastBinding =3D pThisBinding; // Figure out the display length of the column (we will // bind to char since we are only displaying data, in general // you should bind to the appropriate C type if you are going // to manipulate data since it is much faster...) TRYODBC(hStmt, SQL_HANDLE_STMT, SQLColAttribute(hStmt, iCol, SQL_DESC_DISPLAY_SIZE, NULL, 0, NULL, &cchDisplay)); // Figure out if this is a character or numeric column; this is // used to determine if we want to display the data left- or right- // aligned. // SQL_DESC_CONCISE_TYPE maps to the 1.x SQL_COLUMN_TYPE.=20 // This is what you must use if you want to work // against a 2.x driver. TRYODBC(hStmt, SQL_HANDLE_STMT, SQLColAttribute(hStmt, iCol, SQL_DESC_CONCISE_TYPE, NULL, 0, NULL, &ssType)); pThisBinding->fChar =3D (ssType =3D=3D SQL_CHAR || ssType =3D=3D SQL_VARCHAR || ssType =3D=3D SQL_LONGVARCHAR); pThisBinding->sNext =3D NULL; // Arbitrary limit on display size if (cchDisplay > DISPLAY_MAX) cchDisplay =3D DISPLAY_MAX; // Allocate a buffer big enough to hold the text representation // of the data. Add one character for the null terminator pThisBinding->wszBuffer =3D (WCHAR *)malloc((cchDisplay+1) * sizeof= (WCHAR)); if (!(pThisBinding->wszBuffer)) { fwprintf(stderr, L"Out of memory!\n"); exit(-100); } // Map this buffer to the driver's buffer. At Fetch time, // the driver will fill in this data. Note that the size is=20 // count of bytes (for Unicode). All ODBC functions that take // SQLPOINTER use count of bytes; all functions that take only // strings use count of characters. TRYODBC(hStmt, SQL_HANDLE_STMT, SQLBindCol(hStmt, iCol, SQL_C_TCHAR, (SQLPOINTER) pThisBinding->wszBuffer, (cchDisplay + 1) * sizeof(WCHAR), &pThisBinding->indPtr)); // Now set the display size that we will use to display // the data. Figure out the length of the column name TRYODBC(hStmt, SQL_HANDLE_STMT, SQLColAttribute(hStmt, iCol, SQL_DESC_NAME, NULL, 0, &cchColumnNameLength, NULL)); pThisBinding->cDisplaySize =3D max((SQLSMALLINT)cchDisplay, cchColu= mnNameLength); if (pThisBinding->cDisplaySize < NULL_SIZE) pThisBinding->cDisplaySize =3D NULL_SIZE; *pDisplay +=3D pThisBinding->cDisplaySize + DISPLAY_FORMAT_EXTRA; } return; Exit: exit(-1); return; } /************************************************************************ /* DisplayTitles: print the titles of all the columns and set the=20 /* shell window's width /* /* Parameters: /* hStmt Statement handle /* cDisplaySize Total display size /* pBinding list of binding information /************************************************************************/ void DisplayTitles(HSTMT hStmt, DWORD cDisplaySize, BINDING *pBinding) { WCHAR wszTitle[DISPLAY_MAX]; SQLSMALLINT iCol =3D 1; SetConsole(cDisplaySize+2, TRUE); for (; pBinding; pBinding =3D pBinding->sNext) { TRYODBC(hStmt, SQL_HANDLE_STMT, SQLColAttribute(hStmt, iCol++, SQL_DESC_NAME, wszTitle, sizeof(wszTitle), // Note count of bytes! NULL, NULL)); wprintf(DISPLAY_FORMAT_C, PIPE, pBinding->cDisplaySize, pBinding->cDisplaySize, wszTitle); } Exit: wprintf(L" %c", PIPE); SetConsole(cDisplaySize+2, FALSE); wprintf(L"\n"); } /************************************************************************ /* SetConsole: sets console display size and video mode /* /* Parameters /* siDisplaySize Console display size /* fInvert Invert video? /************************************************************************/ void SetConsole(DWORD dwDisplaySize, BOOL fInvert) { HANDLE hConsole; CONSOLE_SCREEN_BUFFER_INFO csbInfo; // Reset the console screen buffer size if necessary hConsole =3D GetStdHandle(STD_OUTPUT_HANDLE); if (hConsole !=3D INVALID_HANDLE_VALUE) { if (GetConsoleScreenBufferInfo(hConsole, &csbInfo)) { if (csbInfo.dwSize.X < (SHORT) dwDisplaySize) { csbInfo.dwSize.X =3D (SHORT) dwDisplaySize; SetConsoleScreenBufferSize(hConsole, csbInfo.dwSize); } gHeight =3D csbInfo.dwSize.Y; } if (fInvert) { SetConsoleTextAttribute(hConsole, (WORD)(csbInfo.wAttributes | = BACKGROUND_BLUE)); } else { SetConsoleTextAttribute(hConsole, (WORD)(csbInfo.wAttributes & = ~(BACKGROUND_BLUE))); } } } /************************************************************************ /* HandleDiagnosticRecord : display error/warning information /* /* Parameters: /* hHandle ODBC handle /* hType Type of handle (HANDLE_STMT, HANDLE_ENV, HANDLE_DBC) /* RetCode Return code of failing command /************************************************************************/ void HandleDiagnosticRecord (SQLHANDLE hHandle,=20=20=20=20 SQLSMALLINT hType,=20=20 RETCODE RetCode) { SQLSMALLINT iRec =3D 0; SQLINTEGER iError; WCHAR wszMessage[1000]; WCHAR wszState[SQL_SQLSTATE_SIZE+1]; if (RetCode =3D=3D SQL_INVALID_HANDLE) { fwprintf(stderr, L"Invalid handle!\n"); return; } while (SQLGetDiagRec(hType, hHandle, ++iRec, wszState, &iError, wszMessage, (SQLSMALLINT)(sizeof(wszMessage) / sizeof(WCHAR)), (SQLSMALLINT *)NULL) =3D=3D SQL_SUCCESS) { // Hide data truncated.. if (wcsncmp(wszState, L"01004", 5)) { fwprintf(stderr, L"[%5.5s] %s (%d)\n", wszState, wszMessage, iE= rror); } } } ------=_NextPart_000_003C_01CF2CE9.8FF82480 Content-Type: text/plain Content-Disposition: inline Content-Transfer-Encoding: 8bit MIME-Version: 1.0 -- Sent via pgsql-odbc mailing list (pgsql-odbc@postgresql.org) To make changes to your subscription: http://www.postgresql.org/mailpref/pgsql-odbc ------=_NextPart_000_003C_01CF2CE9.8FF82480--