├── gurglefish ├── drivers │ ├── __init__.py │ └── postgresql │ │ ├── __init__.py │ │ └── Driver.py ├── logging.yml ├── objects │ ├── __init__.py │ ├── files.py │ ├── sobject.py │ └── connections.py ├── __main__.py ├── __init__.py ├── config.py ├── sfimport.py ├── context.py ├── transformutils.py ├── tools.py ├── sfarchive.py ├── DriverManager.py ├── FileManager.py ├── schema.py ├── sfexport.py └── sfapi.py ├── upload.sh ├── .gitignore ├── requirements.txt ├── gurglefish-sketch.jpg ├── main.py ├── Pipfile ├── setup.py ├── Pipfile.lock ├── README.md └── LICENSE /gurglefish/drivers/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /upload.sh: -------------------------------------------------------------------------------- 1 | twine upload dist/* 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__ 2 | .idea 3 | build/ 4 | dist/ 5 | *.egg-info/ 6 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | pyyaml 2 | requests 3 | fastcache 4 | psycopg2-binary 5 | arrow 6 | -------------------------------------------------------------------------------- /gurglefish-sketch.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mlsmithjr/gurglefish/HEAD/gurglefish-sketch.jpg -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | 2 | from gurglefish import sfarchive 3 | 4 | # 5 | # stub for running gurglefish as a package while developing and testing. 6 | # 7 | 8 | sfarchive.main() 9 | -------------------------------------------------------------------------------- /Pipfile: -------------------------------------------------------------------------------- 1 | [[source]] 2 | url = "https://pypi.org/simple" 3 | verify_ssl = true 4 | name = "pypi" 5 | 6 | [packages] 7 | requests = "*" 8 | pyyaml = "*" 9 | arrow = "*" 10 | fastcache = "*" 11 | 12 | [dev-packages] 13 | 14 | [requires] 15 | python_version = "3.7" 16 | -------------------------------------------------------------------------------- /gurglefish/logging.yml: -------------------------------------------------------------------------------- 1 | version: 1 2 | formatters: 3 | simple: 4 | format: '%(asctime)s - %(levelname)5s - %(name)10s - %(message)s' 5 | handlers: 6 | console: 7 | class: logging.StreamHandler 8 | level: DEBUG 9 | formatter: simple 10 | stream: ext://sys.stdout 11 | loggers: 12 | main: 13 | level: DEBUG 14 | handlers: [console] 15 | propagate: no 16 | schema: 17 | level: DEBUG 18 | handlers: [console] 19 | propagate: no 20 | salesforce: 21 | level: DEBUG 22 | handlers: [console] 23 | propagate: no 24 | dbdriver: 25 | level: DEBUG 26 | handlers: [console] 27 | propagate: no 28 | root: 29 | level: DEBUG 30 | handlers: [console] -------------------------------------------------------------------------------- /gurglefish/objects/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018, 2019 Marshall L Smith Jr 2 | # 3 | # This file is part of Gurglefish. 4 | # 5 | # Gurglefish is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # Gurglefish is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with Gurglefish. If not, see . -------------------------------------------------------------------------------- /gurglefish/drivers/postgresql/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018, 2019 Marshall L Smith Jr 2 | # 3 | # This file is part of Gurglefish. 4 | # 5 | # Gurglefish is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # Gurglefish is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with Gurglefish. If not, see . 17 | from .Driver import Driver 18 | -------------------------------------------------------------------------------- /gurglefish/__main__.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018, 2019 Marshall L Smith Jr 2 | # 3 | # This file is part of Gurglefish. 4 | # 5 | # Gurglefish is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # Gurglefish is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with Gurglefish. If not, see . 17 | from . import sfarchive 18 | 19 | 20 | def main(): 21 | sfarchive.main() 22 | -------------------------------------------------------------------------------- /gurglefish/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018, 2019 Marshall L Smith Jr 2 | # 3 | # This file is part of Gurglefish. 4 | # 5 | # Gurglefish is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # Gurglefish is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with Gurglefish. If not, see . 17 | 18 | __version__ = '1.1.9' 19 | __author__ = 'Marshall L Smith Jr ' 20 | __license__ = 'GPLv3' 21 | 22 | -------------------------------------------------------------------------------- /gurglefish/config.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018, 2019 Marshall L Smith Jr 2 | # 3 | # This file is part of Gurglefish. 4 | # 5 | # Gurglefish is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # Gurglefish is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with Gurglefish. If not, see . 17 | __author__ = 'Marshall L Smith Jr.' 18 | 19 | import os 20 | 21 | storagedir = '/var/lib/gurglefish' 22 | 23 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 24 | 25 | -------------------------------------------------------------------------------- /gurglefish/sfimport.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018, 2019 Marshall L Smith Jr 2 | # 3 | # This file is part of Gurglefish. 4 | # 5 | # Gurglefish is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # Gurglefish is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with Gurglefish. If not, see . 17 | from gurglefish.schema import SFSchemaManager 18 | 19 | __author__ = 'mark' 20 | 21 | 22 | class SFImporter: 23 | context = None 24 | 25 | def __init__(self, context, schema_mgr : SFSchemaManager): 26 | self.context = context 27 | self.storagedir = context.filemgr.exportdir 28 | self.schema_mgr = schema_mgr 29 | 30 | def bulk_load(self, sobject_name): 31 | 32 | if not self.context.dbdriver.table_exists(sobject_name): 33 | self.schema_mgr.create_table(sobject_name) 34 | 35 | return self.context.dbdriver.import_native(sobject_name) 36 | -------------------------------------------------------------------------------- /gurglefish/context.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018, 2019 Marshall L Smith Jr 2 | # 3 | # This file is part of Gurglefish. 4 | # 5 | # Gurglefish is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # Gurglefish is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with Gurglefish. If not, see . 17 | from gurglefish import config 18 | from gurglefish.DriverManager import DbDriverMeta 19 | from gurglefish.FileManager import FileManager 20 | from gurglefish.objects.connections import ConnectionConfig 21 | from gurglefish.sfapi import SFClient 22 | 23 | 24 | class Context: 25 | 26 | def __init__(self, envname: str, env: ConnectionConfig, dbdriver: DbDriverMeta, sfclient: SFClient): 27 | self.env = env 28 | self.envname = envname 29 | self.driver = dbdriver 30 | self.sfapi = sfclient 31 | self.filemgr = FileManager(config.storagedir, self.env.id) 32 | 33 | @property 34 | def config_env(self) -> ConnectionConfig: 35 | return self.env 36 | 37 | @property 38 | def dbdriver(self) -> DbDriverMeta: 39 | return self.driver 40 | 41 | @property 42 | def sfclient(self) -> SFClient: 43 | return self.sfapi 44 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import setuptools 2 | import sys 3 | import re 4 | import os 5 | 6 | if sys.version_info < (3, 6): 7 | print('gurglefish requires at least Python 3.6 to run.') 8 | sys.exit(1) 9 | 10 | with open(os.path.join('gurglefish', '__init__.py'), encoding='utf-8') as f: 11 | version = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", f.read(), re.M).group(1) 12 | 13 | with open('README.md', 'r') as fh: 14 | long_description = fh.read() 15 | 16 | setuptools.setup( 17 | name='gurglefish', 18 | version=version, 19 | python_requires='>=3.6', 20 | author='Marshall L Smith Jr', 21 | author_email='marshallsmithjr@gmail.com', 22 | description='Sync and maintain Salesforce sobjects in a Postgres database', 23 | long_description = long_description, 24 | long_description_content_type = 'text/markdown', 25 | url='https://github.com/mlsmithjr/gurglefish', 26 | include_package_data=True, 27 | # data_files=[('share/doc/gurglefish', ['README.md', 'LICENSE' ]), ('config', ['gurglefish/logging.yml'])], 28 | packages=setuptools.find_packages(), 29 | install_requires=['requests==2.31.0', 'psycopg2-binary==2.8', 'fastcache==1.0.2', 'arrow==0.15.1', 'python-dateutil==2.8.0', 'pyyaml==5.1'], 30 | entry_points={"console_scripts": ["gurglefish=gurglefish.sfarchive:main"]}, 31 | classifiers=[ 32 | 'Programming Language :: Python :: 3', 33 | 'Environment :: Console', 34 | 'Topic :: Database', 35 | 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 36 | 'Intended Audience :: System Administrators', 37 | 'Natural Language :: English', 38 | 'Operating System :: POSIX :: Linux', 39 | 'Operating System :: MacOS :: MacOS X', 40 | 'Operating System :: Microsoft :: Windows :: Windows 10', 41 | ], 42 | keywords='salesforce sobject database synchronization snapshots postgres postgresql', 43 | ) 44 | 45 | -------------------------------------------------------------------------------- /gurglefish/objects/files.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018, 2019 Marshall L Smith Jr 2 | # 3 | # This file is part of Gurglefish. 4 | # 5 | # Gurglefish is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # Gurglefish is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with Gurglefish. If not, see . 17 | 18 | from typing import Dict 19 | 20 | 21 | class LocalTableConfig(object): 22 | 23 | def __init__(self, adict: Dict): 24 | self.item = adict 25 | 26 | @property 27 | def dict(self): 28 | return self.item 29 | 30 | @property 31 | def name(self): 32 | return self.item['name'] 33 | 34 | @property 35 | def enabled(self): 36 | return self.item.get('enabled', False) 37 | 38 | @enabled.setter 39 | def enabled(self, val): 40 | self.item['enabled'] = val 41 | 42 | @property 43 | def auto_drop_columns(self): 44 | return self.item.get('auto_drop_columns', True) 45 | 46 | @property 47 | def auto_create_columns(self): 48 | return self.item.get('auto_create_columns', True) 49 | 50 | @property 51 | def auto_scrub(self) -> str: 52 | return self.item.get('auto_scrub', "daily") 53 | 54 | @property 55 | def sync_schedule(self): 56 | return self.item.get('sync_schedule', 'auto') 57 | 58 | @property 59 | def package_name(self): 60 | return self.item.get('package', None) 61 | 62 | @property 63 | def use_bulkapi(self) -> bool: 64 | return self.item.get('bulkapi', False) 65 | -------------------------------------------------------------------------------- /gurglefish/transformutils.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018, 2019 Marshall L Smith Jr 2 | # 3 | # This file is part of Gurglefish. 4 | # 5 | # Gurglefish is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # Gurglefish is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with Gurglefish. If not, see . 17 | from datetime import datetime, time, date 18 | 19 | import decimal 20 | 21 | 22 | def id(rec, name, fieldlen): 23 | if name in rec and rec[name] != None: 24 | if len(rec[name]) > 15: 25 | return rec[name][0:15] 26 | return rec[name] 27 | return None 28 | 29 | 30 | def inte(rec, name, fieldlen): 31 | if name in rec and rec[name] is not None: 32 | return rec[name] 33 | return None 34 | 35 | 36 | def bl(rec, name, fieldlen): 37 | if name in rec and rec[name] is not None: 38 | return rec[name] 39 | return None 40 | 41 | 42 | def dt(rec, name, fieldlen): 43 | if name in rec and rec[name] is not None: 44 | return py_date(rec[name]) 45 | return None 46 | 47 | 48 | def tm(rec, name, fieldlen): 49 | if name in rec and rec[name] is not None: 50 | return py_time(rec[name]) 51 | return None 52 | 53 | 54 | def ts(rec, name, fieldlen): 55 | if name in rec and rec[name] is not None: 56 | return py_timestamp(rec[name]) 57 | return None 58 | 59 | 60 | def db(rec, name, fieldlen): 61 | if name in rec and rec[name] is not None: 62 | d = decimal.Decimal(rec[name]) 63 | s = str(d) 64 | if 0 < fieldlen < len(s): 65 | # truncate 66 | return float(s[0:fieldlen]) 67 | return rec[name] 68 | return None 69 | 70 | 71 | def st(rec, name, fieldlen=0): 72 | if name in rec and rec[name] is not None: 73 | node = rec[name] 74 | return scrub(node[0:fieldlen]) 75 | return None 76 | 77 | 78 | def stsub(rec, name, subname, fieldlen=0): 79 | if name in rec and rec[name] is not None: 80 | node = rec[name] 81 | if subname in node: 82 | val = node[subname][0:fieldlen] 83 | return scrub(val) 84 | return None 85 | return None 86 | 87 | 88 | def py_timestamp(t) -> datetime: 89 | return datetime.strptime(t[0:19], '%Y-%m-%dT%H:%M:%S') 90 | 91 | 92 | def py_date(d) -> date: 93 | return datetime.strptime(d, '%Y-%m-%d').date() 94 | 95 | 96 | def py_time(t) -> time: 97 | return datetime.strptime(t[0:8], "%H:%M:%S").time() 98 | 99 | 100 | def scrub(s): 101 | if '\\t' in s or '\0' in s: 102 | s = s.replace('\\t', ' ') 103 | s = s.replace('\0', '') 104 | return s 105 | -------------------------------------------------------------------------------- /gurglefish/tools.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018, 2019 Marshall L Smith Jr 2 | # 3 | # This file is part of Gurglefish. 4 | # 5 | # Gurglefish is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # Gurglefish is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with Gurglefish. If not, see . 17 | import datetime 18 | import os 19 | from typing import Optional 20 | 21 | import yaml 22 | 23 | from gurglefish import DriverManager 24 | from gurglefish.context import Context 25 | from gurglefish.objects.connections import Connections, ConnectionConfig 26 | from gurglefish.sfapi import SFClient 27 | import logging.config 28 | 29 | _log = logging.getLogger('main') 30 | 31 | 32 | def setup_env(envname) -> Optional[Context]: 33 | 34 | logconfig = load_log_config() 35 | logging.config.dictConfig(logconfig) 36 | 37 | mde = Connections() 38 | env: ConnectionConfig = mde.get_db_env(envname) 39 | if env is None: 40 | _log.error(f'Configuration for {envname} not found') 41 | exit(1) 42 | 43 | sf = SFClient() 44 | try: 45 | sf.login(env.consumer_key, env.consumer_secret, env.login, env.password, env.authurl) 46 | except Exception as ex: 47 | _log.error(f'Unable to connect to {env.authurl} as {env.login}: {str(ex)}') 48 | return None 49 | 50 | return Context(envname, env, get_db_connection(envname), sf) 51 | 52 | 53 | def get_db_connection(envname: str) -> DriverManager.DbDriverMeta: 54 | mde = Connections() 55 | env: ConnectionConfig = mde.get_db_env(envname) 56 | if env is None: 57 | _log.error(f'Configuration for {envname} not found') 58 | exit(1) 59 | 60 | driver = DriverManager.Manager().get_driver(env.dbvendor) 61 | driver.connect(env) 62 | return driver 63 | 64 | 65 | def json_serial(obj): 66 | """JSON serializer for objects not serializable by default json code""" 67 | 68 | if isinstance(obj, datetime.datetime): 69 | serial = obj.isoformat() 70 | return serial 71 | return str(obj) 72 | 73 | 74 | def dict_list_to_dict(alist, keyfield): 75 | assert(keyfield is not None) 76 | assert(alist is not None) 77 | 78 | result = dict() 79 | for item in alist: 80 | key = item[keyfield] 81 | result[key] = item 82 | return result 83 | 84 | 85 | def sf_timestamp(t: datetime): 86 | s = t.isoformat()[0:19] 87 | s += '+00:00' 88 | return s 89 | 90 | 91 | def parse_timestamp(t): 92 | return datetime.datetime.strptime(t[0:19], '%Y-%m-%dT%H:%M:%S') 93 | 94 | 95 | def load_file_items(filename): 96 | with open(filename, 'r') as f: 97 | line_list = f.readlines() 98 | stripped_list = [line.strip() for line in line_list if len(line) > 0] 99 | return stripped_list 100 | 101 | 102 | def make_arg_list(args_list): 103 | processed_args = [] 104 | for arg in args_list: 105 | if len(arg) == 0: 106 | continue 107 | if arg.startswith('@'): 108 | processed_args.extend(load_file_items(arg[1:])) 109 | else: 110 | processed_args.append(arg) 111 | return processed_args 112 | 113 | 114 | def load_log_config(): 115 | path = os.path.dirname(os.path.abspath(__file__)) 116 | with open(os.path.join(path, 'logging.yml'), 'r') as configfile: 117 | _logconfig = yaml.load(configfile.read(), Loader=yaml.FullLoader) 118 | return _logconfig 119 | -------------------------------------------------------------------------------- /gurglefish/objects/sobject.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018, 2019 Marshall L Smith Jr 2 | # 3 | # This file is part of Gurglefish. 4 | # 5 | # Gurglefish is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # Gurglefish is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with Gurglefish. If not, see . 17 | 18 | from typing import Dict, Optional, Set 19 | 20 | 21 | class SFError(Exception): 22 | def __init__(self, value): 23 | self.value = value 24 | 25 | def __str__(self): 26 | return repr(self.value) 27 | 28 | 29 | class SObjectField(object): 30 | def __init__(self, field: Dict): 31 | self.field = field 32 | 33 | @property 34 | def name(self) -> str: 35 | return self.field['name'] 36 | 37 | @property 38 | def is_custom(self) -> bool: 39 | return self.field['custom'] 40 | 41 | @property 42 | def digits(self) -> int: 43 | return self.field['digits'] 44 | 45 | @property 46 | def label(self) -> str: 47 | return self.field['label'] 48 | 49 | @property 50 | def length(self) -> int: 51 | return self.field['length'] 52 | 53 | @property 54 | def precision(self) -> int: 55 | return self.field['precision'] 56 | 57 | @property 58 | def scale(self) -> int: 59 | return self.field['scale'] 60 | 61 | @property 62 | def references(self) -> [str]: 63 | return self.field.get('referenceTo', []) 64 | 65 | @property 66 | def relationship_name(self) -> str: 67 | return self.field.get('relationshipName', None) 68 | 69 | @property 70 | def get_type(self): 71 | return self.field['type'] 72 | 73 | @property 74 | def is_unique(self) -> bool: 75 | return self.field['unique'] 76 | 77 | @property 78 | def is_externalid(self) -> bool: 79 | return self.field['externalId'] 80 | 81 | @property 82 | def is_idlookup(self) -> bool: 83 | return self.field['idLookup'] 84 | 85 | 86 | class SObjectFields(object): 87 | def __init__(self, fields): 88 | self.fields = dict() 89 | for field in fields: 90 | if isinstance(field, dict): 91 | if field['type'] == 'address': 92 | continue 93 | name = field['name'] 94 | else: 95 | if field.get_type == 'address': 96 | continue 97 | name = field.name 98 | self.fields[name.lower()] = SObjectField(field) 99 | 100 | def find(self, name: str) -> Optional[SObjectField]: 101 | return self.fields.get(name.lower(), None) 102 | 103 | def names(self) -> Set: 104 | return set(self.fields.keys()) 105 | 106 | def values(self) -> [SObjectField]: 107 | return self.fields.values() 108 | 109 | def values_exportable(self) -> [Dict]: 110 | result = list() 111 | for f in self.fields.values(): 112 | result.append(f.field) 113 | return result 114 | 115 | 116 | class ColumnMap(object): 117 | def __init__(self, d: Dict): 118 | self.field = d 119 | 120 | @staticmethod 121 | def from_parts(fieldlen: int, dml: str, table_name: str, sobject_field: str, 122 | db_field: str, fieldtype: str): 123 | return ColumnMap({'fieldlen': fieldlen, 'dml': dml, 'table_name': table_name, 124 | 'sobject_field': sobject_field, 'db_field': db_field, 'fieldtype': fieldtype}) 125 | 126 | @property 127 | def fieldlen(self) -> int: 128 | return self.field['fieldlen'] 129 | 130 | @property 131 | def table_name(self) -> str: 132 | return self.field['table_name'] 133 | 134 | @property 135 | def sobject_field(self) -> str: 136 | return self.field['sobject_field'] 137 | 138 | @property 139 | def db_field(self) -> str: 140 | return self.field['db_field'] 141 | 142 | @property 143 | def field_type(self) -> str: 144 | return self.field['fieldtype'] 145 | 146 | @property 147 | def dml(self) -> str: 148 | return self.field['dml'] 149 | 150 | def as_dict(self) -> Dict: 151 | return self.field 152 | -------------------------------------------------------------------------------- /gurglefish/sfarchive.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018, 2019 Marshall L Smith Jr 2 | # 3 | # This file is part of Gurglefish. 4 | # 5 | # Gurglefish is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # Gurglefish is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with Gurglefish. If not, see . 17 | import argparse 18 | import logging.config 19 | import os 20 | import sys 21 | from typing import Dict 22 | 23 | from gurglefish import tools 24 | from gurglefish.schema import SFSchemaManager 25 | from gurglefish.sfexport import SFExporter 26 | 27 | from gurglefish.sfimport import SFImporter 28 | 29 | 30 | def main(): 31 | parser = argparse.ArgumentParser( 32 | epilog='@file arguments designate a file containing actual arguments, one per line') 33 | group = parser.add_mutually_exclusive_group() 34 | parser.add_argument("env", help="Environment/DB settings name", metavar="env_name") 35 | group.add_argument("--sync", help="sync table updates", nargs="*", metavar="sobject|@file") 36 | group.add_argument("--schema", help="load sobject schema and create tables if missing", nargs="*", metavar="sobject|@file") 37 | group.add_argument("--export", help="export full sobject data to file", nargs="+", metavar="sobject|@file") 38 | group.add_argument("--load", help="load/import full table data, table must be empty", nargs="*", 39 | metavar="sobject|@file") 40 | group.add_argument("--dump", help="dump contents of table to file", nargs="+", metavar="table|@file") 41 | parser.add_argument("--inspect", help="list available sobjects", action="store_true") 42 | #parser.add_argument("--sample", help="sample data (500 rows)", action="store_true") 43 | group.add_argument("--init", help="create config.json file for given environment", action="store_true") 44 | parser.add_argument("--enable", help="enable one or more tables to sync", nargs="+", metavar="sobject|@file") 45 | parser.add_argument("--disable", help="disable one or more tables from sync", nargs="+", metavar="sobject|@file") 46 | parser.add_argument("--scrub", help="force scrub of deleted records", action="store_true") 47 | args = parser.parse_args() 48 | 49 | envname = args.env 50 | 51 | context = tools.setup_env(envname) 52 | if context is None: 53 | exit(1) 54 | logger = logging.getLogger('main') 55 | schema_mgr = SFSchemaManager(context) 56 | 57 | if args.init: 58 | schema_mgr.initialize_config(envname) 59 | sys.exit(0) 60 | 61 | if args.inspect: 62 | thelist: [Dict] = schema_mgr.inspect() 63 | for entry in thelist: 64 | logger.info(entry['name']) 65 | sys.exit(0) 66 | 67 | if args.enable is not None: 68 | schema_mgr.enable_table_sync(args.enable, True) 69 | sys.exit(0) 70 | 71 | if args.disable is not None: 72 | schema_mgr.enable_table_sync(args.enable, False) 73 | sys.exit(0) 74 | 75 | if args.sync is not None: 76 | exp = SFExporter(context) 77 | exp.sync_tables(schema_mgr, args.scrub) 78 | 79 | if args.schema is not None: 80 | if len(args.schema) > 0: 81 | final_args = tools.make_arg_list(args.schema) 82 | schema_mgr.prepare_sobjects(final_args) 83 | else: 84 | schema_mgr.prepare_configured_sobjects() 85 | 86 | if args.export is not None: 87 | exp = SFExporter(context) 88 | table_list = tools.make_arg_list(args.export) 89 | exp.export_tables(table_list, just_sample=args.sample) 90 | 91 | if args.dump is not None: 92 | table_list = tools.make_arg_list(args.dump) 93 | for table in table_list: 94 | export_file = os.path.join(context.filemgr.exportdir, table + '.exp.gz') 95 | context.dbdriver.export_native(table, export_file) 96 | 97 | if args.load and len(args.load) > 0: 98 | imp = SFImporter(context, schema_mgr) 99 | table_list = tools.make_arg_list(args.load) 100 | for tablename in table_list: 101 | logger.info('loading {}'.format(tablename)) 102 | count = imp.bulk_load(tablename) 103 | logger.info('loaded {} records'.format(count)) 104 | 105 | 106 | if __name__ == '__main__': 107 | main() 108 | 109 | -------------------------------------------------------------------------------- /gurglefish/objects/connections.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018, 2019 Marshall L Smith Jr 2 | # 3 | # This file is part of Gurglefish. 4 | # 5 | # Gurglefish is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # Gurglefish is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with Gurglefish. If not, see . 17 | from typing import Optional 18 | 19 | __author__ = 'Marshall L Smith Jr' 20 | 21 | import os 22 | import configparser 23 | from gurglefish.config import storagedir 24 | 25 | 26 | class ConnectionConfig(object): 27 | def __init__(self, d): 28 | self.fields = d 29 | 30 | def to_dict(self): 31 | return dict([(k, v) for k, v in self.fields.items()]) 32 | 33 | @classmethod 34 | def from_dict(cls, d): 35 | return ConnectionConfig(d) 36 | 37 | def to_json(self): 38 | return dict([(k, v) for k, v in self.fields.items()]) 39 | 40 | @property 41 | def id(self): 42 | return self.fields['id'] 43 | 44 | @id.setter 45 | def id(self, i): 46 | self.fields['id'] = i 47 | 48 | @property 49 | def schema(self): 50 | s = self.fields['schema'] 51 | if s is None or len(s) == 0: 52 | s = 'public' 53 | return s 54 | 55 | @schema.setter 56 | def schema(self, name): 57 | self.fields['schema'] = name 58 | 59 | @property 60 | def login(self): 61 | return self.fields['login'] 62 | 63 | @login.setter 64 | def login(self, l): 65 | self.fields['login'] = l 66 | 67 | @property 68 | def password(self): 69 | return self.fields['password'] 70 | 71 | @password.setter 72 | def password(self, x): 73 | self.fields['password'] = x 74 | 75 | @property 76 | def consumer_key(self): 77 | return self.fields['consumer_key'] 78 | 79 | @consumer_key.setter 80 | def consumer_key(self, value): 81 | self.fields['consumer_key'] = value 82 | 83 | @property 84 | def consumer_secret(self): 85 | return self.fields['consumer_secret'] 86 | 87 | @consumer_secret.setter 88 | def consumer_secret(self, value): 89 | self.fields['consumer_secret'] = value 90 | 91 | @property 92 | def authurl(self): 93 | return self.fields['authurl'] 94 | 95 | @authurl.setter 96 | def authurl(self, value): 97 | self.fields['authurl'] = value 98 | 99 | @property 100 | def dbvendor(self): 101 | return self.fields['dbvendor'] 102 | 103 | @dbvendor.setter 104 | def dbvendor(self, value): 105 | self.fields['dbvendor'] = value 106 | 107 | @property 108 | def dbname(self): 109 | return self.fields['dbname'] 110 | 111 | @dbname.setter 112 | def dbname(self, value): 113 | self.fields['dbname'] = value 114 | 115 | @property 116 | def dbuser(self): 117 | return self.fields['dbuser'] 118 | 119 | @dbuser.setter 120 | def dbuser(self, value): 121 | self.fields['dbuser'] = value 122 | 123 | @property 124 | def dbpass(self): 125 | return self.fields['dbpass'] 126 | 127 | @dbpass.setter 128 | def dbpass(self, value): 129 | self.fields['dbpass'] = value 130 | 131 | @property 132 | def dbhost(self): 133 | return self.fields['dbhost'] 134 | 135 | @dbhost.setter 136 | def dbhost(self, value): 137 | self.fields['dbhost'] = value 138 | 139 | @property 140 | def dbport(self): 141 | return self.fields['dbport'] 142 | 143 | @dbport.setter 144 | def dbport(self, value): 145 | self.fields['dbport'] = value 146 | 147 | @property 148 | def threads(self) -> int: 149 | return min(int(self.fields.get('threads', '1')), 4) 150 | 151 | 152 | class Connections(object): 153 | def __init__(self, dbpath=None): 154 | if dbpath is None: 155 | dbpath = os.path.join(storagedir, 'connections.ini') 156 | self.dbpath = dbpath 157 | if os.path.exists(dbpath): 158 | config = configparser.ConfigParser() 159 | config.read(self.dbpath) 160 | self.data = [ConnectionConfig(config[section]) for section in config.sections()] 161 | else: 162 | self.data = [] 163 | 164 | def exists(self): 165 | return os.path.exists(self.dbpath) 166 | 167 | def close(self): 168 | pass 169 | 170 | def fetch_dblist(self): 171 | return self.data 172 | 173 | def get_db_env(self, envname) -> Optional[ConnectionConfig]: 174 | for e in self.data: 175 | if e.id == envname: 176 | return e 177 | return None 178 | -------------------------------------------------------------------------------- /gurglefish/DriverManager.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018, 2019 Marshall L Smith Jr 2 | # 3 | # This file is part of Gurglefish. 4 | # 5 | # Gurglefish is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # Gurglefish is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with Gurglefish. If not, see . 17 | 18 | import datetime 19 | import os 20 | import pkgutil 21 | from abc import ABCMeta, abstractmethod 22 | from typing import List, Optional, Dict 23 | 24 | from gurglefish.objects.connections import ConnectionConfig 25 | from gurglefish.objects.sobject import ColumnMap, SObjectFields 26 | 27 | 28 | class GetDbTablesResult(object): 29 | 30 | def __init__(self, name): 31 | self.tablename = name 32 | 33 | @property 34 | def tablename(self): 35 | return self.name 36 | 37 | @tablename.setter 38 | def tablename(self, name): 39 | self.name = name 40 | 41 | 42 | class DbNativeExporter(object): 43 | __metaclass__ = ABCMeta 44 | 45 | @abstractmethod 46 | def soql(self) -> str: 47 | pass 48 | 49 | @abstractmethod 50 | def write(self, record: Dict): 51 | pass 52 | 53 | @abstractmethod 54 | def close(self): 55 | pass 56 | 57 | 58 | class DbDriverMeta(object): 59 | __metaclass__ = ABCMeta 60 | 61 | @abstractmethod 62 | def connect(self, env: ConnectionConfig): 63 | pass 64 | 65 | @abstractmethod 66 | def create_exporter(self, sobject_name: str, ctx, just_sample=False, timestamp=None) -> DbNativeExporter: 67 | pass 68 | 69 | @abstractmethod 70 | def get_db_tables(self)-> List[GetDbTablesResult]: 71 | pass 72 | 73 | @abstractmethod 74 | def table_exists(self, table_name: str): 75 | pass 76 | 77 | @abstractmethod 78 | def get_db_columns(self, table_name: str): 79 | pass 80 | 81 | @abstractmethod 82 | def dump_ids(self, table_name: str, output_filename: str): 83 | pass 84 | 85 | @abstractmethod 86 | def make_create_table(self, fields: SObjectFields, sobject_name: str): 87 | pass 88 | 89 | @abstractmethod 90 | def make_select_statement(self, field_names: [str], sobject_name: str) -> str: 91 | pass 92 | 93 | @abstractmethod 94 | def exec_ddl(self, ddl: str): 95 | pass 96 | 97 | @abstractmethod 98 | def max_timestamp(self, tablename: str): 99 | pass 100 | 101 | @abstractmethod 102 | def format_for_export(self, trec, tablefields, fieldmap): 103 | pass 104 | 105 | @abstractmethod 106 | def make_transformer(self, sobject_name, table_name: str, fieldlist): 107 | pass 108 | 109 | @abstractmethod 110 | def maintain_indexes(self, sobject_name: str, field_defs): 111 | pass 112 | 113 | @abstractmethod 114 | def record_count(self, table_name: str): 115 | pass 116 | 117 | @abstractmethod 118 | def get_table_fields(self, table_name: str): 119 | pass 120 | 121 | @abstractmethod 122 | def delete(self, cur, table_name: str, key: str): 123 | pass 124 | 125 | @abstractmethod 126 | def upsert(self, cur, table_name: str, trec: dict, journal=None): 127 | pass 128 | 129 | @abstractmethod 130 | def import_native(self, tablename: str): 131 | pass 132 | 133 | @abstractmethod 134 | def export_native(self, table_name, output_path): 135 | pass 136 | 137 | @abstractmethod 138 | def start_sync_job(self): 139 | pass 140 | 141 | @abstractmethod 142 | def finish_sync_job(self, jobid): 143 | pass 144 | 145 | @abstractmethod 146 | def insert_sync_stats(self, jobid, table_name, sync_start, sync_end, sync_since, inserts, updates, deletes, api_calls): 147 | pass 148 | 149 | @abstractmethod 150 | def clean_house(self, date_constraint: datetime): 151 | pass 152 | 153 | @abstractmethod 154 | def alter_table_drop_columns(self, drop_field_names: [str], sobject_name: str): 155 | pass 156 | 157 | @abstractmethod 158 | def alter_table_add_columns(self, new_field_defs, sobject_name: str) -> [ColumnMap]: 159 | pass 160 | 161 | @abstractmethod 162 | def cursor(self): 163 | pass 164 | 165 | @abstractmethod 166 | def close(self): 167 | pass 168 | 169 | @abstractmethod 170 | def commit(self): 171 | pass 172 | 173 | @abstractmethod 174 | def rollback(self): 175 | pass 176 | 177 | 178 | class Manager(object): 179 | 180 | def __init__(self): 181 | self._res = {} 182 | path = os.path.dirname(os.path.abspath(__file__)) 183 | modules = pkgutil.iter_modules(path=[os.path.join(path, 'drivers')]) 184 | for finder, mod_name, ispkg in modules: 185 | toload = finder.find_module(mod_name) 186 | mod = toload.load_module(mod_name) 187 | cls = getattr(mod, 'Driver') 188 | self._res[mod_name] = cls 189 | 190 | def get_driver(self, driver_name) -> Optional[DbDriverMeta]: 191 | if driver_name in self._res: 192 | return self._res[driver_name]() 193 | return None 194 | -------------------------------------------------------------------------------- /gurglefish/FileManager.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018, 2019 Marshall L Smith Jr 2 | # 3 | # This file is part of Gurglefish. 4 | # 5 | # Gurglefish is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # Gurglefish is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with Gurglefish. If not, see . 17 | 18 | import gzip 19 | import json 20 | import os 21 | import sys 22 | from typing import Optional 23 | 24 | from gurglefish.objects.files import LocalTableConfig 25 | from gurglefish.objects.sobject import ColumnMap 26 | 27 | from gurglefish.sfapi import SObjectFields 28 | 29 | 30 | class FileManager(object): 31 | 32 | def __init__(self, basedir, envname): 33 | self.basedir = basedir 34 | self.envname = envname 35 | self.schemadir = os.path.join(basedir, 'db', envname, 'schema') 36 | self.exportdir = os.path.join(basedir, 'db', envname, 'export') 37 | 38 | if not os.path.exists(basedir): 39 | print(f'Gurglefish root director {basedir} does not exists') 40 | sys.exit(1) 41 | 42 | try: 43 | os.makedirs(self.schemadir, exist_ok=True) 44 | except PermissionError as pex: 45 | print(f'Permission denied creating {self.schemadir}') 46 | sys.exit(1) 47 | 48 | try: 49 | os.makedirs(self.exportdir, exist_ok=True) 50 | except PermissionError as pex: 51 | print(f'Permission denied creating {self.exportdir}') 52 | sys.exit(1) 53 | 54 | def create_journal(self, sobject_name): 55 | f = gzip.open(os.path.join(self.exportdir, '{}_journal.log.gz'.format(sobject_name)), 'wb') 56 | return f 57 | 58 | def get_global_filters(self): 59 | try: 60 | with open(os.path.join(self.basedir, 'global-filters.txt'), 'r') as filterfile: 61 | return filterfile.readlines() 62 | except: 63 | pass 64 | return [] 65 | 66 | def get_filters(self): 67 | try: 68 | with open(os.path.join(self.basedir, 'db', self.envname, 'filters.txt', 'r')) as filterfile: 69 | return filterfile.readlines() 70 | except: 71 | pass 72 | return [] 73 | 74 | def get_schema_list(self): 75 | return os.listdir(self.schemadir) 76 | 77 | def get_export_list(self): 78 | return os.listdir(self.exportdir) 79 | 80 | def load_translate_handler(self, sobject_name): 81 | import importlib.machinery 82 | loader = importlib.machinery.SourceFileLoader(sobject_name, os.path.join(self.schemadir, sobject_name, '{}_Transform.py'.format(sobject_name))) 83 | handler = loader.load_module(sobject_name) 84 | return handler 85 | 86 | def get_sobject_fields(self, sobject_name: str) -> Optional[SObjectFields]: 87 | os.makedirs(os.path.join(self.schemadir, sobject_name), exist_ok=True) 88 | filename = os.path.join(self.schemadir, sobject_name, sobject_name + '.json') 89 | try: 90 | with open(filename, 'r') as jsonfile: 91 | return SObjectFields(json.load(jsonfile)) 92 | except Exception: 93 | return None 94 | 95 | def save_sobject_fields(self, sobject_name: str, fields: SObjectFields): 96 | sobject_name = sobject_name.lower() 97 | os.makedirs(os.path.join(self.schemadir, sobject_name), exist_ok=True) 98 | with open(os.path.join(self.schemadir, sobject_name, '{}.json'.format(sobject_name)), 'w') as mapfile: 99 | mapfile.write(json.dumps(fields.values_exportable(), indent=4)) 100 | 101 | def get_configured_tables(self) -> [LocalTableConfig]: 102 | try: 103 | with open(os.path.join(self.basedir, 'db', self.envname, 'config.json'), 'r') as configfile: 104 | return [LocalTableConfig(t) for t in json.load(configfile)['configuration']['sobjects']] 105 | except FileNotFoundError: 106 | return None 107 | 108 | def save_configured_tables(self, new_config: [LocalTableConfig]): 109 | config = {'configuration': {'sobjects': []}} 110 | try: 111 | with open(os.path.join(self.basedir, 'db', self.envname, 'config.json'), 'r') as configfile: 112 | config = json.load(configfile) 113 | except FileNotFoundError: 114 | pass 115 | config['configuration']['sobjects'] = [t.dict for t in new_config] 116 | with open(os.path.join(self.basedir, 'db', self.envname, 'config.json'), 'w') as configfile: 117 | configfile.write(json.dumps(config, indent=4)) 118 | 119 | def get_sobject_map(self, sobject_name: str) -> [ColumnMap]: 120 | sobject_name = sobject_name.lower() 121 | with open(os.path.join(self.schemadir, sobject_name, '{}_map.json'.format(sobject_name)), 'r') as mapfile: 122 | return [ColumnMap(f) for f in json.load(mapfile)] 123 | 124 | def save_sobject_map(self, sobject_name: str, fieldmap: [ColumnMap]): 125 | sobject_name = sobject_name.lower() 126 | os.makedirs(os.path.join(self.schemadir, sobject_name), exist_ok=True) 127 | with open(os.path.join(self.schemadir, sobject_name, '{}_map.json'.format(sobject_name)), 'w') as mapfile: 128 | mapfile.write(json.dumps([f.as_dict() for f in fieldmap], indent=4)) 129 | 130 | def get_sobject_query(self, sobject_name: str): 131 | sobject_name = sobject_name.lower() 132 | with open(os.path.join(self.schemadir, sobject_name, 'query.soql'), 'r') as queryfile: 133 | return queryfile.read() 134 | 135 | def save_table_create(self, sobject_name: str, sql: str): 136 | sobject_name = sobject_name.lower() 137 | os.makedirs(os.path.join(self.schemadir, sobject_name), exist_ok=True) 138 | with open(os.path.join(self.schemadir, sobject_name, '{}.sql'.format(sobject_name)), 'w') as schemafile: 139 | schemafile.write(sql) 140 | 141 | def save_sobject_transformer(self, sobject_name: str, xformr: str): 142 | sobject_name = sobject_name.lower() 143 | os.makedirs(os.path.join(self.schemadir, sobject_name), exist_ok=True) 144 | with open(os.path.join(self.schemadir, sobject_name, '{}_Transform.py'.format(sobject_name)), 145 | 'w') as parserfile: 146 | parserfile.write(xformr) 147 | 148 | def save_sobject_query(self, sobject_name: str, soql: str): 149 | sobject_name = sobject_name.lower() 150 | os.makedirs(os.path.join(self.schemadir, sobject_name), exist_ok=True) 151 | with open(os.path.join(self.schemadir, sobject_name, 'query.soql'), 'w') as queryfile: 152 | queryfile.write(soql) 153 | -------------------------------------------------------------------------------- /gurglefish/schema.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018, 2019 Marshall L Smith Jr 2 | # 3 | # This file is part of Gurglefish. 4 | # 5 | # Gurglefish is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # Gurglefish is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with Gurglefish. If not, see . 17 | import logging 18 | from typing import Dict 19 | 20 | from gurglefish import FileManager 21 | from gurglefish.DriverManager import DbDriverMeta 22 | from gurglefish.context import Context 23 | from gurglefish.objects.files import LocalTableConfig 24 | from gurglefish.objects.sobject import ColumnMap 25 | from gurglefish.sfapi import SObjectFields, SFClient 26 | from gurglefish.tools import make_arg_list 27 | 28 | __author__ = 'mark' 29 | 30 | 31 | class SFSchemaManager: 32 | 33 | def __init__(self, context: Context): 34 | self.filters = context.filemgr.get_global_filters() + context.filemgr.get_filters() 35 | self.context = context 36 | self.log = logging.getLogger("schema") 37 | 38 | @property 39 | def driver(self) -> DbDriverMeta: 40 | return self.context.driver 41 | 42 | @property 43 | def sfclient(self) -> SFClient: 44 | return self.context.sfclient 45 | 46 | @property 47 | def filemgr(self) -> FileManager: 48 | return self.context.filemgr 49 | 50 | @property 51 | def storagedir(self) -> str: 52 | return self.context.filemgr.schemadir 53 | 54 | def inspect(self) -> [Dict]: 55 | solist: [Dict] = self.sfclient.get_sobject_list() 56 | solist: [Dict] = [sobj for sobj in solist if self.accept_sobject(sobj)] 57 | for so in solist: 58 | # 59 | # enrich the data with the package name 60 | # 61 | name = so['name'] 62 | pos = name.find('__') 63 | if pos != -1 and pos < len(name) - 5: 64 | so['package'] = name[0:pos] 65 | else: 66 | so['package'] = 'unpackaged' 67 | return solist 68 | 69 | def prepare_configured_sobjects(self): 70 | table_config: [LocalTableConfig] = self.context.filemgr.get_configured_tables() 71 | table_list = [table.name for table in table_config if table.enabled] 72 | return self.prepare_sobjects(table_list) 73 | 74 | def prepare_sobjects(self, names): 75 | docs = [] 76 | for name in names: 77 | try: 78 | doc = self.sfclient.get_sobject_definition(name) 79 | docs.append(doc) 80 | except Exception as ex: 81 | print('Unable to retrieve {}, skipping'.format(name)) 82 | print(ex) 83 | raise ex 84 | return self._process_sobjects(docs) 85 | 86 | def accept_sobject(self, sobj: Dict) -> bool: 87 | """ 88 | determine if the named sobject is suitable for exporting 89 | 90 | :param sobj:Name of sobject/table 91 | :return: True or False 92 | """ 93 | name = sobj['name'] 94 | 95 | if len(self.filters) > 0 and name not in self.filters: 96 | return False 97 | 98 | if sobj['name'].endswith('_del__c'): 99 | return False 100 | 101 | if sobj['customSetting'] is True or sobj['replicateable'] is False or sobj['updateable'] is False: 102 | return False 103 | if name.endswith('__Tag') or name.endswith('__History') or name.endswith('__Feed'): 104 | return False 105 | if name[0:4] == 'Apex' or name in ('scontrol', 'weblink', 'profile'): 106 | return False 107 | return True 108 | 109 | def _process_sobjects(self, solist): 110 | self.sodict = dict([(so['name'], so) for so in solist]) 111 | sobject_names = set([so['name'].lower() for so in solist]) 112 | for new_sobject_name in sorted(sobject_names): 113 | self.create_table(new_sobject_name) 114 | 115 | def create_table(self, sobject_name: str): 116 | new_sobject_name = sobject_name.lower() 117 | 118 | fields: SObjectFields = self.filemgr.get_sobject_fields(sobject_name) 119 | if fields is None: 120 | fields: SObjectFields = self.sfclient.get_field_list(new_sobject_name) 121 | self.filemgr.save_sobject_fields(sobject_name, fields) 122 | 123 | table_name, fieldlist, create_table_dml = self.driver.make_create_table(fields, new_sobject_name) 124 | select = self.driver.make_select_statement([field.sobject_field for field in fieldlist], 125 | new_sobject_name) 126 | 127 | parser = self.driver.make_transformer(new_sobject_name, table_name, fieldlist) 128 | 129 | self.filemgr.save_sobject_fields(new_sobject_name, fields) 130 | self.filemgr.save_sobject_transformer(new_sobject_name, parser) 131 | self.filemgr.save_sobject_map(new_sobject_name, fieldlist) 132 | self.filemgr.save_table_create(new_sobject_name, create_table_dml + ';\n\n') 133 | self.filemgr.save_sobject_query(new_sobject_name, select) 134 | 135 | # 136 | # now create the table, if needed 137 | # 138 | 139 | try: 140 | if not self.driver.table_exists(sobject_name): 141 | self.log.info(f' creating {sobject_name}') 142 | self.driver.exec_ddl(create_table_dml) 143 | self.log.info(f' creating indexes') 144 | self.driver.maintain_indexes(sobject_name, fields) 145 | except Exception as ex: 146 | print(ex) 147 | raise ex 148 | 149 | def update_sobject_definition(self, sobject_name: str, allow_add=True, allow_drop=True): 150 | sobject_name = sobject_name.lower() 151 | 152 | sobj_columns: SObjectFields = self.sfclient.get_field_list(sobject_name) 153 | table_columns = self.driver.get_db_columns(sobject_name) 154 | 155 | # 156 | # check for added/dropped columns 157 | # 158 | table_field_names = set([tbl['column_name'] for tbl in table_columns]) 159 | new_field_names = sobj_columns.names() - table_field_names 160 | dropped_fields = table_field_names - sobj_columns.names() 161 | 162 | if len(new_field_names) > 0: 163 | if not allow_add: 164 | self.log.warning(f' new column found for {sobject_name}, auto-create disabled, skipping') 165 | else: 166 | self.log.info(f' new columns found, updating table and indexes') 167 | new_field_defs = [sobj_columns.find(f) for f in new_field_names] 168 | newfields: [ColumnMap] = self.driver.alter_table_add_columns(new_field_defs, sobject_name) 169 | if len(newfields) > 0: 170 | self.driver.maintain_indexes(sobject_name, SObjectFields(new_field_defs)) 171 | 172 | fieldmap: [ColumnMap] = self.filemgr.get_sobject_map(sobject_name) 173 | fieldmap.extend(newfields) 174 | self.filemgr.save_sobject_map(sobject_name, fieldmap) 175 | select = self.driver.make_select_statement([field['sobject_field'] for field in fieldmap], 176 | sobject_name) 177 | self.filemgr.save_sobject_query(sobject_name, select) 178 | parser = self.driver.make_transformer(sobject_name, sobject_name, fieldmap) 179 | self.filemgr.save_sobject_transformer(sobject_name, parser) 180 | 181 | self.filemgr.save_sobject_fields(sobject_name, [f for f in sobj_columns.values()]) 182 | 183 | if len(dropped_fields) > 0: 184 | if not allow_drop: 185 | self.log.warning(f' dropped column detected for {sobject_name}, auto-drop disabled, skipping') 186 | # do not allow sync until field(s) allowed to be dropped 187 | return False 188 | fieldmap: [ColumnMap] = self.filemgr.get_sobject_map(sobject_name) 189 | newlist: [ColumnMap] = list() 190 | for item in fieldmap: 191 | if item.sobject_field in dropped_fields: 192 | pass 193 | else: 194 | newlist.append(item) 195 | fieldmap = newlist 196 | self.log.info(f' dropped column(s) detected') 197 | self.driver.alter_table_drop_columns(dropped_fields, sobject_name) 198 | self.filemgr.save_sobject_map(sobject_name, fieldmap) 199 | select = self.driver.make_select_statement([field.sobject_field for field in fieldmap], sobject_name) 200 | self.filemgr.save_sobject_query(sobject_name, select) 201 | parser = self.driver.make_transformer(sobject_name, sobject_name, fieldmap) 202 | self.filemgr.save_sobject_transformer(sobject_name, parser) 203 | 204 | self.filemgr.save_sobject_fields(sobject_name, sobj_columns) 205 | return True 206 | 207 | def initialize_config(self, envname: str): 208 | if self.filemgr.get_configured_tables() is not None: 209 | self.log.error('Initialization halted, config.json already exists. ' 210 | 'Remove file and tables manually to start over') 211 | exit(1) 212 | sobject_list: [Dict] = self.inspect() 213 | sobjectconfig = [] 214 | for sobject in sobject_list: 215 | sobjectconfig.append(LocalTableConfig({'name': sobject['name'].lower(), 'enabled': False})) 216 | self.filemgr.save_configured_tables(sobjectconfig) 217 | self.log.info(f'Initial configuration created for {envname}') 218 | 219 | def enable_table_sync(self, table_names: [str], flag: bool): 220 | table_config: [LocalTableConfig] = self.filemgr.get_configured_tables() 221 | to_enable = [a.lower() for a in make_arg_list(table_names)] 222 | for entry in table_config: 223 | if entry.name in to_enable: 224 | self.log.info(f"Setting {entry.name} sync to {flag}") 225 | entry.enabled = flag 226 | self.filemgr.save_configured_tables(table_config) 227 | -------------------------------------------------------------------------------- /Pipfile.lock: -------------------------------------------------------------------------------- 1 | { 2 | "_meta": { 3 | "hash": { 4 | "sha256": "6fc4ad6ac44630c8f199f843b98cc6defbc0ed6f3fced01b1f5af96eae153b8a" 5 | }, 6 | "pipfile-spec": 6, 7 | "requires": { 8 | "python_version": "3.7" 9 | }, 10 | "sources": [ 11 | { 12 | "name": "pypi", 13 | "url": "https://pypi.org/simple", 14 | "verify_ssl": true 15 | } 16 | ] 17 | }, 18 | "default": { 19 | "arrow": { 20 | "hashes": [ 21 | "sha256:8c53fad4e723a56c02d8df75fd7a879800148d6e51df4713f91502e70a65e1be", 22 | "sha256:9f1503d359011a74cd41169652f0eb0232822f58c67c414229f4174a15ae71f9" 23 | ], 24 | "index": "pypi", 25 | "version": "==0.14.6" 26 | }, 27 | "certifi": { 28 | "hashes": [ 29 | "sha256:0f0d56dc5a6ad56fd4ba36484d6cc34451e1c6548c61daad8c320169f91eddc7", 30 | "sha256:c6c2e98f5c7869efca1f8916fed228dd91539f9f1b444c314c06eef02980c716" 31 | ], 32 | "markers": "python_version >= '3.6'", 33 | "version": "==2023.5.7" 34 | }, 35 | "charset-normalizer": { 36 | "hashes": [ 37 | "sha256:04afa6387e2b282cf78ff3dbce20f0cc071c12dc8f685bd40960cc68644cfea6", 38 | "sha256:04eefcee095f58eaabe6dc3cc2262f3bcd776d2c67005880894f447b3f2cb9c1", 39 | "sha256:0be65ccf618c1e7ac9b849c315cc2e8a8751d9cfdaa43027d4f6624bd587ab7e", 40 | "sha256:0c95f12b74681e9ae127728f7e5409cbbef9cd914d5896ef238cc779b8152373", 41 | "sha256:0ca564606d2caafb0abe6d1b5311c2649e8071eb241b2d64e75a0d0065107e62", 42 | "sha256:10c93628d7497c81686e8e5e557aafa78f230cd9e77dd0c40032ef90c18f2230", 43 | "sha256:11d117e6c63e8f495412d37e7dc2e2fff09c34b2d09dbe2bee3c6229577818be", 44 | "sha256:11d3bcb7be35e7b1bba2c23beedac81ee893ac9871d0ba79effc7fc01167db6c", 45 | "sha256:12a2b561af122e3d94cdb97fe6fb2bb2b82cef0cdca131646fdb940a1eda04f0", 46 | "sha256:12d1a39aa6b8c6f6248bb54550efcc1c38ce0d8096a146638fd4738e42284448", 47 | "sha256:1435ae15108b1cb6fffbcea2af3d468683b7afed0169ad718451f8db5d1aff6f", 48 | "sha256:1c60b9c202d00052183c9be85e5eaf18a4ada0a47d188a83c8f5c5b23252f649", 49 | "sha256:1e8fcdd8f672a1c4fc8d0bd3a2b576b152d2a349782d1eb0f6b8e52e9954731d", 50 | "sha256:20064ead0717cf9a73a6d1e779b23d149b53daf971169289ed2ed43a71e8d3b0", 51 | "sha256:21fa558996782fc226b529fdd2ed7866c2c6ec91cee82735c98a197fae39f706", 52 | "sha256:22908891a380d50738e1f978667536f6c6b526a2064156203d418f4856d6e86a", 53 | "sha256:3160a0fd9754aab7d47f95a6b63ab355388d890163eb03b2d2b87ab0a30cfa59", 54 | "sha256:322102cdf1ab682ecc7d9b1c5eed4ec59657a65e1c146a0da342b78f4112db23", 55 | "sha256:34e0a2f9c370eb95597aae63bf85eb5e96826d81e3dcf88b8886012906f509b5", 56 | "sha256:3573d376454d956553c356df45bb824262c397c6e26ce43e8203c4c540ee0acb", 57 | "sha256:3747443b6a904001473370d7810aa19c3a180ccd52a7157aacc264a5ac79265e", 58 | "sha256:38e812a197bf8e71a59fe55b757a84c1f946d0ac114acafaafaf21667a7e169e", 59 | "sha256:3a06f32c9634a8705f4ca9946d667609f52cf130d5548881401f1eb2c39b1e2c", 60 | "sha256:3a5fc78f9e3f501a1614a98f7c54d3969f3ad9bba8ba3d9b438c3bc5d047dd28", 61 | "sha256:3d9098b479e78c85080c98e1e35ff40b4a31d8953102bb0fd7d1b6f8a2111a3d", 62 | "sha256:3dc5b6a8ecfdc5748a7e429782598e4f17ef378e3e272eeb1340ea57c9109f41", 63 | "sha256:4155b51ae05ed47199dc5b2a4e62abccb274cee6b01da5b895099b61b1982974", 64 | "sha256:49919f8400b5e49e961f320c735388ee686a62327e773fa5b3ce6721f7e785ce", 65 | "sha256:53d0a3fa5f8af98a1e261de6a3943ca631c526635eb5817a87a59d9a57ebf48f", 66 | "sha256:5f008525e02908b20e04707a4f704cd286d94718f48bb33edddc7d7b584dddc1", 67 | "sha256:628c985afb2c7d27a4800bfb609e03985aaecb42f955049957814e0491d4006d", 68 | "sha256:65ed923f84a6844de5fd29726b888e58c62820e0769b76565480e1fdc3d062f8", 69 | "sha256:6734e606355834f13445b6adc38b53c0fd45f1a56a9ba06c2058f86893ae8017", 70 | "sha256:6baf0baf0d5d265fa7944feb9f7451cc316bfe30e8df1a61b1bb08577c554f31", 71 | "sha256:6f4f4668e1831850ebcc2fd0b1cd11721947b6dc7c00bf1c6bd3c929ae14f2c7", 72 | "sha256:6f5c2e7bc8a4bf7c426599765b1bd33217ec84023033672c1e9a8b35eaeaaaf8", 73 | "sha256:6f6c7a8a57e9405cad7485f4c9d3172ae486cfef1344b5ddd8e5239582d7355e", 74 | "sha256:7381c66e0561c5757ffe616af869b916c8b4e42b367ab29fedc98481d1e74e14", 75 | "sha256:73dc03a6a7e30b7edc5b01b601e53e7fc924b04e1835e8e407c12c037e81adbd", 76 | "sha256:74db0052d985cf37fa111828d0dd230776ac99c740e1a758ad99094be4f1803d", 77 | "sha256:75f2568b4189dda1c567339b48cba4ac7384accb9c2a7ed655cd86b04055c795", 78 | "sha256:78cacd03e79d009d95635e7d6ff12c21eb89b894c354bd2b2ed0b4763373693b", 79 | "sha256:80d1543d58bd3d6c271b66abf454d437a438dff01c3e62fdbcd68f2a11310d4b", 80 | "sha256:830d2948a5ec37c386d3170c483063798d7879037492540f10a475e3fd6f244b", 81 | "sha256:891cf9b48776b5c61c700b55a598621fdb7b1e301a550365571e9624f270c203", 82 | "sha256:8f25e17ab3039b05f762b0a55ae0b3632b2e073d9c8fc88e89aca31a6198e88f", 83 | "sha256:9a3267620866c9d17b959a84dd0bd2d45719b817245e49371ead79ed4f710d19", 84 | "sha256:a04f86f41a8916fe45ac5024ec477f41f886b3c435da2d4e3d2709b22ab02af1", 85 | "sha256:aaf53a6cebad0eae578f062c7d462155eada9c172bd8c4d250b8c1d8eb7f916a", 86 | "sha256:abc1185d79f47c0a7aaf7e2412a0eb2c03b724581139193d2d82b3ad8cbb00ac", 87 | "sha256:ac0aa6cd53ab9a31d397f8303f92c42f534693528fafbdb997c82bae6e477ad9", 88 | "sha256:ac3775e3311661d4adace3697a52ac0bab17edd166087d493b52d4f4f553f9f0", 89 | "sha256:b06f0d3bf045158d2fb8837c5785fe9ff9b8c93358be64461a1089f5da983137", 90 | "sha256:b116502087ce8a6b7a5f1814568ccbd0e9f6cfd99948aa59b0e241dc57cf739f", 91 | "sha256:b82fab78e0b1329e183a65260581de4375f619167478dddab510c6c6fb04d9b6", 92 | "sha256:bd7163182133c0c7701b25e604cf1611c0d87712e56e88e7ee5d72deab3e76b5", 93 | "sha256:c36bcbc0d5174a80d6cccf43a0ecaca44e81d25be4b7f90f0ed7bcfbb5a00909", 94 | "sha256:c3af8e0f07399d3176b179f2e2634c3ce9c1301379a6b8c9c9aeecd481da494f", 95 | "sha256:c84132a54c750fda57729d1e2599bb598f5fa0344085dbde5003ba429a4798c0", 96 | "sha256:cb7b2ab0188829593b9de646545175547a70d9a6e2b63bf2cd87a0a391599324", 97 | "sha256:cca4def576f47a09a943666b8f829606bcb17e2bc2d5911a46c8f8da45f56755", 98 | "sha256:cf6511efa4801b9b38dc5546d7547d5b5c6ef4b081c60b23e4d941d0eba9cbeb", 99 | "sha256:d16fd5252f883eb074ca55cb622bc0bee49b979ae4e8639fff6ca3ff44f9f854", 100 | "sha256:d2686f91611f9e17f4548dbf050e75b079bbc2a82be565832bc8ea9047b61c8c", 101 | "sha256:d7fc3fca01da18fbabe4625d64bb612b533533ed10045a2ac3dd194bfa656b60", 102 | "sha256:dd5653e67b149503c68c4018bf07e42eeed6b4e956b24c00ccdf93ac79cdff84", 103 | "sha256:de5695a6f1d8340b12a5d6d4484290ee74d61e467c39ff03b39e30df62cf83a0", 104 | "sha256:e0ac8959c929593fee38da1c2b64ee9778733cdf03c482c9ff1d508b6b593b2b", 105 | "sha256:e1b25e3ad6c909f398df8921780d6a3d120d8c09466720226fc621605b6f92b1", 106 | "sha256:e633940f28c1e913615fd624fcdd72fdba807bf53ea6925d6a588e84e1151531", 107 | "sha256:e89df2958e5159b811af9ff0f92614dabf4ff617c03a4c1c6ff53bf1c399e0e1", 108 | "sha256:ea9f9c6034ea2d93d9147818f17c2a0860d41b71c38b9ce4d55f21b6f9165a11", 109 | "sha256:f645caaf0008bacf349875a974220f1f1da349c5dbe7c4ec93048cdc785a3326", 110 | "sha256:f8303414c7b03f794347ad062c0516cee0e15f7a612abd0ce1e25caf6ceb47df", 111 | "sha256:fca62a8301b605b954ad2e9c3666f9d97f63872aa4efcae5492baca2056b74ab" 112 | ], 113 | "markers": "python_version >= '3.7'", 114 | "version": "==3.1.0" 115 | }, 116 | "fastcache": { 117 | "hashes": [ 118 | "sha256:6de1b16e70335b7bde266707eb401a3aaec220fb66c5d13b02abf0eab8be782b" 119 | ], 120 | "index": "pypi", 121 | "version": "==1.1.0" 122 | }, 123 | "idna": { 124 | "hashes": [ 125 | "sha256:814f528e8dead7d329833b91c5faa87d60bf71824cd12a7530b5526063d02cb4", 126 | "sha256:90b77e79eaa3eba6de819a0c442c0b4ceefc341a7a2ab77d7562bf49f425c5c2" 127 | ], 128 | "markers": "python_version >= '3.5'", 129 | "version": "==3.4" 130 | }, 131 | "python-dateutil": { 132 | "hashes": [ 133 | "sha256:0123cacc1627ae19ddf3c27a5de5bd67ee4586fbdd6440d9748f8abb483d3e86", 134 | "sha256:961d03dc3453ebbc59dbdea9e4e11c5651520a876d0f4db161e8674aae935da9" 135 | ], 136 | "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", 137 | "version": "==2.8.2" 138 | }, 139 | "pyyaml": { 140 | "hashes": [ 141 | "sha256:0113bc0ec2ad727182326b61326afa3d1d8280ae1122493553fd6f4397f33df9", 142 | "sha256:01adf0b6c6f61bd11af6e10ca52b7d4057dd0be0343eb9283c878cf3af56aee4", 143 | "sha256:5124373960b0b3f4aa7df1707e63e9f109b5263eca5976c66e08b1c552d4eaf8", 144 | "sha256:5ca4f10adbddae56d824b2c09668e91219bb178a1eee1faa56af6f99f11bf696", 145 | "sha256:7907be34ffa3c5a32b60b95f4d95ea25361c951383a894fec31be7252b2b6f34", 146 | "sha256:7ec9b2a4ed5cad025c2278a1e6a19c011c80a3caaac804fd2d329e9cc2c287c9", 147 | "sha256:87ae4c829bb25b9fe99cf71fbb2140c448f534e24c998cc60f39ae4f94396a73", 148 | "sha256:9de9919becc9cc2ff03637872a440195ac4241c80536632fffeb6a1e25a74299", 149 | "sha256:a5a85b10e450c66b49f98846937e8cfca1db3127a9d5d1e31ca45c3d0bef4c5b", 150 | "sha256:b0997827b4f6a7c286c01c5f60384d218dca4ed7d9efa945c3e1aa623d5709ae", 151 | "sha256:b631ef96d3222e62861443cc89d6563ba3eeb816eeb96b2629345ab795e53681", 152 | "sha256:bf47c0607522fdbca6c9e817a6e81b08491de50f3766a7a0e6a5be7905961b41", 153 | "sha256:f81025eddd0327c7d4cfe9b62cf33190e1e736cc6e97502b3ec425f574b3e7a8" 154 | ], 155 | "index": "pypi", 156 | "version": "==5.1.2" 157 | }, 158 | "requests": { 159 | "hashes": [ 160 | "sha256:58cd2187c01e70e6e26505bca751777aa9f2ee0b7f4300988b709f44e013003f", 161 | "sha256:942c5a758f98d790eaed1a29cb6eefc7ffb0d1cf7af05c3d2791656dbd6ad1e1" 162 | ], 163 | "index": "pypi", 164 | "version": "==2.31.0" 165 | }, 166 | "six": { 167 | "hashes": [ 168 | "sha256:1e61c37477a1626458e36f7b1d82aa5c9b094fa4802892072e49de9c60c4c926", 169 | "sha256:8abb2f1d86890a2dfb989f9a77cfcfd3e47c2a354b01111771326f8aa26e0254" 170 | ], 171 | "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", 172 | "version": "==1.16.0" 173 | }, 174 | "urllib3": { 175 | "hashes": [ 176 | "sha256:61717a1095d7e155cdb737ac7bb2f4324a858a1e2e6466f6d03ff630ca68d3cc", 177 | "sha256:d055c2f9d38dc53c808f6fdc8eab7360b6fdbbde02340ed25cfbcd817c62469e" 178 | ], 179 | "markers": "python_version >= '3.7'", 180 | "version": "==2.0.2" 181 | } 182 | }, 183 | "develop": {} 184 | } 185 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | ### Gurglefish 3 | #### Salesforce Archiver 4 | 5 | --- 6 | 7 | Backup your Salesforce sobject data to Postgres and keep in sync. 8 | 9 | #### Features 10 | 11 | * One-way data snapshots from Salesforce to Postgres. 12 | * Simple CLI interface. 13 | * Dynamic creation of equivalent database table for your selected sobjects. 14 | * Multiprocessing-enabled for up to 4 concurrent table snapshots. 15 | * Automatic creation and maintenance of indexes: 16 | * Primary key index on ID column 17 | * Master/Detail and Lookup field IDs. 18 | * ExternalId fields. 19 | * Automatic detection of sobject field additions/removals and alteration of table structure to match. 20 | * Cloud-ready for Amazon RDS and Azure. 21 | * Synchronization of record additions/changes/deletions since last run. 22 | * Scrubbing of hard deleted records can be disabled on a per-table basis and on the commandline. 23 | * Logging of sync statistics for each table. 24 | * Export feature to enable faster initial data loading using native Postgres load file format. 25 | * Fast field mapping using code generation. 26 | * Schema artifacts saved in a format easily consumed by custom tooling. 27 | * Tested over 18 months continuous running in a production environment. 28 | 29 | #### Installation 30 | 31 | **Requirements**: 32 | * Python 3.6 or higher 33 | * Postgresql 9.6 or higher 34 | 35 | ```bash 36 | pip3 install --user gurglefish 37 | ``` 38 | 39 | To update: 40 | 41 | ```bash 42 | pip3 install --upgrade gurglefish 43 | ``` 44 | 45 | In order to use the _export_ feature to initially populate very large tables (recommended) you must 46 | install the Postgresql CLI client for your system. 47 | 48 | Examples: 49 | 50 | > Ubuntu 18: ```sudo apt install postgres-client``` 51 | 52 | > CentOS 7: ```sudo apt install postgres96-client``` 53 | 54 | Use your distribution package search tool (yum, apt, dnf) to find the correct name and install. 55 | 56 | #### Configuration 57 | 58 | > **NOTE:** This tool only reads from Salesforce and writes to the database/schema you have configured. However, it is 59 | still very important to secure your accounts appropriately to protect against system invasion. In other words, 60 | **security is your responsibility**. 61 | 62 | **Requirements**: 63 | 64 | * An API-enabled Salesforce user account with *read-only* access to all sobjects to sync. NOTE that sobjects belonging to managed packages may require a license to access. 65 | * A configured Connected App in your Salesforce org accessible by the user account 66 | * A PostgreSQL database and user login with appropriate permission to create and alter tables and indexes only in a schema of your choice. 67 | 68 | Create a directory called _/var/lib/gurglefish_. This is the root of all host storage used by the tool. 69 | Make sure permissions are set accordingly so the running user has r/w privileges. **This directory tree must be protected 70 | appropriately as it may contain unencrypted table exports**. 71 | 72 | ```bash 73 | sudo mkdir /var/lib/gurglefish 74 | sudo chmod +rwx /var/lib/gurglefish # set permissions according to your security needs 75 | ``` 76 | 77 | If you want to use a different directory, or a mount point, just create a symbolic link to your location. 78 | Example: ```sudo ln -s /mnt/my-other-storage/sfarchives /var/lib/gurglefish``` 79 | 80 | Now create the configuration file (connections.ini) that provides login credentials to both your Postgres database and Salesforce organization. It is a standard INI file and can contain definitions for multiple database-org relationships. Put the file in /var/lib/gurglefish. 81 | It will look something like this (for a single database and org): 82 | 83 | ```ini 84 | [prod] 85 | id=prod 86 | login=my-api-user@myorg.com 87 | password=password+securitytoken 88 | consumer_key=key from connected app 89 | consumer_secret=secret from connected app 90 | authurl=https://my.domain.salesforce.com 91 | 92 | dbvendor=postgresql 93 | dbname=gurglefish 94 | schema=public 95 | dbuser=dbadmin 96 | dbpass=dbadmin123 97 | dbhost=192.168.2.61 98 | dbport=5432 99 | 100 | threads=2 101 | ``` 102 | > **NOTE**: Protect this file from prying eyes. You obviously don't want these credentials stolen. 103 | 104 | The settings are mostly self explanatory: 105 | 106 | * Make sure to include your _password_ **and** security token if you have not whitelisted your IP with Salesforce, 107 | otherwise the token can be omitted. 108 | * The _authurl_ selects either your Salesforce production URL or _https://test.salesforce.com_ for sandboxes. 109 | * Currently, the only supported _dbvendor_ is postgresql. 110 | * The _schema_ can be custom, or *public* (the default). If the database is to be shared with other critical data it is highly recommended to isolate in a custom schema (see postgresql docs). 111 | * Use _threads_ with caution. You can have at most 4, as this is a Salesforce-imposed limitation. But the real bottleneck could be your database server. Without custom database tuning, or running on a small platform, you should stick with 1 or 2 threads. Move up to 4 only when you are certain the database isn't a bottleneck. 112 | 113 | #### Getting Started 114 | 115 | Now that you are (hopefully) configured correctly you can pull down a list of sobjects and decide which ones to sync. 116 | 117 | Using the example configuration above: 118 | ```bash 119 | gurglefish prod --init 120 | ``` 121 | 122 | If the Salesforce login was successful you will see the new directory _/var/lib/gurglefish/db/prod_. This is the root where all configuration and export data will be stored for this connection. 123 | 124 | Under _db/prod_ you should see **config.json**. Open it in your favorite editor. You will see entries for all sobjects your user account has access to here. 125 | 126 | > Note: if you do not see sobjects you know exist, your probably don't have permissions to access them or you need a specific license assigned to your account (in the case of commercial managed packages). 127 | 128 | You are free to edit this file as you see fit but make sure it remains valid JSON. When a new sobject is detected a new entry will be added to this file for it. 129 | 130 | Example: 131 | 132 | ```json 133 | { 134 | "configuration": { 135 | "sobjects": [ 136 | { 137 | "name": "account", 138 | "enabled": false, 139 | "auto_scrub": "always" 140 | }, 141 | { 142 | "name": "account_vetting__c", 143 | "enabled": false 144 | }, 145 | { 146 | "name": "account_addresses__c", 147 | "enabled": false 148 | } 149 | ] 150 | } 151 | } 152 | ``` 153 | For each sobject you want to sync, set the "enabled" value to **true**. Or from the CLI use `gurglefish prod --enable sobject_name__c`. Use `--disable` to stop further syncs. 154 | 155 | For each sobject you want to auto detect and cleanup of deleted records, set "auto_scrub" to "always". But this comes at a cost of API calls and slows down the overall syncing process. 156 | 157 | Alternately, you can schedule a run once a day, or some other interval, to perform the scrub. Late a night is a good choice. 158 | 159 | Sample crontab (global scrub once a day at 1am): 160 | 161 | ```crontab 162 | 0 9,13,15,17,19 * * 1-5 gurglefish prod --sync >/tmp/sync.log 163 | 0 1 * * 1-5 gurglefish prod --sync --scrub >/tmp/sync.log 164 | ``` 165 | 166 | 167 | Save the file. 168 | 169 | You are ready to start pulling data. But some choices need to be made first. 170 | 171 | #### The Initial Data Pull 172 | 173 | > This is a good time to discuss the topic of Saleforce API limits. For each run, for each table, one metadata API call is made to detect schema changes and one query is issues to pull down changed records, giving a minimum of 2 per table per run. If you run snapshots every 2 hours on 20 tables, that's 12 x 20 x 2 = 480/day **minimum**. I say _minimum_ because this is best-case scenario where there are less than a few hundred changes. With larger data queries, Salesforce returns the data in "chunks" and API users are required to call back to Salesforce to retrieve the next chunk, until are all retrieved. So for sobjects with a lot of activity, like User, Account, Lead, Opportunity, etc, there could be hundreds of calls for each run. 174 | 175 | > Fortunately, Gurglefish reports to you at the end of a run the total number of API calls consumed so you can keep an eye on it. You can compare to the documented limits [here](https://developer.salesforce.com/docs/atlas.en-us.salesforce_app_limits_cheatsheet.meta/salesforce_app_limits_cheatsheet/salesforce_app_limits_platform_api.htm). So, for example, if you have an Enterprise license and 65+ users you already have the maximum of 1,000,000 calls rolling 24-hour window. 176 | 177 | > And remember, you are sharing those limits with your other integrations. 178 | 179 | 180 | The initial load of data could take quite a bit of time depending on the number of sobjects enabled, number of fields, and number of records. But as a frame of reference, I've seen it process about 200 records per second on an Opportunity table that has over 800 fields. 181 | 182 | The recommendation is to just enable a couple of sobjects to start, give it a run to make sure all is going well. You can then go back and enable other sobjects as you need. In other words, split up your work. You will consume the most API calls during initial loads so space it out if needed. 183 | 184 | **Use standard snapshots** 185 | For any new table load you can stick with standard synchronization/snapshots. Gurglefish will see you are syncing a new table and pull down all records. Once the initial load is finished, subsequent runs will only pull down the changes. 186 | Snapshot can be interrupted - they will resume where they left off on the next run. 187 | 188 | **Use native exports** 189 | Another option is to use the _--export_ feature to dump all sobject records into a postgres native loadable format. This file can then be loaded using _--load_, usually in under a minute. Exported files are saved under the __exports/__ folder and compressed. 190 | 191 | > NOTE: Exported files are not useful for archiving or backups as their formats are integrally tied to the current schema of their sobject/table. If that schema changes the exports are not usable. This is a postgres restriction and is the tradeoff for lightning fast loads. You can remove these files after loading. 192 | 193 | **Use the Salesforce bulk API** 194 | _This is intended as a last-resort edge case_. 195 | Gurglefish will detect if the SOQL required to retrieve data is longer than 16k and inform you to switch to the bulk API to handle it. Honestly, if you have a table that wide you should rethink your design. 196 | To enable just add "bulkapi":true to the sobject in config.json. All sync requires going forward will use the Salesforce Bulk API, which in some cases is slower if you have lots of scheduled bulk jobs pending. Gurglefish will wait up to 10 minutes for the job to start, then time out if it doesn't. 197 | 198 | #### Running 199 | 200 | ```bash 201 | gurglefish prod --sync 202 | ``` 203 | 204 | Seriously, could it be any easier? 205 | 206 | Gurglefish will automatically create any missing tables and indexes in postgres you elected to sync from Salesforce. 207 | 208 | #### Snapshot Frequency 209 | 210 | It is up to you if you want to schedule automatic runs via **cron** or other mechanism. Currently, all tables will snapshot on each run - there are not individually customizable run schedules by table. However, this feature is on the roadmap. 211 | 212 | #### Statistics 213 | 214 | Gurglefish logs statistics for each table on each run to 2 tables: _gf_mdata_sync_jobs_ (master) and _gf_mdata_sync_stats_ (detail) You are free to query these as you like for reporting, auditing, etc. Job statitics are kept for 2 months and cleaned out as they expire. So if you want to keep them around longer you should make provisions to sync them elsewhere. A custom trigger to replicate inserts to a longer-term set of tables is a good idea. 215 | 216 | Also, a record of automatic schema changes is recorded in _gf_mdata_schema_chg_. So whenever a new or dropped column is detected on an sobject it is recorded here. This table is never purged. 217 | 218 | -------------------------------------------------------------------------------- /gurglefish/sfexport.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018, 2019 Marshall L Smith Jr 2 | # 3 | # This file is part of Gurglefish. 4 | # 5 | # Gurglefish is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # Gurglefish is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with Gurglefish. If not, see . 17 | 18 | import logging 19 | import os 20 | import datetime 21 | import sys 22 | from multiprocessing import Process, JoinableQueue, Queue, Value 23 | 24 | import arrow 25 | 26 | from gurglefish import FileManager 27 | from gurglefish import tools 28 | from gurglefish.context import Context 29 | from gurglefish.objects.sobject import ColumnMap 30 | from gurglefish.schema import SFSchemaManager 31 | from gurglefish.objects.files import LocalTableConfig 32 | from gurglefish.sfapi import SFClient, SFQueryTooLarge 33 | 34 | __author__ = 'mark' 35 | 36 | 37 | class ExportThread(Process): 38 | def __init__(self, queue: Queue, env_name: str): 39 | super().__init__(daemon=True) 40 | self.queue = queue 41 | self.env_name = env_name 42 | self.ctx = tools.setup_env(env_name) 43 | self.schema_mgr = SFSchemaManager(self.ctx) 44 | self.filemgr = self.ctx.filemgr 45 | self.sfclient = self.ctx.sfclient 46 | 47 | def run(self): 48 | db = self.ctx.dbdriver 49 | log = logging.getLogger(self.name) 50 | try: 51 | table_configs = self.ctx.filemgr.get_configured_tables() 52 | while not self.queue.empty(): 53 | job = self.queue.get() 54 | try: 55 | table_name = job['table_name'].lower() 56 | just_sample = job['just_sample'] 57 | 58 | this_table: LocalTableConfig = None 59 | for table_config in table_configs: 60 | if table_config.name == table_name: 61 | this_table = table_config 62 | break 63 | 64 | if this_table is None: 65 | log.error(f'Configuration for {table_name} not found in config.json - skipping') 66 | continue 67 | 68 | if not db.table_exists(table_name): 69 | self.schema_mgr.create_table(table_name) 70 | 71 | total_size = self.ctx.sfclient.record_count(table_name) 72 | 73 | if this_table.use_bulkapi: 74 | if total_size > 200_000: 75 | self.ctx.sfclient.add_header('Sforce-Enable-PKChunking', 'chunkSize=5000') 76 | else: 77 | self.ctx.sfclient.drop_header('Sforce-Enable-PKChunking') 78 | # 79 | # Salesforce does an annoying thing - datetime fields retrieve via bulk api are in 80 | # millis-since-epoch rather than the usual ISO string format. So, we need to convert 81 | # them back. Get the map and remove everything but datetime fields (for speed). 82 | # 83 | colmap: [ColumnMap] = self.ctx.filemgr.get_sobject_map(table_name) 84 | dtmap: [ColumnMap] = list() 85 | for col in iter(colmap): 86 | if col.field_type == 'datetime': 87 | dtmap.append(col) 88 | 89 | log.info(f'Exporting {total_size} records in {table_name} using bulk query (may take longer)') 90 | with db.create_exporter(table_name, self.ctx, just_sample) as exporter: 91 | for rec in self.ctx.sfclient.bulk_query(table_name, exporter.soql()): 92 | # replace all the numeric timestamps with correct strings 93 | for col in dtmap: 94 | epoch = rec.get(col.sobject_field, None) 95 | if epoch is not None: 96 | dt = datetime.datetime.fromtimestamp(epoch / 1000) 97 | rec[col.sobject_field] = tools.sf_timestamp(dt) 98 | exporter.write(rec) 99 | else: 100 | log.info(f'Exporting {table_name}') 101 | with db.create_exporter(table_name, self.ctx, just_sample) as exporter: 102 | for rec in self.ctx.sfclient.query(exporter.soql()): 103 | exporter.write(rec) 104 | 105 | if exporter.counter % 5000 == 0 and sys.stdout.isatty(): 106 | print('{}: exporting {} records: {:.0f}%\r'.format(exporter.sobject_name, 107 | total_size, 108 | (exporter.counter / total_size) * 100), 109 | end='\r', flush=True) 110 | finally: 111 | self.queue.task_done() 112 | finally: 113 | db.close() 114 | 115 | 116 | class SyncThread(Process): 117 | def __init__(self, queue: Queue, env_name: str, filemgr: FileManager, sfclient: SFClient, total_calls: Value, 118 | scrub=False): 119 | super().__init__(daemon=True) 120 | self.queue = queue 121 | self.filemgr = filemgr 122 | self.sfclient = sfclient 123 | self.env_name = env_name 124 | 125 | self.context = tools.setup_env(env_name) 126 | self.schema_mgr = SFSchemaManager(self.context) 127 | self.filemgr = self.context.filemgr 128 | self.sfclient = self.context.sfclient 129 | self.total_calls: Value = total_calls 130 | self.force_scrub = scrub 131 | 132 | def run(self): 133 | db = self.context.dbdriver 134 | log = logging.getLogger(self.name) 135 | try: 136 | while not self.queue.empty(): 137 | try: 138 | self.sfclient.calls = 0 139 | job = self.queue.get() 140 | jobid = job['jobid'] 141 | tabledef: LocalTableConfig = job['table'] 142 | sobject_name = tabledef.name.lower() 143 | 144 | log.info(f'Checking {sobject_name} schema for changes') 145 | proceed = self.schema_mgr.update_sobject_definition(sobject_name, 146 | allow_add=tabledef.auto_create_columns, 147 | allow_drop=tabledef.auto_drop_columns) 148 | if not proceed: 149 | print(f'sync of {sobject_name} skipped due to warnings') 150 | continue 151 | 152 | timestamp = self.context.dbdriver.max_timestamp(sobject_name) 153 | soql = self.context.filemgr.get_sobject_query(sobject_name) 154 | 155 | xlate_handler = self.filemgr.load_translate_handler(sobject_name) 156 | new_sync = False 157 | if timestamp is not None: 158 | soql += " where SystemModStamp >= {}".format(tools.sf_timestamp(timestamp)) 159 | soql += " order by SystemModStamp ASC" 160 | log.info(f'start sync {sobject_name} changes after {timestamp}') 161 | else: 162 | soql += ' order by SystemModStamp ASC' 163 | log.info(f'start full download of {sobject_name}') 164 | new_sync = True 165 | with db.cursor as cur: 166 | counter = 0 167 | # journal = self.filemgr.create_journal(sobject_name) 168 | try: 169 | sync_start = datetime.datetime.now() 170 | inserted = 0 171 | updated = 0 172 | deleted = 0 173 | for rec in self.sfclient.query(soql, not new_sync): 174 | del rec['attributes'] 175 | if rec.get('IsDeleted', False): 176 | deleted += db.delete(cur, sobject_name, rec['Id'][0:15]) 177 | continue 178 | trec = xlate_handler.parse(rec) 179 | 180 | try: 181 | i, u = db.upsert(cur, sobject_name, trec, None) 182 | if i: 183 | inserted += 1 184 | if u: 185 | updated += 1 186 | except Exception as ex: 187 | # with open('/tmp/debug.json', 'w') as x: 188 | # x.write(json.dumps(trec, indent=4, default=tools.json_serial)) 189 | raise ex 190 | 191 | if i or u: 192 | counter += 1 193 | if counter % 5000 == 0: 194 | log.info(f'{sobject_name} processed {counter}') 195 | if counter % 10000 == 0: 196 | db.commit() 197 | db.commit() 198 | 199 | # scrub deleted records 200 | if tabledef.auto_scrub == "always" or self.force_scrub: 201 | deleted += self.scrub_deletes(cur, sobject_name) 202 | 203 | self.total_calls.value += self.sfclient.calls 204 | log.info(f'end sync {sobject_name}: {inserted} inserts, {updated} updates, {deleted} deletes') 205 | log.info(f'API calls used for {sobject_name}: {self.sfclient.calls}') 206 | 207 | if counter > 0: 208 | db.insert_sync_stats(jobid, sobject_name, sync_start, datetime.datetime.now(), timestamp, 209 | inserted, updated, deleted, self.sfclient.calls) 210 | except SFQueryTooLarge: 211 | log.error(f'Query for {sobject_name} too large for REST API - switch to bulkapi to continue') 212 | 213 | except Exception as ex: 214 | db.rollback() 215 | raise ex 216 | finally: 217 | self.queue.task_done() 218 | finally: 219 | db.close() 220 | 221 | def scrub_deletes(self, cur, sobject_name: str) -> int: 222 | db = self.context.dbdriver 223 | log = logging.getLogger(self.name) 224 | table_file = os.path.join('/tmp', sobject_name + '.sobject') 225 | sobject_file = os.path.join('/tmp', sobject_name + '.table') 226 | try: 227 | db.dump_ids(sobject_name, table_file) 228 | self.context.sfapi.dump_ids(sobject_name, sobject_file) 229 | 230 | # lets 'diff' the two lists, finding deleted rows to purge from local database 231 | with open(table_file, 'r') as local: 232 | with open(sobject_file, 'r') as remote: 233 | left = set(local.readlines()) 234 | right = set(remote.readlines()) 235 | ids_to_delete = left - right 236 | for i in ids_to_delete: 237 | db.delete(cur, sobject_name, i.strip()) 238 | os.unlink(sobject_file) 239 | os.unlink(table_file) 240 | return len(ids_to_delete) 241 | 242 | except Exception as ex: 243 | log.error(ex) 244 | return 0 245 | 246 | 247 | class SFExporter: 248 | def __init__(self, context: Context): 249 | self.context = context 250 | self.storagedir = context.filemgr.exportdir 251 | os.makedirs(self.storagedir, exist_ok=True) 252 | self.log = logging.getLogger('main') 253 | 254 | def sync_tables(self, schema_mgr: SFSchemaManager, scrub=False): 255 | table_config: [LocalTableConfig] = self.context.filemgr.get_configured_tables() 256 | if table_config is None: 257 | self.log.error('No configuration found - Use --init to create and then edit') 258 | return 259 | tablelist: [LocalTableConfig] = [table for table in table_config if table.enabled] 260 | if len(tablelist) == 0: 261 | self.log.warning('No tables enabled for sync') 262 | return 263 | jobid = self.context.dbdriver.start_sync_job() 264 | queue: Queue = JoinableQueue() 265 | try: 266 | self.log.info('Building table sync queue') 267 | for table in tablelist: 268 | tablename = table.name.lower() 269 | if not self.context.dbdriver.table_exists(tablename): 270 | schema_mgr.create_table(tablename) 271 | 272 | queue.put({'jobid': jobid, 'table': table}) 273 | 274 | self.log.info(f'Allocating {self.context.env.threads} thread(s)') 275 | pool: [SyncThread] = list() 276 | total_api_calls: Value = Value('i', 0) 277 | for i in range(0, self.context.env.threads): 278 | job = SyncThread(queue, self.context.envname, self.context.filemgr, self.context.sfclient, 279 | total_api_calls, scrub) 280 | job.start() 281 | pool.append(job) 282 | 283 | for t in pool: 284 | self.log.debug(f'Waiting on thread {t.name}') 285 | t.join() 286 | if not queue.empty(): 287 | self.log.warning('All threads finished before queue was drained') 288 | self.log.info(f"Total API calls used during sync: {total_api_calls.value}") 289 | 290 | finally: 291 | self.context.dbdriver.finish_sync_job(jobid) 292 | self.context.dbdriver.clean_house(arrow.now().shift(months=-2).datetime) 293 | 294 | def export_tables(self, table_list: [str], just_sample=False): 295 | queue: Queue = JoinableQueue() 296 | for tablename in table_list: 297 | tablename = tablename.lower() 298 | queue.put({'table_name': tablename, 'just_sample': just_sample}) 299 | 300 | thread_count = min(self.context.env.threads, queue.qsize()) 301 | self.log.info(f'Allocating {thread_count} thread(s)') 302 | pool: [ExportThread] = list() 303 | for i in range(0, thread_count): 304 | job = ExportThread(queue, self.context.envname) 305 | job.start() 306 | pool.append(job) 307 | for t in pool: 308 | self.log.debug(f'Waiting on thread {t.name}') 309 | t.join() 310 | if not queue.empty(): 311 | self.log.warning('All threads finished before queue was drained') 312 | -------------------------------------------------------------------------------- /gurglefish/sfapi.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018, 2019 Marshall L Smith Jr 2 | # 3 | # This file is part of Gurglefish. 4 | # 5 | # Gurglefish is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # Gurglefish is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with Gurglefish. If not, see . 17 | import logging 18 | import json 19 | import operator 20 | import time 21 | from typing import Dict, Optional 22 | 23 | import requests 24 | from fastcache import lru_cache 25 | 26 | from gurglefish.objects.sobject import SObjectFields 27 | 28 | MAX_BATCH_SIZE = 100 29 | _API_VERSION = '44.0' 30 | 31 | 32 | class SFQueryTooLarge(Exception): 33 | def __init__(self): 34 | super().__init__(self) 35 | 36 | 37 | class JobBatch: 38 | 39 | def __init__(self, batchinfo: Dict, parent): 40 | self.parent = parent 41 | self.batch_id = batchinfo['id'] 42 | self.batchinfo = batchinfo 43 | 44 | @property 45 | def state(self) -> str: 46 | return self.batchinfo['state'] 47 | 48 | @property 49 | def id(self) -> str: 50 | return self.batch_id 51 | 52 | def get_results(self): 53 | response = self.parent.client.get( 54 | f'{self.parent.service_url}/services/async/{_API_VERSION}/job/{self.parent.job_id}/batch/{self.batch_id}/result') 55 | response.raise_for_status() 56 | self.client.calls += 1 57 | 58 | result = json.loads(response.text) 59 | for resultid in result: 60 | response = self.parent.client.get( 61 | f'{self.parent.service_url}/services/async/{_API_VERSION}/job/{self.parent.job_id}/batch/{self.batch_id}/result/{resultid}', 62 | stream=True) 63 | self.client.calls += 1 64 | doc = '' 65 | for chunk in response.iter_lines(): 66 | if chunk is None: 67 | continue 68 | chunk = chunk.decode('utf-8') 69 | if chunk[0] == '[': 70 | doc = '{' 71 | elif chunk[0] == '}': 72 | doc += '}' 73 | yield json.loads(doc) 74 | doc = '{' 75 | else: 76 | doc += chunk 77 | 78 | def refresh(self): 79 | if self.state != 'Completed': 80 | response = self.parent.client.get( 81 | f'{self.parent.service_url}/services/async/{_API_VERSION}/job/{self.parent.job_id}/batch/{self.batch_id}') 82 | self.client.calls += 1 83 | response.raise_for_status() 84 | self.batchinfo = json.loads(response.text) 85 | return True 86 | return False 87 | 88 | def wait_for_start(self, timeout: int = 180) -> bool: 89 | for i in range(0, timeout, 30): 90 | time.sleep(30) 91 | self.refresh() 92 | if self.state in ('Completed', 'NotProcessed'): 93 | return True 94 | if self.state == 'Failed': 95 | return False 96 | return False 97 | 98 | 99 | class BulkJob: 100 | JOB_OP_QUERY = 'query' 101 | JOB_OP_INSERT = 'insert' 102 | JOB_OP_UPDATE = 'update' 103 | JOB_TYPE_CSV = 'CSV' 104 | JOB_TYPE_XML = 'XML' 105 | JOB_TYPE_JSON = 'JSON' 106 | CONCUR_PARALLEL = 'Parallel' 107 | CONCUR_SERIAL = 'Serial' 108 | 109 | def __init__(self, jobinfo: Dict, client, service_url): 110 | self.job_id = jobinfo['id'] 111 | self.jobinfo = jobinfo 112 | self.client = client 113 | self.service_url = service_url 114 | self.pending: [JobBatch] = list() 115 | self.complete: [str] = list() 116 | 117 | def create_batch(self, payload): 118 | response = self.client.post(f'{self.service_url}/services/async/{_API_VERSION}/job/{self.job_id}/batch', 119 | data=json.dumps(payload, indent=4), 120 | headers={'Content-Type': 'application/json; charset=UTF-8'}) 121 | self.client.calls += 1 122 | response.raise_for_status() 123 | result = json.loads(response.text) 124 | return JobBatch(result, self) 125 | 126 | @property 127 | def batch_count(self) -> int: 128 | return self.jobinfo['numberBatchesTotal'] + self.jobinfo['numberBatchesQueued'] 129 | 130 | def bulk_query(self, soql: str): 131 | response = self.client.post(f'{self.service_url}/services/async/{_API_VERSION}/job/{self.job_id}/batch', 132 | data=soql + ' ', 133 | headers={'Content-Type': 'application/json; charset=UTF-8'}) 134 | self.client.calls += 1 135 | response.raise_for_status() 136 | result = json.loads(response.text) 137 | batch = JobBatch(result, self) 138 | self.pending.append(batch) 139 | return batch 140 | 141 | def is_done(self) -> bool: 142 | self.refresh() 143 | self.get_batches() 144 | all = self.jobinfo['numberBatchesQueued'] + self.jobinfo['numberBatchesInProgress'] + \ 145 | self.jobinfo['numberBatchesFailed'] + self.jobinfo['numberBatchesCompleted'] 146 | 147 | return len(self.complete) >= all and len(self.pending) == 0 and self.jobinfo['numberBatchesQueued'] == 0 148 | 149 | # return 0 < all < self.jobinfo['numberBatchesTotal'] \ 150 | # and len(self.complete) < len(self.pending) \ 151 | # and self.jobinfo['numberBatchesQueued'] == 0 152 | 153 | # 154 | # Returns: 155 | # { 156 | # "apexProcessingTime": 0, 157 | # "apiActiveProcessingTime": 0, 158 | # "apiVersion": 36.0, 159 | # "concurrencyMode": "Parallel", 160 | # "contentType": "JSON", 161 | # "createdById": "005D0000001b0fFIAQ", 162 | # "createdDate": "2015-12-15T20:45:25.000+0000", 163 | # "id": "750D00000004SkGIAU", 164 | # "numberBatchesCompleted": 0, 165 | # "numberBatchesFailed": 0, 166 | # "numberBatchesInProgress": 0, 167 | # "numberBatchesQueued": 0, 168 | # "numberBatchesTotal": 0, 169 | # "numberRecordsFailed": 0, 170 | # "numberRecordsProcessed": 0, 171 | # "numberRetries": 0, 172 | # "object": "Account", 173 | # "operation": "insert", 174 | # "state": "Open", 175 | # "systemModstamp": "2015-12-15T20:45:25.000+0000", 176 | # "totalProcessingTime": 0 177 | # } 178 | # 179 | def refresh(self): 180 | response = self.client.get(f'{self.service_url}/services/async/{_API_VERSION}/job/{self.job_id}') 181 | self.client.calls += 1 182 | response.raise_for_status() 183 | self.jobinfo = json.loads(response.text) 184 | 185 | # 186 | # Returns: 187 | # 188 | # { 189 | # "batchInfo": [ 190 | # { 191 | # "apexProcessingTime": 0, 192 | # "apiActiveProcessingTime": 0, 193 | # "createdDate": "2015-12-15T21:56:43.000+0000", 194 | # "id": "751D00000004YGZIA2", 195 | # "jobId": "750D00000004SkVIAU", 196 | # "numberRecordsFailed": 0, 197 | # "numberRecordsProcessed": 0, 198 | # "state": "Queued", 199 | # "systemModstamp": "2015-12-15T21:57:19.000+0000", 200 | # "totalProcessingTime": 0 201 | # } 202 | # ] 203 | # } 204 | # 205 | def get_batches(self) -> [Dict]: 206 | response = self.client.get(f'{self.service_url}/services/async/{_API_VERSION}/job/{self.job_id}/batch') 207 | self.client.calls += 1 208 | response.raise_for_status() 209 | result = json.loads(response.text) 210 | self.pending: [JobBatch] = list() 211 | for bi in result['batchInfo']: 212 | if bi['id'] not in self.complete: 213 | if bi['state'] in ('Queued', 'Completed', 'InProgress'): 214 | self.pending.append(JobBatch(bi, self)) 215 | else: 216 | self.release_batch(bi['id']) 217 | print('**** unhandled state ' + bi['state']) 218 | 219 | def release_batch(self, batch_id: str): 220 | self.complete.append(batch_id) 221 | 222 | def get_completed_batch(self) -> Optional[JobBatch]: 223 | self.get_batches() 224 | for batch in self.pending: 225 | if batch.state == 'Completed': 226 | return batch 227 | return None 228 | 229 | def close(self): 230 | response = self.client.post(f'{self.service_url}/services/async/{_API_VERSION}/job/{self.job_id}', 231 | data='{"state":"Closed"}') 232 | self.client.calls += 1 233 | response.raise_for_status() 234 | result = json.loads(response.text) 235 | return result 236 | 237 | 238 | class SFClient: 239 | 240 | def __init__(self): 241 | self.log = logging.getLogger('salesforce') 242 | self.access_token = None 243 | self.service_url = None 244 | self.client = None 245 | self._username = None 246 | self.calls = 0 247 | 248 | def login(self, consumer_key, consumer_secret, username, password, server_url): 249 | self._username = username 250 | payload = {'grant_type': 'password', 251 | 'username': username, 252 | 'password': password, 253 | 'client_id': consumer_key, 254 | 'client_secret': consumer_secret 255 | } 256 | rsp = requests.post(server_url + '/services/oauth2/token', data=payload, 257 | headers={'content-type': 'application/x-www-form-urlencoded'}) 258 | payload = json.loads(rsp.text) 259 | if 'error' in payload: 260 | raise Exception(payload['error_description']) 261 | # self.log.debug('payload=%s' % (rsp.text,)) 262 | self.construct(payload['access_token'], payload['instance_url']) 263 | 264 | def construct(self, token, server_url): 265 | self.access_token = token 266 | self.service_url = server_url 267 | self.client = requests.Session() 268 | self.client.headers.update({'Authorization': 'OAuth ' + token, 269 | 'X-SFDC-Session': token, 270 | 'Content-Type': 'application/json; charset=UTF-8', 271 | 'Accept-Encoding': 'gzip, compress, deflate', 'Accept-Charset': 'utf-8'}) 272 | 273 | def close(self): 274 | pass 275 | 276 | @lru_cache(maxsize=3, typed=False) 277 | def get_sobject_definition(self, name: str) -> Dict: 278 | sobject_doc = self._get('sobjects/{}/describe'.format(name), {}) 279 | return sobject_doc 280 | 281 | @lru_cache(maxsize=1, typed=False) 282 | def get_sobject_list(self) -> [Dict]: 283 | payload = self._get('sobjects/', {}) 284 | return payload['sobjects'] 285 | 286 | @lru_cache(maxsize=3, typed=False) 287 | def get_field_list(self, sobject_name: str) -> SObjectFields: 288 | fielddef = self._get('sobjects/%s/describe/' % (sobject_name,), {}) 289 | fieldlist = fielddef['fields'] 290 | fieldlist.sort(key=operator.itemgetter('name')) 291 | return SObjectFields(fieldlist) 292 | 293 | def dump_ids(self, sobject_name, output_filename: str): 294 | with open(output_filename, 'w') as out: 295 | for rec in self.query(f'select Id from {sobject_name} order by Id'): 296 | out.write(rec['Id'][0:15] + '\n') 297 | 298 | def record_count(self, sobject: str, query_filter: str = None): 299 | soql = 'select count() from ' + sobject 300 | if query_filter: 301 | soql += ' where ' + query_filter 302 | fullurl = f'{self.service_url}/services/data/v{_API_VERSION}/query/' 303 | self.log.debug('get %s', fullurl) 304 | response = self.client.get(fullurl, params={'q': soql}) 305 | result_payload = response.json() 306 | if response.status_code != 200: 307 | self.log.error(f'query error {response.status_code}, {response.reason}') 308 | self.log.error(result_payload) 309 | return 310 | self.calls += 1 311 | return result_payload['totalSize'] 312 | 313 | def query(self, soql: str, include_deleted=False): 314 | resource = 'queryAll' if include_deleted else 'query' 315 | fullurl = f'{self.service_url}/services/data/v{_API_VERSION}/{resource}/' 316 | # 317 | # Need to make specific changes to soql to avoid upsetting Salesforce and 318 | # using requests built-in escaping causes problems. 319 | # 320 | soql = soql.replace('+', '%2b').replace('\n', '').replace('\r', '').replace(' ', '+') 321 | response = self.client.get(fullurl, params=f'q={soql}') 322 | result_payload = response.text 323 | if response.status_code == 431: 324 | raise SFQueryTooLarge() 325 | self.calls += 1 326 | if response.status_code != 200: 327 | self.log.error(f'query error {response.status_code}, {response.reason}') 328 | self.log.error(result_payload) 329 | return 330 | data = json.loads(result_payload) 331 | recs = data['records'] 332 | for rec in recs: 333 | yield (rec) 334 | while 'nextRecordsUrl' in data: 335 | next_records_url = data['nextRecordsUrl'] 336 | if next_records_url: 337 | response = self.client.get('%s%s' % (self.service_url, next_records_url)) 338 | self.calls += 1 339 | txt = response.text 340 | if isinstance(txt, str): 341 | result_payload = txt 342 | else: 343 | result_payload = str(txt, 'utf-8') 344 | data = json.loads(result_payload) 345 | recs = data['records'] 346 | for rec in recs: 347 | yield (rec) 348 | else: 349 | break 350 | 351 | def _get(self, url, url_params): 352 | fullurl = f'{self.service_url}/services/data/v{_API_VERSION}/{url}' 353 | response = self.client.get(fullurl, params=url_params) 354 | result_payload = response.text 355 | self.calls += 1 356 | if response.status_code != 200: 357 | self.log.debug('get %s', fullurl) 358 | response.raise_for_status() 359 | data = json.loads(result_payload) 360 | return data 361 | 362 | def _post(self, url, url_params): 363 | fullurl = f'{self.service_url}/services/data/v{_API_VERSION}/{url}' 364 | response = self.client.post(fullurl, params=url_params) 365 | self.calls += 1 366 | if response.status_code != 200: 367 | self.log.debug('post %s', fullurl) 368 | result_payload = response.text 369 | response.raise_for_status() 370 | data = json.loads(result_payload) 371 | return data 372 | 373 | def add_header(self, name: str, val: str): 374 | self.client.headers[name] = val 375 | 376 | def drop_header(self, name: str): 377 | if name in self.client.headers: 378 | del self.client.headers[name] 379 | 380 | def create_job(self, op, sobject_name, content_type='JSON', concur_mode=BulkJob.CONCUR_PARALLEL): 381 | payload = {"operation": op, "object": sobject_name, "contentType": content_type, 382 | "concurrencyMode": concur_mode} 383 | url = f'{self.service_url}/services/async/{_API_VERSION}/job' 384 | self.client.headers['Content-Type'] = 'application/json; charset=UTF-8' 385 | response = self.client.post(url, data=json.dumps(payload), 386 | headers={'Content-Type': 'application/json; charset=UTF-8'}) 387 | self.calls += 1 388 | response.raise_for_status() 389 | result = response.json() 390 | if result['state'] != 'Open': 391 | raise Exception('Invalid job state: {}'.format(result['state'])) 392 | return BulkJob(result, self.client, self.service_url) 393 | 394 | def bulk_query(self, sobject: str, soql: str, job_id=None, timeout=600): 395 | 396 | if job_id is None: 397 | job = self.create_job(BulkJob.JOB_OP_QUERY, sobject) 398 | main_batch = job.bulk_query(soql + ' ') 399 | job.close() 400 | self.log.info(f'Waiting on bulk query job to start, timeout is {timeout} seconds') 401 | 402 | # suppress annoying requests debug logging 403 | logging.getLogger('chardet.charsetprober').setLevel(logging.INFO) 404 | 405 | if main_batch.wait_for_start(timeout): 406 | counter = 0 407 | batches = job.batch_count 408 | job.release_batch(main_batch.id) 409 | while not job.is_done(): 410 | completed = job.get_completed_batch() 411 | if completed is not None: 412 | counter += 1 413 | self.log.debug(f'Processing batch {counter} of {batches}') 414 | for result in completed.get_results(): 415 | del result['attributes'] 416 | yield result 417 | job.release_batch(completed.id) 418 | else: 419 | time.sleep(30) 420 | else: 421 | self.log.error('Timed out waiting for bulk query job to start') 422 | else: 423 | job = BulkJob({'id': job_id, 'state': 'Closed'}, self.client, self.service_url) 424 | counter = 1 425 | while not job.is_done(): 426 | total = job.batch_count 427 | completed = job.get_completed_batch() 428 | if completed is not None: 429 | self.log.debug(f'Processing batch {completed.batch_id} - {counter} of {total}') 430 | for result in completed.get_results(): 431 | del result['attributes'] 432 | yield result 433 | job.release_batch(completed.id) 434 | counter += 1 435 | else: 436 | time.sleep(20) 437 | -------------------------------------------------------------------------------- /gurglefish/drivers/postgresql/Driver.py: -------------------------------------------------------------------------------- 1 | # Copyright 2018, 2019 Marshall L Smith Jr 2 | # 3 | # This file is part of Gurglefish. 4 | # 5 | # Gurglefish is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # Gurglefish is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with Gurglefish. If not, see . 17 | 18 | import datetime 19 | import gzip 20 | import json 21 | import logging 22 | import operator 23 | import os 24 | import string 25 | import sys 26 | from typing import List, Dict 27 | 28 | import psycopg2 29 | import psycopg2.extras 30 | from fastcache import lru_cache 31 | from psycopg2._psycopg import connection, cursor 32 | 33 | from gurglefish import FileManager 34 | from gurglefish import config 35 | from gurglefish import tools 36 | from gurglefish.DriverManager import DbDriverMeta, GetDbTablesResult, DbNativeExporter 37 | from gurglefish.objects.connections import ConnectionConfig 38 | from gurglefish.context import Context 39 | from gurglefish.objects.sobject import SObjectField, SObjectFields, ColumnMap 40 | 41 | 42 | class NativeExporter(DbNativeExporter): 43 | 44 | def __init__(self, sobject: str, db: DbDriverMeta, filemgr: FileManager, just_sample=False, timestamp=None): 45 | self.sobject_name = sobject.lower() 46 | self.dbdriver = db 47 | self.query = None 48 | self.export_file = None 49 | self.tablefields = None 50 | self.xlate_handler = filemgr.load_translate_handler(self.sobject_name) 51 | self.log = logging.getLogger('exporter') 52 | 53 | fieldlist: [ColumnMap] = filemgr.get_sobject_map(self.sobject_name) 54 | self.fieldmap = dict((f.db_field.lower(), f) for f in fieldlist) 55 | 56 | self.tablefields: Dict = self.dbdriver.get_table_fields(self.sobject_name) 57 | self.tablefields: List = sorted(self.tablefields.values(), key=operator.itemgetter('ordinal_position')) 58 | soqlfields = [fm.sobject_field for fm in self.fieldmap.values()] 59 | 60 | self.query = 'select {} from {}'.format(','.join(soqlfields), self.sobject_name) 61 | if timestamp is not None: 62 | self.query += ' where SystemModStamp > {0}'.format(tools.sf_timestamp(timestamp)) 63 | if just_sample: 64 | self.log.info('sampling 500 records max') 65 | self.query += ' limit 500' 66 | self.counter = 0 67 | self.export_file = gzip.open(os.path.join(filemgr.exportdir, self.sobject_name + '.exp.gz'), 'wb', compresslevel=6) 68 | 69 | def __enter__(self): 70 | return self 71 | 72 | def __exit__(self, type, value, traceback): 73 | if self.export_file is not None: 74 | self.export_file.close() 75 | self.export_file = None 76 | 77 | def soql(self) -> str: 78 | return self.query 79 | 80 | def write(self, rec: Dict): 81 | transformed: Dict = self.xlate_handler.parse(rec) 82 | record = NativeExporter.format_for_export(transformed, self.tablefields, self.fieldmap) 83 | self.export_file.write(record) 84 | self.counter += 1 85 | 86 | @staticmethod 87 | def format_for_export(trec: Dict, tablefields: [Dict], fieldmap: Dict[str, ColumnMap]): 88 | parts = [] 89 | for tf in tablefields: 90 | n = tf['column_name'] 91 | f = fieldmap[n] 92 | soqlf = f.sobject_field 93 | if soqlf in trec: 94 | val = trec[soqlf] 95 | if val is None: 96 | parts.append('\\N') 97 | else: 98 | if isinstance(val, bool): 99 | parts.append('True' if val else 'False') 100 | elif isinstance(val, datetime.datetime): 101 | parts.append(val.isoformat()) 102 | elif isinstance(val, str): 103 | parts.append(NativeExporter._escape(val)) 104 | else: 105 | parts.append(str(val)) 106 | else: 107 | parts.append('\\N') 108 | return bytes('\t'.join(parts) + '\n', 'utf-8') 109 | 110 | @staticmethod 111 | def _escape(val): 112 | if '\\' in val or '\n' in val or '\r' in val or '\t' in val: 113 | val = val.replace('\\', '\\\\') 114 | val = val.replace('\n', '\\n') 115 | val = val.replace('\r', '\\r') 116 | val = val.replace('\t', '\\t') 117 | return val 118 | 119 | def close(self): 120 | self.export_file.close() 121 | if sys.stdout.isatty(): 122 | print("\nexported {} records{}".format(self.counter, ' ' * 10)) 123 | 124 | 125 | class Driver(DbDriverMeta): 126 | 127 | def __init__(self): 128 | self.driver_type = "postgresql" 129 | self.dbenv = None 130 | self.db: connection = None 131 | self.storagedir = None 132 | self.log = logging.getLogger('dbdriver') 133 | self.schema_name = None 134 | 135 | def connect(self, dbenv: ConnectionConfig): 136 | self.dbenv = dbenv 137 | dbport = dbenv.dbport if dbenv.dbport is not None and len(dbenv.dbport) > 2 else '5432' 138 | try: 139 | self.db: connection = psycopg2.connect( 140 | "dbname='{0}' user='{1}' password='{2}' host='{3}' port='{4}'".format(dbenv.dbname, dbenv.dbuser, 141 | dbenv.dbpass, dbenv.dbhost, 142 | dbport)) 143 | self.storagedir = os.path.join(config.storagedir, 'db', self.dbenv.id) 144 | self.schema_name = dbenv.schema 145 | self.verify_db_setup() 146 | return True 147 | except Exception as ex: 148 | self.log.fatal(f'Unable to log into {dbenv.dbname} at {dbenv.dbhost}:{dbport} for user {dbenv.dbuser}') 149 | self.log.fatal(ex) 150 | raise ex 151 | 152 | def exec_ddl(self, ddl: str): 153 | cur = self.db.cursor() 154 | cur.execute(ddl) 155 | self.db.commit() 156 | cur.close() 157 | 158 | @property 159 | def dbhost(self): 160 | return self.dbenv.dbhost 161 | 162 | @property 163 | def dbport(self): 164 | return self.dbenv.dbport 165 | 166 | @property 167 | def dbname(self): 168 | return self.dbenv.dbname 169 | 170 | @property 171 | def new_map_cursor(self): 172 | return self.db.cursor(cursor_factory=psycopg2.extras.DictCursor) 173 | 174 | @property 175 | def cursor(self) -> cursor: 176 | return self.db.cursor() 177 | 178 | def close(self): 179 | self.db.close() 180 | 181 | def verify_db_setup(self): 182 | self.exec_ddl(f'CREATE SCHEMA IF NOT EXISTS {self.schema_name}') 183 | if not self.table_exists('gf_mdata_sync_stats'): 184 | ddl = f'create table {self.schema_name}.gf_mdata_sync_stats (' + \ 185 | ' id serial primary key, ' + \ 186 | ' jobid integer, ' + \ 187 | ' table_name text not null, ' + \ 188 | ' inserts numeric(8) not null, ' + \ 189 | ' updates numeric(8) not null, ' + \ 190 | ' deletes numeric(8) not null, ' + \ 191 | ' api_calls numeric(8) not null, ' + \ 192 | ' sync_start timestamp not null default now(), ' + \ 193 | ' sync_end timestamp not null default now(), ' + \ 194 | ' sync_since timestamp not null)' 195 | self.exec_ddl(ddl) 196 | if not self.table_exists('gf_mdata_schema_chg'): 197 | ddl = f'create table {self.schema_name}.gf_mdata_schema_chg (' + \ 198 | ' id serial primary key, ' + \ 199 | ' table_name text not null, ' + \ 200 | ' col_name text not null, ' + \ 201 | ' operation text not null, ' + \ 202 | ' date_added timestamp not null default now())' 203 | self.exec_ddl(ddl) 204 | if not self.table_exists('gf_mdata_sync_jobs'): 205 | ddl = f'create table {self.schema_name}.gf_mdata_sync_jobs (' + \ 206 | ' id serial primary key, ' + \ 207 | ' date_start timestamp not null default now(),' + \ 208 | ' date_finish timestamp)' 209 | self.exec_ddl(ddl) 210 | self.exec_ddl(f'alter table {self.schema_name}.gf_mdata_sync_stats add constraint ' + 211 | 'gf_mdata_sync_stats_job_fk foreign key (jobid) references ' + 212 | f'{self.schema_name}.gf_mdata_sync_jobs(id) on delete cascade') 213 | 214 | def start_sync_job(self): 215 | cur = self.cursor 216 | cur.execute(f'insert into {self.schema_name}.gf_mdata_sync_jobs (date_start) values (%s) returning id', 217 | (datetime.datetime.now(),)) 218 | rowid = cur.fetchone()[0] 219 | cur.close() 220 | self.db.commit() 221 | return rowid 222 | 223 | def finish_sync_job(self, jobid): 224 | cur = self.cursor 225 | cur.execute(f'update {self.schema_name}.gf_mdata_sync_jobs set date_finish=%s where id=%s', 226 | (datetime.datetime.now(), jobid)) 227 | cur.close() 228 | 229 | def insert_sync_stats(self, jobid, table_name, sync_start, sync_end, sync_since, inserts, updates, deletes, api_calls): 230 | cur = self.cursor 231 | if sync_since is None: 232 | sync_since = datetime.datetime(1970, 1, 1, 0, 0, 0) 233 | dml = f'insert into {self.schema_name}.gf_mdata_sync_stats ' + \ 234 | '(jobid, table_name, inserts, updates, deletes, sync_start, ' + \ 235 | 'sync_end, sync_since, api_calls) values (%s,%s,%s,%s,%s,%s,%s,%s,%s)' 236 | 237 | cur.execute(dml, (jobid, table_name, inserts, updates, deletes, sync_start, sync_end, sync_since, api_calls)) 238 | self.db.commit() 239 | 240 | def clean_house(self, date_constraint: datetime): 241 | cur = self.cursor 242 | dml = f'delete from {self.schema_name}.gf_mdata_sync_jobs where date_start < %s' 243 | cur.execute(dml, (date_constraint,)) 244 | self.db.commit() 245 | cur.close() 246 | 247 | def insert_schema_change(self, table_name: string, col_name: string, operation: string): 248 | cur = self.cursor 249 | dml = f'insert into {self.schema_name}.gf_mdata_schema_chg (table_name, col_name, operation) values (%s,%s,%s)' 250 | cur.execute(dml, [table_name, col_name, operation]) 251 | self.db.commit() 252 | cur.close() 253 | 254 | def import_native(self, tablename): 255 | tablename = tablename.lower() 256 | 257 | exportfile = os.path.join(self.storagedir, 'export', tablename + '.exp.gz') 258 | with self.cursor as cur: 259 | with gzip.open(exportfile, 'rb') as infile: 260 | cur.copy_from(infile, tablename) 261 | self.db.commit() 262 | 263 | def export_native(self, table_name, output_path): 264 | table_name = table_name.lower() 265 | with self.cursor as cur: 266 | with gzip.open(output_path, 'wb', compresslevel=6) as outfile: 267 | cur.copy_to(outfile, table_name) 268 | 269 | def delete(self, cur, table_name: str, key: str): 270 | table_name = self.fq_table(table_name) 271 | try: 272 | if cur.execute(f"SELECT id from {table_name} where id=%s", [key]) is None: 273 | return 0 274 | cur.execute(f'delete from {table_name} where Id=%s', [key]) 275 | return 1 276 | except Exception as ex: 277 | self.log.error(f'Deleting record {key} from {table_name}') 278 | return 0 279 | 280 | def upsert(self, cur, table_name, trec: dict, journal=None): 281 | assert ('Id' in trec) 282 | 283 | cur.execute("select * from {} where id = '{}'".format(self.fq_table(table_name), trec['Id'])) 284 | tmp_rec = cur.fetchone() 285 | orig_rec = {} 286 | index = 0 287 | if tmp_rec is not None: 288 | for col in cur.description: 289 | orig_rec[col[0]] = tmp_rec[index] 290 | index += 1 291 | 292 | namelist = [] 293 | data = [] 294 | 295 | inserted = False 296 | updated = False 297 | 298 | if len(orig_rec) == 0: 299 | table_fields = self.get_table_fields(table_name) 300 | existing_field_names = table_fields.keys() 301 | for k, v in trec.items(): 302 | k = k.lower() 303 | if k in existing_field_names: 304 | namelist.append(k) 305 | data.append(v) 306 | 307 | valueplaceholders = ','.join('%s' for _ in range(len(data))) 308 | fieldnames = ','.join(namelist) 309 | sql = 'insert into {0} ({1}) values ({2});'.format(self.fq_table(table_name), fieldnames, valueplaceholders) 310 | if journal: 311 | journal.write(bytes('i:{} --> {}\n'.format(sql, json.dumps(data, default=tools.json_serial)), 'utf-8')) 312 | cur.execute(sql, data) 313 | inserted = True 314 | else: 315 | # 316 | # use only the changed field values 317 | # 318 | pkey = None 319 | for k, v in trec.items(): 320 | k = k.lower() 321 | if k == 'id': 322 | pkey = v 323 | continue 324 | if k in orig_rec: 325 | if orig_rec[k] != v: 326 | namelist.append(k) 327 | data.append(v) 328 | # 329 | # !!!!! FIX DATE/DATETIME PROBLEM 330 | # 331 | 332 | if len(namelist) == 0: 333 | # 334 | # This is a legit case. It is probably due to overlapping lastmodifieddate in sync query where nothing 335 | # actually changed. 336 | return False, False 337 | 338 | assert pkey is not None 339 | sql = 'update {} set '.format(self.fq_table(table_name)) 340 | sets = [] 341 | for name in namelist: 342 | sets.append(name + r'=%s') 343 | sql += ','.join(sets) 344 | sql += " where id = '{}'".format(pkey) 345 | if journal: 346 | journal.write(bytes('u:{} --> {}\n'.format(sql, json.dumps(data, default=tools.json_serial)), 'utf-8')) 347 | cur.execute(sql, data) 348 | updated = True 349 | return inserted, updated 350 | 351 | def commit(self): 352 | self.db.commit() 353 | 354 | def rollback(self): 355 | self.db.rollback() 356 | 357 | @lru_cache(maxsize=5, typed=False) 358 | def get_table_fields(self, table_name: str) -> Dict: 359 | cur = self.new_map_cursor 360 | sql = "select column_name, data_type, character_maximum_length, ordinal_position " + \ 361 | "from information_schema.columns " + \ 362 | "where table_name = '{}' " + \ 363 | "order by ordinal_position" 364 | cur.execute(sql.format(table_name)) 365 | columns = cur.fetchall() 366 | cur.close() 367 | table_fields = dict() 368 | for c in columns: 369 | table_fields[c['column_name']] = {'column_name': c['column_name'], 'data_type': c['data_type'], 370 | 'character_maximum_length': c['character_maximum_length'], 371 | 'ordinal_position': c['ordinal_position']} 372 | return table_fields 373 | 374 | def dump_ids(self, table_name: str, output_filename: str): 375 | cur = self.cursor 376 | sql = f'select id from {self.schema_name}.{table_name} order by id' 377 | cur.execute(sql) 378 | with open(output_filename, 'w') as out: 379 | for rec in cur: 380 | out.write(rec[0] + '\n') 381 | cur.close() 382 | 383 | def record_count(self, table_name: str) -> int: 384 | table_cursor = self.db.cursor() 385 | table_cursor.execute('SELECT count(*) FROM {}.{}'.format(self.schema_name, table_name)) 386 | records = table_cursor.fetchone() 387 | table_cursor.close() 388 | return records 389 | 390 | def get_db_tables(self) -> List[GetDbTablesResult]: 391 | table_cursor = self.db.cursor() 392 | table_cursor.execute( 393 | "SELECT table_name FROM information_schema.tables WHERE table_schema=%s ORDER BY table_name", 394 | (self.schema_name,)) 395 | tables = table_cursor.fetchall() 396 | table_cursor.close() 397 | result = [GetDbTablesResult(row[0]) for row in tables] 398 | return result 399 | 400 | def table_exists(self, table_name: str) -> bool: 401 | table_cursor = self.db.cursor() 402 | table_cursor.execute( 403 | "select count(*) from information_schema.tables where table_name = %s and table_schema=%s", 404 | (table_name, self.schema_name)) 405 | val = table_cursor.fetchone() 406 | cnt, = val 407 | return cnt > 0 408 | 409 | def get_db_columns(self, table_name: str) -> List: 410 | col_cursor = self.new_map_cursor 411 | col_cursor.execute( 412 | "select * from information_schema.columns where table_name=%s " + 413 | "and table_schema=%s " + 414 | "order by column_name", (table_name, self.schema_name)) 415 | cols = col_cursor.fetchall() 416 | col_cursor.close() 417 | return cols 418 | 419 | def _make_column(self, sobject_name: str, field: SObjectField) -> [ColumnMap]: 420 | """ 421 | returns: 422 | list(dict( 423 | fieldlen, dml, table_name, sobject_name, sobject_field, db_field, fieldtype 424 | )) 425 | """ 426 | assert (sobject_name is not None) 427 | assert (field is not None) 428 | # if field is None: return None,None 429 | 430 | sql = '' 431 | fieldname = field.name 432 | fieldtype = field.get_type 433 | fieldlen = field.length 434 | if fieldtype in ('picklist', 'multipicklist', 'email', 'phone', 'url'): 435 | sql += 'varchar ({0}) '.format(fieldlen) 436 | elif fieldtype in ('string', 'encryptedstring', 'textarea', 'combobox'): 437 | sql += 'text ' 438 | elif fieldtype == 'datetime': 439 | sql += 'timestamp ' 440 | elif fieldtype == 'date': 441 | sql += 'date ' 442 | elif fieldtype == 'time': 443 | sql += 'time ' 444 | elif fieldtype == 'id': 445 | sql += 'char(15) primary key ' 446 | elif fieldtype == 'reference': 447 | sql += 'char(15) ' 448 | elif fieldtype == 'boolean': 449 | sql += 'boolean ' 450 | elif fieldtype == 'double': 451 | sql += 'numeric ({0},{1}) '.format(field.precision, field.scale) 452 | fieldlen = field.precision + field.scale + 1 453 | elif fieldtype == 'currency': 454 | sql += 'numeric (18,2) ' 455 | elif fieldtype == 'int': 456 | sql += 'integer ' 457 | fieldlen = 15 458 | elif fieldtype == 'percent': 459 | sql += 'numeric ' 460 | fieldlen = 9 461 | elif fieldtype in ('base64', 'anyType'): # not implemented yet <<<<<< 462 | return [] 463 | elif fieldtype == 'address': 464 | # nothing to handle, this is just an aggregation of fields already exposed for syncing 465 | return [] 466 | else: 467 | self.log.error(f'field {fieldname} unknown type {fieldtype} for sobject {sobject_name}') 468 | raise Exception('field {0} unknown type {1} for sobject {2}'.format(fieldname, fieldtype, sobject_name)) 469 | 470 | new_list = [ColumnMap.from_parts(fieldlen, sql, sobject_name, field.name, fieldname, fieldtype)] 471 | return new_list 472 | 473 | def alter_table_add_columns(self, new_field_defs, sobject_name: str) -> [ColumnMap]: 474 | ddl_template = "ALTER TABLE {} ADD COLUMN {} {}" 475 | cur = self.db.cursor() 476 | newcols = [] 477 | for field in new_field_defs: 478 | if field.get_type == 'address': 479 | continue 480 | col_def: [ColumnMap] = self._make_column(sobject_name, field) 481 | if len(col_def) == 0: 482 | continue 483 | col = col_def[0] 484 | ddl = ddl_template.format(self.fq_table(sobject_name), col.db_field, col.dml) 485 | print(' adding column {} to {}'.format(col.db_field, self.fq_table(sobject_name))) 486 | cur.execute(ddl) 487 | newcols.append(col) 488 | 489 | # record change to schema 490 | sql = f'insert into {self.schema_name}.gf_mdata_schema_chg ' +\ 491 | '(table_name, col_name, operation) values (%s,%s,%s)' 492 | cur.execute(sql, [sobject_name, col.db_field, 'create']) 493 | 494 | self.db.commit() 495 | cur.close() 496 | return newcols 497 | 498 | def alter_table_drop_columns(self, drop_field_names: [str], sobject_name: str): 499 | ddl_template = 'ALTER TABLE {} DROP COLUMN {}' 500 | cur = self.db.cursor() 501 | for field in drop_field_names: 502 | self.log.info(' dropping column {} from {}'.format(field, sobject_name)) 503 | ddl = ddl_template.format(self.fq_table(sobject_name), field) 504 | cur.execute(ddl) 505 | 506 | # record change to schema 507 | sql = 'insert into {}.gf_mdata_schema_chg (table_name, col_name, operation) values (%s,%s,%s)' 508 | cur.execute(sql.format(self.schema_name), [sobject_name, field, 'drop']) 509 | 510 | self.db.commit() 511 | cur.close() 512 | 513 | def maintain_indexes(self, sobject_name, field_defs: SObjectFields): 514 | ddl_template = "CREATE INDEX IF NOT EXISTS {}_{} ON {} ({})" 515 | cur = self.db.cursor() 516 | for field in field_defs.values(): 517 | if field.is_externalid or field.is_idlookup or field.name == 'SystemModStamp': 518 | if field.name != 'id': # Id is already set as the pkey 519 | ddl = ddl_template.format(sobject_name, field.name, self.fq_table(sobject_name), field.name) 520 | cur.execute(ddl) 521 | self.log.info(f' created index {sobject_name}_{field.name}') 522 | self.db.commit() 523 | cur.close() 524 | 525 | def make_select_statement(self, field_names: [str], sobject_name: str) -> str: 526 | select = 'select ' + ',\n'.join(field_names) + ' from ' + sobject_name 527 | return select 528 | 529 | def make_create_table(self, fields: SObjectFields, sobject_name: str) -> (str, [ColumnMap], str): 530 | sobject_name = sobject_name.lower() 531 | self.log.info('new sobject: ' + sobject_name) 532 | tablecols = [] 533 | fieldlist: [ColumnMap] = [] 534 | 535 | for field in fields.values(): 536 | m: [ColumnMap] = self._make_column(sobject_name, field) 537 | if len(m) == 0: 538 | continue 539 | for column in m: 540 | fieldlist.append(column) 541 | tablecols.append(' ' + column.db_field + ' ' + column.dml) 542 | sql = ',\n'.join(tablecols) 543 | return sobject_name, fieldlist, 'create table {0} ( \n{1} )\n'.format(self.fq_table(sobject_name), sql) 544 | 545 | def max_timestamp(self, tablename: str): 546 | col_cursor = self.db.cursor() 547 | col_cursor.execute('select max(SystemModStamp) from ' + self.fq_table(tablename)) 548 | stamp, = col_cursor.fetchone() 549 | col_cursor.close() 550 | return stamp 551 | 552 | def make_transformer(self, sobject_name, table_name, fieldlist: [ColumnMap]): 553 | parser = 'from gurglefish.transformutils import id, bl, db, dt, st, ts, tm, inte\n\n' 554 | parser += 'def parse(rec):\n' + \ 555 | ' result = dict()\n\n' 556 | # ' def push(name, value):\n' + \ 557 | # ' result[name] = value\n\n' 558 | 559 | for field in fieldlist: 560 | fieldtype = field.field_type 561 | fieldname = field.sobject_field 562 | fieldlen = field.fieldlen 563 | dbfield = field.db_field 564 | p_parser = '' 565 | if fieldtype in ('picklist', 'multipicklist', 'string', 'textarea', 'email', 'phone', 566 | 'url', 'encryptedstring', 'combobox'): 567 | p_parser = f'result["{dbfield}"] = st(rec, "{fieldname}", fieldlen={fieldlen})\n' 568 | elif fieldtype == 'datetime': 569 | p_parser = f'result["{dbfield}"] = ts(rec, "{fieldname}", fieldlen={fieldlen})\n' 570 | elif fieldtype == 'date': 571 | p_parser = f'result["{dbfield}"] = dt(rec, "{fieldname}", fieldlen={fieldlen})\n' 572 | elif fieldtype == 'time': 573 | p_parser = f'result["{dbfield}"] = tm(rec, "{fieldname}", fieldlen={fieldlen})\n' 574 | elif fieldtype in ('id', 'reference'): 575 | p_parser = f'result["{dbfield}"] = id(rec, "{fieldname}", fieldlen={fieldlen})\n' 576 | elif fieldtype == 'boolean': 577 | p_parser = f'result["{dbfield}"] = bl(rec, "{fieldname}", fieldlen={fieldlen})\n' 578 | elif fieldtype in ('double', 'currency', 'percent'): 579 | p_parser = f'result["{dbfield}"] = db(rec, "{fieldname}", fieldlen={fieldlen})\n' 580 | elif fieldtype == 'int': 581 | p_parser = f'result["{dbfield}"] = inte(rec, "{fieldname}", fieldlen={fieldlen})\n' 582 | elif fieldtype in ('base64', 'anyType'): # not implemented yet <<<<<< 583 | return None 584 | elif fieldtype == 'address': 585 | # p_parser = 'result["{}"] = stsub(rec, "{}", "{}", fieldlen={})\n'.format(dbfield, fieldname, 586 | # field['subfield'], fieldlen) 587 | pass 588 | 589 | parser += ' ' + p_parser 590 | parser += ' return result' 591 | return parser 592 | 593 | @lru_cache(maxsize=10, typed=False) 594 | def fq_table(self, tablename): 595 | return '"{}"."{}"'.format(self.schema_name, tablename) 596 | 597 | @staticmethod 598 | def _escape(val): 599 | if '\\' in val or '\n' in val or '\r' in val or '\t' in val: 600 | val = val.replace('\\', '\\\\') 601 | val = val.replace('\n', '\\n') 602 | val = val.replace('\r', '\\r') 603 | val = val.replace('\t', '\\t') 604 | return val 605 | 606 | def format_for_export(self, trec: Dict, tablefields: [Dict], fieldmap: Dict[str, ColumnMap]): 607 | parts = [] 608 | for tf in tablefields: 609 | n = tf['column_name'] 610 | f = fieldmap[n] 611 | soqlf = f.sobject_field 612 | if soqlf in trec: 613 | val = trec[soqlf] 614 | if val is None: 615 | parts.append('\\N') 616 | else: 617 | if isinstance(val, bool): 618 | parts.append('True' if val else 'False') 619 | elif isinstance(val, datetime.datetime): 620 | parts.append(val.isoformat()) 621 | elif isinstance(val, str): 622 | parts.append(Driver._escape(val)) 623 | else: 624 | parts.append(str(val)) 625 | else: 626 | parts.append('\\N') 627 | return bytes('\t'.join(parts) + '\n', 'utf-8') 628 | 629 | def create_exporter(self, sobject_name: str, ctx: Context, just_sample=False, timestamp=None) -> DbNativeExporter: 630 | exporter = NativeExporter(sobject_name, self, ctx.filemgr, just_sample, timestamp) 631 | return exporter 632 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------