Пример #1
0
 public long Insert(IDbObject dbObject, IsolationLevel?isolationLevel)
 {
     using (var connection = connectionManager.GetUpdateConnection())
     {
         if (isolationLevel != null)
         {
             var transaction = connection.BeginTransaction();
             try
             {
                 var result = dbFunctionHelper.Insert(dbObject, connection, new Dictionary <IDbObject, long>());
                 transaction.Commit();
                 return(result);
             }
             catch (Exception e)
             {
                 transaction.Rollback();
                 throw new ApplicationException(e.ToString());
             }
         }
         else
         {
             return(dbFunctionHelper.Insert(dbObject, connection, new Dictionary <IDbObject, long>()));
         }
     }
 }
Пример #2
0
        public override void Update(IDbObject obj)
        {
            var o = (DbObjectSmartUpdate)obj;

            o.RaiseUpdating();
            base.InnerUpdate(o);
        }
        public IList<Column> GetColumns(IDbObject parent)
        {
            IList<Column> result = null;

            if (parent is Table)
            {
                result = this.queryForTableColumns(parent as Table);
            }

            if (parent is View)
            {
                result = this.queryForViewColumns(parent as View);
            }

            if (parent is TableFunction)
            {
                result = this.queryForFunctionColumns(parent as TableFunction);
            }

            if (result != null && result.Count > 0)
            {
                for (int i = 0; i < result.Count; i++)
                {
                    result[i].Parent = parent;
                }
            }

            return result;
        }
Пример #4
0
        private static IDbJoin MakeJoin(IDbSelect ownerSelect, IDbObject tempSelect, IDbObjectFactory dbFactory, UniqueNameGenerator nameGenerator)
        {
            var joinAlias = nameGenerator.GenerateAlias(ownerSelect, TranslationConstants.SubSelectPrefix);
            var joinTo    = dbFactory.BuildRef(tempSelect, joinAlias);

            return(dbFactory.BuildJoin(joinTo, ownerSelect));
        }
Пример #5
0
 private int ProcessRelation(IDbObject obj)
 {
     int ret = 0;
     ret += ProcessHasManyAndHasOne(obj);
     ret += ProcessHasAndBelongsToMany(obj);
     return ret;
 }
Пример #6
0
        public long Insert(IDbObject o, DbConnection connection, IDictionary <IDbObject, long> objectGraph)
        {
            var type             = o.GetType();
            var dbFunctionHelper = GetDbFunctionHelper(type);

            return(dbFunctionHelper.Insert(o, connection, objectGraph));
        }
Пример #7
0
        public bool CheckOut(string Login, IDbObject dbObject, out string ErrorMsg)
        {
            TeamCodingFile file = ReadFile();

            CheckSettings(file);
            CheckOutObject CheckOutbject = new CheckOutObject()
            {
                Login        = _Settings.TEAMCODING_LOGIN,
                ServerName   = _ServerName,
                ObjectOwner  = dbObject.ObjectOwner,
                ObjectName   = dbObject.ObjectName,
                ObjectType   = dbObject.ObjectType,
                CheckoutDate = DateTime.Now
            };

            if (!_TeamCodingChecks.ChecksBeforeCheckOut(file.CheckOutObjectsList, CheckOutbject, out ErrorMsg))
            {
                return(false);
            }

            var list    = file.CheckOutObjectsList.ToArray();
            var listLen = list.Length;

            Array.Resize(ref list, listLen + 1);
            list[listLen] = CheckOutbject;

            file.CheckOutObjectsList = list.ToEnumerable();
            SaveFile(file);
            return(true);
        }
Пример #8
0
 public virtual IDbStatment BuildStatement(IDbObject script)
 {
     return(new SqlStatement(script)
     {
         OutputOption = OutputOption
     });
 }
Пример #9
0
        private void UpdateSelection(IDbSelect fromSelect, IDbObject selection, DbReference toSelectRef)
        {
            var dbList = selection as IEnumerable <DbKeyValue>;

            if (dbList != null)
            {
                foreach (var dbObj in dbList)
                {
                    UpdateSelection(fromSelect, dbObj, toSelectRef);
                }
                return;
            }

            var keyValue = selection as DbKeyValue;

            selection = keyValue != null ? keyValue.Value : selection;

            var selectable = GetSelectable(fromSelect, selection, toSelectRef);

            if (keyValue != null)
            {
                selectable.Alias = keyValue.Key;
            }

            fromSelect.Selection.Add(selectable);
        }
Пример #10
0
 public virtual object Insert(IDbObject obj)
 {
     var sb = Composer.GetInsertStatementBuilder(obj);
     var sql = sb.ToSqlStatement(Provider.Dialect, null);
     Provider.ExecuteNonQuery(sql);
     return null;
 }
Пример #11
0
        private void PopulateComboBoxStupac(IDbObject knjigaVrsta)
        {
            GenericPropertyFinder <IDbObject> property = new GenericPropertyFinder <IDbObject>();
            IEnumerable <List <string> >      obj      = property.PrintTModelPropertyAndValue(knjigaVrsta);

            comboBoxStupac.DataSource = obj.ElementAt(0);
        }
Пример #12
0
 public BuilderFrameF3(IDbObject idbobj, string dbName, string tableName, string tableDescription, string modelName, string bllName, string dalName, List <ColumnInfo> fieldlist, List <ColumnInfo> keys, string nameSpace, string folder, string dbHelperName)
 {
     this.dbobj            = idbobj;
     this._dbtype          = idbobj.DbType;
     base.DbName           = dbName;
     base.TableName        = tableName;
     base.TableDescription = tableDescription;
     base.ModelName        = modelName;
     base.BLLName          = bllName;
     base.DALName          = dalName;
     base.NameSpace        = nameSpace;
     base.DbHelperName     = dbHelperName;
     base.Folder           = folder;
     base.Fieldlist        = fieldlist;
     base.Keys             = keys;
     foreach (ColumnInfo current in keys)
     {
         this._key     = current.ColumnName;
         this._keyType = current.TypeName;
         if (current.IsIdentity)
         {
             this._key     = current.ColumnName;
             this._keyType = CodeCommon.DbTypeToCS(current.TypeName);
             break;
         }
     }
 }
Пример #13
0
        internal void PrepareDataIzvod(DataTable dt, IDbObject obj)
        {
            Izvod izvod = (Izvod)obj;

            dt.Rows.Add(
                izvod.Redni_broj,
                "Izvod",
                "Žiro račun: Izvod broj " + izvod.Redni_broj,
                "1000",
                izvod.Datum_izvoda.Split(' ')[0],
                true,
                true,
                false
                );
            foreach (var stavka in izvod.Promet)
            {
                dt.Rows.Add(
                    izvod.Redni_broj,
                    stavka.Naziv,
                    stavka.Opis,
                    stavka.Konto,
                    izvod.Datum_izvoda.Split(' ')[0],
                    stavka.Oznaka == "D",
                    stavka.Oznaka == "P",
                    false
                    );
            }
        }
Пример #14
0
        public DbKeyValue(string key, IDbObject val)
        {
            Key   = key;
            Value = val;

            OutputOption = val?.OutputOption;
        }
Пример #15
0
        private void tvwObjects_MouseDown(object sender, MouseEventArgs e)
        {
            var hitTest = tvwObjects.HitTest(e.X, e.Y);

            _selectedObject = hitTest.Node as ColumnContainerNode;
            _object         = hitTest.Node as IDbObject;

            bool viewDef = false;

            if (_object != null)
            {
                viewDef = _object.DbObject is IDefinition;
            }

            viewDefinitionToolStripMenuItem.Enabled = viewDef;

            findTable(hitTest.Node);

            void findTable(TreeNode node)
            {
                if (node == null)
                {
                    return;
                }
                _selectedTable = node as TableNode;
                if (_selectedTable == null && node.Parent != null)
                {
                    findTable(node.Parent);
                }
            }
        }
Пример #16
0
 public BuilderDAL(IDbObject idbobj, string dbname, string tablename, string modelname, string dalName,
                   List <ColumnInfo> fieldlist, List <ColumnInfo> keys, string namepace,
                   string folder, string dbherlpername, string modelpath,
                   string dalpath, string idalpath, string iclass)
 {
     dbobj         = idbobj;
     _dbname       = dbname;
     _tablename    = tablename;
     _modelname    = modelname;
     _dalname      = dalName;
     _namespace    = namepace;
     _folder       = folder;
     _dbhelperName = dbherlpername;
     _modelpath    = modelpath;
     _dalpath      = dalpath;
     _idalpath     = idalpath;
     _iclass       = iclass;
     Fieldlist     = fieldlist;
     Keys          = keys;
     foreach (ColumnInfo key in _keys)
     {
         _key     = key.ColumnName;
         _keyType = key.TypeName;
         if (key.IsIdentity)
         {
             _key     = key.ColumnName;
             _keyType = CodeCommon.DbTypeToCS(key.TypeName);
             break;
         }
     }
 }
Пример #17
0
 public BuilderFrameS3(IDbObject idbobj, string dbName, string tableName, string modelName, string bllName, string dalName,
                       List <ColumnInfo> fieldlist, List <ColumnInfo> keys,
                       string nameSpace, string folder, string dbHelperName)
 {
     dbobj        = idbobj;
     _dbtype      = idbobj.DbType;
     DbName       = dbName;
     TableName    = tableName;
     ModelName    = modelName;
     BLLName      = bllName;
     DALName      = dalName;
     NameSpace    = nameSpace;
     DbHelperName = dbHelperName;
     Folder       = folder;
     Fieldlist    = fieldlist;
     Keys         = keys;
     foreach (ColumnInfo key in keys)
     {
         _key     = key.ColumnName;
         _keyType = key.TypeName;
         if (key.IsIdentity)
         {
             _key     = key.ColumnName;
             _keyType = CodeCommon.DbTypeToCS(key.TypeName);
             break;
         }
     }
     //model = new BuilderModel(dbobj, DbName, TableName, ModelName, NameSpace, Folder, Modelpath, fieldlist);
 }
        public void UpdateFrom(IDbObject obj)
        {
            var q = obj as Plan;

            Name = q.Name;
            Id   = q.Id;
        }
        public void UpdateFrom(IDbObject obj)
        {
            var q = obj as Client;

            Name     = q.Name;
            ImageUrl = q.ImageUrl;
        }
Пример #20
0
        public void UpdateFrom(IDbObject obj)
        {
            var q = obj as CheckList;

            Title       = q.Title;
            Description = q.Description;
        }
Пример #21
0
        public override void Translate(
            MethodCallExpression m, TranslationState state, UniqueNameGenerator nameGenerator)
        {
            // there may not be a preidcate in any method call
            IDbObject condition = null;

            if (m.GetArguments().Any())
            {
                condition = state.ResultStack.Pop();
            }

            var childSelect = (IDbSelect)state.ResultStack.Pop();
            var dbSelect    = (IDbSelect)state.ResultStack.Peek();

            childSelect.Where = condition.ToBinary(_dbFactory);

            var dbJoin = dbSelect.Joins.Single(j => ReferenceEquals(j.To.Referee, childSelect));

            IDbBinary whereClause = null;

            // ReSharper disable once LoopCanBeConvertedToQuery
            foreach (var joinKey in dbJoin.Condition.GetOperands().OfType <IDbColumn>().Where(c => ReferenceEquals(c.Ref, dbJoin.To)))
            {
                var pkColumn = _dbFactory.BuildColumn(dbJoin.To, joinKey.Name, joinKey.ValType.DotNetType, joinKey.Alias);
                var binary   = _dbFactory.BuildBinary(pkColumn, DbOperator.IsNot, _dbFactory.BuildConstant(null));

                whereClause = whereClause.UpdateBinary(binary, _dbFactory);
            }

            state.ResultStack.Push(whereClause);
        }
Пример #22
0
 public BuilderDAL(IDbObject idbobj, string dbname, string tablename, string modelname, string dalName, List <ColumnInfo> fieldlist, List <ColumnInfo> keys, string namepace, string folder, string dbherlpername, string modelpath, string dalpath, string idalpath, string iclass)
 {
     this.dbobj         = idbobj;
     this._dbname       = dbname;
     this._tablename    = tablename;
     this._modelname    = modelname;
     this._dalname      = dalName;
     this._namespace    = namepace;
     this._folder       = folder;
     this._dbhelperName = dbherlpername;
     this._modelpath    = modelpath;
     this._dalpath      = dalpath;
     this._idalpath     = idalpath;
     this._iclass       = iclass;
     this.Fieldlist     = fieldlist;
     this.Keys          = keys;
     foreach (ColumnInfo current in this._keys)
     {
         this._key     = current.ColumnName;
         this._keyType = current.TypeName;
         if (current.IsIdentity)
         {
             this._key     = current.ColumnName;
             this._keyType = CodeCommon.DbTypeToCS(current.TypeName);
             break;
         }
     }
 }
Пример #23
0
        public virtual void Modify()
        {
            try
            {
                if (this.EditorT != null)
                {
                    DateTime time1 = DateTime.Now;

                    BaseEditor editor = System.Activator.CreateInstance(this.EditorT) as BaseEditor;
                    DateTime   time2  = DateTime.Now;
                    editor.ShowInTaskbar = false;
                    editor.StartPosition = FormStartPosition.CenterScreen;
                    IDbObject obj = gGrid1.GetCurSelect <IDbObject>();
                    editor.KeyId = G.Core.GConvert.ToInt(G.Core.ClassHelper.GetFieldValue(obj, "Id"));

                    var audit = G.Core.ClassHelper.GetFieldValue(obj, AuditField) != null?G.Core.ClassHelper.GetFieldValue(obj, AuditField).ToString() : "";

                    if (audit == "A")
                    {
                        editor.CurEditStatus = EditorStatus.Look;
                    }
                    else
                    {
                        editor.CurEditStatus = EditorStatus.Modify;
                    }
                    string info = (time2 - time1).TotalSeconds.ToString();
                    G.AppInfo.GGlobal.SetInfo(info);
                    editor.ShowDialog();
                    RefreshData();
                }
            }
            catch (Exception e) { MessageBox.Show(e.Message); }
        }
Пример #24
0
        public override void Translate(MethodCallExpression m, TranslationState state, UniqueNameGenerator nameGenerator)
        {
            MemberExpression member   = (m.Object ?? m.Arguments[0]) as MemberExpression;
            IDbObject        dbBinary = null;

            if (member.Type == typeof(string))
            {
                var dbConstants = (IDbConstant)state.ResultStack.Pop();
                dbConstants.Val = $"%{dbConstants.Val}%";

                var dbExpression = (IDbSelectable)state.ResultStack.Pop();
                dbBinary = _dbFactory.BuildBinary(dbExpression, DbOperator.Like, dbConstants);
            }
            else if (member.Type.IsArray)
            {
                var dbConstants = (IDbConstant)state.ResultStack.Pop();

                var dbExpression = (IDbSelectable)state.ResultStack.Pop();
                var dbFunc       = _dbFactory.BuildFunc(SqlTranslationHelper.GetSqlOperator(DbOperator.Any), false, m.Method.ReturnType, dbExpression);
                dbBinary = _dbFactory.BuildBinary(dbConstants, DbOperator.Equal, dbFunc);
            }
            else
            {
                throw new NotSupportedException($"Type {member.Type} is not supported");
            }

            state.ResultStack.Push(dbBinary);
        }
        public IList <Column> GetColumns(IDbObject parent)
        {
            IList <Column> result = null;

            if (parent is Table)
            {
                result = this.queryForTableColumns(parent as Table);
            }

            if (parent is View)
            {
                result = this.queryForViewColumns(parent as View);
            }

            if (parent is TableFunction)
            {
                result = this.queryForFunctionColumns(parent as TableFunction);
            }

            if (result != null && result.Count > 0)
            {
                for (int i = 0; i < result.Count; i++)
                {
                    result[i].Parent = parent;
                }
            }

            return(result);
        }
Пример #26
0
 public DbReference BuildRef(IDbObject dbObj, string alias = null)
 {
     return(new DbReference(dbObj)
     {
         Alias = alias
     });
 }
Пример #27
0
 public BuilderDAL(IDbObject idbobj, string dbname, string tablename, string modelname, string dalName,
     List<ColumnInfo> fieldlist, List<ColumnInfo> keys, string namepace,
     string folder, string dbherlpername, string modelpath, string modelspace,
     string dalpath, string idalpath, string iclass)
 {
     dbobj = idbobj;
     _dbname = dbname;
     _tablename = tablename;
     _modelname = modelname;
     _namespace = namepace;
     _folder = folder;
     _dbhelperName = dbherlpername;
     _modelpath = modelpath;
     _dalpath = dalpath;
     _idalpath = idalpath;
     _iclass = iclass;
     Fieldlist = fieldlist;
     Keys = keys;
     foreach (ColumnInfo key in _keys)
     {
         _IdentityKey = key.ColumnName;
         _IdentityKeyType = key.TypeName;
         if (key.IsIdentity)
         {
             _IdentityKey = key.ColumnName;
             _IdentityKeyType = CodeCommon.DbTypeToCS(key.TypeName);
             break;
         }
     }
 }
Пример #28
0
        public CodeBuilders(IDbObject idbobj)
        {
            dbobj  = idbobj;
            DbType = idbobj.DbType;
            if (_dbhelperName == "")
            {
                switch (DbType)
                {
                case "SQL2000":
                case "SQL2005":
                    _dbhelperName = "DbHelperSQL";
                    break;

                case "Oracle":
                    _dbhelperName = "DbHelperOra";
                    break;

                case "MySQL":
                    _dbhelperName = "DbHelperMySQL";
                    break;

                case "OleDb":
                    _dbhelperName = "DbHelperOleDb";
                    break;
                }
            }
        }
Пример #29
0
 private void SetAdditionalDataObject(IDbObject Object, string Name, string Value)
 {
     if (Name == "Location")
     {
         var pi = ParentDbObject.GetType().GetProperty("LocationWindows");
         if (pi == null)
         {
             return;
         }
         if (Value == null)
         {
             return;
         }
         string val   = Value.Replace(':', Path.DirectorySeparatorChar);
         var    dbrdr = (MhbdReader)ParentReader.ParentReader.ParentReader.ParentReader.ParentReader;
         var    db    = (iTunesDb)dbrdr.DbObject;
         int    pos   = db.FileName.IndexOf(@"\iPod_Control\");
         if (pos < 0)
         {
             return;
         }
         string prefix = db.FileName.Substring(0, pos);
         string loc    = prefix + val;
         pi.SetValue(Object, loc, null);
     }
 }
Пример #30
0
 public override object Insert(IDbObject obj)
 {
     var sb = Composer.GetInsertStatementBuilder(obj);
     var key = Provider.Dialect.ExecuteInsert(sb, Info, Provider);
     Handler.SetKeyValue(obj, key);
     return key;
 }
Пример #31
0
        private void listDbObjects_SelectedIndexChanged(object sender, EventArgs e)
        {
            gridColumns.DataSource = null;
            txtSqlScript.Text      = "";

            _selectedObject = listDbObjects.FocusedItem?.Tag as IDbObject;


            txtSqlScript.Text = _selectedObject?.Script ?? "";

            if (DataProvider.ActiveManager.IsTable(_selectedObject))
            {
                gridColumns.DataSource = DataProvider.ActiveManager.Table(_selectedObject).Columns?.Tables[0];
                tabControl.SelectedTab = tabControl.TabPages[0];

                GridHighlithRow();
            }
            if (DataProvider.ActiveManager.IsView(_selectedObject))
            {
                tabControl.SelectedTab = tabControl.TabPages[1];
            }
            if (DataProvider.ActiveManager.IsStoredProcedure(_selectedObject))
            {
                tabControl.SelectedTab = tabControl.TabPages[1];
            }
        }
Пример #32
0
        public string Insert(IDbObject o, TimeSpan time, bool isRelative, ObjectRemoved removeDelegate)
        {
            string key = o.Id + "_" + o.GetType().Name;

            cache.Insert(key, o, time, isRelative, removeDelegate);
            return(ownIp + "_" + key);
        }
Пример #33
0
        public override object Insert(IDbObject obj)
        {
            object key = null;

            ProcessRelation(obj, () => key = InnerInsert(obj));
            return(key);
        }
Пример #34
0
        public virtual void Audit()
        {
            try
            {
                if (this.EditorT != null)
                {
                    DateTime   time1  = DateTime.Now;
                    BaseEditor editor = System.Activator.CreateInstance(this.EditorT) as BaseEditor;
                    editor.ShowInTaskbar = false;
                    editor.StartPosition = FormStartPosition.CenterScreen;
                    IDbObject obj = gGrid1.GetCurSelect <IDbObject>();
                    editor.KeyId = G.Core.GConvert.ToInt(G.Core.ClassHelper.GetFieldValue(obj, "Id"));
                    var audit = G.Core.ClassHelper.GetFieldValue(obj, AuditField) != null?G.Core.ClassHelper.GetFieldValue(obj, AuditField).ToString() : "";

                    editor.CurEditStatus = EditorStatus.Audit;
                    editor.listTool      = new List <string>()
                    {
                        "预览", "打印", "|", "审核", "反审", "|", "退出"
                    };

                    DateTime time2 = DateTime.Now;
                    G.AppInfo.GGlobal.SetInfo((time2 - time1).TotalSeconds.ToString());
                    editor.ShowDialog();
                    RefreshData();
                }
            }
            catch (Exception e) { MessageBox.Show(e.Message); }
        }
Пример #35
0
        public override int Delete(IDbObject obj)
        {
            var n = base.Delete(obj);

            CacheProvider.Instance.Remove(KeyGenerator.Instance[obj]);
            return(n);
        }
Пример #36
0
        public override object Insert(IDbObject obj)
        {
            var o = (DbObjectSmartUpdate)obj;
            o.RaiseInserting();
            var key = base.Insert(o);
			o.InitLoadedColumns ();
            return key;
        }
Пример #37
0
 public override int Delete(IDbObject obj)
 {
     int ret = 0;
     DbEntry.UsingTransaction(delegate
     {
         ret += ProcessRelation(obj);
         ret += base.Delete(obj);
     });
     return ret;
 }
Пример #38
0
 private void InnerSave(bool isInsert, IDbObject obj)
 {
     if (isInsert)
     {
         Insert(obj);
     }
     else
     {
         Update(obj);
     }
 }
Пример #39
0
 private int ProcessHasAndBelongsToMany(IDbObject obj)
 {
     int ret = 0;
     foreach (CrossTable mt in Info.CrossTables.Values)
     {
         var sb = new DeleteStatementBuilder(mt.Name);
         sb.Where.Conditions = CK.K[mt[0].Column] == Handler.GetKeyValue(obj);
         var sql = sb.ToSqlStatement(Provider.Dialect, Info.QueryRequiredFields, Info.AllowSqlLog);
         ret += Provider.ExecuteNonQuery(sql);
     }
     return ret;
 }
		public int Update(IDbObject o, DbConnection connection, IDictionary<IDbObject, long> objectGraph)
		{
			objectGraph.Add(o, o.Id);
			var classMetadata = ClassMetaDataManager.Instace.GetClassMetaData(o.GetType());
			var result = 0;
			if (o.IsDirty)
			{
				o.IsDirty = false;
				var mappingTable = classMetadata.MappingTable;
				var properties = classMetadata.Properties;
				var command = connection.CreateCommand();
				var queryBuilder = new StringBuilder("UPDATE " + mappingTable + " SET ");
				foreach (var mappingInfo in properties.Values)
				{
					var mappingField = mappingInfo.MappingField;
					queryBuilder.Append("`" + mappingField + "`=@" + mappingField + ", ");
				}
				var tmpString = queryBuilder.ToString(0, queryBuilder.Length - 2);
				queryBuilder.Length = 0;
				queryBuilder.Append(tmpString);
				queryBuilder.Append(" WHERE Id = " + o.Id);
				command.CommandText = queryBuilder.ToString();
				foreach (var mappingInfo in properties.Values)
				{
					var mappingField = mappingInfo.MappingField;
					var propertyInfo = mappingInfo.PropertyInfo;
					var propertyType = propertyInfo.PropertyType;
					object value = propertyInfo.GetValue(o, null);
					if (propertyType.IsPrimitive || propertyType == typeof(string) || propertyType == typeof(DateTime) || propertyType == typeof(decimal))
					{
						command.Parameters.Add(new MySqlParameter("@" + mappingField, value));
					}
					else
					{
						byte[] blob = null;
						if (value != null)
						{
							var formatter = new BinaryFormatter();
							using (var stream = new MemoryStream())
							{
								formatter.Serialize(stream, value);
								blob = stream.ToArray();
							}	
						}
						command.Parameters.Add(new MySqlParameter("@" + mappingField, blob));
					}
				}
				result = command.ExecuteNonQuery();
			}
			UpdateRelations(o, classMetadata, connection, objectGraph);
			return result;
		}
Пример #41
0
        public void ProcessDatabaseSchema(IDbObject dbInfo, IDbInfoProcessor dbInfoProcessor)
        {
            if (null == dbInfo)
            {
                throw new ArgumentNullException("dbInfo", "Invalid IDbObject instance!");
            }
            if (null == dbInfoProcessor)
            {
                throw new ArgumentNullException("dbInfoProcessor", "Invalid IDbInfoProcessor instance!");
            }

            dbInfoProcessor.Process(dbInfo);
        }
Пример #42
0
 private object InnerInsert(IDbObject obj)
 {
     SaveBelongsTo(obj);
     var key = base.Insert(obj);
     foreach (var t2 in Info.CrossTables.Keys)
     {
         var stk = Scope<SavedTypeKey>.Current;
         if (stk != null && t2 == stk.Type)
         {
             SetManyToManyRelation(t2, key, stk.Key);
         }
     }
     ProcessChildren(obj);
     return key;
 }
Пример #43
0
        public void Insert(object key, IDbObject value, TimeSpan time, bool isRelative, ObjectRemoved removeDelegate)
        {
			string valueKey = key.ToString() + "_" + value.GetType().Name;
			string id = cacheLocal.Get(valueKey);
			if (id != null)
			{
				string[] str = id.Split(new char[] { '_' }, 1);
				string host = str[0];
				ServiceCacheProxy cacheProxy = cacheProxies[host];
				if (cacheProxy != null)
				{
					cacheProxy.BeginInsert(FinishInsert, new object[] { valueKey, time, isRelative, removeDelegate },value, time, isRelative, null);
				}
			}
			//TODO insert
			
        }
        private IList<string> getIndexColumnNames(Index index, IDbObject parent)
        {
            var sql = new Sql(@"SELECT C.[name]

                            FROM sys.indexes AS I
             	                            INNER JOIN sys.index_columns AS IC
                                    ON ( I.index_id = IC.index_id AND I.object_id = IC.object_id )
                                INNER JOIN sys.columns AS C
                                    ON ( C.object_id = IC.object_id AND C.column_id = IC.column_id )

                            WHERE I.object_id = @0
                                AND I.index_id = @1

                            ORDER BY IC.key_ordinal, C.[name];", parent.ObjectId, index.IndexId);

            return this.peta.Fetch<string>(sql);
        }
Пример #45
0
		protected void Update(IDbObject obj, Action callback)
		{
			var iwc = ModelContext.GetKeyWhereClause(obj);
			SqlStatement updateStatement = Composer.GetUpdateStatement(obj, iwc);
			if (updateStatement != null) {
				if (callback != null) {
					callback ();
				}
				if (Provider.ExecuteNonQuery(updateStatement) == 0)
				{
					throw new DataException("Record doesn't exist OR LockVersion doesn't match!");
				}
				Composer.ProcessAfterSave(obj);
				var o = obj as DbObjectSmartUpdate;
				if (o != null) {
					o.InitLoadedColumns ();
				}
			}
		}
        public IList<Index> GetIndexes(IDbObject parent)
        {
            IList<Index> indexList = null;

            indexList = this.getTableOrViewIndexes(parent);

               			//lookup columns
            if (indexList != null && indexList.Count > 0)
            {
                for (int i = 0; i < indexList.Count; i++)
                {
                    indexList[i].ColumnNames = this.getIndexColumnNames(indexList[i], parent);
                    indexList[i].Parent = parent;
                }

            }

            return indexList;
        }
Пример #47
0
 private int ProcessHasManyAndHasOne(IDbObject obj)
 {
     var result = 0;
     foreach (var member in Info.RelationMembers)
     {
         if (member.Is.HasMany || member.Is.HasOne)
         {
             var t = member.MemberInfo.MemberType.GetGenericArguments()[0];
             var ctx0 = ModelContext.GetInstance(t);
             ctx0.Operator.Fixer.TryFix();
             var sb = new UpdateStatementBuilder(ctx0.Info.From);
             var key = ctx0.Info.GetBelongsTo(Info.HandleType).Name;
             sb.Values.Add(new KeyOpValue(key, null, KvOpertation.None));
             sb.Where.Conditions = CK.K[key] == Handler.GetKeyValue(obj);
             var sql = sb.ToSqlStatement(ctx0);
             result += ctx0.Provider.ExecuteNonQuery(sql);
         }
     }
     return result;
 }
        private IList<Index> getTableOrViewIndexes(IDbObject parent)
        {
            var sql = new Sql(@"SELECT I.[name] AS IndexName
                                , I.index_id AS IndexId
                                , EP.value AS [Description]
                                , I.is_unique AS IsUnique
                                , I.is_primary_key AS IsPrimaryKey
                                , I.type_desc AS IndexTypeDescription

                            FROM sys.indexes AS I
                                LEFT OUTER JOIN sys.extended_properties AS EP
                                    ON ( EP.class = 7 AND EP.name = 'MS_Description' AND EP.major_id = I.object_id AND EP.minor_id = I.index_id )

                            WHERE object_id = @0
                                AND I.index_id != 0

                            ORDER BY I.[name];", parent.ObjectId);

            return this.peta.Fetch<Index>(sql);
        }
		private void UpdateRelations(IDbObject o, ClassMetaData classMetadata, DbConnection connection, IDictionary<IDbObject, long> objectGraph)
		{
			var relationProperties = classMetadata.RelationProperties;
			foreach (var relation in relationProperties.Values)
			{
				var propertyInfo = relation.PropertyInfo;
				var mappingTable = relation.MappingTable;
				var persistentRelation = new List<long>();
				var command = connection.CreateCommand();
				string queryField;
				if (relation.RelationKind == RelationInfo.RELATION_N_N)
				{
					command.CommandText = "SELECT `" + relation.PartnerKey + "` FROM " + mappingTable + " WHERE `" + relation.OriginalKey + "` = " + o.Id;
					queryField = relation.PartnerKey;
				}
				else
				{
					command.CommandText = "SELECT Id FROM " + mappingTable + " WHERE `" + relation.OriginalKey + "` = " + o.Id;
					queryField = "Id";
				}
				using (var reader = command.ExecuteReader())
				{
					while (reader.Read())
					{
						persistentRelation.Add(reader.GetInt64(reader.GetOrdinal(queryField)));
					}	
				}
				if (relation.RelationKind == RelationInfo.RELATION_1_1)
				{
					Update11Relation(objectGraph, o, connection, relation, command, mappingTable, persistentRelation, propertyInfo);
				}
				else if (relation.RelationKind == RelationInfo.RELATION_1_N)
				{
					Update1NRelation(objectGraph, o, connection, relation, command, mappingTable, persistentRelation, propertyInfo);					
				}
				else if (relation.RelationKind == RelationInfo.RELATION_N_N)
				{
					UpdateNNRelation(objectGraph, o, connection, relation, command, mappingTable, persistentRelation, propertyInfo);					
				}
			}
		}
Пример #50
0
 public override void Update(IDbObject obj)
 {
     ProcessRelation(obj, () => InnerUpdate(obj));
 }
Пример #51
0
 private void SaveBelongsTo(IDbObject obj)
 {
     foreach (var f in Info.RelationMembers)
     {
         if (f.Is.BelongsTo)
         {
             var ho = (ILazyLoading)f.GetValue(obj);
             if (ho.IsLoaded)
             {
                 object llo = ho.Read();
                 if (llo != null)
                 {
                     RelationSave(llo);
                 }
             }
         }
     }
 }
Пример #52
0
 private static void SetBelongsToForeignKey(IDbObject obj, object subobj, object foreignKey)
 {
     MemberHandler belongsTo = ModelContext.GetInstance(subobj.GetType()).Info.GetBelongsTo(obj.GetType());
     if (belongsTo != null)
     {
         var to = belongsTo.GetValue(subobj) as IBelongsTo;
         if (to != null)
         {
             to.ForeignKey = foreignKey;
         }
     }
 }
Пример #53
0
 private void ProcessChildren(IDbObject obj)
 {
     using (new Scope<SavedTypeKey>(new SavedTypeKey(obj.GetType(), Handler.GetKeyValue(obj))))
     {
         foreach (MemberHandler member in Info.RelationMembers)
         {
             if(member.Is.RelationField)
             {
                 var ho = (ILazyLoading)member.GetValue(obj);
                 if (ho.IsLoaded)
                 {
                     Util.TryEnumerate(ho.Read(),
                         o => SetBelongsToForeignKey(obj, o, Handler.GetKeyValue(obj)));
                 }
             }
         }
         foreach (MemberHandler member in Info.RelationMembers)
         {
             var ho = (ILazyLoading)member.GetValue(obj);
             if (ho.IsLoaded)
             {
                 if (member.Is.HasOne)
                 {
                     ProcessHasOne(ho);
                 }
                 else if (member.Is.HasMany)
                 {
                     ProcessHasMany(ho);
                 }
                 else if (member.Is.HasAndBelongsToMany)
                 {
                     ProcessHasAndBelongsToMany(obj, member, ho);
                 }
             }
         }
     }
 }
Пример #54
0
 private void ProcessHasAndBelongsToMany(IDbObject obj, MemberHandler f, ILazyLoading ho)
 {
     object obj2 = ho.Read();
     if (obj2 != null)
     {
         Util.TryEnumerate(obj2, RelationSave);
     }
     var relations = (IHasAndBelongsToManyRelations)ho;
     foreach (object obj3 in relations.SavedNewRelations)
     {
         SetManyToManyRelation(f.MemberType.GetGenericArguments()[0], Handler.GetKeyValue(obj), obj3);
     }
     foreach (object obj4 in relations.RemovedRelations)
     {
         RemoveManyToManyRelation(f.MemberType.GetGenericArguments()[0], Handler.GetKeyValue(obj), obj4);
     }
 }
Пример #55
0
 /// <summary>
 /// Add new item to child objects collection
 /// </summary>
 /// <param name="newItem">Item to be added</param>
 public void Add(IDbObject newItem)
 {
     Children.Add(newItem);
 }
Пример #56
0
 public override object Insert(IDbObject obj)
 {
     object key = null;
     ProcessRelation(obj, () => key = InnerInsert(obj));
     return key;
 }
 public static void Access(this ISession session, IDbObject obj, AccessType accessType)
 {
     session.Access(new [] {obj}, accessType);
 }
Пример #58
0
 private void InnerUpdate(IDbObject obj)
 {
     SaveBelongsTo(obj);
     base.Update(obj);
     ProcessChildren(obj);
 }
Пример #59
0
 private static void ProcessRelation(IDbObject obj, Action saveObj)
 {
     UsingSavedObjectList(
         () =>
         {
             DbEntry.UsingTransaction(delegate
             {
                 if (!Scope<SavedObjectList>.Current.Contains(obj))
                 {
                     Scope<SavedObjectList>.Current.Add(obj);
                     saveObj();
                 }
             });
         });
 }
Пример #60
0
 /// <summary>
 /// Remove specified item from child objects collection
 /// </summary>
 /// <param name="itemToRemove">Item to be removed</param>
 public void Remove(IDbObject itemToRemove)
 {
     Children.Remove(itemToRemove);
 }