I have been told that the 7th of a scale in most cases is a leading tone. In Du gamla du fria we start the melody with what one could call the 3rd of the scale. The first phrase would then end on the 7th. I cannot hear this note as the leading tone. It could be that we are using two scales here. The melody ends on 1(Do) in the scale of the tonic but we actually start in 6 (La) in the scale of the dominant. We could even say that the whole tune ends on Fa and is in Lydoan mode. What is going on?
This is definitely in G Major overall, and the first phrase ends on a V chord, with the melody on the leading tone. However, the A Major chord right before it is obscuring the tonic, making the D Major sound more tonic than it is (overall.) The second phrase is traveling quite a bit harmonically with all the accidentals, though most of them seem to be serving chromatic non-chord tone movement than a harmonic function. Phrases 3&4 are clearly in G Major and the end resolves soundly in G Major.
As Tim says this is an modulation to D - we'd better call it an extension - and the leading tone is now C# of D.
Look at the 2nd pharse: it is completely in D (and seems to imitate the initial motif: the F# is now the 3rd of the new key and ends on D (again c#=leading tone).
The 3rd phrase starts with an upbeat of a 4th again in G and subito modulates to D again (mind the C# in the Alto and Bass!)
The 4th phrase is repeated and in the last ending has a short extension to the relative key E minor but the final ending is clearly G (leading tone F#).
What do you mean with this?
The melody ends on 1(Do) in the scale of the tonic but we actually start in 6 (La) in the scale of the dominant.
Do you mean the first tone of the song? If this B in your opinion is the 6th of D you're wrong. This is the majord 3rd of the triad of the tonic G: GBD
It is easy enough to "analyze" the OP's version as common practice harmony but (like the OP?) I don't find it very convincing musically. It's far too "fussy" - J S Bach could get away harmonizing a simple folk tune with transient key changes on almost every note, but not this composer.
The tune is only "in G major overall" if you want to hear it that way. It works just as well in E aeolian, except I put a G chord on the last note. That way, the problem F# isn't a leading note at all.
BTW if your harmony textbook says the 6/4 chords in this version are "wrong", the check if your ears agree with the book, and if not, find a different book :)