85 lines
3.7 KiB
C#
85 lines
3.7 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Data;
|
|
using System.Text;
|
|
|
|
namespace DbTools {
|
|
public class SqlBuilder {
|
|
|
|
public string[] GetTableNames(IDbConnection cn) {
|
|
if (cn == null) {
|
|
throw new ArgumentNullException("cn");
|
|
}
|
|
List<string> tables = new List<string>();
|
|
if (cn.State != ConnectionState.Open) {
|
|
cn.Open();
|
|
}
|
|
using (IDbCommand cmd = cn.CreateCommand()) {
|
|
cmd.CommandText = "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name;";
|
|
using (IDataReader reader = cmd.ExecuteReader()) {
|
|
while (reader.Read()) {
|
|
tables.Add(reader.GetString(0));
|
|
}
|
|
}
|
|
}
|
|
return tables.ToArray();
|
|
}
|
|
|
|
public string GetTableCreateSql(IDbConnection cn, string tableName, string selectStatement = "select * from $table") {
|
|
if (cn == null) {
|
|
throw new ArgumentNullException("cn");
|
|
}
|
|
if (string.IsNullOrEmpty(tableName)) {
|
|
throw new ArgumentNullException("tableName");
|
|
}
|
|
|
|
if (cn.State != ConnectionState.Open) {
|
|
cn.Open();
|
|
}
|
|
selectStatement = selectStatement.Replace("$table", tableName);
|
|
using (IDbCommand cmd = cn.CreateCommand()) {
|
|
cmd.CommandText = selectStatement;
|
|
using (IDataReader reader = cmd.ExecuteReader(CommandBehavior.SchemaOnly | CommandBehavior.KeyInfo)) {
|
|
DataTable schemaTable = reader.GetSchemaTable();
|
|
if (schemaTable == null) {
|
|
throw new Exception("Could not get schema for table " + tableName);
|
|
}
|
|
StringBuilder sb = new StringBuilder();
|
|
sb.AppendLine("CREATE TABLE " + tableName + " (");
|
|
List<string> pkColumns = new List<string>();
|
|
foreach (DataRow row in schemaTable.Rows) {
|
|
string columnName = row["ColumnName"].ToString();
|
|
string dataType = row["DataTypeName"].ToString();
|
|
int columnSize = Convert.ToInt32(row["ColumnSize"]);
|
|
bool allowDBNull = Convert.ToBoolean(row["AllowDBNull"]);
|
|
bool isKey = Convert.ToBoolean(row["IsKey"]);
|
|
if (isKey) {
|
|
pkColumns.Add(columnName);
|
|
}
|
|
sb.Append(" " + columnName + " " + dataType);
|
|
if (dataType.Equals("VARCHAR", StringComparison.OrdinalIgnoreCase) ||
|
|
dataType.Equals("CHAR", StringComparison.OrdinalIgnoreCase) ||
|
|
dataType.Equals("NVARCHAR", StringComparison.OrdinalIgnoreCase) ||
|
|
dataType.Equals("NCHAR", StringComparison.OrdinalIgnoreCase)) {
|
|
sb.Append("(" + columnSize + ")");
|
|
}
|
|
if (!allowDBNull) {
|
|
sb.Append(" NOT NULL");
|
|
}
|
|
sb.AppendLine(",");
|
|
}
|
|
if (pkColumns.Count > 0) {
|
|
sb.AppendLine(" PRIMARY KEY (" + string.Join(", ", pkColumns) + ")");
|
|
} else {
|
|
// Remove the last comma
|
|
sb.Length -= 3;
|
|
sb.AppendLine();
|
|
}
|
|
sb.AppendLine(");");
|
|
return sb.ToString();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|