private static void CheckStagingTablesListPrimaryKeysFirst(Dictionary <string, PrimaryKeyInfo> pkInfoList) { // it's important that all staging tables list the primary keys first because this is assumed // by the algorithm that performs table diffs. var b = StagingTablesBuilder.Get(StagingSchema.PrimaryStagingSchemaName); foreach (var table in b.GetTables(includePseudoRegisterMarkTable: false)) { if (!table.Name.Equals("CT_CONFIG", StringComparison.OrdinalIgnoreCase)) { PrimaryKeyInfo pkInfo = pkInfoList[table.Name]; if (pkInfo != null) { var stagingTableCols = table.Columns; // deduct 1 for src_timetable_id if (stagingTableCols.Count - 1 < pkInfo.Columns.Count) { throw new ApplicationException( $"Staging table contains fewer columns than primary key of source: {table.Name}"); } for (int n = 0; n < pkInfo.Columns.Count; ++n) { if (!pkInfo.Columns[n].ColumnName.Equals(stagingTableCols[n + 1].Name, StringComparison.OrdinalIgnoreCase)) { throw new ApplicationException( $"Incorrect staging table column order: {table.Name} (primary key columns must be defined first)"); } } } } } }
static void CreateTable( this NpgsqlConnection conn, SqlTable table, PrimaryKeyInfo primaryKey, Dictionary <string, IColumnInfo> fields, uint tableRevision, ILog log) { var b = new NpgsqlCommandBuilder(); log.InfoFormat("Creating table '{0}' at revision {1}", table.Name, tableRevision); var fieldSqls = new List <string>(); foreach (IColumnInfo field in fields.Values) { fieldSqls.Add(field.FieldSql()); } if (null != primaryKey) { fieldSqls.Add(primaryKey.FieldSql()); } string escapedTableName = b.QuoteIdentifier(table.Name); string cmd = "CREATE TABLE " + escapedTableName + " ("; cmd += string.Join(",", fieldSqls); cmd += ")"; cmd += "; COMMENT ON TABLE " + escapedTableName + " IS '" + tableRevision.ToString() + "';"; ExecuteStatement(conn, cmd, log); }
/// <summary> /// 获取主键信息 /// </summary> /// <param name="items"></param> /// <param name="tableName"></param> /// <returns></returns> PrimaryKeyInfo GetPKeyInfo(List <MetaDataColumnInfo> items, string tableName) { var pki = new PrimaryKeyInfo(); //-->获取出主键来 var _key = items.Where(p => p.column_key.IsNotEmpty() && p.column_key.Equals(ConstantCollection.TABLE_KEY)).GetTList <MetaDataColumnInfo>(); if (0 < _key.Count) { //-->获取where条件 List <string> _whereCondition = new List <string>(); List <string> _Fields = new List <string>(); List <String> _Values = new List <string>(); foreach (var pk in _key) { _Fields.Add(pk.column_name); _Values.Add(pk.column_value); if (pk.data_type.ToLower().Equals("int") && pk.column_value == "0") { continue; } _whereCondition.Add(string.Format("{0} {1}", pk.column_name, Wrapper.ConvertToDBTypeWhereUsing(pk))); } if (_whereCondition.Count > 0) { pki.DeleteSentence = string.Format("delete from {0} where {1}", tableName, string.Join(" and ", _whereCondition)); } pki.Name = string.Join("|", _Fields); pki.Value = string.Join(ConstantCollection.Separator_Hollow_pentagram.ToString(), _Values); } return(pki); }
private static void CheckSamePrimaryKeyColumns(List <Dictionary <string, PrimaryKeyInfo> > allPkInfo, StagingTablesBuilder b) { // checks that all source timetables have identical primary key col names for // the tables that are to be extracted, which is an important consideration when // performing the full database diff... foreach (var tableName in b.GetTableNames(includePseudoRegisterMarkTable: false)) { PrimaryKeyInfo baseInfo = null; foreach (var info in allPkInfo) { var pkInfo = info[tableName]; if (pkInfo == null) { throw new ApplicationException($"Could not find primary key data for table: {tableName}"); } if (baseInfo == null) { baseInfo = pkInfo; } else { if (!PrimaryKeyInfo.Identical(baseInfo, pkInfo)) { var sb = new StringBuilder(); sb.Append("There is an incompatibility between source timetables."); sb.AppendFormat(" Primary key column definitions are different for table {0}", tableName); throw new ApplicationException(sb.ToString()); } } } } }
/// <summary> /// Update all items matching WHERE clause using fields from the item sent in. /// If `keys` has been specified on the current Mighty instance then any primary key fields in the item are ignored. /// The item is not filtered to remove fields not in the table, if you need that you can call <see cref="New"/> with first parameter `partialItem` and second parameter `false` first. /// </summary> /// <param name="partialItem">Item containing values to update with</param> /// <param name="where">WHERE clause specifying which rows to update</param> /// <param name="connection">Optional connection to use</param> /// <param name="inParams">Named input parameters</param> /// <param name="args">Auto-numbered input parameters</param> protected int UpdateUsingWithParams(object partialItem, string where, DbConnection connection, object inParams, params object[] args) { var updateValues = new StringBuilder(); var partialItemParameters = new NameValueTypeEnumerator(DataContract, partialItem); // TO DO: Test that this combinedInputParams approach works var combinedInputParams = inParams?.ToExpando() ?? new ExpandoObject(); var toDict = combinedInputParams.ToDictionary(); int i = 0; foreach (var paramInfo in partialItemParameters) { if (!PrimaryKeyInfo.IsKey(paramInfo.Name)) { if (i > 0) { updateValues.Append(", "); } updateValues.Append(paramInfo.Name).Append(" = ").Append(Plugin.PrefixParameterName(paramInfo.Name)); i++; toDict.Add(paramInfo.Name, paramInfo.Value); } } var sql = Plugin.BuildUpdate(CheckGetTableName(), updateValues.ToString(), where); var retval = ExecuteWithParams(sql, args: args, inParams: combinedInputParams, outParams: new { __rowcount = new RowCount() }, connection: connection); return(retval.__rowcount); }
/// <summary> /// 根据ID删除记录 /// </summary> /// <param name="id">要删除的记录ID</param> /// <returns></returns> public int DeleteById(object id) { int ret = -1; DeleteCondition con = new DeleteCondition(EntityInfo.DBInfo); con.Tables.Append(EntityInfo.DBInfo.CurrentDbAdapter.FormatTableName(EntityInfo.TableName)); ParamList list = new ParamList(); ScopeList lstScope = new ScopeList(); PrimaryKeyInfo pkInfo = id as PrimaryKeyInfo; if (pkInfo == null) { lstScope.AddEqual(EntityInfo.PrimaryProperty[0].PropertyName, id); } else { pkInfo.FillScope(EntityInfo.PrimaryProperty, lstScope, true); } con.Condition.Append("1=1"); con.Condition.Append(DataAccessCommon.FillCondition(EntityInfo, list, lstScope)); Dictionary <string, bool> cacheTables = null; cacheTables = _oper.DBInfo.QueryCache.CreateMap(EntityInfo.TableName); ret = ExecuteCommand(con.GetSql(true), list, CommandType.Text, cacheTables); return(ret); }
public virtual void CreatePrimaryKey(PrimaryKeyInfo pk) { Put("^alter ^table %f ^add ^constraint %i ^primary ^key", pk.OwnerTable, pk.ConstraintName); WriteRaw(" ("); ColumnRefs(pk.Columns); WriteRaw(")"); EndCommand(); }
/// <summary> /// This will identify the primary column on the entity for instance uniqueness. /// </summary> /// <param name="column">Expression denoting the primary key</param> /// <param name="columnName">Optional: Data column name of key (defaulted to property name)</param> protected void HasPrimaryKey(Expression <Func <T, object> > column, string columnName) { var name = GetPropertyNameFromExpression(column); var property = FindPropertyFromPropertyName(typeof(T), name); var columnInfo = new PrimaryKeyInfo(typeof(T), property, columnName); PrimaryKey = columnInfo; }
/// <summary> /// Initializes a new instance of the <see cref="CRUDControllerBase{T, O}"/> class. /// </summary> /// <param name="repository">A repository object.</param> public CRUDControllerBase(O repository) { _Repository = repository; PrimaryKeyInfo = CRUDModelPKAttribute.GetPKProperty <T>(); CRUDModelPKAttribute att = (CRUDModelPKAttribute)PrimaryKeyInfo.GetCustomAttribute(typeof(CRUDModelPKAttribute)); IsPKAutoIncrement = att.AutoIncrement; }
// datetime'1900-01-01T00%3A00%3A00' public static string CreatePkTemplate(string tableName, PrimaryKeyInfo[] pki) { if (pki.Length == 0) { throw new NotImplementedException("Case no PK not studied..."); } if (pki.Length == 1) { if (object.ReferenceEquals(pki[0].DotNetType, typeof(System.Guid))) return tableName + "(guid'{@value0}')"; // guid if (object.ReferenceEquals(pki[0].DotNetType, typeof(int))) return tableName + "({@value0})"; // int if (object.ReferenceEquals(pki[0].DotNetType, typeof(long))) return tableName + "({@value0})"; // long if (object.ReferenceEquals(pki[0].DotNetType, typeof(string))) return tableName + "('{@value0}')"; // string if (object.ReferenceEquals(pki[0].DotNetType, typeof(System.DateTime))) return tableName + "(datetime'{@value0}')"; // string throw new NotImplementedException("CreatePkTemplate for type " + pki[0].DotNetType.Name + " not implemented"); } string str = tableName + "("; // <link rel="edit" title="T_SYS_VisualisierungStichtag" href="T_SYS_VisualisierungStichtag(VIS_DWG='%3F',VIS_Stichtag=datetime'1900-01-01T00%3A00%3A00')" /> for (int i = 0; i < pki.Length; ++i) { if (object.ReferenceEquals(pki[i].DotNetType, typeof(System.Guid))) str += pki[i].ColumnName + "=" + "guid'{@value" + i.ToString() + "}'"; // guid if (object.ReferenceEquals(pki[i].DotNetType, typeof(string))) str += pki[i].ColumnName + "=" + "'{@value" + i.ToString() + "}'"; // string if (object.ReferenceEquals(pki[i].DotNetType, typeof(int))) str += pki[i].ColumnName + "=" + "{@value" + i.ToString() + "}"; // int if (object.ReferenceEquals(pki[i].DotNetType, typeof(long))) str += pki[i].ColumnName + "=" + "{@value" + i.ToString() + "}"; // long if (object.ReferenceEquals(pki[i].DotNetType, typeof(System.DateTime))) str += pki[i].ColumnName + "=" + "datetime'{@value" + i.ToString() + "}'"; // string if (i < pki.Length - 1) str += ","; } str += ")"; // return tableName + "T_Benutzer({@value})"; // string // <link rel="edit" title="T_SYS_VisualisierungStichtag" href="T_SYS_VisualisierungStichtag(VIS_DWG='%3F',VIS_Stichtag=datetime'1900-01-01T00%3A00%3A00')" /> return str; }
public virtual void DropPrimaryKey(PrimaryKeyInfo pk) { if (_dialectCaps.ExplicitDropConstraint) { PutCmd("^alter ^table %f ^drop ^primary ^key", pk.OwnerTable); } else { DropConstraint(pk); } }
/// <summary> /// /// </summary> /// <returns></returns> public EfDbCodeTableColumnBuilder PrimaryKey() { var primaryKey = new PrimaryKeyInfo(); primaryKey.PrimaryColumn = _column; primaryKey.Table = TableBuilder.TableInfo; _column.Identity = new Identity(1, 1); TableBuilder.TableInfo.PrimaryKey = primaryKey; return(this); }
/// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="primaryKey"></param> protected virtual T PrimaryKeyCommand <T>(PrimaryKeyInfo primaryKey) where T : class, IPrimaryKeyCommand { var service = CommandServices.GetCommand <T>(); if (service == null) { return(null); } service.SetPrimaryKey(primaryKey); Commands.Add(service); return(service); }
/// <summary> /// /// </summary> /// <param name="table"></param> /// <param name="sqlTable"></param> /// <returns></returns> private PrimaryKeyInfo GetPrimaryKeyInfo(TableInfo table, SqlTable sqlTable) { var sqlPrimaryKey = SqlPrimaryKeyManager.GetPrimaryKey(sqlTable); if (sqlPrimaryKey == null) { return(null); } var primaryKey = new PrimaryKeyInfo(); primaryKey.Name = sqlPrimaryKey.ConstraintName; primaryKey.Table = table; primaryKey.PrimaryColumn = table.GetColumn(sqlPrimaryKey.ColumnName); return(primaryKey); }
/// <summary> /// Returns a string-string dictionary which can be directly bound to ASP.NET dropdowns etc. (see https://stackoverflow.com/a/805610/795690). /// </summary> /// <param name="orderBy">Order by, defaults to primary key</param> /// <returns></returns> override public IDictionary <string, string> KeyValues(string orderBy = null) { if (IsGeneric) { // TO DO: Make sure this works even when there is mapping var db = new MightyOrm(null, TableName, PrimaryKeyInfo.PrimaryKeyColumn, ValueColumn, connectionProvider: new PresetsConnectionProvider(ConnectionString, Factory, Plugin.GetType())); return(db.KeyValues(orderBy)); } string partialMessage = $" to call {nameof(KeyValues)}, please provide one in your constructor"; string valueColumn = CheckGetValueColumn(partialMessage); string pkColumn = PrimaryKeyInfo.CheckGetKeyColumn(partialMessage); // this cast here casts the IEnumerable of ExpandoObject's to an IEnumerable of string-object dictionaries // (since each ExpandoObject can be cast like that) var results = All(orderBy: orderBy ?? pkColumn, columns: $"{pkColumn}, {valueColumn}").Cast <IDictionary <string, object> >(); return(results.ToDictionary(item => item[pkColumn].ToString(), item => item[valueColumn].ToString())); }
/// <summary> /// /// </summary> /// <param name="tableInfo"></param> /// <param name="tableMetadata"></param> /// <returns></returns> private PrimaryKeyInfo GetPrimaryKey(MetadataTableInfo tableInfo, TableMetadata tableMetadata) { var primaryKeyMetadata = tableMetadata.PrimaryKey; if (primaryKeyMetadata == null) { return(null); } var primaryKey = new PrimaryKeyInfo(); primaryKey.Table = tableInfo; primaryKey.Name = primaryKeyMetadata.Name; primaryKey.PrimaryColumn = tableInfo.GetColumn(primaryKeyMetadata.PrimaryColumn?.Name); MigrateManager.CorrectName(primaryKey); return(primaryKey); }
/// <summary> /// 根据主键查找实体 /// </summary> /// <param name="id">主键</param> /// <returns></returns> public T GetEntityById(object id) { ScopeList lstScope = new ScopeList(); PrimaryKeyInfo info = id as PrimaryKeyInfo; if (info == null) { lstScope.AddEqual(CurEntityInfo.PrimaryProperty[0].PropertyName, id); } else { info.FillScope(CurEntityInfo.PrimaryProperty, lstScope, true); } return(GetUnique(lstScope)); }
public string GetIdentityStatement(PrimaryKeyInfo primaryKeyInfo) { var statement = new StringBuilder(); if (primaryKeyInfo.Column.PropertyType == typeof(long)) { statement.Append("SELECT CAST(ISNULL(SCOPE_IDENTITY(), 0) AS BIGINT) AS ID"); } else if (primaryKeyInfo.Column.PropertyType == typeof(int)) { statement.Append("SELECT CAST(ISNULL(SCOPE_IDENTITY(), 0) AS INT) AS ID"); } else if (primaryKeyInfo.Column.PropertyType == typeof(Guid)) { statement.AppendFormat("SELECT CAST(ISNULL(SCOPE_IDENTITY(), '{0}') AS UNIQUEIDENTIFIER) AS ID", Guid.Empty); } return(statement.ToString()); }
/// <summary> /// 根据ID获取记录 /// </summary> /// <param name="id">ID</param> /// <param name="isSearchByCache">是否缓存搜索</param> /// <returns></returns> public T GetObjectById(object id, bool isSearchByCache) { ParamList list = null; T ret = default(T); list = new ParamList(); string tabName = CurEntityInfo.DBInfo.CurrentDbAdapter.FormatTableName(CurEntityInfo.TableName); ScopeList lstScope = new ScopeList(); lstScope.UseCache = isSearchByCache; PrimaryKeyInfo pkInfo = id as PrimaryKeyInfo; if (pkInfo == null) { lstScope.AddEqual(CurEntityInfo.PrimaryProperty[0].PropertyName, id); } else { pkInfo.FillScope(CurEntityInfo.PrimaryProperty, lstScope, true); } SelectCondition sc = GetSelectContant(list, lstScope, GetSelectParams(lstScope)); //sql.Append( DataAccessCommon.FillCondition(CurEntityInfo,list, lstScope)); Dictionary <string, bool> cacheTables = null; if (lstScope.UseCache) { cacheTables = _oper.DBInfo.QueryCache.CreateMap(CurEntityInfo.TableName); } using (IDataReader reader = _oper.Query(sc.GetSql(lstScope.UseCache), list, cacheTables)) { if (reader.Read()) { ret = LoadFromReader(reader); } } return(ret); }
/// <summary> /// Returns a string-string dictionary which can be directly bound to ASP.NET dropdowns etc. (see https://stackoverflow.com/a/805610/795690). /// </summary> /// <param name="orderBy">Order by, defaults to primary key</param> /// <param name="cancellationToken">Async <see cref="CancellationToken"/></param> /// <returns></returns> override public async Task <IDictionary <string, string> > KeyValuesAsync(CancellationToken cancellationToken, string orderBy = "") { if (IsGeneric) { // TO DO: Make sure this works even when there is mapping var db = new MightyOrm(null, TableName, PrimaryKeyInfo.PrimaryKeyColumn, ValueColumn, connectionProvider: new PresetsConnectionProvider(ConnectionString, Factory, Plugin.GetType())); return(await db.KeyValuesAsync(cancellationToken, orderBy)); } string partialMessage = $" to call {nameof(KeyValuesAsync)}, please provide one in your constructor"; string valueColumn = CheckGetValueColumn(partialMessage); string pkColumn = PrimaryKeyInfo.CheckGetKeyColumn(partialMessage); var results = await AllAsync(cancellationToken, orderBy : orderBy ?? pkColumn, columns : $"{pkColumn}, {valueColumn}"); // Convert results to required format var retval = new Dictionary <string, string>(); await results.ForEachAsync(result => { var expando = result as ExpandoObject; var item = expando.ToDictionary(); retval.Add(item[pkColumn].ToString(), item[valueColumn].ToString()); }); return(retval); }
/// <summary> /// /// </summary> /// <param name="table"></param> /// <returns></returns> private PrimaryKeyInfo GetPrimaryKeyInfo(EFTableInfo table) { var primary = table.Entity.FindPrimaryKey(); var primaryRelational = primary?.Relational(); if (primaryRelational == null) { return(null); } var result = new PrimaryKeyInfo(); result.Name = primaryRelational.Name; result.Table = table; var prop = primary.Properties?.FirstOrDefault(); var name = prop?.Relational()?.ColumnName; result.PrimaryColumn = table.GetColumn(name); _migrateManager.CorrectName(result); return(result); }
private static List <T> CheckPrimarySearch <T>(EditorWindow window, TableConfig tableConfig, List <T> dataList) { List <T> tempList = new List <T>(); PrimaryKeyInfo primaryKeyInfo = TSDatabaseUtils.PrimaryKeySerializeData.PrimaryKeyDic[tableConfig.TableName]; for (int i = 0; i < dataList.Count; i++) { window.ShowNotification(new GUIContent("正在搜索...")); T data = dataList[i]; string temp = data.GetType().GetField(tableConfig.PrimaryKey).GetValue(data).ToString(); if (primaryKeyInfo.Values.ContainsKey(temp)) { if (primaryKeyInfo.Values[temp] != 1) { tempList.Add(data); } } else { tempList.Add(data); } } return(tempList.ToList()); }
private static PrimaryKeyInfo GetPrimaryKey(SqlConnection con, string tableName) { var cmdPrimaryKeys = new SqlCommand { CommandText = MyQueries.GetPrimaryKeyQuery(tableName), CommandType = CommandType.Text, Connection = con }; var drPrimaryKeys = cmdPrimaryKeys.ExecuteReader(); PrimaryKeyInfo primaryKey = new PrimaryKeyInfo(); if (drPrimaryKeys.Read()) { primaryKey = new PrimaryKeyInfo { PkName = drPrimaryKeys[0].ToString(), TableName = drPrimaryKeys[1].ToString(), ColumnName = drPrimaryKeys[2].ToString() }; } drPrimaryKeys.Close(); return(primaryKey); }
public override IList<Data.Database.PrimaryKeyInfo> GetPrimaryKeys(string tbl_name) { var ret = new List<PrimaryKeyInfo>(); var sql = "SELECT c.name " + "FROM sys.columns c " + " LEFT JOIN sys.index_columns ic " + " ON ic.object_id = c.object_id AND ic.column_id = c.column_id " + " LEFT JOIN sys.indexes i " + " ON ic.object_id = i.object_id AND ic.index_id = i.index_id " + "WHERE c.object_id = OBJECT_ID('"+tbl_name+"') AND i.is_primary_key = 1"; var rows = this.ExecuteQuery(sql); foreach (var row in rows) { var ci = new PrimaryKeyInfo() { Column = (string)row["name"] }; ret.Add(ci); } return ret; }
/// <summary> /// /// </summary> /// <param name="primaryKey"></param> public virtual void SetPrimaryKey(PrimaryKeyInfo primaryKey) { PrimaryKey = primaryKey; }
private void CheckPlayerData() { for (int i = 0; i < TSDatabaseUtils.TableConfigSerializeData.TableConfigList.Count; i++) { if (TSDatabaseUtils.TableConfigSerializeData.TableConfigList[i].TableName == "Test") { _tableConfig = TSDatabaseUtils.TableConfigSerializeData.TableConfigList[i]; break; } } if (string.IsNullOrEmpty(_tableConfig.DataPath)) { string path = EditorUtility.SaveFilePanelInProject(LanguageUtils.CommonSaveFile, _tableConfig.TableName + ".asset", "asset", ""); if (string.IsNullOrEmpty(path)) { if (EditorUtility.DisplayDialog(LanguageUtils.CommonSaveFailed, LanguageUtils.CommonNullPath, "OK")) { return; } } _tableConfig.DataPath = path; _serializeData = ScriptableObject.CreateInstance <TestSerializeData>(); TSDatabaseUtils.PrimaryKeySerializeData.PrimaryKeyDic.Add(_tableConfig.TableName, new PrimaryKeyInfo()); _primaryKeyInfo = TSDatabaseUtils.PrimaryKeySerializeData.PrimaryKeyDic[_tableConfig.TableName]; _primaryKeyInfo.TableName = _tableConfig.TableName; _primaryKeyInfo.PrimaryKey = _tableConfig.PrimaryKey; _primaryKeyInfo.PrimaryType = _tableConfig.PrimaryType; _primaryKeyInfo.Values = new Dictionary <string, int>(); TSDatabaseUtils.SavaGlobalData(); AssetDatabase.CreateAsset(_serializeData, path); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); } else { _serializeData = AssetDatabase.LoadAssetAtPath <TestSerializeData>(_tableConfig.DataPath); _primaryKeyInfo = TSDatabaseUtils.PrimaryKeySerializeData.PrimaryKeyDic[_tableConfig.TableName]; if (_tableConfig.PrimaryKey != _primaryKeyInfo.PrimaryKey) { //更换主键 _primaryKeyInfo.TableName = _tableConfig.TableName; _primaryKeyInfo.PrimaryKey = _tableConfig.PrimaryKey; _primaryKeyInfo.PrimaryType = _tableConfig.PrimaryType; _primaryKeyInfo.Values = new Dictionary <string, int>(); for (int i = 0; i < _serializeData.DataList.Count; i++) { string value = _serializeData.DataList[i].Id.ToString(); if (!_primaryKeyInfo.Values.ContainsKey(value)) { _primaryKeyInfo.Values.Add(value, 1); } else { _primaryKeyInfo.Values[value]++; } } TSDatabaseUtils.SavaGlobalData(); } } _dataList = new List <Test>(); _dataList.AddRange(_serializeData.DataList); }
public void DropPrimaryKey(PrimaryKeyInfo pk) { _database.FindTable(pk.OwnerTable).DropConstraint(pk); }
public void CreatePrimaryKey(PrimaryKeyInfo pk) { _database.FindTable(pk.OwnerTable).AddConstraint(pk); }
/// <summary> /// /// </summary> /// <param name="primaryKey"></param> protected virtual void CreatePrimaryKey(PrimaryKeyInfo primaryKey) { PrimaryKeyCommand <ICreatePrimaryKeyCommand>(primaryKey); }
/// <summary> /// /// </summary> /// <param name="primaryKey"></param> protected virtual void DropPrimaryKey(PrimaryKeyInfo primaryKey) { PrimaryKeyCommand <IDropPrimaryKeyCommand>(primaryKey); }
public static void CreateAndAddInputParameterForPrimaryKeyValue(this IDbCommand command, TableInfo tableinfo, PrimaryKeyInfo primaryKeyInfo, object value) { var parameter = command.CreateParameter(); parameter.Direction = ParameterDirection.Input; parameter.ParameterName = primaryKeyInfo.GetPrimaryKeyName(); parameter.DbType = primaryKeyInfo.DbType; parameter.Value = tableinfo.CoalesceValue(value); TryAddParameterToCollection(command, parameter); }
public ICdlWriter CreateWriter(TableInfo inputRowFormat, CopyTableTargetOptions options, IShellContext context, DataFormatSettings sourceDataFormat) { var connection = GetConnectionProvider(context); using (var conn = connection.Connect()) { var db = new DatabaseInfo(); db.LinkedInfo = LinkedInfo; var tbl = inputRowFormat.CloneTable(db); tbl.FullName = GetFullName(context); foreach (var col in tbl.Columns) { col.AutoIncrement = false; } tbl.ForeignKeys.Clear(); if (tbl.PrimaryKey != null) { tbl.PrimaryKey.ConstraintName = null; } tbl.AfterLoadLink(); if (IdentityColumn != null) { var col = new ColumnInfo(tbl); col.Name = IdentityColumn; col.DataType = "int"; col.AutoIncrement = true; col.NotNull = true; var pk = new PrimaryKeyInfo(tbl); pk.Columns.Add(new ColumnReference { RefColumn = col }); pk.ConstraintName = "PK_" + tbl.Name; tbl.PrimaryKey = pk; tbl.Columns.Insert(0, col); } //var sw = new StringWriter(); var so = new ConnectionSqlOutputStream(conn, null, connection.Factory.CreateDialect()); var dmp = connection.Factory.CreateDumper(so, new SqlFormatProperties()); if (DropIfExists) { dmp.DropTable(tbl, true); } bool useExistingTable = false; if (UseIfExists) { var ts = context.GetDatabaseStructure(connection.ProviderString); useExistingTable = ts.FindTableLike(tbl.FullName.Schema, tbl.FullName.Name) != null; } if (!useExistingTable) { tbl.Columns.ForEach(x => x.EnsureDataType(connection.Factory.CreateSqlTypeProvider())); dmp.CreateTable(tbl); } //using (var cmd = conn.CreateCommand()) //{ // cmd.CommandText = sw.ToString(); // cmd.ExecuteNonQuery(); //} return(new TableWriter(context, connection, GetFullName(context), inputRowFormat, options, useExistingTable ? null : tbl, LinkedInfo, sourceDataFormat)); } }