jsql-neo 6.5.13__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,128 @@
1
+ Metadata-Version: 2.4
2
+ Name: jsql-neo
3
+ Version: 6.5.13
4
+ Summary: Python client and CLI for JSQL-NEO (Node.js backend)
5
+ Author: vexify
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/vexify-org/jsql-python
8
+ Project-URL: Repository, https://github.com/vexify-org/jsql-python
9
+ Project-URL: Issues, https://github.com/vexify-org/jsql-python/issues
10
+ Keywords: jsql,json,database,sql,node,sqlite
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.8
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Database
22
+ Requires-Python: >=3.8
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Dynamic: license-file
26
+
27
+ # jsql-neo (Python)
28
+
29
+ Python client and CLI for [JSQL-NEO](https://github.com/vexify-org/JSQL-neo).
30
+ The engine stays in Node.js: this package ships a thin Python API over a
31
+ stdio JSON bridge and a `jsql` command that proxies to the Node CLI.
32
+
33
+ ## Install
34
+
35
+ Install Node.js and the `jsql-neo` npm package first:
36
+
37
+ ```bash
38
+ curl -fsSL https://jsql.vexify.top/setup | bash
39
+ ```
40
+
41
+ Then install the Python package:
42
+
43
+ ```bash
44
+ pip install jsql-neo
45
+ ```
46
+
47
+ Requires Node.js 18+ and `jsql-neo` >= 6.5.12.
48
+
49
+ ## CLI
50
+
51
+ The `jsql` command is the Node CLI, proxied:
52
+
53
+ ```bash
54
+ jsql serve --port 3306 --data-dir ./data
55
+ jsql plugin search xql
56
+ jsql plugin install xql
57
+ jsql version
58
+ ```
59
+
60
+ Exit codes, stdin/stdout and TTY behaviour are preserved (the process is
61
+ replaced with `node bin/jsql` on POSIX).
62
+
63
+ ## Python API
64
+
65
+ ```python
66
+ from jsql_neo import Database
67
+
68
+ db = Database(":memory:") # or Database("./data/app.json")
69
+
70
+ db.createTable("users", {
71
+ "id": {"type": "integer", "primaryKey": True, "autoIncrement": True},
72
+ "name": {"type": "string"},
73
+ "age": {"type": "integer"},
74
+ })
75
+
76
+ db.insert("users", {"name": "alice", "age": 30})
77
+ db.insertMany("users", [{"name": "bob", "age": 25}])
78
+
79
+ rows = db.find("users", {"age": {"$gt": 26}}, {"sort": {"age": 1}})
80
+ print(rows)
81
+
82
+ db.update("users", {"name": "bob"}, {"age": 26})
83
+ db.removeWhere("users", {"name": "bob"})
84
+
85
+ for row in db.query("SELECT name FROM users ORDER BY name"):
86
+ print(row)
87
+
88
+ db.close()
89
+ ```
90
+
91
+ Use it as a context manager:
92
+
93
+ ```python
94
+ with Database("./data/app.json") as db:
95
+ print(db.getTables())
96
+ ```
97
+
98
+ Any method on the Node `Database` object is reachable through the bridge:
99
+
100
+ ```python
101
+ db.save()
102
+ db.stats()
103
+ db.begin()
104
+ db.commit()
105
+ db.backup("./backup.json")
106
+ ```
107
+
108
+ Errors from the engine raise `jsql_neo.JSQLException`.
109
+
110
+ ## Configuration
111
+
112
+ | Variable | Purpose |
113
+ | --- | --- |
114
+ | `JSQL_NEO_JS` | Path to the `jsql-neo` npm package directory |
115
+ | `JSQL_NODE` | Path to the Node.js executable |
116
+
117
+ The package locates the npm package from the current directory
118
+ (`node_modules/jsql-neo`), the global npm root, or the `jsql` executable on
119
+ `PATH`. If nothing is found it raises `JSQLNotInstalled` with the setup command.
120
+
121
+ ## Versioning
122
+
123
+ The Python package version mirrors the npm package (`6.5.13`). The Python
124
+ wrapper only needs `jsql-neo >= 6.5.12`.
125
+
126
+ ## License
127
+
128
+ Apache-2.0
@@ -0,0 +1,102 @@
1
+ # jsql-neo (Python)
2
+
3
+ Python client and CLI for [JSQL-NEO](https://github.com/vexify-org/JSQL-neo).
4
+ The engine stays in Node.js: this package ships a thin Python API over a
5
+ stdio JSON bridge and a `jsql` command that proxies to the Node CLI.
6
+
7
+ ## Install
8
+
9
+ Install Node.js and the `jsql-neo` npm package first:
10
+
11
+ ```bash
12
+ curl -fsSL https://jsql.vexify.top/setup | bash
13
+ ```
14
+
15
+ Then install the Python package:
16
+
17
+ ```bash
18
+ pip install jsql-neo
19
+ ```
20
+
21
+ Requires Node.js 18+ and `jsql-neo` >= 6.5.12.
22
+
23
+ ## CLI
24
+
25
+ The `jsql` command is the Node CLI, proxied:
26
+
27
+ ```bash
28
+ jsql serve --port 3306 --data-dir ./data
29
+ jsql plugin search xql
30
+ jsql plugin install xql
31
+ jsql version
32
+ ```
33
+
34
+ Exit codes, stdin/stdout and TTY behaviour are preserved (the process is
35
+ replaced with `node bin/jsql` on POSIX).
36
+
37
+ ## Python API
38
+
39
+ ```python
40
+ from jsql_neo import Database
41
+
42
+ db = Database(":memory:") # or Database("./data/app.json")
43
+
44
+ db.createTable("users", {
45
+ "id": {"type": "integer", "primaryKey": True, "autoIncrement": True},
46
+ "name": {"type": "string"},
47
+ "age": {"type": "integer"},
48
+ })
49
+
50
+ db.insert("users", {"name": "alice", "age": 30})
51
+ db.insertMany("users", [{"name": "bob", "age": 25}])
52
+
53
+ rows = db.find("users", {"age": {"$gt": 26}}, {"sort": {"age": 1}})
54
+ print(rows)
55
+
56
+ db.update("users", {"name": "bob"}, {"age": 26})
57
+ db.removeWhere("users", {"name": "bob"})
58
+
59
+ for row in db.query("SELECT name FROM users ORDER BY name"):
60
+ print(row)
61
+
62
+ db.close()
63
+ ```
64
+
65
+ Use it as a context manager:
66
+
67
+ ```python
68
+ with Database("./data/app.json") as db:
69
+ print(db.getTables())
70
+ ```
71
+
72
+ Any method on the Node `Database` object is reachable through the bridge:
73
+
74
+ ```python
75
+ db.save()
76
+ db.stats()
77
+ db.begin()
78
+ db.commit()
79
+ db.backup("./backup.json")
80
+ ```
81
+
82
+ Errors from the engine raise `jsql_neo.JSQLException`.
83
+
84
+ ## Configuration
85
+
86
+ | Variable | Purpose |
87
+ | --- | --- |
88
+ | `JSQL_NEO_JS` | Path to the `jsql-neo` npm package directory |
89
+ | `JSQL_NODE` | Path to the Node.js executable |
90
+
91
+ The package locates the npm package from the current directory
92
+ (`node_modules/jsql-neo`), the global npm root, or the `jsql` executable on
93
+ `PATH`. If nothing is found it raises `JSQLNotInstalled` with the setup command.
94
+
95
+ ## Versioning
96
+
97
+ The Python package version mirrors the npm package (`6.5.13`). The Python
98
+ wrapper only needs `jsql-neo >= 6.5.12`.
99
+
100
+ ## License
101
+
102
+ Apache-2.0
@@ -0,0 +1,24 @@
1
+ """Python client for JSQL-NEO.
2
+
3
+ The database engine stays in Node.js; this package provides a Python API
4
+ (``jsql_neo.Database``) over a stdio JSON bridge and a ``jsql`` CLI that
5
+ proxies to the Node CLI.
6
+
7
+ Install the Node side once with::
8
+
9
+ curl -fsSL https://jsql.vexify.top/setup | bash
10
+ """
11
+
12
+ from ._node import JSQLNotInstalled, SETUP_HINT, find_package_root
13
+ from .database import Database, JSQLException
14
+
15
+ __version__ = "6.5.13"
16
+
17
+ __all__ = [
18
+ "Database",
19
+ "JSQLException",
20
+ "JSQLNotInstalled",
21
+ "SETUP_HINT",
22
+ "find_package_root",
23
+ "__version__",
24
+ ]
@@ -0,0 +1,6 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ if __name__ == "__main__":
6
+ sys.exit(main())
@@ -0,0 +1,125 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const path = require('path');
5
+ const readline = require('readline');
6
+
7
+ const root = process.env.JSQL_NEO_JS_ROOT;
8
+ const pkg = root ? require(path.join(root, 'index.js')) : require('jsql-neo');
9
+
10
+ let db = null;
11
+ let closed = false;
12
+
13
+ function replacer(key, value) {
14
+ if (typeof value === 'bigint') {
15
+ if (value <= Number.MAX_SAFE_INTEGER && value >= Number.MIN_SAFE_INTEGER) {
16
+ return Number(value);
17
+ }
18
+ return value.toString();
19
+ }
20
+ return value;
21
+ }
22
+
23
+ function send(payload) {
24
+ let line;
25
+ try {
26
+ line = JSON.stringify(payload, replacer);
27
+ } catch (e) {
28
+ line = JSON.stringify({
29
+ id: payload && payload.id,
30
+ ok: false,
31
+ error: { message: 'Result is not JSON-serializable: ' + e.message }
32
+ });
33
+ }
34
+ process.stdout.write(line + '\n');
35
+ }
36
+
37
+ async function init(args) {
38
+ const dbPath = args[0];
39
+ const options = args[1] || {};
40
+ db = new pkg.Database(dbPath, options);
41
+ if (typeof db.loadDatabase === 'function') {
42
+ await db.loadDatabase();
43
+ }
44
+ return { path: dbPath };
45
+ }
46
+
47
+ async function dispatch(method, args) {
48
+ if (!db) {
49
+ throw new Error('Database is not initialized');
50
+ }
51
+ if (typeof method !== 'string' || method.startsWith('_') || method === 'constructor') {
52
+ throw new Error('Invalid method: ' + String(method));
53
+ }
54
+ const fn = db[method];
55
+ if (typeof fn !== 'function') {
56
+ throw new Error('Unknown method: ' + method);
57
+ }
58
+ for (const arg of args) {
59
+ if (typeof arg === 'function') {
60
+ throw new Error('Function arguments are not supported over the bridge');
61
+ }
62
+ }
63
+ return await fn.apply(db, args);
64
+ }
65
+
66
+ async function handle(msg) {
67
+ const id = msg.id;
68
+ const method = msg.method;
69
+ const args = Array.isArray(msg.args) ? msg.args : [];
70
+
71
+ if (method === 'close') {
72
+ try {
73
+ if (db && !closed) {
74
+ closed = true;
75
+ await db.close();
76
+ }
77
+ } catch (e) {
78
+ // closing is best-effort; the process exits either way
79
+ }
80
+ send({ id: id, ok: true, result: null });
81
+ setTimeout(() => process.exit(0), 0);
82
+ return;
83
+ }
84
+
85
+ if (method === 'ping') {
86
+ send({ id: id, ok: true, result: 'pong' });
87
+ return;
88
+ }
89
+
90
+ try {
91
+ const result = method === '__init' ? await init(args) : await dispatch(method, args);
92
+ send({ id: id, ok: true, result: result === undefined ? null : result });
93
+ } catch (e) {
94
+ send({
95
+ id: id,
96
+ ok: false,
97
+ error: {
98
+ name: e && e.name ? e.name : 'Error',
99
+ message: e && e.message ? e.message : String(e),
100
+ code: e && e.code != null ? e.code : null
101
+ }
102
+ });
103
+ }
104
+ }
105
+
106
+ const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity });
107
+ let chain = Promise.resolve();
108
+
109
+ rl.on('line', line => {
110
+ if (!line.trim()) return;
111
+ chain = chain.then(() => {
112
+ let msg;
113
+ try {
114
+ msg = JSON.parse(line);
115
+ } catch (e) {
116
+ send({ id: null, ok: false, error: { message: 'Invalid JSON request' } });
117
+ return;
118
+ }
119
+ return handle(msg);
120
+ });
121
+ });
122
+
123
+ rl.on('close', () => {
124
+ process.exit(0);
125
+ });
@@ -0,0 +1,109 @@
1
+ """Locate the Node.js runtime and the jsql-neo npm package."""
2
+
3
+ import os
4
+ import shutil
5
+ import subprocess
6
+ from pathlib import Path
7
+
8
+ SETUP_HINT = "curl -fsSL https://jsql.vexify.top/setup | bash"
9
+
10
+ _PACKAGE_ENTRY = ("package.json", "bin", "jsql")
11
+
12
+
13
+ class JSQLNotInstalled(RuntimeError):
14
+ """Raised when Node.js or the jsql-neo npm package cannot be found."""
15
+
16
+
17
+ def node_executable():
18
+ """Return the Node.js executable path."""
19
+ exe = os.environ.get("JSQL_NODE") or shutil.which("node")
20
+ if not exe:
21
+ raise JSQLNotInstalled(
22
+ "Node.js was not found on PATH.\n"
23
+ "Install Node.js and jsql-neo with:\n"
24
+ " " + SETUP_HINT
25
+ )
26
+ return exe
27
+
28
+
29
+ def _looks_like_package(path):
30
+ p = Path(path)
31
+ return (p / _PACKAGE_ENTRY[0]).is_file() and (p / _PACKAGE_ENTRY[1] / _PACKAGE_ENTRY[2]).is_file()
32
+
33
+
34
+ def _resolve_from_cwd(node, cwd):
35
+ script = "process.stdout.write(require.resolve('jsql-neo/package.json'))"
36
+ try:
37
+ out = subprocess.run(
38
+ [node, "-e", script],
39
+ cwd=cwd,
40
+ capture_output=True,
41
+ text=True,
42
+ timeout=20,
43
+ )
44
+ except (OSError, subprocess.SubprocessError):
45
+ return None
46
+ if out.returncode != 0:
47
+ return None
48
+ resolved = out.stdout.strip()
49
+ if not resolved:
50
+ return None
51
+ return Path(resolved).parent
52
+
53
+
54
+ def _global_root():
55
+ npm = shutil.which("npm")
56
+ if not npm:
57
+ return None
58
+ try:
59
+ out = subprocess.run([npm, "root", "-g"], capture_output=True, text=True, timeout=30)
60
+ except (OSError, subprocess.SubprocessError):
61
+ return None
62
+ if out.returncode != 0:
63
+ return None
64
+ root = out.stdout.strip()
65
+ return Path(root) / "jsql-neo" if root else None
66
+
67
+
68
+ def find_package_root():
69
+ """Return the jsql-neo npm package directory.
70
+
71
+ Resolution order:
72
+ 1. ``JSQL_NEO_JS`` environment variable (package directory)
73
+ 2. ``require.resolve`` from the current working directory (local install)
74
+ 3. ``npm root -g`` (global install)
75
+ 4. the ``jsql`` executable on PATH (symlink to the package bin)
76
+ """
77
+ env = os.environ.get("JSQL_NEO_JS")
78
+ if env:
79
+ path = Path(env).expanduser()
80
+ if path.name == "package.json":
81
+ path = path.parent
82
+ if _looks_like_package(path):
83
+ return path.resolve()
84
+ raise JSQLNotInstalled(
85
+ "JSQL_NEO_JS does not point to a jsql-neo package: %s\n"
86
+ "Install it with:\n %s" % (path, SETUP_HINT)
87
+ )
88
+
89
+ node = node_executable()
90
+
91
+ local = _resolve_from_cwd(node, os.getcwd())
92
+ if local and _looks_like_package(local):
93
+ return local.resolve()
94
+
95
+ root = _global_root()
96
+ if root and _looks_like_package(root):
97
+ return root.resolve()
98
+
99
+ jsql = shutil.which("jsql")
100
+ if jsql:
101
+ candidate = Path(jsql).resolve().parent.parent
102
+ if _looks_like_package(candidate):
103
+ return candidate
104
+
105
+ raise JSQLNotInstalled(
106
+ "The jsql-neo npm package was not found.\n"
107
+ "Install Node.js and jsql-neo with:\n"
108
+ " " + SETUP_HINT
109
+ )
@@ -0,0 +1,32 @@
1
+ """``jsql`` command line proxy to the Node.js CLI."""
2
+
3
+ import os
4
+ import subprocess
5
+ import sys
6
+
7
+ from ._node import JSQLNotInstalled, find_package_root, node_executable
8
+
9
+
10
+ def main(argv=None):
11
+ args = list(sys.argv[1:] if argv is None else argv)
12
+ try:
13
+ node = node_executable()
14
+ root = find_package_root()
15
+ except JSQLNotInstalled as exc:
16
+ sys.stderr.write("jsql: %s\n" % exc)
17
+ return 1
18
+
19
+ script = os.path.join(str(root), "bin", "jsql")
20
+ if not os.path.isfile(script):
21
+ sys.stderr.write("jsql: missing CLI entry point: %s\n" % script)
22
+ return 1
23
+
24
+ if os.name == "posix":
25
+ os.execv(node, [node, script] + args)
26
+ return 1
27
+
28
+ return subprocess.call([node, script] + args)
29
+
30
+
31
+ if __name__ == "__main__":
32
+ sys.exit(main())
@@ -0,0 +1,272 @@
1
+ """Python Database wrapper around the JSQL-NEO Node.js engine."""
2
+
3
+ import base64
4
+ import datetime
5
+ import decimal
6
+ import json
7
+ import os
8
+ import queue
9
+ import subprocess
10
+ import threading
11
+
12
+ from ._node import find_package_root, node_executable
13
+
14
+ _BRIDGE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "_bridge.js")
15
+
16
+
17
+ class JSQLException(RuntimeError):
18
+ """Error raised by the JSQL engine."""
19
+
20
+ def __init__(self, message, code=None, name="Error"):
21
+ super().__init__(message)
22
+ self.code = code
23
+ self.name = name
24
+
25
+
26
+ def _json_default(value):
27
+ if isinstance(value, (datetime.datetime, datetime.date, datetime.time)):
28
+ return value.isoformat()
29
+ if isinstance(value, decimal.Decimal):
30
+ return float(value)
31
+ if isinstance(value, (set, frozenset)):
32
+ return list(value)
33
+ if isinstance(value, bytes):
34
+ return base64.b64encode(value).decode("ascii")
35
+ raise TypeError("Object of type %s is not JSON serializable" % type(value).__name__)
36
+
37
+
38
+ class Database:
39
+ """A JSQL-NEO database backed by a Node.js child process.
40
+
41
+ Parameters
42
+ ----------
43
+ path:
44
+ Database file path, a data directory, or ``":memory:"``.
45
+ options:
46
+ Options forwarded to the JSQL ``Database`` constructor.
47
+ """
48
+
49
+ def __init__(self, path=":memory:", options=None, **kwargs):
50
+ opts = dict(options or {})
51
+ opts.update(kwargs)
52
+ self.path = path
53
+ self.options = opts
54
+ self._proc = None
55
+ self._lock = threading.Lock()
56
+ self._next_id = 0
57
+ self._closed = False
58
+ self._stderr = []
59
+ self._stderr_lock = threading.Lock()
60
+ self._lines = queue.Queue()
61
+ self._start()
62
+
63
+ # -- process lifecycle -------------------------------------------------
64
+
65
+ def _start(self):
66
+ node = node_executable()
67
+ root = find_package_root()
68
+ env = os.environ.copy()
69
+ env["JSQL_NEO_JS_ROOT"] = str(root)
70
+ self._proc = subprocess.Popen(
71
+ [node, _BRIDGE],
72
+ stdin=subprocess.PIPE,
73
+ stdout=subprocess.PIPE,
74
+ stderr=subprocess.PIPE,
75
+ text=True,
76
+ bufsize=1,
77
+ env=env,
78
+ )
79
+ threading.Thread(target=self._read_stdout, daemon=True).start()
80
+ threading.Thread(target=self._read_stderr, daemon=True).start()
81
+ self._call("__init", self.path, self.options, timeout=60)
82
+
83
+ def _read_stdout(self):
84
+ proc = self._proc
85
+ if proc is None or proc.stdout is None:
86
+ return
87
+ for line in proc.stdout:
88
+ self._lines.put(line)
89
+ self._lines.put(None)
90
+
91
+ def _read_stderr(self):
92
+ proc = self._proc
93
+ if proc is None or proc.stderr is None:
94
+ return
95
+ for line in proc.stderr:
96
+ with self._stderr_lock:
97
+ self._stderr.append(line.rstrip())
98
+ if len(self._stderr) > 50:
99
+ del self._stderr[0]
100
+
101
+ def _stderr_tail(self):
102
+ with self._stderr_lock:
103
+ return "\n".join(self._stderr[-10:])
104
+
105
+ # -- RPC ---------------------------------------------------------------
106
+
107
+ def _call(self, method, *args, **kwargs):
108
+ timeout = kwargs.pop("timeout", None)
109
+ if kwargs:
110
+ raise TypeError("Unexpected keyword arguments: %s" % ", ".join(kwargs))
111
+ with self._lock:
112
+ if self._closed:
113
+ raise JSQLException("Database is closed")
114
+ if self._proc is None or self._proc.poll() is not None:
115
+ raise JSQLException(
116
+ "JSQL bridge is not running" + self._suffix()
117
+ )
118
+ self._next_id += 1
119
+ request = json.dumps(
120
+ {"id": self._next_id, "method": method, "args": list(args)},
121
+ default=_json_default,
122
+ )
123
+ try:
124
+ self._proc.stdin.write(request + "\n")
125
+ self._proc.stdin.flush()
126
+ except (BrokenPipeError, OSError) as exc:
127
+ raise JSQLException("Failed to write to JSQL bridge: %s%s" % (exc, self._suffix()))
128
+ try:
129
+ line = self._lines.get(timeout=timeout) if timeout else self._lines.get()
130
+ except queue.Empty:
131
+ raise JSQLException("JSQL call timed out: %s" % method)
132
+ if line is None:
133
+ raise JSQLException("JSQL bridge exited unexpectedly" + self._suffix())
134
+ response = json.loads(line)
135
+ if response.get("ok"):
136
+ return response.get("result")
137
+ error = response.get("error") or {}
138
+ raise JSQLException(
139
+ error.get("message", "Unknown JSQL error"),
140
+ code=error.get("code"),
141
+ name=error.get("name", "Error"),
142
+ )
143
+
144
+ def _suffix(self):
145
+ tail = self._stderr_tail()
146
+ return (":\n" + tail) if tail else ""
147
+
148
+ def _call_opt(self, method, *args):
149
+ values = list(args)
150
+ while values and values[-1] is None:
151
+ values.pop()
152
+ return self._call(method, *values)
153
+
154
+ # -- convenience API ---------------------------------------------------
155
+
156
+ def createTable(self, name, schema=None):
157
+ return self._call_opt("createTable", name, schema)
158
+
159
+ def dropTable(self, name):
160
+ return self._call("dropTable", name)
161
+
162
+ def hasTable(self, name):
163
+ return self._call("hasTable", name)
164
+
165
+ def getTables(self):
166
+ return self._call("getTables")
167
+
168
+ def getTableSchema(self, name):
169
+ return self._call("getTableSchema", name)
170
+
171
+ def insert(self, table, data):
172
+ return self._call("insert", table, data)
173
+
174
+ def insertMany(self, table, items):
175
+ return self._call("insertMany", table, items)
176
+
177
+ def find(self, table, filter=None, opts=None):
178
+ return self._call("find", table, filter if filter is not None else {}, opts or {})
179
+
180
+ def findById(self, table, id):
181
+ return self._call("findById", table, id)
182
+
183
+ def count(self, table):
184
+ return self._call("count", table)
185
+
186
+ def update(self, table, query, updates):
187
+ return self._call("update", table, query, updates)
188
+
189
+ def delete(self, table, query=None):
190
+ return self._call("delete", table, query if query is not None else {})
191
+
192
+ def removeWhere(self, table, filter):
193
+ return self._call("removeWhere", table, filter)
194
+
195
+ def truncate(self, table):
196
+ return self._call("truncate", table)
197
+
198
+ def query(self, sql, params=None, opts=None):
199
+ return self._call_opt("query", sql, params, opts)
200
+
201
+ def begin(self):
202
+ return self._call("begin")
203
+
204
+ def commit(self):
205
+ return self._call("commit")
206
+
207
+ def rollback(self):
208
+ return self._call("rollback")
209
+
210
+ def save(self):
211
+ return self._call("save")
212
+
213
+ def stats(self):
214
+ return self._call("stats")
215
+
216
+ def close(self):
217
+ if self._closed:
218
+ return
219
+ try:
220
+ self._call("close", timeout=10)
221
+ except JSQLException:
222
+ pass
223
+ finally:
224
+ self._closed = True
225
+ proc = self._proc
226
+ if proc is not None:
227
+ try:
228
+ proc.wait(timeout=5)
229
+ except subprocess.TimeoutExpired:
230
+ proc.kill()
231
+ proc.wait()
232
+ for stream in (proc.stdin, proc.stdout, proc.stderr):
233
+ try:
234
+ stream.close()
235
+ except Exception:
236
+ pass
237
+
238
+ # -- dynamic proxy -----------------------------------------------------
239
+
240
+ def __getattr__(self, name):
241
+ if name.startswith("_") or name in ("path", "options"):
242
+ raise AttributeError(name)
243
+
244
+ def call(*args, **kwargs):
245
+ if kwargs:
246
+ raise TypeError(
247
+ "%s() does not accept keyword arguments; pass an options "
248
+ "object as the last positional argument" % name
249
+ )
250
+ return self._call(name, *args)
251
+
252
+ call.__name__ = name
253
+ return call
254
+
255
+ def __enter__(self):
256
+ return self
257
+
258
+ def __exit__(self, exc_type, exc, tb):
259
+ self.close()
260
+ return False
261
+
262
+ def __del__(self):
263
+ try:
264
+ self.close()
265
+ except Exception:
266
+ pass
267
+
268
+ def __repr__(self):
269
+ return "<jsql_neo.Database path=%r%s>" % (
270
+ self.path,
271
+ " closed" if self._closed else "",
272
+ )
File without changes
@@ -0,0 +1,128 @@
1
+ Metadata-Version: 2.4
2
+ Name: jsql-neo
3
+ Version: 6.5.13
4
+ Summary: Python client and CLI for JSQL-NEO (Node.js backend)
5
+ Author: vexify
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/vexify-org/jsql-python
8
+ Project-URL: Repository, https://github.com/vexify-org/jsql-python
9
+ Project-URL: Issues, https://github.com/vexify-org/jsql-python/issues
10
+ Keywords: jsql,json,database,sql,node,sqlite
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.8
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Database
22
+ Requires-Python: >=3.8
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Dynamic: license-file
26
+
27
+ # jsql-neo (Python)
28
+
29
+ Python client and CLI for [JSQL-NEO](https://github.com/vexify-org/JSQL-neo).
30
+ The engine stays in Node.js: this package ships a thin Python API over a
31
+ stdio JSON bridge and a `jsql` command that proxies to the Node CLI.
32
+
33
+ ## Install
34
+
35
+ Install Node.js and the `jsql-neo` npm package first:
36
+
37
+ ```bash
38
+ curl -fsSL https://jsql.vexify.top/setup | bash
39
+ ```
40
+
41
+ Then install the Python package:
42
+
43
+ ```bash
44
+ pip install jsql-neo
45
+ ```
46
+
47
+ Requires Node.js 18+ and `jsql-neo` >= 6.5.12.
48
+
49
+ ## CLI
50
+
51
+ The `jsql` command is the Node CLI, proxied:
52
+
53
+ ```bash
54
+ jsql serve --port 3306 --data-dir ./data
55
+ jsql plugin search xql
56
+ jsql plugin install xql
57
+ jsql version
58
+ ```
59
+
60
+ Exit codes, stdin/stdout and TTY behaviour are preserved (the process is
61
+ replaced with `node bin/jsql` on POSIX).
62
+
63
+ ## Python API
64
+
65
+ ```python
66
+ from jsql_neo import Database
67
+
68
+ db = Database(":memory:") # or Database("./data/app.json")
69
+
70
+ db.createTable("users", {
71
+ "id": {"type": "integer", "primaryKey": True, "autoIncrement": True},
72
+ "name": {"type": "string"},
73
+ "age": {"type": "integer"},
74
+ })
75
+
76
+ db.insert("users", {"name": "alice", "age": 30})
77
+ db.insertMany("users", [{"name": "bob", "age": 25}])
78
+
79
+ rows = db.find("users", {"age": {"$gt": 26}}, {"sort": {"age": 1}})
80
+ print(rows)
81
+
82
+ db.update("users", {"name": "bob"}, {"age": 26})
83
+ db.removeWhere("users", {"name": "bob"})
84
+
85
+ for row in db.query("SELECT name FROM users ORDER BY name"):
86
+ print(row)
87
+
88
+ db.close()
89
+ ```
90
+
91
+ Use it as a context manager:
92
+
93
+ ```python
94
+ with Database("./data/app.json") as db:
95
+ print(db.getTables())
96
+ ```
97
+
98
+ Any method on the Node `Database` object is reachable through the bridge:
99
+
100
+ ```python
101
+ db.save()
102
+ db.stats()
103
+ db.begin()
104
+ db.commit()
105
+ db.backup("./backup.json")
106
+ ```
107
+
108
+ Errors from the engine raise `jsql_neo.JSQLException`.
109
+
110
+ ## Configuration
111
+
112
+ | Variable | Purpose |
113
+ | --- | --- |
114
+ | `JSQL_NEO_JS` | Path to the `jsql-neo` npm package directory |
115
+ | `JSQL_NODE` | Path to the Node.js executable |
116
+
117
+ The package locates the npm package from the current directory
118
+ (`node_modules/jsql-neo`), the global npm root, or the `jsql` executable on
119
+ `PATH`. If nothing is found it raises `JSQLNotInstalled` with the setup command.
120
+
121
+ ## Versioning
122
+
123
+ The Python package version mirrors the npm package (`6.5.13`). The Python
124
+ wrapper only needs `jsql-neo >= 6.5.12`.
125
+
126
+ ## License
127
+
128
+ Apache-2.0
@@ -0,0 +1,16 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ jsql_neo/__init__.py
5
+ jsql_neo/__main__.py
6
+ jsql_neo/_bridge.js
7
+ jsql_neo/_node.py
8
+ jsql_neo/cli.py
9
+ jsql_neo/database.py
10
+ jsql_neo/py.typed
11
+ jsql_neo.egg-info/PKG-INFO
12
+ jsql_neo.egg-info/SOURCES.txt
13
+ jsql_neo.egg-info/dependency_links.txt
14
+ jsql_neo.egg-info/entry_points.txt
15
+ jsql_neo.egg-info/top_level.txt
16
+ tests/test_jsql_neo.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ jsql = jsql_neo.cli:main
@@ -0,0 +1 @@
1
+ jsql_neo
@@ -0,0 +1,41 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "jsql-neo"
7
+ version = "6.5.13"
8
+ description = "Python client and CLI for JSQL-NEO (Node.js backend)"
9
+ readme = "README.md"
10
+ requires-python = ">=3.8"
11
+ license = { text = "Apache-2.0" }
12
+ authors = [{ name = "vexify" }]
13
+ keywords = ["jsql", "json", "database", "sql", "node", "sqlite"]
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Intended Audience :: Developers",
17
+ "License :: OSI Approved :: Apache Software License",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3.8",
20
+ "Programming Language :: Python :: 3.9",
21
+ "Programming Language :: Python :: 3.10",
22
+ "Programming Language :: Python :: 3.11",
23
+ "Programming Language :: Python :: 3.12",
24
+ "Programming Language :: Python :: 3.13",
25
+ "Topic :: Database",
26
+ ]
27
+
28
+ [project.scripts]
29
+ jsql = "jsql_neo.cli:main"
30
+
31
+ [project.urls]
32
+ Homepage = "https://github.com/vexify-org/jsql-python"
33
+ Repository = "https://github.com/vexify-org/jsql-python"
34
+ Issues = "https://github.com/vexify-org/jsql-python/issues"
35
+
36
+ [tool.setuptools]
37
+ packages = ["jsql_neo"]
38
+ include-package-data = true
39
+
40
+ [tool.setuptools.package-data]
41
+ jsql_neo = ["_bridge.js", "py.typed"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,97 @@
1
+ import subprocess
2
+ import sys
3
+ import unittest
4
+
5
+ from jsql_neo import Database, JSQLException
6
+ from jsql_neo._node import JSQLNotInstalled, find_package_root
7
+
8
+
9
+ def available():
10
+ try:
11
+ find_package_root()
12
+ return True
13
+ except JSQLNotInstalled:
14
+ return False
15
+
16
+
17
+ SCHEMA = {
18
+ "id": {"type": "integer", "primaryKey": True, "autoIncrement": True},
19
+ "name": {"type": "string"},
20
+ "age": {"type": "integer"},
21
+ }
22
+
23
+
24
+ @unittest.skipUnless(available(), "jsql-neo npm package is not installed")
25
+ class DatabaseTests(unittest.TestCase):
26
+ def setUp(self):
27
+ self.db = Database(":memory:")
28
+
29
+ def tearDown(self):
30
+ self.db.close()
31
+
32
+ def test_crud(self):
33
+ self.db.createTable("users", SCHEMA)
34
+ self.assertTrue(self.db.hasTable("users"))
35
+
36
+ self.db.insert("users", {"name": "alice", "age": 30})
37
+ self.db.insertMany(
38
+ "users",
39
+ [{"name": "bob", "age": 25}, {"name": "carol", "age": 35}],
40
+ )
41
+
42
+ rows = self.db.find("users", {"age": {"$gt": 26}}, {"sort": {"age": 1}})
43
+ self.assertEqual([row["name"] for row in rows], ["alice", "carol"])
44
+ self.assertEqual(self.db.count("users"), 3)
45
+
46
+ self.db.update("users", {"name": "bob"}, {"age": 26})
47
+ bob = self.db.find("users", {"name": "bob"})[0]
48
+ self.assertEqual(bob["age"], 26)
49
+
50
+ self.db.removeWhere("users", {"name": "carol"})
51
+ self.assertEqual(self.db.count("users"), 2)
52
+
53
+ self.db.delete("users", {"name": "alice"})
54
+ self.assertEqual(self.db.count("users"), 1)
55
+
56
+ def test_query(self):
57
+ self.db.createTable("users", SCHEMA)
58
+ self.db.insertMany(
59
+ "users",
60
+ [{"name": "alice", "age": 30}, {"name": "bob", "age": 25}],
61
+ )
62
+ result = self.db.query("SELECT name FROM users ORDER BY name")
63
+ self.assertEqual(result["columns"], ["name"])
64
+ self.assertEqual([row["name"] for row in result["raw"]], ["alice", "bob"])
65
+ self.assertEqual(result["rows"], [["alice"], ["bob"]])
66
+
67
+ def test_generic_proxy(self):
68
+ self.db.createTable("notes", {"id": {"type": "integer", "primaryKey": True}, "body": {"type": "string"}})
69
+ self.db.insert("notes", {"id": 1, "body": "hello"})
70
+ self.assertIn("notes", self.db.getTables())
71
+ self.assertIsInstance(self.db.stats(), dict)
72
+
73
+ def test_error(self):
74
+ with self.assertRaises(JSQLException):
75
+ self.db._call("definitelyNotAMethod")
76
+
77
+ def test_closed(self):
78
+ self.db.close()
79
+ with self.assertRaises(JSQLException):
80
+ self.db.getTables()
81
+
82
+
83
+ @unittest.skipUnless(available(), "jsql-neo npm package is not installed")
84
+ class CliTests(unittest.TestCase):
85
+ def test_version(self):
86
+ out = subprocess.run(
87
+ [sys.executable, "-m", "jsql_neo", "version"],
88
+ capture_output=True,
89
+ text=True,
90
+ timeout=60,
91
+ )
92
+ self.assertEqual(out.returncode, 0, out.stderr)
93
+ self.assertRegex(out.stdout.strip(), r"^\d+\.\d+\.\d+$")
94
+
95
+
96
+ if __name__ == "__main__":
97
+ unittest.main()