Package: easy-postgres
Easy PostgresAbstraction layer for PostgreSQL database manipulation based on thepsycopg2packagePrimary focuses arelightweight APIandhigh flexibilitywhen it comes to handling user input. This should make the package very easy to use while maintaining a usable performance level.ContentsEasy PostgresContentsWARNING: Work in ProgressHow To UseConnectionclassConnection.runmethodConnection.onemethodConnection.allmethodConnection.itermethodConnection.XXX_dictmethodsDictionaryclassAccessing ItemsTransactionclassLicenseWARNING: Work in ProgressThis package is currently under heavy development and should NOT be used in production. The current API is very likely to change in the near future.How To UseConnectionclassTo do anything, you must first create an instance of theConnectionclass. Give the instructor aDSN. The DSN can take many forms, so please check thepsycopg2.connectfunction documentationfor more details.Once you have aConnection, you are ready to run any common SQL query (SELECT,INSERT,UPDATE,DELETEshould definitely work; the rest should probably work, but it is not guaranteed).Connection.runmethodExecutes the specified SQL query and returns nothing (None). This is the right choice for all non-returning queries (INSERT,UPDATE,DELETE,DROP, etc.). AnINSERTquery with aRETURNINGclause should use theConnection.onemethod instead.Connection.onemethodExecutes the specified SQL query and returns a single row. If the returned row only has a single column, the single value will be returned. In the case of multiple returned columns, a tuple containing all the column values will be returned.If the number of returned rows is not exactly equal to one,Nonewill be returned instead.This method is meant to be used for SQL queries that are guaranteed to always return exactly one row (e.g.,SELECT COUNT(*) FROM table;,INSERT INTO table (id) VALUES (1) RETURNING id;).SQL QueryReturned ResultSELECT 'Hello World!';"Hello World!"SELECT 'Hello', 'World!';("Hello", "World!")SELECT 1;1SELECT 1, 2;(1, 2)SELECT 1, 2, 3, 4, 5;(1, 2, 3, 4, 5)Connection.allmethodExecutes the specified SQL query and returns all the rows as a list. Single-column results will be converted to a list of the column's values. The behavior is similar to theConnection.onemethod.This method is mostly meant to be used forSELECTqueries that may return more (or less) than one row.Connection.itermethodExecutes the specified SQL query and returns all the rows as a generator. This method is an alternative toConnection.allto be used when iterating over a large number of rows. The rows are fetched one at a time, so casting the generator to a list will give the same exact result as callingConnection.allwould have, but it will likely be much slower.Connection.XXX_dictmethodsThese methods execute the SQL queries just like their non-dict counterparts, but instead of returning a value or a tuple, they return aDictionaryinstance.It is advisable to give all the returned columns a unique name without any special characters (_is the only allowed exception). If you include any special character in the column name or if the column name is a Python keyword (if,for, etc.) or the name of a built-in method name (__init__,__str__, etc.), the column value will become inaccessible as an attribute, or worse yet, some functionality of theDictionaryclass may be broken. Please keep this in mind when using theXXX_dictmethods.DictionaryclassAn extension of the Python's built-indictclass. It makes the items accessible via attributes (the item's key is used as the attribute name). There are several limitations, but the code should be slightly more readable. The support for the default dictionary item access (via an index) remains.ADictionarycan be initialized from a regular dictionary, using keyword arguments or a combination of both.Accessing ItemsFor the purpose of this example, imagine you ran an SQL query that returned a single row as aDictionary. The query result is stored in a variable calledresult. Now you want to print the value of thepricecolumn. Here is a comparison ofdictandDictionary.Access MethodStandarddictDictionaryIndexprint(result["price"])print(result["price"])AttributeN/Aprint(result.price)You can use whichever way of accessing the items you prefer. If you want, you can even cast theDictionaryback to adictfor better compatibility. Being able to access items as attributes simply seems more convenient and easier to read.TransactionclassThis class can be used to execute several SQL queries in a series without intermediate commits. If an exception occurs during any of the queries, all the changes made during the transaction will be rolled back. Otherwise, the changes will be committed all at once when you exit the transaction block. This prevents committing only partial changes when an error occurs, which could lead to an unexpected state of the database.Keep in mind that thisTransactionclass is by no means related to the SQLTRANSACTION.Instances of this class are only meant to be used in the head ofwithblocks (see code below for intended usage). It is preferable to create aTransactionby calling theConnection.transactionmethod instead of calling the constructor manually (even though there is no difference as of writing this). Please do not create multipleTransactions at once using the sameConnection.conn=Connection("postgresql:///db")withconn.transaction():row_id=conn.one("INSERT INTO table (id, value) VALUES (10, 'Hello World!') RETURNING id;")prev_id=conn.one("SELECT MAX(id) FROM table WHERE id <%s;",row_id)conn.run("UPDATE table SET value = 'New Value' WHERE id =%s;",prev_id)This is perhaps kind of a silly code, but it demonstrates the functionality. If one of the queries fails (throws an exception), no changes will be committed. If they all succeed, the changes will be made after the last query is executed and thewithblock is exited.LicenseThis package is available under theMIT License.