If you're looking to go back far enough to the origins of the pistol you are going to be looking at 14th and 15th century European history. The pistol never developed independently, the cannon had been around a long time, and was refined to the various arquebuses, early muskets and early pistols. The reason these firearms were developed, including the pistol was simple. Europe was divided into dozens of regions constantly at war and now that there was technology that could beat the mounted knight for a fraction of the cost of maintaining ones own mounted knights....off they went with the firearm.
The first pistols and other firearms were used as offensive weapons in war because it was easy and cheap to arm a bunch of illiterate serfs with them and actually have them be able to kill the cream of the crop of your neightbors mounted forces. The knights got off their horses and the development of firarms based armies began. The pistol wasn't a defensive weapon for a long time, as they were in the early days, the property of whichever duke or king was arming his serfs. In fact, they were so inaccurate in the beginning they weren't really feasible to use individually anyway, which is why the early style of firearms warfare developed with massed "walls" of men firing volleys together at the enemy. Even long after the firarm was in use and infantry armies were growing again, the primary weapon was still a core of pikemen of some sort. The pistol was just a refined version of these firarms and as someone mentioned, worked perfectly for mobile cavalry. However, still, the cavalry primary weapon was still the sword. The pistol used up close and personal, very close. I guess you could argue that they would be for self defense in that case, however the cavalry was probably already involved in a war to begin with.
If you were looking for some historical root of pistols being created as defensive weapons, there probably isn't any. All historical roots of firearms were as weapons for cheap, easy to train offfensive armies. Those armies were not standing armies either in the early days, it was simply too expensive to maintain any type of force unless you wanted to use it to attack.
As for why officers were armed in the 19th century, once revolvers were invented, it was only good practice to arm the police who were charged with maintaining law and order with them. The reason for those police being armed is the same as it is now, the police are tasked with entering and intervening in any potentially violent situation and unlike the public, dont' really have the option to escape and avoid.