Skip to content

Commit

Permalink
NuGet v1.4.0, programmatic table CREATE and DROP
Browse files Browse the repository at this point in the history
  • Loading branch information
jchristn committed Aug 19, 2019
1 parent 33aea20 commit 81d43c6
Show file tree
Hide file tree
Showing 9 changed files with 530 additions and 78 deletions.
54 changes: 40 additions & 14 deletions DatabaseWrapper/Column.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,6 @@ namespace DatabaseWrapper
{
public class Column
{
#region Constructor

/// <summary>
/// Metadata for a column in a database table.
/// </summary>
public Column()
{
}

#endregion

#region Public-Members

/// <summary>
Expand All @@ -29,18 +18,23 @@ public Column()
/// <summary>
/// Whether or not the column is the table's primary key.
/// </summary>
public bool IsPrimaryKey;
public bool PrimaryKey;

/// <summary>
/// The data type of the column.
/// </summary>
public string DataType;
public DataType Type;

/// <summary>
/// The maximum character length of the data contained within the column.
/// </summary>
public int? MaxLength;

/// <summary>
/// For precision, i.e. number of places after the decimal.
/// </summary>
public int? Precision;

/// <summary>
/// Whether or not the column can contain NULL.
/// </summary>
Expand All @@ -49,7 +43,39 @@ public Column()
#endregion

#region Private-Members


#endregion

#region Constructors-and-Factories

/// <summary>
/// Instantiate the object.
/// </summary>
public Column()
{
}

/// <summary>
/// Instantiate the object.
/// </summary>
/// <param name="name">Name of the column.</param>
/// <param name="primaryKey">Indicate if this column is the primary key.</param>
/// <param name="dt">DataType for the column.</param>
/// <param name="maxLen">Max length for the column.</param>
/// <param name="precision">Precision for the column.</param>
/// <param name="nullable">Indicate if this column is nullable.</param>
public Column(string name, bool primaryKey, DataType dt, int? maxLen, int? precision, bool nullable)
{
if (String.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name));

Name = name;
PrimaryKey = primaryKey;
Type = dt;
MaxLength = maxLen;
Precision = precision;
Nullable = nullable;
}

#endregion

#region Public-Methods
Expand Down
16 changes: 16 additions & 0 deletions DatabaseWrapper/DataType.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Text;

namespace DatabaseWrapper
{
public enum DataType
{
Varchar,
Nvarchar,
Int,
Long,
Decimal,
DateTime
}
}
164 changes: 146 additions & 18 deletions DatabaseWrapper/DatabaseClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -117,10 +117,6 @@ public DatabaseClient(
string instance,
string database)
{
//
// MsSql, MySql, and PostgreSql will use server IP, port, username, password, database
// Sqlite will use just database and it should refer to the database file
//
if (String.IsNullOrEmpty(serverIp)) throw new ArgumentNullException(nameof(serverIp));
if (serverPort < 0) throw new ArgumentOutOfRangeException(nameof(serverPort));
if (String.IsNullOrEmpty(database)) throw new ArgumentNullException(nameof(database));
Expand Down Expand Up @@ -202,8 +198,72 @@ public List<Column> DescribeTable(string tableName)
}
else
{
throw new Exception("Table " + tableName + " is not in the tables list");
throw new KeyNotFoundException("Table " + tableName + " is not in the tables list");
}
}

/// <summary>
/// Create a table with a specified name.
/// </summary>
/// <param name="tableName">The name of the table.</param>
/// <param name="columns">Columns.</param>
public void CreateTable(string tableName, List<Column> columns)
{
if (String.IsNullOrEmpty(tableName)) throw new ArgumentNullException(nameof(tableName));
if (columns == null || columns.Count < 1) throw new ArgumentNullException(nameof(columns));

string query = null;

switch (_DbType)
{
case DbTypes.MsSql:
query = MssqlHelper.CreateTableQuery(tableName, columns);
break;

case DbTypes.MySql:
query = MysqlHelper.CreateTableQuery(tableName, columns);
break;

case DbTypes.PgSql:
query = PgsqlHelper.CreateTableQuery(tableName, columns);
break;
}

DataTable result = Query(query);

LoadTableNames();
LoadTableDetails();
}

/// <summary>
/// Drop the specified table.
/// </summary>
/// <param name="tableName">The table to drop.</param>
public void DropTable(string tableName)
{
if (String.IsNullOrEmpty(tableName)) throw new ArgumentNullException(nameof(tableName));

string query = null;

switch (_DbType)
{
case DbTypes.MsSql:
query = MssqlHelper.DropTableQuery(tableName);
break;

case DbTypes.MySql:
query = MysqlHelper.DropTableQuery(tableName);
break;

case DbTypes.PgSql:
query = PgsqlHelper.DropTableQuery(tableName);
break;
}

DataTable result = Query(query);

LoadTableNames();
LoadTableDetails();
}

/// <summary>
Expand All @@ -222,15 +282,15 @@ public string GetPrimaryKeyColumn(string tableName)
{
foreach (Column c in details)
{
if (c.IsPrimaryKey) return c.Name;
if (c.PrimaryKey) return c.Name;
}
}

throw new Exception("Unable to find primary key for table " + tableName);
}
else
{
throw new Exception("Table " + tableName + " is not in the tables list");
throw new KeyNotFoundException("Table " + tableName + " is not in the tables list");
}
}

Expand Down Expand Up @@ -262,7 +322,7 @@ public List<string> GetColumnNames(string tableName)
}
else
{
throw new Exception("Table " + tableName + " is not in the tables list");
throw new KeyNotFoundException("Table " + tableName + " is not in the tables list");
}
}

Expand Down Expand Up @@ -837,6 +897,73 @@ public string SanitizeString(string val)
throw new Exception("Unknown database type");
}

/// <summary>
/// Retrieve a DataType based on a supplied string.
/// </summary>
/// <param name="s">String.</param>
/// <returns>DataType.</returns>
public DataType DataTypeFromString(string s)
{
if (String.IsNullOrEmpty(s)) throw new ArgumentNullException(nameof(s));

s = s.ToLower();

switch (s)
{
case "bigserial": // pgsql
case "bigint": // mssql
return DataType.Long;

case "smallserial": // pgsql
case "smallest": // pgsql
case "tinyint": // mssql, mysql
case "integer": // pgsql
case "int": // mssql, mysql
case "smallint": // mssql, mysql
case "mediumint": // mysql
case "serial": // pgsql
return DataType.Int;

case "double precision": // pgsql
case "real": // pgsql
case "float": // mysql
case "double": // mysql
case "decimal": // mssql
case "numeric": // mssql
return DataType.Decimal;

case "timestamp without timezone": // pgsql
case "timestamp without time zone": // pgsql
case "timestamp with timezone": // pgsql
case "timestamp with time zone": // pgsql
case "time without timezone": // pgsql
case "time without time zone": // pgsql
case "time with timezone": // pgsql
case "time with time zone": // pgsql
case "time": // mssql, mysql
case "date": // mssql, mysql
case "datetime": // mssql, mysql
case "datetime2": // mssql
case "timestamp": // mysql
return DataType.DateTime;

case "character": // pgsql
case "char": // mssql, mysql, pgsql
case "text": // mssql, mysql, pgsql
case "varchar": // mssql, mysql, pgsql
return DataType.Varchar;

case "character varying": // pgsql
case "nchar":
case "ntext":
case "nvarchar":
return DataType.Nvarchar; // mssql

default:
throw new ArgumentException("Unknown DataType: " + s);
}
}

#endregion

#region Private-Methods
Expand Down Expand Up @@ -936,9 +1063,10 @@ private void LoadTableNames()
}
}

_TableNames = new ConcurrentList<string>();

if (tableNames != null && tableNames.Count > 0)
{
_TableNames = new ConcurrentList<string>();
foreach (string curr in tableNames)
{
_TableNames.Add(curr);
Expand Down Expand Up @@ -1007,9 +1135,9 @@ private void LoadTableDetails()
#region Mssql

tempColumn.Name = currColumn["COLUMN_NAME"].ToString();
if (currColumn["CONSTRAINT_NAME"].ToString().StartsWith("PK_")) tempColumn.IsPrimaryKey = true;
else tempColumn.IsPrimaryKey = false;
tempColumn.DataType = currColumn["DATA_TYPE"].ToString();
if (currColumn["CONSTRAINT_NAME"].ToString().StartsWith("PK_")) tempColumn.PrimaryKey = true;
else tempColumn.PrimaryKey = false;
tempColumn.Type = DataTypeFromString(currColumn["DATA_TYPE"].ToString());
if (!Int32.TryParse(currColumn["CHARACTER_MAXIMUM_LENGTH"].ToString(), out maxLength)) { tempColumn.MaxLength = null; }
else tempColumn.MaxLength = maxLength;
if (String.Compare(currColumn["IS_NULLABLE"].ToString(), "YES") == 0) tempColumn.Nullable = true;
Expand All @@ -1022,9 +1150,9 @@ private void LoadTableDetails()
#region Mysql

tempColumn.Name = currColumn["COLUMN_NAME"].ToString();
if (String.Compare(currColumn["COLUMN_KEY"].ToString(), "PRI") == 0) tempColumn.IsPrimaryKey = true;
else tempColumn.IsPrimaryKey = false;
tempColumn.DataType = currColumn["DATA_TYPE"].ToString();
if (String.Compare(currColumn["COLUMN_KEY"].ToString(), "PRI") == 0) tempColumn.PrimaryKey = true;
else tempColumn.PrimaryKey = false;
tempColumn.Type = DataTypeFromString(currColumn["DATA_TYPE"].ToString());
if (!Int32.TryParse(currColumn["CHARACTER_MAXIMUM_LENGTH"].ToString(), out maxLength)) { tempColumn.MaxLength = null; }
else tempColumn.MaxLength = maxLength;
if (String.Compare(currColumn["IS_NULLABLE"].ToString(), "YES") == 0) tempColumn.Nullable = true;
Expand All @@ -1037,9 +1165,9 @@ private void LoadTableDetails()
#region Pgsql

tempColumn.Name = currColumn["column_name"].ToString();
if (String.Compare(currColumn["is_primary_key"].ToString(), "YES") == 0) tempColumn.IsPrimaryKey = true;
else tempColumn.IsPrimaryKey = false;
tempColumn.DataType = currColumn["DATA_TYPE"].ToString();
if (String.Compare(currColumn["is_primary_key"].ToString(), "YES") == 0) tempColumn.PrimaryKey = true;
else tempColumn.PrimaryKey = false;
tempColumn.Type = DataTypeFromString(currColumn["DATA_TYPE"].ToString());
if (!Int32.TryParse(currColumn["max_len"].ToString(), out maxLength)) { tempColumn.MaxLength = null; }
else tempColumn.MaxLength = maxLength;
if (String.Compare(currColumn["IS_NULLABLE"].ToString(), "YES") == 0) tempColumn.Nullable = true;
Expand Down
4 changes: 2 additions & 2 deletions DatabaseWrapper/DatabaseWrapper.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<PropertyGroup>
<TargetFrameworks>netstandard2.0;net452</TargetFrameworks>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<Version>1.3.2</Version>
<Version>1.4.0</Version>
<Authors>Joel Christner</Authors>
<Company>Joel Christner</Company>
<Description>Simple database wrapper for Microsoft SQL Server, MySQL, and PostgreSQL written in C# supporting dynamic query building and nesting using expressions.</Description>
Expand All @@ -12,7 +12,7 @@
<RepositoryUrl>https://github.com/jchristn/DatabaseWrapper</RepositoryUrl>
<RepositoryType>Github</RepositoryType>
<PackageLicenseUrl>https://github.com/jchristn/DatabaseWrapper/blob/master/LICENSE.txt</PackageLicenseUrl>
<PackageReleaseNotes>Breaking change: rework Mssql SELECT pagination (no longer using an inner and outer query), requires ORDER BY clause be set now.</PackageReleaseNotes>
<PackageReleaseNotes>Programmatic table creation (CREATE TABLE) and drop (DROP TABLE)</PackageReleaseNotes>
<PackageTags>database sql mysql mssql pgsql postgresql dynamic query builder datarow datatable</PackageTags>
<PackageIconUrl>https://raw.githubusercontent.com/jchristn/databasewrapper/master/assets/icon.ico</PackageIconUrl>
</PropertyGroup>
Expand Down
Loading

0 comments on commit 81d43c6

Please sign in to comment.