It was Ramiel who stabbed Castiel with the spear, and he did it in Supernatural season 12 with the Lance of Michael. The point of the attack was basically to use one of Heaven’s deadliest weapons against an angel, and it nearly killed Cas because the lance is designed to slowly and painfully destroy angels.

What happened

Ramiel had the Lance of Michael, a divine weapon originally created by Archangel Michael, and used it on Castiel during the battle in “Stuck in the Middle (With You).” The weapon was built to kill good beings slowly and agonizingly, which is why Castiel was in such bad shape after being stabbed.

Why he did it

Ramiel was fighting the Winchesters and their allies, so stabbing Castiel was part of the battle rather than a random attack. He was protecting himself and using the lance as a weapon against an enemy angel, which made the scene especially brutal.

What saved Cas

Castiel survived because Crowley broke the lance, which destroyed its power and reversed the effect on Cas. Once the weapon was broken, Castiel recovered almost immediately.

TL;DR

Ramiel stabbed Castiel with the Lance of Michael because he was using a powerful angel-killing weapon in combat, and the lance’s magic was what nearly killed Cas.