Skip to content

Commit

Permalink
🎉 New Destination: SQLite (#15018)
Browse files Browse the repository at this point in the history
* sqlite destination skeleton

* Add doc

* Add destination to  general docs

* clean unused files

* add seed and icon

* sqlite destination skeleton

* Add doc

* Add destination to  general docs

* add seed and icon

* correct config file

* remove unused import

* run seed spec file

Co-authored-by: marcosmarxm <marcosmarxm@gmail.com>
Co-authored-by: Marcos Marx <marcosmarxm@users.noreply.github.com>
  • Loading branch information
3 people authored Aug 9, 2022
1 parent d057555 commit 474e8c4
Show file tree
Hide file tree
Showing 22 changed files with 701 additions and 0 deletions.
1 change: 1 addition & 0 deletions airbyte-config/init/src/main/resources/icons/sqlite.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
Expand Up @@ -308,3 +308,10 @@
documentationUrl: https://docs.airbyte.io/integrations/destinations/google-sheets
icon: google-sheets.svg
releaseStage: alpha
- name: Local SQLite
destinationDefinitionId: b76be0a6-27dc-4560-95f6-2623da0bd7b6
dockerRepository: airbyte/destination-sqlite
dockerImageTag: 0.1.0
documentationUrl: https://docs.airbyte.io/integrations/destinations/local-sqlite
icon: sqlite.svg
releaseStage: alpha
23 changes: 23 additions & 0 deletions airbyte-config/init/src/main/resources/seed/destination_specs.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -5158,3 +5158,26 @@
- - "client_secret"
oauthFlowOutputParameters:
- - "refresh_token"
- dockerImage: "airbyte/destination-sqlite:0.1.0"
spec:
documentationUrl: "https://docs.airbyte.io/integrations/destinations/sqlite"
connectionSpecification:
$schema: "http://json-schema.org/draft-07/schema#"
title: "Destination Sqlite"
type: "object"
required:
- "destination_path"
additionalProperties: false
properties:
destination_path:
type: "string"
description: "Path to the sqlite.db file. The file will be placed inside\
\ that local mount. For more information check out our <a href=\"https://docs.airbyte.io/integrations/destinations/sqlite\"\
>docs</a>"
example: "/local/sqlite.db"
supportsIncremental: true
supportsNormalization: false
supportsDBT: false
supported_destination_sync_modes:
- "overwrite"
- "append"
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
*
!Dockerfile
!main.py
!destination_sqlite
!setup.py
38 changes: 38 additions & 0 deletions airbyte-integrations/connectors/destination-sqlite/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
FROM python:3.9.11-alpine3.15 as base

# build and load all requirements
FROM base as builder
WORKDIR /airbyte/integration_code

# upgrade pip to the latest version
RUN apk --no-cache upgrade \
&& pip install --upgrade pip \
&& apk --no-cache add tzdata build-base


COPY setup.py ./
# install necessary packages to a temporary folder
RUN pip install --prefix=/install .

# build a clean environment
FROM base
WORKDIR /airbyte/integration_code

# copy all loaded and built libraries to a pure basic image
COPY --from=builder /install /usr/local
# add default timezone settings
COPY --from=builder /usr/share/zoneinfo/Etc/UTC /etc/localtime
RUN echo "Etc/UTC" > /etc/timezone

# bash is installed for more convenient debugging.
RUN apk --no-cache add bash

# copy payload code only
COPY main.py ./
COPY destination_sqlite ./destination_sqlite

ENV AIRBYTE_ENTRYPOINT "python /airbyte/integration_code/main.py"
ENTRYPOINT ["python", "/airbyte/integration_code/main.py"]

LABEL io.airbyte.version=0.1.0
LABEL io.airbyte.name=airbyte/destination-sqlite
123 changes: 123 additions & 0 deletions airbyte-integrations/connectors/destination-sqlite/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
# Sqlite Destination

This is the repository for the Sqlite destination connector, written in Python.
For information about how to use this connector within Airbyte, see [the documentation](https://docs.airbyte.io/integrations/destinations/sqlite).

## Local development

### Prerequisites
**To iterate on this connector, make sure to complete this prerequisites section.**

#### Minimum Python version required `= 3.7.0`

#### Build & Activate Virtual Environment and install dependencies
From this connector directory, create a virtual environment:
```
python -m venv .venv
```

This will generate a virtualenv for this module in `.venv/`. Make sure this venv is active in your
development environment of choice. To activate it from the terminal, run:
```
source .venv/bin/activate
pip install -r requirements.txt
```
If you are in an IDE, follow your IDE's instructions to activate the virtualenv.

Note that while we are installing dependencies from `requirements.txt`, you should only edit `setup.py` for your dependencies. `requirements.txt` is
used for editable installs (`pip install -e`) to pull in Python dependencies from the monorepo and will call `setup.py`.
If this is mumbo jumbo to you, don't worry about it, just put your deps in `setup.py` but install using `pip install -r requirements.txt` and everything
should work as you expect.

#### Building via Gradle
From the Airbyte repository root, run:
```
./gradlew :airbyte-integrations:connectors:destination-sqlite:build
```

#### Create credentials
**If you are a community contributor**, follow the instructions in the [documentation](https://docs.airbyte.io/integrations/destinations/sqlite)
to generate the necessary credentials. Then create a file `secrets/config.json` conforming to the `destination_sqlite/spec.json` file.
Note that the `secrets` directory is gitignored by default, so there is no danger of accidentally checking in sensitive information.
See `integration_tests/sample_config.json` for a sample config file.

**If you are an Airbyte core member**, copy the credentials in Lastpass under the secret name `destination sqlite test creds`
and place them into `secrets/config.json`.

### Locally running the connector
```
python main.py spec
python main.py check --config secrets/config.json
python main.py discover --config secrets/config.json
python main.py read --config secrets/config.json --catalog integration_tests/configured_catalog.json
```

### Locally running the connector docker image

#### Build
First, make sure you build the latest Docker image:
```
docker build . -t airbyte/destination-sqlite:dev
```

You can also build the connector image via Gradle:
```
./gradlew :airbyte-integrations:connectors:destination-sqlite:airbyteDocker
```
When building via Gradle, the docker image name and tag, respectively, are the values of the `io.airbyte.name` and `io.airbyte.version` `LABEL`s in
the Dockerfile.

#### Run
Then run any of the connector commands as follows:
```
docker run --rm airbyte/destination-sqlite:dev spec
docker run --rm -v $(pwd)/secrets:/secrets airbyte/destination-sqlite:dev check --config /secrets/config.json
# messages.jsonl is a file containing line-separated JSON representing AirbyteMessages
cat messages.jsonl | docker run --rm -v $(pwd)/secrets:/secrets -v $(pwd)/integration_tests:/integration_tests airbyte/destination-sqlite:dev write --config /secrets/config.json --catalog /integration_tests/configured_catalog.json
```
## Testing
Make sure to familiarize yourself with [pytest test discovery](https://docs.pytest.org/en/latest/goodpractices.html#test-discovery) to know how your test files and methods should be named.
First install test dependencies into your virtual environment:
```
pip install .[tests]
```
### Unit Tests
To run unit tests locally, from the connector directory run:
```
python -m pytest unit_tests
```

### Integration Tests
There are two types of integration tests: Acceptance Tests (Airbyte's test suite for all destination connectors) and custom integration tests (which are specific to this connector).
#### Custom Integration tests
Place custom tests inside `integration_tests/` folder, then, from the connector root, run
```
python -m pytest integration_tests
```
#### Acceptance Tests
Coming soon:

### Using gradle to run tests
All commands should be run from airbyte project root.
To run unit tests:
```
./gradlew :airbyte-integrations:connectors:destination-sqlite:unitTest
```
To run acceptance and custom integration tests:
```
./gradlew :airbyte-integrations:connectors:destination-sqlite:integrationTest
```

## Dependency Management
All of your dependencies should go in `setup.py`, NOT `requirements.txt`. The requirements file is only used to connect internal Airbyte dependencies in the monorepo for local development.
We split dependencies between two groups, dependencies that are:
* required for your connector to work need to go to `MAIN_REQUIREMENTS` list.
* required for the testing need to go to `TEST_REQUIREMENTS` list

### Publishing a new version of the connector
You've checked out the repo, implemented a million dollar feature, and you're ready to share your changes with the world. Now what?
1. Make sure your changes are passing unit and integration tests.
1. Bump the connector version in `Dockerfile` -- just increment the value of the `LABEL io.airbyte.version` appropriately (we use [SemVer](https://semver.org/)).
1. Create a Pull Request.
1. Pat yourself on the back for being an awesome contributor.
1. Someone from Airbyte will take a look at your PR and iterate with you to merge it into master.
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
plugins {
id 'airbyte-python'
id 'airbyte-docker'
}

airbytePython {
moduleDirectory 'destination_sqlite'
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
#
# Copyright (c) 2022 Airbyte, Inc., all rights reserved.
#


from .destination import DestinationSqlite

__all__ = ["DestinationSqlite"]
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
#
# Copyright (c) 2022 Airbyte, Inc., all rights reserved.
#

import datetime
import json
import os
import sqlite3
import uuid
from asyncio.log import logger
from collections import defaultdict
from typing import Any, Iterable, Mapping

from airbyte_cdk import AirbyteLogger
from airbyte_cdk.destinations import Destination
from airbyte_cdk.models import AirbyteConnectionStatus, AirbyteMessage, ConfiguredAirbyteCatalog, DestinationSyncMode, Status, Type


class DestinationSqlite(Destination):
@staticmethod
def _get_destination_path(destination_path: str) -> str:
"""
Get a normalized version of the destination path.
Automatically append /local/ to the start of the path
"""
if not destination_path.startswith("/local"):
destination_path = os.path.join("/local", destination_path)

destination_path = os.path.normpath(destination_path)
if not destination_path.startswith("/local"):
raise ValueError(
f"destination_path={destination_path} is not a valid path." "A valid path shall start with /local or no / prefix"
)

return destination_path

def write(
self, config: Mapping[str, Any], configured_catalog: ConfiguredAirbyteCatalog, input_messages: Iterable[AirbyteMessage]
) -> Iterable[AirbyteMessage]:

"""
Reads the input stream of messages, config, and catalog to write data to the destination.
This method returns an iterable (typically a generator of AirbyteMessages via yield) containing state messages received
in the input message stream. Outputting a state message means that every AirbyteRecordMessage which came before it has been
successfully persisted to the destination. This is used to ensure fault tolerance in the case that a sync fails before fully completing,
then the source is given the last state message output from this method as the starting point of the next sync.
:param config: dict of JSON configuration matching the configuration declared in spec.json
:param configured_catalog: The Configured Catalog describing the schema of the data being received and how it should be persisted in the
destination
:param input_messages: The stream of input messages received from the source
:return: Iterable of AirbyteStateMessages wrapped in AirbyteMessage structs
"""
streams = {s.stream.name for s in configured_catalog.streams}
path = config.get("destination_path")
path = self._get_destination_path(path)
con = sqlite3.connect(path)
with con:
# create the tables if needed
for configured_stream in configured_catalog.streams:
name = configured_stream.stream.name
table_name = f"_airbyte_raw_{name}"
if configured_stream.destination_sync_mode == DestinationSyncMode.overwrite:
# delete the tables
query = """
DROP TABLE IF EXISTS {}
""".format(
table_name
)
con.execute(query)
# create the table if needed
query = """
CREATE TABLE IF NOT EXISTS {table_name} (
_airbyte_ab_id TEXT PRIMARY KEY,
_airbyte_emitted_at TEXT,
_airbyte_data TEXT
)
""".format(
table_name=table_name
)
con.execute(query)

buffer = defaultdict(list)

for message in input_messages:
if message.type == Type.STATE:
# flush the buffer
for stream_name in buffer.keys():

query = """
INSERT INTO {table_name}
VALUES (?,?,?)
""".format(
table_name=f"_airbyte_raw_{stream_name}"
)

con.executemany(query, buffer[stream_name])

con.commit()
buffer = defaultdict(list)

yield message
elif message.type == Type.RECORD:
data = message.record.data
stream = message.record.stream
if stream not in streams:
logger.debug(f"Stream {stream} was not present in configured streams, skipping")
continue

# add to buffer
buffer[stream].append((str(uuid.uuid4()), datetime.datetime.now().isoformat(), json.dumps(data)))

# flush any remaining messages
for stream_name in buffer.keys():

query = """
INSERT INTO {table_name}
VALUES (?,?,?)
""".format(
table_name=f"_airbyte_raw_{stream_name}"
)

con.executemany(query, buffer[stream_name])

con.commit()

def check(self, logger: AirbyteLogger, config: Mapping[str, Any]) -> AirbyteConnectionStatus:
"""
Tests if the input configuration can be used to successfully connect to the destination with the needed permissions
e.g: if a provided API token or password can be used to connect and write to the destination.
:param logger: Logging object to display debug/info/error to the logs
(logs will not be accessible via airbyte UI if they are not passed to this logger)
:param config: Json object containing the configuration of this destination, content of this json is as specified in
the properties of the spec.json file
:return: AirbyteConnectionStatus indicating a Success or Failure
"""
try:
# parse the destination path
path = config.get("destination_path")
path = self._get_destination_path(path)

os.makedirs(os.path.dirname(path), exist_ok=True)
con = sqlite3.connect(path)
con.execute("SELECT 1;")

return AirbyteConnectionStatus(status=Status.SUCCEEDED)
except Exception as e:
return AirbyteConnectionStatus(status=Status.FAILED, message=f"An exception occurred: {repr(e)}")
Loading

0 comments on commit 474e8c4

Please sign in to comment.