import urllib

import pyvo
from astropy.table import Table

# Load our example table
our_data = Table.read(
  "http://docs.g-vo.org/pmadd-testdata.txt",
	format="ascii")

# Fix its metadata 
# (not required with a sensible input format)
our_data["col1"].name, our_data["col2"].name = "ra", "dec"

# construct a service; I've taken the URL from TOPCAT's 
# TAP service browser # ("Selected TAP Service" near the 
# foot of the dialog)
service = pyvo.dal.TAPService(
  "http://gea.esac.esa.int/tap-server/tap")

# run the query and retrieve the result; note that the 
# "t1" after TAP_UPLOAD must match the key in the uploads 
# dictionary.
result = service.run_sync("""
  SELECT
   tc.*, pmra, pmdec, 
   phot_g_mean_mag, phot_bp_mean_mag, phot_rp_mean_mag
   FROM gaiadr2.gaia_source AS db
   JOIN TAP_UPLOAD.t1 AS tc
   ON 1=CONTAINS(POINT('ICRS', db.ra, db.dec),
                 CIRCLE('ICRS', tc.ra, tc.dec, 1./3600.))""",
  uploads = {'t1': our_data}).to_table()

# save the results; use a useful format now.
result.write("our-data-amended.vot", format="votable")
