I have created a temporary table with an npgsql command and if there is an error in my code, after I cannot find my temporary table! I know that postgres don’t drop temporary table inside the connection but only when I close the connection.
This is a sample test code:
try {
//___
var connectionString_log = new NpgsqlConnectionStringBuilder
{
Host = "127.0.0.1",
Database = "bracciniRRSNET",
Username = "dba",
Password = "sql",
Port = 5432,
Pooling = false,
ApplicationName = "NewRRSNpgsqlClient", //ConnectionInfo.ApplicationName, Questo è nel token!
IncludeErrorDetail = true
}.ConnectionString;
var connection = new NpgsqlConnection(connectionString_log);
{
connection.Open();
var transaction = connection.BeginTransaction();
var command = new NpgsqlCommand("", connection, transaction:transaction);
//Create a temporary table and insert some records.
command.CommandText = @"CREATE TEMP TABLE temp_users(
user_id SERIAL PRIMARY KEY,
username VARCHAR(50) NOT NULL,
email VARCHAR(100) NOT NULL
) ON COMMIT PRESERVE ROWS;INSERT INTO temp_users (username, email) VALUES ('Alice', '[email protected]');
INSERT INTO temp_users (username, email) VALUES ('Bob', '[email protected]');";
command.ExecuteNonQuery();
var sql_copy = $"COPY delstory to STDout BINARY;";
command.CommandText = sql_copy;
byte[] buffer = new byte[100 * 1024 * 1024];
MemoryStream memoryStream = new MemoryStream();
using (var outStream = await connection.BeginRawBinaryCopyAsync(sql_copy))
{
int bytesRead;
`your text`
while ((bytesRead = await outStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
{
memoryStream.Write(buffer, 0, bytesRead);
}
}
memoryStream.Seek(0, SeekOrigin.Begin);
try
{
//Now do a duplicate key error.....
var copy = $"COPY delstory from STDin BINARY";
command.CommandText = copy;
using (var outStream = await connection.BeginRawBinaryCopyAsync(copy))
{
int bytesRead;
while ((bytesRead = memoryStream.Read(buffer, 0, buffer.Length)) > 0)
{
await outStream.WriteAsync(buffer, 0, bytesRead);
}
outStream.Write(buffer);
}
}
catch (Exception ex)
{
if (ex.Message.Contains("23505:")) // Duplicated error catch
{
try
{
transaction.Commit(); //Close transaction that's blocked
transaction = connection.BeginTransaction();
command = new NpgsqlCommand("", connection, transaction: transaction);
command.CommandText = "select count(*) from temp_users;"; // Cannot find temp_users!
var reader = await command.ExecuteReaderAsync();
reader.Read();
Console.WriteLine(ex.Message);
}
catch (Exception ex2)
{
Console.WriteLine(ex2.Message);
}
}
}
connection.Close();
}
}
catch (Exception ex) { Console.WriteLine(ex.Message); }
Output: 42P01: relation “temp_users” does not exist
Where is my mistake ?
Why the table is out ?
New contributor
Gianluca Braccini is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.