├── .github └── workflows │ └── python-driver-test.yaml ├── .gitignore ├── LICENSE ├── README.md ├── agensgraph ├── __init__.py ├── _edge.py ├── _graphid.py ├── _graphpath.py ├── _property.py └── _vertex.py ├── setup.py └── tests ├── __init__.py ├── test_agensgraph.py ├── test_edge.py ├── test_graphid.py ├── test_graphpath.py ├── test_property.py └── test_vertex.py /.github/workflows/python-driver-test.yaml: -------------------------------------------------------------------------------- 1 | name: Python Driver Tests 2 | 3 | on: 4 | push: 5 | branches: [ '*' ] 6 | paths-ignore: 7 | - 'README.md' 8 | - 'VERSION.md' 9 | pull_request: 10 | branches: [ '*' ] 11 | paths-ignore: 12 | - 'README.md' 13 | - 'VERSION.md' 14 | jobs: 15 | driver-ci: 16 | runs-on: ubuntu-latest 17 | 18 | steps: 19 | - name: Get latest commit id of AgensGraph 20 | run: | 21 | echo "AG_COMMIT_HASH=$(git ls-remote https://github.com/skaiworldwide-oss/agensgraph.git HEAD | awk '{print $1}')" >> $GITHUB_ENV 22 | 23 | - name: Cache AgensGraph Build 24 | uses: actions/cache@v3 25 | id: agcache 26 | with: 27 | path: ~/agensgraph_build 28 | key: ${{ runner.os }}-v1-agensgraph-${{ env.AG_COMMIT_HASH }} 29 | 30 | - name: Install System Dependencies 31 | run: | 32 | sudo apt-get update 33 | sudo apt-get install -y \ 34 | build-essential \ 35 | libreadline-dev \ 36 | zlib1g-dev \ 37 | flex \ 38 | bison \ 39 | python3-dev \ 40 | libpq-dev \ 41 | git 42 | 43 | - name: Clone and Build AgensGraph 44 | if: steps.agcache.outputs.cache-hit != 'true' 45 | run: | 46 | git clone https://github.com/skaiworldwide-oss/agensgraph.git ~/agensgraph_source 47 | cd ~/agensgraph_source 48 | ./configure --prefix=$HOME/agensgraph_build 49 | make -j$(nproc) 50 | make install 51 | 52 | - name: Set Environment Variables 53 | run: | 54 | echo "AGDATA=$HOME/agens_data" >> $GITHUB_ENV 55 | echo "LD_LIBRARY_PATH=$HOME/agensgraph_build/lib:$LD_LIBRARY_PATH" >> $GITHUB_ENV 56 | echo "PATH=$HOME/agensgraph_build/bin:$PATH" >> $GITHUB_ENV 57 | 58 | - name: Initialize DB Cluster 59 | run: | 60 | mkdir -p "$HOME/agens_data" 61 | $HOME/agensgraph_build/bin/initdb -D "$HOME/agens_data" 62 | 63 | - name: Start AgensGraph 64 | run: | 65 | $HOME/agensgraph_build/bin/ag_ctl start -D "$HOME/agens_data" -l "$HOME/agens_data/server.log" 66 | sleep 10 67 | 68 | - name: Create test database 69 | run: | 70 | $HOME/agensgraph_build/bin/createdb agensgraph_test 71 | 72 | - name: Checkout Python Driver 73 | uses: actions/checkout@v4 74 | 75 | - name: Set up Python 76 | uses: actions/setup-python@v4 77 | with: 78 | python-version: '3.10' 79 | 80 | - name: Build package 81 | run: | 82 | python setup.py install 83 | 84 | - name: Run regression tests 85 | env: 86 | AGENGRAPH_TESTDB: agensgraph_test 87 | AGENGRAPH_TESTDB_HOST: localhost 88 | AGENGRAPH_TESTDB_PORT: 5432 89 | AGENGRAPH_TESTDB_USER: runner 90 | AGENGRAPH_TESTDB_PASSWORD: runner 91 | run: | 92 | python setup.py test 93 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .eggs/ 2 | build 3 | dist 4 | *.egg-info/ 5 | *.pyc 6 | *.swp 7 | .idea -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # AgensGraph Python Driver 2 | 3 | AgensGraph Python Driver allows Python programs to connect to an AgensGraph database. Since it is [Psycopg2](http://initd.org/psycopg/) type extension module for AgensGraph, it supports additional data types such as `Vertex`, `Edge`, and `Path` to represent graph data. 4 | 5 | ## Features 6 | - Cypher query support for Psycopg2 PostgreSQL Python driver (enables cypher queries directly) 7 | - Deserialize AgensGraph results (AGType) to Vertex, Edge, Path 8 | 9 | ## Build From Source 10 | 11 | ```sh 12 | git clone https://github.com/skaiworldwide-oss/agensgraph-python 13 | cd agensgraph-python 14 | python setup.py install 15 | ``` 16 | 17 | ## Example 18 | 19 | ```python 20 | import psycopg2 21 | import agensgraph 22 | 23 | conn = psycopg2.connect("dbname=test host=127.0.0.1 user=agens") 24 | cur = conn.cursor() 25 | cur.execute("DROP GRAPH IF EXISTS t CASCADE") 26 | cur.execute("CREATE GRAPH t") 27 | cur.execute("SET graph_path = t") 28 | 29 | cur.execute("CREATE (:v {name: 'AgensGraph'})") 30 | conn.commit(); 31 | 32 | cur.execute("MATCH (n) RETURN n") 33 | v = cur.fetchone()[0] 34 | print(v.props['name']) 35 | ``` 36 | 37 | ## Test 38 | 39 | You may run the following command to test AgensGraph Python Driver. 40 | 41 | ```sh 42 | python setup.py test 43 | ``` 44 | 45 | Before running the command, set the following environment variables to specify which database you will use for the test. 46 | 47 | Variable Name | Meaning 48 | ---------------------------- | --------------------------- 49 | `AGENSGRAPH_TESTDB` | database name to connect to 50 | `AGENSGRAPH_TESTDB_HOST` | database server host 51 | `AGENSGRAPH_TESTDB_PORT` | database server port 52 | `AGENSGRAPH_TESTDB_USER` | database user name 53 | `AGENSGRAPH_TESTDB_PASSWORD` | user password 54 | -------------------------------------------------------------------------------- /agensgraph/__init__.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Copyright (c) 2014-2017, Bitnine Inc. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | ''' 16 | 17 | from psycopg2 import extensions as _ext 18 | 19 | from agensgraph._graphid import ( 20 | GraphId, cast_graphid as _cast_graphid, adapt_graphid as _adapt_graphid) 21 | from agensgraph._vertex import Vertex, cast_vertex as _cast_vertex 22 | from agensgraph._edge import Edge, cast_edge as _cast_edge 23 | from agensgraph._graphpath import Path, cast_graphpath as _cast_graphpath 24 | from agensgraph._property import Property 25 | 26 | _GRAPHID_OID = 7002 27 | _VERTEX_OID = 7012 28 | _EDGE_OID = 7022 29 | _GRAPHPATH_OID = 7032 30 | 31 | GRAPHID = _ext.new_type((_GRAPHID_OID,), 'GRAPHID', _cast_graphid) 32 | _ext.register_type(GRAPHID) 33 | _ext.register_adapter(GraphId, _adapt_graphid) 34 | 35 | VERTEX = _ext.new_type((_VERTEX_OID,), 'VERTEX', _cast_vertex) 36 | _ext.register_type(VERTEX) 37 | 38 | EDGE = _ext.new_type((_EDGE_OID,), 'EDGE', _cast_edge) 39 | _ext.register_type(EDGE) 40 | 41 | PATH = _ext.new_type((_GRAPHPATH_OID,), 'PATH', _cast_graphpath) 42 | _ext.register_type(PATH) 43 | 44 | __all__ = ['GraphId', 'Vertex', 'Edge', 'Path', 'Property', 45 | 'GRAPHID', 'VERTEX', 'EDGE', 'PATH'] 46 | -------------------------------------------------------------------------------- /agensgraph/_edge.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Copyright (c) 2014-2017, Bitnine Inc. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | ''' 16 | 17 | import re 18 | 19 | from psycopg2 import InterfaceError 20 | from psycopg2.extras import json 21 | 22 | from agensgraph._graphid import cast_graphid 23 | 24 | _pattern = re.compile(r'(.+?)\[(.+?)\]\[(.+?),(.+?)\](.*)', re.S) 25 | 26 | class Edge(object): 27 | def __init__(self, label, eid, start, end, props): 28 | self.label = label 29 | self.eid = eid 30 | self.start = start 31 | self.end = end 32 | self.props = props 33 | 34 | def __eq__(self, other): 35 | if isinstance(self, other.__class__): 36 | return self.eid == other.eid 37 | return False 38 | 39 | def __repr__(self): 40 | return "%s(%s)" % (self.__class__.__name__, self) 41 | 42 | def __str__(self): 43 | return "%s[%s][%s,%s]%s" % (self.label, self.eid, self.start, self.end, 44 | json.dumps(self.props)) 45 | 46 | def cast_edge(value, cur): 47 | if value is None: 48 | return None 49 | 50 | m = _pattern.match(value) 51 | if m: 52 | label = m.group(1) 53 | eid = cast_graphid(m.group(2), cur) 54 | start = cast_graphid(m.group(3), cur) 55 | end = cast_graphid(m.group(4), cur) 56 | props = json.loads(m.group(5)) 57 | return Edge(label, eid, start, end, props) 58 | else: 59 | raise InterfaceError("bad edge representation: %s" % value) 60 | -------------------------------------------------------------------------------- /agensgraph/_graphid.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Copyright (c) 2014-2017, Bitnine Inc. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | ''' 16 | 17 | import re 18 | 19 | from psycopg2 import InterfaceError 20 | from psycopg2.extensions import AsIs 21 | 22 | _pattern = re.compile(r'(\d+)\.(\d+)') 23 | 24 | class GraphId(object): 25 | def __init__(self, gid): 26 | self.gid = gid 27 | 28 | def getId(self): 29 | return self.gid 30 | 31 | def __eq__(self, other): 32 | if isinstance(self, other.__class__): 33 | return self.gid == other.gid 34 | return False 35 | 36 | def __repr__(self): 37 | return "%s(%s)" % (self.__class__.__name__, self) 38 | 39 | def __str__(self): 40 | return "%d.%d" % self.gid 41 | 42 | def cast_graphid(value, cur): 43 | if value is None: 44 | return None 45 | 46 | m = _pattern.match(value) 47 | if m: 48 | labid = int(m.group(1)) 49 | locid = int(m.group(2)) 50 | gid = (labid, locid) 51 | return GraphId(gid) 52 | else: 53 | raise InterfaceError("bad graphid representation: %s" % value) 54 | 55 | def adapt_graphid(graphid): 56 | return AsIs("'%s'" % graphid) 57 | -------------------------------------------------------------------------------- /agensgraph/_graphpath.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Copyright (c) 2014-2017, Bitnine Inc. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | ''' 16 | 17 | from psycopg2 import InterfaceError 18 | 19 | from agensgraph._vertex import cast_vertex 20 | from agensgraph._edge import cast_edge 21 | 22 | class Path(object): 23 | def __init__(self, vertices, edges): 24 | self.vertices = vertices 25 | self.edges = edges 26 | 27 | def __eq__(self, other): 28 | if isinstance(self, other.__class__): 29 | return self.vertices == other.vertices and self.edges == other.edges 30 | return False 31 | 32 | def __len__(self): 33 | return len(self.edges) 34 | 35 | def __repr__(self): 36 | return "%s(%s)" % (self.__class__.__name__, self) 37 | 38 | def __str__(self): 39 | p = [None] * (len(self.vertices) + len(self.edges)) 40 | p[::2] = [str(v) for v in self.vertices] 41 | p[1::2] = [str(e) for e in self.edges] 42 | return "[%s]" % ','.join(p) 43 | 44 | def cast_graphpath(value, cur): 45 | if value is None: 46 | return None 47 | 48 | tokens = [] 49 | 50 | # ignore wrapping '[' and ']' characters 51 | pos = 1 52 | length = len(value) - 1 53 | 54 | start = pos 55 | depth = 0 56 | gid = False 57 | 58 | while pos < length: 59 | c = value[pos] 60 | if c == '"': 61 | if depth > 0: 62 | # Parse "string". 63 | # Leave pos unchanged if unmatched right " were found. 64 | 65 | escape = False 66 | i = pos + 1 67 | 68 | while i < length: 69 | c = value[i] 70 | if c == '\\': 71 | escape = not escape 72 | elif c == '"': 73 | if escape: 74 | escape = False 75 | else: 76 | pos = i 77 | break 78 | else: 79 | escape = False 80 | 81 | i += 1 82 | elif c == '[' and depth == 0: 83 | gid = True 84 | elif c == ']' and depth == 0: 85 | gid = False 86 | elif c == '{': 87 | depth += 1 88 | elif c == '}': 89 | depth -= 1 90 | if depth < 0: 91 | raise InterfaceError("bad graphpath representation: %s" % value) 92 | elif c == ',' and depth == 0 and not gid: 93 | tokens.append(value[start:pos]) 94 | start = pos + 1 95 | 96 | pos += 1 97 | 98 | tokens.append(value[start:pos]) 99 | 100 | vertices = [cast_vertex(t, cur) for t in tokens[0::2]] 101 | edges = [cast_edge(t, cur) for t in tokens[1::2]] 102 | return Path(vertices, edges) 103 | -------------------------------------------------------------------------------- /agensgraph/_property.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Copyright (c) 2014-2018, Bitnine Inc. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | ''' 16 | 17 | import sys 18 | 19 | from psycopg2.extensions import ISQLQuote 20 | from psycopg2.extras import json 21 | 22 | # borrowed from simplejson's compat.py 23 | if sys.version_info[0] < 3: 24 | string_types = (basestring,) 25 | integer_types = (int, long) 26 | def dict_items(o): 27 | return o.iteritems() 28 | else: 29 | string_types = (str,) 30 | integer_types = (int,) 31 | def dict_items(o): 32 | return o.items() 33 | 34 | def quote_string(s): 35 | s = s[1:-1] 36 | s = "'" + s.replace("'", "''") + "'" 37 | return s 38 | 39 | class PropertyEncoder(object): 40 | def encode(self, o): 41 | chunks = self.iterencode(o) 42 | if not isinstance(chunks, (list, tuple)): 43 | chunks = list(chunks) 44 | return ''.join(chunks) 45 | 46 | def iterencode(self, o): 47 | markers = {} 48 | _iterencode = _make_iterencode(markers, json.dumps, quote_string) 49 | return _iterencode(o) 50 | 51 | def _make_iterencode(markers, _encoder, _quote_string, 52 | dict=dict, 53 | float=float, 54 | id=id, 55 | isinstance=isinstance, 56 | list=list, 57 | tuple=tuple, 58 | string_types=string_types, 59 | integer_types=integer_types, 60 | dict_items=dict_items): 61 | def _iterencode_list(o): 62 | if not o: 63 | yield '[]' 64 | return 65 | 66 | markerid = id(o) 67 | if markerid in markers: 68 | raise ValueError('Circular reference detected') 69 | markers[markerid] = o 70 | 71 | yield '[' 72 | first = True 73 | for e in o: 74 | if first: 75 | first = False 76 | else: 77 | yield ',' 78 | 79 | for chunk in _iterencode(e): 80 | yield chunk 81 | yield ']' 82 | 83 | del markers[markerid] 84 | 85 | def _iterencode_dict(o): 86 | if not o: 87 | yield '{}' 88 | return 89 | 90 | markerid = id(o) 91 | if markerid in markers: 92 | raise ValueError('Circular reference detected') 93 | markers[markerid] = o 94 | 95 | yield '{' 96 | first = True 97 | for k, v in dict_items(o): 98 | if isinstance(k, string_types): 99 | pass 100 | elif (k is True or k is False or k is None or 101 | isinstance(k, integer_types) or isinstance(k, float)): 102 | k = _encoder(k) 103 | else: 104 | raise TypeError('keys must be str, int, float, bool or None, ' 105 | 'not %s' % k.__class__.__name__) 106 | 107 | if first: 108 | first = False 109 | else: 110 | yield ',' 111 | 112 | yield _quote_string(_encoder(k)) 113 | yield ':' 114 | for chunk in _iterencode(v): 115 | yield chunk 116 | yield '}' 117 | 118 | del markers[markerid] 119 | 120 | def _iterencode(o): 121 | if isinstance(o, string_types): 122 | yield _quote_string(_encoder(o)) 123 | elif isinstance(o, (list, tuple)): 124 | for chunk in _iterencode_list(o): 125 | yield chunk 126 | elif isinstance(o, dict): 127 | for chunk in _iterencode_dict(o): 128 | yield chunk 129 | else: 130 | yield _encoder(o) 131 | 132 | return _iterencode 133 | 134 | _default_encoder = PropertyEncoder() 135 | 136 | class Property(object): 137 | def __init__(self, value): 138 | self.value = value 139 | 140 | def __conform__(self, proto): 141 | if proto is ISQLQuote: 142 | return self 143 | 144 | def prepare(self, conn): 145 | self._conn = conn 146 | 147 | def getquoted(self): 148 | return _default_encoder.encode(self.value) 149 | -------------------------------------------------------------------------------- /agensgraph/_vertex.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Copyright (c) 2014-2017, Bitnine Inc. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | ''' 16 | 17 | import re 18 | 19 | from psycopg2 import InterfaceError 20 | from psycopg2.extras import json 21 | 22 | from agensgraph._graphid import cast_graphid 23 | 24 | _pattern = re.compile(r'(.+?)\[(.+?)\](.*)', re.S) 25 | 26 | class Vertex(object): 27 | def __init__(self, label, vid, props): 28 | self.label = label 29 | self.vid = vid 30 | self.props = props 31 | 32 | def __eq__(self, other): 33 | if isinstance(self, other.__class__): 34 | return self.vid == other.vid 35 | return False 36 | 37 | def __repr__(self): 38 | return "%s(%s)" % (self.__class__.__name__, self) 39 | 40 | def __str__(self): 41 | return "%s[%s]%s" % (self.label, self.vid, json.dumps(self.props)) 42 | 43 | def cast_vertex(value, cur): 44 | if value is None: 45 | return None 46 | 47 | m = _pattern.match(value) 48 | if m: 49 | label = m.group(1) 50 | vid = cast_graphid(m.group(2), cur) 51 | props = json.loads(m.group(3)) 52 | return Vertex(label, vid, props) 53 | else: 54 | raise InterfaceError("bad vertex representation: %s" % value) 55 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | 3 | setup( 4 | name='agensgraph', 5 | version='1.0.0', 6 | description='Psycopg2 type extension module for AgensGraph', 7 | install_requires=['psycopg2>=2.5.4'], 8 | 9 | packages=find_packages(exclude=['tests']), 10 | test_suite = "tests", 11 | 12 | author='Junseok Yang', 13 | author_email='jsyang@bitnine.net', 14 | maintainer='Gitae Yun', 15 | maintainer_email='gtyun@bitnine.net', 16 | url='https://github.com/skaiworldwide-oss/agensgraph-python', 17 | license='Apache License Version 2.0', 18 | ) 19 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/skaiworldwide-oss/agensgraph-python/77394115e6db1724a4ce88499b1d357e601bd96b/tests/__init__.py -------------------------------------------------------------------------------- /tests/test_agensgraph.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Copyright (c) 2014-2018, Bitnine Inc. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | ''' 16 | 17 | import os 18 | import unittest 19 | 20 | import psycopg2 21 | 22 | import agensgraph 23 | 24 | dbname = os.environ.get('AGENSGRAPH_TESTDB', 'agensgraph_test') 25 | dbhost = os.environ.get('AGENSGRAPH_TESTDB_HOST', None) 26 | dbport = os.environ.get('AGENSGRAPH_TESTDB_PORT', None) 27 | dbuser = os.environ.get('AGENSGRAPH_TESTDB_USER', None) 28 | dbpass = os.environ.get('AGENSGRAPH_TESTDB_PASSWORD', None) 29 | 30 | dsn = 'dbname=%s' % dbname 31 | if dbhost is not None: 32 | dsn += ' host=%s' % dbhost 33 | if dbport is not None: 34 | dsn += ' port=%s' % dbport 35 | if dbuser is not None: 36 | dsn += ' user=%s' % dbuser 37 | if dbpass is not None: 38 | dsn += ' password=%s' % dbpass 39 | 40 | class TestConnection(unittest.TestCase): 41 | def setUp(self): 42 | self.conn = psycopg2.connect(dsn) 43 | self.cur = self.conn.cursor() 44 | self.cur.execute('DROP GRAPH IF EXISTS t CASCADE') 45 | self.cur.execute('CREATE GRAPH t') 46 | self.cur.execute('SET graph_path = t') 47 | self.conn.commit() 48 | 49 | def tearDown(self): 50 | self.cur.execute('DROP GRAPH t CASCADE') 51 | self.cur.close() 52 | self.conn.close() 53 | 54 | class TestGraphId(TestConnection): 55 | def test_graphid(self): 56 | self.cur.execute('CREATE (n {}) RETURN id(n)') 57 | self.conn.commit() 58 | 59 | gid0 = self.cur.fetchone()[0] 60 | 61 | self.cur.execute("MATCH (n) WHERE id(n) = %s RETURN id(n)", (gid0,)) 62 | gid1 = self.cur.fetchone()[0] 63 | 64 | self.assertEqual(gid1, gid0) 65 | 66 | class TestVertex(TestConnection): 67 | def test_vertex(self): 68 | self.cur.execute( 69 | "CREATE (n:v {s: '', i: 0, b: false, a: [], o: {}}) RETURN n") 70 | self.conn.commit() 71 | 72 | v = self.cur.fetchone()[0] 73 | self.assertEqual('v', v.label) 74 | self.assertEqual('', v.props['s']) 75 | self.assertEqual(0, v.props['i']) 76 | self.assertFalse(v.props['b']) 77 | self.assertEqual([], v.props['a']) 78 | self.assertEqual({}, v.props['o']) 79 | 80 | self.cur.execute("MATCH (n) WHERE id(n) = %s RETURN count(*)", (v.vid,)) 81 | self.assertEqual(1, self.cur.fetchone()[0]) 82 | 83 | class TestEdge(TestConnection): 84 | def test_edge(self): 85 | self.cur.execute( 86 | "CREATE (n)-[r:e {s: '', i: 0, b: false, a: [], o: {}}]->(m)\n" 87 | 'RETURN n, r, m') 88 | self.conn.commit() 89 | 90 | t = self.cur.fetchone() 91 | v0 = t[0] 92 | e = t[1] 93 | v1 = t[2] 94 | 95 | self.assertEqual('e', e.label) 96 | self.assertEqual(e.start, v0.vid) 97 | self.assertEqual(e.end, v1.vid) 98 | self.assertEqual('', e.props['s']) 99 | self.assertEqual(0, e.props['i']) 100 | self.assertFalse(e.props['b']) 101 | self.assertEqual([], e.props['a']) 102 | self.assertEqual({}, e.props['o']) 103 | 104 | self.cur.execute("MATCH ()-[r]->() WHERE id(r) = %s RETURN count(*)", 105 | (e.eid,)) 106 | self.assertEqual(1, self.cur.fetchone()[0]) 107 | 108 | class TestPath(TestConnection): 109 | def test_path(self): 110 | self.cur.execute("CREATE p=({s: '[}\\\\\"'})-[:e]->() RETURN p") 111 | self.conn.commit() 112 | 113 | p = self.cur.fetchone()[0] 114 | self.assertEqual(1, len(p)) 115 | 116 | for v in p.vertices: 117 | self.cur.execute("MATCH (n) WHERE id(n) = %s RETURN count(*)", 118 | (v.vid,)) 119 | self.assertEqual(1, self.cur.fetchone()[0]) 120 | 121 | for e in p.edges: 122 | self.cur.execute( 123 | "MATCH ()-[r]->() WHERE id(r) = %s RETURN count(*)", 124 | (e.eid,)) 125 | self.assertEqual(1, self.cur.fetchone()[0]) 126 | 127 | class TestParam(TestConnection): 128 | def setUp(self): 129 | super(TestParam, self).setUp() 130 | self.name = "'Agens\"Graph'" 131 | 132 | def test_param_dict(self): 133 | d = {'name': self.name, 'since': 2016} 134 | p = agensgraph.Property(d) 135 | self.cur.execute('CREATE (n %s) RETURN n', (p,)) 136 | self.conn.commit() 137 | 138 | v = self.cur.fetchone()[0] 139 | self.assertEqual(self.name, v.props['name']) 140 | self.assertEqual(2016, v.props['since']) 141 | 142 | def test_param_list_and_tuple(self): 143 | a = [self.name, 2016] 144 | t = (self.name, 2016) 145 | pa = agensgraph.Property(a) 146 | pt = agensgraph.Property(t) 147 | self.cur.execute('CREATE (n {a: %s, t: %s}) RETURN n', (pa, pt)) 148 | self.conn.commit() 149 | 150 | v = self.cur.fetchone()[0] 151 | va = v.props['a'] 152 | self.assertEqual(self.name, va[0]) 153 | self.assertEqual(2016, va[1]) 154 | vt = v.props['t'] 155 | self.assertEqual(self.name, vt[0]) 156 | self.assertEqual(2016, vt[1]) 157 | 158 | if __name__ == '__main__': 159 | unittest.main() 160 | -------------------------------------------------------------------------------- /tests/test_edge.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Copyright (c) 2014-2017, Bitnine Inc. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | ''' 16 | 17 | import unittest 18 | 19 | from psycopg2.extras import json 20 | 21 | from agensgraph._edge import Edge, cast_edge 22 | from agensgraph._graphid import GraphId 23 | 24 | class TestEdge(unittest.TestCase): 25 | def setUp(self): 26 | out = 'e[5.7][7.3,7.9]{"s": "", "i": 0, "b": false, "a": [], "o": {}}' 27 | self.e = cast_edge(out, None) 28 | 29 | def test_label(self): 30 | self.assertEqual('e', self.e.label) 31 | 32 | def test_eid(self): 33 | self.assertEqual(GraphId((5, 7)), self.e.eid) 34 | 35 | def test_start(self): 36 | self.assertEqual(GraphId((7, 3)), self.e.start) 37 | 38 | def test_end(self): 39 | self.assertEqual(GraphId((7, 9)), self.e.end) 40 | 41 | def test_props(self): 42 | self.assertEqual('', self.e.props['s']) 43 | self.assertEqual(0, self.e.props['i']) 44 | self.assertFalse(self.e.props['b']) 45 | self.assertEqual([], self.e.props['a']) 46 | self.assertEqual({}, self.e.props['o']) 47 | 48 | def test_eq(self): 49 | self.assertEqual(self.e, self.e) 50 | 51 | def test_str(self): 52 | props = '{"s": "", "i": 0, "b": false, "a": [], "o": {}}' 53 | out = "e[5.7][7.3,7.9]%s" % json.dumps(json.loads(props)) 54 | self.assertEqual(out, str(self.e)) 55 | 56 | def test_repr(self): 57 | self.assertEqual("%s(%s)" % (Edge.__name__, self.e), repr(self.e)) 58 | -------------------------------------------------------------------------------- /tests/test_graphid.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Copyright (c) 2014-2017, Bitnine Inc. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | ''' 16 | 17 | import unittest 18 | 19 | from agensgraph._graphid import GraphId, cast_graphid, adapt_graphid 20 | 21 | class TestGraphId(unittest.TestCase): 22 | def setUp(self): 23 | self.out = '7.9' 24 | self.gid = cast_graphid(self.out, None) 25 | 26 | def test_getId(self): 27 | self.assertEqual((7, 9), self.gid.getId()) 28 | 29 | def test_eq(self): 30 | self.assertEqual(self.gid, self.gid) 31 | 32 | def test_str(self): 33 | self.assertEqual(self.out, str(self.gid)) 34 | 35 | def test_repr(self): 36 | self.assertEqual("%s(%s)" % (GraphId.__name__, self.gid), 37 | repr(self.gid)) 38 | 39 | def test_adapt(self): 40 | self.assertEqual(b"'7.9'", adapt_graphid(self.gid).getquoted()) 41 | -------------------------------------------------------------------------------- /tests/test_graphpath.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Copyright (c) 2014-2017, Bitnine Inc. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | ''' 16 | 17 | import unittest 18 | 19 | from psycopg2.extras import json 20 | 21 | from agensgraph._graphpath import Path, cast_graphpath 22 | 23 | class TestPath(unittest.TestCase): 24 | def setUp(self): 25 | self.o0 = '[n[7.3]{}]' 26 | self.p0 = cast_graphpath(self.o0, None) 27 | self.o1 = '[n[7.3]{},r[5.7][7.3,7.9]{},n[7.9]{}]' 28 | self.p1 = cast_graphpath(self.o1, None) 29 | 30 | def test_vertices(self): 31 | self.assertEqual(1, len(self.p0.vertices)) 32 | self.assertEqual('n[7.3]{}', str(self.p0.vertices[0])) 33 | self.assertEqual(2, len(self.p1.vertices)) 34 | self.assertEqual('n[7.3]{}', str(self.p1.vertices[0])) 35 | self.assertEqual('n[7.9]{}', str(self.p1.vertices[1])) 36 | 37 | def test_edges(self): 38 | self.assertEqual(0, len(self.p0.edges)) 39 | self.assertEqual(1, len(self.p1.edges)) 40 | self.assertEqual('r[5.7][7.3,7.9]{}', str(self.p1.edges[0])) 41 | 42 | def test_eq(self): 43 | self.assertEqual(self.p0, self.p0) 44 | self.assertEqual(self.p1, self.p1) 45 | 46 | def test_len(self): 47 | self.assertEqual(0, len(self.p0)) 48 | self.assertEqual(1, len(self.p1)) 49 | 50 | def test_str(self): 51 | self.assertEqual(self.o0, str(self.p0)) 52 | self.assertEqual(self.o1, str(self.p1)) 53 | 54 | def test_repr(self): 55 | self.assertEqual("%s(%s)" % (Path.__name__, self.p0), repr(self.p0)) 56 | self.assertEqual("%s(%s)" % (Path.__name__, self.p1), repr(self.p1)) 57 | -------------------------------------------------------------------------------- /tests/test_property.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Copyright (c) 2014-2018, Bitnine Inc. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | ''' 16 | 17 | import unittest 18 | 19 | from agensgraph._property import Property 20 | 21 | from psycopg2.extensions import QuotedString, adapt 22 | 23 | class TestProperty(unittest.TestCase): 24 | def test_string(self): 25 | self.assertEqual(r"'\"'", Property('"').getquoted()) 26 | self.assertEqual(r"''''", Property("'").getquoted()) 27 | 28 | def test_number(self): 29 | self.assertEqual('0', Property(0).getquoted()) 30 | self.assertEqual('-1', Property(-1).getquoted()) 31 | self.assertEqual('3.14159', Property(3.14159).getquoted()) 32 | 33 | def test_boolean(self): 34 | self.assertEqual('true', Property(True).getquoted()) 35 | self.assertEqual('false', Property(False).getquoted()) 36 | 37 | def test_null(self): 38 | self.assertEqual('null', Property(None).getquoted()) 39 | 40 | def test_array(self): 41 | a = ["'\\\"'", 3.14159, True, None, (), {}] 42 | e = "['''\\\\\\\"''',3.14159,true,null,[],{}]" 43 | self.assertEqual(e, Property(a).getquoted()) 44 | 45 | def test_object(self): 46 | self.assertEqual("{'\\\"':'\\\"'}", Property({'"': '"'}).getquoted()) 47 | self.assertEqual("{'3.14159':3.14159}", 48 | Property({3.14159: 3.14159}).getquoted()) 49 | self.assertEqual("{'true':false}", Property({True: False}).getquoted()) 50 | self.assertEqual("{'null':null}", Property({None: None}).getquoted()) 51 | self.assertEqual("{'a':[]}", Property({'a': []}).getquoted()) 52 | self.assertEqual("{'o':{}}", Property({'o': {}}).getquoted()) 53 | self.assertRaises(TypeError, Property({(): None}).getquoted) 54 | -------------------------------------------------------------------------------- /tests/test_vertex.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Copyright (c) 2014-2017, Bitnine Inc. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | ''' 16 | 17 | import unittest 18 | 19 | from psycopg2.extras import json 20 | 21 | from agensgraph._graphid import GraphId 22 | from agensgraph._vertex import Vertex, cast_vertex 23 | 24 | class TestVertex(unittest.TestCase): 25 | def setUp(self): 26 | out = 'v[7.9]{"s": "", "i": 0, "b": false, "a": [], "o": {}}' 27 | self.v = cast_vertex(out, None) 28 | 29 | def test_label(self): 30 | self.assertEqual('v', self.v.label) 31 | 32 | def test_vid(self): 33 | self.assertEqual(GraphId((7, 9)), self.v.vid) 34 | 35 | def test_props(self): 36 | self.assertEqual('', self.v.props['s']) 37 | self.assertEqual(0, self.v.props['i']) 38 | self.assertFalse(self.v.props['b']) 39 | self.assertEqual([], self.v.props['a']) 40 | self.assertEqual({}, self.v.props['o']) 41 | 42 | def test_eq(self): 43 | self.assertEqual(self.v, self.v) 44 | 45 | def test_str(self): 46 | props = '{"s": "", "i": 0, "b": false, "a": [], "o": {}}' 47 | out = "v[7.9]%s" % json.dumps(json.loads(props)) 48 | self.assertEqual(out, str(self.v)) 49 | 50 | def test_repr(self): 51 | self.assertEqual("%s(%s)" % (Vertex.__name__, self.v), repr(self.v)) 52 | --------------------------------------------------------------------------------