private bool CreateCode(string savePath) { string listTable = string.Empty; string str2 = string.Empty; this.DataAccessList = new List <string>(); this.FacadeList = new List <string>(); this.MyClassList = new List <string>(); tempList = new List <string>(); this.GetTempList(this.TemplateTreeView.Nodes); foreach (var item in lboxTable2.Items) { TableSchema table = this.tables.FirstOrDefault(s => s.Name == item.ToString()); ViewSchema view = this.views.FirstOrDefault(s => s.Name == item.ToString()); foreach (string tempPath in this.tempList) { try { CodeFile file = null; if (table != null) { file = TemplateFactory.BuilderCodes(tempPath, table); } else { file = TemplateFactory.BuilderCodes(tempPath, view); } this.GernalFile(file.Codes, string.Format(@"{0}\{1}", savePath, file.FileName)); this.DataAccessList.Add(file.FileName + "#" + file.Codes); continue; } catch (Exception exception) { if (exception.Message.IndexOf("未设置主键") > 0) { listTable = listTable + "|" + str2; base.DialogResult = base.Alert(exception.Message + ",是否终止生成!", "生成失败", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation); if (base.DialogResult == DialogResult.Yes) { base.Alert("取消成功", "生成失败!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); return(false); } this.lboxTable.Items.Add(item); } else { base.Alert(exception.Message, "生成失败!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } break; } } } if (!string.IsNullOrEmpty(listTable.Trim())) { this.DelItem(listTable); } base.Alert("生成完成!", "生成完成", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); return(true); }
public bool ShowViewEditorDialog (IEditSchemaProvider schemaProvider, ViewSchema view, bool create) { ViewEditorSettings settings = new ViewEditorSettings (); ViewEditorDialog dlg = new ViewEditorDialog (schemaProvider, create, settings); dlg.Initialize (view); return RunDialog (dlg);
public string GetClassNameView(ViewSchema view) { if (view == null) { return(""); } return(view.Name); }
public void InitializeContext() { this.store.TransactionManager.DoWithinTransaction(() => { var patternModel = this.store.ElementFactory.CreateElement<PatternModelSchema>(); this.product = patternModel.Create<PatternSchema>(); this.view = this.product.Create<ViewSchema>(); }); }
public void InitializeContext() { this.store.TransactionManager.DoWithinTransaction(() => { var patternModel = this.store.ElementFactory.CreateElement <PatternModelSchema>(); this.product = patternModel.Create <PatternSchema>(); this.view = this.product.Create <ViewSchema>(); }); }
public bool ShowViewEditorDialog(IEditSchemaProvider schemaProvider, ViewSchema view, bool create) { ViewEditorSettings settings = new ViewEditorSettings(); ViewEditorDialog dlg = new ViewEditorDialog(schemaProvider, create, settings); dlg.Initialize(view); return(RunDialog(dlg)); }
private void OnViewSchemaReaderProgressChanged(ViewSchema lastProcessed, int processed, int remaining) { var handler = ViewSchemaReaderProgressChanged; if (handler != null) { handler(this, new ViewSchemaReaderProgressChangedEventArgs(lastProcessed, processed, remaining)); } }
//http://www.sqlite.org/lang_createview.html public override void CreateView(ViewSchema view) { IPooledDbConnection conn = connectionPool.Request(); IDbCommand command = conn.CreateCommand(view.Definition); using (command) conn.ExecuteNonQuery(command); conn.Release(); }
public ViewSchemaContainer(ViewSchema schema) { if (schema == null) { throw new ArgumentNullException("schema"); } this.schema = schema; }
public virtual void Initialize() { this.store.TransactionManager.DoWithinTransaction(() => { this.elementOwner = this.store.ElementFactory.CreateElement<PatternSchema>(); this.view = this.store.ElementFactory.CreateElement<ViewSchema>(); this.elementOwner.Views.Add(this.view); }); validationContext = new ValidationContext(ValidationCategories.Save, this.view); }
private string _003CdbConvert_Load_003Eb__1_2(ViewSchema vs) { _003C_003Ec__DisplayClass1_1 _003C_003Ec__DisplayClass1_ = new _003C_003Ec__DisplayClass1_1(); _003C_003Ec__DisplayClass1_._003C_003E4__this = this; _003C_003Ec__DisplayClass1_.vs = vs; _003C_003Ec__DisplayClass1_.updated = null; Invoke(new MethodInvoker(_003C_003Ec__DisplayClass1_._003CdbConvert_Load_003Eb__3)); return(_003C_003Ec__DisplayClass1_.updated); }
public virtual void Initialize() { this.store.TransactionManager.DoWithinTransaction(() => { var patternModel = this.store.ElementFactory.CreateElement <PatternModelSchema>(); this.pattern = patternModel.Create <PatternSchema>(); this.view = this.pattern.Create <ViewSchema>(); }); validationContext = new ValidationContext(ValidationCategories.Save, this.pattern); }
public ViewNode(DatabaseConnectionContext context, ViewSchema view) : base(context) { if (view == null) { throw new ArgumentNullException("view"); } this.view = view; }
private string OnFailedViewDefinitionHandler(ViewSchema vs) { string updated = null; Invoke(new MethodInvoker(() => { updated = FailedViewDefinitionHandler(vs); })); return(updated); }
public virtual void Initialize() { this.store.TransactionManager.DoWithinTransaction(() => { this.elementOwner = this.store.ElementFactory.CreateElement <PatternSchema>(); this.view = this.store.ElementFactory.CreateElement <ViewSchema>(); this.elementOwner.Views.Add(this.view); }); validationContext = new ValidationContext(ValidationCategories.Save, this.view); }
protected override void ProcessRecord() { base.ProcessRecord(); var ctx = base.Context; XmlDocument viewSchema = null; if (ViewSchema != null) { viewSchema = ViewSchema.Read(); } if (string.IsNullOrEmpty(ViewTitle) && viewSchema == null) { throw new ArgumentException("You must specify a value for at least one of the ViewTitle or ViewSchema parameters."); } var web = ctx.Site.OpenWeb(Web.Read()); SPOFile file = File.Read(web); SPOList list = List.Read(web, true); Guid viewId = Guid.Empty; if (!string.IsNullOrEmpty(ViewTitle)) { var view = list.GetViews().Where(v => v.Title.ToLowerInvariant() == ViewTitle.ToLowerInvariant()).FirstOrDefault(); if (view == null) { throw new ArgumentException("The value specified for the ViewTitle parameter does not match an existing view."); } } string xml = GetXsltListViewWebPartXml(list.Id, list.Url, viewId, viewSchema, file.ServerRelativeUrl, Title, JSLink, ChromeType); if (list.BaseTemplate == 106) { if (viewSchema == null) { var view = list.GetViews().Where(v => v.Title.ToLowerInvariant() == ViewTitle.ToLowerInvariant()).FirstOrDefault(); viewSchema = new XmlDocument(); viewSchema.LoadXml(view.ListViewXml); } xml = GetListViewWebPartXml(list.Id, list.Url, viewSchema, file.ServerRelativeUrl, Title, ChromeType); } if (ParameterSetName == "WikiPage") { SPOWikiPage wikiPage = file as SPOWikiPage; if (wikiPage == null) { throw new Exception("The specified file is either not found or is not a wiki page."); } WriteObject(wikiPage.AddWebPartToWikiPage(xml, Title, Row, Column, AddSpace)); } else { WriteObject(file.AddWebPartToWebPartPage(xml, Zone, ZoneIndex, Title)); } }
public static bool HasIdColumn(ViewSchema tv) { foreach (ViewColumnSchema column in tv.Columns) { if (column.Name == "Id") { return(true); } } return(false); }
internal TableConfiguration ReadPropertyXmlInner(PropertySerializerContext context, XmlNode propertyValue) { XPathNavigator navigator = propertyValue.CreateNavigator(); XmlNamespaceManager manager = new XmlNamespaceManager(navigator.NameTable); XPathNodeIterator iterator; // Add the CodeSmith namespace manager.AddNamespace("cs", CodeSmithProject.DefaultNamespace); // Get the DatabaseSchema DatabaseSchema databaseSchema = null; iterator = (XPathNodeIterator)navigator.Evaluate("cs:DatabaseSchema", manager); if (iterator.MoveNext()) { XmlNode oNode = ((IHasXmlNode)iterator.Current).GetNode(); databaseSchema = (DatabaseSchema) new DatabaseSchemaSerializer().ReadPropertyXml(context, oNode); } // Get the SourceTable TableSchema sourceTable = null; if (databaseSchema != null) { string strOwner = navigator.Evaluate("string(cs:SourceTable/cs:Owner/text())", manager) as string; string strName = navigator.Evaluate("string(cs:SourceTable/cs:Name/text())", manager) as string; if (!string.IsNullOrEmpty(strName)) { sourceTable = !string.IsNullOrEmpty(strOwner) ? databaseSchema.Tables[strOwner, strName] : databaseSchema.Tables[strName]; } } // Get the SourceView ViewSchema sourceView = null; if (databaseSchema != null) { string strOwner = navigator.Evaluate("string(cs:SourceView/cs:Owner/text())", manager) as string; string strName = navigator.Evaluate("string(cs:SourceView/cs:Name/text())", manager) as string; if (!string.IsNullOrEmpty(strName)) { sourceView = !string.IsNullOrEmpty(strOwner) ? databaseSchema.Views[strOwner, strName] : databaseSchema.Views[strName]; } } // Create and return return(new TableConfiguration { SourceTable = sourceTable, SourceView = sourceView }); }
public static bool HadBankId(ViewSchema view) { foreach (ViewColumnSchema column in view.Columns) { if (column.Name == "BankId") { return(true); } } return(false); }
public static string GetTVRemark(ViewSchema view) { if (view.ExtendedProperties["remark"] != null) { return(view.ExtendedProperties["remark"].Value.ToString()); } else { return(GetClassName(view)); } }
private void OnCreateViewThreaded(object state) { object[] objs = state as object[]; ISchemaProvider provider = objs[0] as ISchemaProvider; ViewSchema view = objs[1] as ViewSchema; BaseNode node = objs[2] as BaseNode; provider.CreateView(view); node.Refresh(); }
public static bool HadColumnName(ViewSchema view, string columnName) { foreach (ViewColumnSchema column in view.Columns) { if (column.Name.ToLower() == columnName) { return(true); } } return(false); }
public TEntity GetAndCreate(ViewSchema viewSchema) { if (_content == null) { throw new ArgumentNullException("viewSchema"); } TEntity entity = EntityContext.Entities.ByTable(viewSchema.FullName); if (entity != null) { return(entity); } entity = new TEntity { FullName = viewSchema.FullName, TableName = viewSchema.Name, TableSchema = viewSchema.Owner }; string className = _content.ToClassName(viewSchema.Name); className = _content.UniqueNamer.UniqueClassName(className); string mappingName = className + "Map"; mappingName = _content.UniqueNamer.UniqueClassName(mappingName); string contextName = _content.Settings.ContextName(className); contextName = _content.ToPropertyName(EntityContext.ClassName, contextName); contextName = _content.UniqueNamer.UniqueContextName(contextName); entity.ClassName = className; entity.ContextName = contextName; entity.MappingName = mappingName; entity.Properties = new PropertyCollection <TProperty>(); PropertyTemplate <TEntity, TProperty> propertyTemplate = new PropertyTemplate <TEntity, TProperty>(_content) { Entity = entity }; foreach (ViewColumnSchema dataObjectBase in viewSchema.Columns.Selected()) { propertyTemplate.GetAndCreate(dataObjectBase); } EntityContext.Entities.Add(entity); return(entity); }
public static string GetViewObjStr(ViewSchema tv) { if (GetCType(tv.Columns["Id"], tv.ExtendedProperties) == "int") { return("ViewIntObj"); } else { return("ViewObj"); } }
protected void OnCreateView() { BaseNode node = CurrentNode.DataItem as BaseNode; IDbFactory fac = node.ConnectionContext.DbFactory; ISchemaProvider schemaProvider = node.ConnectionContext.SchemaProvider; ViewSchema view = schemaProvider.GetNewViewSchema("NewView"); if (fac.GuiProvider.ShowViewEditorDialog(schemaProvider, view, true)) { ThreadPool.QueueUserWorkItem(new WaitCallback(OnCreateViewThreaded), new object[] { schemaProvider, view, node } as object); } }
public ViewEditorDialog(ISchemaProvider schemaProvider, ViewSchema view, bool create) { if (schemaProvider == null) { throw new ArgumentNullException("schemaProvider"); } if (view == null) { throw new ArgumentNullException("view"); } this.schemaProvider = schemaProvider; this.view = view; this.action = create ? SchemaActions.Create : SchemaActions.Alter; this.Build(); if (create) { Title = GettextCatalog.GetString("Create View"); } else { Title = GettextCatalog.GetString("Alter View"); } notebook = new Notebook(); sqlEditor = new SqlEditorWidget(); sqlEditor.TextChanged += new EventHandler(SqlChanged); notebook.AppendPage(sqlEditor, new Label(GettextCatalog.GetString("Definition"))); IDbFactory fac = schemaProvider.ConnectionPool.DbFactory; if (fac.IsCapabilitySupported("View", action, ViewCapabilities.Comment)) { commentEditor = new CommentEditorWidget(); notebook.AppendPage(commentEditor, new Label(GettextCatalog.GetString("Comment"))); } notebook.Page = 0; entryName.Text = view.Name; if (!create) { sqlEditor.Text = schemaProvider.GetViewAlterStatement(view); commentEditor.Comment = view.Comment; } vboxContent.PackStart(notebook, true, true, 0); vboxContent.ShowAll(); SetWarning(null); }
public static string GetSortStr2(ViewSchema view) { if (HadColumnName(view, "Order")) { return("[Order] asc"); } else if (HadColumnName(view, "CreateDate")) { return("[CreateDate] DESC"); } return(""); }
public void WhenSameNamedElementAddedToSameOwner_ThenValidateNameIsUniqueFails() { this.store.TransactionManager.DoWithinTransaction(() => { ViewSchema view2 = this.store.ElementFactory.CreateElement <ViewSchema>(); view2.Name = this.view.Name; this.elementOwner.Views.Add(view2); }); this.view.ValidateNameIsUnique(validationContext); Assert.True(validationContext.CurrentViolations.Count == 1); Assert.True(validationContext.ValidationSubjects.IndexOf(this.view) == 0); }
public void WhenSameNamedElementAddedToDifferentOwner_ThenValidateNameIsUniqueSucceeds() { this.store.TransactionManager.DoWithinTransaction(() => { PatternSchema elementOwner2 = this.store.ElementFactory.CreateElement <PatternSchema>(); ViewSchema view2 = this.store.ElementFactory.CreateElement <ViewSchema>(); view2.Name = this.view.Name; elementOwner2.Views.Add(view2); }); this.view.ValidateNameIsUnique(validationContext); Assert.True(validationContext.CurrentViolations.Count == 0); }
public void WhenSameNamedElementAddedToDifferentOwner_ThenValidateNameIsUniqueSucceeds() { this.store.TransactionManager.DoWithinTransaction(() => { ViewSchema elementOwner2 = this.store.ElementFactory.CreateElement <ViewSchema>(); CollectionSchema element2 = this.store.ElementFactory.CreateElement <CollectionSchema>(); element2.Name = this.element.Name; elementOwner2.Elements.Add(element2); }); this.element.ValidateNameIsUnique(validationContext); Assert.True(validationContext.CurrentViolations.Count == 0); }
// see: http://dev.mysql.com/doc/refman/5.1/en/views-table.html public override ViewSchemaCollection GetViews() { ViewSchemaCollection views = new ViewSchemaCollection(); using (IPooledDbConnection conn = connectionPool.Request()) { using (IDbCommand command = conn.CreateCommand(string.Format( @"SELECT TABLE_NAME, TABLE_SCHEMA FROM information_schema.VIEWS where TABLE_SCHEMA = '{0}' ORDER BY TABLE_NAME" , ConnectionPool.ConnectionContext.ConnectionSettings.Database))){ try { // Views are supported in mysql since version 5. if (GetMainVersion(command) >= 5) { using (IDataReader r = command.ExecuteReader()) { while (r.Read()) { ViewSchema view = new ViewSchema(this); view.Name = r.GetString(0); view.OwnerName = r.GetString(1); using (IPooledDbConnection conn2 = connectionPool.Request()) { using (IDbCommand command2 = conn2.CreateCommand(string.Concat( "SHOW CREATE TABLE `", view.Name, "`;"))) { using (IDataReader r2 = command2.ExecuteReader()) { r2.Read(); view.Definition = r2.GetString(1); } } conn2.Release(); } views.Add(view); } r.Close(); } } } catch (Exception e) { QueryService.RaiseException(e); } finally { conn.Release(); } } } return(views); }
public void InitializeContext() { var store = new DslTestStore <PatternModelDomainModel>(); var serviceProvider = Mock.Get(store.ServiceProvider); serviceProvider.Setup(s => s.GetService(typeof(IPatternManager))).Returns( Mock.Of <IPatternManager>(p => p.InstalledToolkits == new List <IInstalledToolkitInfo>())); PatternModelSchema authoredPatternModel = null; store.TransactionManager.DoWithinTransaction(() => { authoredPatternModel = store.ElementFactory.CreateElement <PatternModelSchema>(); }); var uriService = Mock.Of <IUriReferenceService>( u => u.ResolveUri <IInstanceBase>(It.IsAny <Uri>()) == Mock.Of <IProduct>(p => p.ToolkitInfo.Identifier == "AuthoredToolkit")); var patternSchema = authoredPatternModel.Create <PatternSchema>(); patternSchema.Name = "FooPattern"; patternSchema.PatternLink = "patternmanager://foo"; patternSchema.UriService = uriService; this.view = patternSchema.Create <ViewSchema>(); this.view.Name = "View1"; store.TransactionManager.DoWithinTransaction(() => { this.authoredExtensionPoint = store.ElementFactory.CreateElement <ExtensionPointSchema>("ExtensionPoint1"); this.view.ExtensionPoints.Add(this.authoredExtensionPoint); }); // Customize Toolkit var tailoredUriService = Mock.Of <IUriReferenceService>( u => u.ResolveUri <IInstanceBase>(It.IsAny <Uri>()) == Mock.Of <IProduct>(p => p.ToolkitInfo.Identifier == "TailoredToolkit")); var tailoredPatternModel = PatternModelSpec.TailorPatternModel(authoredPatternModel, new Version("1.0.0.0"), "AuthoredToolkit"); store.TransactionManager.DoWithinTransaction(() => { tailoredPatternModel.Pattern.UriService = tailoredUriService; tailoredPatternModel.BaseId = "AuthoredToolkit"; }); this.tailoredExtensionPoint = tailoredPatternModel.Pattern.Views[0].ExtensionPoints[0]; }
public void Initialize(ViewSchema view) { if (view == null) { throw new ArgumentNullException("view"); } this.view = view; if (action == SchemaActions.Alter) { // sqlEditor.Text = schemaProvider.GetViewAlterStatement (view); commentEditor.Comment = view.Comment; } }
public override ColumnSchemaCollection GetViewColumns (ViewSchema view) { ColumnSchemaCollection columns = new ColumnSchemaCollection (); using (IPooledDbConnection conn = connectionPool.Request ()) { using (IDbCommand command = conn.CreateCommand (String.Format ("DESCRIBE {0}", view.Name))) { try { using (IDataReader r = command.ExecuteReader()) { while (r.Read ()) { ColumnSchema column = new ColumnSchema (this, view); column.Name = r.GetString (0); column.DataTypeName = r.GetString (1); column.IsNullable = r.IsDBNull (2); column.DefaultValue = r.GetString (4); column.Comment = r.GetString (5); column.OwnerName = view.Name; columns.Add (column); } r.Close (); } } catch (Exception e) { QueryService.RaiseException (e); } finally { conn.Release (); } } } return columns; }
// see: http://dev.mysql.com/doc/refman/5.1/en/views-table.html public override ViewSchemaCollection GetViews () { ViewSchemaCollection views = new ViewSchemaCollection (); using (IPooledDbConnection conn = connectionPool.Request ()) { using (IDbCommand command = conn.CreateCommand (string.Format ( @"SELECT TABLE_NAME, TABLE_SCHEMA FROM information_schema.VIEWS where TABLE_SCHEMA = '{0}' ORDER BY TABLE_NAME", ConnectionPool.ConnectionContext.ConnectionSettings.Database))){ try { // Views are supported in mysql since version 5. if (GetMainVersion (command) >= 5) { using (IDataReader r = command.ExecuteReader()) { while (r.Read ()) { ViewSchema view = new ViewSchema (this); view.Name = r.GetString (0); view.OwnerName = r.GetString (1); using (IPooledDbConnection conn2 = connectionPool.Request ()) { using (IDbCommand command2 = conn2.CreateCommand (string.Concat( "SHOW CREATE TABLE `", view.Name, "`;"))) { using (IDataReader r2 = command2.ExecuteReader()) { r2.Read (); view.Definition = r2.GetString (1); } } conn2.Release (); } views.Add (view); } r.Close (); } } } catch (Exception e) { QueryService.RaiseException (e); } finally { conn.Release (); } } } return views; }
private void CreateView(ViewSchema viewSchema) { Table table; if (Database.Tables.Contains(viewSchema.FullName)) { table = Database.Tables[viewSchema.FullName]; } else { Type type = new Type(ToClassName(viewSchema.Name)); table = new Table(viewSchema.FullName, type); Database.Tables.Add(table); } if (string.IsNullOrEmpty(table.Type.Name)) table.Type.Name = ToClassName(viewSchema.Name); if (string.IsNullOrEmpty(table.Member)) table.Member = table.Type.Name; foreach (ViewColumnSchema columnSchema in viewSchema.Columns) { Column column; if (table.Type.Columns.Contains(columnSchema.Name)) { column = table.Type.Columns[columnSchema.Name]; } else { column = new Column(GetSystemType(columnSchema)); column.Name = columnSchema.Name; table.Type.Columns.Add(column); } PopulateColumn(column, columnSchema, table.Type.Name); } table.Type.Columns.IsProcessed = true; table.Type.Associations.IsProcessed = true; table.IsProcessed = true; }
public ViewSchema[] GetViews(string connectionString, DatabaseSchema database) { //Get only the 'tables' of type 'view'. The 'Tables' catlog also includes //system tables, and regular tables DataTable dt = GetSchemaData(connectionString, Tables, null /*restrictions[0] - catalog*/, null /*restrictions[1] - unused*/, null /*restrictions[2] - table*/, ViewType /*restrictions[3] - type*/); ViewSchema[] views = new ViewSchema[dt.Rows.Count]; int tableSchemaIdx = 0; foreach (DataRow dr in dt.Rows) { ViewSchema view = new ViewSchema(database, (String)dr[TableNameColumn], String.Empty, DateTime.MinValue); views[tableSchemaIdx++] = view; } return views; }
public override ColumnSchemaCollection GetViewColumns (ViewSchema view) { ColumnSchemaCollection columns = new ColumnSchemaCollection (); using (IPooledDbConnection conn = connectionPool.Request ()) { using (IDbCommand command = conn.CreateCommand (string.Format ( @"SELECT attname, typname, attlen, attnotnull FROM pg_catalog.pg_attribute a LEFT JOIN pg_catalog.pg_attrdef adef ON a.attrelid = adef.adrelid AND a.attnum = adef.adnum LEFT JOIN pg_catalog.pg_type t ON a.atttypid = t.oid WHERE a.attrelid = (SELECT oid FROM pg_catalog.pg_class WHERE relname='{0}') AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum;", view.Name))) { try { using (IDataReader r = command.ExecuteReader()) { while (r.Read ()) { ColumnSchema column = new ColumnSchema (this, view); column.Name = r.GetString(0); column.DataTypeName = r.GetString (1); column.SchemaName = view.SchemaName; column.IsNullable = r.GetBoolean (3); column.DataType.LengthRange.Default = r.GetInt32 (2); // TODO: Fill column.Definition columns.Add (column); } r.Close (); } } catch (Exception e) { QueryService.RaiseException (e); } finally { conn.Release (); } } } return columns;
public ViewColumnSchema[] GetViewColumns(string connectionString, ViewSchema view) { DataTable dt = GetSchemaData(connectionString, Columns, null /*restrictions[0] - catalog*/, null /*restrictions[1] - unused*/, view.Name /*restrictions[2] - table*/, null /*restrictions[3] - column*/); ViewColumnSchema[] columns = new ViewColumnSchema[dt.Rows.Count]; int colIdx = 0; foreach (DataRow dr in dt.Rows) { ViewColumnSchema col = new ViewColumnSchema(view, (String)dr[ColumnsNameColumn], DbTypeFromType((String)dr[ColumnsTypeColumn]), NativeTypeFromType((String)dr[ColumnsTypeColumn]), 0, 0, 0, (bool)dr[ColumnsNullableColumn] ); columns[colIdx++] = col; } return columns; }
//http://dev.mysql.com/doc/refman/5.1/en/rename-table.html public override void RenameView (ViewSchema view, string name) { ExecuteNonQuery (string.Concat("RENAME TABLE ", view.Name, " TO ", name, ";")); view.Name = name; }
private void LoadProperties(ViewSchema view, StringCollection uniqueColumns, StringCollection filterColumns) { foreach (ViewColumnSchema col in view.Columns) { //need case insensitive //bool isUniqueMember = uniqueColumns.Contains(col.Name); bool isUniqueMember = uniqueColumns.ToString().ToLower().IndexOf(col.Name.ToLower()) >= 0; bool isFilterMember = filterColumns.ToString().ToLower().IndexOf(col.Name.ToLower()) >= 0; PropertyInfo prop = new PropertyInfo(col, this, isUniqueMember, isFilterMember); _properties.Add(prop); if (prop.IsPrimaryKey) _uniqueProperties.Add(prop); if (prop.IsFilterKey) _filterProperties.Add(prop); } }
public void InitializeContext() { var store = new DslTestStore<PatternModelDomainModel>(); var serviceProvider = Mock.Get(store.ServiceProvider); serviceProvider.Setup(s => s.GetService(typeof(IPatternManager))).Returns( Mock.Of<IPatternManager>(p => p.InstalledToolkits == new List<IInstalledToolkitInfo>())); PatternModelSchema authoredPatternModel = null; store.TransactionManager.DoWithinTransaction(() => { authoredPatternModel = store.ElementFactory.CreateElement<PatternModelSchema>(); }); var uriService = Mock.Of<IUriReferenceService>( u => u.ResolveUri<IInstanceBase>(It.IsAny<Uri>()) == Mock.Of<IProduct>(p => p.ToolkitInfo.Identifier == "AuthoredToolkit")); var patternSchema = authoredPatternModel.Create<PatternSchema>(); patternSchema.Name = "FooPattern"; patternSchema.PatternLink = "patternmanager://foo"; patternSchema.UriService = uriService; this.view = patternSchema.Create<ViewSchema>(); this.view.Name = "View1"; store.TransactionManager.DoWithinTransaction(() => { this.authoredExtensionPoint = store.ElementFactory.CreateElement<ExtensionPointSchema>("ExtensionPoint1"); this.view.ExtensionPoints.Add(this.authoredExtensionPoint); }); // Customize Toolkit var tailoredUriService = Mock.Of<IUriReferenceService>( u => u.ResolveUri<IInstanceBase>(It.IsAny<Uri>()) == Mock.Of<IProduct>(p => p.ToolkitInfo.Identifier == "TailoredToolkit")); var tailoredPatternModel = PatternModelSpec.TailorPatternModel(authoredPatternModel, new Version("1.0.0.0"), "AuthoredToolkit"); store.TransactionManager.DoWithinTransaction(() => { tailoredPatternModel.Pattern.UriService = tailoredUriService; tailoredPatternModel.BaseId = "AuthoredToolkit"; }); this.tailoredExtensionPoint = tailoredPatternModel.Pattern.Views[0].ExtensionPoints[0]; }
public virtual void Initialize() { this.store.TransactionManager.DoWithinTransaction(() => { var patternModel = this.store.ElementFactory.CreateElement<PatternModelSchema>(); this.pattern = patternModel.Create<PatternSchema>(); this.view = this.pattern.Create<ViewSchema>(); }); validationContext = new ValidationContext(ValidationCategories.Save, this.pattern); }
public override ViewSchemaCollection GetViews () { ViewSchemaCollection views = new ViewSchemaCollection (); using (IPooledDbConnection conn = connectionPool.Request ()) { using (IDbCommand command = conn.CreateCommand (@"SELECT su.name AS owner, so.name as table_name, so.id as table_id, so.crdate as created_date, so.xtype as table_type FROM dbo.sysobjects so, dbo.sysusers su WHERE xtype = 'V' AND su.uid = so.uid ORDER BY 1, 2")) try { using (command) { using (IDataReader r = command.ExecuteReader()) { while (r.Read()) { ViewSchema view = new ViewSchema (this); view.Name = r.GetString (1); view.SchemaName = r.GetString (0); view.OwnerName = r.GetString (0); StringBuilder sb = new StringBuilder(); sb.AppendFormat ("-- View: {0}\n", view.Name); sb.AppendFormat ("-- DROP VIEW {0};\n\n", view.Name); sb.AppendFormat (" {0}\n);", GetSource ("[" + view.OwnerName + "].[" + view.Name + "]")); view.Definition = sb.ToString (); views.Add (view); } r.Close (); } } } catch (Exception e) { QueryService.RaiseException (e); } finally { conn.Release (); } } return views;
public override ColumnSchemaCollection GetViewColumns (ViewSchema view) { ColumnSchemaCollection columns = new ColumnSchemaCollection (); using (IPooledDbConnection conn = connectionPool.Request ()) { using (IDbCommand command = conn.CreateCommand (string.Format("SELECT * FROM \"{0}\" WHERE 1 = 0", view.Name))) try { using (IDataReader r = command.ExecuteReader()) { for (int i = 0; i < r.FieldCount; i++) { ColumnSchema column = new ColumnSchema (this, view); column.Name = r.GetName(i); column.DataTypeName = r.GetDataTypeName(i); column.DefaultValue = ""; column.Definition = ""; column.OwnerName = view.OwnerName; column.SchemaName = view.OwnerName; columns.Add (column); } r.Close (); } } catch (Exception e) { QueryService.RaiseException (e); } finally { conn.Release (); } } return columns;
//http://dev.mysql.com/doc/refman/5.1/en/create-view.html public override void CreateView (ViewSchema view) { ExecuteNonQuery (view.Definition); }
//http://dev.mysql.com/doc/refman/5.1/en/drop-view.html public override void DropView (ViewSchema view) { ExecuteNonQuery (string.Concat("DROP VIEW IF EXISTS ", view.Name, ";")); }
public ViewColumnSchema[] GetViewColumns(string connectionString, ViewSchema view) { return new ViewColumnSchema[0]; }
public string GetViewText(string connectionString, ViewSchema view) { return ""; }
//http://msdn2.microsoft.com/en-US/library/aa238878(SQL.80).aspx public override void RenameView (ViewSchema view, string name) { Rename (view.Name, name, "OBJECT"); view.Name = name;
protected override DatabaseSchema ReadSourceSchema(SqlConnection sqlServerConnection, SqlConversionHandler handler, SqlTableSelectionHandler selectionHandler) { // First step is to read the names of all tables in the database List<TableSchema> tables = new List<TableSchema>(); sqlServerConnection.Open(); //Logging.Log(LogLevel.Debug, "SQL Server Connection initialized"); List<string> tableNames = new List<string>(); List<string> tblschema = new List<string>(); // Initialize in clause for schemas and tables. //Logging.Log(LogLevel.Debug, "Intializing schemas and tables to load where clauses"); string schemasToLoad = Utilities.ContainsSchemaInfo(TablesToLoad) ? Utilities.ConvertTableToLoadToInClause(TablesToLoad, true, "TABLE_SCHEMA").ToUpper() : string.Empty; //if (schemasToLoad != string.Empty) //Logging.Log(LogLevel.Debug, string.Format("Schemas IN clause: {0}", schemasToLoad)); string tablesToLoad = TablesToLoad.Count > 0 ? Utilities.ConvertTableToLoadToInClause(TablesToLoad, false, "TABLE_NAME").ToUpper() : string.Empty; //if (tablesToLoad != string.Empty) //Logging.Log(LogLevel.Debug, string.Format("Tables IN clause: {0}", tablesToLoad)); string whereClause = string.Empty; if (schemasToLoad != string.Empty && tablesToLoad != string.Empty) whereClause = string.Format(" AND {0} AND {1} ", schemasToLoad, tablesToLoad); else if (schemasToLoad != string.Empty && tablesToLoad == string.Empty) whereClause = string.Format(" AND {0} ", schemasToLoad); else if (schemasToLoad == string.Empty && tablesToLoad != string.Empty) whereClause = string.Format(" AND {0} ", tablesToLoad); //Logging.Log(LogLevel.Debug, "Intializing SQL statement"); // This command will read the names of all tables in the database string sqlQuery = string.Format(@"select * from INFORMATION_SCHEMA.TABLES where TABLE_TYPE = 'BASE TABLE'{0}", whereClause); //Logging.Log(LogLevel.Debug, string.Format("Sql Server INFORMATION_SCHEMA.TABLES query: \n\n{0}\n\n", sqlQuery)); SqlCommand cmd = new SqlCommand(sqlQuery, sqlServerConnection); //Logging.Log(LogLevel.Debug, "SqlCommand initialized"); using (SqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { tableNames.Add((string)reader["TABLE_NAME"]); tblschema.Add((string)reader["TABLE_SCHEMA"]); } } // Next step is to use ADO APIs to query the schema of each table. int count = 0; for (int i = 0; i < tableNames.Count; i++) { string tname = tableNames[i]; string tschma = tblschema[i]; string fullName = tschma + "." + tname; // Load only the tables in TablesToLoad. if (TablesToLoad.Count > 0 && !TablesToLoad.Exists(t => t.SqlServerFullName.ToLower() == fullName.ToLower())) continue; TableSchema ts = CreateTableSchema(sqlServerConnection, tname, tschma); CreateForeignKeySchema(sqlServerConnection, ts); tables.Add(ts); count++; CheckCancelled(); handler(false, true, (int)(count * 50.0 / tableNames.Count), "Parsed table " + tname); //Logging.Log(LogLevel.Debug, "parsed table schema for [" + tname + "]"); } sqlServerConnection.Close(); //Logging.Log(LogLevel.Debug, "finished parsing all tables in SQL Server schema"); // Allow the user a chance to select which tables to convert, only if the TablesToLoad list isn't defined. if (selectionHandler != null && TablesToLoad.Count > 0) { List<TableSchema> updated = selectionHandler(tables); if (updated != null) tables = updated; } Regex removedbo = new Regex(@"dbo\.", RegexOptions.Compiled | RegexOptions.IgnoreCase); // Continue and read all of the views in the database List<ViewSchema> views = new List<ViewSchema>(); sqlServerConnection.Open(); cmd = new SqlCommand(@"SELECT TABLE_NAME, VIEW_DEFINITION from INFORMATION_SCHEMA.VIEWS", sqlServerConnection); using (SqlDataReader reader = cmd.ExecuteReader()) { count = 0; while (reader.Read()) { ViewSchema vs = new ViewSchema(); vs.ViewName = (string)reader["TABLE_NAME"]; vs.ViewSQL = (string)reader["VIEW_DEFINITION"]; // Remove all ".dbo" strings from the view definition vs.ViewSQL = removedbo.Replace(vs.ViewSQL, string.Empty); views.Add(vs); count++; CheckCancelled(); handler(false, true, 50 + (int)(count * 50.0 / views.Count), "Parsed view " + vs.ViewName); //Logging.Log(LogLevel.Debug, "parsed view schema for [" + vs.ViewName + "]"); } } sqlServerConnection.Close(); DatabaseSchema ds = new DatabaseSchema(); ds.Tables = tables; ds.Views = views; return ds; }
public override ViewSchemaCollection GetViews () { ViewSchemaCollection views = new ViewSchemaCollection (); using (IPooledDbConnection conn = connectionPool.Request ()) { using (IDbCommand command = conn.CreateCommand (string.Format ( @"SELECT v.schemaname, v.viewname, v.viewowner, v.definition, (c.oid <= {0}), (SELECT description from pg_description pd, pg_class pc WHERE pc.oid = pd.objoid AND pc.relname= v.viewname) FROM pg_views v, pg_class c WHERE v.viewname = c.relname ORDER BY viewname", LastSystemOID))) { try { using (IDataReader r = command.ExecuteReader()) { while (r.Read ()) { ViewSchema view = new ViewSchema (this); view.Name = r.GetString (1); view.OwnerName = r.GetString (2); view.SchemaName = r.GetString (0); view.IsSystemView = r.GetBoolean (4); view.Comment = r.IsDBNull (5) ? null : r.GetString (5); // TODO: Fill view.Definition views.Add (view); } r.Close (); } } catch (Exception e) { QueryService.RaiseException (e); } finally { conn.Release (); } } } return views;
public DataTable GetViewData(string connectionString, ViewSchema view) { return new DataTable(); }
private Entity GetEntity(EntityContext entityContext, ViewSchema viewSchema) { string key = viewSchema.FullName; Entity entity = entityContext.Entities.ByTable(key) ?? CreateEntity(entityContext, viewSchema); if (!entity.Properties.IsProcessed) CreateProperties(entity, viewSchema.Columns); entity.IsProcessed = true; return entity; }
//http://www.postgresql.org/docs/8.2/interactive/sql-createview.html public override void CreateView (ViewSchema view) { throw new NotImplementedException ();
public override string GetViewAlterStatement (ViewSchema view) { return String.Concat ("DROP VIEW ", view.Name, "; ", Environment.NewLine, view.Definition);
public System.Data.DataTable GetViewData(string connectionString, ViewSchema view) { using (SQLiteConnection conn = GetConnection(connectionString)) { using (SQLiteCommand cmd = conn.CreateCommand()) { cmd.CommandType = CommandType.TableDirect; cmd.CommandText = view.Name; SQLiteDataAdapter da = new SQLiteDataAdapter(); da.SelectCommand = cmd; DataSet ds = new DataSet(); da.Fill(ds); return ds.Tables[0]; } } }
//http://www.postgresql.org/docs/8.2/interactive/sql-altertable.html public override void RenameView (ViewSchema view, string name) { //this is no copy paste error, it really is "ALTER TABLE" ExecuteNonQuery (string.Concat("ALTER TABLE ", view.Name, " RENAME TO ", name, ";")); view.Name = name;
public string GetViewText(string connectionString, ViewSchema view) { DataTable dt = GetSchemaData(connectionString, Views, null /*restrictions[0] - catalog*/, null /*restrictions[1] - unused*/, view.Name /*restrictions[2] - view*/); if (dt.Rows.Count != 1) { throw new ArgumentException(String.Format("Unexpected number of rows in Views collection for view {0}", view.Name)); } return (String)dt.Rows[0][ViewsTextColumn]; }
public override string GetViewAlterStatement (ViewSchema view) { return view.Definition.Insert (8, "OR REPLACE ");