ckanext-xloader 2.2.0__tar.gz → 2.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. {ckanext_xloader-2.2.0/ckanext_xloader.egg-info → ckanext_xloader-2.3.0}/PKG-INFO +1 -1
  2. {ckanext_xloader-2.2.0 → ckanext_xloader-2.3.0}/ckanext/xloader/config_declaration.yaml +10 -0
  3. {ckanext_xloader-2.2.0 → ckanext_xloader-2.3.0}/ckanext/xloader/jobs.py +41 -44
  4. {ckanext_xloader-2.2.0 → ckanext_xloader-2.3.0}/ckanext/xloader/loader.py +107 -45
  5. {ckanext_xloader-2.2.0 → ckanext_xloader-2.3.0}/ckanext/xloader/plugin.py +20 -1
  6. ckanext_xloader-2.3.0/ckanext/xloader/tests/test_chunks.py +169 -0
  7. {ckanext_xloader-2.2.0 → ckanext_xloader-2.3.0}/ckanext/xloader/tests/test_jobs.py +5 -3
  8. {ckanext_xloader-2.2.0 → ckanext_xloader-2.3.0/ckanext_xloader.egg-info}/PKG-INFO +1 -1
  9. {ckanext_xloader-2.2.0 → ckanext_xloader-2.3.0}/ckanext_xloader.egg-info/SOURCES.txt +1 -0
  10. {ckanext_xloader-2.2.0 → ckanext_xloader-2.3.0}/pyproject.toml +1 -1
  11. {ckanext_xloader-2.2.0 → ckanext_xloader-2.3.0}/CHANGELOG +0 -0
  12. {ckanext_xloader-2.2.0 → ckanext_xloader-2.3.0}/LICENSE +0 -0
  13. {ckanext_xloader-2.2.0 → ckanext_xloader-2.3.0}/MANIFEST.in +0 -0
  14. {ckanext_xloader-2.2.0 → ckanext_xloader-2.3.0}/README.md +0 -0
  15. {ckanext_xloader-2.2.0 → ckanext_xloader-2.3.0}/ckanext/__init__.py +0 -0
  16. {ckanext_xloader-2.2.0 → ckanext_xloader-2.3.0}/ckanext/xloader/__init__.py +0 -0
  17. {ckanext_xloader-2.2.0 → ckanext_xloader-2.3.0}/ckanext/xloader/action.py +0 -0
  18. {ckanext_xloader-2.2.0 → ckanext_xloader-2.3.0}/ckanext/xloader/auth.py +0 -0
  19. {ckanext_xloader-2.2.0 → ckanext_xloader-2.3.0}/ckanext/xloader/cli.py +0 -0
  20. {ckanext_xloader-2.2.0 → ckanext_xloader-2.3.0}/ckanext/xloader/command.py +0 -0
  21. {ckanext_xloader-2.2.0 → ckanext_xloader-2.3.0}/ckanext/xloader/db.py +0 -0
  22. {ckanext_xloader-2.2.0 → ckanext_xloader-2.3.0}/ckanext/xloader/helpers.py +0 -0
  23. {ckanext_xloader-2.2.0 → ckanext_xloader-2.3.0}/ckanext/xloader/interfaces.py +0 -0
  24. {ckanext_xloader-2.2.0 → ckanext_xloader-2.3.0}/ckanext/xloader/job_exceptions.py +0 -0
  25. {ckanext_xloader-2.2.0 → ckanext_xloader-2.3.0}/ckanext/xloader/parser.py +0 -0
  26. {ckanext_xloader-2.2.0 → ckanext_xloader-2.3.0}/ckanext/xloader/schema.py +0 -0
  27. {ckanext_xloader-2.2.0 → ckanext_xloader-2.3.0}/ckanext/xloader/templates/datastore/snippets/dictionary_form.html +0 -0
  28. {ckanext_xloader-2.2.0 → ckanext_xloader-2.3.0}/ckanext/xloader/templates/package/resource_edit_base.html +0 -0
  29. {ckanext_xloader-2.2.0 → ckanext_xloader-2.3.0}/ckanext/xloader/templates/package/resource_read.html +0 -0
  30. {ckanext_xloader-2.2.0 → ckanext_xloader-2.3.0}/ckanext/xloader/templates/package/snippets/resource_info.html +0 -0
  31. {ckanext_xloader-2.2.0 → ckanext_xloader-2.3.0}/ckanext/xloader/templates/package/snippets/resource_item.html +0 -0
  32. {ckanext_xloader-2.2.0 → ckanext_xloader-2.3.0}/ckanext/xloader/templates/package/snippets/resources.html +0 -0
  33. {ckanext_xloader-2.2.0 → ckanext_xloader-2.3.0}/ckanext/xloader/templates/xloader/confirm_datastore_delete.html +0 -0
  34. {ckanext_xloader-2.2.0 → ckanext_xloader-2.3.0}/ckanext/xloader/templates/xloader/resource_data.html +0 -0
  35. {ckanext_xloader-2.2.0 → ckanext_xloader-2.3.0}/ckanext/xloader/tests/__init__.py +0 -0
  36. {ckanext_xloader-2.2.0 → ckanext_xloader-2.3.0}/ckanext/xloader/tests/ckan_setup.py +0 -0
  37. {ckanext_xloader-2.2.0 → ckanext_xloader-2.3.0}/ckanext/xloader/tests/fixtures.py +0 -0
  38. {ckanext_xloader-2.2.0 → ckanext_xloader-2.3.0}/ckanext/xloader/tests/test_action.py +0 -0
  39. {ckanext_xloader-2.2.0 → ckanext_xloader-2.3.0}/ckanext/xloader/tests/test_loader.py +0 -0
  40. {ckanext_xloader-2.2.0 → ckanext_xloader-2.3.0}/ckanext/xloader/tests/test_parser.py +0 -0
  41. {ckanext_xloader-2.2.0 → ckanext_xloader-2.3.0}/ckanext/xloader/tests/test_plugin.py +0 -0
  42. {ckanext_xloader-2.2.0 → ckanext_xloader-2.3.0}/ckanext/xloader/tests/test_utils.py +0 -0
  43. {ckanext_xloader-2.2.0 → ckanext_xloader-2.3.0}/ckanext/xloader/utils.py +0 -0
  44. {ckanext_xloader-2.2.0 → ckanext_xloader-2.3.0}/ckanext/xloader/views.py +0 -0
  45. {ckanext_xloader-2.2.0 → ckanext_xloader-2.3.0}/ckanext/xloader/webassets/css/xloader.css +0 -0
  46. {ckanext_xloader-2.2.0 → ckanext_xloader-2.3.0}/ckanext/xloader/webassets/webassets.yml +0 -0
  47. {ckanext_xloader-2.2.0 → ckanext_xloader-2.3.0}/ckanext_xloader.egg-info/dependency_links.txt +0 -0
  48. {ckanext_xloader-2.2.0 → ckanext_xloader-2.3.0}/ckanext_xloader.egg-info/entry_points.txt +0 -0
  49. {ckanext_xloader-2.2.0 → ckanext_xloader-2.3.0}/ckanext_xloader.egg-info/requires.txt +0 -0
  50. {ckanext_xloader-2.2.0 → ckanext_xloader-2.3.0}/ckanext_xloader.egg-info/top_level.txt +0 -0
  51. {ckanext_xloader-2.2.0 → ckanext_xloader-2.3.0}/dev-requirements.txt +0 -0
  52. {ckanext_xloader-2.2.0 → ckanext_xloader-2.3.0}/requirements.txt +0 -0
  53. {ckanext_xloader-2.2.0 → ckanext_xloader-2.3.0}/setup.cfg +0 -0
  54. {ckanext_xloader-2.2.0 → ckanext_xloader-2.3.0}/setup.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ckanext-xloader
3
- Version: 2.2.0
3
+ Version: 2.3.0
4
4
  Summary: Express Loader - quickly load data into CKAN DataStore
5
5
  Author: David Read (davidread), Patricio Del Boca (pdelboca)
6
6
  Author-email: ThrawnCA <carl.antuar@smartservice.qld.gov.au>, "Jesse Vickery (JVickery-TBS)" <jesse.vickery@tbs-sct.gc.ca>, "Adrià Mercader (amercader)" <amercadero@gmail.com>, "Brett Jones (kowh-ai)" <datashades@linkdigital.com.au>, "William Dutton (duttonw)" <william.dutton@qld.gov.au>
@@ -206,3 +206,13 @@ groups:
206
206
  like database deadlocks or network timeouts. Set to 0 to disable retries.
207
207
  type: int
208
208
  required: false
209
+ - key: ckanext.xloader.copy_chunk_size
210
+ default: 1073741824
211
+ example: 536870912
212
+ description: |
213
+ Maximum size in bytes for each chunk when processing files.
214
+ Files are split into chunks to prevent memory exhaustion and
215
+ system freezing. Default is 1GB (1073741824 bytes). Smaller values
216
+ use less memory but create more chunks.
217
+ type: int
218
+ required: false
@@ -29,50 +29,46 @@ from ckan.lib.api_token import get_user_from_token
29
29
 
30
30
  log = logging.getLogger(__name__)
31
31
 
32
- SSL_VERIFY = asbool(config.get('ckanext.xloader.ssl_verify', True))
33
- if not SSL_VERIFY:
34
- requests.packages.urllib3.disable_warnings()
35
-
36
- MAX_CONTENT_LENGTH = int(config.get('ckanext.xloader.max_content_length') or 1e9)
37
- # Don't try Tabulator load on large files
38
- MAX_TYPE_GUESSING_LENGTH = int(config.get('ckanext.xloader.max_type_guessing_length') or MAX_CONTENT_LENGTH / 10)
39
- MAX_EXCERPT_LINES = int(config.get('ckanext.xloader.max_excerpt_lines') or 0)
40
32
  CHUNK_SIZE = 16 * 1024 # 16kb
41
33
  DOWNLOAD_TIMEOUT = 30
42
34
 
43
- MAX_RETRIES = int(config.get('ckanext.xloader.max_retries', 1))
44
35
  RETRYABLE_ERRORS = (
45
36
  errors.DeadlockDetected,
46
37
  errors.LockNotAvailable,
47
38
  errors.ObjectInUse,
48
39
  HTTPError,
49
- XLoaderTimeoutError
40
+ XLoaderTimeoutError
50
41
  )
51
- # Retries can only occur in cases where the datastore entry exists,
52
- # so use the standard timeout
53
- RETRIED_JOB_TIMEOUT = config.get('ckanext.xloader.job_timeout', '3600')
54
- APITOKEN_HEADER_NAME = config.get('apitoken_header_name', 'Authorization')
42
+
43
+ # Variables that are set from config values and must be available to all jobs
44
+ ssl_verify = None
45
+ max_content_length = None
46
+ max_type_guessing_length = None
47
+ max_excerpt_lines = None
48
+ max_retries = None
49
+ retried_job_timeout = None
50
+ apitoken_header_name = None
55
51
 
56
52
 
57
53
  def is_retryable_error(error):
58
54
  """
59
55
  Determine if an error should trigger a retry attempt.
60
-
56
+
61
57
  Checks if the error is a temporary/transient condition that might
62
58
  succeed on retry. Returns True for retryable HTTP status codes and
63
59
  other temporary errors.
64
-
60
+
65
61
  Retryable HTTP status codes:
66
62
  - 408 Request Timeout
67
- - 429 Too Many Requests
63
+ - 429 Too Many Requests
68
64
  - 500 Internal Server Error
69
- - 502 Bad Gateway
65
+ - 502 Bad Gateway
70
66
  - 503 Service Unavailable
71
67
  - 504 Gateway Timeout
72
68
  - 507 Insufficient Storage
73
69
  - 522 Connection Timed Out (Cloudflare)
74
70
  - 524 A Timeout Occurred (Cloudflare)
75
-
71
+
76
72
  :param error: Exception object to check
77
73
  :type error: Exception
78
74
  :return: True if error should be retried, False otherwise
@@ -163,11 +159,11 @@ def xloader_data_into_datastore(input):
163
159
  def handle_retryable_error(e, input, job_id, job_dict, logger, error_state):
164
160
  """
165
161
  Handle retryable errors by attempting to retry the job or marking it as failed.
166
-
162
+
167
163
  Checks if the error is retryable (database deadlocks, HTTP timeouts, etc.) and
168
164
  within the retry limit. If so, enqueues a new job attempt. Otherwise, marks
169
165
  the job as errored.
170
-
166
+
171
167
  :param e: The exception that occurred
172
168
  :type e: Exception
173
169
  :param input: Job input data containing metadata and API key
@@ -180,13 +176,13 @@ def handle_retryable_error(e, input, job_id, job_dict, logger, error_state):
180
176
  :type logger: logging.Logger
181
177
  :param error_state: Mutable dict to track error state {'errored': bool}
182
178
  :type error_state: dict
183
-
179
+
184
180
  :returns: True if job was retried, None otherwise
185
181
  :rtype: bool or None
186
182
  """
187
183
  if isinstance(e, RETRYABLE_ERRORS) and is_retryable_error(e):
188
184
  tries = job_dict['metadata'].get('tries', 0)
189
- if tries < MAX_RETRIES:
185
+ if tries < max_retries:
190
186
  tries = tries + 1
191
187
  log.info("Job %s failed due to temporary error [%s], retrying", job_id, e)
192
188
  logger.info("Job failed due to temporary error [%s], retrying", e)
@@ -197,7 +193,7 @@ def handle_retryable_error(e, input, job_id, job_dict, logger, error_state):
197
193
  [input],
198
194
  title="retry xloader_data_into_datastore: resource: {} attempt {}".format(
199
195
  job_dict['metadata']['resource_id'], tries),
200
- rq_kwargs=dict(timeout=RETRIED_JOB_TIMEOUT)
196
+ rq_kwargs=dict(timeout=retried_job_timeout)
201
197
  )
202
198
  return True
203
199
  db.mark_job_as_errored(
@@ -305,9 +301,10 @@ def xloader_data_into_datastore_(input, job_dict, logger):
305
301
  use_type_guessing = asbool(
306
302
  config.get('ckanext.xloader.use_type_guessing', config.get(
307
303
  'ckanext.xloader.just_load_with_messytables', False))) \
308
- and not datastore_resource_exists(resource['id']) \
309
- and os.path.getsize(tmp_file.name) <= MAX_TYPE_GUESSING_LENGTH
304
+ and not datastore_resource_exists(resource['id']) \
305
+ and os.path.getsize(tmp_file.name) <= max_type_guessing_length
310
306
  logger.info("'use_type_guessing' mode is: %s", use_type_guessing)
307
+
311
308
  try:
312
309
  if use_type_guessing:
313
310
  try:
@@ -324,8 +321,8 @@ def xloader_data_into_datastore_(input, job_dict, logger):
324
321
  logger.info('Trying again with tabulator')
325
322
  tabulator_load()
326
323
  except JobTimeoutException:
327
- logger.warning('Job timed out after %ss', RETRIED_JOB_TIMEOUT)
328
- raise JobError('Job timed out after {}s'.format(RETRIED_JOB_TIMEOUT))
324
+ logger.warning('Job timed out after %ss', retried_job_timeout)
325
+ raise JobError('Job timed out after {}s'.format(retried_job_timeout))
329
326
  except FileCouldNotBeLoadedError as e:
330
327
  logger.warning('Loading excerpt for this format not supported.')
331
328
  logger.error('Loading file raised an error: %s', e)
@@ -348,8 +345,8 @@ def _download_resource_data(resource, data, api_key, logger):
348
345
  :param api_key: CKAN api key - needed to obtain resources that are private
349
346
  :param logger:
350
347
 
351
- If the download is bigger than MAX_CONTENT_LENGTH then it just downloads a
352
- excerpt (of MAX_EXCERPT_LINES) for preview, and flags it by setting
348
+ If the download is bigger than max_content_length then it just downloads a
349
+ excerpt (of max_excerpt_lines) for preview, and flags it by setting
353
350
  data['datastore_contains_all_records_of_source_file'] = False
354
351
  which will be saved to the resource later on.
355
352
  '''
@@ -374,7 +371,7 @@ def _download_resource_data(resource, data, api_key, logger):
374
371
  if resource.get('url_type') == 'upload':
375
372
  # If this is an uploaded file to CKAN, authenticate the request,
376
373
  # otherwise we won't get file from private resources
377
- headers[APITOKEN_HEADER_NAME] = api_key
374
+ headers[apitoken_header_name] = api_key
378
375
 
379
376
  # Add a constantly changing parameter to bypass URL caching.
380
377
  # If we're running XLoader, then either the resource has
@@ -389,14 +386,14 @@ def _download_resource_data(resource, data, api_key, logger):
389
386
  response = get_response(download_url, headers)
390
387
 
391
388
  cl = response.headers.get('content-length')
392
- if cl and int(cl) > MAX_CONTENT_LENGTH:
389
+ if cl and int(cl) > max_content_length:
393
390
  response.close()
394
391
  raise DataTooBigError()
395
392
 
396
393
  # download the file to a tempfile on disk
397
394
  for chunk in response.iter_content(CHUNK_SIZE):
398
395
  length += len(chunk)
399
- if length > MAX_CONTENT_LENGTH:
396
+ if length > max_content_length:
400
397
  raise DataTooBigError
401
398
  tmp_file.write(chunk)
402
399
  m.update(chunk)
@@ -406,14 +403,14 @@ def _download_resource_data(resource, data, api_key, logger):
406
403
  except DataTooBigError:
407
404
  tmp_file.close()
408
405
  message = 'Data too large to load into Datastore: ' \
409
- '{cl} bytes > max {max_cl} bytes.' \
410
- .format(cl=cl or length, max_cl=MAX_CONTENT_LENGTH)
406
+ '{cl} bytes > max {max_cl} bytes.' \
407
+ .format(cl=cl or length, max_cl=max_content_length)
411
408
  logger.warning(message)
412
- if MAX_EXCERPT_LINES <= 0:
409
+ if max_excerpt_lines <= 0:
413
410
  raise JobError(message)
414
411
  logger.info('Loading excerpt of ~{max_lines} lines to '
415
412
  'DataStore.'
416
- .format(max_lines=MAX_EXCERPT_LINES))
413
+ .format(max_lines=max_excerpt_lines))
417
414
  tmp_file = get_tmp_file(url)
418
415
  response = get_response(url, headers)
419
416
  length = 0
@@ -424,7 +421,7 @@ def _download_resource_data(resource, data, api_key, logger):
424
421
  m.update(line)
425
422
  length += len(line)
426
423
  line_count += 1
427
- if length > MAX_CONTENT_LENGTH or line_count >= MAX_EXCERPT_LINES:
424
+ if length > max_content_length or line_count >= max_excerpt_lines:
428
425
  break
429
426
  response.close()
430
427
  data['datastore_contains_all_records_of_source_file'] = False
@@ -439,7 +436,7 @@ def _download_resource_data(resource, data, api_key, logger):
439
436
  except requests.exceptions.Timeout:
440
437
  logger.warning('URL time out after %ss', DOWNLOAD_TIMEOUT)
441
438
  raise XLoaderTimeoutError('Connection timed out after {}s'.format(
442
- DOWNLOAD_TIMEOUT))
439
+ DOWNLOAD_TIMEOUT))
443
440
  except requests.exceptions.RequestException as e:
444
441
  tmp_file.close()
445
442
  try:
@@ -452,8 +449,8 @@ def _download_resource_data(resource, data, api_key, logger):
452
449
  request_url=url, response=None)
453
450
  except JobTimeoutException:
454
451
  tmp_file.close()
455
- logger.warning('Job timed out after %ss', RETRIED_JOB_TIMEOUT)
456
- raise JobError('Job timed out after {}s'.format(RETRIED_JOB_TIMEOUT))
452
+ logger.warning('Job timed out after %ss', retried_job_timeout)
453
+ raise JobError('Job timed out after {}s'.format(retried_job_timeout))
457
454
 
458
455
  logger.info('Downloaded ok - %s', printable_file_size(length))
459
456
  file_hash = m.hexdigest()
@@ -464,7 +461,7 @@ def _download_resource_data(resource, data, api_key, logger):
464
461
  def get_response(url, headers):
465
462
  def get_url():
466
463
  kwargs = {'headers': headers, 'timeout': DOWNLOAD_TIMEOUT,
467
- 'verify': SSL_VERIFY, 'stream': True} # just gets the headers for now
464
+ 'verify': ssl_verify, 'stream': True} # just gets the headers for now
468
465
  if 'ckan.download_proxy' in config:
469
466
  proxy = config.get('ckan.download_proxy')
470
467
  kwargs['proxies'] = {'http': proxy, 'https': proxy}
@@ -520,14 +517,14 @@ def callback_xloader_hook(result_url, api_key, job_dict):
520
517
  if ':' in api_key:
521
518
  header, key = api_key.split(':')
522
519
  else:
523
- header, key = APITOKEN_HEADER_NAME, api_key
520
+ header, key = apitoken_header_name, api_key
524
521
  headers[header] = key
525
522
 
526
523
  try:
527
524
  result = requests.post(
528
525
  modify_input_url(result_url), # modify with local config
529
526
  data=json.dumps(job_dict, cls=DatetimeJsonEncoder),
530
- verify=SSL_VERIFY,
527
+ verify=ssl_verify,
531
528
  headers=headers)
532
529
  except requests.ConnectionError:
533
530
  return False
@@ -143,6 +143,109 @@ def _clear_datastore_resource(resource_id):
143
143
  conn.execute(sa.text('TRUNCATE TABLE "{}" RESTART IDENTITY'.format(resource_id)))
144
144
 
145
145
 
146
+ def copy_file(csv_filepath, engine, logger, resource_id, headers, delimiter):
147
+ # Options for loading into postgres:
148
+ # 1. \copy - can't use as that is a psql meta-command and not accessible
149
+ # via psycopg2
150
+ # 2. COPY - requires the db user to have superuser privileges. This is
151
+ # dangerous. It is also not available on AWS, for example.
152
+ # 3. pgloader method? - as described in its docs:
153
+ #
154
+ # Note that while the COPY command is restricted to read either from
155
+ # its standard input or from a local file on the server's file system,
156
+ # the command line tool psql implements a \copy command that knows
157
+ # how to stream a file local to the client over the network and into
158
+ # the PostgreSQL server, using the same protocol as pgloader uses.
159
+ # 4. COPY FROM STDIN - not quite as fast as COPY from a file, but avoids
160
+ # the superuser issue. <-- picked
161
+
162
+ with engine.begin() as conn:
163
+ cur = conn.connection.cursor()
164
+ #cur.execute('SET DATESTYLE TO "SQL , MDY"')
165
+ try:
166
+ with open(csv_filepath, 'rb') as f:
167
+ # can't use :param for table name because params are only
168
+ # for filter values that are single quoted.
169
+ try:
170
+ cur.copy_expert(
171
+ "COPY \"{resource_id}\" ({column_names}) "
172
+ "FROM STDIN "
173
+ "WITH (DELIMITER '{delimiter}', FORMAT csv, HEADER 1, "
174
+ " ENCODING '{encoding}');"
175
+ .format(
176
+ resource_id=resource_id,
177
+ column_names=', '.join(['"{}"'.format(h)
178
+ for h in headers]),
179
+ delimiter=delimiter,
180
+ encoding='UTF8',
181
+ ),
182
+ f)
183
+ except psycopg2.DataError as e:
184
+ # e is a str but with foreign chars e.g.
185
+ # 'extra data: "paul,pa\xc3\xbcl"\n'
186
+ # but logging and exceptions need a normal (7 bit) str
187
+ error_str = str(e)
188
+ logger.warning('%s: %s', resource_id, error_str)
189
+ raise LoaderError('Error during the load into PostgreSQL:'
190
+ ' {}'.format(error_str))
191
+ finally:
192
+ cur.close()
193
+
194
+ def split_copy_by_size(input_file, engine, logger, resource_id, headers, delimiter = ',', max_size=1024**3, encoding='utf-8'): # 1 Gigabyte
195
+ """
196
+ Reads a CSV file, splits it into chunks of maximum size, and writes each chunk
197
+ to PostgreSQL COPY command to load the data into a table.
198
+
199
+ Args:
200
+ input_file (str): Path to the input CSV file.
201
+ max_size (int, optional): Maximum size (in bytes) of each output file. Defaults to 1 Gigabyte.
202
+ tablename (str, optional): Name of the target table in PostgreSQL for the COPY command. Defaults to None.
203
+ columns (list, optional): List of column names for the COPY command, matching the CSV header. Defaults to None.
204
+ connection (str, optional): Connection string for the PostgreSQL database. Defaults to an empty string.
205
+ delimiter (str, optional): Delimiter character used in the CSV file. Defaults to ','.
206
+ """
207
+
208
+ chunk_count = 0
209
+ file_size = os.path.getsize(input_file)
210
+ logger.info('Starting chunked processing for file size: %s bytes with chunk size: %s bytes', file_size, max_size)
211
+
212
+ with open(input_file, 'r', encoding = encoding) as infile:
213
+ current_file = None
214
+ output_filename = f'/tmp/output_{resource_id}.csv'
215
+ header = False
216
+ for row in infile:
217
+ if current_file is None or current_file.tell() >= max_size:
218
+ # Close previous file if necessary
219
+ if current_file:
220
+ chunk_count += 1
221
+ logger.debug('Before copying chunk %s: %s', chunk_count, output_filename)
222
+ copy_file(output_filename, engine, logger, resource_id, headers, delimiter)
223
+ logger.debug('Copied chunk %s: %s', chunk_count, output_filename)
224
+ current_file.close()
225
+ header = True
226
+
227
+ current_file = open(output_filename, 'w')
228
+ if header:
229
+ current_file.write(delimiter.join(headers) + '\n')
230
+ current_file.write(row)
231
+
232
+
233
+ # Close the last file if open
234
+ if current_file:
235
+ current_file.close()
236
+
237
+ # Copy the last file
238
+ chunk_count += 1
239
+ logger.debug('Before copying final chunk %s: %s', chunk_count, output_filename)
240
+ copy_file(output_filename, engine, logger, resource_id, headers, delimiter)
241
+ logger.debug('Copied final chunk %s: %s', chunk_count, output_filename)
242
+ os.remove(output_filename)
243
+
244
+ logger.info('Completed chunked processing: %s chunks processed for file size %s bytes', chunk_count, file_size)
245
+ if infile:
246
+ infile.close()
247
+
248
+
146
249
  def _read_metadata(table_filepath, mimetype, logger):
147
250
  # Determine the header row
148
251
  logger.info('Determining column names and types')
@@ -342,51 +445,10 @@ def load_csv(csv_filepath, resource_id, mimetype='text/csv', allow_type_guessing
342
445
 
343
446
  logger.info('Copying to database...')
344
447
 
345
- # Options for loading into postgres:
346
- # 1. \copy - can't use as that is a psql meta-command and not accessible
347
- # via psycopg2
348
- # 2. COPY - requires the db user to have superuser privileges. This is
349
- # dangerous. It is also not available on AWS, for example.
350
- # 3. pgloader method? - as described in its docs:
351
- # Note that while the COPY command is restricted to read either from
352
- # its standard input or from a local file on the server's file system,
353
- # the command line tool psql implements a \copy command that knows
354
- # how to stream a file local to the client over the network and into
355
- # the PostgreSQL server, using the same protocol as pgloader uses.
356
- # 4. COPY FROM STDIN - not quite as fast as COPY from a file, but avoids
357
- # the superuser issue. <-- picked
358
-
359
- with engine.begin() as conn:
360
- cur = conn.connection.cursor()
361
- try:
362
- with open(csv_filepath, 'rb') as f:
363
- # can't use :param for table name because params are only
364
- # for filter values that are single quoted.
365
- try:
366
- cur.copy_expert(
367
- "COPY \"{resource_id}\" ({column_names}) "
368
- "FROM STDIN "
369
- "WITH (DELIMITER '{delimiter}', FORMAT csv, HEADER 1, "
370
- " ENCODING '{encoding}');"
371
- .format(
372
- resource_id=resource_id,
373
- column_names=', '.join(['"{}"'.format(h)
374
- for h in headers]),
375
- delimiter=delimiter,
376
- encoding='UTF8',
377
- ),
378
- f)
379
- except psycopg2.DataError as e:
380
- # e is a str but with foreign chars e.g.
381
- # 'extra data: "paul,pa\xc3\xbcl"\n'
382
- # but logging and exceptions need a normal (7 bit) str
383
- error_str = str(e)
384
- logger.warning(error_str)
385
- raise LoaderError('Error during the load into PostgreSQL:'
386
- ' {}'.format(error_str))
387
-
388
- finally:
389
- cur.close()
448
+ # Copy file to datastore db, split to chunks.
449
+ max_size = config.get('ckanext.xloader.copy_chunk_size', 1024**3)
450
+ logger.debug('Using chunk size: %s bytes for resource %s', max_size, resource_id)
451
+ split_copy_by_size(csv_filepath, engine, logger, resource_id, headers, delimiter, int(max_size))
390
452
 
391
453
  logger.info('...copying done')
392
454
 
@@ -2,13 +2,14 @@
2
2
 
3
3
  import logging
4
4
 
5
+ import requests
5
6
  from ckan import plugins
6
7
  from ckan.plugins import toolkit
7
8
 
8
9
  from ckan.model.domain_object import DomainObjectOperation
9
10
  from ckan.model.resource import Resource
10
11
 
11
- from . import action, auth, helpers as xloader_helpers, utils
12
+ from . import action, auth, helpers as xloader_helpers, jobs, utils
12
13
  from ckanext.xloader.utils import XLoaderFormats
13
14
 
14
15
  try:
@@ -70,6 +71,24 @@ class xloaderPlugin(plugins.SingletonPlugin):
70
71
  else:
71
72
  self.ignore_hash = False
72
73
 
74
+ # Set config values that need to be available to all jobs, without loading
75
+ # the config itself in every single job
76
+ jobs.ssl_verify = toolkit.asbool(config_.get('ckanext.xloader.ssl_verify', True))
77
+ if not jobs.ssl_verify:
78
+ requests.packages.urllib3.disable_warnings()
79
+
80
+ jobs.max_content_length = int(config_.get('ckanext.xloader.max_content_length') or 1e9)
81
+ # Don't try Tabulator load on large files
82
+ jobs.max_type_guessing_length = int(
83
+ config_.get('ckanext.xloader.max_type_guessing_length') or jobs.max_content_length / 10
84
+ )
85
+ jobs.max_excerpt_lines = int(config_.get('ckanext.xloader.max_excerpt_lines') or 0)
86
+ jobs.max_retries = int(config_.get('ckanext.xloader.max_retries', 1))
87
+ # Retries can only occur in cases where the datastore entry exists,
88
+ # so use the standard timeout
89
+ jobs.retried_job_timeout = config_.get('ckanext.xloader.job_timeout', '3600')
90
+ jobs.apitoken_header_name = config_.get('apitoken_header_name', 'Authorization')
91
+
73
92
  # IPipeValidation
74
93
 
75
94
  def receive_validation_report(self, validation_report):
@@ -0,0 +1,169 @@
1
+ # -*- coding: utf-8 -*-
2
+ import os
3
+ import pytest
4
+ import tempfile
5
+ import logging
6
+ from typing import Callable, List, Tuple, Any
7
+ from unittest.mock import patch, MagicMock
8
+ import csv
9
+ import sqlalchemy.orm as orm
10
+
11
+ from ckan.tests import factories
12
+ from ckanext.xloader import loader
13
+ from ckanext.xloader.loader import get_write_engine
14
+ from ckanext.xloader.tests.test_loader import TestLoadBase, get_sample_filepath
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+
19
+ @pytest.fixture()
20
+ def Session():
21
+ engine = get_write_engine()
22
+ Session = orm.scoped_session(orm.sessionmaker(bind=engine))
23
+ yield Session
24
+ Session.close()
25
+
26
+
27
+ @pytest.mark.usefixtures("full_reset", "with_plugins")
28
+ @pytest.mark.ckan_config("ckan.plugins", "datastore xloader")
29
+ class TestChunkedLoading(TestLoadBase):
30
+
31
+ def _create_mock_split_copy(self, chunk_size: int) -> Callable:
32
+ """Create a mock function for split_copy_by_size with specified chunk size"""
33
+ original_split_copy = loader.split_copy_by_size
34
+
35
+ def mock_split_copy(input_file: Any, engine: Any, logger: Any, resource_id: str, headers: List[str], delimiter: str = ',', max_size: int = 1024**3) -> Any:
36
+ return original_split_copy(input_file, engine, logger, resource_id, headers, delimiter, chunk_size)
37
+
38
+ return mock_split_copy
39
+
40
+ def _create_mock_copy_file(self, copy_calls_list: List[Tuple]) -> Callable:
41
+ """Create a mock function for copy_file that tracks calls"""
42
+ original_copy_file = loader.copy_file
43
+
44
+ def mock_copy_file(*args: Any, **kwargs: Any) -> Any:
45
+ copy_calls_list.append(args)
46
+ return original_copy_file(*args, **kwargs)
47
+
48
+ return mock_copy_file
49
+
50
+ def _generate_large_csv(self, filepath: str, num_rows: int = 100000, row_size_kb: int = 1) -> Tuple[str, List[str], int]:
51
+ """Generate a large CSV file for testing chunked processing"""
52
+ headers = ['id', 'name', 'description', 'data']
53
+
54
+ # Create data that will make each row approximately row_size_kb KB
55
+ padding_size = (row_size_kb * 1024) - 50 # Account for other columns
56
+ padding_data = 'x' * max(1, padding_size)
57
+
58
+ with open(filepath, 'w', newline='', encoding='utf-8') as csvfile:
59
+ writer = csv.writer(csvfile)
60
+ writer.writerow(headers)
61
+
62
+ for i in range(num_rows):
63
+ writer.writerow([
64
+ i + 1,
65
+ f'Name_{i + 1}',
66
+ f'Description for row {i + 1}',
67
+ padding_data
68
+ ])
69
+
70
+ return filepath, headers, num_rows
71
+
72
+ def test_chunked_processing_large_file(self, Session: Any) -> None:
73
+ """Test that large files are processed in chunks and data integrity is maintained"""
74
+
75
+ # Create a temporary large CSV file (~15MB to trigger chunking)
76
+ with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False) as temp_file:
77
+ temp_filepath = temp_file.name
78
+
79
+ try:
80
+ # Generate file with ~15MB (15000 rows * ~1KB each)
81
+ csv_filepath, expected_headers, expected_rows = self._generate_large_csv(
82
+ temp_filepath, num_rows=15000, row_size_kb=1
83
+ )
84
+
85
+ # Verify file size is large enough to trigger chunking
86
+ file_size = os.path.getsize(csv_filepath)
87
+ assert file_size > 10 * 1024 * 1024, f"File size {file_size} should be > 10MB"
88
+
89
+ resource = factories.Resource()
90
+ resource_id = resource['id']
91
+
92
+ # Set up mocks with 10MB chunk size
93
+ copy_calls = []
94
+ mock_split_copy = self._create_mock_split_copy(10 * 1024 * 1024)
95
+ mock_copy_file = self._create_mock_copy_file(copy_calls)
96
+
97
+ with patch('ckanext.xloader.loader.split_copy_by_size', side_effect=mock_split_copy):
98
+ with patch('ckanext.xloader.loader.copy_file', side_effect=mock_copy_file):
99
+ # Load the CSV with chunked processing
100
+ fields = loader.load_csv(
101
+ csv_filepath,
102
+ resource_id=resource_id,
103
+ mimetype="text/csv",
104
+ logger=logger,
105
+ )
106
+
107
+ # Verify chunking occurred (should have multiple copy calls)
108
+ assert len(copy_calls) > 1, "Expected multiple chunks but file was not chunked"
109
+
110
+ # Verify data integrity - check that all rows were loaded
111
+ records = self._get_records(Session, resource_id)
112
+ assert len(records) == expected_rows, f"Expected {expected_rows} records, got {len(records)}"
113
+
114
+ # Verify column structure
115
+ column_names = self._get_column_names(Session, resource_id)
116
+ expected_columns = ['_id', '_full_text'] + expected_headers
117
+ assert column_names == expected_columns
118
+
119
+ # Verify first and last records to ensure data integrity
120
+ # Sort records by the 'id' column (index 1) to ensure consistent ordering
121
+ sorted_records = sorted(records, key=lambda x: int(x[1]))
122
+ first_record = sorted_records[0]
123
+ last_record = sorted_records[-1]
124
+
125
+ # Check first record (excluding _id and _full_text columns)
126
+ # The _get_records method excludes _full_text by default, so indices are:
127
+ # 0: _id, 1: id, 2: name, 3: description, 4: data
128
+
129
+ assert first_record[1] == '1' # id column (index 1 after _id)
130
+ assert first_record[2] == 'Name_1' # name column (index 2)
131
+
132
+ # Check last record
133
+ assert last_record[1] == str(expected_rows) # id column
134
+ assert last_record[2] == f'Name_{expected_rows}' # name column
135
+
136
+ finally:
137
+ # Clean up temporary file
138
+ if os.path.exists(temp_filepath):
139
+ os.unlink(temp_filepath)
140
+
141
+ def test_small_file_no_chunking(self, Session: Any) -> None:
142
+ """Test that small files are not chunked when chunk size is larger than file"""
143
+
144
+ # Use existing small sample file
145
+ csv_filepath = get_sample_filepath("simple.csv")
146
+ resource = factories.Resource()
147
+ resource_id = resource['id']
148
+
149
+ # Set up mocks with large chunk size to prevent chunking
150
+ copy_calls = []
151
+ mock_split_copy = self._create_mock_split_copy(10 * 1024 * 1024) # 10MB
152
+ mock_copy_file = self._create_mock_copy_file(copy_calls)
153
+
154
+ with patch('ckanext.xloader.loader.split_copy_by_size', side_effect=mock_split_copy):
155
+ with patch('ckanext.xloader.loader.copy_file', side_effect=mock_copy_file):
156
+ fields = loader.load_csv(
157
+ csv_filepath,
158
+ resource_id=resource_id,
159
+ mimetype="text/csv",
160
+ logger=logger,
161
+ )
162
+
163
+ # Small file should only have one copy call (no chunking)
164
+ assert len(copy_calls) == 1, f"Small file should not be chunked, got {len(copy_calls)} copy calls"
165
+
166
+ # Verify data loaded correctly
167
+ records = self._get_records(Session, resource_id)
168
+ assert len(records) == 6 # Known number of records in simple.csv
169
+
@@ -83,6 +83,7 @@ def data(create_with_upload, apikey):
83
83
 
84
84
  @pytest.mark.usefixtures("clean_db", "with_plugins")
85
85
  @pytest.mark.ckan_config("ckanext.xloader.job_timeout", 2)
86
+ @pytest.mark.ckan_config("ckanext.xloader.copy_chunk_size", 5120)
86
87
  @pytest.mark.ckan_config("ckan.jobs.timeout", 2)
87
88
  class TestXLoaderJobs(helpers.FunctionalRQTestBase):
88
89
 
@@ -180,12 +181,13 @@ class TestXLoaderJobs(helpers.FunctionalRQTestBase):
180
181
  stdout = cli.invoke(ckan, ["jobs", "worker", "--burst"]).output
181
182
  assert "Data too large to load into Datastore:" in stdout
182
183
 
184
+
185
+ @pytest.mark.ckan_config("ckanext.xloader.max_excerpt_lines", 1)
183
186
  def test_data_max_excerpt_lines_config(self, cli, data):
184
187
  self.enqueue(jobs.xloader_data_into_datastore, [data])
185
188
  with mock.patch("ckanext.xloader.jobs.get_response", get_large_response):
186
- with mock.patch("ckanext.xloader.jobs.MAX_EXCERPT_LINES", 1):
187
- stdout = cli.invoke(ckan, ["jobs", "worker", "--burst"]).output
188
- assert "Loading excerpt of ~1 lines to DataStore." in stdout
189
+ stdout = cli.invoke(ckan, ["jobs", "worker", "--burst"]).output
190
+ assert "Loading excerpt of ~1 lines to DataStore." in stdout
189
191
 
190
192
  resource = helpers.call_action("resource_show", id=data["metadata"]["resource_id"])
191
193
  assert resource["datastore_contains_all_records_of_source_file"] is False
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ckanext-xloader
3
- Version: 2.2.0
3
+ Version: 2.3.0
4
4
  Summary: Express Loader - quickly load data into CKAN DataStore
5
5
  Author: David Read (davidread), Patricio Del Boca (pdelboca)
6
6
  Author-email: ThrawnCA <carl.antuar@smartservice.qld.gov.au>, "Jesse Vickery (JVickery-TBS)" <jesse.vickery@tbs-sct.gc.ca>, "Adrià Mercader (amercader)" <amercadero@gmail.com>, "Brett Jones (kowh-ai)" <datashades@linkdigital.com.au>, "William Dutton (duttonw)" <william.dutton@qld.gov.au>
@@ -37,6 +37,7 @@ ckanext/xloader/tests/__init__.py
37
37
  ckanext/xloader/tests/ckan_setup.py
38
38
  ckanext/xloader/tests/fixtures.py
39
39
  ckanext/xloader/tests/test_action.py
40
+ ckanext/xloader/tests/test_chunks.py
40
41
  ckanext/xloader/tests/test_jobs.py
41
42
  ckanext/xloader/tests/test_loader.py
42
43
  ckanext/xloader/tests/test_parser.py
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "ckanext-xloader"
7
- version = "2.2.0"
7
+ version = "2.3.0"
8
8
  description = "Express Loader - quickly load data into CKAN DataStore"
9
9
  classifiers = [ "Development Status :: 5 - Production/Stable",
10
10
  "License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)",
File without changes