ALM DOs & DON’Ts – Database source control

Every application needs to store its data. A (relational) database is the most common choice in many situations. Like every other component of our software project, a database schema must be managed with a version control system. We will never work without source control for our source code files and we must use the same mindset when dealing with a db.

database-source-control.png

The database is a critical part of our application. If we deploy version 2.0 of our application against version 1.0 of our database, what do we get? A broken application. And that’s why our database should always be under source control right next to our application code.

Advertisements

ALM DOs and DON’Ts – CI builds status

We all know the practice of continuous integration.

One of the common pitfalls about CI is that the build status is not monitored and not treated as one of the top priorities for the team.

build-ci-status

A healty/green status of our CI process means that our code is in a good shape for what our automated tests can tell. Fixing the build status ASAP is easier than leave it red and fix later because the recent changes of the codebase are vivid in the team members’ memory.

Quella sottile linea invisibile

Camminando giusto giusto sul confine tra Italia e Austria nel percorso Water Trail.

Un passo sei di qua e un passo sei di là. Così semplice, quasi banale. Eppure la differenza è enorme. Sarà una fissa mia ma queste cose mi affascinano. E mi chiedo: perché proprio lì la linea di confine e non un metro prima o dopo? Come viene deciso?

Questi confini geografici mi scatenano poi dei pensieri piu generici o astratti. Quanti confini attraversiamo nella nostra vita? E quanti ammettono un tornare indietro?

I nostri confini sono anche ciò che ci caratterizza: i nostri limiti, i nostri princìpi, la nostra confort zone. Cosa facciamo quotidianamente e in modo tangibile per espandere noi stessi, le nostre abilità e le nostre conoscenze?

Detto questo mi fermo qua, potrei cominciare a farneticare e sconfinare in un territorio filosofeggiante che non mi appartiene.

A voi affascinano i limiti, i confini, le situazioni limite?

Mastering database migrations scripts with VSTS

During the lifecycle of our applications it’s very likely that to support new functionalities we need to modify the structure of our database. In this particular post I mean a relational database.

When we deal with a database in a production environment we can’t simply drop an existing database and create a new one with the latest version of the schema.

The database is unlike application code in as much as it contains state, in terms of table-based data,  that needs to be preserved after an upgrade.

drop-create

This is why when dealing with database changes we need to talk about migration scripts.

Migration Scripts

A migration script is a set of SQL commands that changes the database schema or updates data to evolve the database from the version n-1 to the version whitout loss of data.

Migration scripts are typically collected in a dedicated folder in our repository, named sequentially.

The migration scripts must be executed in the specific order to be able to build the n-th version of our database.

The first migration script

The first script in our collection is responsible to create the first version of our db starting from an empty database.

The following is an example of a simple first migration script that we can name 00000001.sql. The example is for a simple database with one schema named Ordering and one table called Customers in the Ordering schema.

CREATE SCHEMA Ordering
GO
CREATE TABLE Ordering.Customers(
    Id INT PRIMARY KEY,
    CompanyName NVARCHAR(100) NOT NULL
)
GO

Create the first migration script from an existing database

If we work on a solution with an existing complex database we need a tool to create our first migration script. Tools are capable of tracking dependencies and relations inside the db schema to calculate a single script that evolves our db to the desired state. There are many tools on the market. In this example we’ll use Red-Gate SQL Compare. With this tool we select our existing db as the source (IC6.ParrishShoes) and our target to sync. As we explained before we need an empty database so we compare our db to that and we obtain our first script.

The script calculated by SQL Compare engine is the following.

/*
Run this script on:

        ..EmptyTarget    -  This database will be modified

to synchronize it with:

        ..IC6.ParrishShoes

You are recommended to back up your database before running this script

Script created by SQL Compare version 13.4.0.6563 from Red Gate Software Ltd at 03/08/2018 23:20:53

*/
SET NUMERIC_ROUNDABORT OFF
GO
SET ANSI_PADDING, ANSI_WARNINGS, CONCAT_NULL_YIELDS_NULL, ARITHABORT, QUOTED_IDENTIFIER, ANSI_NULLS ON
GO
SET XACT_ABORT ON
GO
SET TRANSACTION ISOLATION LEVEL Serializable
GO
BEGIN TRANSACTION
GO
IF @@ERROR  0 SET NOEXEC ON
GO
PRINT N'Creating schemas'
GO
CREATE SCHEMA [Ordering]
AUTHORIZATION [dbo]
GO
IF @@ERROR  0 SET NOEXEC ON
GO
PRINT N'Creating [Ordering].[Customers]'
GO
CREATE TABLE [Ordering].[Customers]
(
[Id] [int] NOT NULL,
[CompanyName] [nvarchar] (100) COLLATE Latin1_General_CI_AS NOT NULL
)
GO
IF @@ERROR  0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK__Customer__3214EC072CF93715] on [Ordering].[Customers]'
GO
ALTER TABLE [Ordering].[Customers] ADD CONSTRAINT [PK__Customer__3214EC072CF93715] PRIMARY KEY CLUSTERED  ([Id])
GO
IF @@ERROR  0 SET NOEXEC ON
GO
COMMIT TRANSACTION
GO
IF @@ERROR  0 SET NOEXEC ON
GO
-- This statement writes to the SQL Server Log so SQL Monitor can show this deployment.
IF HAS_PERMS_BY_NAME(N'sys.xp_logevent', N'OBJECT', N'EXECUTE') = 1
BEGIN
    DECLARE @databaseName AS nvarchar(2048), @eventMessage AS nvarchar(2048)
    SET @databaseName = REPLACE(REPLACE(DB_NAME(), N'\', N'\\'), N'"', N'\"')
    SET @eventMessage = N'Redgate SQL Compare: { "deployment": { "description": "Redgate SQL Compare deployed to ' + @databaseName + N'", "database": "' + @databaseName + N'" }}'
    EXECUTE sys.xp_logevent 55000, @eventMessage
END
GO
DECLARE @Success AS BIT
SET @Success = 1
SET NOEXEC OFF
IF (@Success = 1) PRINT 'The database update succeeded'
ELSE BEGIN
	IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION
	PRINT 'The database update failed'
END
GO

Compile a database

If we run the previous script and we get zero errors we can say that we can compile our database. The same concept apply when we can execute a collection of migration scripts in the correct order without errors.

Being able to compile a database it’s a huge benefit because it enables us to create a database on demand by simply executing a list of script to get the desired version on which we can develop, run test, deploy to a new customer etc. We can also start to do some automation for our database tasks.

Automation with VSTS – Checking our migration scripts

An important part of having a collection of db migrations scripts is that we have to frequently check that this chain of scripts is valid.

We can invest in automation to do that and with VSTS is very simple to get started.

In the following example we create a build process that executes all the migrations scripts in our repository to a target database to check if everything can be completed without errors.

We go to the Build section of VSTS and create a new Build process from an empty process.

We browse in the marketplace the DbUp extension (free!).

DbUp is a .NET library that helps you to deploy changes to SQL Server databases. It tracks which SQL scripts have been run already, and runs the change scripts that are needed to get your database up to date.

2018-08-03_23-40-20

After the installation process of DbUb we can refresh our list of available task and add the DbUp Migration task. With this task we can execute scripts included in a folder of our repository to a target database. The configuration of the connection string is done with VSTS Build variables in the dedicated tab. We configure the script folder path and the Single Transaction strategy, too. This way all the scripts are executed in one single transaction and if we get an error everything will be rolled-back.

2018-08-04_00-06-31

2018-08-04_00-16-49.png

When we complete the configuration of the task we click Save And Queue.

The build process will start and if we’re a bit lucky everything will succeed.

2018-08-04_00-24-07.png

We can see that DbUp applied correctly the scripts by browing the db with SQL Mangament.

  • First 2018-08-04_00-07-34
  • After 2018-08-04_00-12-42

TL; DR

With this tutorial we’ve learned the basics of migrations scripts, how to create them with a tool and how to check if our collection of scripts is valid with automation implemented with VSTS and DbUp.

This is just the start

When we have such powerful tools we can start to think about automated processes that test our chain of scripts in many ways. We can do an “incremental” approach like the example above triggered at every change in the scripts folder. We can schedule a build process that every day at noon will execute all the migration scripts versus a temporary brand new database.

What will you do with this super powers? Let me know in the comments below!

Reference

VSTS DbUp Marketplace – https://marketplace.visualstudio.com/items?itemName=johanclasson.UpdateDatabaseWithDbUp

Red-Gate SQL Compare – https://www.red-gate.com/products/sql-development/sql-compare/index

Power is nothing without control

You can’t control (leave alone improve) what you can’t see – Me

Power is nothing without control – Pirelli

Why a dashboard?

When we drive our car we have everything under control: speed, revs, oil and water temperatures and fuel level. We need a dashboard in our car because we have to know our current speed to respect speed limits, to know how much petrol we have in our fuel-tank to decide if we can go to work without a trip to the gas station etc. All this data to do the simple job of driving! This is necessary because we need to take informed decisions.

white motorcycle cluster gauge
Photo by Mikes Photos on Pexels.com

What does it mean for our daily activities in a software department? We need our dashboard, too! How can we do our job of deliveing (not only writing!) a working software with the lowest bug count as possibile, quickly, on a budget and coordinating with other people? It’s a huge task compared to drive a car alone and yet many of us rely on instinct and guts to make decisions for an entire software team.

A dashboard for the software Engineer

Which indicators and gauges do we need as software engineers? I think there are a few things we Always need to know about our team.

  1. Team Cycle time: how much time/days does a unit of work take to go from started to completed? And with completed we mean delivered to the customer.
  2. Team Lead time: how much time/days dows a unit of work take to go from a created to completed?
  3. How fast are we going? How many story points we deliver every fixed amount of time? (sprint, week… name your favorite).
  4. Bug count. How many known defects (bugs) have we? Is the count increasing or decreasing?

Here we can see a dashboard created with Microsoft VSTS where the team can get an immediate report of the situation.

2018-08-03_13-46-49.png

Create a dashboard

Every team is different and needs specific/custom dashboard. To create a dashboard with Microsoft VSTS we can go to

https://THE_DOMAIN/THE_PROJECT/_dashboards/

and then we expand the dashboard list with the arrow button (1) and click New Dashboard (2).

2018-08-03_14-02-31.pngWe give our dashboard a name and hit Create.

2018-08-03_14-09-48.pngWe can add widgets picking from the right-side list, search or browse the Marketplace to add something extra to our VSTS.

2018-08-03_14-11-55.png

When we’ve finished to create our dashboard we click “Done editing”.

TL; DR

A dashboard is a must have to control or improve our team and our process. It enables us to understand our current indicators and shows if a new way to work improves or worsen the situation. With a dashboard we can take informed decisions about many arugments: current velocity of the team, quality of the software, lead time and so on. We’ve seen how to create and configure a dashboard with Microsoft VSTS.

Reference

Microsoft VSTS Docs: https://docs.microsoft.com/en-us/vsts/report/dashboards/?view=vsts

I principi di Dale Carnegie

Sto ripassando, dopo un po’ troppi mesi, i testi di Dale Carnegie.

Metto qui a futura memoria e per rapida consultazione l’elenco dei principi trattati.

Principi Dale Carnegie

Tecniche fondamentali per trattare con la gente

  1. Non criticare, non recriminare, non giudicare.
  2. Siate prodighi di apprezzamenti onesti e sinceri.
  3. Suscitate negli altri la vostra stessa volontà.

Sei modi per farsi benvolere

  1. Interessatevi sinceramente delle altre persone.
  2. Sorridete
  3. Ricordatevi che per una persona il suo nome è il suono più importante e più dolce in qualsivoglia lingua.
  4. Siate buoni ascoltatori. Incoraggiate gli altri a parlare di se stessi.
  5. Parlate di quello che interessa agli altri.
  6. Fate in modo che gli altri si sentano importanti con la massima naturalezza e sincerità.

Come convincere il prossimo a condividere le vostre opinioni

  1. Il modo migliore per avere una discussione consiste nell’evitarla.
  2. Mostrate rispetto per le opinioni altrui. no dite mai: “Lei ha torto!”.
  3. Se avete torto, ammettetelo subito e spassionatamente.
  4. Cominciate sempre col mostrarvi amici
  5. Fate in modo che il vostro interlocutore sia indotto a rispondere sì sin dal principio.
  6. Lasciate che i vostri interlocutori chiaccherino quanto vogliono.
  7. Date agli altri la sensazione che siano stati loro per primi ad avere l’idea giusta.
  8. Cercate di vedere onestamente le cose dal punto di vista del vostro interlocutore.
  9. Siate comprensivi nei confronti delle idee e dei desideri altrui.
  10. Fate appello ai motivi più nobili.
  11. Drammatizzate le vostre idee.
  12. Lanciate una sfida.

Essere un leader: come far cambiare opinione agli altri senza offendere e suscitare risentimenti

  1. Iniziare sempre con le lodi e l’apprezzamento sincero.
  2. Richiamate l’attenzione degli errori altrui in maniera indiretta.
  3. Parlate dei vostri errori prima di sottolineare quelli altrui.
  4. Fate domande invece di impartire ordini diretti.
  5. Fate in modo che l’altra persona salvi la faccia.
  6. Lodate ogni più piccolo progresso. Siate calorosi nell’approvazione e prodighi di lodi.
  7. Date agli altri l’impressione di avere una reputazione da difendere.
  8. Usate l’incoraggiamento. Mostrate quant’è facile correggere gli errori.
  9. Fate sì che l’altra persona sia felice di fare quello che le suggerite.