예제 #1
0
 public override void BuildTableAddSql(DbObjectChange change, DbTableInfo table)
 {
     const string SqlTemplate = @"CREATE TABLE {0} (" + "\r\n {1} \r\n); ";
       var specs = table.Columns.Select(c => GetColumnSpec(c)).ToList();
       //Until now it was the same as default impl method in base class. Now we need to add Primary key and Foreign key constraints
       //Primary Key
       var pk = table.PrimaryKey;
       var col0 = pk.KeyColumns[0].Column;
       //Identity Primary Key is taken care of in GetColumnSpec
       // Note: looks like we need to declare identity PK in GetColumnSpec - SQLite is quite tricky in this way
       if (!col0.Flags.IsSet(DbColumnFlags.Identity)) {
     var strKeyCols = pk.KeyColumns.GetSqlNameList();
     var pkSpec = string.Format("PRIMARY KEY({0})", strKeyCols);
     specs.Add(pkSpec);
       }
       //Foreign keys (ref constraints
       foreach(var refC in table.RefConstraints) {
     var strKeyCols = refC.FromKey.KeyColumns.GetSqlNameList();
     //find target table
     var strPkKeyCols = refC.ToKey.KeyColumns.GetSqlNameList();
     var fkSpec = string.Format("FOREIGN KEY({0}) REFERENCES {1}({2})", strKeyCols, refC.ToKey.Table.TableName, strPkKeyCols);
     if(refC.CascadeDelete)
       fkSpec += " ON DELETE CASCADE";
     specs.Add(fkSpec);
       }
       //Build final Table statement
       var columnSpecs = string.Join("," + Environment.NewLine, specs);
       change.AddScript(DbScriptType.TableAdd, SqlTemplate, table.FullName, columnSpecs);
 }
예제 #2
0
 public TableExpression(Type type, string name, DbTableInfo tableInfo, LockOptions lockOptions = LockOptions.None)
     : base(SqlExpressionType.Table, type)
 {
     Vita.Common.Util.Check(type != null, "TableExpression (name: {0}) - type may not be null.", name);
       TableInfo = tableInfo;
       Name = name;
       LockOptions = lockOptions;
 }
예제 #3
0
파일: DbModel.cs 프로젝트: radtek/vita
        public void AddTable(DbTableInfo table)
        {
            var key = table.FullName;

            Util.Check(!_tablesByName.ContainsKey(key), "Duplicate table in DbModel: {0}", table.FullName);
            _tables.Add(table);
            _tablesByName.Add(key, table);
        }
예제 #4
0
 public DbKeyInfo(string name, DbTableInfo table, KeyType type, EntityKeyInfo entityKey = null)
     : base(table.DbModel, table.Schema, DbObjectType.Key, entityKey)
 {
     Name      = name;
     Table     = table;
     KeyType   = type;
     EntityKey = entityKey;
     table.Keys.Add(this);
     base.GlobalName = DbModelHelper.GetGlobalName(table.Schema, name);
 }
예제 #5
0
        public static IList <DbRefConstraintInfo> GetIncomingReferences(this DbTableInfo table)
        {
            if (table == null)
            {
                return(new List <DbRefConstraintInfo>());
            }
            var refs = table.DbModel.Tables.SelectMany(t => t.RefConstraints.Where(r => r.ToKey.Table == table)).ToList();

            return(refs);
        }
예제 #6
0
        private DbColumnInfo CreateDbColumn(DbTableInfo table, EntityMemberInfo member)
        {
            bool   isError    = false;
            var    colName    = member.ColumnName;
            string colDefault = member.ColumnDefault; //comes from attribute

            if (colDefault != null && member.DataType == typeof(string) && !colDefault.StartsWith("'"))
            {
                colDefault = colDefault.Quote();
            }

            var dbTypeInfo = _driver.TypeRegistry.GetDbTypeInfo(member, _log);

            if (dbTypeInfo == null)
            {
                isError = true;
                LogError("Driver failed to match db type for data type {0}, member {1}.{2}", member.DataType, member.Entity.FullName, member.MemberName);
                // do not throw, continue to find more errors
                //Util.Throw("Driver failed to match db type for data type {0}, member {1}.{2}", member.DataType, member.Entity.FullName, member.MemberName);
                return(null);
            }
            var dbColumn = new DbColumnInfo(member, table, colName, dbTypeInfo);

            if (!string.IsNullOrEmpty(colDefault))
            {
                dbColumn.DefaultExpression = colDefault;
            }
            if (member.AutoValueType == AutoType.Identity)
            {
                dbColumn.Flags |= DbColumnFlags.Identity | DbColumnFlags.NoUpdate | DbColumnFlags.NoInsert;
            }
            if (member.Flags.IsSet(EntityMemberFlags.Secret))
            {
                dbColumn.Flags |= DbColumnFlags.NoUpdate; //updated only thru custom update method
            }
            if (member.Flags.IsSet(EntityMemberFlags.NoDbInsert))
            {
                dbColumn.Flags |= DbColumnFlags.NoInsert;
            }
            if (member.Flags.IsSet(EntityMemberFlags.NoDbUpdate))
            {
                dbColumn.Flags |= DbColumnFlags.NoUpdate;
            }
            if (isError)
            {
                dbColumn.Flags |= DbColumnFlags.Error;
            }
            if (member.Flags.IsSet(EntityMemberFlags.UnlimitedSize) && _driver.Supports(DbFeatures.ForceNullableMemo)) //case for SQL CE
            {
                dbColumn.Flags |= DbColumnFlags.Nullable;
            }
            return(dbColumn);
        }//method
예제 #7
0
        }//method

        private string ConstructDbKeyName(DbTableInfo table, KeyType keyType, IList <DbKeyColumnInfo> keyColumns, string entityKeyName)
        {
            string keyName = entityKeyName;
            //check that it does not exist; if it does, append index to it.
            var existing = table.Keys.FirstOrDefault(c => c.Name == keyName);

            if (existing != null)
            {
                keyName = keyName + (_tableKeyIndex++);
            }
            return(keyName);
        }
예제 #8
0
 public override DbCommandInfo CreateDbCommandInfo(EntityCommand entityCommand, string name, DbTableInfo mainTable, DbExecutionType executionType, string sql)
 {
     var cmdInfo = base.CreateDbCommandInfo(entityCommand, name, mainTable, executionType, sql);
       var ent = entityCommand.TargetEntityInfo;
       if (cmdInfo.Kind == EntityCommandKind.Insert && ent.Flags.IsSet(EntityFlags.HasIdentity)) {
     //Add actions to read identity value
     var idPrm = cmdInfo.Parameters.FirstOrDefault(p => p.SourceColumn.Flags.IsSet(DbColumnFlags.Identity));
     if (idPrm != null)
       cmdInfo.PostUpdateActions.Add(GetLastRowId);
       }
       return cmdInfo;
 }
예제 #9
0
파일: DbModel.cs 프로젝트: radtek/vita
 /// <summary>Constructs DbModel from EntityModel.</summary>
 /// <param name="entityApp"></param>
 /// <param name="config"></param>
 public DbModel(EntityApp entityApp, DbModelConfig config) : this(config) {
     Util.Check(entityApp != null, "entityApp parameter may not be null.");
     EntityApp = entityApp;
     //Add schemas
     foreach (var area in entityApp.Areas)
     {
         Schemas.Add(new DbSchemaInfo(this, config.GetSchema(area)));
     }
     VersionInfo = new DbVersionInfo(EntityApp, Config);
     var nullEnt = EntityApp.Model.NullEntityInfo;
     _nullTable = new DbTableInfo(this, null, "!!NullTable", nullEnt);
 }
예제 #10
0
 //constructor loader from the database
 public DbColumnInfo(DbTableInfo table, string columnName, DbTypeInfo typeInfo)
     : base(table.DbModel, table.Schema, DbObjectType.Column, null)
 {
     Table      = table;
     ColumnName = columnName;
     TypeInfo   = typeInfo;
     if (typeInfo.IsNullable)
     {
         this.Flags |= DbColumnFlags.Nullable;
     }
     Table.Columns.Add(this);
     base.GlobalName = DbModelHelper.GetGlobalName(table.Schema, table.TableName, columnName);
 }
예제 #11
0
        private DbColumnInfo CreateDbColumn(DbTableInfo table, EntityMemberInfo member)
        {
            var    colName    = member.ColumnName;
            string colDefault = member.ColumnDefault; //comes from attribute

            if (colDefault != null && member.DataType == typeof(string) && !colDefault.StartsWith("'"))
            {
                colDefault = colDefault.Quote();
            }

            var dbTypeInfo = GetDBTypeMapping(member);

            if (dbTypeInfo == null)
            {
                return(null);
            }
            var dbColumn = new DbColumnInfo(member, table, colName, dbTypeInfo);

            dbColumn.Converter = _driver.TypeRegistry.GetDbValueConverter(dbTypeInfo, member);
            if (dbColumn.Converter == null)
            {
                LogError($"Member {member}, type {member.DataType}: failed to find DbConverter to db type {dbTypeInfo.DbTypeSpec}");
                return(null);
            }
            if (!string.IsNullOrEmpty(colDefault))
            {
                dbColumn.DefaultExpression = colDefault;
            }
            if (member.AutoValueType == AutoType.Identity)
            {
                dbColumn.Flags |= DbColumnFlags.Identity | DbColumnFlags.NoUpdate | DbColumnFlags.NoInsert;
            }
            if (member.Flags.IsSet(EntityMemberFlags.RowVersion))
            {
                dbColumn.Flags |= DbColumnFlags.RowVersion | DbColumnFlags.NoUpdate | DbColumnFlags.NoInsert;
            }
            if (member.Flags.IsSet(EntityMemberFlags.Secret))
            {
                dbColumn.Flags |= DbColumnFlags.NoUpdate; //updated only thru custom update method
            }
            if (member.Flags.IsSet(EntityMemberFlags.NoDbInsert))
            {
                dbColumn.Flags |= DbColumnFlags.NoInsert;
            }
            if (member.Flags.IsSet(EntityMemberFlags.NoDbUpdate))
            {
                dbColumn.Flags |= DbColumnFlags.NoUpdate;
            }
            return(dbColumn);
        }//method
예제 #12
0
 //constructor loader from the database
 public DbColumnInfo(DbTableInfo table, string columnName, DbTypeInfo typeInfo, bool isNullable)
     : base(table.DbModel, table.Schema, DbObjectType.Column, null)
 {
     Table = table;
     SetName(columnName);
     // TO FIX
     TypeInfo = typeInfo;
     if (isNullable)
     {
         this.Flags |= DbColumnFlags.Nullable;
     }
     Table.Columns.Add(this);
     base.LogRefName = DbModelHelper.JoinNames(table.Schema, table.TableName, columnName);
 }
예제 #13
0
        }//method

        //Create tables and regular "value" columns
        private void BuildTables()
        {
            var supportsViews = _dbModel.Driver.Supports(DbFeatures.Views);

            foreach (var entity in _entityModel.Entities)
            {
                if (!IsActive(entity.Area))
                {
                    continue;
                }
                if (entity.Kind == EntityKind.View && !supportsViews)
                {
                    continue;
                }
                var tableName = GetDbTableViewName(entity);
                var objType   = entity.Kind == EntityKind.Table ? DbObjectType.Table : DbObjectType.View;
                var schema    = _dbModelConfig.GetSchema(entity.Area);
                var table     = new DbTableInfo(_dbModel, schema, tableName, entity, objType);
                // Check materialized view - automatically set the flag if there are indexes on the view
                if (entity.Kind == EntityKind.View)
                {
                    if (_driver.Supports(DbFeatures.MaterializedViews) && entity.ViewDefinition.Options.IsSet(DbViewOptions.Materialized))
                    {
                        table.IsMaterializedView = true;
                    }
                }
                //create Value columns
                foreach (var member in entity.Members)
                {
                    if (member.Kind == EntityMemberKind.Column)
                    {
                        CreateDbColumn(table, member);
                    }
                }
                //reorder DbColumns, make PK appear first
                var pkColumns = table.Columns.Where(c => c.Member.Flags.IsSet(EntityMemberFlags.PrimaryKey)).ToList();
                foreach (var pkCol in pkColumns)
                {
                    table.Columns.Remove(pkCol);
                    table.Columns.Insert(0, pkCol);
                }
                //order by
                if (entity.DefaultOrderBy != null)
                {
                    table.DefaultOrderBy = ConstructDefaultOrderBy(table);
                }
            }//foreach entityInfo
            CheckErrors();
        }
예제 #14
0
 //Replace references to properties (ex: {SomeProp}) with column references
 // Filters are supported by MS SQL only. MS SQL parses and normalizes the filter, enclosing column names in [], and enclosing filter in ()
 // To match the final result in database - so that db schema comparison works correctly - we do the same with filter definition
 private string ProcessKeyFilter(string filter, DbTableInfo table)
 {
     if (filter == null || !filter.Contains('{'))
     {
         return(filter);
     }
     foreach (var col in table.Columns)
     {
         var name = "{" + col.Member.MemberName + "}";
         if (!filter.Contains(name))
         {
             continue;
         }
         var colRef = '[' + col.ColumnName + ']';
         filter = filter.Replace(name, colRef);
     }
     filter = "(" + filter + ")";
     return(filter);
 }
예제 #15
0
 public override DbCommandInfo CreateDbCommandInfo(EntityCommand entityCommand, string name, DbTableInfo mainTable, DbExecutionType executionType, string sql)
 {
     var cmdInfo = base.CreateDbCommandInfo(entityCommand, name, mainTable, executionType, sql);
       var ent = entityCommand.TargetEntityInfo;
       if (cmdInfo.Kind == EntityCommandKind.Insert && ent.Flags.IsSet(EntityFlags.HasIdentity)) {
     //Add actions to read identity value
     var idPrm = cmdInfo.Parameters.FirstOrDefault(p => p.SourceColumn.Flags.IsSet(DbColumnFlags.Identity));
     if (idPrm != null) {
       cmdInfo.PostUpdateActions.Add((conn, cmd, rec) => {
     var idCmd = conn.DbConnection.CreateCommand();
     idCmd.CommandText = "Select @@IDENTITY;";
     idCmd.Transaction = conn.DbTransaction;
     var id =  conn.Database.ExecuteDbCommand(idCmd, conn, DbExecutionType.Scalar); //it is decimal
     var intId = Convert.ChangeType(id, idPrm.SourceColumn.Member.DataType);
     rec.SetValueDirect(idPrm.SourceColumn.Member, intId);
       });
     }//if IdPrm ...
       }
       return cmdInfo;
 }
예제 #16
0
        public DbCommandInfo(EntityCommand entityCommand, string commandName, DbTableInfo table, DbExecutionType executionType, string sql, string tag)
            : base(table.DbModel, table.Schema, DbObjectType.Command, entityCommand)
        {
            EntityCommand  = entityCommand;
            CommandName    = commandName;
            Table          = table;
            ExecutionType  = executionType;
            Sql            = sql;
            Description    = EntityCommand.Description;
            DescriptiveTag = tag;
            //derived entities
            FullCommandName = Table.DbModel.Driver.FormatFullName(Schema, CommandName);
            Kind            = entityCommand.Kind;
            var dbModel = table.DbModel;

            dbModel.AddCommand(this);
            if (Table != null)
            {
                Table.CrudCommands.Add(this);
            }
            base.GlobalName = DbModelHelper.GetGlobalName(Schema, commandName);
        }
예제 #17
0
        private IList <DbKeyColumnInfo> ConstructDefaultOrderBy(DbTableInfo table)
        {
            var keyMembers = table.Entity.DefaultOrderBy;

            if (keyMembers == null || keyMembers.Count == 0)
            {
                return(null);
            }
            var orderByList = new List <DbKeyColumnInfo>();
            var ent         = table.Entity;

            foreach (var keyMember in keyMembers)
            {
                var col = table.Columns.FirstOrDefault(c => c.Member == keyMember.Member);
                if (col == null)
                {
                    // This might happen in OrderBy on many-to-many list, when we order by member in target table
                    // ex: Author.Books, order by book.PublishedOn; in this case primary table is link table IBookAuthor;
                    // otherTbl is IBook
                    var otherTbl = _dbModel.GetTable(keyMember.Member.Entity.EntityType);
                    if (otherTbl != null)
                    {
                        col = otherTbl.Columns.FirstOrDefault(c => c.Member == keyMember.Member);
                    }
                }
                if (col == null)
                {
                    _log.LogError($"Failed to build ORDER BY list for table {table.TableName}: " +
                                  $"cannot find column for member {keyMember.Member.MemberName}.");
                }
                var dbKeyColumn = new DbKeyColumnInfo(col, keyMember);
                orderByList.Add(dbKeyColumn);
            }
            if (orderByList.Count == 0)
            {
                return(null);
            }
            return(orderByList);
        }
예제 #18
0
 public virtual void BuildViewAddSql(DbObjectChange change, DbTableInfo view)
 {
     const string sqlTemplate =
     @"CREATE VIEW {0} AS
     {1}"; //no ';' at the end, SQL must have it already
       change.AddScript(DbScriptType.ViewAdd, sqlTemplate, view.FullName, view.ViewSql);
 }
예제 #19
0
 public override void BuildViewAddSql(DbObjectChange change, DbTableInfo view)
 {
     const string sqlTemplate =
     @"CREATE VIEW {0} {1}  AS
       {2}"; //notice - no ';' at the end, SQL must have it already
       // For materialized views add 'With SCHEMABINDING' attribute
       var attrs = view.IsMaterializedView ? "WITH SCHEMABINDING" : string.Empty;
       change.AddScript(DbScriptType.ViewAdd, sqlTemplate, view.FullName, attrs, view.ViewSql);
       const string GrantSelectTemplate = "GRANT SELECT ON {0} TO [{1}];";
       if (!string.IsNullOrWhiteSpace(Settings.GrantExecReadToRole))
     change.AddScript(DbScriptType.Grant, GrantSelectTemplate, view.FullName, Settings.GrantExecReadToRole);
 }
예제 #20
0
 public DbKeyInfo(string name, DbTableInfo table, KeyType type, EntityKeyInfo entityKey = null)
     : base(table.DbModel, table.Schema, DbObjectType.Key, entityKey)
 {
     Name = name;
       Table = table;
       KeyType = type;
       EntityKey = entityKey;
       table.Keys.Add(this);
       base.GlobalName = DbModelHelper.GetGlobalName(table.Schema, name);
 }
예제 #21
0
 //constructor loader from the database
 public DbColumnInfo(DbTableInfo table, string columnName, DbTypeInfo typeInfo)
     : base(table.DbModel, table.Schema, DbObjectType.Column, null)
 {
     Table = table;
       ColumnName = columnName;
       TypeInfo = typeInfo;
       if (typeInfo.IsNullable)
     this.Flags |= DbColumnFlags.Nullable;
       Table.Columns.Add(this);
       base.GlobalName = DbModelHelper.GetGlobalName(table.Schema, table.TableName, columnName);
 }
예제 #22
0
 public virtual EntityMaterializer CreateEntityMaterializer(DbTableInfo table, IList<DbColumnInfo> columns)
 {
     var matzr = new EntityMaterializer(table);
       foreach (var col in columns)
     matzr.AddColumn(col);
       return matzr;
 }
예제 #23
0
 //creates a TSQL statement that raises error with custom message like 'VITA:Concurrency/Update/books.Author/123' (123 is primary key value)
 private string BuildRowCountCheckStatement(DbTableInfo table, List<DbParamInfo> pkParams, EntityCommandKind commandKind)
 {
     const string sqlCheckRowCount = @"
     IF @@RowCount = 0
     BEGIN
       DECLARE @msg NVARCHAR(200) = {0};
       RAISERROR(@msg, 11, 111);
     END
     ";
       //Build message expression
       var opType = commandKind == EntityCommandKind.Update ? "Update" : "Delete";
       var msg = "'" + ErrorTagConcurrentUpdateConflict + "/" + opType + "/" + table.FullName + "/' + ";
       var pkExprs = pkParams.Select(p => string.Format("CAST({0} AS NVARCHAR(50))", p.Name));
       var strPks = string.Join(" + ';' + ", pkExprs);
       msg += strPks;
       var result = string.Format(sqlCheckRowCount, msg);
       return result;
 }
예제 #24
0
 // For some providers keys might be combined; so to properly account for this, we count keys this way - separately by each type.
 private int CountKeys(DbTableInfo table)
 {
     return CountKeys(table, KeyType.PrimaryKey) + CountKeys(table, KeyType.ForeignKey) + CountKeys(table, KeyType.Index);
 }
예제 #25
0
        //Create tables and regular "value" columns
        private void BuildTables()
        {
            var supportsViews = _dbModel.Driver.Supports(DbFeatures.Views);
              foreach (var entityInfo in _entityModel.Entities) {
            if (!IsActive(entityInfo.Area))
              continue;
            if (entityInfo.Kind == EntityKind.View && !supportsViews)
              continue;

            var tableName = ConstructDefaultTableName(entityInfo);
            var objType = entityInfo.Kind == EntityKind.Table ? DbObjectType.Table : DbObjectType.View;
            var schema = _config.GetSchema(entityInfo.Area);
            var table = new DbTableInfo(_dbModel, schema, tableName, entityInfo, objType);
            // Check materialized view - automatically set the flag if there are indexes on the view
            if (entityInfo.Kind == EntityKind.View) {
              if (_driver.Supports(DbFeatures.MaterializedViews) && entityInfo.ViewDefinition.Options.IsSet(DbViewOptions.Materialized))
            table.IsMaterializedView = true;
            }
            //create Value columns
            foreach (var member in entityInfo.Members)
              if (member.Kind == MemberKind.Column)
            CreateDbColumn(table, member);
            //reorder DbColumns, make PK appear first
            var pkColumns = table.Columns.Where(c => c.Member.Flags.IsSet(EntityMemberFlags.PrimaryKey)).ToList();
            foreach (var pkCol in pkColumns) {
              table.Columns.Remove(pkCol);
              table.Columns.Insert(0, pkCol);
            }
              }//foreach entityInfo
              CheckErrors();
        }
예제 #26
0
 public void AddTable(DbTableInfo table)
 {
     Util.Check(!_dbObjectsByName.ContainsKey(table.FullName), "Duplicate table in DbModel: {0}", table.FullName);
     _tables.Add(table);
     _dbObjectsByName[table.FullName] = table;
 }
예제 #27
0
 // To detect changes in views and routines, we hash sql text and add the hash in comment inside the text.
 // This works OK in most cases, for stored procs and views. However, MySql (and Postgres) do not save original view definition
 // MySql removes all comments from view definition. So the only way to retrieve the original source and hash value is to load
 // it from form file.
 private void LoadViewHashFromFormFile(DbTableInfo view)
 {
     const string SqlTemplate =
     "SELECT LOAD_FILE(CONCAT(IFNULL(@@GLOBAL.datadir, CONCAT(@@GLOBAL.basedir, 'data/')), '{0}/{1}.frm')) AS ViewDef;";
       try {
     var sql = string.Format(SqlTemplate, view.Schema, view.TableName);
     var dt = ExecuteSelect(sql);
     if (dt.Rows.Count < 1)
       return;
     // LOAD_FILE should return content as string, but it doesn't, sometimes at least (bug, admitted by MySql team, still not fixed for years)
     // It might return byte array (as it happens on my machine - RI)
     var value = dt.Rows[0]["ViewDef"];
     string viewDef;
     if (value == null)
       return;
     if (value is string)
       viewDef = (string)value;
     else if (value.GetType() == typeof(byte[])) {
       viewDef = Encoding.Default.GetString((byte[])value);
     } else
       return;
     var hashIndex = viewDef.IndexOf(SqlSourceHasher.HashPrefix);
     if (hashIndex < 0)
       return;
     var start = hashIndex + SqlSourceHasher.HashPrefix.Length;
     var starIndex = viewDef.IndexOf('*', start);
     if (starIndex < 0)
       return;
     var hash = viewDef.Substring(start, starIndex - start);
     view.ViewHash = hash;
       } catch (Exception ex) {
     //Too many things can go wrong, do not break process, just log warning
     Log.Info("Failed to load view hash for view {0}.{1}, error: {2}.", view.Schema, view.TableName, ex.Message);
       }
 }
예제 #28
0
 public virtual void BuildViewDropSql(DbObjectChange change, DbTableInfo view)
 {
     change.AddScript(DbScriptType.ViewDrop, "DROP VIEW {0}", view.FullName);
 }
예제 #29
0
 public override void BuildViewAddSql(DbObjectChange change, DbTableInfo view)
 {
     const string createViewTemplate =
     @"CREATE {0} VIEW {1}  AS
       {2};
       COMMENT ON {0} VIEW {1} IS '{3}';
     "; //notice - no ';' at the end, SQL must have it already
       // For indexed views add 'MATERIALIZED' attribute
       var matz = view.IsMaterializedView ? "MATERIALIZED" : string.Empty;
       //var escapedSql = view.ViewSql.Replace("'", "''");
       change.AddScript(DbScriptType.ViewAdd, createViewTemplate, matz, view.FullName, view.ViewSql, view.ViewHash);
 }
예제 #30
0
 public virtual void BuildTableDropSql(DbObjectChange change, DbTableInfo table)
 {
     change.AddScript(DbScriptType.TableDrop, "DROP TABLE {0}", table.FullName);
 }
예제 #31
0
 public DbTableChangeGroup(DbTableInfo oldTable, DbTableInfo newTable)
 {
     OldTable = oldTable;
       NewTable = newTable;
       var tbl = NewTable ?? OldTable;
       TableName = tbl.FullName;
 }
예제 #32
0
        private DbColumnInfo CreateDbColumn(DbTableInfo table, EntityMemberInfo member)
        {
            bool isError = false;
              var colName = member.ColumnName;
              string colDefault = member.ColumnDefault; //comes from attribute
              if (colDefault != null && member.DataType == typeof(string) && !colDefault.StartsWith("'"))
            colDefault = colDefault.Quote();

              var dbTypeInfo = _driver.TypeRegistry.GetDbTypeInfo(member, _log);
              if (dbTypeInfo == null) {
            isError = true;
            LogError("Driver failed to match db type for data type {0}, member {1}.{2}", member.DataType, member.Entity.FullName, member.MemberName);
            // do not throw, continue to find more errors
            //Util.Throw("Driver failed to match db type for data type {0}, member {1}.{2}", member.DataType, member.Entity.FullName, member.MemberName);
            return null;
              }
              var dbColumn = new DbColumnInfo(member, table, colName, dbTypeInfo);
              if (!string.IsNullOrEmpty(colDefault))
            dbColumn.DefaultExpression = colDefault;
              if (member.AutoValueType == AutoType.Identity)
            dbColumn.Flags |= DbColumnFlags.Identity | DbColumnFlags.NoUpdate | DbColumnFlags.NoInsert;
              if (member.Flags.IsSet(EntityMemberFlags.Secret))
            dbColumn.Flags |= DbColumnFlags.NoUpdate; //updated only thru custom update method
              if (member.Flags.IsSet(EntityMemberFlags.NoDbInsert))
            dbColumn.Flags |= DbColumnFlags.NoInsert;
              if(member.Flags.IsSet(EntityMemberFlags.NoDbUpdate))
            dbColumn.Flags |= DbColumnFlags.NoUpdate;
              if(isError)
            dbColumn.Flags |= DbColumnFlags.Error;
              if (member.Flags.IsSet(EntityMemberFlags.UnlimitedSize) && _driver.Supports(DbFeatures.ForceNullableMemo)) //case for SQL CE
            dbColumn.Flags |= DbColumnFlags.Nullable;
              return dbColumn;
        }
예제 #33
0
 public virtual DbCommandInfo CreateDbCommandInfo(EntityCommand entityCommand, string name, DbTableInfo mainTable, DbExecutionType executionType, string sql)
 {
     var descrTag = GetDbCommandDescriptiveTag(entityCommand);
       var cmdInfo = new DbCommandInfo(entityCommand, name, mainTable, executionType, sql, descrTag);
       //Create parameters from entity command parameters
       var policy = DbModel.Config.NamingPolicy;
       var prmPrefix = GetParameterPrefix();
       for(int i=0; i< entityCommand.Parameters.Count; i++) {
     var entParam = entityCommand.Parameters[i];
     var paramName = prmPrefix + policy.ConstructDbParameterName(entParam.Name);
     DbParamInfo prmInfo;
     if (entParam.SourceMember != null) {
       var col = mainTable.Columns.FirstOrDefault(c => c.Member == entParam.SourceMember);
       Util.Check(col != null, "Failed to find Db column for member {0}, entity {1}.", entParam.SourceMember.MemberName, mainTable.Entity.Name);
       prmInfo = cmdInfo.AddParameter(entParam, paramName, col, i);
     } else {
       var typeInfo = GetDbTypeInfo(entParam.DataType, entParam.Size);
       prmInfo = cmdInfo.AddParameter(entParam, paramName, typeInfo, i);
     }
     // SQL CE does not support output parameters
     if (!this.DbModel.Driver.Supports(DbFeatures.OutputParameters))
       prmInfo.Direction = ParameterDirection.Input;
     if (prmInfo.Direction == ParameterDirection.Output || prmInfo.Direction == ParameterDirection.InputOutput) {
       cmdInfo.PostUpdateActions.Add((con, cmd, rec) => {
     var prm = (IDbDataParameter) cmd.Parameters[prmInfo.Name];
     rec.SetValueDirect(prmInfo.SourceColumn.Member, prm.Value);
       });
     }
       }//foreach entParam
       return cmdInfo;
 }
예제 #34
0
 //Replace references to properties (ex: {SomeProp}) with column references
 // Filters are supported by MS SQL only. MS SQL parses and normalizes the filter, enclosing column names in [], and enclosing filter in ()
 // To match the final result in database - so that db schema comparison works correctly - we do the same with filter definition
 private string ProcessKeyFilter(string filter, DbTableInfo table)
 {
     if(filter == null || !filter.Contains('{'))
     return filter;
       foreach(var col in table.Columns) {
     var name = "{" + col.Member.MemberName + "}";
     if(!filter.Contains(name))
       continue;
     var colRef = '[' + col.ColumnName + ']';
     filter = filter.Replace(name, colRef);
       }
       filter = "(" + filter + ")";
       return filter;
 }
예제 #35
0
 protected virtual string ProcessFilter(EntityCommand command, DbTableInfo table)
 {
     var filter = command.Filter;
       if (filter == null || !filter.Contains('{'))
     return filter;
       foreach (var col in table.Columns) {
     var name = "{" + col.Member.MemberName + "}";
     if (!filter.Contains(name))
       continue;
     var colRef = '"' + col.ColumnName + '"';
     filter = filter.Replace(name, colRef);
       }
       filter = "(" + filter + ")";
       return filter;
 }
예제 #36
0
 public virtual void BuildTableAddSql(DbObjectChange change, DbTableInfo table)
 {
     const string SqlTemplate = @"CREATE TABLE {0} (" + "\r\n {1} \r\n); ";
       var specs = table.Columns.Select(c => GetColumnSpec(c));
       var columnSpecs = string.Join("," + Environment.NewLine, specs);
       change.AddScript(DbScriptType.TableAdd, SqlTemplate, table.FullName, columnSpecs);
 }
예제 #37
0
 public DbCommandInfo(EntityCommand entityCommand, string commandName, DbTableInfo table, DbExecutionType executionType, string sql, string tag)
     : base(table.DbModel, table.Schema, DbObjectType.Command, entityCommand)
 {
     EntityCommand = entityCommand;
       CommandName = commandName;
       Table = table;
       ExecutionType = executionType;
       Sql = sql;
       Description = EntityCommand.Description;
       DescriptiveTag = tag;
       //derived entities
       FullCommandName = Table.DbModel.Driver.GetFullName(Schema, CommandName);
       Kind = entityCommand.Kind;
       var dbModel = table.DbModel;
       dbModel.AddCommand(this);
       if(Table != null)
     Table.CrudCommands.Add(this);
       base.GlobalName = DbModelHelper.GetGlobalName(Schema, commandName);
 }
예제 #38
0
 public EntityRecordReader(DbTableInfo tableInfo)
 {
     _tableInfo = tableInfo;
     EntityType = _tableInfo.Entity.EntityType;
 }
예제 #39
0
 public DbColumnInfo(EntityMemberInfo member, DbTableInfo table, string columnName, DbTypeInfo typeInfo)
     : base(table.DbModel, table.Schema, DbObjectType.Column, member)
 {
     Member = member;
       Table = table;
       ColumnName = columnName;
       TypeInfo = typeInfo;
       Table.Columns.Add(this);
       base.GlobalName = DbModelHelper.GetGlobalName(Schema, table.TableName, columnName);
       if (member.Flags.IsSet(EntityMemberFlags.Nullable))
     Flags |= DbColumnFlags.Nullable;
       if (member.Flags.IsSet(EntityMemberFlags.Identity))
     Flags |= DbColumnFlags.Identity;
       if (member.Flags.IsSet(EntityMemberFlags.ForeignKey)) {
     Flags |= DbColumnFlags.ForeignKey;
     if (member.ForeignKeyOwner.ReferenceInfo.ToKey.Entity.Flags.IsSet(EntityFlags.HasIdentity))
       Flags |= DbColumnFlags.IdentityForeignKey;
       }
 }
예제 #40
0
 public override void BuildViewDropSql(DbObjectChange change, DbTableInfo view)
 {
     var matzed = view.IsMaterializedView ? "MATERIALIZED" : string.Empty;
       change.AddScript(DbScriptType.ViewDrop, "DROP {0} VIEW {1};", matzed, view.FullName);
       //base.BuildViewDropSql(change, view);
 }
예제 #41
0
 public static DbColumnInfo GetColumnByMemberName(this DbTableInfo table, string memberName)
 {
     return(table.Columns.FirstOrDefault(c => c.Member.MemberName == memberName));
 }
예제 #42
0
 public override void BuildTableRenameSql(DbObjectChange change, DbTableInfo oldTable, DbTableInfo newTable)
 {
     change.AddScript(DbScriptType.TableRename, "ALTER TABLE {0} RENAME TO \"{1}\" ;", oldTable.FullName, newTable.TableName);
 }
예제 #43
0
 private string ConstructDbKeyName(DbTableInfo table, KeyType keyType, IList<DbKeyColumnInfo> keyColumns, string entityKeyName)
 {
     string keyName = entityKeyName;
       //check that it does not exist; if it does, append index to it.
       var existing = table.Keys.FirstOrDefault(c => c.Name == keyName);
       if (existing != null)
     keyName = keyName + (_tableKeyIndex++);
       return keyName;
 }
예제 #44
0
 public virtual void BuildTableRenameSql(DbObjectChange change, DbTableInfo oldTable, DbTableInfo newTable)
 {
     //Syntax for MySql and almost like Postgres
       change.AddScript(DbScriptType.TableRename, "ALTER TABLE {0} RENAME TO \"{1}\" ;", oldTable.FullName, newTable.FullName);
 }
예제 #45
0
 private int CountKeys(DbTableInfo table, KeyType keyType)
 {
     return table.Keys.Count(k => k.KeyType.IsSet(keyType));
 }
예제 #46
0
 private IList<DbKeyColumnInfo> ConstructOrderBy(DbTableInfo table)
 {
     var orderByList = new List<DbKeyColumnInfo>();
       var ent = table.Entity;
       foreach (var keyMember in ent.DefaultOrderBy) {
     var col = table.Columns.FirstOrDefault(c=>c.Member == keyMember.Member);
     if (col == null)
       LogError("Failed to build ORDER BY list for table {0}: cannot find column for member {1}.", table.TableName, keyMember.Member.MemberName);
     var dbKeyColumn = new DbKeyColumnInfo(col, keyMember);
     orderByList.Add(dbKeyColumn);
       }
       if (orderByList.Count == 0)
     return null;
       return orderByList;
 }