How to use the carto.sql.SQLClient function in carto

To help you get started, we’ve selected a few carto examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github CartoDB / carto-python / tests / test_sql.py View on Github external
def test_sql(api_key_auth_client_usr, mock_requests, do_post=True):
    with mock_requests.mocker:
        sql = SQLClient(api_key_auth_client_usr)
        data = sql.send('select * from ' + EXISTING_POINT_DATASET,
                        do_post=do_post)

    assert data is not None
    assert 'rows' in data
    assert 'total_rows' in data
    assert 'time' in data
    assert len(data['rows']) > 0
github CartoDB / carto-python / tests / test_sql.py View on Github external
def test_sql_unverified_fails_with_auth_client(wrong_onprem_auth_client):
    if wrong_onprem_auth_client is None:
        assert True is True
        return

    sql = SQLClient(wrong_onprem_auth_client)
    with pytest.raises(CartoException):
        data = sql.send('select version()')
github CartoDB / cartoframes / test / test_context.py View on Github external
"renaming `secret.json.sample` to `secret.json` "
                              "and updating the credentials to match your "
                              "environment.")
                self.apikey = None
                self.username = None
        else:
            self.apikey = os.environ['APIKEY']
            self.username = os.environ['USERNAME']

        self.user_url = self.user_url()

        if self.username and self.apikey:
            self.baseurl = self.user_url.format(username=self.username)
            self.auth_client = APIKeyAuthClient(base_url=self.baseurl,
                                                api_key=self.apikey)
            self.sql_client = SQLClient(self.auth_client)

        # sets skip value
        WILL_SKIP = self.apikey is None or self.username is None  # noqa: F841

        # table naming info
        has_mpl = 'mpl' if os.environ.get('MPLBACKEND') else 'nonmpl'
        has_gpd = 'gpd' if os.environ.get('USE_GEOPANDAS') else 'nongpd'
        pyver = sys.version[0:3].replace('.', '_')
        buildnum = os.environ.get('TRAVIS_BUILD_NUMBER')

        test_slug = '{ver}_{num}_{mpl}_{gpd}'.format(
            ver=pyver, num=buildnum, mpl=has_mpl, gpd=has_gpd
        )

        # test tables
        self.test_read_table = 'cb_2013_us_csa_500k'
github CartoDB / carto-python / tests / test_sql.py View on Github external
def test_no_auth_sql_error_get(no_auth_client):
    sql = SQLClient(no_auth_client)

    with pytest.raises(CartoException):
        sql.send('select * from non_existing_dataset', {'do_post': False})
github CartoDB / cartoframes / tests / unit / core / managers / test_context_manager.py View on Github external
def test_execute_query(self, mocker):
        # Given
        mocker.patch('cartoframes.core.managers.context_manager._create_auth_client')
        mock = mocker.patch.object(SQLClient, 'send')

        # When
        cm = ContextManager(self.credentials)
        cm.execute_query('query')

        # Then
        mock.assert_called_once_with('query', True, True, None)
github CartoDB / carto-python / examples / export_dataset.py View on Github external
'Default is `csv`')

args = parser.parse_args()


# Authenticate to CARTO account
if args.CARTO_BASE_URL and args.CARTO_API_KEY and args.organization:
    auth_client = APIKeyAuthClient(
        args.CARTO_BASE_URL, args.CARTO_API_KEY, args.organization)
else:
    logger.error('You need to provide valid credentials, run with -h parameter for details')
    import sys
    sys.exit(1)

# SQL wrapper
sql = SQLClient(APIKeyAuthClient(args.CARTO_BASE_URL, args.CARTO_API_KEY))

query = "select * from " + args.DATASET + ""
result = sql.send(query, format=args.EXPORT_FORMAT)

filename = args.DATASET + "." + args.EXPORT_FORMAT
with open(filename, 'w') as f:
    f.write(result)
f.close()

print("File saved: " + filename)
github CartoDB / carto-python / examples / copy_example.py View on Github external
' (defaults to env variable CARTO_API_KEY)')


args = parser.parse_args()

# Set authentification to CARTO
if args.CARTO_BASE_URL and args.CARTO_API_KEY:
    auth_client = APIKeyAuthClient(
        args.CARTO_BASE_URL, args.CARTO_API_KEY)
else:
    logger.error('You need to provide valid credentials, run with '
                 '-h parameter for details')
    sys.exit(1)

# Create and cartodbfy a table
sqlClient = SQLClient(auth_client)
sqlClient.send("""
    CREATE TABLE IF NOT EXISTS copy_example (
      the_geom geometry(Geometry,4326),
      name text,
      age integer
    )
    """)
sqlClient.send("SELECT CDB_CartodbfyTable(current_schema, 'copy_example')")

copyClient = CopySQLClient(auth_client)

# COPY FROM example
logger.info("COPY'ing FROM file...")
query = ('COPY copy_example (the_geom, name, age) '
         'FROM stdin WITH (FORMAT csv, HEADER true)')
result = copyClient.copyfrom_file_path(query, 'files/copy_from.csv')
github CartoDB / carto-python / examples / duplicate_table.py View on Github external
args = parser.parse_args()

TABLE_NAME = args.TABLE_NAME

# Set authentification to CARTO
auth_src_client = APIKeyAuthClient(
    SRC_URL,
    SRC_API_KEY
)
auth_dst_client = APIKeyAuthClient(
    DST_URL,
    DST_API_KEY
)

# Get SQL API clients
sql_src_client = SQLClient(auth_src_client)
sql_dst_client = SQLClient(auth_dst_client)

# Create a SQL utility function to extract source table structure.
with open('generate_create_table_statement.sql', 'r') as f:
    query_generate_create_table_statement = f.read()
logger.info('Creating function generate_create_table_statement...')
res = sql_src_client.send(query_generate_create_table_statement)
logger.info('Response: {}'.format(res))

# Get the table structure
logger.info('Getting the CREATE TABLE statement for %s' % TABLE_NAME)
query = (
    "SELECT generate_create_table_statement('%s')"
    " AS create_table" % TABLE_NAME
)
res = sql_src_client.send(query)
github CartoDB / cartoframes / cartoframes / context.py View on Github external
def __init__(self, base_url=None, api_key=None, creds=None, session=None,
                 verbose=0):

        self.creds = Credentials(creds=creds, key=api_key, base_url=base_url)
        self.auth_client = APIKeyAuthClient(base_url=self.creds.base_url(),
                                            api_key=self.creds.key(),
                                            session=session)
        self.sql_client = SQLClient(self.auth_client)
        self.creds.username(self.auth_client.username)
        self.is_org = self._is_org_user()

        self._map_templates = {}
        self._srcdoc = None
        self._verbose = verbose
github CartoDB / cartoframes / cartoframes / context.py View on Github external
verbose=0):

        self.creds = Credentials(creds=creds, key=api_key, base_url=base_url)
        self.auth_client = APIKeyAuthClient(
            base_url=self.creds.base_url(),
            api_key=self.creds.key(),
            session=session,
            client_id='cartoframes_{}'.format(__version__),
            user_agent='cartoframes_{}'.format(__version__)
        )
        self.auth_api_client = AuthAPIClient(
            base_url=self.creds.base_url(),
            api_key=self.creds.key(),
            session=session
        )
        self.sql_client = SQLClient(self.auth_client)
        self.copy_client = CopySQLClient(self.auth_client)
        self.batch_sql_client = BatchSQLClient(self.auth_client)
        self.creds.username(self.auth_client.username)
        self._is_authenticated()
        self.is_org = self._is_org_user()

        self._map_templates = {}
        self._srcdoc = None
        self._verbose = verbose