-
Notifications
You must be signed in to change notification settings - Fork 96
Expand file tree
/
Copy pathtable.py
More file actions
1622 lines (1419 loc) · 67.1 KB
/
table.py
File metadata and controls
1622 lines (1419 loc) · 67.1 KB
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import collections
import csv
import inspect
import itertools
import json
import logging
import uuid
import warnings
from dataclasses import dataclass, field
from pathlib import Path
import numpy as np
import pandas
from .condition import make_condition
from .declare import alter, declare
from .errors import (
AccessError,
DataJointError,
DuplicateError,
IntegrityError,
UnknownAttributeError,
)
from .expression import QueryExpression
from .heading import Heading
from .staged_insert import staged_insert1 as _staged_insert1
from .utils import get_master, is_camel_case, user_choice
logger = logging.getLogger(__name__.split(".")[0])
# Note: Foreign key error parsing is now handled by adapter methods
# Legacy regexp and query kept for reference but no longer used
@dataclass
class ValidationResult:
"""
Result of table.validate() call.
Attributes:
is_valid: True if all rows passed validation
errors: List of (row_index, field_name, error_message) tuples
rows_checked: Number of rows that were validated
"""
is_valid: bool
errors: list = field(default_factory=list) # list of (row_index, field_name | None, message)
rows_checked: int = 0
def __bool__(self) -> bool:
"""Allow using ValidationResult in boolean context."""
return self.is_valid
def raise_if_invalid(self):
"""Raise DataJointError if validation failed."""
if not self.is_valid:
raise DataJointError(self.summary())
def summary(self) -> str:
"""Return formatted error summary."""
if self.is_valid:
return f"Validation passed: {self.rows_checked} rows checked"
lines = [f"Validation failed: {len(self.errors)} error(s) in {self.rows_checked} rows"]
for row_idx, field_name, message in self.errors[:10]: # Show first 10 errors
field_str = f" in field '{field_name}'" if field_name else ""
lines.append(f" Row {row_idx}{field_str}: {message}")
if len(self.errors) > 10:
lines.append(f" ... and {len(self.errors) - 10} more errors")
return "\n".join(lines)
class Table(QueryExpression):
"""
Table is an abstract class that represents a table in the schema.
It implements insert and delete methods and inherits query functionality.
To make it a concrete class, override the abstract properties specifying the connection,
table name, database, and definition.
"""
_table_name = None # must be defined in subclass
# These properties must be set by the schema decorator (schemas.py) at class level
# or by FreeTable at instance level
database = None
declaration_context = None
@property
def table_name(self):
# For UserTable subclasses, table_name is computed by the metaclass.
# Delegate to the class's table_name if _table_name is not set.
if self._table_name is None:
return type(self).table_name
return self._table_name
@property
def class_name(self):
return self.__class__.__name__
# Base tier class names that should not raise errors when heading is None
_base_tier_classes = frozenset({"Table", "UserTable", "Lookup", "Manual", "Imported", "Computed", "Part"})
@property
def heading(self):
"""
Return the table's heading, or raise a helpful error if not configured.
Overrides QueryExpression.heading to provide a clear error message
when the table is not properly associated with an activated schema.
For base tier classes (Lookup, Manual, etc.), returns None to support
introspection (e.g., help()).
"""
if self._heading is None:
# Don't raise error for base tier classes - they're used for introspection
if self.__class__.__name__ in self._base_tier_classes:
return None
raise DataJointError(
f"Table `{self.__class__.__name__}` is not properly configured. "
"Ensure the schema is activated before using the table. "
"Example: schema.activate('database_name') or schema = dj.Schema('database_name')"
)
return self._heading
@property
def definition(self):
raise NotImplementedError("Subclasses of Table must implement the `definition` property")
def declare(self, context=None):
"""
Declare the table in the schema based on self.definition.
Parameters
----------
context : dict, optional
The context for foreign key resolution. If None, foreign keys are
not allowed.
"""
if self.connection.in_transaction:
raise DataJointError("Cannot declare new tables inside a transaction, e.g. from inside a populate/make call")
# Validate class name #1150
class_name = self.class_name
if "_" in class_name:
warnings.warn(
f"Table class name `{class_name}` contains underscores. CamelCase names without underscores are recommended.",
UserWarning,
stacklevel=2,
)
class_name = class_name.replace("_", "")
if not is_camel_case(class_name):
raise DataJointError(
f"Table class name `{self.class_name}` is invalid. "
"Class names must be in CamelCase, starting with a capital letter."
)
sql, _external_stores, primary_key, fk_attribute_map, pre_ddl, post_ddl = declare(
self.full_table_name, self.definition, context, self.connection.adapter, config=self.connection._config
)
# Call declaration hook for validation (subclasses like AutoPopulate can override)
self._declare_check(primary_key, fk_attribute_map)
sql = sql.format(database=self.database)
try:
# Execute pre-DDL statements (e.g., CREATE TYPE for PostgreSQL enums)
for ddl in pre_ddl:
try:
self.connection.query(ddl.format(database=self.database))
except Exception:
# Ignore errors (type may already exist)
pass
self.connection.query(sql)
# Execute post-DDL statements (e.g., COMMENT ON for PostgreSQL)
for ddl in post_ddl:
self.connection.query(ddl.format(database=self.database))
except AccessError:
# Only suppress if table already exists (idempotent declaration)
# Otherwise raise - user needs to know about permission issues
if self.is_declared:
return
raise AccessError(
f"Cannot declare table {self.full_table_name}. "
f"Check that you have CREATE privilege on schema `{self.database}` "
f"and REFERENCES privilege on any referenced parent tables."
) from None
# Populate lineage table for this table's attributes
self._populate_lineage(primary_key, fk_attribute_map)
def _declare_check(self, primary_key, fk_attribute_map):
"""
Hook for declaration-time validation. Subclasses can override.
Called before the table is created in the database. Override this method
to add validation logic (e.g., AutoPopulate validates FK-only primary keys).
Parameters
----------
primary_key : list
List of primary key attribute names.
fk_attribute_map : dict
Dict mapping child_attr -> (parent_table, parent_attr).
"""
pass # Default: no validation
def _populate_lineage(self, primary_key, fk_attribute_map):
"""
Populate the ~lineage table with lineage information for this table's attributes.
Lineage is stored for:
- All FK attributes (traced to their origin)
- Native primary key attributes (lineage = self)
Parameters
----------
primary_key : list
List of primary key attribute names.
fk_attribute_map : dict
Dict mapping child_attr -> (parent_table, parent_attr).
"""
from .lineage import (
ensure_lineage_table,
get_lineage,
delete_table_lineages,
insert_lineages,
)
# Ensure the ~lineage table exists
ensure_lineage_table(self.connection, self.database)
# Delete any existing lineage entries for this table (for idempotent re-declaration)
delete_table_lineages(self.connection, self.database, self.table_name)
entries = []
# FK attributes: copy lineage from parent (whether in PK or not)
for attr, (parent_table, parent_attr) in fk_attribute_map.items():
# Parse parent table name: `schema`.`table` or "schema"."table" -> (schema, table)
parent_db, parent_tbl = self.connection.adapter.split_full_table_name(parent_table)
# Get parent's lineage for this attribute
parent_lineage = get_lineage(self.connection, parent_db, parent_tbl, parent_attr)
if parent_lineage:
# Copy parent's lineage
entries.append((self.table_name, attr, parent_lineage))
else:
# Parent doesn't have lineage entry - use parent as origin
# This can happen for legacy/external schemas without lineage tracking
lineage = f"{parent_db}.{parent_tbl}.{parent_attr}"
entries.append((self.table_name, attr, lineage))
logger.warning(
f"Lineage for `{parent_db}`.`{parent_tbl}`.`{parent_attr}` not found "
f"(parent schema's ~lineage table may be missing or incomplete). "
f"Using it as origin. Once the parent schema's lineage is rebuilt, "
f"run schema.rebuild_lineage() on this schema to correct the lineage."
)
# Native PK attributes (in PK but not FK): this table is the origin
for attr in primary_key:
if attr not in fk_attribute_map:
lineage = f"{self.database}.{self.table_name}.{attr}"
entries.append((self.table_name, attr, lineage))
if entries:
insert_lineages(self.connection, self.database, entries)
def alter(self, prompt=True, context=None):
"""
Alter the table definition from self.definition
"""
if self.connection.in_transaction:
raise DataJointError("Cannot update table declaration inside a transaction, e.g. from inside a populate/make call")
if context is None:
frame = inspect.currentframe().f_back
context = dict(frame.f_globals, **frame.f_locals)
del frame
old_definition = self.describe(context=context)
sql, _external_stores = alter(self.definition, old_definition, context, self.connection.adapter)
if not sql:
if prompt:
logger.warning("Nothing to alter.")
else:
sql = "ALTER TABLE {tab}\n\t".format(tab=self.full_table_name) + ",\n\t".join(sql)
if not prompt or user_choice(sql + "\n\nExecute?") == "yes":
try:
self.connection.query(sql)
except AccessError:
# skip if no create privilege
pass
else:
# reset heading
self.__class__._heading = Heading(table_info=self.heading.table_info)
if prompt:
logger.info("Table altered")
def from_clause(self):
"""
Return the FROM clause of SQL SELECT statements.
Returns
-------
str
The full table name for use in SQL FROM clauses.
"""
return self.full_table_name
def get_select_fields(self, select_fields=None):
"""
Return the selected attributes from the SQL SELECT statement.
Parameters
----------
select_fields : list, optional
List of attribute names to select. If None, selects all attributes.
Returns
-------
str
The SQL field selection string.
"""
return "*" if select_fields is None else self.heading.project(select_fields).as_sql
def parents(self, primary=None, as_objects=False, foreign_key_info=False):
"""
Return the list of parent tables.
Parameters
----------
primary : bool, optional
If None, then all parents are returned. If True, then only foreign keys
composed of primary key attributes are considered. If False, return
foreign keys including at least one secondary attribute.
as_objects : bool, optional
If False, return table names. If True, return table objects.
foreign_key_info : bool, optional
If True, each element in result also includes foreign key info.
Returns
-------
list
List of parents as table names or table objects with (optional) foreign
key information.
"""
get_edge = self.connection.dependencies.parents
nodes = [
next(iter(get_edge(name).items())) if name.isdigit() else (name, props)
for name, props in get_edge(self.full_table_name, primary).items()
]
if as_objects:
nodes = [(FreeTable(self.connection, name), props) for name, props in nodes]
if not foreign_key_info:
nodes = [name for name, props in nodes]
return nodes
def children(self, primary=None, as_objects=False, foreign_key_info=False):
"""
Return the list of child tables.
Parameters
----------
primary : bool, optional
If None, then all children are returned. If True, then only foreign keys
composed of primary key attributes are considered. If False, return
foreign keys including at least one secondary attribute.
as_objects : bool, optional
If False, return table names. If True, return table objects.
foreign_key_info : bool, optional
If True, each element in result also includes foreign key info.
Returns
-------
list
List of children as table names or table objects with (optional) foreign
key information.
"""
get_edge = self.connection.dependencies.children
nodes = [
next(iter(get_edge(name).items())) if name.isdigit() else (name, props)
for name, props in get_edge(self.full_table_name, primary).items()
]
if as_objects:
nodes = [(FreeTable(self.connection, name), props) for name, props in nodes]
if not foreign_key_info:
nodes = [name for name, props in nodes]
return nodes
def descendants(self, as_objects=False):
"""
Return list of descendant tables in topological order.
Parameters
----------
as_objects : bool, optional
If False (default), return a list of table names. If True, return a
list of table objects.
Returns
-------
list
List of descendant tables in topological order.
"""
return [
FreeTable(self.connection, node) if as_objects else node
for node in self.connection.dependencies.descendants(self.full_table_name)
if not node.isdigit()
]
def ancestors(self, as_objects=False):
"""
Return list of ancestor tables in topological order.
Parameters
----------
as_objects : bool, optional
If False (default), return a list of table names. If True, return a
list of table objects.
Returns
-------
list
List of ancestor tables in topological order.
"""
return [
FreeTable(self.connection, node) if as_objects else node
for node in self.connection.dependencies.ancestors(self.full_table_name)
if not node.isdigit()
]
def parts(self, as_objects=False):
"""
Return part tables for this master table.
Parameters
----------
as_objects : bool, optional
If False (default), the output is a list of full table names. If True,
return table objects.
Returns
-------
list
List of part table names or table objects.
"""
self.connection.dependencies.load(force=False)
nodes = [
node
for node in self.connection.dependencies.nodes
if not node.isdigit() and node.startswith(self.full_table_name[:-1] + "__")
]
return [FreeTable(self.connection, c) for c in nodes] if as_objects else nodes
@property
def is_declared(self):
"""
Check if the table is declared in the schema.
Returns
-------
bool
True if the table is declared in the schema.
"""
query = self.connection.adapter.get_table_info_sql(self.database, self.table_name)
return self.connection.query(query).rowcount > 0
@property
def full_table_name(self):
"""
Return the full table name in the schema.
Returns
-------
str
Full table name in the format `database`.`table_name`.
"""
if self.database is None or self.table_name is None:
raise DataJointError(
f"Class {self.__class__.__name__} is not associated with a schema. "
"Apply a schema decorator or use schema() to bind it."
)
return self.adapter.make_full_table_name(self.database, self.table_name)
@property
def adapter(self):
"""Database adapter for backend-agnostic SQL generation."""
return self.connection.adapter
def update1(self, row):
"""
Update one existing entry in the table.
Caution: In DataJoint the primary modes for data manipulation is to ``insert`` and
``delete`` entire records since referential integrity works on the level of records,
not fields. Therefore, updates are reserved for corrective operations outside of main
workflow. Use UPDATE methods sparingly with full awareness of potential violations of
assumptions.
The primary key attributes must always be provided.
Parameters
----------
row : dict
A dict containing the primary key values and the attributes to update.
Setting an attribute value to None will reset it to the default value (if any).
Examples
--------
>>> table.update1({'id': 1, 'value': 3}) # update value in record with id=1
>>> table.update1({'id': 1, 'value': None}) # reset value to default
"""
# argument validations
if not isinstance(row, collections.abc.Mapping):
raise DataJointError("The argument of update1 must be dict-like.")
if not set(row).issuperset(self.primary_key):
raise DataJointError("The argument of update1 must supply all primary key values.")
try:
raise DataJointError("Attribute `%s` not found." % next(k for k in row if k not in self.heading.names))
except StopIteration:
pass # ok
if len(self.restriction):
raise DataJointError("Update cannot be applied to a restricted table.")
key = {k: row[k] for k in self.primary_key}
if len(self & key) != 1:
raise DataJointError("Update can only be applied to one existing entry.")
# UPDATE query
row = [self.__make_placeholder(k, v) for k, v in row.items() if k not in self.primary_key]
assignments = ",".join(f"{self.adapter.quote_identifier(r[0])}={r[1]}" for r in row)
query = "UPDATE {table} SET {assignments} WHERE {where}".format(
table=self.full_table_name,
assignments=assignments,
where=make_condition(self, key, set()),
)
self.connection.query(query, args=list(r[2] for r in row if r[2] is not None))
def validate(self, rows, *, ignore_extra_fields=False) -> ValidationResult:
"""
Validate rows without inserting them.
Validates:
- Field existence (all fields must be in table heading)
- Row format (correct number of attributes for positional inserts)
- Codec validation (type checking via codec.validate())
- NULL constraints (non-nullable fields must have values)
- Primary key completeness (all PK fields must be present)
- UUID format and JSON serializability
Cannot validate (database-enforced):
- Foreign key constraints
- Unique constraints (other than PK)
- Custom MySQL constraints
Parameters
----------
rows : iterable
Same format as insert() - iterable of dicts, tuples, numpy records,
or a pandas DataFrame.
ignore_extra_fields : bool, optional
If True, ignore fields not in the table heading.
Returns
-------
ValidationResult
Result with is_valid, errors list, and rows_checked count.
Examples
--------
>>> result = table.validate(rows)
>>> if result:
... table.insert(rows)
... else:
... print(result.summary())
"""
errors = []
# Convert DataFrame to records
if isinstance(rows, pandas.DataFrame):
rows = rows.reset_index(drop=len(rows.index.names) == 1 and not rows.index.names[0]).to_records(index=False)
# Convert Path (CSV) to list of dicts
if isinstance(rows, Path):
with open(rows, newline="") as data_file:
rows = list(csv.DictReader(data_file, delimiter=","))
rows = list(rows) # Materialize iterator
row_count = len(rows)
for row_idx, row in enumerate(rows):
# Validate row format and fields
row_dict = None
try:
if isinstance(row, np.void): # numpy record
fields = list(row.dtype.fields.keys())
row_dict = {name: row[name] for name in fields}
elif isinstance(row, collections.abc.Mapping):
fields = list(row.keys())
row_dict = dict(row)
else: # positional tuple/list
if len(row) != len(self.heading):
errors.append(
(
row_idx,
None,
f"Incorrect number of attributes: {len(row)} given, {len(self.heading)} expected",
)
)
continue
fields = list(self.heading.names)
row_dict = dict(zip(fields, row))
except TypeError:
errors.append((row_idx, None, f"Invalid row type: {type(row).__name__}"))
continue
# Check for unknown fields
if not ignore_extra_fields:
for field_name in fields:
if field_name not in self.heading:
errors.append((row_idx, field_name, f"Field '{field_name}' not in table heading"))
# Validate each field value
for name in self.heading.names:
if name not in row_dict:
# Check if field is required (non-nullable, no default, not autoincrement)
attr = self.heading[name]
if not attr.nullable and attr.default is None and not attr.autoincrement:
errors.append((row_idx, name, f"Required field '{name}' is missing"))
continue
value = row_dict[name]
attr = self.heading[name]
# Skip validation for None values on nullable columns
if value is None:
if not attr.nullable and attr.default is None:
errors.append((row_idx, name, f"NULL value not allowed for non-nullable field '{name}'"))
continue
# Codec validation
if attr.codec:
try:
attr.codec.validate(value)
except (TypeError, ValueError) as e:
errors.append((row_idx, name, f"Codec validation failed: {e}"))
continue
# UUID validation
if attr.uuid and not isinstance(value, uuid.UUID):
try:
uuid.UUID(value)
except (AttributeError, ValueError):
errors.append((row_idx, name, f"Invalid UUID format: {value}"))
continue
# JSON serialization check
if attr.json:
try:
json.dumps(value)
except (TypeError, ValueError) as e:
errors.append((row_idx, name, f"Value not JSON serializable: {e}"))
continue
# Numeric NaN check
if attr.numeric and value != "" and not isinstance(value, (bool, np.bool_)):
try:
if np.isnan(float(value)):
# NaN is allowed - will be converted to NULL
pass
except (TypeError, ValueError):
# Not a number that can be checked for NaN - let it pass
pass
# Check primary key completeness
for pk_field in self.primary_key:
if pk_field not in row_dict or row_dict[pk_field] is None:
pk_attr = self.heading[pk_field]
if not pk_attr.autoincrement:
errors.append((row_idx, pk_field, f"Primary key field '{pk_field}' is missing or NULL"))
return ValidationResult(is_valid=len(errors) == 0, errors=errors, rows_checked=row_count)
def insert1(self, row, **kwargs):
"""
Insert one data record into the table.
For ``kwargs``, see ``insert()``.
Parameters
----------
row : numpy.void, dict, or sequence
A numpy record, a dict-like object, or an ordered sequence to be inserted
as one row.
**kwargs
Additional arguments passed to ``insert()``.
See Also
--------
insert : Insert multiple data records.
"""
self.insert((row,), **kwargs)
@property
def staged_insert1(self):
"""
Context manager for staged insert with direct object storage writes.
Use this for large objects like Zarr arrays where copying from local storage
is inefficient. Allows writing directly to the destination storage before
finalizing the database insert.
Example:
with table.staged_insert1 as staged:
staged.rec['subject_id'] = 123
staged.rec['session_id'] = 45
# Create object storage directly
z = zarr.open(staged.store('raw_data', '.zarr'), mode='w', shape=(1000, 1000))
z[:] = data
# Assign to record
staged.rec['raw_data'] = z
# On successful exit: metadata computed, record inserted
# On exception: storage cleaned up, no record inserted
Yields:
StagedInsert: Context for setting record values and getting storage handles
"""
return _staged_insert1(self)
def insert(
self,
rows,
replace=False,
skip_duplicates=False,
ignore_extra_fields=False,
allow_direct_insert=None,
chunk_size=None,
):
"""
Insert a collection of rows.
Parameters
----------
rows : iterable or pathlib.Path
Either (a) an iterable where an element is a numpy record, a dict-like
object, a pandas.DataFrame, a polars.DataFrame, a pyarrow.Table, a
sequence, or a query expression with the same heading as self, or
(b) a pathlib.Path object specifying a path relative to the current
directory with a CSV file, the contents of which will be inserted.
replace : bool, optional
If True, replaces the existing tuple.
skip_duplicates : bool, optional
If True, silently skip duplicate inserts.
ignore_extra_fields : bool, optional
If False (default), fields that are not in the heading raise error.
allow_direct_insert : bool, optional
Only applies in auto-populated tables. If False (default), insert may
only be called from inside the make callback.
chunk_size : int, optional
If set, insert rows in batches of this size. Useful for very large
inserts to avoid memory issues. Each chunk is a separate transaction.
Examples
--------
>>> Table.insert([
... dict(subject_id=7, species="mouse", date_of_birth="2014-09-01"),
... dict(subject_id=8, species="mouse", date_of_birth="2014-09-02")])
Large insert with chunking:
>>> Table.insert(large_dataset, chunk_size=10000)
"""
if isinstance(rows, pandas.DataFrame):
# drop 'extra' synthetic index for 1-field index case -
# frames with more advanced indices should be prepared by user.
rows = rows.reset_index(drop=len(rows.index.names) == 1 and not rows.index.names[0]).to_records(index=False)
# Polars DataFrame -> list of dicts (soft dependency, check by type name)
if type(rows).__module__.startswith("polars") and type(rows).__name__ == "DataFrame":
rows = rows.to_dicts()
# PyArrow Table -> list of dicts (soft dependency, check by type name)
if type(rows).__module__.startswith("pyarrow") and type(rows).__name__ == "Table":
rows = rows.to_pylist()
if isinstance(rows, Path):
with open(rows, newline="") as data_file:
rows = list(csv.DictReader(data_file, delimiter=","))
# prohibit direct inserts into auto-populated tables
if not allow_direct_insert and not getattr(self, "_allow_insert", True):
raise DataJointError(
"Inserts into an auto-populated table can only be done inside "
"its make method during a populate call."
" To override, set keyword argument allow_direct_insert=True."
)
if inspect.isclass(rows) and issubclass(rows, QueryExpression):
rows = rows() # instantiate if a class
if isinstance(rows, QueryExpression):
# insert from select - chunk_size not applicable
if chunk_size is not None:
raise DataJointError("chunk_size is not supported for QueryExpression inserts")
if not ignore_extra_fields:
try:
raise DataJointError(
"Attribute %s not found. To ignore extra attributes in insert, "
"set ignore_extra_fields=True." % next(name for name in rows.heading if name not in self.heading)
)
except StopIteration:
pass
fields = list(name for name in rows.heading if name in self.heading)
quoted_fields = ",".join(self.adapter.quote_identifier(f) for f in fields)
# Duplicate handling (backend-agnostic)
if skip_duplicates:
duplicate = self.adapter.skip_duplicates_clause(self.full_table_name, self.primary_key)
else:
duplicate = ""
command = "REPLACE" if replace else "INSERT"
query = f"{command} INTO {self.full_table_name} ({quoted_fields}) {rows.make_sql(fields)}{duplicate}"
self.connection.query(query)
return
# Chunked insert mode
if chunk_size is not None:
rows_iter = iter(rows)
while True:
chunk = list(itertools.islice(rows_iter, chunk_size))
if not chunk:
break
self._insert_rows(chunk, replace, skip_duplicates, ignore_extra_fields)
return
# Single batch insert (original behavior)
self._insert_rows(rows, replace, skip_duplicates, ignore_extra_fields)
def _insert_rows(self, rows, replace, skip_duplicates, ignore_extra_fields):
"""
Internal helper to insert a batch of rows.
Parameters
----------
rows : iterable
Iterable of rows to insert.
replace : bool
If True, use REPLACE instead of INSERT.
skip_duplicates : bool
If True, use ON DUPLICATE KEY UPDATE.
ignore_extra_fields : bool
If True, ignore unknown fields.
"""
# collects the field list from first row (passed by reference)
field_list = []
rows = list(self.__make_row_to_insert(row, field_list, ignore_extra_fields) for row in rows)
if rows:
try:
# Handle empty field_list (all-defaults insert)
if field_list:
fields_clause = f"({','.join(self.adapter.quote_identifier(f) for f in field_list)})"
else:
fields_clause = "()"
# Build duplicate clause (backend-agnostic)
if skip_duplicates:
duplicate = self.adapter.skip_duplicates_clause(self.full_table_name, self.primary_key)
else:
duplicate = ""
command = "REPLACE" if replace else "INSERT"
placeholders = ",".join("(" + ",".join(row["placeholders"]) + ")" for row in rows)
query = f"{command} INTO {self.from_clause()}{fields_clause} VALUES {placeholders}{duplicate}"
self.connection.query(
query,
args=list(itertools.chain.from_iterable((v for v in r["values"] if v is not None) for r in rows)),
)
except UnknownAttributeError as err:
raise err.suggest("To ignore extra fields in insert, set ignore_extra_fields=True")
except DuplicateError as err:
raise err.suggest("To ignore duplicate entries in insert, set skip_duplicates=True")
def insert_dataframe(self, df, index_as_pk=None, **insert_kwargs):
"""
Insert DataFrame with explicit index handling.
This method provides symmetry with to_pandas(): data fetched with to_pandas()
(which sets primary key as index) can be modified and re-inserted using
insert_dataframe() without manual index manipulation.
Parameters
----------
df : pandas.DataFrame
DataFrame to insert.
index_as_pk : bool, optional
How to handle DataFrame index:
- None (default): Auto-detect. Use index as primary key if index names
match primary_key columns. Drop if unnamed RangeIndex.
- True: Treat index as primary key columns. Raises if index names don't
match table primary key.
- False: Ignore index entirely (drop it).
**insert_kwargs
Passed to insert() - replace, skip_duplicates, ignore_extra_fields,
allow_direct_insert, chunk_size.
Examples
--------
Round-trip with to_pandas():
>>> df = table.to_pandas() # PK becomes index
>>> df['value'] = df['value'] * 2 # Modify data
>>> table.insert_dataframe(df) # Auto-detects index as PK
Explicit control:
>>> table.insert_dataframe(df, index_as_pk=True) # Use index
>>> table.insert_dataframe(df, index_as_pk=False) # Ignore index
"""
if not isinstance(df, pandas.DataFrame):
raise DataJointError("insert_dataframe requires a pandas DataFrame")
# Auto-detect if index should be used as PK
if index_as_pk is None:
index_as_pk = self._should_index_be_pk(df)
# Validate index if using as PK
if index_as_pk:
self._validate_index_columns(df)
# Prepare rows
if index_as_pk:
rows = df.reset_index(drop=False).to_records(index=False)
else:
rows = df.reset_index(drop=True).to_records(index=False)
self.insert(rows, **insert_kwargs)
def _should_index_be_pk(self, df) -> bool:
"""
Auto-detect if DataFrame index should map to primary key.
Returns True if:
- Index has named columns that exactly match the table's primary key
Returns False if:
- Index is unnamed RangeIndex (synthetic index)
- Index names don't match primary key
"""
# RangeIndex with no name -> False (synthetic index)
if df.index.names == [None]:
return False
# Check if index names match PK columns
index_names = set(n for n in df.index.names if n is not None)
return index_names == set(self.primary_key)
def _validate_index_columns(self, df):
"""Validate that index columns match the table's primary key."""
index_names = [n for n in df.index.names if n is not None]
if set(index_names) != set(self.primary_key):
raise DataJointError(
f"DataFrame index columns {index_names} do not match "
f"table primary key {list(self.primary_key)}. "
f"Use index_as_pk=False to ignore index, or reset_index() first."
)
def delete_quick(self, get_count=False):
"""
Deletes the table without cascading and without user prompt.
If this table has populated dependent tables, this will fail.
"""
query = "DELETE FROM " + self.full_table_name + self.where_clause()
cursor = self.connection.query(query)
# Use cursor.rowcount (DB-API 2.0 standard, works for both MySQL and PostgreSQL)
count = cursor.rowcount if get_count else None
return count
def delete(
self,
transaction: bool = True,
prompt: bool | None = None,
part_integrity: str = "enforce",
) -> int:
"""
Deletes the contents of the table and its dependent tables, recursively.
Args:
transaction: If `True`, use of the entire delete becomes an atomic transaction.
This is the default and recommended behavior. Set to `False` if this delete is
nested within another transaction.
prompt: If `True`, show what will be deleted and ask for confirmation.
If `False`, delete without confirmation. Default is `dj.config['safemode']`.
part_integrity: Policy for master-part integrity. One of:
- ``"enforce"`` (default): Error if parts would be deleted without masters.
- ``"ignore"``: Allow deleting parts without masters (breaks integrity).
- ``"cascade"``: Also delete masters when parts are deleted (maintains integrity).
Returns:
Number of deleted rows (excluding those from dependent tables).
Raises:
DataJointError: Delete exceeds maximum number of delete attempts.
DataJointError: When deleting within an existing transaction.
DataJointError: Deleting a part table before its master (when part_integrity="enforce").
ValueError: Invalid part_integrity value.
"""