public LegacyDbExpressionConverterTests() { const string ssdl = "<Schema Namespace='AdventureWorksModel.Store' Provider='System.Data.SqlClient' ProviderManifestToken='2008' xmlns='http://schemas.microsoft.com/ado/2009/11/edm/ssdl'>" + " <EntityContainer Name='AdventureWorksModelStoreContainer'>" + " <EntitySet Name='EntitiesSet' EntityType='AdventureWorksModel.Store.Entities' Schema='dbo' />" + " <EntitySet Name='OtherEntitiesSet' EntityType='AdventureWorksModel.Store.OtherEntities' Schema='dbo' />" + " </EntityContainer>" + " <EntityType Name='Entities'>" + " <Key>" + " <PropertyRef Name='Id' />" + " </Key>" + " <Property Name='Id' Type='int' StoreGeneratedPattern='Identity' Nullable='false' />" + " <Property Name='Name' Type='nvarchar(max)' Nullable='false' />" + " </EntityType>" + " <EntityType Name='OtherEntities'>" + " <Key>" + " <PropertyRef Name='Id' />" + " </Key>" + " <Property Name='Id' Type='int' StoreGeneratedPattern='Identity' Nullable='false' />" + " <Property Name='Name' Type='nvarchar(max)' Nullable='false' />" + " </EntityType>" + "</Schema>"; _storeItemCollection = Utils.CreateStoreItemCollection(ssdl); _legacyStoreItemCollection = _storeItemCollection.ToLegacyStoreItemCollection(); _legacyDbExpressionConverter = new LegacyDbExpressionConverter(_legacyStoreItemCollection); }
/// <summary> /// Returns a <see cref="DbSchema"/> object that represents the metadata contained /// by the specified StoreItemCollection. If no such element exist, the specified /// factory method is used to create one. /// </summary> /// <param name="metadata"> /// The StoreItemCollection object that contains the metadata. /// </param> /// <param name="schemaFactoryMethod"> /// The factory method that instantiates the desired element. /// </param> /// <returns> /// The DbSchema object. /// </returns> public static DbSchema GetDbSchema( StoreItemCollection metadata, Func<StoreItemCollection, DbSchema> schemaFactoryMethod) { return store.Get( new DbSchemaKey(metadata), () => schemaFactoryMethod(metadata)); }
public static MetadataWorkspace CreateMetadataWorkspace(List<XElement> csdl, List<XElement> ssdl, List<XElement> msl) { EdmItemCollection eic = new EdmItemCollection(csdl.Select(c => c.CreateReader())); StoreItemCollection sic = new StoreItemCollection(ssdl.Select(c => c.CreateReader())); StorageMappingItemCollection smic = new StorageMappingItemCollection(eic, sic, msl.Select(c => c.CreateReader())); // and create metadata workspace based on them. #if !EFOLD MetadataWorkspace workspace = new MetadataWorkspace( () => eic, () => sic, () => smic); #else // Obsolete API MetadataWorkspace workspace = new MetadataWorkspace(); workspace.RegisterItemCollection(eic); workspace.RegisterItemCollection(sic); workspace.RegisterItemCollection(smic); #endif return workspace; }
static IEnumerable<string> Tables(StoreItemCollection storeItems) { foreach (var entitySet in storeItems.GetItems<EntityContainer>()[0].BaseEntitySets.OfType<EntitySet>()) { var result = new StringBuilder(); var additionalColumnComments = new Dictionary<string, string>(); result.AppendFormat("RECREATE TABLE {0} (", SqlGenerator.QuoteIdentifier(MetadataHelpers.GetTableName(entitySet))); result.AppendLine(); foreach (var property in MetadataHelpers.GetProperties(entitySet.ElementType)) { var column = GenerateColumn(property); result.Append("\t"); result.Append(column.ColumnName); result.Append(","); result.AppendLine(); foreach (var item in column.ColumnComments) additionalColumnComments.Add(item.Key, item.Value); } result.AppendFormat("CONSTRAINT {0} PRIMARY KEY ({1})", SqlGenerator.QuoteIdentifier(string.Format("PK_{0}", MetadataHelpers.GetTableName(entitySet))), string.Join(", ", entitySet.ElementType.KeyMembers.Select(pk => SqlGenerator.QuoteIdentifier(pk.Name)))); result.AppendLine(); result.Append(");"); result.AppendLine(); foreach (var identity in entitySet.ElementType.KeyMembers.Where(pk => MetadataHelpers.IsStoreGeneratedIdentity(pk)).Select(i => i.Name)) { additionalColumnComments.Add(identity, "#PK_GEN#"); } foreach (var comment in additionalColumnComments) { result.AppendFormat("COMMENT ON COLUMN {0}.{1} IS '{2}';", SqlGenerator.QuoteIdentifier(MetadataHelpers.GetTableName(entitySet)), SqlGenerator.QuoteIdentifier(comment.Key), comment.Value); result.AppendLine(); } yield return result.ToString(); } }
public static DbSchema CreateDbSchema(StoreItemCollection edmStoreSchema) { EdmTypeConverter converter = new EdmTypeConverter(new DefaultTypeConverter()); CanonicalContainer container = new CanonicalContainer(edmStoreSchema, converter); IBareSchema bareSchema = new DynamicBareSchema(container); TableConfigurationGroup tableConfig = new TableConfigurationGroup(); tableConfig.Register(new BareSchemaConfiguration(bareSchema)); tableConfig.Register<PrimaryKeyConfiguration>(); tableConfig.Register<IdentityConfiguration>(); tableConfig.Register<GeneratedGuidConfiguration>(); tableConfig.Register<NotNullConfiguration>(); tableConfig.Register<VarcharLimitConfiguration>(); tableConfig.Register<CharLimitConfiguration>(); tableConfig.Register<IndexConfiguration>(); DbSchemaBuilder schemaBuilder = new DbSchemaBuilder(); foreach (EntityInfo entityInfo in container.Entities) { DbTableInfoBuilder tableBuilder = new DbTableInfoBuilder(); // Run all configurations tableConfig.Configure(entityInfo, tableBuilder); schemaBuilder.Register(tableBuilder); } RelationConfigurationGroup associationConfig = new RelationConfigurationGroup(); associationConfig.Register<RelationConfiguration>(); foreach (AssociationInfo associationInfo in container.Associations) { associationConfig.Configure(associationInfo, schemaBuilder); } return schemaBuilder.Create(); }
static IEnumerable<string> ForeignKeyConstraints(StoreItemCollection storeItems) { foreach (var associationSet in storeItems.GetItems<EntityContainer>()[0].BaseEntitySets.OfType<AssociationSet>()) { var result = new StringBuilder(); ReferentialConstraint constraint = associationSet.ElementType.ReferentialConstraints.Single<ReferentialConstraint>(); AssociationSetEnd end = associationSet.AssociationSetEnds[constraint.FromRole.Name]; AssociationSetEnd end2 = associationSet.AssociationSetEnds[constraint.ToRole.Name]; result.AppendFormat("ALTER TABLE {0} ADD CONSTRAINT {1} FOREIGN KEY ({2})", SqlGenerator.QuoteIdentifier(MetadataHelpers.GetTableName(end2.EntitySet)), SqlGenerator.QuoteIdentifier(string.Format("FK_{0}", associationSet.Name)), constraint.ToProperties.Select(fk => SqlGenerator.QuoteIdentifier(fk.Name)).StringJoin(", ")); result.AppendLine(); result.AppendFormat("REFERENCES {0}({1})", SqlGenerator.QuoteIdentifier(MetadataHelpers.GetTableName(end.EntitySet)), constraint.FromProperties.Select(pk => SqlGenerator.QuoteIdentifier(pk.Name)).StringJoin(", ")); result.AppendLine(); result.AppendFormat("ON DELETE {0}", end.CorrespondingAssociationEndMember.DeleteBehavior == OperationAction.Cascade ? "CASCADE" : "NO ACTION"); result.Append(";"); yield return result.ToString(); } }
public static string Transform(StoreItemCollection storeItems, string providerManifestToken) { var result = new StringBuilder(); if (storeItems == null) { result.Append("-- No input."); return result.ToString(); } result.Append("-- Tables"); result.AppendLine(); result.Append(string.Join(Environment.NewLine, Tables(storeItems))); result.AppendLine(); result.Append("-- Foreign Key Constraints"); result.AppendLine(); result.Append(string.Join(Environment.NewLine, ForeignKeyConstraints(storeItems))); result.AppendLine(); result.AppendLine(); result.Append("-- EOF"); return result.ToString(); }
/// <summary> /// Generates a data definition langauge (DDL0 script that creates schema objects (tables, primary keys, foreign keys) based on the contents of the <see cref="T:System.Data.Metadata.Edm.StoreItemCollection"/> parameter and targeted for the version of the database corresponding to the provider manifest token. /// </summary> /// <param name="providerManifestToken">The provider manifest token identifying the target version.</param> /// <param name="storeItemCollection">The structure of the database.</param> /// <returns> /// A DDL script that creates schema objects based on the contents of the <see cref="T:System.Data.Metadata.Edm.StoreItemCollection"/> parameter and targeted for the version of the database corresponding to the provider manifest token. /// </returns> protected override string DbCreateDatabaseScript(string providerManifestToken, StoreItemCollection storeItemCollection) { if (string.IsNullOrEmpty(providerManifestToken)) { throw new ArgumentNullException("providerManifestToken"); } string providerInvariantName; string realToken; // check if the name of the wrapped provider is specified in the token int p = providerManifestToken.IndexOf(';'); if (p < 0) { // wrapped provider is not in the token - use default one realToken = providerManifestToken; providerInvariantName = this.DefaultWrappedProviderName; } else { // extract provider name from the token providerInvariantName = providerManifestToken.Substring(0, p); realToken = providerManifestToken.Substring(p + 1); } // retrieve wrapped provider manifest DbProviderServices services = GetProviderServicesByName(providerInvariantName); return services.CreateDatabaseScript(realToken, storeItemCollection); }
/// <summary> /// Initializes a new FunctionImportMappingComposable instance. /// </summary> /// <param name="functionImport">The model function import.</param> /// <param name="targetFunction">The store composable function.</param> /// <param name="resultMapping">The result mapping for the function import.</param> /// <param name="containerMapping">The parent container mapping.</param> public FunctionImportMappingComposable( EdmFunction functionImport, EdmFunction targetFunction, FunctionImportResultMapping resultMapping, EntityContainerMapping containerMapping) : base( Check.NotNull(functionImport, "functionImport"), Check.NotNull(targetFunction, "targetFunction")) { Check.NotNull(resultMapping, "resultMapping"); Check.NotNull(containerMapping, "containerMapping"); if (!functionImport.IsComposableAttribute) { throw new ArgumentException(Strings.NonComposableFunctionCannotBeMappedAsComposable("functionImport")); } if (!targetFunction.IsComposableAttribute) { throw new ArgumentException(Strings.NonComposableFunctionCannotBeMappedAsComposable("targetFunction")); } EdmType resultType; if (!MetadataHelper.TryGetFunctionImportReturnType(functionImport, 0, out resultType)) { throw new ArgumentException(Strings.InvalidReturnTypeForComposableFunction); } // when this method is invoked when a CodeFirst model is being built (e.g. from a custom convention) the // StorageMappingItemCollection will be null. In this case we can call the converting method directly which // will return the correct result but the result won't be memoized. This however does not matter at this // point since the model is still being constructed. var cTypeTargetFunction = containerMapping.StorageMappingItemCollection != null ? containerMapping.StorageMappingItemCollection.StoreItemCollection.ConvertToCTypeFunction(targetFunction) : StoreItemCollection.ConvertFunctionSignatureToCType(targetFunction); var cTypeTvfElementType = TypeHelpers.GetTvfReturnType(cTypeTargetFunction); var sTypeTvfElementType = TypeHelpers.GetTvfReturnType(targetFunction); if (cTypeTvfElementType == null) { Debug.Assert(sTypeTvfElementType == null); throw new ArgumentException( Strings.Mapping_FunctionImport_ResultMapping_InvalidSType(functionImport.Identity), "functionImport"); } var errors = new List <EdmSchemaError>(); var functionImportHelper = new FunctionImportMappingComposableHelper( containerMapping, String.Empty, errors); FunctionImportMappingComposable mapping; if (Helper.IsStructuralType(resultType)) { functionImportHelper.TryCreateFunctionImportMappingComposableWithStructuralResult( functionImport, cTypeTargetFunction, resultMapping.SourceList, cTypeTvfElementType, sTypeTvfElementType, LineInfo.Empty, out mapping); } else { Debug.Assert(TypeSemantics.IsScalarType(resultType)); Debug.Assert(resultMapping.TypeMappings.Count == 0); functionImportHelper.TryCreateFunctionImportMappingComposableWithScalarResult( functionImport, cTypeTargetFunction, targetFunction, resultType, cTypeTvfElementType, LineInfo.Empty, out mapping); } if (mapping == null) { throw new InvalidOperationException(errors.Count > 0 ? errors[0].Message : String.Empty); } _containerMapping = mapping._containerMapping; m_commandParameters = mapping.m_commandParameters; m_structuralTypeMappings = mapping.m_structuralTypeMappings; m_targetFunctionKeys = mapping.m_targetFunctionKeys; _resultMapping = resultMapping; }
protected override void DbCreateDatabase(DbConnection connection, int?commandTimeout, StoreItemCollection storeItemCollection) { UsingPostgresDBConnection((NpgsqlConnection)connection, conn => { var sb = new StringBuilder(); sb.Append("CREATE DATABASE \""); sb.Append(connection.Database); sb.Append("\""); if (conn.EntityTemplateDatabase != null) { sb.Append(" TEMPLATE \""); sb.Append(conn.EntityTemplateDatabase); sb.Append("\""); } using (NpgsqlCommand command = new NpgsqlCommand(sb.ToString(), conn)) { command.ExecuteNonQuery(); } }); }
/// <summary> /// Returns a value indicating whether a given database exists on the server and whether schema objects contained in the storeItemCollection have been created. /// </summary> /// <param name="connection">Connection to a database whose existence is verified by this method.</param> /// <param name="commandTimeout">Execution timeout for any commands needed to determine the existence of the database.</param> /// <param name="storeItemCollection">The structure of the database whose existence is determined by this method.</param> /// <returns> /// true if the database indicated by the connection and the <paramref name="storeItemCollection"/> parameter exists. /// </returns> protected override bool DbDatabaseExists(DbConnection connection, int? commandTimeout, StoreItemCollection storeItemCollection) { var wrappedConnection = ((DbConnectionWrapper)connection).WrappedConnection; var services = DbProviderServices.GetProviderServices(wrappedConnection); return services.DatabaseExists(wrappedConnection, commandTimeout, storeItemCollection); }
protected override void DbDeleteDatabase(DbConnection connection, int? commandTimeout, StoreItemCollection storeItemCollection) { InnerProviderServices.DeleteDatabase(((GlimpseDbConnection)connection).InnerConnection, commandTimeout, storeItemCollection); }
public bool IsInitialized(StoreItemCollection edmStoreSchema) { // TODO: Lock if (this.database == null) { return false; } // Find container EntityContainer entityContainer = edmStoreSchema.GetItems<EntityContainer>().FirstOrDefault(); foreach (EntitySet entitySet in entityContainer.BaseEntitySets.OfType<EntitySet>()) { // TODO: Verify fields if (!this.Internal.ContainsTable(entitySet.GetTableName())) { return false; } } return true; }
protected override void DbCreateDatabase(DbConnection connection, int? commandTimeout, #pragma warning disable 3001 StoreItemCollection storeItemCollection) #pragma warning restore 3001 { FbConnection.CreateDatabase(connection.ConnectionString, 16384, true, false); string script = DbCreateDatabaseScript(GetDbProviderManifestToken(connection), storeItemCollection); FbScript fbScript = new FbScript(script); fbScript.Parse(); using (var fbConnection = new FbConnection(connection.ConnectionString)) { var execution = new FbBatchExecution(fbConnection); execution.AppendSqlStatements(fbScript); execution.Execute(); } }
public static EntityConnection Create( List <DatabaseSpecificModification> tableAndColumn, string connString, string model) { var conceptualReader = XmlReader.Create( Assembly .GetExecutingAssembly() .GetManifestResourceStream(model + ".csdl") ); var mappingReader = XmlReader.Create( Assembly .GetExecutingAssembly() .GetManifestResourceStream(model + ".msl") ); var storageReader = XmlReader.Create( Assembly .GetExecutingAssembly() .GetManifestResourceStream(model + ".ssdl") ); var conceptualXml = XElement.Load(conceptualReader); var mappingXml = XElement.Load(mappingReader); var storageXml = XElement.Load(storageReader); Action <XElement> removeNodes = (element) => { if (element.Attribute("Name") != null && tableAndColumn.Any(oo => oo.Table == element.Attribute("Name").Value) || element.Attribute("StoreEntitySet") != null && tableAndColumn.Any(oo => oo.Table == element.Attribute("StoreEntitySet").Value)) { var matchingSelectParts = tableAndColumn.Where(oo => element.Value.Contains(string.Format("\"{0}\".\"{1}\" AS \"{1}\"", oo.Table, oo.Column))); if (matchingSelectParts.Any()) { foreach (var matchingSelectPart in matchingSelectParts) { var definingQuery = element.ElementsAnyNS("DefiningQuery").Single(); definingQuery.Value = definingQuery.Value.Replace(string.Format(", \n\"{0}\".\"{1}\" AS \"{1}\"", matchingSelectPart.Table, matchingSelectPart.Column), ""); } } else { var nodes = element.Nodes() .Where(o => o is XElement && ((XElement)o).Attribute("Name") != null && tableAndColumn.Any(oo => ((XElement)o).Attribute("Name").Value == oo.Column)); foreach (var node in nodes.ToList()) { node.Remove(); } } } }; foreach (var entitySet in storageXml.Elements()) { if (entitySet.Attribute("Name").Value == "ModelStoreContainer") { foreach (var entityContainerEntitySet in entitySet.Elements()) { removeNodes(entityContainerEntitySet); } } removeNodes(entitySet); } foreach (var entitySet in conceptualXml.Elements()) { if (entitySet.Attribute("Name").Value == "ModelStoreContainer") { foreach (var entityContainerEntitySet in entitySet.Elements()) { removeNodes(entityContainerEntitySet); } } removeNodes(entitySet); } foreach (var entitySet in mappingXml.Elements().ElementAt(0).Elements()) { if (entitySet.Name.LocalName == "EntitySetMapping") { foreach (var entityContainerEntitySet in entitySet.Elements().First().Elements()) { removeNodes(entityContainerEntitySet); } } removeNodes(entitySet); } storageXml.CreateReader(); StoreItemCollection storageCollection = new StoreItemCollection( new XmlReader[] { storageXml.CreateReader() } ); EdmItemCollection conceptualCollection = new EdmItemCollection(new [] { conceptualXml.CreateReader() }); StorageMappingItemCollection mappingCollection = new StorageMappingItemCollection( conceptualCollection, storageCollection, new [] { mappingXml.CreateReader() } ); var workspace = new MetadataWorkspace(); workspace.RegisterItemCollection(conceptualCollection); workspace.RegisterItemCollection(storageCollection); workspace.RegisterItemCollection(mappingCollection); var connectionData = new EntityConnectionStringBuilder(connString); var connection = DbProviderFactories .GetFactory(connectionData.Provider) .CreateConnection(); connection.ConnectionString = connectionData.ProviderConnectionString; return(new EntityConnection(workspace, connection)); }
protected override void DbDeleteDatabase(DbConnection connection, int?commandTimeout, StoreItemCollection storeItemCollection) { InnerProviderServices.DeleteDatabase(((GlimpseDbConnection)connection).InnerConnection, commandTimeout, storeItemCollection); }
protected override bool DbDatabaseExists(DbConnection connection, int?commandTimeout, StoreItemCollection storeItemCollection) { return(InnerProviderServices.DatabaseExists(((GlimpseDbConnection)connection).InnerConnection, commandTimeout, storeItemCollection)); }
protected override void DbCreateDatabase(DbConnection connection, int?commandTimeout, StoreItemCollection storeItemCollection) { _providerServices.CreateDatabase(connection, commandTimeout, storeItemCollection); }
public WSJDE() : base("name=WSJDE") { ObjectContext context = (this as IObjectContextAdapter).ObjectContext; string environment = ConfigurationManager.AppSettings.Get("Environment"); const string devCTL = "TESTCTL"; const string devDTA = "TESTDTA"; const string qaCTL = "CRPCTL"; const string qaDTA = "CRPDTA"; const string prodCTL = "PRODCTL"; const string prodDTA = "PRODDTA"; var x = Assembly.GetExecutingAssembly().GetManifestResourceStream("WSJDEData.WSJDE.ssdl"); XmlReader[] sReaders = new XmlReader[] { XmlReader.Create(Assembly.GetExecutingAssembly().GetManifestResourceStream("WSJDEData.WSJDE.ssdl")) }; XmlReader[] mReaders = new XmlReader[] { XmlReader.Create(Assembly.GetExecutingAssembly().GetManifestResourceStream("WSJDEData.WSJDE.msl")) }; StoreItemCollection sCollection = new StoreItemCollection(sReaders); ObjectContext objContext = ((IObjectContextAdapter)context).ObjectContext; MetadataWorkspace workspace = objContext.MetadataWorkspace; EdmItemCollection cCollection = workspace.GetItemCollection(DataSpace.CSpace) as EdmItemCollection; StorageMappingItemCollection csCollection = new StorageMappingItemCollection(cCollection, sCollection, mReaders); workspace.RegisterItemCollection(sCollection); workspace.RegisterItemCollection(csCollection); EntityContainer container = workspace.GetItem <EntityContainer>("WSJDEModelStoreContainer", DataSpace.SSpace); foreach (EntitySetBase entitySetBase in container.BaseEntitySets) { string schema = entitySetBase.Schema; if (schema != null) { string name = schema.Substring(schema.Length - 3); if (name == "CTL") { switch (environment) { case "Dev": typeof(EntitySetBase).GetField("_schema", BindingFlags.NonPublic | BindingFlags.Instance) .SetValue(entitySetBase, devCTL); break; case "QA": typeof(EntitySetBase).GetField("_schema", BindingFlags.NonPublic | BindingFlags.Instance) .SetValue(entitySetBase, qaCTL); break; case "Prod": typeof(EntitySetBase).GetField("_schema", BindingFlags.NonPublic | BindingFlags.Instance) .SetValue(entitySetBase, prodCTL); break; } } if (name == "DTA") { switch (environment) { case "Dev": typeof(EntitySetBase).GetField("_schema", BindingFlags.NonPublic | BindingFlags.Instance) .SetValue(entitySetBase, devDTA); break; case "QA": typeof(EntitySetBase).GetField("_schema", BindingFlags.NonPublic | BindingFlags.Instance) .SetValue(entitySetBase, qaDTA); break; case "Prod": typeof(EntitySetBase).GetField("_schema", BindingFlags.NonPublic | BindingFlags.Instance) .SetValue(entitySetBase, prodDTA); break; } } } } }
/// <summary> /// Generates a data definition langauge (DDL0 script that creates schema objects (tables, primary keys, foreign keys) based on the contents of the <see cref="T:System.Data.Metadata.Edm.StoreItemCollection"/> parameter and targeted for the version of the database corresponding to the provider manifest token. /// </summary> /// <param name="providerManifestToken">The provider manifest token identifying the target version.</param> /// <param name="storeItemCollection">The structure of the database.</param> /// <returns> /// A DDL script that creates schema objects based on the contents of the <see cref="T:System.Data.Metadata.Edm.StoreItemCollection"/> parameter and targeted for the version of the database corresponding to the provider manifest token. /// </returns> protected override string DbCreateDatabaseScript(string providerManifestToken, StoreItemCollection storeItemCollection) { if (string.IsNullOrEmpty(providerManifestToken)) { throw new ArgumentNullException("providerManifestToken"); } string providerInvariantName; string realToken; // check if the name of the wrapped provider is specified in the token int p = providerManifestToken.IndexOf(';'); if (p < 0) { // wrapped provider is not in the token - use default one realToken = providerManifestToken; providerInvariantName = this.DefaultWrappedProviderName; } else { // extract provider name from the token providerInvariantName = providerManifestToken.Substring(0, p); realToken = providerManifestToken.Substring(p + 1); } // retrieve wrapped provider manifest DbProviderServices services = GetProviderServicesByName(providerInvariantName); return(services.CreateDatabaseScript(realToken, storeItemCollection)); }
/// <summary> /// Deletes all store objects specified in the store item collection from the database and the database itself. /// </summary> /// <param name="connection">Connection to an existing database that needs to be deleted.</param> /// <param name="commandTimeout">Execution timeout for any commands needed to delete the database.</param> /// <param name="storeItemCollection">The structure of the database to be deleted.</param> protected override void DbDeleteDatabase(DbConnection connection, int?commandTimeout, StoreItemCollection storeItemCollection) { var wrappedConnection = ((DbConnectionWrapper)connection).WrappedConnection; var services = DbProviderServices.GetProviderServices(wrappedConnection); services.DeleteDatabase(wrappedConnection, commandTimeout, storeItemCollection); }
protected override string DbCreateDatabaseScript(string providerManifestToken, StoreItemCollection storeItemCollection) { if (providerManifestToken == null) { throw new ArgumentNullException("providerManifestToken must not be null"); } if (storeItemCollection == null) { throw new ArgumentNullException("storeItemCollection must not be null"); } return(JetCreateDatabaseSqlGenerator.CreateObjectsScript(storeItemCollection)); }
protected override void DbCreateDatabase(DbConnection connection, int? commandTimeout, StoreItemCollection storeItemCollection) { UsingPostgresDBConnection((NpgsqlConnection)connection, conn => { using (NpgsqlCommand command = new NpgsqlCommand("CREATE DATABASE \"" + connection.Database + "\";", conn)) { command.ExecuteNonQuery(); } }); }
/// <summary> /// Creates a database indicated by connection and creates schema objects (tables, primary keys, foreign keys) based on the contents of a StoreItemCollection. /// Note: in EF 6.1 this is not called if the provider implements Migration classes /// Note: we can't create database for Jet Connections /// </summary> /// <param name="connection">Connection to a non-existent database that needs to be created and populated with the store objects indicated with the storeItemCollection parameter.</param> /// <param name="commandTimeout">Execution timeout for any commands needed to create the database.</param> /// <param name="storeItemCollection">The collection of all store items based on which the script should be created.</param> /// <exception cref="System.ArgumentNullException"> /// connection must not be null /// or /// storeItemCollection must not be null /// </exception> /// <exception cref="System.ArgumentException">The connection is not of type 'JetConnection'.</exception> protected override void DbCreateDatabase(DbConnection connection, int?commandTimeout, StoreItemCollection storeItemCollection) { if (connection == null) { throw new ArgumentNullException("connection must not be null"); } if (storeItemCollection == null) { throw new ArgumentNullException("storeItemCollection must not be null"); } JetConnection jetConnection = connection as JetConnection; if (jetConnection == null) { throw new ArgumentException("The connection is not of type 'JetConnection'."); } ConnectionState oldConnectionState = connection.State; if (oldConnectionState == ConnectionState.Closed) { connection.Open(); } foreach (EntityContainer container in storeItemCollection.GetItems <EntityContainer>()) { var entitySets = container.BaseEntitySets.OfType <EntitySet>().OrderBy(s => s.Name); foreach (EntitySet entitySet in container.BaseEntitySets.OfType <EntitySet>().OrderBy(s => s.Name)) { string createObjectScript = JetCreateDatabaseSqlGenerator.CreateObjectScript(entitySet); jetConnection.CreateCommand(createObjectScript, commandTimeout).ExecuteNonQuery(); } foreach (AssociationSet associationSet in container.BaseEntitySets.OfType <AssociationSet>().OrderBy(s => s.Name)) { string createObjectScript = JetCreateDatabaseSqlGenerator.CreateObjectScript(associationSet); jetConnection.CreateCommand(createObjectScript, commandTimeout).ExecuteNonQuery(); } } if (oldConnectionState == ConnectionState.Closed) { connection.Close(); } }
protected override bool DbDatabaseExists(DbConnection connection, int? commandTimeout, #pragma warning disable 3001 StoreItemCollection storeItemCollection) #pragma warning restore 3001 { if (connection.State == ConnectionState.Open || connection.State == ConnectionState.Executing || connection.State == ConnectionState.Fetching) { return true; } else { try { connection.Open(); return true; } catch { return false; } finally { try { connection.Close(); } catch { } } } }
/// <summary> /// Returns a value indicating whether a given database exists on the server. /// </summary> /// <param name="connection">Connection to a database whose existence is checked by this method.</param> /// <param name="commandTimeout">Execution timeout for any commands needed to determine the existence of the database.</param> /// <param name="storeItemCollection">The collection of all store items from the model. This parameter is no longer used for determining database existence.</param> /// <returns> /// True if the provider can deduce the database only based on the connection. /// </returns> /// <exception cref="System.ArgumentNullException"> /// connection must not be null /// or /// storeItemCollection must not be null /// </exception> /// <exception cref="System.ArgumentException">connection must be a valid JetConnection</exception> protected override bool DbDatabaseExists(DbConnection connection, int?commandTimeout, StoreItemCollection storeItemCollection) { if (connection == null) { throw new ArgumentNullException("connection must not be null"); } if (storeItemCollection == null) { throw new ArgumentNullException("storeItemCollection must not be null"); } JetConnection jetConnection = connection as JetConnection; if (jetConnection == null) { throw new ArgumentException("connection must be a valid JetConnection"); } // No database handling provided for Jet but we need to know if there is at least the migration history table return(jetConnection.TableExists(System.Data.Entity.Migrations.History.HistoryContext.DefaultTableName)); }
protected override string DbCreateDatabaseScript(string providerManifestToken, StoreItemCollection storeItemCollection) { return InnerProviderServices.CreateDatabaseScript(providerManifestToken, storeItemCollection); }
protected override void DbDeleteDatabase(DbConnection connection, int?commandTimeout, StoreItemCollection storeItemCollection) { if (connection == null) { throw new ArgumentNullException("connection must not be null"); } if (storeItemCollection == null) { throw new ArgumentNullException("storeItemCollection must not be null"); } JetConnection jetConnection = connection as JetConnection; if (jetConnection == null) { throw new ArgumentException("connection must be a valid JetConnection"); } // No database handling provided for Jet }
/// <summary> /// Returns a value indicating whether a given database exists on the server and whether schema objects contained in the storeItemCollection have been created. /// </summary> /// <param name="connection">Connection to a database whose existence is verified by this method.</param> /// <param name="commandTimeout">Execution timeout for any commands needed to determine the existence of the database.</param> /// <param name="storeItemCollection">The structure of the database whose existence is determined by this method.</param> /// <returns> /// true if the database indicated by the connection and the <paramref name="storeItemCollection"/> parameter exists. /// </returns> protected override bool DbDatabaseExists(DbConnection connection, int?commandTimeout, StoreItemCollection storeItemCollection) { var wrappedConnection = ((DbConnectionWrapper)connection).WrappedConnection; var services = DbProviderServices.GetProviderServices(wrappedConnection); return(services.DatabaseExists(wrappedConnection, commandTimeout, storeItemCollection)); }
protected override void DbCreateDatabase(DbConnection connection, int?commandTimeout, StoreItemCollection storeItemCollection) { if (connection == null) { throw new ArgumentNullException("connection"); } MySqlConnection conn = connection as MySqlConnection; if (conn == null) { throw new ArgumentException(Resources.ConnectionMustBeOfTypeMySqlConnection, "connection"); } string query = DbCreateDatabaseScript(null, storeItemCollection); using (MySqlConnection c = new MySqlConnection()) { MySqlConnectionStringBuilder sb = new MySqlConnectionStringBuilder(conn.ConnectionString); string dbName = sb.Database; sb.Database = null; c.ConnectionString = sb.ConnectionString; c.Open(); string fullQuery = String.Format("CREATE DATABASE `{0}`; USE `{0}`; {1}", dbName, query); MySqlScript s = new MySqlScript(c, fullQuery); s.Execute(); } }
protected override bool DbDatabaseExists(DbConnection connection, int?commandTimeout, StoreItemCollection storeItemCollection) { bool exists = false; UsingPostgresDBConnection((NpgsqlConnection)connection, conn => { using (NpgsqlCommand command = new NpgsqlCommand("select count(*) from pg_catalog.pg_database where datname = '" + connection.Database + "';", conn)) { exists = Convert.ToInt32(command.ExecuteScalar()) > 0; } }); return(exists); }
protected override bool DbDatabaseExists(DbConnection connection, int?commandTimeout, StoreItemCollection storeItemCollection) { if (connection == null) { throw new ArgumentNullException("connection"); } MySqlConnection conn = connection as MySqlConnection; if (conn == null) { throw new ArgumentException(Resources.ConnectionMustBeOfTypeMySqlConnection, "connection"); } MySqlConnectionStringBuilder builder = new MySqlConnectionStringBuilder(); builder.ConnectionString = conn.ConnectionString; string dbName = builder.Database; builder.Database = null; using (MySqlConnection c = new MySqlConnection(builder.ConnectionString)) { c.Open(); DataTable table = c.GetSchema("Databases", new string[] { dbName }); if (table != null && table.Rows.Count == 1) { return(true); } return(false); } }
protected override void DbDeleteDatabase(DbConnection connection, int?commandTimeout, StoreItemCollection storeItemCollection) { UsingPostgresDBConnection((NpgsqlConnection)connection, conn => { //Close all connections in pool or exception "database used by another user appears" NpgsqlConnection.ClearAllPools(); using (NpgsqlCommand command = new NpgsqlCommand("DROP DATABASE \"" + connection.Database + "\";", conn)) { command.ExecuteNonQuery(); } }); }
protected override void DbDeleteDatabase(DbConnection connection, int?commandTimeout, StoreItemCollection storeItemCollection) { if (connection == null) { throw new ArgumentNullException("connection"); } MySqlConnection conn = connection as MySqlConnection; if (conn == null) { throw new ArgumentException(Resources.ConnectionMustBeOfTypeMySqlConnection, "connection"); } MySqlConnectionStringBuilder builder = new MySqlConnectionStringBuilder(); builder.ConnectionString = conn.ConnectionString; string dbName = builder.Database; builder.Database = null; using (MySqlConnection c = new MySqlConnection(builder.ConnectionString)) { c.Open(); MySqlCommand cmd = new MySqlCommand(String.Format("DROP DATABASE IF EXISTS `{0}`", dbName), c); if (commandTimeout.HasValue) { cmd.CommandTimeout = commandTimeout.Value; } cmd.ExecuteNonQuery(); } }
public static EntityConnection CreateEntityConnectionForOracle(string connectionStringName, string modelName = null, string schemaName = null) { string connString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString; EntityConnectionStringBuilder ecsBuilder = new EntityConnectionStringBuilder(connString); if (modelName == null) { try { // For example: // Metadata = "res://*/Boaud.BoaudModel.csdl|res://*/Boaud.BoaudModel.ssdl|res://*/Boaud.BoaudModel.msl"; // modelName = "Boaud.BoaudModel"; string[] metaArray = ecsBuilder.Metadata.Split('|'); modelName = Path.GetFileNameWithoutExtension(metaArray[0]); } catch { return(null); } } if (schemaName == null) { try { OracleConnectionStringBuilder ocsBuilder = new OracleConnectionStringBuilder(ecsBuilder.ProviderConnectionString); schemaName = ocsBuilder.UserID; } catch { return(null); } } #region Conceptual XmlReader conceptualXmlReader = XmlReader.Create(Assembly.GetExecutingAssembly().GetManifestResourceStream(modelName + ".csdl")); XmlReader[] conceptualXmlReaderArray = new XmlReader[] { conceptualXmlReader }; EdmItemCollection conceptualCollection = new EdmItemCollection(conceptualXmlReaderArray); #endregion #region Store XmlReader storeXmlReader = XmlReader.Create(Assembly.GetExecutingAssembly().GetManifestResourceStream(modelName + ".ssdl")); XElement storeXElement = XElement.Load(storeXmlReader); XNamespace storeXNamespace = "http://schemas.microsoft.com/ado/2009/11/edm/ssdl"; foreach (XElement entitySet in storeXElement.Descendants(storeXNamespace + "EntitySet")) { XAttribute schemaAttribute = entitySet.Attributes("Schema").FirstOrDefault(); if (schemaAttribute != null) { schemaAttribute.SetValue(schemaName); } } StoreItemCollection storeCollection = new StoreItemCollection( new XmlReader[] { storeXElement.CreateReader() } ); #endregion #region Mapping XmlReader mappingXmlReader = XmlReader.Create(Assembly.GetExecutingAssembly().GetManifestResourceStream(modelName + ".msl")); XmlReader[] mappingXmlReaderArray = new XmlReader[] { mappingXmlReader }; StorageMappingItemCollection mappingCollection = new StorageMappingItemCollection( conceptualCollection, storeCollection, mappingXmlReaderArray ); #endregion MetadataWorkspace workspace = new MetadataWorkspace(() => conceptualCollection, () => storeCollection, () => mappingCollection); DbConnection connection = DbProviderFactories.GetFactory(ecsBuilder.Provider).CreateConnection(); connection.ConnectionString = ecsBuilder.ProviderConnectionString; return(new EntityConnection(workspace, connection)); }
protected override void DbCreateDatabase(DbConnection connection, int?commandTimeout, StoreItemCollection storeItemCollection) { UsingPostgresDBConnection((NpgsqlConnection)connection, conn => { using (NpgsqlCommand command = new NpgsqlCommand("CREATE DATABASE \"" + connection.Database + "\";", conn)) { command.ExecuteNonQuery(); } }); }
private static MetadataWorkspace CreateWrappedMetadataWorkspace(string metadata, IEnumerable<string> wrapperProviderNames) { // parse Metadata keyword and load CSDL,SSDL,MSL files into XElement structures... var csdl = new List<XElement>(); var ssdl = new List<XElement>(); var msl = new List<XElement>(); ParseMetadata(metadata, csdl, ssdl, msl); // fix all SSDL files by changing 'Provider' to our provider and modifying foreach (var ssdlFile in ssdl) { foreach (string providerName in wrapperProviderNames) { ssdlFile.Attribute("ProviderManifestToken").Value = ssdl[0].Attribute("Provider").Value + ";" + ssdlFile.Attribute("ProviderManifestToken").Value; ssdlFile.Attribute("Provider").Value = providerName; } } // load item collections from XML readers created from XElements... EdmItemCollection eic = new EdmItemCollection(csdl.Select(c => c.CreateReader())); StoreItemCollection sic = new StoreItemCollection(ssdl.Select(c => c.CreateReader())); StorageMappingItemCollection smic = new StorageMappingItemCollection(eic, sic, msl.Select(c => c.CreateReader())); // and create metadata workspace based on them. #if !EFOLD MetadataWorkspace workspace = new MetadataWorkspace( () => eic, () => sic, () => smic); #else // Obsolete API MetadataWorkspace workspace = new MetadataWorkspace(); workspace.RegisterItemCollection(eic); workspace.RegisterItemCollection(sic); workspace.RegisterItemCollection(smic); #endif return workspace; }
/// <summary> /// Attempts to create a StorageMappingItemCollection from the specified metadata file, EdmItemCollection, and StoreItemCollection /// </summary> public bool TryCreateStorageMappingItemCollection(string sourcePath, EdmItemCollection edmItemCollection, StoreItemCollection storeItemCollection, out StorageMappingItemCollection storageMappingItemCollection) { storageMappingItemCollection = null; if (!ValidateInputPath(sourcePath, _textTransformation)) { return(false); } if (edmItemCollection == null) { throw new ArgumentNullException("edmItemCollection"); } if (storeItemCollection == null) { throw new ArgumentNullException("storeItemCollection"); } ItemCollection itemCollection = null; StorageMappingItemCollectionBuilder collectionBuilder = new StorageMappingItemCollectionBuilder(_textTransformation, edmItemCollection, storeItemCollection); if (collectionBuilder.TryCreateItemCollection(_textTransformation.Host.ResolvePath(sourcePath), out itemCollection)) { storageMappingItemCollection = (StorageMappingItemCollection)itemCollection; } return(storageMappingItemCollection != null); }
/// <summary> /// Deletes all store objects specified in the store item collection from the database and the database itself. /// </summary> /// <param name="connection">Connection to an existing database that needs to be deleted.</param> /// <param name="commandTimeout">Execution timeout for any commands needed to delete the database.</param> /// <param name="storeItemCollection">The structure of the database to be deleted.</param> protected override void DbDeleteDatabase(DbConnection connection, int? commandTimeout, StoreItemCollection storeItemCollection) { var wrappedConnection = ((DbConnectionWrapper)connection).WrappedConnection; var services = DbProviderServices.GetProviderServices(wrappedConnection); services.DeleteDatabase(wrappedConnection, commandTimeout, storeItemCollection); }
public StorageMappingItemCollectionBuilder(DynamicTextTransformation textTransformation, EdmItemCollection edmItemCollection, StoreItemCollection storeItemCollection) : base(textTransformation, MetadataConstants.MSL_EXTENSION, MetadataConstants.MSL_EDMX_SECTION_NAME, MetadataConstants.MSL_ROOT_ELEMENT_NAME) { _edmItemCollection = edmItemCollection; _storeItemCollection = storeItemCollection; }
protected override void DbCreateDatabase(DbConnection connection, int? commandTimeout, #pragma warning disable 3001 StoreItemCollection storeItemCollection) #pragma warning restore 3001 { FbConnection fbConnection = CheckAndCastToFbConnection(connection); string script = DbCreateDatabaseScript(GetDbProviderManifestToken(fbConnection), storeItemCollection); FbScript fbScript = new FbScript(script); fbScript.Parse(); FbConnection.CreateDatabase(fbConnection.ConnectionString); new FbBatchExecution(fbConnection, fbScript).Execute(); }
/** <inheritDoc /> */ protected override bool DbDatabaseExists(DbConnection connection, int?commandTimeout, StoreItemCollection storeItemCollection) { return(_services.DatabaseExists(connection, commandTimeout, storeItemCollection)); }
protected override string DbCreateDatabaseScript(string providerManifestToken, #pragma warning disable 3001 StoreItemCollection storeItemCollection) #pragma warning restore 3001 { return SsdlToFb.Transform(storeItemCollection, providerManifestToken); }
/// <summary> /// API for checkin whether database exists or not. /// This will internally only check whether the file that the connection points to exists or not. /// Note: In case of SQLCE, timeout and storeItemCollection parameters are ignored. /// </summary> /// <param name="connection"> Connection </param> /// <param name="timeOut"> Timeout for internal commands. </param> /// <param name="storeItemCollection"> Item Collection. </param> /// <returns> Bool indicating whether database exists or not. </returns> protected override bool DbDatabaseExists(DbConnection connection, int?timeOut, StoreItemCollection storeItemCollection) { Check.NotNull(connection, "connection"); Check.NotNull(storeItemCollection, "storeItemCollection"); // Validate and cast the connection. ValidateConnection(connection); if (_isLocalProvider) { return(CommonUtils.DatabaseExists(connection.DataSource)); } else { Type rdpType; // If we are working with RDP, then we will need to invoke the APIs through reflection. var engine = RemoteProviderHelper.GetRemoteSqlCeEngine(connection.ConnectionString, out rdpType); Debug.Assert(engine != null); var mi = rdpType.GetMethod("FileExists", new[] { typeof(string), typeof(int?) }); Debug.Assert(mi != null); // We will pass 'timeout' to RDP, this will be used as timeout period for connecting and executing on TDSServer. return((bool)(mi.Invoke(engine, new object[] { connection.DataSource, timeOut }))); } }
protected override void DbDeleteDatabase(DbConnection connection, int? commandTimeout, #pragma warning disable 3001 StoreItemCollection storeItemCollection) #pragma warning restore 3001 { FbConnection.DropDatabase(connection.ConnectionString); }
protected override string DbCreateDatabaseScript(string providerManifestToken, StoreItemCollection storeItemCollection) { StringBuilder sql = new StringBuilder(); sql.AppendLine("-- MySql script"); sql.AppendLine("-- Created on " + DateTime.Now); if (serverVersion == null) serverVersion = new Version(providerManifestToken == null ? "5.5" : providerManifestToken); foreach (EntityContainer container in storeItemCollection.GetItems<EntityContainer>()) { // now output the tables foreach (EntitySet es in container.BaseEntitySets.OfType<EntitySet>()) { sql.Append(GetTableCreateScript(es)); } // now output the foreign keys foreach (AssociationSet a in container.BaseEntitySets.OfType<AssociationSet>()) { sql.Append(GetAssociationCreateScript(a.ElementType)); } } return sql.ToString(); }
public void Initialize(StoreItemCollection edmStoreSchema) { if (this.IsInitialized(edmStoreSchema)) { return; } DbSchema schema = DbSchemaStore.GetDbSchema( edmStoreSchema, sic => DbSchemaFactory.CreateDbSchema(sic)); this.Initialize(schema); }
protected override void DbDeleteDatabase(DbConnection connection, int? commandTimeout, StoreItemCollection storeItemCollection) { if (connection == null) throw new ArgumentNullException("connection"); MySqlConnection conn = connection as MySqlConnection; if (conn == null) throw new ArgumentException(Resources.ConnectionMustBeOfTypeMySqlConnection, "connection"); MySqlConnectionStringBuilder builder = new MySqlConnectionStringBuilder(); builder.ConnectionString = conn.ConnectionString; string dbName = builder.Database; builder.Database = null; using (MySqlConnection c = new MySqlConnection(builder.ConnectionString)) { c.Open(); MySqlCommand cmd = new MySqlCommand(String.Format("DROP DATABASE IF EXISTS `{0}`", dbName), c); if (commandTimeout.HasValue) cmd.CommandTimeout = commandTimeout.Value; cmd.ExecuteNonQuery(); } }
protected override bool DbDatabaseExists(DbConnection connection, int? commandTimeout, StoreItemCollection storeItemCollection) { return InnerProviderServices.DatabaseExists(((GlimpseDbConnection)connection).InnerConnection, commandTimeout, storeItemCollection); }
protected override void DbCreateDatabase(DbConnection connection, int? commandTimeout, StoreItemCollection storeItemCollection) { UsingPostgresDBConnection((NpgsqlConnection)connection, conn => { var sb = new StringBuilder(); sb.Append("CREATE DATABASE \""); sb.Append(connection.Database); sb.Append("\""); if (conn.EntityTemplateDatabase != null) { sb.Append(" TEMPLATE \""); sb.Append(conn.EntityTemplateDatabase); sb.Append("\""); } using (NpgsqlCommand command = new NpgsqlCommand(sb.ToString(), conn)) { command.ExecuteNonQuery(); } }); }
/** <inheritDoc /> */ protected override void DbDeleteDatabase(DbConnection connection, int?commandTimeout, StoreItemCollection storeItemCollection) { _services.DeleteDatabase(connection, commandTimeout, storeItemCollection); }
internal static string CreateObjectsScript(StoreItemCollection storeItemCollection) { throw new NotImplementedException(); }
protected override void DbCreateDatabase(DbConnection connection, int? commandTimeout, StoreItemCollection storeItemCollection) { if (connection == null) throw new ArgumentNullException("connection"); MySqlConnection conn = connection as MySqlConnection; if (conn == null) throw new ArgumentException(Resources.ConnectionMustBeOfTypeMySqlConnection, "connection"); // Ensure a valid provider manifest token. string providerManifestToken = this.GetDbProviderManifestToken(connection); string query = DbCreateDatabaseScript(providerManifestToken, storeItemCollection); using (MySqlConnection c = new MySqlConnection()) { MySqlConnectionStringBuilder sb = new MySqlConnectionStringBuilder(conn.ConnectionString); string dbName = sb.Database; sb.Database = null; c.ConnectionString = sb.ConnectionString; c.Open(); string fullQuery = String.Format("CREATE DATABASE `{0}`; USE `{0}`; {1}", dbName, query); MySqlScript s = new MySqlScript(c, fullQuery); s.Execute(); } }
/// <summary> /// delete the database. /// </summary> /// <param name="connection">The connection.</param> /// <param name="commandTimeout">The command timeout.</param> /// <param name="storeItemCollection">The store item collection.</param> protected override void DbDeleteDatabase(DbConnection connection, int?commandTimeout, StoreItemCollection storeItemCollection) { _tail.DeleteDatabase(GetRealConnection(connection), commandTimeout, storeItemCollection); }
protected override bool DbDatabaseExists(DbConnection connection, int? commandTimeout, StoreItemCollection storeItemCollection) { if (connection == null) throw new ArgumentNullException("connection"); MySqlConnection conn = connection as MySqlConnection; if (conn == null) throw new ArgumentException(Resources.ConnectionMustBeOfTypeMySqlConnection, "connection"); MySqlConnectionStringBuilder builder = new MySqlConnectionStringBuilder(); builder.ConnectionString = conn.ConnectionString; string dbName = builder.Database; builder.Database = null; using (MySqlConnection c = new MySqlConnection(builder.ConnectionString)) { c.Open(); DataTable table = c.GetSchema("Databases", new string[] { dbName }); if (table != null && table.Rows.Count == 1) return true; return false; } }
/// <summary> /// create the database script. /// </summary> /// <param name="providerManifestToken">The provider manifest token.</param> /// <param name="storeItemCollection">The store item collection.</param> /// <returns>a string containing the database script.</returns> protected override string DbCreateDatabaseScript(string providerManifestToken, StoreItemCollection storeItemCollection) { return(_tail.CreateDatabaseScript(providerManifestToken, storeItemCollection)); }
protected override bool DbDatabaseExists(DbConnection connection, int? commandTimeout, StoreItemCollection storeItemCollection) { bool exists = false; UsingPostgresDBConnection((NpgsqlConnection)connection, conn => { using (NpgsqlCommand command = new NpgsqlCommand("select count(*) from pg_catalog.pg_database where datname = '" + connection.Database + "';", conn)) { exists = Convert.ToInt32(command.ExecuteScalar()) > 0; } }); return exists; }
/// <summary> /// test if the database exists. /// </summary> /// <param name="connection">The connection.</param> /// <param name="commandTimeout">The command timeout.</param> /// <param name="storeItemCollection">The store item collection.</param> /// <returns>true if the database exists.</returns> protected override bool DbDatabaseExists(DbConnection connection, int?commandTimeout, StoreItemCollection storeItemCollection) { return(_tail.DatabaseExists(GetRealConnection(connection), commandTimeout, storeItemCollection)); }
protected override void DbDeleteDatabase(DbConnection connection, int? commandTimeout, StoreItemCollection storeItemCollection) { UsingPostgresDBConnection((NpgsqlConnection)connection, conn => { //Close all connections in pool or exception "database used by another user appears" NpgsqlConnection.ClearAllPools(); using (NpgsqlCommand command = new NpgsqlCommand("DROP DATABASE \"" + connection.Database + "\";", conn)) { command.ExecuteNonQuery(); } }); }
/// <summary> /// Creates the MetadataWorkspace for the given context type and base context type. /// </summary> /// <param name="contextType">The type of the context.</param> /// <param name="baseContextType">The base context type (DbContext or ObjectContext).</param> /// <returns>The generated <see cref="MetadataWorkspace"/></returns> public static MetadataWorkspace CreateMetadataWorkspaceFromResources(Type contextType, Type baseContextType) { // get the set of embedded mapping resources for the target assembly and create // a metadata workspace info for each group IEnumerable<string> metadataResourcePaths = FindMetadataResources(contextType.Assembly); IEnumerable<MetadataWorkspaceInfo> workspaceInfos = GetMetadataWorkspaceInfos(metadataResourcePaths); // Search for the correct EntityContainer by name and if found, create // a comlete MetadataWorkspace and return it foreach (var workspaceInfo in workspaceInfos) { EdmItemCollection edmItemCollection = new EdmItemCollection(workspaceInfo.Csdl); Type currentType = contextType; while (currentType != baseContextType && currentType != typeof(object)) { EntityContainer container; if (edmItemCollection.TryGetEntityContainer(currentType.Name, out container)) { StoreItemCollection store = new StoreItemCollection(workspaceInfo.Ssdl); #if DBCONTEXT // This actually means EF6+ MetadataWorkspace workspace = new MetadataWorkspace( () => edmItemCollection, () => store, () => new StorageMappingItemCollection(edmItemCollection, store, workspaceInfo.Msl), () => new ObjectItemCollection()); #else // EF4 StorageMappingItemCollection mapping = new StorageMappingItemCollection(edmItemCollection, store, workspaceInfo.Msl); MetadataWorkspace workspace = new MetadataWorkspace(); workspace.RegisterItemCollection(edmItemCollection); workspace.RegisterItemCollection(store); workspace.RegisterItemCollection(mapping); workspace.RegisterItemCollection(new ObjectItemCollection()); #endif return workspace; } currentType = currentType.BaseType; } } return null; }