Autor: Bodoconsult EDV-Dienstleistungen GmbH, Robert Leisner
https://www.nuget.org/packages/Bodoconsult.Core.Database.Postgres/
https://github.com/RobertLeisner/Bodoconsult.Core.Database.Postgres
Bodoconsult.Core.Database.Postgres library simplifies the access to Postgres based databases. It handles the most common database actions like getting datatables, running SQL statement or fetch scalar values from the database.
Additionally the library contains some tools for developers making the usage of the database layers derived from Bodoconsult.Core.Database as easy as possible. See below.
The source code contain a NUnit test classes, the following source code is extracted from. The samples below show the most helpful use cases for the library.
The database used for unit tests is the Chinook sample database from https://github.com/lerocha/chinook-database.
To connect to a Postgres database with this library you need to provide connection string. Here a sample for such a connection string:
Host=192.168.10.125;Port=5432;Username=postgres;Password=mypassword;Database=dvdrental;SslMode=Disable;
For more information on connection strings see https://www.connectionstrings.com/postgresql/.
The most important class in the library is the the class PostgresConnManager. PostgresConnManager exposes the following main methods:
[SetUp]
public void Setup()
{
var conn = TestHelper.PostgresConnectionString;
_db = PostgresConnManager.GetConnManager(conn);
}
[Test]
public void TestTestConnection()
{
// Assert
// Act
var result = _db.TestConnection();
// Assert
Assert.IsTrue(result);
}
[Test]
public void TestGetDataTableSql()
{
// Assert
var sql =
"SELECT * " +
"FROM Film; ";
// Act
var result = _db.GetDataTable(sql);
// Assert
Assert.IsNotNull(result);
}
[Test]
public void TestGetDataTableCommand()
{
// Act
var sql =
"SELECT * " +
"FROM Film; ";
var cmd = new NpgsqlCommand(sql);
// Act
var result = _db.GetDataTable(cmd);
// Assert
Assert.IsNotNull(result);
}
/// <summary>
/// Get a datatable from the database from a (parameterized) SqlCommand object (choose this option to avoid SQL injection)
/// </summary>
[Test]
public void TestGetDataTableFromCommandWithGetCommand()
{
const string sql = "SELECT * FROM Film";
var cmd = _db.GetCommand();
cmd.CommandText = sql;
// Add parameters here if required
var erg = _db.GetDataTable(cmd);
Assert.IsTrue(erg.Rows.Count > 0);
}
/// <summary>
/// Get a datatable from the database from a plain SQL string (avoid this option due to SQL injection)
/// </summary>
[Test]
public void TestGetDataReaderFromSql()
{
const string sql = "SELECT * FROM Film";
var erg = _db.GetDataReader(sql);
Assert.IsTrue(erg.FieldCount > 0);
}
/// <summary>
/// Get a datatable from the database from a (parameterized) SqlCommand object (choose this option to avoid SQL injection)
/// </summary>
[Test]
public void TestGetDataReaderFromCommand()
{
const string sql = "SELECT * FROM Film";
var cmd = new NpgsqlCommand
{
CommandText = sql
};
// Add parameters here if required
var erg = _db.GetDataReader(cmd);
Assert.IsTrue(erg.FieldCount > 0);
}
/// <summary>
/// Get a datatable from the database from a (parameterized) SqlCommand object (choose this option to avoid SQL injection)
/// </summary>
[Test]
public void TestGetDataReaderFromCommandWidthGetCommand()
{
const string sql = "SELECT * FROM Film";
var cmd = _db.GetCommand();
cmd.CommandText = sql;
// Add parameters here if required
var erg = _db.GetDataReader(cmd);
Assert.IsTrue(erg.FieldCount > 0);
}
/// <summary>
/// Get a datatable from the database from a (parameterized) SqlCommand object (choose this option to avoid SQL injection)
/// </summary>
[Test]
public void TestGetDataReaderFromCommandWidthGetCommandAndParameter()
{
const string sql = "SELECT * FROM Film WHERE film_id=@ID;";
var cmd = _db.GetCommand();
cmd.CommandText = sql;
var p = _db.GetParameter(cmd, "@ID", GeneralDbType.Int);
p.Value = 8;
// Add parameters here if required
var erg = _db.GetDataReader(cmd);
Assert.IsTrue(erg.FieldCount > 0);
Assert.IsTrue(erg.HasRows);
}
/// <summary>
/// Execute a plain SQL string (avoid this option due to SQL injection)
/// </summary>
[Test]
public void TestExecFromSql()
{
const string sql = "DELETE FROM Film WHERE film_id=-99";
Assert.DoesNotThrow(() => _db.Exec(sql));
}
/// <summary>
/// Execute a SqlCommand object (choose this option to avoid SQL injection)
/// </summary>
[Test]
public void TestExecFromCommand()
{
const string sql = "DELETE FROM Film WHERE film_id=@Key";
// Create command
var cmd = new NpgsqlCommand()
{
CommandText = sql
};
// Add a parameter to the command
var para = cmd.Parameters.Add("@Key", NpgsqlDbType.Integer);
para.Value = -99;
Assert.DoesNotThrow(() => _db.Exec(cmd));
}
/// <summary>
/// Get a scalar value from database from a plain SQL string (avoid this option due to SQL injection)
/// </summary>
[Test]
public void TestExecWithResultFromSql()
{
const string sql = "SELECT film_id FROM film WHERE film_id=8";
var result = _db.ExecWithResult(sql);
Assert.IsNotNull(result);
Assert.IsFalse(string.IsNullOrEmpty(result));
}
/// <summary>
/// Get a scalar value from database from SqlCommand object (choose this option to avoid SQL injection)
/// </summary>
[Test]
public void TestExecWithResultFromCommand()
{
const string sql = "SELECT film_id FROM Film WHERE film_id=@Key";
// Create command
var cmd = new NpgsqlCommand
{
CommandText = sql
};
// Add a parameter to the command
var para = cmd.Parameters.Add("@Key", NpgsqlDbType.Integer);
para.Value = 8;
var result = _db.ExecWithResult(cmd);
Assert.IsNotNull(result);
Assert.IsFalse(string.IsNullOrEmpty(result));
}
[Test]
public void TestExecMultiple()
{
const string sql = "DELETE FROM Film WHERE film_id=-99";
var commands = new List<DbCommand>();
var cmd = new NpgsqlCommand(sql);
commands.Add(cmd);
cmd = new NpgsqlCommand(sql);
commands.Add(cmd);
cmd = new NpgsqlCommand(sql);
commands.Add(cmd);
var result = _db.ExecMultiple(commands);
Assert.IsTrue(result == 0);
}
There is as basic metadata infrastructure implemented to help developers to make best usage of Bodoconsult.Core.Database. This metadata infrastructure derived from IMetaDataService / BaseMetaDataService creates C### code files based on a certain SQL statement OR DBCommand object.
Here a sample how to use the IMetaDataService infrastructure:
const string conn = "Valid ADO.NET provider connection string";
const string sql = "SELECT * FROM \"Customer\";";
const string entityName = "Customer";
const string primaryKeyField = "CustomerId";
const string targetPath = @"D:\temp";
// Instanciate the metadata service
var service = PostgresMetaDataService();
// Get the metadata for the SQL statement
service.GetMetaData(conn, entityName, sql, primaryKeyField);
// Export the code files
var result = service.ExportAll(targetPath);
As a result you will find four files with code in the folder D:\temp:
Bodoconsult (http://www.bodoconsult.de) is a Munich based software development company from Germany.
Robert Leisner is senior software developer at Bodoconsult. See his profile on http://www.bodoconsult.de/Curriculum_vitae_Robert_Leisner.pdf.
Copyright (c) Bodoconsult EDV-Dienstleistungen GmbH
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
License: https://licenses.nuget.org/MIT
SPDX identifier MIT
License text MIT License
Copyright (c) Bodoconsult EDV-Dienstleistungen GmbH
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Project-Url: https://github.com/npgsql/npgsql
License: https://licenses.nuget.org/PostgreSQL
SPDX identifier PostgreSQL
License text PostgreSQL Database Management System
(formerly known as Postgres, then as Postgres95)
Portions Copyright (c) 1996-2010, The PostgreSQL Global Development Group
Portions Copyright (c) 1994, The Regents of the University of California
Permission to use, copy, modify, and distribute this software and its documentation for any purpose, without fee, and without a written agreement is hereby granted, provided that the above copyright notice and this paragraph and the following two paragraphs appear in all copies.
IN NO EVENT SHALL _____ BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF _____ HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
_____ SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND _____ HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.