데이터 통합사용 가능한 커넥터Microsoft Access

본 번역은 검증되지 않았습니다. AIP를 통해 영문원문으로부터 번역되었습니다.

Microsoft Access

소스 탐색과 배치 동기화로 Access 테이블을 읽거나, 코드에서 데이터베이스를 다운로드하고 파싱할 수 있습니다. Python 파이프라인에서는 Azure Files의 전체 데이터베이스 파일을 교체하여 행 하나를 업데이트할 수도 있습니다. 테이블 내보내기는 사용할 수 없습니다.

Microsoft Access 커넥터는 Microsoft Access용 Palantir 제공 드라이버입니다.

새 Microsoft Access 소스를 생성하려면 Palantir 제공 드라이버의 표준 설정 절차를 따른 다음, 아래 섹션에서 Microsoft Access 전용 구성 및 네트워킹을 확인하세요. 전체 속성 참조는 공식 Microsoft Access 드라이버 관련 문서 ↗를 참조하세요.

지원 기능

기능상태
탐색🟢 정식 출시
배치 동기화🟢 정식 출시
점진적🟢 정식 출시

구성

아래 속성은 필수이거나 권장됩니다.

속성필수 여부설명기본값
ConnectionType ↗필수Microsoft Access 파일을 저장하고 검색하는 데 사용되는 파일 스토리지 서비스, 서버 또는 파일 액세스 프로토콜을 지정합니다.Azure Files
DataSource ↗필수MS Access 데이터베이스 파일의 전체 경로 및 이름입니다.—

데이터베이스 파일에 연결

Microsoft Access는 파일 기반입니다. ConnectionType은 스토리지 서비스 또는 파일 액세스 프로토콜을 선택하고, DataSource는 .mdb 또는 .accdb 파일을 식별합니다. 스토리지 제공자에 필요한 속성과 DataSource 형식은 Microsoft Access 연결 가이드 ↗를 따르세요.

이 페이지의 코드 내 소스 사용 예제는 Azure Files 기반 Access 소스를 사용합니다. 가져온 소스를 통해 데이터베이스를 다운로드하고 코드 런타임에서 파일을 파싱하며, 코드에 Access API 또는 JDBC 연결을 노출하지 않습니다.

Azure 파일 공유 구성

다음 소스 속성을 설정하세요.

속성값
ConnectionTypeAzure Files
DataSourceazurefile://<file-share>/<path>/<database>.accdb
AzureStorageAccountAzure 스토리지 계정 이름

이 예제에서 사용하는 AccessKey 구성의 경우, AuthScheme을 AccessKey로 설정하고 스토리지 계정 키를 암호화된 AzureAccessKey 속성으로 추가하세요.

소스가 <storage-account>.file.core.windows.net:443에 연결할 수 있도록 허용하는 이그레스 정책을 추가하세요.

데이터베이스 테이블 읽기

소스 탐색을 사용하여 데이터베이스의 테이블을 미리 보고, 수집하려는 각 테이블에 대해 배치 동기화를 생성하세요.

코드에서 데이터베이스 테이블 읽기

아래 예제는 Azure Files 기반 데이터베이스 하나를 다운로드하고 Departments 및 Employees 테이블을 읽습니다. 예제를 사용하기 전에 다음을 수행하세요.

  1. Foundry 워커에서 실행되도록 Access 소스를 구성하세요. 에이전트 워커 소스는 코드로 가져올 수 없습니다.
  2. 소스를 Code Repositories로 가져올 수 있도록 허용하세요. Python 파이프라인의 경우 외부 변환 소스 가져오기 지침을 따르세요. Function의 경우 소스의 내보내기 제어도 구성하고 외부 API 액세스 지침을 따르세요.
  3. Access 소스를 리포지토리로 가져오세요. TypeScript v1에서는 모든 MicrosoftAccessSource를 가져온 소스의 생성된 TypeScript 식별자로 바꾸세요. 예제를 functions-typescript/src/index.ts에 배치하거나, 별도 모듈을 사용하는 경우 해당 파일에서 MicrosoftAccessReadFunctions를 내보내세요. TypeScript v2에서는 SOURCE_API_NAME에 소스의 코드 API 이름을 사용하고, SOURCE_RID에 해당 RID를 사용하세요.
  4. 선택한 예제의 모든 스토리지 계정, 파일 공유, 데이터베이스 경로 및 결과물 플레이스홀더를 바꾸세요.
  5. 아래에 표시된 런타임 종속성을 추가하세요.
런타임추가 종속성결과 및 리소스 제한
Python 파이프라인pandas>=1.5,<3, requests==2.34.2 및 mdbtools==1.0.1데이터베이스를 1 MiB 청크 단위로 스트리밍하고, HTTP 및 mdb-export 명령에 120-second 시간 제한을 적용하며, 데이터셋 스냅샷 하나를 작성합니다.
Python Functionrequests==2.34.2 및 mdbtools==1.0.1동일한 스트리밍 및 시간 제한을 사용한 후, CSV 값은 스트링으로, 빈 필드는 null로 표현한 JSON을 반환합니다.
TypeScript v1 Functionmdb-reader@^3.2.0전체 데이터베이스를 메모리에 로드하고 명시적인 요청 시간 제한 없이 JSON을 반환합니다.
TypeScript v2 Functionmdb-reader@^3.2.0전체 데이터베이스를 메모리에 로드하고 명시적인 요청 시간 제한 없이 JSON을 반환합니다.

각 예제는 Azure Files GET을 한 번 수행합니다. 이 예제에는 재시도 요청이 포함되어 있지 않으며 데이터베이스 크기 제한을 적용하지 않습니다. 또한 Access 파일을 업로드하거나 교체하거나 변경하지 않습니다.

Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 """READ-only Microsoft Access table materialization through Azure Files.""" import base64 import hashlib import hmac import io import os import subprocess import tempfile from datetime import datetime, timezone from urllib.parse import quote import pandas as pd import requests from transforms.api import Output, transform from transforms.external.systems import ResolvedSource, Source, external_systems SOURCE_RID = "ri.magritte..source.<MICROSOFT_ACCESS_SOURCE_RID>" STORAGE_ACCOUNT = "<AZURE_STORAGE_ACCOUNT>" SHARE_NAME = "<AZURE_FILE_SHARE>" FILE_PATH = "<PATH_TO_ACCESS_DATABASE.accdb>" OUTPUT_PATH = ( "/<NAMESPACE>/<PROJECT>/" "<FOLDER>/<OUTPUT_DATASET>" ) AZURE_API_VERSION = "2023-11-03" TABLE_NAMES = ("Departments", "Employees") @external_systems(access=Source(SOURCE_RID)) @transform.using(output=Output(OUTPUT_PATH)) def read_access_tables(access: ResolvedSource, output) -> None: """Download, parse, and materialize Departments and Employees.""" access_key = access.get_secret("AzureAccessKey") x_ms_date = datetime.now(timezone.utc).strftime("%a, %d %b %Y %H:%M:%S GMT") signed_headers = { "x-ms-date": x_ms_date, "x-ms-version": AZURE_API_VERSION, } canonicalized_headers = "".join( f"{name.lower()}:{' '.join(str(value).strip().split())}\n" for name, value in sorted(signed_headers.items(), key=lambda item: item[0].lower()) ) canonicalized_resource = f"/{STORAGE_ACCOUNT}/{SHARE_NAME}/{FILE_PATH}" standard_headers = ["GET", "", "", "", "", "", "", "", "", "", "", ""] string_to_sign = "\n".join(standard_headers) + "\n" + canonicalized_headers + canonicalized_resource digest = hmac.new( base64.b64decode(access_key), string_to_sign.encode("utf-8"), hashlib.sha256, ).digest() signature = base64.b64encode(digest).decode("ascii") headers = dict(signed_headers) headers["Authorization"] = f"SharedKey {STORAGE_ACCOUNT}:{signature}" encoded_path = quote(FILE_PATH, safe="/") url = f"https://{STORAGE_ACCOUNT}.file.core.windows.net/{SHARE_NAME}/{encoded_path}" proxy_uri = access.get_https_proxy_uri() proxies = {"http": proxy_uri, "https": proxy_uri} if proxy_uri else None with tempfile.TemporaryDirectory() as directory: database_path = os.path.join(directory, "testdb.accdb") response = requests.request( "GET", url, params=None, headers=headers, data=None, proxies=proxies, timeout=120, stream=True, ) response.raise_for_status() with response: with open(database_path, "wb") as output_file: for chunk in response.iter_content(chunk_size=1024 * 1024): if chunk: output_file.write(chunk) frames = [] for table_name in TABLE_NAMES: completed = subprocess.run( ["mdb-export", database_path, table_name], check=True, capture_output=True, text=True, timeout=120, ) frame = pd.read_csv(io.StringIO(completed.stdout)) frame.insert(0, "source_table", table_name) frames.append(frame) output.write_table(pd.concat(frames, ignore_index=True, sort=False))
Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 """READ-only Microsoft Access table retrieval through Azure Files.""" import base64 import csv import hashlib import hmac import io import json import os import subprocess import tempfile from datetime import datetime, timezone from urllib.parse import quote import requests from functions.api import function from functions.sources import get_source SOURCE_RID = "ri.magritte..source.<MICROSOFT_ACCESS_SOURCE_RID>" STORAGE_ACCOUNT = "<AZURE_STORAGE_ACCOUNT>" SHARE_NAME = "<AZURE_FILE_SHARE>" FILE_PATH = "<PATH_TO_ACCESS_DATABASE.accdb>" AZURE_API_VERSION = "2023-11-03" def _read_table(database_path: str, table_name: str) -> list[dict[str, str | None]]: completed = subprocess.run( ["mdb-export", database_path, table_name], check=True, capture_output=True, text=True, timeout=120, ) records: list[dict[str, str | None]] = [] for row in csv.DictReader(io.StringIO(completed.stdout)): records.append({key: value if value != "" else None for key, value in row.items()}) return records @function(sources=[SOURCE_RID]) def read_access_tables() -> str: """Return Departments and Employees as one JSON object on demand.""" source = get_source(rid=SOURCE_RID) access_key = source.get_secret("AzureAccessKey") x_ms_date = datetime.now(timezone.utc).strftime("%a, %d %b %Y %H:%M:%S GMT") signed_headers = { "x-ms-date": x_ms_date, "x-ms-version": AZURE_API_VERSION, } canonicalized_headers = "".join( f"{name.lower()}:{' '.join(str(value).strip().split())}\n" for name, value in sorted(signed_headers.items(), key=lambda item: item[0].lower()) ) canonicalized_resource = f"/{STORAGE_ACCOUNT}/{SHARE_NAME}/{FILE_PATH}" standard_headers = ["GET", "", "", "", "", "", "", "", "", "", "", ""] string_to_sign = "\n".join(standard_headers) + "\n" + canonicalized_headers + canonicalized_resource digest = hmac.new( base64.b64decode(access_key), string_to_sign.encode("utf-8"), hashlib.sha256, ).digest() headers = { **signed_headers, "Authorization": ( f"SharedKey {STORAGE_ACCOUNT}:" f"{base64.b64encode(digest).decode('ascii')}" ), } url = ( f"https://{STORAGE_ACCOUNT}.file.core.windows.net/" f"{SHARE_NAME}/{quote(FILE_PATH, safe='/')}" ) proxy_uri = source.get_https_proxy_uri() proxies = {"http": proxy_uri, "https": proxy_uri} if proxy_uri else None response = requests.request( "GET", url, headers=headers, proxies=proxies, timeout=120, stream=True, ) response.raise_for_status() with response: with tempfile.TemporaryDirectory() as directory: database_path = os.path.join(directory, "testdb.accdb") with open(database_path, "wb") as output_file: for chunk in response.iter_content(chunk_size=1024 * 1024): if chunk: output_file.write(chunk) payload = { "Departments": _read_table(database_path, "Departments"), "Employees": _read_table(database_path, "Employees"), } return json.dumps(payload, default=str)
Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 import { createHmac } from "crypto"; import { Buffer } from "buffer"; import { ExternalSystems, Function, UserFacingError } from "@foundry/functions-api"; import { MicrosoftAccessSource } from "@foundry/external-systems/sources"; import MDBReader from "mdb-reader"; const STORAGE_ACCOUNT = "<AZURE_STORAGE_ACCOUNT>"; const SHARE_NAME = "<AZURE_FILE_SHARE>"; const SOURCE_FILE_PATH = "<PATH_TO_ACCESS_DATABASE.accdb>"; const AZURE_API_VERSION = "2023-11-03"; export class MicrosoftAccessReadFunctions { @ExternalSystems({ sources: [MicrosoftAccessSource] }) @Function() public async readAccessTablesTsV1(): Promise<string> { const accessKey = MicrosoftAccessSource.getSecret("AzureAccessKey"); const xMsDate = new Date().toUTCString(); const signedHeaders: Record<string, string> = { "x-ms-date": xMsDate, "x-ms-version": AZURE_API_VERSION, }; const canonicalizedHeaders = Object.entries(signedHeaders) .sort(([left], [right]) => left.toLowerCase().localeCompare(right.toLowerCase())) .map(([name, value]) => `${name.toLowerCase()}:${value.trim().replace(/\s+/g, " ")}\n`) .join(""); const canonicalizedResource = `/${STORAGE_ACCOUNT}/${SHARE_NAME}/${SOURCE_FILE_PATH}`; const standardHeaders = ["GET", "", "", "", "", "", "", "", "", "", "", ""]; const stringToSign = `${standardHeaders.join("\n")}\n${canonicalizedHeaders}${canonicalizedResource}`; const signature = createHmac("sha256", Buffer.from(accessKey, "base64")) .update(stringToSign, "utf8") .digest("base64"); const authorization = `SharedKey ${STORAGE_ACCOUNT}:${signature}`; const encodedPath = SOURCE_FILE_PATH.split("/").map(encodeURIComponent).join("/"); const fileUrl = `https://${STORAGE_ACCOUNT}.file.core.windows.net/${SHARE_NAME}/${encodedPath}`; const response = await MicrosoftAccessSource.fetch(fileUrl, { method: "GET", headers: { ...signedHeaders, Authorization: authorization, }, }); if (!response.ok) { const body = await response.text(); throw new UserFacingError( `Azure Files GET ${SOURCE_FILE_PATH} failed (${response.status}): ${body.slice(0, 500)}`, ); } const reader = new MDBReader(Buffer.from(await response.arrayBuffer())); const tables = { Departments: reader.getTable("Departments").getData(), Employees: reader.getTable("Employees").getData(), }; return JSON.stringify(tables, (_key, item: unknown) => { if (typeof item === "bigint") { return item.toString(); } if (Buffer.isBuffer(item)) { return item.toString("base64"); } return item; }); } }
Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 import { createHmac } from "node:crypto"; import { Buffer } from "node:buffer"; import MDBReader from "mdb-reader"; import { getFetch, getSource } from "@palantir/functions-sources"; import { UserFacingError } from "@osdk/functions"; const SOURCE_RID = "ri.magritte..source.<MICROSOFT_ACCESS_SOURCE_RID>"; const SOURCE_API_NAME = "<MICROSOFT_ACCESS_SOURCE_API_NAME>"; const SOURCE_FILE_PATH = "<PATH_TO_ACCESS_DATABASE.accdb>"; const STORAGE_ACCOUNT = "<AZURE_STORAGE_ACCOUNT>"; const SHARE_NAME = "<AZURE_FILE_SHARE>"; const AZURE_API_VERSION = "2023-11-03"; export const config = { sources: [SOURCE_API_NAME], }; /** Downloads the Access file and returns Departments and Employees as JSON. */ export default async function readAccessTablesTsV2(): Promise<string> { const source = await getSource({ rid: SOURCE_RID }); const accessKey = source.secrets.AzureAccessKey; if (!accessKey) throw new UserFacingError("Microsoft Access source is missing AzureAccessKey."); const fetchFromSource = await getFetch(source); const xMsDate = new Date().toUTCString(); const signedHeaders: Record<string, string> = { "x-ms-date": xMsDate, "x-ms-version": AZURE_API_VERSION, }; const canonicalizedHeaders = Object.entries(signedHeaders) .sort(([left], [right]) => left.toLowerCase().localeCompare(right.toLowerCase())) .map(([name, value]) => `${name.toLowerCase()}:${value.trim().replace(/\s+/g, " ")}\n`) .join(""); const canonicalizedResource = `/${STORAGE_ACCOUNT}/${SHARE_NAME}/${SOURCE_FILE_PATH}`; const standardHeaders = ["GET", "", "", "", "", "", "", "", "", "", "", ""]; const stringToSign = `${standardHeaders.join("\n")}\n${canonicalizedHeaders}${canonicalizedResource}`; const signature = createHmac("sha256", Buffer.from(accessKey, "base64")) .update(stringToSign, "utf8") .digest("base64"); const authorization = `SharedKey ${STORAGE_ACCOUNT}:${signature}`; const encodedPath = SOURCE_FILE_PATH.split("/").map(encodeURIComponent).join("/"); const fileUrl = `https://${STORAGE_ACCOUNT}.file.core.windows.net/${SHARE_NAME}/${encodedPath}`; const response = await fetchFromSource(fileUrl, { method: "GET", headers: { ...signedHeaders, Authorization: authorization, }, }); if (!response.ok) { const body = await response.text(); throw new UserFacingError( `Azure Files GET ${SOURCE_FILE_PATH} failed (${response.status}): ${body.slice(0, 500)}`, ); } const reader = new MDBReader(Buffer.from(await response.arrayBuffer())); const tables = { Departments: reader.getTable("Departments").getData(), Employees: reader.getTable("Employees").getData(), }; return JSON.stringify(tables, (_key, item: unknown) => { if (typeof item === "bigint") return item.toString(); if (Buffer.isBuffer(item)) return item.toString("base64"); return item; }); }

Python 파이프라인에서 행 하나 업데이트

다음 예제는 Azure Files 기반 .accdb 파일에서 조건에 따라 행 하나를 변경합니다. 데이터베이스를 다운로드하고 UCanAccess로 업데이트를 적용한 다음, 고유한 이름의 후보 파일을 업로드합니다. 그런 다음 대상에 대한 임대를 획득하고 대상의 ETag가 변경되지 않았는지 확인합니다. 마지막으로 후보 파일의 이름을 변경하여 대상 파일을 덮어씁니다.

이 워크플로는 전체 .accdb 파일을 교체합니다. 운영 데이터에 사용하기 전에 폐기 가능한 복사본에서 테스트하세요. 매크로, 연결된 테이블, 암호화된 데이터베이스, 대용량 파일 및 더 광범위한 동시 쓰기 시나리오와의 호환성은 검증되지 않았습니다.

이 예제를 사용하기 전에 다음을 수행하세요.

  1. 코드에서 데이터베이스 테이블 읽기의 Python 파이프라인 소스 가져오기 단계를 완료하세요.
  2. OpenJDK 17, JPype1==1.7.1, JayDeBeApi==1.2.3, requests, pandas, transforms, transforms-external-systems를 설치하세요.
  3. ucanaccess-5.1.8.jar, jackcess-5.1.7.jar, hsqldb-2.7.4.jar를 myproject/lib에 추가하고, lib/*.jar를 myproject와 함께 패키징하세요.
  4. 소스, Azure Files, 결과물 데이터셋 및 조건부 행 플레이스홀더를 바꾸세요. 소스는 계정 키를 암호화된 AzureAccessKey 속성으로 노출해야 합니다.
Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 import base64 import hashlib import hmac import os import tempfile import uuid from datetime import datetime, timezone from pathlib import Path from urllib.parse import quote import jaydebeapi import pandas as pd import requests from transforms.api import Output, transform from transforms.external.systems import ResolvedSource, Source, external_systems SOURCE_RID = "ri.magritte..source.<MICROSOFT_ACCESS_SOURCE_RID>" STORAGE_ACCOUNT = "<AZURE_STORAGE_ACCOUNT>" SHARE_NAME = "<AZURE_FILE_SHARE>" FILE_PATH = "<PATH_TO_ACCESS_DATABASE.accdb>" OUTPUT_PATH = "/<NAMESPACE>/<PROJECT>/<FOLDER>/<OUTPUT_DATASET>" AZURE_API_VERSION = "2023-11-03" MAX_RANGE_BYTES = 4 * 1024 * 1024 EMPLOYEE_ID = 1001 EMPLOYEE_NAME = "Example Employee" EXPECTED_OLD_DEPT_ID = 10 NEW_DEPT_ID = 20 def _azure_request(access_key, proxies, method, path, *, query=None, headers=None, data=None): request_query = dict(query or {}) request_headers = {name.lower(): str(value) for name, value in (headers or {}).items()} request_headers["x-ms-date"] = datetime.now(timezone.utc).strftime( "%a, %d %b %Y %H:%M:%S GMT" ) request_headers["x-ms-version"] = AZURE_API_VERSION standard_headers = [method] + [ request_headers.get(name, "") for name in ( "content-encoding", "content-language", "content-length", "content-md5", "content-type", "date", "if-modified-since", "if-match", "if-none-match", "if-unmodified-since", "range", ) ] if standard_headers[3] == "0": standard_headers[3] = "" canonicalized_headers = "".join( f"{name}:{' '.join(value.strip().split())}\n" for name, value in sorted(request_headers.items()) if name.startswith("x-ms-") ) canonicalized_resource = f"/{STORAGE_ACCOUNT}/{SHARE_NAME}/{path}" for name, value in sorted(request_query.items(), key=lambda item: item[0].lower()): canonicalized_resource += f"\n{name.lower()}:{value}" string_to_sign = "\n".join(standard_headers) + "\n" + canonicalized_headers + canonicalized_resource signature = base64.b64encode( hmac.new(base64.b64decode(access_key), string_to_sign.encode("utf-8"), hashlib.sha256).digest() ).decode("ascii") request_headers["Authorization"] = f"SharedKey {STORAGE_ACCOUNT}:{signature}" return requests.request( method, f"https://{STORAGE_ACCOUNT}.file.core.windows.net/{SHARE_NAME}/{quote(path, safe='/')}", params=request_query or None, headers=request_headers, data=data, proxies=proxies, timeout=120, ) @external_systems(access=Source(SOURCE_RID)) @transform.using(output=Output(OUTPUT_PATH)) def write_access_row(access: ResolvedSource, output) -> None: access_key = access.get_secret("Azure" + "Access" + "Key") proxy_uri = access.get_https_proxy_uri() proxies = {"http": proxy_uri, "https": proxy_uri} if proxy_uri else None with _azure_request(access_key, proxies, "GET", FILE_PATH) as response: if response.status_code == 404: output.write_table(pd.DataFrame([{"status": "skipped_target_missing", "affected_rows": 0}])) return response.raise_for_status() original_bytes = response.content original_etag = response.headers.get("ETag") if not original_bytes or not original_etag: raise RuntimeError("The target download was empty or did not return an ETag") with tempfile.TemporaryDirectory() as directory: database_path = os.path.join(directory, "working.accdb") with open(database_path, "wb") as database_file: database_file.write(original_bytes) library_directory = Path(__file__).resolve().parents[1] / "lib" connection = jaydebeapi.connect( "net.ucanaccess.jdbc.UcanaccessDriver", f"jdbc:ucanaccess://{database_path}", [], [str(library_directory / name) for name in ( "ucanaccess-5.1.8.jar", "jackcess-5.1.7.jar", "hsqldb-2.7.4.jar", )], ) cursor = None try: cursor = connection.cursor() cursor.execute( "UPDATE Employees SET DeptId = ? WHERE Id = ? AND Name = ? AND DeptId = ?", [NEW_DEPT_ID, EMPLOYEE_ID, EMPLOYEE_NAME, EXPECTED_OLD_DEPT_ID], ) affected_rows = cursor.rowcount if affected_rows != 1: connection.rollback() raise RuntimeError(f"Expected one updated row, received {affected_rows}") connection.commit() finally: if cursor is not None: cursor.close() connection.close() with open(database_path, "rb") as database_file: candidate_bytes = database_file.read() candidate_path = f"{FILE_PATH}.candidate-{uuid.uuid4().hex}" lease_id = None replaced = False try: with _azure_request( access_key, proxies, "PUT", candidate_path, headers={"Content-Length": "0", "x-ms-content-length": str(len(candidate_bytes)), "x-ms-type": "file"}, data=b"", ) as response: response.raise_for_status() for start in range(0, len(candidate_bytes), MAX_RANGE_BYTES): chunk = candidate_bytes[start : start + MAX_RANGE_BYTES] with _azure_request( access_key, proxies, "PUT", candidate_path, query={"comp": "range"}, headers={ "Content-Length": str(len(chunk)), "x-ms-range": f"bytes={start}-{start + len(chunk) - 1}", "x-ms-write": "update", }, data=chunk, ) as response: response.raise_for_status() with _azure_request( access_key, proxies, "PUT", FILE_PATH, query={"comp": "lease"}, headers={"Content-Length": "0", "x-ms-lease-action": "acquire", "x-ms-lease-duration": "-1"}, data=b"", ) as response: response.raise_for_status() lease_id = response.headers.get("x-ms-lease-id") lease_etag = response.headers.get("ETag") if not lease_id or lease_etag != original_etag: raise RuntimeError("The destination changed before replacement") with _azure_request( access_key, proxies, "PUT", FILE_PATH, query={"comp": "rename"}, headers={ "Content-Length": "0", "x-ms-file-rename-source": ( f"https://{STORAGE_ACCOUNT}.file.core.windows.net/" f"{SHARE_NAME}/{quote(candidate_path, safe='/')}" ), "x-ms-file-rename-replace-if-exists": "true", "x-ms-destination-lease-id": lease_id, }, data=b"", ) as response: response.raise_for_status() replaced = True finally: if lease_id is not None: with _azure_request( access_key, proxies, "PUT", FILE_PATH, query={"comp": "lease"}, headers={"Content-Length": "0", "x-ms-lease-action": "release", "x-ms-lease-id": lease_id}, data=b"", ) as response: response.raise_for_status() if not replaced: _azure_request(access_key, proxies, "DELETE", candidate_path).close() output.write_table(pd.DataFrame([{"status": "updated", "affected_rows": affected_rows}]))

코드 예제 범위

  • 코드 내 소스 사용 예제는 AuthScheme=AccessKey로 구성된 Azure Files 소스만 지원합니다.
  • WRITE 예제는 Python 파이프라인을 사용합니다. 이 예제는 Python 또는 TypeScript Functions의 WRITE 지원을 보장하지 않습니다.