### How to differentiate a messy function of 2 variables

I have a very involved and messy function of two variable for which I need to find 1st and 2nd derivatives. It makes more sense to break this into "functions" so that one can use the chain rule. The following is a simplified version of what I really need.

x0 = 1 + hg^2 + h
y0 = g + h^2

f1 = Ax0 - y0
f2 = By0 + x0

d = sqrt(f1^2 + f2^2)

I need partial of d w.r.t. g, partial of d w.r.t. h, partial of d w.r.t. g^2, etc.

How can I do this in SageMath?