velocity-python 0.0.89__py3-none-any.whl → 0.0.92__py3-none-any.whl

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.

Potentially problematic release.


This version of velocity-python might be problematic. Click here for more details.

@@ -0,0 +1,409 @@
1
+ Metadata-Version: 2.4
2
+ Name: velocity-python
3
+ Version: 0.0.92
4
+ Summary: A rapid application development library for interfacing with data storage
5
+ Author-email: Velocity Team <contact@example.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://codeclubs.org/projects/velocity
8
+ Keywords: database,orm,sql,rapid-development,data-storage
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Topic :: Database
12
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.7
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: License :: OSI Approved :: MIT License
20
+ Classifier: Operating System :: OS Independent
21
+ Requires-Python: >=3.7
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: boto3>=1.26.0
25
+ Requires-Dist: requests>=2.25.0
26
+ Requires-Dist: jinja2>=3.0.0
27
+ Requires-Dist: xlrd>=2.0.0
28
+ Requires-Dist: openpyxl>=3.0.0
29
+ Requires-Dist: sqlparse>=0.4.0
30
+ Provides-Extra: mysql
31
+ Requires-Dist: mysql-connector-python>=8.0.0; extra == "mysql"
32
+ Provides-Extra: sqlserver
33
+ Requires-Dist: python-tds>=1.10.0; extra == "sqlserver"
34
+ Provides-Extra: postgres
35
+ Requires-Dist: psycopg2-binary>=2.9.0; extra == "postgres"
36
+ Provides-Extra: dev
37
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
38
+ Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
39
+ Requires-Dist: black>=23.0.0; extra == "dev"
40
+ Requires-Dist: flake8>=6.0.0; extra == "dev"
41
+ Requires-Dist: mypy>=1.0.0; extra == "dev"
42
+ Requires-Dist: pre-commit>=3.0.0; extra == "dev"
43
+ Provides-Extra: test
44
+ Requires-Dist: pytest>=7.0.0; extra == "test"
45
+ Requires-Dist: pytest-cov>=4.0.0; extra == "test"
46
+ Requires-Dist: pytest-mock>=3.10.0; extra == "test"
47
+ Provides-Extra: docs
48
+ Requires-Dist: sphinx>=5.0.0; extra == "docs"
49
+ Requires-Dist: sphinx-rtd-theme>=1.2.0; extra == "docs"
50
+ Dynamic: license-file
51
+
52
+ # Velocity.DB
53
+
54
+ A modern Python database abstraction library that simplifies database operations across multiple database engines. Velocity.DB provides a unified interface for PostgreSQL, MySQL, SQLite, and SQL Server, with features like transaction management, automatic connection pooling, and database-agnostic query building.
55
+
56
+ ## Features
57
+
58
+ - **Multi-database support**: PostgreSQL, MySQL, SQLite, SQL Server
59
+ - **Transaction management**: Decorator-based transaction handling with automatic rollback
60
+ - **Query builder**: Database-agnostic SQL generation with foreign key expansion
61
+ - **Connection pooling**: Automatic connection management and pooling
62
+ - **Type safety**: Comprehensive type hints and validation
63
+ - **Modern Python**: Built for Python 3.8+ with modern packaging
64
+
65
+ ## Supported Databases
66
+
67
+ - **PostgreSQL** (via psycopg2)
68
+ - **MySQL** (via mysqlclient)
69
+ - **SQLite** (built-in sqlite3)
70
+ - **SQL Server** (via pytds)
71
+
72
+ ## Installation
73
+
74
+ Install the base package:
75
+
76
+ ```bash
77
+ pip install velocity-python
78
+ ```
79
+
80
+ Install with database-specific dependencies:
81
+
82
+ ```bash
83
+ # For PostgreSQL
84
+ pip install velocity-python[postgres]
85
+
86
+ # For MySQL
87
+ pip install velocity-python[mysql]
88
+
89
+ # For SQL Server
90
+ pip install velocity-python[sqlserver]
91
+
92
+ # For all databases
93
+ pip install velocity-python[all]
94
+ ```
95
+
96
+ ## Quick Start
97
+
98
+ ### Database Connection
99
+
100
+ ```python
101
+ import velocity.db
102
+
103
+ # PostgreSQL
104
+ engine = velocity.db.postgres(
105
+ host="localhost",
106
+ port=5432,
107
+ database="mydb",
108
+ user="username",
109
+ password="password"
110
+ )
111
+
112
+ # MySQL
113
+ engine = velocity.db.mysql(
114
+ host="localhost",
115
+ port=3306,
116
+ database="mydb",
117
+ user="username",
118
+ password="password"
119
+ )
120
+
121
+ # SQLite
122
+ engine = velocity.db.sqlite("path/to/database.db")
123
+
124
+ # SQL Server
125
+ engine = velocity.db.sqlserver(
126
+ host="localhost",
127
+ port=1433,
128
+ database="mydb",
129
+ user="username",
130
+ password="password"
131
+ ### Transaction Management
132
+
133
+ Use the `@engine.transaction` decorator for automatic transaction handling:
134
+
135
+ ```python
136
+ @engine.transaction
137
+ def create_user(tx):
138
+ # All operations within this function are wrapped in a transaction
139
+ user = tx.table('users').new()
140
+ user['name'] = 'John Doe'
141
+ user['email'] = 'john@example.com'
142
+ # Transaction commits automatically on success or rolls back on error
143
+ return user['sys_id']
144
+ ```
145
+
146
+ ### Table Operations
147
+
148
+ #### Creating Tables
149
+
150
+ ```python
151
+ @engine.transaction
152
+ def create_tables(tx):
153
+ # Create a users table
154
+ users = tx.table('users')
155
+ users.create()
156
+
157
+ # Add columns by setting data
158
+ user = users.new()
159
+ user['name'] = 'Sample User'
160
+ user['email'] = 'user@example.com'
161
+ user['created_at'] = datetime.now()
162
+ ```
163
+
164
+ #### Selecting Data
165
+
166
+ ```python
167
+ @engine.transaction
168
+ def query_users(tx):
169
+ users = tx.table('users')
170
+
171
+ # Select all users
172
+ all_users = users.select().all()
173
+
174
+ # Select with conditions
175
+ active_users = users.select(where={'status': 'active'}).all()
176
+
177
+ # Select specific columns
178
+ names = users.select(columns=['name', 'email']).all()
179
+
180
+ # Select with ordering and limits
181
+ recent = users.select(
182
+ orderby='created_at DESC',
183
+ qty=10
184
+ ).all()
185
+
186
+ # Find single record
187
+ user = users.find({'email': 'john@example.com'})
188
+
189
+ # Get by primary key
190
+ user = users.find(123)
191
+ ```
192
+
193
+ #### Updating Data
194
+
195
+ ```python
196
+ @engine.transaction
197
+ def update_user(tx):
198
+ users = tx.table('users')
199
+
200
+ # Update single record
201
+ user = users.find(123)
202
+ user['name'] = 'Updated Name'
203
+ user['updated_at'] = datetime.now()
204
+
205
+ # Bulk update
206
+ users.update(
207
+ {'status': 'inactive'},
208
+ where={'last_login': {'<': '2023-01-01'}}
209
+ )
210
+ ```
211
+
212
+ #### Inserting Data
213
+
214
+ ```python
215
+ @engine.transaction
216
+ def create_users(tx):
217
+ users = tx.table('users')
218
+
219
+ # Create new record
220
+ user = users.new()
221
+ user['name'] = 'New User'
222
+ user['email'] = 'new@example.com'
223
+
224
+ # Insert with data
225
+ user_id = users.insert({
226
+ 'name': 'Another User',
227
+ 'email': 'another@example.com'
228
+ })
229
+
230
+ # Upsert (insert or update)
231
+ users.upsert(
232
+ {'name': 'John Doe', 'status': 'active'},
233
+ {'email': 'john@example.com'} # matching condition
234
+ )
235
+ ```
236
+
237
+ #### Deleting Data
238
+
239
+ ```python
240
+ @engine.transaction
241
+ def delete_users(tx):
242
+ users = tx.table('users')
243
+
244
+ # Delete single record
245
+ user = users.find(123)
246
+ user.delete()
247
+
248
+ # Delete with conditions
249
+ users.delete(where={'status': 'inactive'})
250
+
251
+ # Truncate table
252
+ users.truncate()
253
+
254
+ # Drop table
255
+ users.drop()
256
+ ```
257
+
258
+ ### Advanced Queries
259
+
260
+ #### Foreign Key Navigation
261
+
262
+ Velocity.DB supports automatic foreign key expansion using pointer syntax:
263
+
264
+ ```python
265
+ @engine.transaction
266
+ def get_user_with_profile(tx):
267
+ users = tx.table('users')
268
+
269
+ # Automatic join via foreign key
270
+ users_with_profiles = users.select(
271
+ columns=['name', 'email', 'profile.bio', 'profile.avatar_url'],
272
+ where={'status': 'active'}
273
+ ).all()
274
+ ```
275
+
276
+ #### Complex Conditions
277
+
278
+ ```python
279
+ @engine.transaction
280
+ def complex_queries(tx):
281
+ users = tx.table('users')
282
+
283
+ # Multiple conditions
284
+ results = users.select(where={
285
+ 'status': 'active',
286
+ 'created_at': {'>=': '2023-01-01'},
287
+ 'age': {'BETWEEN': [18, 65]},
288
+ 'email': {'LIKE': '%@company.com'}
289
+ }).all()
290
+
291
+ # OR conditions
292
+ results = users.select(where={
293
+ 'OR': [
294
+ {'status': 'active'},
295
+ {'priority': 'high'}
296
+ ]
297
+ }).all()
298
+ ```
299
+
300
+ #### Aggregations and Grouping
301
+
302
+ ```python
303
+ @engine.transaction
304
+ def analytics(tx):
305
+ orders = tx.table('orders')
306
+
307
+ # Count records
308
+ total_orders = orders.count()
309
+ recent_orders = orders.count(where={'created_at': {'>=': '2023-01-01'}})
310
+
311
+ # Aggregations
312
+ stats = orders.select(
313
+ columns=['COUNT(*) as total', 'SUM(amount) as revenue', 'AVG(amount) as avg_order'],
314
+ where={'status': 'completed'},
315
+ groupby='customer_id'
316
+ ).all()
317
+ ```
318
+
319
+ ### Raw SQL
320
+
321
+ When you need full control, execute raw SQL:
322
+
323
+ ```python
324
+ @engine.transaction
325
+ def raw_queries(tx):
326
+ # Execute raw SQL
327
+ results = tx.execute("""
328
+ SELECT u.name, COUNT(o.id) as order_count
329
+ FROM users u
330
+ LEFT JOIN orders o ON u.id = o.user_id
331
+ WHERE u.status = %s
332
+ GROUP BY u.id, u.name
333
+ HAVING COUNT(o.id) > %s
334
+ """, ['active', 5]).all()
335
+
336
+ # Get single value
337
+ total = tx.execute("SELECT COUNT(*) FROM users").scalar()
338
+
339
+ # Get simple list
340
+ names = tx.execute("SELECT name FROM users").as_simple_list()
341
+ ```
342
+
343
+ ## Error Handling
344
+
345
+ Transactions automatically handle rollbacks on exceptions:
346
+
347
+ ```python
348
+ @engine.transaction
349
+ def safe_transfer(tx):
350
+ try:
351
+ # Multiple operations that must succeed together
352
+ from_account = tx.table('accounts').find(from_id)
353
+ to_account = tx.table('accounts').find(to_id)
354
+
355
+ from_account['balance'] -= amount
356
+ to_account['balance'] += amount
357
+
358
+ # If any operation fails, entire transaction rolls back
359
+
360
+ except Exception as e:
361
+ # Transaction automatically rolled back
362
+ logger.error(f"Transfer failed: {e}")
363
+ raise
364
+ ```
365
+
366
+ ## Development
367
+
368
+ ### Setting up for Development
369
+
370
+ ```bash
371
+ git clone https://github.com/your-repo/velocity-python.git
372
+ cd velocity-python
373
+ pip install -e .[dev]
374
+ ```
375
+
376
+ ### Running Tests
377
+
378
+ ```bash
379
+ pytest tests/
380
+ ```
381
+
382
+ ### Code Quality
383
+
384
+ ```bash
385
+ # Format code
386
+ black src/
387
+
388
+ # Type checking
389
+ mypy src/
390
+
391
+ # Linting
392
+ flake8 src/
393
+ ```
394
+
395
+ ## License
396
+
397
+ This project is licensed under the MIT License - see the LICENSE file for details.
398
+
399
+ ## Contributing
400
+
401
+ 1. Fork the repository
402
+ 2. Create a feature branch (`git checkout -b feature/amazing-feature`)
403
+ 3. Commit your changes (`git commit -m 'Add some amazing feature'`)
404
+ 4. Push to the branch (`git push origin feature/amazing-feature`)
405
+ 5. Open a Pull Request
406
+
407
+ ## Changelog
408
+
409
+ See [CHANGELOG.md](CHANGELOG.md) for a list of changes and version history.
@@ -1,4 +1,4 @@
1
- velocity/__init__.py,sha256=eeZsYrccdbfc9oqIw9cgzKD9hVgz7vR-gJYLQvOBt9Y,106
1
+ velocity/__init__.py,sha256=_hF10ca5YZOujcRq12zSbpL0fZy3TWkf_BY06OrD-tw,106
2
2
  velocity/app/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
3
  velocity/app/invoices.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
4
  velocity/app/orders.py,sha256=W-HAXEwY8-IFXbKh82HnMeRVZM7P-TWGEQOWtkLIzI4,6298
@@ -30,11 +30,11 @@ velocity/db/servers/sqlite.py,sha256=X210a5pENT9PiVK7f16fxXzFwEsq8fSe58Vouv2xqlk
30
30
  velocity/db/servers/sqlite_reserved.py,sha256=-xmjl-Hgu6lKqkCAXq_6U8_aJX6gvaMgLMLdCt-Ej7o,3006
31
31
  velocity/db/servers/sqlserver.py,sha256=0uGLEWRXiUhrOVTpEA1zvaKq1mcfiaCDp9r7gX-N71g,29914
32
32
  velocity/db/servers/sqlserver_reserved.py,sha256=3LGQYU0qfvk6AbKety96gbzzfLbZ0dNHDPLxKGvvi4Q,4596
33
- velocity/db/servers/tablehelper.py,sha256=njGGwUovioQ9sKB6O-L8OWIuSaHgdJ-EDeokEf5zY2c,11516
33
+ velocity/db/servers/tablehelper.py,sha256=IW17pedialg2xNORv2uAqNA9SB3aomDtB1HRxAEvBmA,21936
34
34
  velocity/db/servers/postgres/__init__.py,sha256=Z0zJib46hz1zfEAMG0rQBlJ6lp47LW7t0_63xMS0zrI,528
35
35
  velocity/db/servers/postgres/operators.py,sha256=A2T1qFwhzPl0fdXVhLZJhh5Qfx-qF8oZsDnxnq2n_V8,389
36
36
  velocity/db/servers/postgres/reserved.py,sha256=5tKLaqFV-HrWRj-nsrxl5KGbmeM3ukn_bPZK36XEu8M,3648
37
- velocity/db/servers/postgres/sql.py,sha256=o2hnu0SLbQdU4-e7R8_t9T9mjY7RiaLadD0unWNqfXA,38188
37
+ velocity/db/servers/postgres/sql.py,sha256=OoVctgZ3C2sUu6PeMFVCbmQHyfWY-KNmBlCX2PkvaGA,41326
38
38
  velocity/db/servers/postgres/types.py,sha256=Wa45ppVf_pdWul-jYWFRGMl6IdSq8dAp10SKnhL7osQ,3757
39
39
  velocity/misc/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
40
40
  velocity/misc/db.py,sha256=MPgt-kkukKR_Wh_S_5W-MyDgaeoZ4YLoDJ54wU2ppm4,2830
@@ -47,8 +47,8 @@ velocity/misc/tools.py,sha256=_bGneHHA_BV-kUonzw5H3hdJ5AOJRCKfzhgpkFbGqIo,1502
47
47
  velocity/misc/conv/__init__.py,sha256=MLYF58QHjzfDSxb1rdnmLnuEQCa3gnhzzZ30CwZVvQo,40
48
48
  velocity/misc/conv/iconv.py,sha256=d4_BucW8HTIkGNurJ7GWrtuptqUf-9t79ObzjJ5N76U,10603
49
49
  velocity/misc/conv/oconv.py,sha256=h5Lo05DqOQnxoD3y6Px_MQP_V-pBbWf8Hkgkb9Xp1jk,6032
50
- velocity_python-0.0.89.dist-info/licenses/LICENSE,sha256=aoN245GG8s9oRUU89KNiGTU4_4OtnNmVi4hQeChg6rM,1076
51
- velocity_python-0.0.89.dist-info/METADATA,sha256=SV3lG6P-Urgr3tDgPhQZlJjFhCcij3Uv9JaBhg9l68I,8586
52
- velocity_python-0.0.89.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
53
- velocity_python-0.0.89.dist-info/top_level.txt,sha256=JW2vJPmodgdgSz7H6yoZvnxF8S3fTMIv-YJWCT1sNW0,9
54
- velocity_python-0.0.89.dist-info/RECORD,,
50
+ velocity_python-0.0.92.dist-info/licenses/LICENSE,sha256=aoN245GG8s9oRUU89KNiGTU4_4OtnNmVi4hQeChg6rM,1076
51
+ velocity_python-0.0.92.dist-info/METADATA,sha256=Q2xb0O7dB0jcQk3ejKvaivyYCaKw0azJ-OuqX8lGDGM,9977
52
+ velocity_python-0.0.92.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
53
+ velocity_python-0.0.92.dist-info/top_level.txt,sha256=JW2vJPmodgdgSz7H6yoZvnxF8S3fTMIv-YJWCT1sNW0,9
54
+ velocity_python-0.0.92.dist-info/RECORD,,
@@ -1,186 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: velocity-python
3
- Version: 0.0.89
4
- Summary: A rapid application development library for interfacing with data storage
5
- Author-email: Paul Perez <pperez@codeclubs.org>
6
- Project-URL: Homepage, https://codeclubs.org/projects/velocity
7
- Classifier: Programming Language :: Python :: 3
8
- Classifier: License :: OSI Approved :: MIT License
9
- Classifier: Operating System :: OS Independent
10
- Requires-Python: >=3.7
11
- Description-Content-Type: text/markdown
12
- License-File: LICENSE
13
- Requires-Dist: boto3
14
- Requires-Dist: requests
15
- Requires-Dist: jinja2
16
- Requires-Dist: xlrd
17
- Requires-Dist: openpyxl
18
- Requires-Dist: sqlparse
19
- Provides-Extra: mysql
20
- Requires-Dist: mysql-connector-python; extra == "mysql"
21
- Provides-Extra: sqlserver
22
- Requires-Dist: python-tds; extra == "sqlserver"
23
- Provides-Extra: postgres
24
- Requires-Dist: psycopg2-binary; extra == "postgres"
25
- Dynamic: license-file
26
-
27
- # Velocity.DB
28
-
29
- This project's goal is to simplify database management by abstracting complex (and many times database engine specific) functions to Python methods. This project is still in its infancy and is not yet ready for production use. If you would like to contribute to this project, please feel free to fork it and submit a pull request. This documentation is severely out of date and not yet complete, but will be updated as the project progresses.
30
-
31
- This project currently supports the following database engines:
32
-
33
- <b>PostgreSQL</b><br/>
34
- <b>Microsoft SQL Server</b><br/>
35
- <b>SQLite</b><br/>
36
- <b>MySQL</b><br/>
37
-
38
- [The source for this project is available here][src].
39
-
40
- <b>Prerequisites:</b><br/>
41
- The following packages must be installed prior to using Velocity.DB:<br/>
42
- `psycopg2` - For PostgreSQL<br/>
43
- `pytds` - For Microsoft SQL Server<br/>
44
- `sqlite3` - For SQLite 3<br/>
45
- `mysqlclient` - MySQL<br/>
46
- You will also need the MySQL Connector for your operating system before you install `mysqlclient`. You can download it <a href='https://dev.mysql.com/downloads/connector/c/'>here.</a>
47
-
48
- <b>For Windows Users:</b><br/>
49
- If you're using Windows, after you install the MySQL Connector you will need the Visual C++ Compiler for Python 2.7, you can download it <a href='https://www.microsoft.com/en-us/download/details.aspx?id=44266'>here.</a> After both dependencies are installed you can install `mysqlclient` without issue.
50
-
51
- Optionally if you only want to support a single database engine or do not want to install dependencies for engines you won't be using, download the source code for velocity.db and comment out the engines you wont be using in the `python-db/velocity/db/__init_.py` file on the following lines:
52
-
53
- <pre>
54
- # Import for PostgreSQL Support
55
- import servers.postgres
56
- postgres = servers.postgres.initialize()
57
- <br/># Import for Microsoft SQL Server Support
58
- import servers.sqlserver
59
- sqlserver = servers.sqlserver.initialize
60
- <br/># Import for SQLite 3 Support
61
- import servers.sqlite
62
- sqlite = servers.sqlite.initialize
63
- <br/># Import for MySQL Support
64
- import servers.mysql
65
- mysql = servers.mysql.initialize</pre>
66
-
67
- If you setup your project this way, make sure to install velocity.db using: `python setup.py develop` in case you want to revert your changes.
68
-
69
- ----
70
-
71
- # Using Velocity.DB
72
-
73
- <b>Warning: Not all database engines are alike, and some datatypes in certain engines will be specific to the engine. This tutorial assumes you have basic knowledge of your database engine and it's specific datatypes.</b>
74
-
75
- To setup Velocity.DB with your server, define your server variable like so:
76
-
77
- <b>PostgreSQL:</b>
78
- <pre>
79
- import velocity.db
80
- <br/>server = velocity.db.postgres({
81
- 'database':'db-name',
82
- 'host': 'server',
83
- 'user':'username',
84
- 'password':'password',
85
- })
86
- </pre>
87
- <b>Microsoft SQL Server:</b>
88
- <pre>
89
- import velocity.db
90
- <br/>server = velocity.db.sqlserver({
91
- 'database': 'db-name',
92
- 'server': 'server',
93
- 'user':'username',
94
- 'password':'password',
95
- 'use_mars': True, # To enable Multiple Active Result Sets (disabled by default)
96
- })
97
- </pre>
98
- <b>SQLite:</b>
99
- <pre>
100
- import velocity.db
101
- <br/>server = velocity.db.sqlserver({
102
- 'database': 'db-name' # Use ':memory:' for an in memory database
103
- })
104
- </pre>
105
- <b>MySQL:</b>
106
- <pre>
107
- import velocity.db
108
- <br/>server = velocity.db.mysql({
109
- 'db':'db-name',
110
- 'host':'server',
111
- 'user':'username',
112
- 'passwd':'password',
113
- })
114
- </pre>
115
- <br>
116
- <b>Basic SQL Functions:</b><br/>
117
- Since the SQL ANSI standard holds all SQL compliant databases to the CRUD standard (Create, Read, Update, Delete) we will cover how to accomplish all of those functions using Velocity.DB.<br/>
118
- <br/><b>The <code>@server.transaction</code> Decorator:</b><br/>
119
- All SQL transactions have to live in their own functions so that in case some part of the function fails, the transaction will not commit. In order to signify a method as a transaction, use the <code>@server.transaction</code> decorator. Any function using this decorator will not commit any changes to the database unless the function successfully completes without error. This also passes the argument <code>tx</code> to your method which allows you to access the transaction object within your method.<br/>
120
- <br/><b>Creating a Table:</b>
121
- <pre>
122
- @server.transaction
123
- def create_new_table(self, tx):
124
- t = tx.table('new_table')
125
- t.create()
126
- </pre>
127
- Once the function is complete the transaction will commit and you will have a new table in your database titled 'new_table'.<br>
128
- If you would like to create a new row and add a column, you could do so using the following syntax:
129
- <pre>
130
- @server.transaction
131
- def add_column(self,tx):
132
- # We will be using the same table we made in the above method.
133
- t = tx.table('new_table')
134
- # Creates a new row with a primary key of 1 (sys_id by default)
135
- r = t.row(1)
136
- r['new_column'] = 'Value to be placed in the first row of the new column'
137
- </pre>
138
- <br/><b>Reading Data from a Table:</b>
139
- <br/>Now let's say you already have a table with data named 'people', and you want to read the 'firstname' column of your table on the third row and return that field. You would accomplish this in Velocity.DB like so:
140
- <pre>
141
- @server.transaction
142
- def read_third_firstname(self, tx):
143
- t = tx.table('people')
144
- r = t.row(3)
145
- return r['firstname']
146
- </pre>
147
- The above method will return the value of the 'firstname' column in row 3 of the table. The table object is iterable so if you would like to return the values of each field in the 'firstname' column you could do so like this:
148
- <pre>
149
- @server.transaction
150
- def read_all_firstnames(self,tx):
151
- t = tx.table('people')
152
- name_list = []
153
- for r in t:
154
- name_list.append(r['firstname'])
155
- return name_list
156
- </pre>
157
- <b>Updating a Preexisting Table:</b><br/>
158
- If you already have a table that you would like to update the data within, you can update data fields using the same syntax that you would use to create the field. This example will be working on a table named 'people' with columns: 'firstname' and 'lastname' with information filled out for 3 rows. Let's assume that the person on row 2 just got married and their last name has changed so we need to update it within the database.
159
- <pre>
160
- @server.transaction
161
- def update_lastname(self, tx):
162
- t = tx.table('people')
163
- r = t.row(2)
164
- r['lastname'] = 'Newname'
165
- </pre>
166
- Notice the syntax is the same as if we were creating a new column. This syntax will attempt to insert the data, and if the column doesn't exist then it will create it. It will also see if the data is already populated, and if so it will issue a UPDATE command to the database instead.<br/>
167
- <br/><b>Deleting Data and Dropping Tables:</b><br/>
168
- To delete data from an existing table you may want to only delete a specific row. We will use the same 'people' database, let's go ahead and delete the person that was occupying row 3.
169
- <pre>
170
- @server.transaction
171
- def delete_person(self, tx):
172
- t = tx.table('people')
173
- r = t.row(3)
174
- r.delete()
175
- </pre>
176
- It's as simple as that! But what if instead you were wanting to drop the whole table? <b>Warning: Executing the following code will drop the table from the database, if you are testing on your own database make sure you have a backup first.</b>
177
- <pre>
178
- @server.transaction
179
- def drop_table(self, tx):
180
- t = tx.table('people')
181
- t.drop()
182
- </pre>
183
- Keep in mind this will use the "IF EXISTS" SQL statement so if you accidentally misspell a table name, your program will not hang and no tables will be dropped.<br/>
184
- <br/>Congratulations, you now know how to use basic CRUD functionality with Velocity.DB. Velocity.DB has many advanced features as well, so if you'd like to see how some of those methods are used check out the <code>python-db/velocity/tests/db/unit_tests.py</code> file for examples.
185
-
186
- [src]: https://github.com/