Download the PHP package simplon/postgres without Composer
On this page you can find all versions of the php package simplon/postgres. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Informations about the package postgres
_ _ _ ___(_)_ __ ___ _ __ | | ___ _ __ _ __ ___ ___| |_ __ _ _ __ ___ ___ / __| | '_ ` _ \| '_ \| |/ _ \| '_ \ | '_ \ / _ \/ __| __/ _` | '__/ _ \/ __| \__ \ | | | | | | |_) | | (_) | | | | | |_) | (_) \__ \ || (_| | | | __/\__ \ |___/_|_| |_| |_| .__/|_|\___/|_| |_| | .__/ \___/|___/\__\__, |_| \___||___/ |_| |_| |___/
Simplon/Postgres
- Installing
- Direct vs. PgSqlManager
- Setup connection
- Usage: Direct access
4.1. Query
4.2. Insert
4.3. Update
4.4. Replace
4.5. Delete
4.6. Execute - Usage: PgSqlManager
5.1. Query
5.2. Insert
5.3. Update
5.4. Replace
5.5. Delete
5.6. Execute - IN() Clause Handling
6.1. The issue
6.2. The solution - CRUD Helper
7.1. Intro
7.2. Requirements
7.3. Flexibility/Restrictions
7.4. Conclusion
7.5. Examples
7.6. Example Custom Vo - Exceptions
Dependecies
- PHP >= 5.3
- PDO
1. Installing
Easy install via composer. Still no idea what composer is? Inform yourself here.
2. Direct vs. PgSqlManager
I implemented two different ways of interacting with Postgres. The first option is the usual one which interacts directly with the database. Following a straight forward example to show you what I mean:
In constrast to the prior method the PgSqlManager uses a Builder Pattern to deal with the database. What advantage does that offer? Well, in case that we want to do more things with our query before sending it off we encapsule it as a . From there on we could pass it throughout our application to add more data or alike before sending the query finally off to the database. Again, a quick example of how we would rewrite the above :
3. Setup connection
The library requires a config value object in order to instantiate a connection with Postgres. See how it's done:
The following code shows all possible parameters to setup a connection:
In case that you wanna use the there is one piece missing:
4. Usage: Direct access
4.1. Query
FetchColumn
Returns a selected column from the first match. The example below returns or if nothing was found.
FetchColumnMany
Returns an array with the selected column from all matching datasets. In the example below an array with all will be returned or if nothing was found.
FetchColumnManyCursor
Returns one matching dataset at a time. It is resource efficient and therefore handy when your result has many data. In the example below you either iterate through the foreach loop in case you have matchings or nothing will happen.
FetchRow
Returns all selected columns from a matched dataset. The example below returns , for the matched dataset. If nothing got matched will be returned.
FetchRowMany
Returns all selected columns from all matched dataset. The example below returns for each matched dataset , . If nothing got matched will be returned.
FetchRowManyCursor
Same explanation as for except that we receive all selected columns.
4.2. Insert
Single data
Inserting data into the database is pretty straight forward. Follow the example below:
The result depends on the table. If the table holds an column you will receive the ID count for the inserted data. If the table does not hold such a field you will receive for a successful insert. If anything went bogus you will receive .
Many datasets
Follow the example for inserting many datasets at once:
The result depends on the table. If the table holds an column you will receive the ID count for the inserted data. If the table does not hold such a field you will receive for a successful insert. If anything went bogus you will receive .
4.3. Updating
Simple update statement
Same as for insert statements accounts for updates. Its easy to understand. If the update succeeded the response will be . If something went wrong you will receive .
Custom update conditions query
Same as for insert statements accounts for updates. Its easy to understand. If the update succeeded the response will be . If something went wrong you will receive .
4.4. Replace
As Postgres states it: works exactly like , except that if an old row in the table has the same value as a new row for a or a , the old row is deleted before the new row is inserted.
Replace a single datasets
As a result you will either receive the or in case something went wrong.
Replace multiple datasets
As a result you will either receive an array of or in case something went wrong.
4.5. Delete
Simple delete conditions
The following example demonstrates how to remove data. If the query succeeds we will receive else .
Custom delete conditions query
The following example demonstrates how to remove data with a custom conditions query. If the query succeeds we will receive else .
4.6. Execute
This method is ment for calls which do not require any parameters such as . If the call succeeds you will receive . If it fails an will be thrown.
5. Usage: PgSqlManager
The following query examples will be a rewrite of the aforementioned examples. Remember: We need an instance of the . Paragraph shows how to get your hands on it.
5.1. Query
FetchColumn
Returns a selected column from the first match. In the example below will be returned or if nothing was found.
FetchColumnMany
Returns an array with the selected column from all matching datasets. In the example below an array with all will be returned or if nothing was found.
FetchColumnManyCursor
Returns one matching dataset at a time. It is resource efficient and therefore handy when your result has many data. In the example below you either iterate through the foreach loop in case you have matchings or nothing will happen.
FetchRow
Returns all selected columns from a matched dataset. The example below returns , for the matched dataset. If nothing got matched will be returned.
FetchRowMany
Returns all selected columns from all matched dataset. The example below returns for each matched dataset , . If nothing got matched will be returned.
FetchRowManyCursor
Same explanation as for except that we receive all selected columns.
5.2. Insert
Single data
Inserting data into the database is pretty straight forward. Follow the example below:
The result depends on the table. If the table holds an column you will receive the ID count for the inserted data. If the table does not hold such a field you will receive for a successful insert. If anything went bogus you will receive .
Many datasets
Follow the example for inserting many datasets at once:
The result depends on the table. If the table holds an column you will receive the ID count for the inserted data. If the table does not hold such a field you will receive for a successful insert. If anything went bogus you will receive .
5.3. Update
Simple update statement
Same as for insert statements accounts for updates. Its easy to understand. If the update succeeded the response will be . If something went wrong you will receive .
Custom update conditions query
Same as for insert statements accounts for updates. Its easy to understand. If the update succeeded the response will be . If something went wrong you will receive .
5.4. Replace
As Postgres states it: works exactly like , except that if an old row in the table has the same value as a new row for a or a , the old row is deleted before the new row is inserted.
Replace a single datasets
As a result you will either receive the or in case something went wrong.
Replace multiple datasets
As a result you will either receive an array of or in case something went wrong.
5.5. Delete
Simple delete conditions
The following example demonstrates how to remove data. If the query succeeds we will receive else .
Custom delete conditions query
The following example demonstrates how to remove data with a custom conditions query. If the query succeeds we will receive else .
6. IN() Clause Handling
6.1. The issue
There is no way using an clause via PDO. This functionality is simply not given. However, you could do something like the following:
Looks good at first sight - not sexy but probably does the job, right? Wrong. This approach only works with and it does not the user's input - the reason why we use in first place.
Just for the record here is a string example which would not work:
The only way how this would work is by wrapping each value like the following: . Way too much work.
6.2. The solution
To take advantage of the built in with escaping and type handling do the following:
7. CRUD Helper
7.1. Intro
stands for and reflects the for basic functions for persisent storage.
I found myself writing more and more CRUDs for all my object/database interactions simply for the reason of having a when I was interacting with these objects for above mentioned functions. Eventually, it has sort of a touch of a database model but with more flexibility. Also, we keep writing and by that we keep the red line for all our code base.
Note: are actually while models are not value objects. The reason for this is that a value object is vehicle for all sorts of data while models are only vehicles for database data. At least that's what it should be.
7.2. Requirements/Restrictions
There are really not many requirements/restrictions:
- Instance of - requires an instance of .
- Value object needs to extend from
- Table name should be in plural or set it via within the value object.
- Value object's instance variables must match the table's column names in (see example below).
- Each value object reflects only - fetches your data.
- Don't set any property in your value object which doesn't reflect your database table. If you have to, make either use of or . See for description.
- In case of a : if your field name differs from
id
you need to set it viaPgSqlCrudVo::crudPkName
. This is necessary for auto-incrementing the PK field as well as for receiving thelastInsertId
.
7.3. Flexibility
-
Set source: In case you have a table name which can't be easily pluralised (e.g. person/people) you can set the source yourself via
PgSqlCrudVo::$crudSource
within value object -
Set custom read query: In case you need a custom query to get your object you can set it when you instantiate the object
new PgSqlCrudVo($query)
or simply within your__construct() { parent::construct($query); }
. -
Callbacks: You can implement two methods which will be called prior/after saving an object:
PgSqlCrudVo::crudBeforeSave($isCreateEvent)
andPgSqlCrudVo::crudAfterSave($isCreateEvent)
. The manager will pass you a boolean to let you know what type of save process happens/happened. You could use this e.g. to set automaticallycreated_at
andupdated_at
fields. -
Set columns: If you have to either match property- and column name or only want a selection of your properties make use of
PgSqlCrudVo::crudColumns()
within your value object. It should return an array where theARRAY KEY
reflects the value object'sVARIABLE NAME
and theARRAY VALUE
theCOLUMN NAME
. Example:array('createdAt' => 'created_at')
-
Ignore properties: Considering the prior point you could do the reverse and simply
IGNORE VARIABLES
. For that implementPgSqlCrudVo::crudIgnore()
which should return an array of properties you would like to ignore. -
No assumptions: There are no assumptions about primary keys or anything alike. You set all conditions for reading, updating and/or deleting objects.
- Casted values: Thanks to your value object which is always in between you and your database you can cast all values - good bye
STRING CASTED ONLY
values.
7.4. Conclusion
That's all what is needed - at least for now. It's simple
, explicit
and flexible
enough not to restrict you in your requirements respectively your creativity
.
7.5. Examples
Enough talk, bring it on! Alright, what is needed? Lets assume we have a database table called users
and a value
object called UserVo
. Note: the value object name has to be the singular of the table's plural name.
Here is the table schema:
CREATE TABLE users (
id serial NOT NULL,
name varying(50) NOT NULL DEFAULT '',
email varying(254) NOT NULL DEFAULT '',
created_at int(10) unsigned NOT NULL,
updated_at int(10) unsigned NOT NULL,
CONSTRAINT users_user_pkey PRIMARY KEY (id)
);
... and here is our value object for the given table:
Now, lets do some CRUD, baby! For all processes we need an instance of our PgSqlCrudManager
:
Create a user:
Read a user:
Update a user:
Delete a user:
7.6. Example Custom Vo
Setting a custom table name
since the plural from person is not persons:
In case your column names
are totally off there is a way to match them anyway against your properties
:
Sometimes there are some helper properties
which are not part of your database entry. Here is a way to ignore them:
8. Exceptions
For both access methods (direct, PgSqlManager) occuring exceptions will be wrapped by a PostgresException
. All essential exception information will be summarised as JSON
within the Exception Message
.
Here is an example of how that might look like:
{"query":"SELECT pro_id FROM names WHERE connector_type = :connectorType","params":{"connectorType":"FB"},"errorInfo":{"sqlStateCode":"42S22","code":1054,"message":"Unknown column 'pro_id' in 'field list'"}}
License
Simplon/Postgres is freely distributable under the terms of the MIT license.
Copyright (c) 2015 Tino Ehrich ([email protected])
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
All versions of postgres with dependencies
ext-pdo Version *