How to drop a PostgreSQL database if there are active connections to it?


In PostgreSQL, you cannot drop a database if there are active connections to it. You must first terminate all connections to the database before you can drop it. Here are the steps you can follow to drop a PostgreSQL database with active connections:

1- Identify the active connections to the database you want to drop. You can use the following SQL query to list all active connections:

 

SELECT pg_terminate_backend(pg_stat_activity.pid)

FROM pg_stat_activity

WHERE pg_stat_activity.datname = 'your_database_name'

  AND pid <> pg_backend_pid();


 This query will terminate all connections to the database except for the current connection.

2- After running the above query, try to drop the database using the following SQL command:

 

DROP DATABASE your_database_name;


 If there are no more active connections to the database, this command will drop the database.

If there are still active connections to the database, you will get an error message indicating that the database cannot be dropped because there are still active connections. In this case, repeat step 1 to ensure all connections have been terminated, and then try again to drop the database.

Note that dropping a database will permanently delete all data in the database. Make sure to take appropriate backups and verify that you are dropping the correct database before proceeding.

Finding the maximum difference between columns from different rows in Postgresql


To find the maximum difference between columns from different rows in PostgreSQL, you can use a combination of window functions and subqueries. Here is an example query:

 

SELECT MAX(abs(t1.col1 - t2.col1)) AS max_diff

FROM (

  SELECT col1, ROW_NUMBER() OVER (ORDER BY id) AS row_num

  FROM table_name

) AS t1

JOIN (

  SELECT col1, ROW_NUMBER() OVER (ORDER BY id) AS row_num

  FROM table_name

) AS t2 ON t1.row_num < t2.row_num 


 This query will calculate the absolute difference between col1 values from all possible pairs of rows in the table and then return the maximum difference.

Here's a breakdown of how the query works:

  • We use two subqueries (t1 and t2) to generate row numbers for each row in the table, using the ROW_NUMBER() window function. We order the rows by the primary key column (id) to ensure consistent ordering.
  • We join the two subqueries on the row numbers, with t1.row_num < t2.row_num to ensure that we only compare each row to all subsequent rows.
  • We calculate the absolute difference between the col1 values from t1 and t2 using abs(t1.col1 - t2.col1).
  • Finally, we use MAX() to return the maximum difference across all pairs of rows.

Note that this query only considers one column (col1) for simplicity, but you can modify it to include additional columns as needed.

How do I force Postgres to respect the configuration file on service start? Or how can I assign shared_buffer and max_connections on boot?


 By default, Postgres will use the values specified in its configuration file when it starts up. However, there are a few things you can do to ensure that it respects the configuration file and uses the values you specify.

First, make sure that the configuration file is in the correct location and has the correct name. By default, the configuration file is named postgresql.conf and is located in the data directory. You can specify a different configuration file using the -D and -c options when starting the Postgres service.

Second, check the output of the Postgres service startup logs to see if there are any errors or warnings related to the configuration file. If there are errors or warnings, you will need to address those issues before the service will start using the values specified in the configuration file.

If you still have trouble getting Postgres to use the values specified in the configuration file, you can try explicitly setting the values using the -c option when starting the service. For example, to set the shared_buffers and max_connections parameters, you can use the following command:

 

sudo systemctl start postgresql -c "shared_buffers=512MB" -c "max_connections=100"

 

This will start the Postgres service with shared_buffers set to 512MB and max_connections set to 100. Note that this approach will override any values specified in the configuration file, so use it with caution.

 

What is data annotation?


Data annotation is a way to define metadata for model properties in .NET applications. This metadata can be used for various purposes, such as validation, formatting, and documentation. In .NET Core 6.0, data annotations are implemented using attributes that can be applied to model properties.

Why would I use Data Annotation?

Here are some reasons why you might want to use data annotations in your .NET application:

  • Validation: Data annotations can be used to validate input data and ensure that it meets specific criteria. For example, you can use the [Required] attribute to ensure that a property is not null or empty, or the [RegularExpression] attribute to ensure that a property matches a specific pattern.
  • Formatting: Data annotations can be used to format property values in a specific way. For example, you can use the [DataType(DataType.Date)] attribute to ensure that a date property is displayed in a specific format.
  • Documentation: Data annotations can be used to provide additional information about a model property, which can be used for documentation purposes. For example, you can use the [Display(Name = "First Name")] attribute to specify the display name for a property.
  • Simplify Code: Using data annotations can help simplify code by reducing the amount of validation code that needs to be written. Instead of writing custom validation logic, you can use data annotations to perform common validation tasks.

Here's an example of how to use data annotations in .NET Core 6.0:

 

using System.ComponentModel.DataAnnotations;

public class Person

{

    [Required(ErrorMessage = "Name is required")]

    public string Name { getset; }

 

    [EmailAddress(ErrorMessage = "Invalid email address")]

    public string Email { getset; }

 

    [Range(18, 99, ErrorMessage = "Age must be between 18 and 99")]

    public int Age { getset; }

}

 

In this example, we have defined a Person class with three properties: Name, Email, and Age. We have used data annotations to define metadata for each property.

The [Required] attribute specifies that the Name property is required and will generate an error message if it is not present. The [EmailAddress] attribute specifies that the Email property must be a valid email address. The [Range] attribute specifies that the Age property must be between 18 and 99.

Data annotations can be used in conjunction with model binding and validation in ASP.NET Core controllers to ensure that the data being submitted by users is valid and meets the required criteria.

 

[HttpPost]

public IActionResult Create(Person person)

{

    if (!ModelState.IsValid)

    {

        return BadRequest(ModelState);

    }

    return Ok();

} 

 

In this example, we have defined a Create action that accepts a Person object as input. We have used ModelState.IsValid to check whether the data being submitted is valid, and if not, we return a BadRequest response with the error messages generated by the data annotations.

Overall, data annotations provide a convenient way to define metadata for model properties in .NET Core 6.0 applications, and can be used for a variety of purposes such as validation, formatting, and documentation. 

What is new in .Net 6.0?


.NET Core 6.0 is a major release of the .NET Core framework that was released in November 2021. It is an open-source, cross-platform framework for building modern applications, including web applications, microservices, desktop applications, and more.

Some of the key features and improvements in .NET Core 6.0 include:

Performance improvements - .NET Core 6.0 includes various runtime and framework performance improvements, making it faster and more efficient than previous versions.

ASP.NET Core updates - This release includes new features in ASP.NET Core such as Web API improvements, better Blazor support, and more.

Improved productivity - .NET 6.0 includes many new features designed to improve developer productivity, including support for C# 10, top-level statements, file-scoped namespaces, and more.

Better support for cloud-native applications - .NET 6.0 includes better support for building and running cloud-native applications, including containerization, Kubernetes, and Azure Functions.

New APIs and libraries - .NET 6.0 introduces new APIs and libraries, including new APIs for HTTP/3 and gRPC, as well as new libraries for JSON, XML, and more.

Overall, .NET Core 6.0 is a major release that brings many new features and improvements to the framework, making it a great choice for building modern, high-performance applications.

 

Some fundamental things we should know when we started to work with .Net Core 6.0

 

Hot Reload

Hot Reload is a feature introduced in .NET 6.0 that allows you to make changes to your code while your application is running and see the changes immediately, without having to stop and restart the application. This can be a huge productivity boost for developers, as it enables a faster feedback loop when making changes to the code.

Hot Reload in .NET 6.0 is supported in Visual Studio 2022, Visual Studio for Mac 2022, and in the .NET CLI. The feature supports several scenarios, including adding or removing code, changing method signatures, and editing XAML or Razor files.

To use Hot Reload in Visual Studio, you can simply set a breakpoint in your code and then make changes to your code while your application is running. When you save your changes, the code will be reloaded automatically, and your breakpoint will be hit again. You can also make changes to XAML or Razor files and see the changes in real-time.

To use Hot Reload in the .NET CLI, you can use the dotnet watch command to automatically reload your application when changes are detected. For example, you can run dotnet watch run to start your application and watch for changes.

Hot Reload in .NET 6.0 is a powerful feature that can help boost developer productivity and streamline the development process. It allows you to make changes to your code in real-time and see the results immediately, making it easier to debug and test your code.

 

Project file

In .NET Core 6.0, the project file format has been updated to a simplified format called "SDK-style" project files. The new project file format is designed to be more concise and easier to read, with a focus on the project's dependencies and configuration.

The SDK-style project file format eliminates the need for separate project files for different project types, such as class library, console app, and web app projects. Instead, all project types are supported within a single project file.

Here is an example of an SDK-style project file for a console application in .NET 6.0:

<Project Sdk="Microsoft.NET.Sdk">

      <PropertyGroup>

            <OutputType>Exe</OutputType>

            <TargetFramework>net6.0</TargetFramework>

      </PropertyGroup>

 

      <ItemGroup>

            <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="6.0.0" />

            <PackageReference Include="Newtonsoft.Json" Version="13.0.1" />

      </ItemGroup>

</Project>

As you can see, the project file starts with a <Project> element that specifies the SDK version to use. The <PropertyGroup> element contains configuration settings for the project, such as the output type and target framework. The <ItemGroup> element lists the project's dependencies, which are defined as package references.

The new project file format in .NET 6.0 makes it easier to manage and configure projects, with a simplified structure that makes it easier to read and understand.

Launch Setting Json

In .NET Core 6.0, the launchSettings.json file is used to configure how the application is launched when running in Visual Studio or using the dotnet run command. The launchSettings.json file can be found in the Properties folder of a project, and it contains a set of profiles that define different launch configurations for the application.

 

Here's an example of a launchSettings.json file in .NET 6.0:

{

  "profiles": {

    "MyApp": {

      "commandName": "Project",

      "workingDirectory": "$(ProjectDir)",

      "environmentVariables": {

        "ASPNETCORE_ENVIRONMENT": "Development"

      },

      "applicationUrl": "https://localhost:5001;http://localhost:5000"

    }

  }

}

 

In this example, there is one profile named "MyApp". The commandName property specifies that the project should be launched as a project. The workingDirectory property specifies the project's root directory. The environmentVariables property sets the ASPNETCORE_ENVIRONMENT variable to "Development". The applicationUrl property specifies the URLs to use when launching the application.

You can add additional profiles to the launchSettings.json file to define different launch configurations for the application. For example, you might have one profile for running the application locally and another profile for running the application in a production environment.

Overall, the launchSettings.json file in .NET 6.0 provides a convenient way to configure and manage the launch settings for your application, making it easier to launch and debug your application in different environments.         

Appsetting.json

In .NET Core 6.0, the appsettings.json file is used to store configuration data for your application. The file contains key-value pairs that can be used to configure various aspects of the application, such as database connections, logging, and other application settings.

Here's an example of an appsettings.json file in .NET 6.0:

{

  "ConnectionStrings": {

    "MyDatabase": "Server=myserver;Database=mydatabase;User Id=myuser;Password=mypassword;"

  },

  "Logging": {

    "LogLevel": {

      "Default": "Information",

      "Microsoft": "Warning",

      "System": "Error"

    }

  },

  "MyAppSettings": {

    "SomeSetting": "SomeValue",

    "AnotherSetting": "AnotherValue"

  }

}

 

In this example, the file contains three sections: ConnectionStrings, Logging, and MyAppSettings. The ConnectionStrings section contains a connection string that can be used to connect to a database. The Logging section specifies the log levels for various parts of the application. The MyAppSettings section contains custom settings for the application.

You can access the values in the appsettings.json file from your application code using the Configuration object. The Configuration object is created by the ASP.NET Core host and is available throughout the application.

Here's an example of how to access the ConnectionStrings section in the appsettings.json file:

 

var builder = WebApplication.CreateBuilder(args);

 

// Add services to the container.

 

builder.Services.AddControllers();

var connectionString = builder.Configuration.GetConnectionString("DBConnectionString");

builder.Services.AddDbContext<SQLDBContext>(options => options.UseSqlServer(connectionString));

Overall, the appsettings.json file in .NET 6.0 provides a convenient way to store and manage configuration data for your application, making it easier to configure and customize your application's behavior.

 

Program.cs

Program and Startup files are unified into Program.cs file. Here you can see how new Program.cs file’s code looks like.

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddRazorPages();

var app = builder.Build();

// Configure the HTTP request pipeline.

if (!app.Environment.IsDevelopment())

{

    app.UseExceptionHandler("/Error");

    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.

    app.UseHsts();

}

app.UseHttpsRedirection();

app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapRazorPages();

app.Run();

 

  • ConfigureServices is replaced with WebApplication.Services.
  • builder.Build() returns a configured WebApplication to the variable app. Configure is replaced with configuration calls to same services using app.

 

SQL Server: Query to remove special characters from string


The following query can be used to remove special characters from a string using the STUFF function:

DECLARE @String VARCHAR(100) = 'Hello@!#$%^&*()_+ World'

SELECT STUFF(@String, PATINDEX('%[^a-zA-Z0-9 ]%', @String), 1, '') AS [CleanString]

WHILE PATINDEX('%[^a-zA-Z0-9 ]%', @String) > 0

BEGIN

  SET @String = STUFF(@String, PATINDEX('%[^a-zA-Z0-9 ]%', @String), 1, '')

END

SELECT @String AS [CleanString]

This query uses the PATINDEX function to search for any characters that are not letters, numbers, or spaces. The STUFF function then replaces these characters with an empty string. The process is repeated until all special characters are removed. The final result is stored in the @String variable.

What is the difference between OLAP and OLTP?


OLAP (Online Analytical Processing) and OLTP (Online Transaction Processing) are two different approaches to organizing and managing data in a database. 

OLTP is designed to manage transaction-oriented applications, which require fast query performance and efficient data modification operations. It is optimized for insert, update, and delete operations and focuses on maintaining data accuracy and consistency through transactions. In an OLTP system, data is stored in a normalized fashion to minimize redundancy and improve data integrity. 

On the other hand, OLAP is designed for data analysis and business intelligence tasks, which require fast access to aggregated data. It is optimized for complex queries and aggregations and focuses on storing data in a denormalized fashion to improve query performance. In an OLAP system, data is often pre-calculated and stored in a multidimensional data model, such as a cube, to allow for quick access to aggregated data. 

In summary, OLTP is optimized for transactional systems, while OLAP is optimized for data analysis. 

Related Posts

How to drop a PostgreSQL database if there are active connections to it?

In PostgreSQL, you cannot drop a database if there are active connections to it. You must first terminate all connections to the database be...