public void ToLegacyStoreTypeUsage_returns_legacy_type_for_RowType() { const string ssdl = "<Schema Namespace='AdventureWorksModel.Store' Provider='System.Data.SqlClient' ProviderManifestToken='2008' xmlns='http://schemas.microsoft.com/ado/2009/11/edm/ssdl'>" + " <Function Name='GetNames'>" + " <ReturnType>" + " <CollectionType>" + " <RowType>" + " <Property Name='FirstName' Type='nvarchar' Nullable='false' />" + " <Property Name='LastName' Type='nvarchar' Nullable='false' />" + " </RowType>" + " </CollectionType>" + " </ReturnType>" + " </Function>" + "</Schema>"; var storeItemCollection = Utils.CreateStoreItemCollection(ssdl); var legacyStoreItemCollection = new LegacyMetadata.StoreItemCollection(new[] { XmlReader.Create(new StringReader(ssdl)) }); var rowTypeUsage = ((CollectionType)storeItemCollection .GetItems <EdmFunction>().Single(f => f.Name == "GetNames") .ReturnParameters[0].TypeUsage.EdmType).TypeUsage; var legacyRowTypeUsage = rowTypeUsage.ToLegacyStoreTypeUsage( legacyStoreItemCollection.GetItems <LegacyMetadata.EdmType>().ToArray()); TypeUsageVerificationHelper.VerifyTypeUsagesEquivalent(legacyRowTypeUsage, rowTypeUsage); }
private static MetadataWorkspace CreateWrappedMetadataWorkspace(string metadata, IEnumerable<string> wrapperProviderNames) { MetadataWorkspace workspace = new MetadataWorkspace(); // 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. workspace = new MetadataWorkspace(); workspace.RegisterItemCollection(eic); workspace.RegisterItemCollection(sic); workspace.RegisterItemCollection(smic); return workspace; }
/// <summary> /// Helper function for generating the scripts for tables & constraints. /// </summary> /// <param name="itemCollection"></param> /// <returns></returns> internal static List<string> CreateObjectsScript(StoreItemCollection itemCollection, bool returnWarnings) { var builder = new SqlDdlBuilder(); // Iterate over the container. foreach (var container in itemCollection.GetItems<EntityContainer>()) { // Generate create table statements. foreach (var set in container.BaseEntitySets) { // If it is a type of entitySet, generate Create Table statements. var entitySet = set as EntitySet; if (entitySet != null) { builder.AppendCreateTable(entitySet); } } // Generate Foreign Key constraints. foreach (var set in container.BaseEntitySets) { // If it is association set, generate Foreign Key constraints. var associationSet = set as AssociationSet; if (associationSet != null) { builder.AppendCreateForeignKeys(associationSet); } } } // Return the final command text. return builder.GetCommandText(returnWarnings); }
public StorageMappingItemCollection(EdmItemCollection edmCollection, StoreItemCollection storeCollection, params string[] filePaths) : base(DataSpace.CSSpace) { EntityUtil.CheckArgumentNull(edmCollection, "edmCollection"); EntityUtil.CheckArgumentNull(storeCollection, "storeCollection"); EntityUtil.CheckArgumentNull(filePaths, "filePaths"); this.m_edmCollection = edmCollection; this.m_storeItemCollection = storeCollection; // Wrap the file paths in instances of the MetadataArtifactLoader class, which provides // an abstraction and a uniform interface over a diverse set of metadata artifacts. // MetadataArtifactLoader composite = null; List<XmlReader> readers = null; try { composite = MetadataArtifactLoader.CreateCompositeFromFilePaths(filePaths, XmlConstants.CSSpaceSchemaExtension); readers = composite.CreateReaders(DataSpace.CSSpace); this.Init(edmCollection, storeCollection, readers, composite.GetPaths(DataSpace.CSSpace), true /*throwOnError*/); } finally { if (readers != null) { Helper.DisposeXmlReaders(readers); } } }
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); }
public void ToStoreLegacyType_returns_legacy_type_for_EntityType() { 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='Entities' EntityType='AdventureWorksModel.Store.Entities' 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>" + "</Schema>"; var storeItemCollection = Utils.CreateStoreItemCollection(ssdl); var legacyStoreItemCollection = new LegacyMetadata.StoreItemCollection(new[] { XmlReader.Create(new StringReader(ssdl)) }); var entityTypeUsage = TypeUsage.CreateDefaultTypeUsage(storeItemCollection.GetItem<EntityType>("AdventureWorksModel.Store.Entities")); var legacyEntityTypeUsage = entityTypeUsage.ToLegacyStoreTypeUsage(legacyStoreItemCollection.GetItems<LegacyMetadata.EdmType>().ToArray()); TypeUsageVerificationHelper.VerifyTypeUsagesEquivalent(legacyEntityTypeUsage, entityTypeUsage); }
public void ToStoreLegacyType_returns_legacy_type_for_EntityType() { 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='Entities' EntityType='AdventureWorksModel.Store.Entities' 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>" + "</Schema>"; var storeItemCollection = Utils.CreateStoreItemCollection(ssdl); var legacyStoreItemCollection = new LegacyMetadata.StoreItemCollection(new[] { XmlReader.Create(new StringReader(ssdl)) }); var entityTypeUsage = TypeUsage.CreateDefaultTypeUsage(storeItemCollection.GetItem <EntityType>("AdventureWorksModel.Store.Entities")); var legacyEntityTypeUsage = entityTypeUsage.ToLegacyStoreTypeUsage(legacyStoreItemCollection.GetItems <LegacyMetadata.EdmType>().ToArray()); TypeUsageVerificationHelper.VerifyTypeUsagesEquivalent(legacyEntityTypeUsage, entityTypeUsage); }
public static string GenerateDatabaseScript(string providerManifestToken, StoreItemCollection storeItemCollection) { if (storeItemCollection == null) return string.Empty; var result = new StringBuilder(); result.Append(string.Join(Environment.NewLine, GenerateTables(storeItemCollection))); result.AppendLine(); result.Append(string.Join(Environment.NewLine, GenerateForeignKeys(storeItemCollection))); result.AppendLine(); return result.ToString(); }
/// <summary> /// API for deleting the database. /// In SQLCE case, this will translate to File.Delete() call. /// Note: Timeout and storeItemCollection parameters are ignored. /// </summary> /// <param name="connection"></param> /// <param name="timeOut"></param> /// <param name="storeItemCollection"></param> protected override void DbDeleteDatabase(DbConnection connection, int? timeOut, StoreItemCollection storeItemCollection) { // Validate that connection is a SqlCeConnection. ValidateConnection(connection); // We don't support create/delete database operations inside a transaction as they can't be rolled back. if (InTransactionScope()) { throw ADP1.DeleteDatabaseNotAllowedWithinTransaction(); } // Throw an exception if connection is open. // We should not close the connection because user could have result sets/data readers associated with this connection. // Thus, it is users responsiblity to close the connection before calling delete database. // if (connection.State == ConnectionState.Open) { throw ADP1.DeleteDatabaseWithOpenConnection(); } if (_isLocalProvider) { CommonUtils.DeleteDatabase(connection.DataSource); } else { try { 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); // Invoke the required method on SqlCeEngine. var mi = rdpType.GetMethod("DeleteDatabaseWithError", 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. mi.Invoke(engine, new object[] { connection.DataSource, timeOut }); } catch (Exception e) { throw e.GetBaseException(); } } }
static IEnumerable<string> GenerateForeignKeys(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}.{1} ADD FOREIGN KEY ({2}) REFERENCES {3}.{4}({5}){6};", SqlGenerator.QuoteIdentifier(MetadataHelpers.GetSchemaName(end2.EntitySet)), SqlGenerator.QuoteIdentifier(MetadataHelpers.GetTableName(end2.EntitySet)), string.Join(", ", constraint.ToProperties.Select(fk => SqlGenerator.QuoteIdentifier(fk.Name))), SqlGenerator.QuoteIdentifier(MetadataHelpers.GetSchemaName(end.EntitySet)), SqlGenerator.QuoteIdentifier(MetadataHelpers.GetTableName(end.EntitySet)), string.Join(", ", constraint.FromProperties.Select(pk => SqlGenerator.QuoteIdentifier(pk.Name))), end.CorrespondingAssociationEndMember.DeleteBehavior == OperationAction.Cascade ? " ON DELETE CASCADE" : string.Empty); yield return result.ToString(); } }
/// <summary> /// Main driver function. /// </summary> /// <param name="args"></param> public static void Generate(string outputFileName) { //The following functions are omitted because they have counterparts in the BCL string[] omittedFunctions = new[] { "Sum", "Min", "Max", "Average", "Avg", "Count", "BigCount", "Trim", "RTrim", "LTrim", "Concat", "Length", "Substring", "Replace", "IndexOf", "ToUpper", "ToLower", "Contains", "StartsWith", "EndsWith", "Year", "Month", "Day", "DayOfYear", "Hour", "Minute", "Second", "Millisecond", "CurrentDateTime", "CurrentDateTimeOffset", "CurrentUtcDateTime", "BitwiseAnd", "BitwiseOr", "BitwiseXor", "BitwiseNot", "Round", "Abs", "Power", "NewGuid", "Floor", "Ceiling", }; //The following functions are omitted from SqlFunctions because they already exist in EntityFunctions string[] omittedSqlFunctions = new[] { "STDEV", "STDEVP", "VAR", "VARP", "COUNT_BIG", "Left", "Right", "Reverse", "GetTotalOffsetMinutes", "TruncateTime", "CreateDateTime", "CreateDateTimeOffset", "CreateTime", "Add", "Diff", "Truncate", "SYSDATETIME", "SYSUTCDATETIME", "SYSDATETIMEOFFSET", "LEN", "LOWER", "UPPER", "NEWID", }; //Generate Sql Server function stubs String ssdl = @"<Schema Namespace='LinqFunctionStubsGenerator' Alias='Self' Provider='SampleEntityFrameworkProvider' ProviderManifestToken='2008' xmlns='http://schemas.microsoft.com/ado/2006/04/edm/ssdl'></Schema>"; XmlReader[] xmlReaders = new XmlReader[1]; xmlReaders[0] = XmlReader.Create(new StringReader(ssdl)); StoreItemCollection storeItemCollection = new StoreItemCollection(xmlReaders); IEnumerable<EdmFunction> sqlFunctions = storeItemCollection.GetItems<EdmFunction>() .Where(f => f.NamespaceName == "SqlServer") .Where(f => !(omittedFunctions.Concat(omittedSqlFunctions)).Contains(f.Name, StringComparer.OrdinalIgnoreCase)); FunctionStubFileWriter sqlStubsFileWriter = new FunctionStubFileWriter(sqlFunctions, GetFunctionNamingDictionary(), GetParameterNamingDictionary()); sqlStubsFileWriter.GenerateToFile(outputFileName, "SampleEntityFrameworkProvider", "SampleSqlFunctions", "SqlServer", true); }
public EntityModelSchemaGenerator(StoreItemCollection storeItemCollection, string namespaceName, string modelEntityContainerName) { EDesignUtil.CheckArgumentNull(storeItemCollection, "storeItemCollection"); EDesignUtil.CheckArgumentNull(namespaceName, "namespaceName"); EDesignUtil.CheckArgumentNull(modelEntityContainerName, "modelEntityContainerName"); var storeContainers = storeItemCollection.GetItems<EntityContainer>().ToArray(); if (storeContainers.Length != 1) { throw EDesignUtil.SingleStoreEntityContainerExpected("storeItemCollection"); } Initialize( storeContainers[0], storeItemCollection.GetItems<EdmFunction>().Where(f => f.IsFromProviderManifest == false && f.IsComposableAttribute == true && f.AggregateAttribute == false), namespaceName, modelEntityContainerName); }
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 = "mysql"; 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; } }
static IEnumerable<string> GenerateTables(StoreItemCollection storeItems) { foreach (var entitySet in storeItems.GetItems<EntityContainer>()[0].BaseEntitySets.OfType<EntitySet>()) { var result = new StringBuilder(); var tableName = MetadataHelpers.GetTableName(entitySet); var schemaName = MetadataHelpers.GetSchemaName(entitySet); result.AppendFormat("CREATE TABLE {0}.{1} (", SqlGenerator.QuoteIdentifier(schemaName), SqlGenerator.QuoteIdentifier(tableName)); result.AppendLine(); result.Append("\t"); result.Append(string.Join("," + Environment.NewLine + "\t", MetadataHelpers.GetProperties(entitySet.ElementType).Select(p => GenerateColumn(p)))); result.Append(");"); result.AppendLine(); result.AppendFormat("ALTER TABLE {0}.{1} ADD PRIMARY KEY ({2});", SqlGenerator.QuoteIdentifier(schemaName), SqlGenerator.QuoteIdentifier(tableName), string.Join(", ", entitySet.ElementType.KeyMembers.Select(pk => SqlGenerator.QuoteIdentifier(pk.Name)))); result.AppendLine(); yield return result.ToString(); } }
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 = "mysql"; 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 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 = "mysql"; 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(); } }
private static StorageMappingItemCollection ToStorageMappingItemCollection( this DbDatabaseMapping databaseMapping, EdmItemCollection itemCollection, StoreItemCollection storeItemCollection) { //Contract.Requires(databaseMapping != null); //Contract.Requires(itemCollection != null); //Contract.Requires(storeItemCollection != null); var stringBuilder = new StringBuilder(); using (var xmlWriter = XmlWriter.Create( stringBuilder, new XmlWriterSettings { Indent = true })) { new MslSerializer().Serialize(databaseMapping, xmlWriter); } using (var xmlReader = XmlReader.Create(new StringReader(stringBuilder.ToString()))) { return new StorageMappingItemCollection(itemCollection, storeItemCollection, new[] { xmlReader }); } }
/// <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) { // 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 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(); }
/// <summary> /// Generates a DDL script which creates schema objects (tables, primary keys, foreign keys) /// based on the contents of the storeItemCollection and targeted for the version of the backend corresponding to /// the providerManifestToken. /// Individual statements should be separated using database-specific DDL command separator. /// It is expected that the generated script would be executed in the context of existing database with /// sufficient permissions, and it should not include commands to create the database, but it may include /// commands to create schemas and other auxiliary objects such as sequences, etc. /// </summary> /// <param name="providerManifestToken">The provider manifest token identifying the target version</param> /// <param name="storeItemCollection">The collection of all store items based on which the script should be created</param> /// <returns> /// A DDL script which creates schema objects based on contents of storeItemCollection /// and targeted for the version of the backend corresponding to the providerManifestToken. /// </returns> public string CreateDatabaseScript(string providerManifestToken, StoreItemCollection storeItemCollection) { return DbCreateDatabaseScript(providerManifestToken, storeItemCollection); }
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"); SampleConnection sampleConnection = connection as SampleConnection; if (sampleConnection == null) throw new ArgumentException("connection must be a valid SampleConnection"); string databaseName = GetDatabaseName(sampleConnection); bool exists = false; UsingMasterConnection(sampleConnection, conn => { StoreVersion storeVersion = StoreVersionUtils.GetStoreVersion(conn); string databaseExistsScript = DdlBuilder.CreateDatabaseExistsScript(databaseName); int result = (int)CreateCommand(conn, databaseExistsScript, commandTimeout).ExecuteScalar(); exists = (result == 1); }); return exists; }
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"); SampleConnection sampleConnection = connection as SampleConnection; if (sampleConnection == null) throw new ArgumentException("connection must be a valid SampleConnection"); string databaseName = GetDatabaseName(sampleConnection); string dropDatabaseScript = DdlBuilder.DropDatabaseScript(databaseName); // clear the connection pool in case someone is holding on to the database sampleConnection.ClearPool(); UsingMasterConnection(sampleConnection, (conn) => { CreateCommand(conn, dropDatabaseScript, commandTimeout).ExecuteNonQuery(); }); }
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 DdlBuilder.CreateObjectsScript(storeItemCollection); }
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"); SampleConnection sampleConnection = connection as SampleConnection; if (sampleConnection == null) { throw new ArgumentException("The connection is not of type 'SampleConnection'."); } string databaseName = GetDatabaseName(sampleConnection); if (string.IsNullOrEmpty(databaseName)) { throw new InvalidOperationException("Initial Catalog is missing from the connection string"); } string dataFileName, logFileName; GetDatabaseFileNames(sampleConnection, out dataFileName, out logFileName); string createDatabaseScript = DdlBuilder.CreateDatabaseScript(databaseName, dataFileName, logFileName); string createObjectsScript = DdlBuilder.CreateObjectsScript(storeItemCollection); UsingMasterConnection(sampleConnection, conn => { // create database CreateCommand(conn, createDatabaseScript, commandTimeout).ExecuteNonQuery(); }); // Clear connection pool for the database connection since after the 'create database' call, a previously // invalid connection may now be valid. sampleConnection.ClearPool(); UsingConnection(sampleConnection, conn => { // create database objects CreateCommand(conn, createObjectsScript, commandTimeout).ExecuteNonQuery(); }); }
/// <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 collection of all store items contained in the database that should be deleted<</param> public void DeleteDatabase(DbConnection connection, int? commandTimeout, StoreItemCollection storeItemCollection) { DbDeleteDatabase(connection, commandTimeout, storeItemCollection); }
protected virtual void DbDeleteDatabase(DbConnection connection, int? commandTimeout, StoreItemCollection storeItemCollection) { throw EntityUtil.ProviderIncompatible(Strings.ProviderDoesNotSupportDeleteDatabase); }
/// <summary> /// Returns a value indicating whether given database exists on the server /// and/or whether schema objects contained in teh storeItemCollection have been created. /// If the provider can deduct the database only based on the connection, they do not need /// to additionally verify all elements of the storeItemCollection. /// </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 contained in the database /// whose existence is determined by this method<</param> /// <returns>Whether the database indicated by the connection and the storeItemCollection exist</returns> public bool DatabaseExists(DbConnection connection, int? commandTimeout, StoreItemCollection storeItemCollection) { return DbDatabaseExists(connection, commandTimeout, storeItemCollection); }
protected virtual bool DbDatabaseExists(DbConnection connection, int? commandTimeout, StoreItemCollection storeItemCollection) { throw EntityUtil.ProviderIncompatible(Strings.ProviderDoesNotSupportDatabaseExists); }
protected virtual string DbCreateDatabaseScript(string providerManifestToken, StoreItemCollection storeItemCollection) { throw EntityUtil.ProviderIncompatible(Strings.ProviderDoesNotSupportCreateDatabaseScript); }
public LegacyDbExpressionConverter(LegacyMetadata.StoreItemCollection storeItemCollection) { Debug.Assert(storeItemCollection != null, "storeItemCollection != null"); _storeItemCollection = storeItemCollection; }
protected override void DbDeleteDatabase(DbConnection connection, int? commandTimeout, StoreItemCollection storeItemCollection) { InnerProviderServices.DeleteDatabase(((GlimpseProfileDbConnection)connection).InnerConnection, commandTimeout, storeItemCollection); }
protected override bool DbDatabaseExists(DbConnection connection, int? commandTimeout, StoreItemCollection storeItemCollection) { return InnerProviderServices.DatabaseExists(((GlimpseProfileDbConnection)connection).InnerConnection, commandTimeout, storeItemCollection); }
protected override string DbCreateDatabaseScript(string providerManifestToken, StoreItemCollection storeItemCollection) { return InnerProviderServices.CreateDatabaseScript(providerManifestToken, storeItemCollection); }