Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
65 commits
Select commit Hold shift + click to select a range
67e41ef
Fixed #367
dimitri-yatsenko Oct 12, 2017
f89bf0e
Merge branch 'master' of https://github.com/datajoint/datajoint-python
dimitri-yatsenko Oct 12, 2017
159cb51
fixed dependencies
dimitri-yatsenko Oct 12, 2017
bb88117
implemented the Union operator
dimitri-yatsenko Oct 13, 2017
9703126
bugfix in populate
dimitri-yatsenko Oct 13, 2017
4fa1abd
fixed a bug in server-side insert with missing attributes
dimitri-yatsenko Oct 13, 2017
d6b9f2a
work on cascading delete
dimitri-yatsenko Oct 19, 2017
c35ed7a
Merge branch 'master' of https://github.com/dimitri-yatsenko/datajoin…
dimitri-yatsenko Oct 19, 2017
7299058
fixed #375 -- added the max_calls argument to populate
dimitri-yatsenko Oct 19, 2017
3baf487
simplified insert from select
dimitri-yatsenko Oct 20, 2017
4969c36
consolidating the use of hashes
dimitri-yatsenko Oct 20, 2017
ce774be
added module `external` for handling external storage
dimitri-yatsenko Oct 20, 2017
ad650b0
minor fix in external, work in progress
dimitri-yatsenko Oct 20, 2017
860d04b
minor
dimitri-yatsenko Oct 20, 2017
2144b0f
changed how external storage is configured
dimitri-yatsenko Oct 20, 2017
cfc1e21
minor bug
dimitri-yatsenko Oct 20, 2017
0195cfc
minor formatting
dimitri-yatsenko Oct 20, 2017
d821bcf
removed the JobManager class -- it was never used
dimitri-yatsenko Oct 20, 2017
183b324
bugfix from previous commit
dimitri-yatsenko Oct 20, 2017
6164eb5
renamed the display_progress argument in populate()
dimitri-yatsenko Oct 20, 2017
96f0d20
Merge branch 'master' of https://github.com/dimitri-yatsenko/datajoin…
dimitri-yatsenko Oct 20, 2017
b37175b
rolled back unintended changes in delete
dimitri-yatsenko Oct 20, 2017
9688e5d
fixed typo JobsTable -> JobTable
dimitri-yatsenko Oct 20, 2017
bcc0048
fixed bugs introduced in recent commits
dimitri-yatsenko Oct 20, 2017
28208c2
Merge branch 'master' of https://github.com/datajoint/datajoint-python
dimitri-yatsenko Oct 20, 2017
04b1829
fixed test_requirements
dimitri-yatsenko Oct 20, 2017
1c8e071
fixed indentation
dimitri-yatsenko Oct 20, 2017
bb11c1b
minor
dimitri-yatsenko Oct 20, 2017
9fc36b4
minor
dimitri-yatsenko Oct 20, 2017
9fca90f
minor code refactor in schema.py
dimitri-yatsenko Oct 22, 2017
7069dad
improved the error message in autopopulate
dimitri-yatsenko Oct 22, 2017
3bc28c5
correction to previous commit
dimitri-yatsenko Oct 22, 2017
a3d1a53
Merge branch 'master' of https://github.com/datajoint/datajoint-python
dimitri-yatsenko Oct 24, 2017
d9cca7b
Merge branch 'master' of https://github.com/dimitri-yatsenko/datajoin…
dimitri-yatsenko Oct 24, 2017
1b37ee9
typo
dimitri-yatsenko Oct 24, 2017
cf3cf0c
made `make` and acceptable name for the populate callback (issue #387)
dimitri-yatsenko Oct 25, 2017
85b6587
small bugfix for rare cases with multiple inheritance
dimitri-yatsenko Oct 27, 2017
f936073
minor fix
dimitri-yatsenko Oct 27, 2017
2b622c1
Merge branch 'master' of https://github.com/dimitri-yatsenko/datajoin…
dimitri-yatsenko Oct 27, 2017
5270d80
minor fixes
dimitri-yatsenko Oct 29, 2017
85502b0
Merge branch 'master' of https://github.com/dimitri-yatsenko/datajoin…
dimitri-yatsenko Oct 30, 2017
bdba20d
undid an unintended change in delete
dimitri-yatsenko Oct 30, 2017
919efba
implemented declaration of external fields
dimitri-yatsenko Oct 30, 2017
e30dfb2
added tests for external storage
dimitri-yatsenko Oct 30, 2017
259950d
minor cleanup
dimitri-yatsenko Oct 30, 2017
3a7f416
minor cleanup
dimitri-yatsenko Oct 30, 2017
3594c67
added external storage tests
dimitri-yatsenko Nov 5, 2017
7eb114c
Merge branch 'master' of https://github.com/datajoint/datajoint-python
dimitri-yatsenko Nov 5, 2017
4d1af79
Completed basic implementation of external storage.
dimitri-yatsenko Nov 5, 2017
4a58a9a
ERD does not show dependencies on external storage
dimitri-yatsenko Nov 5, 2017
1ca0b09
again, the ERD no longer includes references to ~external
dimitri-yatsenko Nov 5, 2017
add950f
fixed #328: the jobs table now records the error stack
dimitri-yatsenko Nov 5, 2017
90c021e
fixes for #328
dimitri-yatsenko Nov 5, 2017
782a9a5
fixed #388 -- a more elegant way to skip duplicates in insert
dimitri-yatsenko Nov 5, 2017
383595d
followup to previous commit
dimitri-yatsenko Nov 5, 2017
794dc47
made insert from query more consistent with insert from variables
dimitri-yatsenko Nov 5, 2017
5ab3381
fixed issue #381 -- better error messages for syntax errors in declar…
dimitri-yatsenko Nov 5, 2017
4b2671e
typo from previous commit
dimitri-yatsenko Nov 6, 2017
9a0b902
set the strict mode at connection time
dimitri-yatsenko Nov 6, 2017
7302571
set sql_mode in connection
dimitri-yatsenko Nov 6, 2017
569881a
updated the sql_mode
dimitri-yatsenko Nov 6, 2017
86c2480
added tests for union and for external storage. Other minor fixes bas…
dimitri-yatsenko Nov 13, 2017
6f7c6bd
improved documentation and error messages for fetch and fetch1. Fixe…
dimitri-yatsenko Nov 14, 2017
8018a9d
added tests for external storage
dimitri-yatsenko Nov 15, 2017
7627569
changed the shape of the computed nodes in the ERD to elipse to avoid…
dimitri-yatsenko Nov 15, 2017
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
implemented declaration of external fields
  • Loading branch information
dimitri-yatsenko committed Oct 30, 2017
commit 919efba42aeb614fdf4e0325b794b7a444d9a0e9
9 changes: 6 additions & 3 deletions datajoint/base_relation.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,14 @@ def context(self):

def declare(self):
"""
Loads the table heading. If the table is not declared, use self.definition to declare
Use self.definition to declare the table in the database
"""
try:
self.connection.query(
declare(self.full_table_name, self.definition, self._context))
sql, uses_external = declare(self.full_table_name, self.definition, self._context)
if uses_external:
# trigger the creation of the external hash lookup for the current schema
sql = sql.format(external_table_name=self.connection.schemas[self.database].external_table)
self.connection.query(sql)
except pymysql.OperationalError as error:
if error.args[0] == server_error_codes['command denied']:
logger.warning(error.args[1])
Expand Down
48 changes: 41 additions & 7 deletions datajoint/declare.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@
import pyparsing as pp
import logging

from . import DataJointError
from . import DataJointError, config

STORE_NAME_LENGTH = 8
HASH_DATA_TYPE = 'varchar(43)'

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -114,6 +117,7 @@ def declare(full_table_name, definition, context):
attribute_sql = []
foreign_key_sql = []
index_sql = []
uses_external = False

for line in definition:
if line.startswith('#'): # additional comments are ignored
Expand All @@ -127,7 +131,8 @@ def declare(full_table_name, definition, context):
elif re.match(r'^(unique\s+)?index[^:]*$', line, re.I): # index
index_sql.append(line) # the SQL syntax is identical to DataJoint's
else:
name, sql = compile_attribute(line, in_key)
name, sql, is_external = compile_attribute(line, in_key, foreign_key_sql)
uses_external = uses_external or is_external
if in_key and name not in primary_key:
primary_key.append(name)
if name not in attributes:
Expand All @@ -141,16 +146,17 @@ def declare(full_table_name, definition, context):
['PRIMARY KEY (`' + '`,`'.join(primary_key) + '`)'] +
foreign_key_sql +
index_sql) +
'\n) ENGINE=InnoDB, COMMENT "%s"' % table_comment)
'\n) ENGINE=InnoDB, COMMENT "%s"' % table_comment), uses_external


def compile_attribute(line, in_key=False):
def compile_attribute(line, in_key, foreign_key_sql):
"""
Convert attribute definition from DataJoint format to SQL

:param line: attribution line
:param in_key: set to True if attribute is in primary key set
:returns: (name, sql) -- attribute name and sql code for its declaration
:param foreign_key_sql:
:returns: (name, sql, is_external) -- attribute name and sql code for its declaration
"""

try:
Expand All @@ -177,5 +183,33 @@ def compile_attribute(line, in_key=False):
else:
match['default'] = 'NOT NULL'
match['comment'] = match['comment'].replace('"', '\\"') # escape double quotes in comment
sql = ('`{name}` {type} {default}' + (' COMMENT "{comment}"' if match['comment'] else '')).format(**match)
return match['name'], sql

is_external = match['type'] == 'external' or match['type'].startswith('external_')
if not is_external:
sql = ('`{name}` {type} {default}' + (' COMMENT "{comment}"'
if match['comment'] else '')).format(**match)
else:
# process externally stored attribute
if in_key:
raise DataJointError('External attributes cannot be primary.')
if match['type'] not in config:
raise DataJointError('The external store `{type}` is not configured.'.format(**match))
if len(match['type']) > STORE_NAME_LENGTH + STORE_NAME_LENGTH + 1:
raise DataJointError(
'The external store name `{type}` is too long. Must be <={max_len} characters.'.format(
max_len=STORE_NAME_LENGTH, **match))
sql = """
`_{name}` char({store_name_len}) COMMENT "{type}",
`{name}` {hash_type} {default}{comment}'
""".format(
comment=' COMMENT "{comment}"' if match['comment'] else '',
hash_type=HASH_DATA_TYPE,
store_name_len=STORE_NAME_LENGTH,
**match)
foreign_key_sql.append(
"""
FOREIGN KEY (`_{name}`,`name`) REFERENCES {{external_table}} (`store`, `hash`)
ON UPDATE RESTRICT ON DELETE RESTRICT
""".format(**match))

return match['name'], sql, is_external
74 changes: 38 additions & 36 deletions datajoint/external.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import os
import pymysql
from . import config, DataJointError
from .hash import long_hash
from .blob import pack, unpack
from .base_relation import BaseRelation
from .declare import HASH_DATA_TYPE, STORE_NAME_LENGTH


class ExternalTable(BaseRelation):
"""
The table tracking externally stored objects
The table tracking externally stored objects.
Declare as ExternalTable(connection, database)
"""
def __init__(self, arg, database=None):
if isinstance(arg, ExternalTable):
Expand All @@ -29,13 +30,13 @@ def __init__(self, arg, database=None):
def definition(self):
return """
# external storage tracking
store :char(8) # the name of external store
hash :char(43) # the hash of stored object
store :char({store_name_length}) # the name of external store
hash :{hash_data_type} # the hash of stored object
---
count = 1 :int # reference count
size :bigint unsigned # size of object in bytes
timestamp=CURRENT_TIMESTAMP :timestamp # automatic timestamp
"""
""".format(store_name_length=STORE_NAME_LENGTH, hash_data_type=HASH_DATA_TYPE)

@property
def table_name(self):
Expand All @@ -45,43 +46,42 @@ def put(self, store, obj):
"""
put an object in external store
"""
# serialize object
# serialize object
blob = pack(obj)
hash = long_hash(blob)

# write object
# write object
try:
spec = config['external.%s' % store]
except KeyError:
raise DataJointError('storage.%s is not configured' % store)

if spec['protocol'] == 'file':
if spec['protocol'] == 'file':
folder = os.path.join(spec['location'], self.database)
full_path = os.path.join(folder, hash)
if not os.path.isfile(full_path):
try:
with open(full_path, 'wb') as f:
with open(full_path, 'wb') as f:
f.write(blob)
except FileNotFoundError:
os.makedirs(folder)
with open(full_path, 'wb') as f:
f.write(blob)
with open(full_path, 'wb') as f:
f.write(blob)
else:
raise DataJointError('Unknown external storage %s' % store)

# insert tracking info
query = """INSERT INTO `{db}`.`{table}` (store, hash, size) VALUES ({store}, {hash}, {size})
ON DUPLICATE KEY count=count+1, timestamp=CURRENT_TIMESTAMP""".format(
db=self.database,
table=self.table_name,
store=store,
hash=hash,
size=len(blob))
self.connection.

# insert tracking info
self.connection.query(
"""
INSERT INTO `{db}`.`{table}` (store, hash, size) VALUES ({store}, {hash}, {size})
ON DUPLICATE KEY count=count+1, timestamp=CURRENT_TIMESTAMP""".format(
db=self.database,
table=self.table_name,
store=store,
hash=hash,
size=len(blob)))
return hash


def get(self, store, hash):
"""
get an object from external store
Expand All @@ -91,26 +91,28 @@ def get(self, store, hash):
except KeyError:
raise DataJointError('storage.%s is not configured' % store)

if spec['protocol'] == 'file':
if spec['protocol'] == 'file':
full_path = os.path.join(spec['location'], self.database, hash)
try:
with open(full_path, 'rb') as f:
blob = f.read()
except FileNotFoundError:
raise DataJointError('Lost external blob')
try:
with open(full_path, 'rb') as f:
blob = f.read()
except FileNotFoundError:
raise DataJointError('Lost external blob')
else:
raise DataJointError('Unknown external storage %s' % store)

return unpack(blob)

return unpack(blob)

def remove(self, store, hash)
def remove(self, store, hash):
"""
delete an object from external store
"""
# decrement count
query = "UPDATE `{db}`.`{table}` count=count-1 WHERE store={store} and hash={hash}".format(
db=self.database,
table=self.table_name,
store=store,
hash=hash)
self.connection.query(
"""
UPDATE `{db}`.`{table}` count=count-1 WHERE store={store} and hash={hash}
""".format(
db=self.database,
table=self.table_name,
store=store,
hash=hash))
17 changes: 14 additions & 3 deletions datajoint/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from . import conn, DataJointError, config
from .erd import ERD
from .jobs import JobTable
from .external import ExternalTable
from .heading import Heading
from .utils import user_choice, to_camel_case
from .user_relations import Part, Computed, Imported, Manual, Lookup
Expand Down Expand Up @@ -51,7 +52,8 @@ def __init__(self, database, context, connection=None, create_tables=True):
self.connection = connection
self.context = context
self.create_tables = create_tables
self._jobs=None
self._jobs = None
self._external = None
if not self.exists:
if not self.create_tables:
raise DataJointError("Database named `{database}` was not defined. "
Expand Down Expand Up @@ -212,16 +214,25 @@ def __call__(self, cls):
def jobs(self):
"""
schema.jobs provides a view of the job reservation table for the schema
:return: jobs relation
:return: jobs table
"""
if self._jobs is None:
self._jobs = JobTable(self.connection, self.database)
return self._jobs

@property
def external_table(self):
"""
schema.external provides a view of the external hash table for the schema
:return: external table
"""
if self._external is None:
self._external = ExternalTable(self.connection, self.database)
return self._external

def erd(self):
# get the caller's locals()
import inspect
frame = inspect.currentframe()
context = frame.f_back.f_locals
return ERD(self, context=context)