How to omit database name or schema in query text or deny this?
Last modified:
Active Query Builder can skip default namespace prefixes for database objects. This helps to make SQL query text clearer. Active Query Builder detects default namespaces during the metadata loading process and omits them in the query text by default. This behavior can be altered by changing the ObjectPrefixSkipping property in the QueryBuilder.SQLGenerationOptions and the QueryBuilder.SQLFormattingOptions groups. The QueryBuilder.SQLGenerationOptions group affects the output of QueryBuilder.SQL property (unformatted SQL) while the QueryBuilder.SQLFormattingOptions group affects the output of QueryBuilder.FormattedSQL property.
MetadataItem objects for namespaces which can be omitted are marked in the Metadata Container as default using the MetadataItem.Default property. Note that a query with omitted object prefixes could be successfully executed only against a connection with appropriate database user credentials.
If you load metadata programmatically (add items to the metadata container with code), setting the Default property is trivial. But if you load metadata from live database connection and want to change this property for some of the loaded metadata items, you must handle the MetadataContainer.ItemMetadataLoaded event as follows:
// add handler queryBuilder1.MetadataContainer.ItemMetadataLoaded += MetadataContainerOnItemMetadataLoaded; // set database "HIVE" and schema "Default" as default private void MetadataContainerOnItemMetadataLoaded(object sender, MetadataItem item, MetadataType loadTypes) { foreach (var childItem in item.Items) { if (childItem.Type == MetadataType.Database && childItem.Name == "HIVE" || childItem.Type == MetadataType.Schema && childItem.Name == "Default") { childItem.Default = true; } } }
To get the default database and schema names from the underlying database server use appropriate static methods of the MetadataNamesFetcher object: GetDefaultDatabaseName, GetDefaultSchemaNames.
To find the default namespace objects in the Metadata Container use the following code:
// load the first level of the Metadata Container which should have the default database // in case of connecting to the database server that supports multiple databases queryBuilder1.MetadataContainer.Items.Load(MetadataType.Database, false); // get list of loaded databases List<MetadataNamespace> databases = queryBuilder1.MetadataContainer.Items.GetItems<MetadataNamespace>(MetadataType.Database); // find the default database in the list foreach (MetadataNamespace database in databases) { if (database.Default) { database.Items.Load(MetadataType.Schema, false); List<MetadataNamespace> schemas = database.Items.GetItems<MetadataNamespace>(MetadataType.Schema); foreach (MetadataNamespace schema in schemas) { if (schema.Default) { MetadataObject table = schema.AddTable("Demo Table"); // ... } } } }