├── README.md ├── k8s.md ├── javascript.md ├── deep_learning.md ├── docker.md ├── python.md ├── LICENSE └── relational_databases.md /README.md: -------------------------------------------------------------------------------- 1 | # Best Practices 2 | 3 | Anthology of best practices 4 | -------------------------------------------------------------------------------- /k8s.md: -------------------------------------------------------------------------------- 1 | # Kubernetes 2 | 3 | - [Kubernetes Production Patterns](https://github.com/gravitational/workshop/blob/master/k8sprod.md) 4 | - [Design Patterns for Container-based Distributed Systems](https://www.usenix.org/conference/hotcloud16/workshop-program/presentation/burns) 5 | -------------------------------------------------------------------------------- /javascript.md: -------------------------------------------------------------------------------- 1 | # Javascript Best Practices 2 | 3 | - [ES6 Cheat Sheet](https://github.com/DrkSephy/es6-cheatsheet) 4 | - [You Don't Know JS](https://github.com/getify/You-Dont-Know-JS) 5 | - [Effectice JavaScript](https://www.amazon.com/dp/0321812182): pre-ES6 but still interesting 6 | 7 | 8 | - [Node JS Best Practices 2017](https://blog.risingstack.com/node-js-best-practices-2017/]) 9 | - [Node Best Practices](https://devcenter.heroku.com/articles/node-best-practices) 10 | -------------------------------------------------------------------------------- /deep_learning.md: -------------------------------------------------------------------------------- 1 | # Deep Learning Best Practices 2 | 3 | - Tensorflow: https://github.com/aicodes/tf-bestpractice 4 | - Transfer learning: http://cs231n.github.io/transfer-learning/ 5 | - [TensorFlow: A proposal of good practices for files, folders and models architecture](https://blog.metaflow.fr/tensorflow-a-proposal-of-good-practices-for-files-folders-and-models-architecture-f23171501ae3) 6 | 7 | Resources surveying the field: 8 | 9 | - [Deep Convolutional Neural Network Design Patterns](https://arxiv.org/abs/1611.00847) 10 | - [Deep Reinforcement Learning: An Overview](https://arxiv.org/abs/1701.07274) 11 | - [An overview of gradient descent optimization algorithms](https://arxiv.org/abs/1609.04747) 12 | - [On Unifying Deep Generative Models](https://arxiv.org/abs/1706.00550) 13 | -------------------------------------------------------------------------------- /docker.md: -------------------------------------------------------------------------------- 1 | # Docker Best Practices 2 | 3 | - Keep containers stateless. 4 | - Use COPY instead of ADD. 5 | - Make COPY last line before CMD or ENTRYPOINT. 6 | - Each line in the Dockerfile is cached. 7 | - Separate COPY of requirements.txt from source code. 8 | - CMD vs ENTRYPOINT: ENTRYPOINT is the main command. Treat 9 | CMD as the default flag for the entrypoint. Example: 10 | ``` 11 | ENTRYPOINT ["s3cmd"] 12 | CMD ["--help"] 13 | ``` 14 | - Bind to 0.0.0.0. Otherwise you get issue with Kubernetes. 15 | - Make services have healthcheck endpoints. 16 | - Switch to non-root-user 17 | ``` 18 | RUN groupadd -r myapp && useradd -r -g myapp myapp 19 | USER myapp 20 | ``` 21 | - Log everything to STDOUT. 22 | - One process per container. 23 | - Limit access from network. Example: 24 | ``` 25 | docker network create --driver bridge isolated_nw 26 | docker run --network=isolated_nw --name=container busybox 27 | ``` 28 | - Support SIGTERM, SIGKILL and SIGINT to exit gracefully. 29 | - 1 Process per container. 30 | - No supervisord, uWSGI 1 worker. 31 | 32 | ## Removing images and conatiners with no tags 33 | 34 | ``` 35 | #!/bin/bash 36 | 37 | # Delete all stopped containers 38 | sudo docker rm $(sudo docker ps -q -f status=exited) 39 | # Delete all dangling (unused) images 40 | sudo docker rmi $(sudo docker images -q -f dangling=true) 41 | ``` 42 | 43 | ### Alternative using --no-run-if-empty 44 | 45 | xargs with `--no-run-if-empty` is even better as it does cleanly handle the case when there is nothing to be removed. 46 | 47 | ``` 48 | #!/bin/bash 49 | 50 | # Delete all stopped containers 51 | sudo docker ps -q -f status=exited | xargs --no-run-if-empty sudo docker rm 52 | # Delete all dangling (unused) images 53 | sudo docker images -q -f dangling=true | xargs --no-run-if-empty sudo docker rmi 54 | ``` 55 | 56 | Alternative: deleting images with no tags 57 | 58 | `sudo docker rmi $(sudo docker images | grep "^" | awk '{print $3}')` 59 | 60 | ## Resources 61 | - https://docs.docker.com/engine/userguide/eng-image/dockerfile_best-practices/ 62 | - https://github.com/FuriKuri/docker-best-practices 63 | - [3 tricks for mastering Docker with Python](https://hackernoon.com/3-tricks-for-mastering-docker-with-python-99876412348d#.aljoaimgx) 64 | - https://gist.github.com/ngpestelos/4fc2e31e19f86b9cf10b#gistcomment-1769502 65 | -------------------------------------------------------------------------------- /python.md: -------------------------------------------------------------------------------- 1 | # Python Best Practices 2 | 3 | > A universal convention supplies all of maintainability, clarity, consistency, and a foundation for 4 | > good programming habits too. What it doesn't do is insist that you follow it against your will. 5 | > That's Python! [Tim Peters on comp.lang.python, 2001-06-16] 6 | 7 | ## Style Guide 8 | 9 | Use Google's Python Style Guide [[1](http://sphinxcontrib-napoleon.readthedocs.org/en/latest/example_google.html) 10 | and [2](https://google-styleguide.googlecode.com/svn/trunk/pyguide.html)]. 11 | Documentation can be automatically generated with 12 | [Napoloen](http://sphinxcontrib-napoleon.readthedocs.org/en/latest/index.html). 13 | 14 | ## Project Structure 15 | 16 | See my [cookiecutter pypackage](https://github.com/ksindi/cookiecutter-pypackage). 17 | 18 | ## Linting 19 | 20 | Use [flake8](https://flake8.readthedocs.io/en/latest/). 21 | 22 | Tip: add `#noQA: E123` (replace with actual error code) at end of line to ignore a line and `# flake8: noqa` to ignore file. Python style error codes: https://pycodestyle.readthedocs.io/en/latest/intro.html#error-codes. 23 | 24 | ## Unit testing 25 | 26 | Use [doctest](https://docs.python.org/3/library/doctest.html) for small utility functions that never change. 27 | 28 | Use [pytest](http://doc.pytest.org/en/latest/) for larger unittests. 29 | 30 | Other tools: [mock](https://pypi.python.org/pypi/mock) 31 | 32 | ## Commits 33 | 34 | Commit messages should be in the form: `{prefix} [{ticket}] {descriptive message}`. 35 | 36 | Example: `ENH [TICKET-123] add foo script` 37 | 38 | Label prefixes follow pandas [guidelines](http://pandas.pydata.org/pandas-docs/stable/contributing.html#committing-your-code): 39 | 40 | > ENH: Enhancement, new functionality 41 | > BUG: Bug fix 42 | > DOC: Additions/updates to documentation 43 | > TST: Additions/updates to tests 44 | > BLD: Updates to the build process/scripts 45 | > PERF: Performance improvement 46 | > CLN: Code cleanup 47 | 48 | ## Recommended Libraries 49 | 50 | - [attrs](https://attrs.readthedocs.io/en/stable/) 51 | - [requests](http://docs.python-requests.org/en/master/) 52 | - [tqdm](https://github.com/noamraph/tqdm) 53 | - [fire](https://github.com/google/python-fire) 54 | - [joblib](https://pythonhosted.org/joblib/parallel.html) 55 | - [udatetime](https://github.com/freach/udatetime) 56 | - [jinjasql](https://github.com/hashedin/jinjasql) 57 | - [maya](https://github.com/kennethreitz/maya) 58 | - [pipenv](https://github.com/kennethreitz/pipenv) 59 | 60 | ## Resources 61 | 62 | List of resources that advise on Python best practices, in order of relevance: 63 | - [Effective Python](http://www.amazon.com/Effective-Python-Specific-Software-Development/dp/0134034287) by Brett Slatkin [Book] 64 | - [Refactoring Python](https://speakerdeck.com/pycon2016/brett-slatkin-refactoring-python-why-and-how-to-restructure-your-code) [Slides] 65 | - [Elements of Python Style](https://github.com/amontalenti/elements-of-python-style) [URL] 66 | - [Beyond PEP 8](https://www.youtube.com/watch?v=wf-BqAjZb8M) [Video] 67 | - [Writing Python 2-3 compatible code](http://python-future.org/compatible_idioms.html) [URL] 68 | - [Transforming Code into Beautiful, Idiomatic Python](https://www.youtube.com/watch?v=OSGv2VnC0go) [Video] 69 | - [Python Best Practice Patterns by Vladimir Keleshev](http://stevenloria.com/python-best-practice-patterns-by-vladimir-keleshev-notes/) [URL] 70 | - [What's New In Python 3.6](https://docs.python.org/3/whatsnew/3.6.html) 71 | - [Effective Python in Python 3.6](https://speakerdeck.com/hayaosuzuki/effective-python-in-python-3-dot-6) 72 | 73 | ## More Python Resources 74 | - [New data structures in Python 3](https://github.com/topper-123/Articles/blob/master/New-interesting-data-types-in-Python3.rst) 75 | - [Undestanding the Python GIL](https://www.slideshare.net/dabeaz/understanding-the-python-gil) 76 | - [Python 3 FAQ by eev.ee](https://eev.ee/blog/2016/07/31/python-faq-why-should-i-use-python-3/) 77 | - [Python with type hints](http://www.daveoncode.com/2017/03/06/writing-better-software-with-python-3-6-type-hints) 78 | 79 | ## Examples of Well Written Python Code 80 | 81 | Code repositories that make good use of the language: 82 | 83 | - [requests](https://github.com/kennethreitz/requests) 84 | - [joblib](https://github.com/joblib/joblib) 85 | - [moviepy](https://github.com/Zulko/moviepy) 86 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /relational_databases.md: -------------------------------------------------------------------------------- 1 | Relational Database Best Practices 2 | 3 | _Adapted from Silicon Age Relational Database Conventions v1.1_ 4 | 5 | - [Tables](#tables) 6 | - [Fields](#fields) 7 | - [Identities](#identities) 8 | - [Integrity](#integrity) 9 | - [Other Database Objects](#other-database-objects) 10 | - [Tracking](#tracking) 11 | - [Normalization](#normalization) 12 | - [Design Best Practices](#design-best-practices) 13 | - [Appendix A: Common Abbreviations/Acronyms](#appendix-a-common-abbreviationsacronyms) 14 | - [Appendix R: Reserved Words](#appendix-r-reserved-words) 15 | - [Appendix T: Sample Triggers](#appendix-t-sample-triggers) 16 | 17 | ## Tables 18 | 19 | - Table names will be singular nouns. 20 | - The initial character of each table name and the first character of 21 | each *significant* word in a table name should be uppercase. All 22 | other characters should be lowercase. 23 | - Separate words in table names will be separated by underscores. 24 | - Table names will be restricted to 30 characters. 25 | - Words reserved by common databases may not be used as table names. 26 | - Words may not be abbreviated unless the abbreviation is clear, 27 | documented, and is used consistently within the data model. 28 | - If a table Y provides the principal classification of the rows of 29 | another table X and, in addition, is both slowly-changing and 30 | single-level, it should be named "X\_Type". 31 | - Table names may not be generic collective words like "Group" or "Set". 32 | - Self-referencing, hierarchical tables should have the morpheme 33 | "\_Tree" appended to their names. The "\_Tree" morpheme should *not* 34 | be included in the name of the primary key because the values 35 | contained therein do not have a tree structure. Likewise, 36 | association tables joining a self-referencing table should not 37 | include the "\_Tree" in their name. 38 | - Tables implementing many-to-many relationships should be given names 39 | like "X\_to\_Y" where X and Y are the names of the other tables. The 40 | tables represented by X and Y should be included in the name in 41 | alphabetical order, i.e. Exercise_to_Member, not 42 | Member\_to\_Exercise. The "to" is not capitalized in the name of a 43 | table. Whenever possible, eschew table names of the form "X\_to\_Y", 44 | replacing them with precise names for the relationship. 45 | - Table names of the form X\_to\_Y\_to\_Z are not allowed; at least 46 | one of the subrelationships (X\_to\_Y or X\_to\_Z) should be 47 | renamed. 48 | 49 | **Table naming examples:** 50 | 51 | | Example | Rating | Reason | 52 | |---------------|--------|----------------------------------------------------| 53 | | Level | Bad | "Level" is a reserved word in SQL Server | 54 | | dexter | Bad | First letters should be capitalized | 55 | | Zip\_Codes | Bad | Plural and "ZIP" should be capitalized | 56 | | Receipt | Good | | 57 | | StarWars | Bad | Words should be separated by underscores | 58 | | Criteria | Bad | "Criteria" is plural; should be "Criterion" | 59 | | Thrashed | Bad | Not a noun | 60 | | Turkey\_Pie | Good | | 61 | | Age\_of\_Emps | Bad | "of" should be capitalized and "Emps" is not clear | 62 | 63 | 64 | ## Fields 65 | 66 | - Field names will be singular nouns or verb phrases. 67 | - Field names will be entirely lowercase. 68 | - Separate words in field names will be divided by underscores. 69 | - Field names will be restricted to 30 characters. 70 | - Surrogate keys will be named "id". Foreign keys will have associated 71 | table name prepended. 72 | - Words reserved by common databases may not be used as field names. 73 | - Words may not be abbreviated unless the abbreviation is clear and is 74 | used consistently within the data model (see 75 | [Appendix A](#appendix-a-common-abbreviationsacronyms)). 76 | - A field which contains numbers indicated the order in which its 77 | elements should be displayed or processed should be called "seq". 78 | If multiple sequences are necessary, a role descriptor should be 79 | prepended to "seq" as in "display\_seq". 80 | - Most tables should contain textual fields called "description" and 81 | "note". The desc field should contain information that could be 82 | displayed to a user or client detailing the row. The note field 83 | should contain internal information of interest to data entry 84 | operators or system administrators. 85 | - The field name "name" is suggested for names that will be meaningful 86 | for frequent external users of the system ("Serial Port 25M"). 87 | "long\_name" is suggested for names that beginners will need 88 | ("Serial Port, RS232C, 25-pin, male"). "short\_name" is suggested 89 | for names that can be used for experts ("RS232C-25m") in order to 90 | save room. Not all of these three fields need always be present, 91 | though if long\_name or short\_name is present, name should also be. 92 | - Tables with data that will need to be statically bound to by 93 | developers should contain a "code" column. This column should 94 | contain only capital letters, underscores and no whitespace 95 | characters. This column should be uniquely indexed. Consider, for 96 | example, the following table: 97 | ```sql 98 | CREATE TABLE Department ( 99 | id INT PRIMARY KEY, 100 | code VARCHAR(50) NOT NULL UNIQUE CHECK((UPPER(code) = code) AND (INSTR(code, ' ') = 0)), 101 | name VARCHAR(100) NOT NULL UNIQUE 102 | ); 103 | ``` 104 | 105 | Typical entries in the name field would include "Human 106 | Resources" and "Engineering". Related code entries would include 107 | "HUMAN\_RESOURCES" and "ENGINEERING". 108 | 109 | ## Identities 110 | 111 | - Surrogate keys will have an integral data type whose size is 112 | approximately 32 bits. 113 | - Identities will start at 1000 and increment by one (except for ids 114 | described herein). 115 | - Surrogate keys will always have the following eight special 116 | one-digit codes used to encode various common types of missing data: 117 | 118 | | ID | Name | Meaning (Example: Person.hat\_id) | 119 | |----|----------------|---------------------------------------| 120 | | 1 | None | has no hat (and we know it) | 121 | | 2 | Not Applicable | logically inconsistent to have hat (Person.is_alive = 0) | 122 | | 3 | Unspecified | may be associated but unknown (new inserts) | 123 | | 4 | Unknown | unknown after efforts to get state | 124 | | 5 | Custom | can't be properly associated with Hat | 125 | | 6 | Structural or Internal | for referential integrity (Hat.color\_id for Hat.hat\_id between 1 and 8) | 126 | | 7 | Error | error occurred in generation of id | 127 | | 8 | Inherit | field obtained from other part of data model | 128 | 129 | - Some tables may require additional special codes, most frequently 130 | for different types of inheritance. They should be given 2- or 131 | 3-digit codes as appropriate. 132 | 133 | ## Integrity 134 | 135 | - All tables will have primary keys. 136 | - All logical foreign key relationships will be created; if 137 | performance considerations prevent their use, they should be 138 | disabled, not deleted. 139 | - Nearly every table should have a surrogate key which forms its 140 | (entire) primary key. 141 | - NULLs should appear only when a field is inapplicable to the row 142 | because of polymorphism. In some databases NULL may also be used 143 | to indicate the empty string if it is syntactically identical to 144 | ''. In addition, some databases treat NULL textual fields far more 145 | (space-)efficiently than empty textual fields; in these cases the 146 | use of NULL may be preferable. In all other cases, NULL values 147 | should not appear and fields should be declared "NOT NULL". 148 | - The status of unavailable data should be indicated using the following 149 | convention: 150 | 151 | - For foreign keys to surrogate keys (that is, id fields), the 152 | standard single-digit codes should be used along with any 153 | specific two- or three-digit codes defined only for that table 154 | (see [Identities](#identities)). 155 | - For character data, the following characters, codes, or strings 156 | should be used to indicate the status of the field. These obviously 157 | encode special cases which should be checked by applications in 158 | order to perform the correct action. 159 | 160 | | Meaning | 1-2 Chars | 3-14 Chars | 15+ Chars | 161 | |-------------|-----------|------------|------------------| 162 | | None | ‘-’ | ‘—’ | ‘None’ | 163 | | Not App. | ‘/’ | ‘///’ | ‘Not Applicable’ | 164 | | Unspecified | ‘?’ | ‘???’ | ‘Unspecified’ | 165 | | Unknown | ‘&’ | ‘&&&’ | ‘Unknown’ | 166 | | Custom | ‘~’ | ‘~~~’ | ‘Custom’ | 167 | | Structural | ‘\#’ | ‘\#\#\#’ | ‘Structural’ | 168 | | Error | ‘!’ | ‘!!!’ | ‘Error’ | 169 | | Inherit | ‘^’ | ‘^^^’ | ‘Inherit’ | 170 | 171 | *An attempt has been made to choose codes that will not interfere 172 | with real data. In the event that they do, choose appropriate codes 173 | and document the deviation from the standard.* 174 | 175 | - Where appropriate, character fields should DEFAULT to the appropriate 176 | value which, in most cases, will be '?', '???', or 'Unspecified'. 177 | - All foreign keys should be NOT NULL. 178 | 179 | ## Other Database Objects 180 | 181 | - Views should follow the naming conventions for tables except that 182 | the morpheme "\_v" should be appended to the name (without altering 183 | field names in any way). 184 | - Indexes 185 | - Primary Key indexes should be named XPK\_[Table]. The X 186 | indicates an index and PK signifies a primary key. 187 | - Foreign Key indexes should be named XFK[sequence the index was 188 | created]\_[Table]. 189 | - Unique Keys should be named XAK[sequence the index was 190 | created]\_[Table]. The AK stands for alternate key. 191 | - Other indexes should be name X[sequence the index was 192 | created]\_[Table] 193 | - Triggers should be named [Table]\_tr\_[Action][Timing], where 194 | [Action] is some combination of "i", "u", "d", and "s" indicating 195 | insert, update, delete, and select respectively. If the database 196 | allows the specification of BEFORE and AFTER triggers (as Oracle 197 | does), the Timing variable should be replaced with "b" or "a". 198 | - Named defaults should have "\_df" appended to their names. 199 | - Denormalized tables that are automatically maintained by triggers, 200 | background processes, or other means should have "\_d" appended to 201 | their names. 202 | - User defined types should have "\_t" appended to their names. 203 | - Stored procedures should have "\_sp" appended to their names. 204 | 205 | ## Tracking 206 | 207 | - All tables should have fields named "inserted" and "updated" that 208 | contain the times at which each row was inserted and last updated. 209 | - Whenever performance considerations allow, the inserted and updated 210 | fields should be maintained by triggers. See 211 | [Appendix T](#appendix-t-sample-triggers) for examples. 212 | - Columns used to indicate the first and last dates (or other ranges) 213 | of validity for a row should be named "start\_date" and 214 | "end\_date" respectively. "9999-01-01" should be used as the 215 | general code for a row that is currently valid and has no specified 216 | date of invalidation. 217 | 218 | ## Normalization 219 | 220 | - All data models should be in 221 | [Boyce-Codd normal form](https://en.wikipedia.org/wiki/Boyce%E2%80%93Codd_normal_form); 222 | BCNF is slightly stronger than 223 | [Third normal form](https://en.wikipedia.org/wiki/Third_normal_form) 224 | and, in most cases, is equivalent to it. 225 | - Denormalization from this standard should be documented and 226 | justified. 227 | 228 | ## Design Best Practices 229 | 230 | - Measurements 231 | - When storing measurement information such as mass, length, 232 | volume, time, etc. choose one unit of measurement that will be 233 | used throughout the database and separately store the display 234 | method preferred by the user and a list of conversions from the 235 | base unit. 236 | - Recommended standards of measurement are kilograms, meters, 237 | cubic meters, and the number of milliseconds since January 1, 238 | 1970 for time/date fields (epoch time). 239 | - Self-Referencing Tables 240 | - The column that references the primary-key of the table will 241 | generally be called parent\_[name of the id column]. For 242 | example, if the table was named Turkey\_Pie, the primary key 243 | would be turkey\_pie\_id and the column referencing 244 | turkey\_pie\_id would be parent\_turkey\_pie\_id. 245 | - The parent id of top-level entries should have their parent\_id 246 | set to the primary key. 247 | 248 | ## Appendix A: Common Abbreviations/Acronyms 249 | Document the use of any abbreviation when used for naming 250 | database objects no matter how common the usage. 251 | 252 | | Abbreviation/Acronym | Expansion | 253 | |----------------------|--------------| 254 | | cls | class | 255 | | grp | group | 256 | | param | parameter | 257 | | qty | quantity | 258 | | seq | sequence | 259 | | std | standard | 260 | | str | string | 261 | | sys | system | 262 | | val | value | 263 | 264 | Any standard measurement reductions such as "mi" for mile and 265 | "km" for kilometer. 266 | 267 | ## Appendix R: Reserved Words 268 | Not Available 269 | 270 | ## Appendix T: Sample Triggers 271 | Not Available 272 | --------------------------------------------------------------------------------