A controversial bill to change South Australia's abortion laws has been narrowly defeated in the state's upper house.