How to connect to postgresql in a multithreaded C application - sql

I have a few threads in my application. Each has its own PGconn* connection that is individually opened with the same connection string. When a thread makes a query, it almost never returns PGRES_TUPLES_OK.
I can provide some code examples if necessary, but does anything stand out here? I have tried using global mutexes as well, to no avail. I am using postgresql 9.3
PQerrorMessage(db) returns: connection pointer is NULL
From the postgresql documentation:
If a null pointer is returned, it should be treated like a PGRES_FATAL_ERROR result. Use PQerrorMessage to get more information about the error.

Ok, I figured it out.
I was using a function to open each connection, and was passing a pointer to a PGconn struct to it.
I needed to pass a double pointer.

Related

Can the delete operator be used instead of the Marshal.FreeHGlobal method to free memory from a wchar_t*?

I read the official documentation for the StringToHGlobalUni method and it says that the FreeHGlobal method should be use to free memory.
The memory allocated by StringToHGlobalUni method is on the native heap, so I don't see why the delete operator could not be used.
I searched a lot, but I couldn't find any explanation why I can't use the delete operator.
I'm new to this and some explanations would help me. Can the delete operator be used or not ?
Code
const wchar_t* filePath = (const wchar_t*)(Marshal::StringToHGlobalUni(inputFilePath)).ToPointer();
Marshal::FreeHGlobal(IntPtr((void*)filePath));
Don't use Marshal::StringToHGlobalUni in C++/CLI.
Use either
PtrToStringChars (accesses Unicode characters in-place, no allocation) or
marshal_as<std::wstring> (manages the allocation with a smart pointer class that will free it correctly and automatically)
Apart from the fact that StringToHGlobalUni requires you to free the memory manually, the name of that function is completely misleading. It has absolutely no connection to HGLOBAL whatsoever.

Why does defining a variable of type of Smo.Server cause a 10 second delay

Bear with me here, ok!!
We use SMO a lot to do all kinds of things, including to check for the presence of particular stored procedures in the database. So we have a method in our data access class called HasProc, which returns a boolean. It's in a part of the application that hasn't been changed for over a year, possibly two years.
Lately, it's been taking ages (10s) to return a value, and I've been trying to pin down why.
It turns out that even defining the variable that will hold the SMO Server (not instantiating it, just defining it) causes a 10s delay in the code arriving into the function.
Here's the relevant bit of the code, which just returns True now, for clarity:
Public Function HasProc(ByVal storedProcName As String) As Boolean
Dim s As Microsoft.SqlServer.Management.Smo.Server
Return True
End Function
In Visual Studio 12, stepping through the code using F11, the 10 second delay happens before the code highlight arrives at Public Function etc...
If I comment out the Dim statement, it all runs instantly.
Even more weirdly, if I disable my ethernet adaptor, the delay does not occur.
This is reproducible across three computers. I'm using VS2012, and SMO v11, to which we recently upgraded in order to support SQL Server 2012.
The other thing is that the delay happens even if the Return True statement is before, rather than after the Dim statement.
Any ideas?
This would happen if the static initializer for that class performs network IO (which is generally a bad idea).
If you pause the debugger during the delay, you can find out exactly what it's doing.

Handle declarations

Can anyone tell me what the difference is between these 2 lines of code, which one is better to use?
System::String ^MyStr = gcnew System::String(MyStr);
System::String ^MyStr;
Those lines are not equivalent. In the first one, you will get an exception beacuse you're trying to create a String from an uninitialized tracking handle (MyStr). In the second one, MyStr is declared, not defined, it points to garbage and will throw an exception if you attempt to use it. Which one you should use depends on the rest of the code
The second one creates a new handle variable. If it's a local variable, then as #dario_ramos says, it's uninitialized, and your program will likely crash if you try to use the handle before assigning it. If it's a member variable or global, then it will be nullptr.
The first one is similar, although it can only be used for locals or globals (member variables use the ctor-initializer syntax in C++/CLI just like plain C++), and does exactly what you're not permitted to do. It reads the brand new uninitialized handle and passes it to the System::String constructor. If by chance the constructor finishes, a handle to the newly constructed String will be placed into the variable as part of initialization. But because the constructor is trying to make a copy of random garbage (if it's a local) or nullptr (if a global), most likely it will simply crash.
It's a bad idea to use the value of any variable in its own initializer (sometimes you need to use the address, never the value).

Tracking down the source of E_POINTER in IMFMediaSource::ReadSample

I'm getting an E_POINTER error from the ReadSample call, and as far as I can tell, none of the pointers are invalid. See snippet below (note, it's a C++/CLI app):
IMFSample* sample = NULL;
pin_ptr<IMFSample*> pinnedSample = &sample;
LONGLONG timeStamp;
HRESULT hr = mSourceReader->ReadSample(
(DWORD)MF_SOURCE_READER_FIRST_VIDEO_STREAM,
0,
NULL,
NULL,
&timeStamp,
pinnedSample
);
I suspect the problem lies in the construction of the mSourceReader (an IMFSourceReader instance, created from an IMFMediaSource). But, alas, I've no idea how to backtrack and find the source, as all the COM calls in the chain of commands that created mSourceReader returned S_OK.
Much thanks for any tips.
You don't need pin_ptr when taking the address of a local variable, since the garbage collector never moves local variables around anyway.
I'd guess that one of the other three parameters you're passing NULL to is non-optional, but I need to see what function you're calling to know for sure.
Did you create the IMFSourceReader in synchronous or asynchronous mode? The docs say:
This method can complete synchronously or asynchronously. If you provide a callback pointer when you create the source reader, the method is asynchronous. Otherwise, the method is synchronous.
I think this is your problem:
In synchronous mode:
The pdwStreamFlags and ppSample parameters cannot be NULL. Otherwise, the method returns E_POINTER.
You've passed NULL for pdwStreamFlags, which is not allowed.
Doc link: http://msdn.microsoft.com/en-us/library/dd374665.aspx

CLI/C++ Converting "this" pointer to an integer

I am trying to trace managed object creation/disposing in a CLI/C++ prog:
::System::Diagnostics::Trace::WriteLine(String::Format(
"Created {0} #{1:X8}",
this->GetType()->Name,
((UInt64)this).ToString()));
Which fails with
error C2440: 'type cast' : cannot convert from 'MyType ^const ' to 'unsigned __int64'
Is there a way to keep track of the unique object IDs this way?
Thanks!
First of all, why this doesn't work. Managed handle types ^ aren't pointers. They aren't just addresses. An instance of a managed type can and will be moved around in memory by GC, so addresses aren't stable; hence why it wouldn't let you do such a cast (as GC can execute at any moment, and you do not know when, any attempt to use such an address as a raw value is inherently a race condition).
Another thing that is often recommended, but doesn't actually work, is Object.GetHashCode(). For one thing, it returns an int, obviously not enough to be unique on x64. Furthermore, the documentation doesn't guarantee that values are unique, and they actually aren't in 2.0+.
The only working solution is to create a an instance of System.Runtime.InteropServices.GCHandle for your object, and then cast it to IntPtr - that is guaranteed to be both unique, and stable.
Check out the GCHandle type: http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.gchandle.aspx. Looks like it would do what you want, though it looks it would be a bit of a pain to use for your purposes...
Even if you could cast this to some integral value for display, it probably wouldn't be a useful unique identifier. This is because unlike C++, in C++/CLI the location of a (managed) object (and by extension the value of this) can potentially change during that object's lifetime. The (logically) same object could print two different strings at different points in the program.
MyType ^const is a reference type. Hence it's in the managed memory space, and you can't get direct memory pointers to these types, as they can change at any time.
Is there a way to keep track of the unique object IDs this way? Thanks!
You could use MyType.GetHashCode();