/// <summary> /// Creates a SQL Statement for insert-all operation. /// </summary> /// <param name="queryBuilder">The query builder to be used.</param> /// <param name="tableName">The name of the target table.</param> /// <param name="fields">The list of fields to be inserted.</param> /// <param name="batchSize">The batch size of the operation.</param> /// <param name="primaryField">The primary field from the database.</param> /// <param name="identityField">The identity field from the database.</param> /// <param name="hints">The table hints to be used.</param> /// <returns>A sql statement for insert operation.</returns> public override string CreateInsertAll(QueryBuilder queryBuilder, string tableName, IEnumerable <Field> fields = null, int batchSize = Constant.DefaultBatchOperationSize, DbField primaryField = null, DbField identityField = null, string hints = null) { // Initialize the builder var builder = queryBuilder ?? new QueryBuilder(); // Call the base var commandText = base.CreateInsertAll(builder, tableName, fields, batchSize, primaryField, identityField, hints); // Variables needed var databaseType = (string)null; // Check for the identity if (identityField != null) { var dbType = new ClientTypeToDbTypeResolver().Resolve(identityField.Type); if (dbType != null) { databaseType = new DbTypeToSqlServerStringNameResolver().Resolve(dbType.Value); } } if (identityField != null) { // Variables needed var commandTexts = new List <string>(); var splitted = commandText.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); // Iterate the indexes for (var index = 0; index < splitted.Length; index++) { var line = splitted[index].Trim(); var returnValue = string.IsNullOrEmpty(databaseType) ? "SELECT SCOPE_IDENTITY()" : $"SELECT CONVERT({databaseType}, SCOPE_IDENTITY())"; commandTexts.Add(string.Concat(line, " ; ", returnValue, " ;")); } // Set the command text commandText = commandTexts.Join(" "); } // Return the query return(commandText); }
/// <summary> /// Creates a SQL Statement for insert operation. /// </summary> /// <param name="queryBuilder">The query builder to be used.</param> /// <param name="tableName">The name of the target table.</param> /// <param name="fields">The list of fields to be inserted.</param> /// <param name="primaryField">The primary field from the database.</param> /// <param name="identityField">The identity field from the database.</param> /// <param name="hints">The table hints to be used.</param> /// <returns>A sql statement for insert operation.</returns> public override string CreateInsert(QueryBuilder queryBuilder, string tableName, IEnumerable <Field> fields = null, DbField primaryField = null, DbField identityField = null, string hints = null) { // Initialize the builder var builder = queryBuilder ?? new QueryBuilder(); // Call the base base.CreateInsert(builder, tableName, fields, primaryField, identityField, hints); // Variables needed var databaseType = "BIGINT"; // Check for the identity if (identityField != null) { var dbType = new ClientTypeToDbTypeResolver().Resolve(identityField.Type); if (dbType != null) { databaseType = new DbTypeToSqlServerStringNameResolver().Resolve(dbType.Value); } } // Set the return value var result = identityField != null? string.Concat("CONVERT(", databaseType, ", SCOPE_IDENTITY())") : primaryField != null?primaryField.Name.AsParameter(DbSetting) : "NULL"; builder .Select() .WriteText(result) .As("[Result]") .End(); // Return the query return(builder.GetString()); }
/// <summary> /// Creates a SQL Statement for merge-all operation. /// </summary> /// <param name="queryBuilder">The query builder to be used.</param> /// <param name="tableName">The name of the target table.</param> /// <param name="fields">The list of fields to be merged.</param> /// <param name="qualifiers">The list of the qualifier <see cref="Field"/> objects.</param> /// <param name="batchSize">The batch size of the operation.</param> /// <param name="primaryField">The primary field from the database.</param> /// <param name="identityField">The identity field from the database.</param> /// <param name="hints">The table hints to be used.</param> /// <returns>A sql statement for merge operation.</returns> public override string CreateMergeAll(QueryBuilder queryBuilder, string tableName, IEnumerable <Field> fields, IEnumerable <Field> qualifiers = null, int batchSize = Constant.DefaultBatchOperationSize, DbField primaryField = null, DbField identityField = null, string hints = null) { // Ensure with guards GuardTableName(tableName); GuardHints(hints); GuardPrimary(primaryField); GuardIdentity(identityField); // Verify the fields if (fields?.Any() != true) { throw new MissingFieldsException($"The list of fields cannot be null or empty."); } // Check the qualifiers if (qualifiers?.Any() == true) { // Check if the qualifiers are present in the given fields var unmatchesQualifiers = qualifiers.Where(field => fields.FirstOrDefault(f => string.Equals(field.Name, f.Name, StringComparison.OrdinalIgnoreCase)) == null); // Throw an error we found any unmatches if (unmatchesQualifiers?.Any() == true) { throw new InvalidQualifiersException($"The qualifiers '{unmatchesQualifiers.Select(field => field.Name).Join(", ")}' are not " + $"present at the given fields '{fields.Select(field => field.Name).Join(", ")}'."); } } else { if (primaryField != null) { // Make sure that primary is present in the list of fields before qualifying to become a qualifier var isPresent = fields?.FirstOrDefault(f => string.Equals(f.Name, primaryField.Name, StringComparison.OrdinalIgnoreCase)) != null; // Throw if not present if (isPresent == false) { throw new InvalidQualifiersException($"There are no qualifier field objects found for '{tableName}'. Ensure that the " + $"primary field is present at the given fields '{fields.Select(field => field.Name).Join(", ")}'."); } // The primary is present, use it as a default if there are no qualifiers given qualifiers = primaryField.AsField().AsEnumerable(); } else { // Throw exception, qualifiers are not defined throw new MissingQualifierFieldsException($"There are no qualifier fields found for '{tableName}'."); } } // Get the insertable and updateable fields var insertableFields = fields .Where(field => !string.Equals(field.Name, identityField?.Name, StringComparison.OrdinalIgnoreCase)); var updateableFields = fields .Where(field => !string.Equals(field.Name, primaryField?.Name, StringComparison.OrdinalIgnoreCase) && !string.Equals(field.Name, identityField?.Name, StringComparison.OrdinalIgnoreCase)); // Variables needed var databaseType = (string)null; // Check for the identity if (identityField != null) { var dbType = new ClientTypeToDbTypeResolver().Resolve(identityField.Type); if (dbType != null) { databaseType = new DbTypeToSqlServerStringNameResolver().Resolve(dbType.Value); } } else if (primaryField != null) { var dbType = new ClientTypeToDbTypeResolver().Resolve(primaryField.Type); if (dbType != null) { databaseType = new DbTypeToSqlServerStringNameResolver().Resolve(dbType.Value); } } // Initialize the builder var builder = queryBuilder ?? new QueryBuilder(); // Build the query builder.Clear(); // Iterate the indexes for (var index = 0; index < batchSize; index++) { // MERGE T USING S builder.Merge() .TableNameFrom(tableName, DbSetting) .HintsFrom(hints) .As("T") .Using() .OpenParen() .Select() .ParametersAsFieldsFrom(fields, index, DbSetting) .CloseParen() .As("S") // QUALIFIERS .On() .OpenParen() .WriteText(qualifiers? .Select( field => field.AsJoinQualifier("S", "T", DbSetting)) .Join(" AND ")) .CloseParen() // WHEN NOT MATCHED THEN INSERT VALUES .When() .Not() .Matched() .Then() .Insert() .OpenParen() .FieldsFrom(insertableFields, DbSetting) .CloseParen() .Values() .OpenParen() .AsAliasFieldsFrom(insertableFields, "S", DbSetting) .CloseParen() // WHEN MATCHED THEN UPDATE SET .When() .Matched() .Then() .Update() .Set() .FieldsAndAliasFieldsFrom(updateableFields, "T", "S", DbSetting); // Set the output var outputField = identityField ?? primaryField; if (outputField != null) { builder .WriteText(string.Concat("OUTPUT INSERTED.", outputField.Name.AsField(DbSetting))) .As("[Result]"); } // End the builder builder.End(); } // Return the query return(builder.GetString()); }
/// <summary> /// Creates a SQL Statement for insert-all operation. /// </summary> /// <param name="queryBuilder">The query builder to be used.</param> /// <param name="tableName">The name of the target table.</param> /// <param name="fields">The list of fields to be inserted.</param> /// <param name="batchSize">The batch size of the operation.</param> /// <param name="primaryField">The primary field from the database.</param> /// <param name="identityField">The identity field from the database.</param> /// <returns>A sql statement for insert operation.</returns> public string CreateInsertAll(QueryBuilder queryBuilder, string tableName, IEnumerable <Field> fields = null, int batchSize = Constant.DefaultBatchOperationSize, DbField primaryField = null, DbField identityField = null) { // Ensure with guards GuardTableName(tableName); GuardPrimary(primaryField); GuardIdentity(identityField); // Verify the fields if (fields?.Any() != true) { throw new NullReferenceException($"The list of fields cannot be null or empty."); } // Ensure the primary is on the list if it is not an identity if (primaryField != null) { if (primaryField != identityField) { var isPresent = fields.FirstOrDefault(f => string.Equals(f.Name, primaryField.Name, StringComparison.OrdinalIgnoreCase)) != null; if (isPresent == false) { throw new InvalidOperationException("The non-identity primary field must be present during insert operation."); } } } // Variables needed var databaseType = (string)null; var insertableFields = fields .Where(f => !string.Equals(f.Name, identityField?.Name, StringComparison.OrdinalIgnoreCase)); // Check for the identity if (identityField != null) { var dbType = new ClientTypeToDbTypeResolver().Resolve(identityField.Type); if (dbType != null) { databaseType = new DbTypeToSqlServerStringNameResolver().Resolve(dbType.Value); } } // Build the query (queryBuilder ?? new QueryBuilder()) .Clear(); // Iterate the indexes for (var index = 0; index < batchSize; index++) { queryBuilder.Insert() .Into() .TableNameFrom(tableName, DbSetting) .OpenParen() .FieldsFrom(insertableFields) .CloseParen() .Values() .OpenParen() .ParametersFrom(insertableFields, index, DbSetting) .CloseParen() .End(); // Set the return field if (identityField != null) { var returnValue = string.Concat(identityField.UnquotedName.AsParameter(index, DbSetting), " = ", string.IsNullOrEmpty(databaseType) ? "SCOPE_IDENTITY()" : "CONVERT(", databaseType, ", SCOPE_IDENTITY())"); queryBuilder .Set() .WriteText(returnValue) .End(); } } // Return the query return(queryBuilder.GetString()); }
/// <summary> /// Creates a SQL Statement for insert operation. /// </summary> /// <param name="queryBuilder">The query builder to be used.</param> /// <param name="tableName">The name of the target table.</param> /// <param name="fields">The list of fields to be inserted.</param> /// <param name="primaryField">The primary field from the database.</param> /// <param name="identityField">The identity field from the database.</param> /// <returns>A sql statement for insert operation.</returns> public string CreateInsert(QueryBuilder queryBuilder, string tableName, IEnumerable <Field> fields = null, DbField primaryField = null, DbField identityField = null) { // Ensure with guards GuardTableName(tableName); GuardPrimary(primaryField); GuardIdentity(identityField); // Verify the fields if (fields?.Any() != true) { throw new NullReferenceException($"The list of insertable fields must not be null for '{tableName}'."); } // Ensure the primary is on the list if it is not an identity if (primaryField != null) { if (primaryField != identityField) { var isPresent = fields.FirstOrDefault(f => string.Equals(f.Name, primaryField.Name, StringComparison.OrdinalIgnoreCase)) != null; if (isPresent == false) { throw new InvalidOperationException("The non-identity primary field must be present during insert operation."); } } } // Variables needed var databaseType = "BIGINT"; var insertableFields = fields .Where(f => !string.Equals(f.Name, identityField?.Name, StringComparison.OrdinalIgnoreCase)); // Check for the identity if (identityField != null) { var dbType = new ClientTypeToDbTypeResolver().Resolve(identityField.Type); if (dbType != null) { databaseType = new DbTypeToSqlServerStringNameResolver().Resolve(dbType.Value); } } // Build the query (queryBuilder ?? new QueryBuilder()) .Clear() .Insert() .Into() .TableNameFrom(tableName, DbSetting) .OpenParen() .FieldsFrom(insertableFields) .CloseParen() .Values() .OpenParen() .ParametersFrom(insertableFields, 0, DbSetting) .CloseParen() .End(); // Set the return value var result = identityField != null? string.Concat("CONVERT(", databaseType, ", SCOPE_IDENTITY())") : primaryField != null?primaryField.Name.AsParameter(DbSetting) : "NULL"; queryBuilder .Select() .WriteText(result) .As("[Result]") .End(); // Return the query return(queryBuilder.GetString()); }