https://wiki.postgresql.org/api.php?action=feedcontributions&user=Boshomi&feedformat=atomPostgreSQL wiki - User contributions [en]2024-03-29T13:53:31ZUser contributionsMediaWiki 1.35.13https://wiki.postgresql.org/index.php?title=Using_psycopg2_with_PostgreSQL&diff=17850Using psycopg2 with PostgreSQL2012-06-26T18:03:45Z<p>Boshomi: syntaxhighlight</p>
<hr />
<div>[[Psycopg2]] is a fairly mature driver for interacting with PostgreSQL from the Python scripting language. It is written in C and provides to efficiently perform the full range of SQL operations against Postgres databases. This page deals with the 2nd version of the driver, not much older ''psycopg'' driver.<br />
<br />
==Overview==<br />
<br />
===Links===<br />
*[http://initd.org/psycopg/docs/index.html Official Project Documentation]<br />
*[http://initd.org/svn/psycopg/psycopg2/trunk/examples/ Psycopg2 Project Examples]<br />
*[[Psycopg2 Tutorial|Simple Tutorial on Psycopg2 with Python 2.4]]<br />
<br />
===Features===<br />
*Multiple connections / connection objects (Does not force the use of a singleton)<br />
*Transaction management/Methods<br />
*Return columns as a Python Dictionary (Hash) with column names<br />
*Automatic filtering<br />
*Cursor object<br />
*Connection pooling (example to be added later)<br />
*Asynchronous queries (Thread Safe)<br />
<br />
===Complaints===<br />
*Hard to find documentation<br />
*Sometimes hard to find distribution packages (python-Psycopg2)<br />
*Sometimes examples are not updated with code modifications<br />
<br />
==Examples==<br />
I will not assume you are perfectly familiar with Python in the below examples; therefore I have provided an excessive amount of comments and each example is a full-fledged script instead of just a snippet.<br />
<br />
You may want to copy the examples into your favorite code editor for syntax highlighting!<br />
<br />
All code examples were tested on Python 2.6 running OpenSUSE Linux.<br />
<br />
===Connect to Postgres===<br />
<br />
Connect to the Postgres Database using authentication. Catch and print a connection error if one occurs.<br />
<br />
<source lang="python"><br />
#!/usr/bin/python<br />
import psycopg2<br />
import sys<br />
<br />
def main():<br />
#Define our connection string<br />
conn_string = "host='localhost' dbname='my_database' user='postgres' password='secret'"<br />
<br />
# print the connection string we will use to connect<br />
print "Connecting to database\n ->%s" % (conn_string)<br />
<br />
# get a connection, if a connect cannot be made an exception will be raised here<br />
conn = psycopg2.connect(conn_string)<br />
<br />
# conn.cursor will return a cursor object, you can use this cursor to perform queries<br />
cursor = conn.cursor()<br />
print "Connected!\n"<br />
<br />
if __name__ == "__main__":<br />
main()<br />
</source><br />
<br />
===Perform a Select===<br />
<br />
This example shows how to connect to a database, and then obtain and use a cursor object to retrieve records from a table.<br />
<br />
In this example we will assume your database is named "my_database" in the public schema and the table you are selecting from is named "my_table".<br />
<br />
<source lang="python"><br />
#!/usr/bin/python<br />
import psycopg2<br />
import sys<br />
import pprint<br />
<br />
def main():<br />
conn_string = "host='localhost' dbname='my_database' user='postgres' password='secret'"<br />
# print the connection string we will use to connect<br />
print "Connecting to database\n ->%s" % (conn_string)<br />
<br />
# get a connection, if a connect cannot be made an exception will be raised here<br />
conn = psycopg2.connect(conn_string)<br />
<br />
# conn.cursor will return a cursor object, you can use this cursor to perform queries<br />
cursor = conn.cursor()<br />
<br />
# execute our Query<br />
cursor.execute("SELECT * FROM my_table")<br />
<br />
# retrieve the records from the database<br />
records = cursor.fetchall()<br />
<br />
# print out the records using pretty print<br />
# note that the NAMES of the columns are not shown, instead just indexes.<br />
# for most people this isn't very useful so we'll show you how to return<br />
# columns as a dictionary (hash) in the next example.<br />
pprint.pprint(records)<br />
<br />
if __name__ == "__main__":<br />
main()<br />
</source><br />
<br />
===Select/Fetch Records with Column Names===<br />
<br />
In this example we will perform a select just like we did above but this time we will return columns as a Python Dictionary so column names are present.<br />
<br />
We will also use Psycopg2's prinf-style variable replacement, as well as a different fetch method to return a row (fetchone).<br />
<br />
<source lang="python"><br />
#!/usr/bin/python<br />
import psycopg2<br />
#note that we have to import the Psycopg2 extras library!<br />
import psycopg2.extras<br />
import sys<br />
<br />
def main():<br />
conn_string = "host='localhost' dbname='my_database' user='postgres' password='secret'"<br />
# print the connection string we will use to connect<br />
print "Connecting to database\n ->%s" % (conn_string)<br />
<br />
# get a connection, if a connect cannot be made an exception will be raised here<br />
conn = psycopg2.connect(conn_string)<br />
<br />
# conn.cursor will return a cursor object, you can use this query to perform queries<br />
# note that in this example we pass a cursor_factory argument that will<br />
# dictionary cursor so COLUMNS will be returned as a dictionary so we<br />
# can access columns by their name instead of index.<br />
cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)<br />
<br />
# tell postgres to use more work memory<br />
work_mem = 2048<br />
<br />
# by passing a tuple as the 2nd argument to the execution function our<br />
# %s string variable will get replaced with the order of variables in<br />
# the list. In this case there is only 1 variable.<br />
# Note that in python you specify a tuple with one item in it by placing<br />
# a comma after the first variable and surrounding it in parentheses.<br />
cursor.execute('SET work_mem TO %s', (work_mem,))<br />
<br />
# Then we get the work memory we just set -> we know we only want the<br />
# first ROW so we call fetchone.<br />
# then we use bracket access to get the FIRST value.<br />
# Note that even though we've returned the columns by name we can still<br />
# access columns by numeric index as well - which is really nice.<br />
cursor.execute('SHOW work_mem')<br />
<br />
# Call fetchone - which will fetch the first row returned from the<br />
# database.<br />
memory = cursor.fetchone()<br />
<br />
# access the column by numeric index:<br />
# even though we enabled columns by name I'm showing you this to<br />
# show that you can still access columns by index and iterate over them.<br />
print "Value: ", memory[0]<br />
<br />
# print the entire row <br />
print "Row: ", memory<br />
<br />
if __name__ == "__main__":<br />
main()<br />
</source><br />
<br />
===Fetch Records using a Server-Side Cursor===<br />
<br />
If you have an extremely large result set to retrieve from your database, or you would like to iterate through a tables records without first retrieving the entire table a cursor is exactly what you need.<br />
<br />
A cursor keeps the database connection open and retrieves database records 1 by 1 as you request them.<br />
<br />
There are several ways to accomplish this in Psycopg2, I will show you the most basic example.<br />
<br />
For advanced usage see the documentation on the use of cursor.scroll() see:<br />
* [http://initd.org/psycopg/docs/usage.html#server-side-cursors Server-Side Cursors]<br />
* [http://initd.org/psycopg/docs/cursor.html#cursor.scroll Scroll() Method]<br />
<br />
<source lang="python"><br />
#!/usr/bin/python<br />
import psycopg2<br />
#note that we have to import the Psycopg2 extras library!<br />
import psycopg2.extras<br />
import sys<br />
<br />
def main():<br />
conn_string = "host='localhost' dbname='my_database' user='postgres' password='secret'"<br />
# print the connection string we will use to connect<br />
print "Connecting to database\n ->%s" % (conn_string)<br />
<br />
conn = psycopg2.connect(conn_string)<br />
<br />
# HERE IS THE IMPORTANT PART, by specifying a name for the cursor<br />
# psycopg2 creates a server-side cursor, which prevents all of the<br />
# records from being downloaded at once from the server.<br />
cursor = conn.cursor('cursor_unique_name', cursor_factory=psycopg2.extras.DictCursor)<br />
cursor.execute('SELECT * FROM my_table LIMIT 1000')<br />
<br />
# Because cursor objects are iterable we can just call 'for - in' on<br />
# the cursor object and the cursor will automatically advance itself<br />
# each iteration.<br />
# This loop should run 1000 times, assuming there are at least 1000<br />
# records in 'my_table'<br />
row_count = 0<br />
for row in cursor:<br />
row_count += 1<br />
print "row: %s %s\n" % (row_count, row)<br />
<br />
if __name__ == "__main__":<br />
main()<br />
</source><br />
<br />
[[Category:Python]]</div>Boshomihttps://wiki.postgresql.org/index.php?title=Performance_Optimization&diff=17798Performance Optimization2012-06-12T21:36:07Z<p>Boshomi: +cat</p>
<hr />
<div>== General Setup and Optimization ==<br />
* [[Tuning Your PostgreSQL Server]] by Greg Smith, Robert Treat, and Christopher Browne<br />
* [http://www.revsys.com/writings/postgresql-performance.html Performance Tuning PostgreSQL] by Frank Wiles<br />
* [http://www.pgcon.org/2008/schedule/events/104.en.html GUCs: A Three Hour Tour] by Josh Berkus. Also useful here is his [http://pgfoundry.org/docman/view.php/1000106/84/calcfactors.sxc tuning OpenOffice spreadsheet], which suggests tuning values for 5 different types of workloads. <br />
* [http://linuxfinances.info/info/quickstart.html QuickStart Guide to Tuning PostgreSQL] by Christopher Browne<br />
* [http://www.westnet.com/~gsmith/content/postgresql/pg-5minute.htm 5-Minute Introduction to PostgreSQL Performance] by Greg Smith<br />
* [http://www.varlena.com/GeneralBits/Tidbits/annotated_conf_e.html Annotated postgresql.conf] by Josh Berkus and Shridhar Daithankar (older V7.4 targeted version of material covered in the GUC tour referenced above)<br />
* [http://www.varlena.com/GeneralBits/Tidbits/perf.html Performance Tuning] by Josh Berkus and Shridhar Daithankar<br />
* [http://www.zope.org/Members/pupq/pg_in_aggregates Replacing Slow Loops in PostgreSQL] by Joel Burton<br />
* [http://www.postgresql.org/files/documentation/books/aw_pgsql/hw_performance/ PostgreSQL Hardware Performance Tuning] by Bruce Momjian<br />
* [http://www.targeted.org/articles/databases/fragmentation.html The effects of data fragmentation in a mixed load database] by Dmitry Dvoinikov<br />
* [http://www.2ndquadrant.com/static/2quad/media/pdfs/talks/Postgres_Performance_Update83.pdf PostgreSQL Performance Features in 8.3] by Simon Riggs<br />
* [http://www.2ndquadrant.com/static/2quad/media/pdfs/talks/Postgres_Performance_Update84.pdf PostgreSQL Performance Features in 8.4] by Simon Riggs<br />
<br />
Performance courses are available from a number of companies. Check [http://www.postgresql.org/about/eventarchive events and trainings] for further details.<br />
<br />
==Critical maintenance for performance==<br />
*[[Introduction to VACUUM, ANALYZE, EXPLAIN, and COUNT]] by Jim Nasby.<br />
*[[VACUUM FULL]] and why you should avoid it<br />
*[[Planner Statistics]]<br />
*[[Using EXPLAIN]]<br />
*[[Logging Difficult Queries]]<br />
*[[Logging Checkpoints]]<br />
*[http://www.westnet.com/~gsmith/content/postgresql/chkp-bgw-83.htm Checkpoints and the Background Writer: PostgreSQL 8.3 Improvements and Migration] by Greg Smith<br />
*[[Bulk Loading and Restores]]<br />
*[[Performance Analysis Tools]] by Craig Ringer<br />
<br />
== Database architecture ==<br />
* [[Priorities|Limiting and prioritizing user/query/database resource usage]] by Craig Ringer<br />
* [[Prioritizing databases by separating into multiple clusters]] by Craig Ringer<br />
* [[Clustering]]<br />
* [[Shared Storage]]<br />
<br />
==Database Hardware Selection and Setup==<br />
* [[Database Hardware]]<br />
* [[Reliable Writes]]<br />
<br />
==Benchmark Workloads== <br />
* [[:Category:Benchmarking]]<br />
<br />
[[Category:Administration]][[Category:Performance]][[Category:Benchmarking]]<br />
[[Category:General articles and guides]]</div>Boshomihttps://wiki.postgresql.org/index.php?title=Placeholder&diff=17779Placeholder2012-06-09T08:55:50Z<p>Boshomi: + DELETEME</p>
<hr />
<div>#REDIRECT [[Placeholer]]<br />
<br />
[[Category:DELETEME]]</div>Boshomihttps://wiki.postgresql.org/index.php?title=PostgreSQL_for_Enterprise_Business_Applications&diff=17778PostgreSQL for Enterprise Business Applications2012-06-09T08:44:48Z<p>Boshomi: -pure advertising / no improvement</p>
<hr />
<div>== Introduction ==<br />
<br />
A frequent question about PostgreSQL, and open source databases in general, is about their suitability for demanding, high-dollar, business applications. While many programmers have trusted PostgreSQL for simple bulletin boards, web counters, and small ordering systems, there have not been many public descriptions of much more complex business systems in place, or helpful setup guidelines for people seeking to build such systems.<br />
<br />
In the process of building up some truly enterprise-level systems (400+ websites, $600K (USD) per month of monetary transactions, and 200+ physical satellite locations interacting with the systems and data on a daily basis) with a PHP/Apache/PostgreSQL combination, I've learned a few things. Some apply to working methods, some to large-business practice, some to simply tuning a system for maximum efficiency.<br />
<br />
Ron Chmara (2002-01-29)<br />
<br />
== Things I've learned ==<br />
<br />
<br />
# Treat it like any other accounting program. Separate user entered data from system recorded data. Use separate tables, and either external, or internal (to PostgreSQL) logic to validate the data. If your normal business logic and accounting practices are based on double entry, mirror that as well. If your systems have entry-only tables, and monthly record locks, you may find it desirable to have archival tables to store the now-locked data in.<br />
# Use transactions. This will save time, money, and headaches. For large looping inserts, for example, it dramatically reduces the amount of time required for disk writes, and if you have a program failure, or a need to abort the data entry, you aren't left with half-entered data tables.<br />
# Tune and optimize your code for doing as much as possible in one pg_exec() statement. Multiple statements should be avoided whenever possible. (let the db engine do the work, not PHP). This allows for quicker dB interaction, keeping the overhead of dB communication (and Apache CPU time) low. Since applications and tables are often built piecemeal, it's good to revisit older code, which may have more than 15 database interactions, and reduce it to one or two statements.<br />
# Decide upon numeric precision ahead of time (how many decimals?) and code for that. Always. Without fail. Different companies, and industries have different requirements, but by setting this ruleset up ahead of time you avoid running into difficult precision and rounding debates later in the code's lifecycle.<br />
# pgdump as frequently as you desire, and copy it off to a safe server. Not because it goes down (I had a programmer familiar with one of the other open-source databases (*cough*) ask if the dB had gone down, and was confused for a bit... because PostgreSQL *hasn't* gone down), but because you always want to be able to isolate a database at given breakpoints. While you can also do the same kind of thing with entry-only database systems (where an update is instead a "later" version of the record), it doesn't have the same level of # Did I mention having a backup server? It doesn't matter how good the app is, lightning will damage the best of them. The more mission critical a system is, the more you'll appreciate having off-site, or multi-site, backup database (and web) servers.<br />
# You may need to recompile or otherwise adjust your kernel for larger shared memory (shm) and/or semaphore (sem) space. Otherwise, you'll run out of memory for backends when PostgreSQL needs them. The default on RedHat 6.2, for example, only allowed for 32. The pg_pconnect php function needs a backend per connection for each apache process, which means that for 50 apache processes to one database, you need 50 postmaster backends. If you are running ten databases, and you have 20 active apache processes, you would need 200 backends. One way around this issue is to set your httpd.conf 'MaxRequest' counter low to rotate the pool, which closes the apache processes frequently (ensuring that you gain some speed with persistent connections, but that connections are closed after a certain amount of time). Another solution is to only connect to one database (which has all of your tables), to reduce the number of required backends. See also: http://www.postgresql.org/docs/current/interactive/kernel-resources.html<br />
# Investigate AOLserver as an alternative for connection pooling features (which takes care of the above issue).<br />
# If you're porting old PHP code, get the latest CVS copy or >= 4.0.7 which should have the row grabbing option in PG functions, which makes life much easier. It's not completely documented (as of 6/30/01), but it works like the php mysql functions now. The pg_close functions also work, which can help to manage the connection pooling issues with Apache.<br />
# A note about oid/currval/nextval: Ignore older documentation if you're using a recent version of pg. Several websites and books were written when these functions behaved in a different manner. One thing that does still hold true, is that using currval and nextval may not guarantee perfect serializtion (there may be holes if some interactions are aborted, or stopped, or unused). If you need perfect serialization, you can perform an insert and retrieve the record serial number based on oid, or, as noted above, use an entry table (with expected serial holes) which then feeds linearly into a table (without holes).<br />
# If you haven't done accounting apps before, hire an accountant/programmer. Their services can be pricey until you learn the ropes, but after that, the knowledge is invaluable. Even having a non-coding accountant "collaborator" to look through the code diagrams and results helps to ensure a more stable, more business-rules oriented, product. Depending on the level of accounting logic required, it may also be helpful to have a manual of GAAP (Generally Accepted Accounting Principles) standards handy.<br />
# Did I mention backups? Even inside of PG? Set up development only tables, or a dev-only machine, so your building and testing happens in an independent manner from the live data. Updating millions of customer orders to be $0.00 on a live server is not an experience you want to have. As your code complexity increases, you may wish to have two testing servers, one for code development, and another for version (Apache, PHP, PostgreSQL, etc.) testing. This way you can test new versions of application software separate from your ongoing development environment.<br />
# Watch out for binary math. Many systems and function calls use it by default, so compensate (and/or cast) accordingly. One approach is to only use integer math, and then work backwards to your decimal places, another is to work at a higher precision (8 decimal points) and return data at a lower, required, precision (4 decimal points.)<br />
# Watch out for bad data. Never, ever, under any circumstances, grant the web-server user too many rights ... or, even worse, put an SQL statement in a GET. Filter all input data for size, string type, expected user, etc. Filter, filter, filter. Then filter again. Most security warnings related to programming with PHP, or other web-based data systems, come from issues where the data is not being appropriately validated before it is being used.<br />
# Force small data fields as part of the filtering. While is is tempting to make all fields TEXT, it creates massive dB rows in the long run, and will slow down the entire system. It also enforces another layer of filtering, in cases where bad (oversized) data could be inadvertently entered and used.<br />
# Timestamp every record. This can really save you time when you need to find an exact range (such as everything done on tuesday, because you had some bad code, or tuesday's export is broken...). I find it useful to timestamp a creation date, and modification date. If you're using some form of internal user authorization (such as mod_ldap), it can also be valuable to stamp records with things like the creators uid and modifier's uid.<br />
# For some systems, you should never use "update", just insert a reversing record. (See Tips #1 and #11.) This allows you to maintain a granular record of all transactions, preventing loss of historical data. It all depends on the accounting practices required, and how much data you will need to preserve. For example, rather than zeroing out a purchase amount, or deleting an invoice number, you would insert a negative purchase for an additional record.<br />
# Vacuum often. Daily, or more often, as needed. After large record changes, VACUUM and VACUUM ANALYZE can boot performance for 1000% or more.<br />
<br />
Hope this helps.<br />
<br />
[[Category:Community]]</div>Boshomihttps://wiki.postgresql.org/index.php?title=TABLESAMPLE_Implementation&diff=17634TABLESAMPLE Implementation2012-05-23T08:28:10Z<p>Boshomi: syntaxhighlight Backus–Naur-Form (bnf)</p>
<hr />
<div>== Introduction ==<br />
TABLESAMPLE is an interesting sql clause. It is defined in SQL standard 2003. An example is<br/><br />
<code><br />
SELECT avg(salary)<br/><br />
FROM emp TABLESAMPLE SYSTEM (50);<br/><br />
</code><br />
It will return a sample of the underlying table of which the size depends on the number specified in the bracket. The detail of the specification of this query from SQL standard 2003 is described [[#Project Details|below]].<br/><br />
Microsoft SQL Server and DB2 have implemented this clause. Querying a sample of a table is often occurring in people’s work. An paper on elaborating the usage of sampling is on [http://www.almaden.ibm.com/cs/people/peterh/idugjbig.pdf a paper from IBM]. In page 1 and 2, the author describes the benefits and usage of a fast sampling method towards the discovering general trends and patterns in data. <br/><br />
It will be useful for PostgreSQL to implement this feature and make it available to the users.<br />
<br />
<br />
== Project Details ==<br />
===About TABLESAMPLE Clause=== <br />
<br />
====Concepts====<br />
In a <code>&lt;table reference&gt;</code>, <code>&lt;sample clause&gt;</code> can be specified to return a subset of result rows depending on<br />
the <code>&lt;sample method&gt;</code> and <code>&lt;sample percentage&gt;</code>. If the <code>&lt;sample clause> contains <code>&lt;repeatable clause&gt;</code>,<br />
then repeated executions of that <code>&lt;table reference&gt;</code> return a result table with identical rows for a given<br />
<code>&lt;repeat argument&gt;</code>, provided certain implementation-defined conditions are satisfied.<br />
<br />
<br />
====Syntax====<br />
<source lang="bnf" enclose="pre"><br />
<table reference> ::= <table factor> | <joined table><br />
<table factor> ::= <table primary> [ <sample clause> ]<br />
table primary> ::= <table or query name> [ [ AS ] <correlation name> ]<br />
<sample clause> ::= TABLESAMPLE <sample method> <left paren> <br />
<sample percentage> <right paren> [ <repeatable clause> ]<br />
<sample method> ::= BERNOULLI | SYSTEM<br />
<repeatable clause> ::= REPEATABLE <left paren> <repeat argument> <right paren><br />
<sample percentage> ::= <numeric value expression><br />
<repeat argument> ::= <numeric value expression><br />
</source><br />
<br />
====General Rules====<br />
Let TP be the <code>&lt;table primary&gt;</code> immediately contained in a <code>&lt;table factor&gt;</code> TF. Let RT be the result of<br />
TP. Case:<br />
# If <code>&lt;sample clause&gt;</code> is specified, then:<br />
#:(a) Let N be the number of rows in RT and let S be the value of <code>&lt;sample percentage&gt;</code>.<br />
#:(b) If S is the null value or if S < 0 (zero) or if S > 100, then an exception condition is raised: “data exception — invalid sample size”.<br />
#:(c) If <code>&lt;repeatable clause&gt;</code> is specified, then let RPT be the value of <code>&lt;repeat argument&gt;</code>. If RPT is the null value, then an exception condition is raised: data exception — invalid repeat argument in a sample clause”.<br />
#:(d) Case:<br />
#::# If <code>&lt;sample method&gt;</code> specifies BERNOULLI, then the result of TF is a table containing approximately (N &#8727; S/100) rows of RT. The probability of a row of RT being included in result of TF is S/100. Further, whether a given row of RT is included in result of TF is independent of whether other rows of RT are included in result of TF.<br />
#::# Otherwise, result of TF is a table containing approximately (N &#8727; S/100) rows of RT. The probability of a row of RT being included in result of TF is S/100.<br />
#:(e) If TF contains outer references, then a table with identical rows is generated every time TF is evaluated with a given set of values for outer references.<br />
# Otherwise, result of TF is RT.<br />
<br />
<br />
- <code>sample method</code> is specified in two types: BERNOULLI and SYSTEM<br/><br />
- BERNOULLI implies picking tuples with a specified probability.<br/><br />
- SYSTEM implies picking pages with a specified probability.<br/><br />
<br />
<br />
===Implementation Details===<br />
====List of features==== <br />
# TABLESAMPLE using select, delete, and update<br />
# SYSTEM method<br />
# REPEATABLE support<br />
# BERNOULLI method<br />
# Use optimizer statistics to produce a more accurate sample<br />
# non-integer sample percentage and repeat seed<br />
# sampling quality enhancement<br />
<br />
:4, 5 and 6 are not included in Neil’s implementation. For 5, we can use optimizer statistics to refine the algorithm for the random number selection of ages or rows. The sample produced shall be more accurate.<br />
<br />
====Inch-stones====<br />
# Conduct the basic features' implementation, able to query TABLESAMPLE clause using select, SYSTEM, with different combination of SQL queries. <br />
# Implementation of other basic features, REPEATABLE and BERNOULLI.<br />
# Improvement implementation. Support for using optimizer statistics to produce more accurate sample, non-integer sample percentage and repeat seed, and sampling quality improvement. <br />
<br />
====Project Schedule ====<br />
# From April 23rd-Mid May: learning and understanding.<br />
# From Mid May- Mid June: implement simple TABLESAMPLE clause, with SYSTEM method, and no REPEATABLE support. And do testing.<br />
# Mid June-Mid July: implement other supports, like REPEATABLE clause, and BERNOULLI method, and do testing. Improvement 5 and 6 are also implemented now. <br />
# Mid July- Mid Aug: Explore ways of improving sampling quality should be done at period 2 and 3. This period will be used to implement those ideas.<br />
<br />
== References ==<br />
* [http://www.neilconway.org/talks/hacking/ottawa/sql_standard.pdf www.neilconway.org: The TABLESAMPLE Clause: Excerpts From SQL:2003 ]<br />
* [http://www.almaden.ibm.com/cs/people/peterh/idugjbig.pdf Speeding up DB2 UDB Using Sampling: Peter J. Haas: IBM Almaden Research Center]<br />
<br />
[[Category:SQL Keyword]]</div>Boshomihttps://wiki.postgresql.org/index.php?title=TABLESAMPLE_Implementation&diff=17633TABLESAMPLE Implementation2012-05-22T23:23:21Z<p>Boshomi: /* Syntax */</p>
<hr />
<div>== Introduction ==<br />
TABLESAMPLE is an interesting sql clause. It is defined in SQL standard 2003. An example is<br/><br />
<code><br />
SELECT avg(salary)<br/><br />
FROM emp TABLESAMPLE SYSTEM (50);<br/><br />
</code><br />
It will return a sample of the underlying table of which the size depends on the number specified in the bracket. The detail of the specification of this query from SQL standard 2003 is described [[#Project Details|below]].<br/><br />
Microsoft SQL Server and DB2 have implemented this clause. Querying a sample of a table is often occurring in people’s work. An paper on elaborating the usage of sampling is on [http://www.almaden.ibm.com/cs/people/peterh/idugjbig.pdf a paper from IBM]. In page 1 and 2, the author describes the benefits and usage of a fast sampling method towards the discovering general trends and patterns in data. <br/><br />
It will be useful for PostgreSQL to implement this feature and make it available to the users.<br />
<br />
<br />
== Project Details ==<br />
===About TABLESAMPLE Clause=== <br />
<br />
====Concepts====<br />
In a <code>&lt;table reference&gt;</code>, <code>&lt;sample clause&gt;</code> can be specified to return a subset of result rows depending on<br />
the <code>&lt;sample method&gt;</code> and <code>&lt;sample percentage&gt;</code>. If the <code>&lt;sample clause> contains <code>&lt;repeatable clause&gt;</code>,<br />
then repeated executions of that <code>&lt;table reference&gt;</code> return a result table with identical rows for a given<br />
<code>&lt;repeat argument&gt;</code>, provided certain implementation-defined conditions are satisfied.<br />
<br />
<br />
====Syntax====<br />
<source lang="text" enclose="bnf"><br />
<table reference> ::= <table factor> | <joined table><br />
<table factor> ::= <table primary> [ <sample clause> ]<br />
table primary> ::= <table or query name> [ [ AS ] <correlation name> ]<br />
<sample clause> ::= TABLESAMPLE <sample method> <left paren> <br />
<sample percentage> <right paren> [ <repeatable clause> ]<br />
<sample method> ::= BERNOULLI | SYSTEM<br />
<repeatable clause> ::= REPEATABLE <left paren> <repeat argument> <right paren><br />
<sample percentage> ::= <numeric value expression><br />
<repeat argument> ::= <numeric value expression><br />
</source><br />
<br />
====General Rules====<br />
Let TP be the <code>&lt;table primary&gt;</code> immediately contained in a <code>&lt;table factor&gt;</code> TF. Let RT be the result of<br />
TP. Case:<br />
# If <code>&lt;sample clause&gt;</code> is specified, then:<br />
#:(a) Let N be the number of rows in RT and let S be the value of <code>&lt;sample percentage&gt;</code>.<br />
#:(b) If S is the null value or if S < 0 (zero) or if S > 100, then an exception condition is raised: “data exception — invalid sample size”.<br />
#:(c) If <code>&lt;repeatable clause&gt;</code> is specified, then let RPT be the value of <code>&lt;repeat argument&gt;</code>. If RPT is the null value, then an exception condition is raised: data exception — invalid repeat argument in a sample clause”.<br />
#:(d) Case:<br />
#::# If <code>&lt;sample method&gt;</code> specifies BERNOULLI, then the result of TF is a table containing approximately (N &#8727; S/100) rows of RT. The probability of a row of RT being included in result of TF is S/100. Further, whether a given row of RT is included in result of TF is independent of whether other rows of RT are included in result of TF.<br />
#::# Otherwise, result of TF is a table containing approximately (N &#8727; S/100) rows of RT. The probability of a row of RT being included in result of TF is S/100.<br />
#:(e) If TF contains outer references, then a table with identical rows is generated every time TF is evaluated with a given set of values for outer references.<br />
# Otherwise, result of TF is RT.<br />
<br />
<br />
- <code>sample method</code> is specified in two types: BERNOULLI and SYSTEM<br/><br />
- BERNOULLI implies picking tuples with a specified probability.<br/><br />
- SYSTEM implies picking pages with a specified probability.<br/><br />
<br />
<br />
===Implementation Details===<br />
====List of features==== <br />
# TABLESAMPLE using select, delete, and update<br />
# SYSTEM method<br />
# REPEATABLE support<br />
# BERNOULLI method<br />
# Use optimizer statistics to produce a more accurate sample<br />
# non-integer sample percentage and repeat seed<br />
# sampling quality enhancement<br />
<br />
:4, 5 and 6 are not included in Neil’s implementation. For 5, we can use optimizer statistics to refine the algorithm for the random number selection of ages or rows. The sample produced shall be more accurate.<br />
<br />
====Inch-stones====<br />
# Conduct the basic features' implementation, able to query TABLESAMPLE clause using select, SYSTEM, with different combination of SQL queries. <br />
# Implementation of other basic features, REPEATABLE and BERNOULLI.<br />
# Improvement implementation. Support for using optimizer statistics to produce more accurate sample, non-integer sample percentage and repeat seed, and sampling quality improvement. <br />
<br />
====Project Schedule ====<br />
# From April 23rd-Mid May: learning and understanding.<br />
# From Mid May- Mid June: implement simple TABLESAMPLE clause, with SYSTEM method, and no REPEATABLE support. And do testing.<br />
# Mid June-Mid July: implement other supports, like REPEATABLE clause, and BERNOULLI method, and do testing. Improvement 5 and 6 are also implemented now. <br />
# Mid July- Mid Aug: Explore ways of improving sampling quality should be done at period 2 and 3. This period will be used to implement those ideas.<br />
<br />
== References ==<br />
* [http://www.neilconway.org/talks/hacking/ottawa/sql_standard.pdf www.neilconway.org: The TABLESAMPLE Clause: Excerpts From SQL:2003 ]<br />
* [http://www.almaden.ibm.com/cs/people/peterh/idugjbig.pdf Speeding up DB2 UDB Using Sampling: Peter J. Haas: IBM Almaden Research Center]<br />
<br />
[[Category:SQL Keyword]]</div>Boshomihttps://wiki.postgresql.org/index.php?title=Enlaces&diff=17629Enlaces2012-05-21T09:53:41Z<p>Boshomi: Redirected page to Main Page/es</p>
<hr />
<div>#REDIRECT [[Main Page/es]]</div>Boshomihttps://wiki.postgresql.org/index.php?title=Mejorando_el_rendimiento_de_tu_Postgresql_Server&diff=17628Mejorando el rendimiento de tu Postgresql Server2012-05-21T09:52:43Z<p>Boshomi: Redirected page to Tuning Your PostgreSQL Server/es</p>
<hr />
<div>#REDIRECT [[Tuning Your PostgreSQL Server/es]]</div>Boshomihttps://wiki.postgresql.org/index.php?title=Perguntas_Frequentes&diff=17627Perguntas Frequentes2012-05-21T09:51:55Z<p>Boshomi: Redirected page to FAQ/pt</p>
<hr />
<div>#REDIRECT [[FAQ/pt]]</div>Boshomihttps://wiki.postgresql.org/index.php?title=FAQ/Perguntas_Frequentes&diff=17626FAQ/Perguntas Frequentes2012-05-21T09:51:27Z<p>Boshomi: Redirected page to FAQ/pt</p>
<hr />
<div>#REDIRECT [[FAQ/pt]]</div>Boshomihttps://wiki.postgresql.org/index.php?title=FAQ/Perguntas_Frequentes&diff=17625FAQ/Perguntas Frequentes2012-05-21T09:50:04Z<p>Boshomi: Redirected page to FAQ/pt-br</p>
<hr />
<div>#REDIRECT [[FAQ/pt-br]]</div>Boshomihttps://wiki.postgresql.org/index.php?title=Progaganda&diff=17624Progaganda2012-05-21T09:49:29Z<p>Boshomi: + DELETE ME</p>
<hr />
<div>#REDIRECT [[Propaganda]]<br />
[[Category:DELETEME]]</div>Boshomihttps://wiki.postgresql.org/index.php?title=Preguntas&diff=17623Preguntas2012-05-21T09:48:23Z<p>Boshomi: Redirected page to FAQ/es</p>
<hr />
<div>#REDIRECT [[FAQ/es]]</div>Boshomihttps://wiki.postgresql.org/index.php?title=%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98%E4%B8%8E%E8%A7%A3%E7%AD%94&diff=17618常见问题与解答2012-05-19T23:47:48Z<p>Boshomi: </p>
<hr />
<div>== 官方问答集 ==<br />
<br />
官方的问答集正处于向Wiki迁移的过程中。对于那些尚未在此页中列出的问答,请参考[http://www.postgresql.org/docs/faq/ 官方网站上的FAQ页面]。<br />
<br />
==== 通用性问答集 ====<br />
* [[Developer FAQ|开发者问答(英文)]]<br />
<br />
==== 平台相关问答 ====<br />
* [[在Windows平台上安装与运行PostgreSQL的常见问题与解答|在Windows平台上安装与运行PostgreSQL]]<br />
<br />
== 其他问答集 ==<br />
* [[Client Authentication|为什么我不能从远程系统连接到数据库?]]<br />
* [[Fixing Sequences|怎么样改正不正确的序列?]]<br />
* [[Slow Counting|为什么"select count(*) from table"这么慢?]]<br />
* [[Using EXPLAIN|我该怎么做让语句执行更快?]]<br />
* [[Logging Difficult Queries|如何能查找为何个别语句执行缓慢?]]<br />
* [[Version History|新的PostgreSQL版本有何改动?]]<br />
* [[pgpass|管理任务如何能不需口令登陆服务器?]]<br />
* [[Hint Bits|为什么在我执行只读查询时,我看到了大量写数据库操作?]]<br />
[[Category:FAQ]]<br />
[[Category:Chinese]]</div>Boshomihttps://wiki.postgresql.org/index.php?title=%D0%A7%D0%B0%D1%81%D1%82%D0%BE_%D0%97%D0%B0%D0%B4%D0%B0%D0%B2%D0%B0%D0%B5%D0%BC%D1%8B%D0%B5_%D0%92%D0%BE%D0%BF%D1%80%D0%BE%D1%81%D1%8B&diff=17617Часто Задаваемые Вопросы2012-05-19T23:46:49Z<p>Boshomi: </p>
<hr />
<div>{{Languages|FAQ}}<br />
[[:Category:FAQ|Additional FAQ Entries on this Wiki]]<br />
<br />
Перевод на русский язык выполнил Виктор Вислобоков (corochoone@gmail.com) 03.12.2010 ([http://postgresql.ru.net/docs/FAQ_russian.html])<br />
<br />
== Переводы на другие языки ==<br />
<br />
* [[Häufig gestellte Fragen|German]]<br />
* [[Perguntas Frequentes|Portuguese]]<br />
* [[Preguntas Frecuentes|Spanish]]<br />
<br />
== Вопросы специфичные для платформы ==<br />
<br />
Пользователи Windows также должны прочитать [[Running & Installing PostgreSQL On Native Windows|platform FAQ for Windows]]. А также [[Frequently Asked Questions#Platform FAQs|FAQs for other platforms]].<br />
<br />
== Общие вопросы ==<br />
<br />
=== Что такое PostgreSQL? Как произносится это название? Что такое Postgres? ===<br />
<br />
PostgreSQL произносится Post-Gres-Q-L (Пост-Грес-Кью-Эл). (Для особо любопытствующих как произносить "PostgreSQL", существует<br />
аудиофайл [http://www.postgresql.org/files/postgresql.mp3 audio file].)<br />
<br />
PostgreSQL - это объектно-реляционная система управления базами данных (СУБД), которая имеет традиционные возможности коммерческих СУБД с расширениями, которые есть в СУБД нового поколения. PostgreSQL - это свободное и полностью открытое программное обеспечение.<br />
<br />
Разработку PostgreSQL выполняет команда разработчиков, разбросанная по всему миру и связанная через Интернет. Разработка является общественным проектом и не управляется какой-либо компанией. Подробности смотрите в FAQ для разработчиков, [[Developer_FAQ | FAQ для разработчиков]].<br />
<br />
Postgres — это широко используемое сокращение для PostgreSQL. Первоначальным именем проекта в Беркли было Postgres и этот ник теперь наиболее популярен в разговорах о PostgreSQL по сравнению с другими. Если вам трудно полностью проговаривать 'PostgreSQL', можно просто говорить 'Postgres'.<br />
<br />
=== Кто управляет PostgreSQL? ===<br />
<br />
Если вы ищите какого-то особенного человека, центральный комитет или управляющую компанию, то напрасно --- их нет. У нас есть ядро комитета и разработчиков, работающих с CVS, но эти группы служат больше для административных целей, чем для управления. Проект напрямую функционирует с помощью сообщества разработчиков и пользователей, к которому может присоединится каждый. Всё что нужно -- это подписаться на списки рассылки и участвовать в дискуссиях. (Подробности о том как включиться в разработку PostgreSQL смотрите в [[Developer FAQ|FAQ для разработчиков]].)<br />
<br />
=== Что представляет из себя Всемирная Группа Разрабочиков PostgreSQL (PGDG)? ===<br />
<br />
"PGDG" -- это интернациональное объединение, без образования юридического лица, отдельных людей и компаний, которые вносят свой вклад в проект PostgreSQL. Команда PostgreSQL Core Team обычно выступает в качестве спикеров для PGDG.<br />
<br />
=== Что представляет из себя PostgreSQL Core Team? ===<br />
<br />
Это комитет, состоящий из 5-7 членов (в настоящий момент 6), которые внесли наибольший вклад в PostgreSQL и которые:<br />
(а) устанавливают даты выпусков, (b) управляют конфиденциальными вопросами проекта, (c) общаются как спикеры с PGDG,<br />
когда это требуется и (d) выступают арбитрами в тех вопросах, по которым в сообществе не достигнуто консенсуса.<br />
В настоящий момент Основная Команда представлена вверху страницы<br />
[http://www.postgresql.org/community/contributors/ списка участников]<br />
<br />
=== Что можно сказать о различных фондах PostgreSQL? ===<br />
<br />
Хотя проект PostgreSQL использует некоммерческие фирмы в США, Европе, Бразилии и Японии для<br />
координации проектом и сбора средств, эти фирмы не являются владельцами кода PostgreSQL.<br />
<br />
=== Какова лицензия на PostgreSQL? ===<br />
<br />
PostgreSQL распространяется по лицензии сходной с BSD и MIT. В своей основе, она<br />
позволяет пользователям делать с кодом всё что угодно, включая перепродажу скомпилированных<br />
файлов без исходного кода. Единственное ограничение состоит в том, что вы можете<br />
возложить на нас юридическую ответственность за проблемы с этим программным обеспечением.<br />
Также существует требование о том, что все копии данного программного обеспечения должны<br />
включать в себя данные сведения об авторских правах. Вот лицензия, которую мы используем:<br />
<br />
Система Управления Базами Данных PostgreSQL<br />
(также известная как Postgres, ранее Postgres95)<br />
<br />
Portions copyright (c) 1996-2011, PostgreSQL Global Development Group<br />
<br />
Portions Copyright (c) 1994 Regents of the University of California<br />
<br />
Предоставляются права на использование, копирование, изменение и распространение данного<br />
программного обеспечения и его документации для любых целей, бесплатно и без подписания<br />
какого-либо соглашения, при условии что для каждой копии будут предоставлены данное выше<br />
замечание об авторских правах, текущий параграф и два следующих параграфа.<br />
<br />
КАЛИФОРНИЙСКИЙ УНИВЕРСИТЕТ НЕ НЕСЕТ НИКАКОЙ ОТВЕТСТВЕННОСТИ ЗА ЛЮБЫЕ ПОВРЕЖДЕНИЯ,<br />
ВКЛЮЧАЯ ПОТЕРЮ ДОХОДА, НАНЕСЕННЫЕ ПРЯМЫМ ИЛИ НЕПРЯМЫМ, СПЕЦИАЛЬНЫМ ИЛИ СЛУЧАЙНЫМ<br />
ИСПОЛЬЗОВАНИЕМ ДАННОГО ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ ИЛИ ЕГО ДОКУМЕНТАЦИИ, ДАЖЕ ЕСЛИ<br />
КАЛИФОРНИЙСКИЙ УНИВЕРСИТЕТ БЫЛ ИЗВЕЩЕН О ВОЗМОЖНОСТИ ТАКИХ ПОВРЕЖДЕНИЙ.<br />
<br />
КАЛИФОРНИЙСКИЙ УНИВЕРСИТЕТ СПЕЦИАЛЬНО ОТКАЗЫВАЗЫВАЕТСЯ ПРЕДОСТАВЛЯТЬ ЛЮБЫЕ ГАРАНТИИ,<br />
ВКЛЮЧАЯ, НО НЕ ОГРАНИЧИВАЯСЬ ТОЛЬКО ЭТИМИ ГАРАНТИЯМИ: НЕЯВНЫЕ ГАРАНТИИ ПРИГОДНОСТИ<br />
ТОВАРА ИЛИ ПРИГОДНОСТИ ДЛЯ ОТДЕЛЬНОЙ ЦЕЛИ. ДАННОЕ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ<br />
НА ОСНОВЕ ПРИЦИПА "КАК ЕСТЬ" И КАЛИФОРНИЙСКИЙ УНИВЕРСИТЕТ НЕ ОБЯЗАН ПРЕДОСТАВЛЯТЬ<br />
СОПРОВОЖДЕНИЕ, ПОДДЕРЖКУ, ОБНОВЛЕНИЯ, РАСШИРЕНИЯ ИЛИ ИЗМЕНЕНИЯ.<br />
<br />
=== На каких платформах работает PostgreSQL? ===<br />
<br />
Обычно, PostgreSQL может работать на любой современной платформе совместимой с Unix.<br />
<br />
Платформы, которые прошли явное тестирование перечислены на сайте <br />
[http://buildfarm.postgresql.org/ Build farm].<br />
Документацию, которая содержит множество подробностей о поддерживаемых платформах можно найти на<br />
http://www.postgresql.org/docs/current/static/supported-platforms.html.<br />
<br />
PostgreSQL также работает на операционных системах Microsoft Windows, основанных на NT,<br />
таких как Win2000 SP4, WinXP и Win2003. Пакет инсталлятора доступен по адресу<br />
http://www.postgresql.org/download/windows. Версии Windows, основанные на MS-DOS (Win95, Win98, WinMe)<br />
могут запускать PostgreSQL с помощью Cygwin.<br />
<br />
=== Где можно взять PostgreSQL? ===<br />
<br />
Дистрибутивы в скомпилированном виде для разных операционных систем и платформ; см.<br />
[http://www.postgresql.org/download страницу скачивания].<br />
<br />
Исходный код можно получить [http://www.postgresql.org/ftp/ через веб-браузер] или [ftp://ftp.postgresql.org/pub/ по ftp].<br />
<br />
=== Какая на данный момент наиболее свежая версия? ===<br />
<br />
Последнюю версию PostgreSQL можно узнать перейдя на главную страницу [http://www.postgresql.org/ нашего сайта].<br />
<br />
Обычно мы выпускаем новые старшие версии каждый год, а младшие версии каждые несколько месяцев.<br />
Младшие версии обычно выпускаются в одно и то же время для всех поддерживаемых старших версий.<br />
Больше информации о старших и младших версиях можно найти на<br />
http://www.postgresql.org/support/versioning.<br />
<br />
=== Где получить поддержку? ===<br />
<br />
Сообщество PostgreSQL предоставляет помощь множеству пользователей через E-mail. Основной web-сайт для подписки на списки рассылки по E-mail это:<br />
http://www.postgresql.org/community/lists/. Хорошим местом для того, чтобы начать задавать вопросы являются списки general (общие вопросы) или bugs (ошибки). Для наилучших результатов, прочитайте [[guide to reporting problems]] перед тем как отправлять сообщение об ошибке, чтобы убедиться, что<br />
вы включили всю необходимую информацию для того, чтобы вам помогли.<br />
<br />
Главным IRC каналом является #postgreql, расположенный на сервере Freenode (irc.freenode.net). На этом же сервере существуют каналы на испанском (#postgresql-es), французском (#postgresqlfr) и бразильском (#postgresql-br) языках. Также существует канал по PostgreSQL на сервере EFNet.<br />
<br />
Список коммерческой поддержки компаний доступен на<br />
http://www.postgresql.org/support/professional_support.<br />
<br />
=== Как мне сообщить об ошибке? ===<br />
<br />
Посетите страничку со специальной формой отчёта об ошибке в PostgreSQL по адресу:<br />
http://www.postgresql.org/support/submitbug, чтобы отправить сообщение об ошибке в<br />
список рассылки pgsql-bugs. Также проверьте наличие более свежей версии PostgreSQL на нашем FTP сайте<br />
ftp://ftp.postgresql.org/pub/.<br />
<br />
Чтобы получить полезный и информативный ответ важно, чтобы вы прочитали<br />
[[guide to reporting problems]], чтобы убедиться, что вы включили в ваше сообщение<br />
всю информацию, которая требуется для полного понимания и работы над вашим сообщением.<br />
<br />
На ошибки, уведомление о которых были сделаны через специальную форму или отправленные в какой-либо список рассылки PostgreSQL, обычно генерируется один из следующих ответов:<br />
* Это не ошибка и почему<br />
* Это известная ошибка и она уже есть в списке TODO<br />
* Данная ошибка была исправлена в текущем выпуске<br />
* Данная ошибка была исправлена, но исправление пока не попало в официальный выпуск<br />
* Запрашивается более детальная информация: <br />
** Операционная система<br />
** Версия PostgreSQL<br />
** Тест, воспроизводящий ошибку<br />
** Отладочная информация<br />
** [[Generating_a_stack_trace_of_a_PostgreSQL_backend|Вывод backtrace отладчика]]<br />
* Это новая ошибка. Может произойти следующее: <br />
** Будет создано исправление, которое будет включено в следующий выпуск<br />
** Ошибка не может быть исправлена немедленно и будет добавлена в список TODO<br />
<br />
=== Как найти информацию об известных ошибках или отсутствующих возможностях? ===<br />
<br />
PostgreSQL поддерживает расширенный подкласс SQL:2008. См. список [[Todo|TODO]]<br />
на предмет известных ошибок, отсутствующих возможностей и будущих планов.<br />
<br />
На запрос какой-либо возможности обычно приходят следующие ответы:<br />
* Данная возможность уже есть в списке TODO<br />
* Данная возможность нежелательна потому что: <br />
** Она дублирует существующую функциональность, которая следует стандарту SQL<br />
** Данная возможность сильно усложнила бы код, но дала бы маленькую выгоду<br />
** Данная возможность небезопасна или ненадёжна<br />
* Данная новая возможность добавлена в список TODO<br />
<br />
PostgreSQL не использует какую-либо систему отслеживания ошибок, потому что мы обнаружили, что использование прямого обращения по электронной почте и обновляемого списка TODO является более эффективным. На практике, ошибки в программном обеспечении сохраняются очень недолго, а ошибки, которые важны большому количеству пользователей исправляются моментально. Есть только одно место, где можно найти все изменения, улучшения и исправления, сделанные в выпуске PostgreSQL - это журналы сообщений системы контроля версий CVS. Даже замечания к выпускам не содержат все изменения, сделанные в программном обеспечении.<br />
<br />
=== Ошибка, с которой я столкнулся исправлена в новой старшей версии PostgreSQL, но я не могу обновляться. Могу ли я получить патч, чтобы решить проблему? ===<br />
<br />
Нет. Никто не будет делать специальный патч для вас, извлекая исправление, например из 8.4.3, чтобы применить его к 8.4.1.<br />
Это потому, что никогда не должно быть необходимости делать это.<br />
<br />
PostgreSQL имеет строгую политику, по которой исправление ошибок осуществляется только в текущих выпусках, согласно<br />
[http://www.postgresql.org/support/versioning политике версий]. Это позволяет безопасно обновляться, например, с 8.4.1 до 8.4.3.<br />
<br />
Поддерживается совместимость на бинарном (двоичном) уровне, не требуется выполнять дамп и восстановление, ничего не будет разрушено, но<br />
ошибки, которые могут вызывать проблемы, исправляются. Даже, если вы никогда не сталкивались с какой-то конкретной ошибкой, это может произойти<br />
в будущем и таким образом имеет смысл оперативно обновляться. Для этого просто нужно установить обновление и перезапустить сервер баз данных, ничего более.<br />
<br />
Обновление с 8.3 до 8.4 или с 8.4 до 9.0 является обновлением старшей версии и не может производиться также. Однако, если ошибка найдена в<br />
9.0, то она обычно исправляется во всех обслуживаемых старых версиях, т.е. в 8.4 и 8.3, если это безопасно и имеет практическую пользу.<br />
<br />
Таким образом, если у вас работает версия 8.1.0, то выполнение обновления до 8.1.21 <b>сильно</b> рекомендуется и является безопасным.<br />
С другой стороны, обновление на следующую старшую версию, т.е. 8.2.x, может потребовать изменений в вашем приложении и потребует выполнения дампа, восстановления и перезагрузки.<br />
<br />
Если вы хотите быть осторожным при любых обновлениях, вам необходимо прочитать<br />
[http://www.postgresql.org/docs/current/static/release.html замечания к выпуску] для каждого выпуска между текущим и последней младшей версией.<br />
Если у вас просто параноидальная боязнь обновлений, вы можете получить исходный код для каждого списка изменений, внесённых в выпуски из<br />
[http://git.postgresql.org/ PostgreSQL's репозитория git] и опробовать его.<br />
<br />
Очень рекомендуется, чтобы вы <b>всегда</b> обновляли последнюю младшую версию. Избегайте попыток извлечь и применить отдельные исправления<br />
из выпусков; делая такое, вы обходите все проверки качества, выполненные командой PostgreSQL при подготовке выпуска и создаёте собственную специальную версию, которую <i>не использует никто кроме вас</i>. Намного безопасней обновиться до последнего, оттестированного, безопасного выпуска.<br />
<i>Применение патчей к вашей собственной, нестандартной сборке потребует также множество времени и усилий и будет требовать того же времени простоя как и при обычном обновлении.</i><br />
<br />
=== У меня есть программа, которая хочет версию PostgreSQL x.y.1. Могу я использовать вместо этого версию PostgreSQL x.y.2? ===<br />
<br />
Любая программа, которая работает с конкретной версией, такой как 8.4.1, должна работать с любыми другими младшими версиям той же старшей версии. Это<br />
означает, что если программа хочет версию 8.4.1, то она может и должна работать вместо этого с последней версией из выпусков 8.4.<br />
<br />
Подробности смотрите в предыдущем вопросе.<br />
<br />
=== Какая документация имеется в наличии? ===<br />
<br />
PostgreSQL содержит много документации, включая большое руководство, страницы электронного руководства man и некоторые маленькие тестовые примеры. Смотрите в каталог /doc. Вы также можете просматривать документацию в Интернет по адресу http://www.postgresql.org/docs.<br />
<br />
Есть несколько книг о PostgreSQL, которые вы можете купить, две из них также доступны в интернет. Список книг можно найти по адресу<br />
http://www.postgresql.org/docs/books/. Одна из наиболее популярных - это книга Korry & Susan Douglas.<br />
<br />
Коллекцию технических статей по PostgreSQL вы можете найти в<br />
[[Community_Generated_Articles%2C_Guides%2C_and_Documentation | wiki]].<br />
<br />
Клиент командной строки psql имеет несколько команд \d для отображения информации по типам, операторам, функциям, агрегатам и т.д. - используйте \? для получения списка доступных команд.<br />
<br />
=== Как мне научиться SQL? ===<br />
<br />
Во-первых, возьмите одну из книг по PostgreSQL, о которых говорилось выше. Многим из наших пользователей также нравится книга The Practical SQL Handbook, Bowman, Judith S., et al., Addison-Wesley. Другим нравится The Complete Reference SQL, Groff et al., McGraw-Hill.<br />
<br />
Многие люди рассматривают документацию по PostgreSQL как прекрасное руководство для обучения самому SQL, а также его реализации для PostgreSQL.<br />
Для достижения лучших результатов, используйте PostgreSQL вместе с другой полнофункциональной SQL СУБД, которую вы знаете, таким образом вы научитесь использовать SQL без специфичных для PostgreSQL особенностей. Документация по PostgreSQL обычно рассказывает, когда та или иная возможность PostgreSQL расширяет стандарт.<br />
<br />
Существует также множество прекрасных учебников доступных в online: <br />
* http://www.intermedia.net/support/sql/sqltut.shtm<br />
* http://sqlcourse.com<br />
* http://www.w3schools.com/sql/default.asp<br />
* http://mysite.verizon.net/Graeme_Birchall/id1.html<br />
* http://sqlzoo.net<br />
<br />
=== Как мне прислать исправление или присоединится к команде разработчиков? ===<br />
<br />
См. [[Developer FAQ|FAQ для разработчиков]].<br />
<br />
=== Как сравнить PostgreSQL с другими СУБД? ===<br />
<br />
Существует несколько методов сравнения программного обеспечения: возможности, производительность, надежность, поддержка и цена.<br />
<br />
==== Возможности ====<br />
<br />
PostgreSQL имеет большинство возможностей представленных в больших коммерческих СУБД, такие как: транзакции, подзапросы, триггеры, представления, внешние ключи, ограничения целостности и разные блокировки. У нас есть некоторые возможности, которых нет у них: типы, определяемые пользователем, механизм наследования, правила и конкуретное многоверсионное управление для работы с содержимым блокировок.<br />
<br />
==== Производительность ====<br />
<br />
Производительность PostgreSQL сходна с другими коммерческими СУБД и с СУБД с открытым исходным кодом. В каких-то вещах мы быстрее, в каких-то медленнее. Наша производительности обычно +/-10% по сравнению с другими СУБД. <br />
<br />
==== Надёжность ====<br />
<br />
Мы понимали, что наша СУБД должна быть надежной или она ничего не будет стоить. Мы стараемся выпускать хорошо проверенный, стабильный код, который содержит минимум ошибок. Каждый выпуск проходит стадию бета-тестирования и наша история выпусков показывает что мы можем предоставлять стабильные, монолитные выпуски, которые готовы к продуктивному использованию. Мы верим, что мы производим проверку не хуже, чем у других СУБД в данной области.<br />
<br />
==== Поддержка ====<br />
<br />
Наши списки рассылки предоставляют возможность общения с большой группой разработчиков и пользователей, которые могут помочь решить любые возникшие проблемы. В то же время, мы не гарантируем какие-либо исправления, но и разработчики коммерческих СУБД не всегда делают исправления. Прямой доступ к разработчикам, сообществу пользователей, руководствам и исходным текстам часто делают поддержку PostgreSQL превосходящей другие СУБД. Существует коммерческая поддержка по результам возникших инцидентов, которая доступна для тех кому она нужна. <br />
(См. [[#Where_can_I_get_support.3F | вопрос 3.10]]).<br />
<br />
==== Цена ====<br />
<br />
Наш продукт бесплатен как для коммерческого так, и не для коммерческого использования. Вы можете добавлять свой код в наш продукт без ограничений, за исключением тех, что описываются в нашей лицензии стиля BSD, которая приведена выше.<br />
<br />
=== Может ли PostgreSQL быть встраиваемой СУБД? ===<br />
<br />
PostgreSQL разрабатывается по архитектуре клиент/сервер, которая требует отдельных процессов для каждого клиента и сервера, а также несколько вспомогательных процессов. Многие встраиваемые архитектуры могут соответствовать таким требованиям. Однако, если ваша встраиваемая архитектура требует сервер баз данных для запуска внутри прикладного процесса, вы не можете использовать Postgres и вам лучше бы выбрать для базы данных какое-либо другое облегченное решение.<br />
<br />
Популярные встраиваемые решения включают [http://sqlite.org SQLite] и [http://firebirdsql.org Firebird SQL].<br />
<br />
=== Как мне отписаться от списков рассылки PostgreSQL? Как избежать получения дублирующихся сообщений? ===<br />
<br />
Страница PostgreSQL Majordomo позволяет подписаться или отписаться от любых<br />
списков рассылки. (Вам может понадобится ваш пароль для Majordomo, для авторизации).<br />
<br />
Все списки рассылки PostgreSQL настраиваются как группа, отвечающая в список и первоначальному<br />
автору E-mail сообщения. Это сделано для того, чтобы пользователи получали ответы как можно быстрее.<br />
Если вы предпочитаете не получать дублирующихся сообщений из списка в случае если вы уже получили<br />
E-mail сообщение напрямую, установите флажок eliminatecc на странице настроек Majordomo. Вы можете<br />
также предотвратить получение копий вашего же сообщения в список самому себе, сняв флажок selfcopy.<br />
<br />
== Вопросы пользователей по клиентской части ==<br />
<br />
=== Какие интерфейсы есть для PostgreSQL? ===<br />
<br />
Установка PostgreSQL включает только C и встроенный (embedded) C интерфейсы. Все другие интерфейсы являются независимыми проектами и загружаются отдельно; самостоятельность проектов позволяет им организовать собственное расписание выпусков новых версий и иметь собственную команду разработчиков.<br />
<br />
Некоторые языки программирования, такие как PHP включают в себя интерфейс к PostgreSQL. Интерфейсы для таких языков как Perl, TCL, Python и многих других, доступны на http://pgfoundry.org.<br />
<br />
=== Какие инструменты существуют для использования PostgreSQL через Web? ===<br />
<br />
Прекрасное введение во взаимодействие баз данных и Web можно найти на:<br />
http://www.webreview.com<br />
<br />
Для интеграции с Web, PHP (http://www.php.net) является неплохим интерфейсом.<br />
<br />
В сложных случаях, многие пользуются Perl и DBD::Pg с CGI.pm или mod_perl.<br />
<br />
=== Есть ли у PostgreSQL графический интерфейс пользователя? ===<br />
<br />
Для PostgreSQL существует большое количество инструментов с графическим интерфейсом как коммерческих, так и открытых. Подробности можно найти в<br />
[[Community Guide to PostgreSQL GUI Tools]].<br />
<br />
== Вопросы администрирования ==<br />
<br />
=== Как мне установить PostgreSQL в место отличное от /usr/local/pgsql? ===<br />
<br />
Задайте опцию --prefix когда запускаете configure.<br />
<br />
=== Я установил PostgreSQL и не знаю пароль пользователя postgres ===<br />
<br />
Дэйв Пейдж написал [http://pgsnake.blogspot.com/2010/07/postgresql-passwords-and-installers.html blog post] рассказывающий какие разные типы паролей используются при работе с PostgreSQL и как решить некоторые проблемы, такие как сброс этих паролей.<br />
<br />
=== Как мне управлять соединениями от других компьютеров? ===<br />
<br />
По умолчанию, PostgreSQL разрешает только соединения на локальной машине через сокеты домена Unix или TCP/IP соединения. Для того, чтобы другие машины смогли подключиться к базе вы должны изменить listen_addresses в postgresql.conf, разрешить host-авторизация в файле $PGDATA/pg_hba.conf и перезапустить сервер СУБД.<br />
<br />
=== Как мне настроить СУБД для получения лучшей производительности? ===<br />
<br />
Существует три главных области, которые потенциально могут увеличить производительность:<br />
<br />
==== Изменение запроса ====<br />
Это означает модификацию запросов для получения лучшей производительности:<br />
<br />
* Создание индексов, включая индексных выражений и частичные индексы<br />
* Использование COPY вместо множества INSERT<br />
* Группировка нескольких операторов в единую транзакцию для уменьшения нагрузки при выполнении завершения транзакции<br />
* Использование CLUSTER, когда из индекса берётся множество строк<br />
* Использование LIMIT для того, чтобы возвращалась только часть вывода от запроса<br />
* Использование Подготовленных (Prepared) запросов<br />
* Использование ANALYZE для обслуживания статистики оптимизатора<br />
* Регулярное использование VACUUM или pg_autovacuum<br />
* Удаление индексов во время больших изменений данных<br />
<br />
==== Настройка сервера ====<br />
Некоторые установки в postgresql.conf влияют на производительность. Подробный полный список установок см. в <br />
Administration Guide/Server Run-time Environment/Run-time Configuration.<br />
<br />
==== Выбор "железа" - аппаратного обеспечения ====<br />
Влияние "железа" на производительность подробно описано в<br />
http://www.powerpostgresql.com/PerfList/ и<br />
http://momjian.us/main/writings/pgsql/hw_performance/index.html.<br />
<br />
=== Какие возможности для отладки есть в наличии? ===<br />
<br />
Есть множество установок в настройках сервера, начинающихся на log_* на<br />
http://www.postgresql.org/docs/current/interactive/runtime-config-logging.html, позволяющих протоколировать запросы и статистику работы процесса, которая очень полезна для отладки и измерения производительности.<br />
<br />
=== Почему я получаю сообщение "Sorry, too many clients" когда пытаюсь подключиться к базе? ===<br />
<br />
Вы достигли установленного по умолчанию ограничения в 100 сессий подключения к базе данных. Вам необходимо увеличить лимит на количество конкурентных backend процессов для вашего сервера БД, изменив значение max_connections в файле postgresql.conf и перестартовать сервер БД.<br />
<br />
=== Как выполнить обновление PostgreSQL? ===<br />
<br />
См. общее описание об обновлениях в http://www.postgresql.org/support/versioning и<br />
http://www.postgresql.org/docs/current/static/install-upgrading.html<br />
для специфичных инструкций.<br />
<br />
=== Будет ли PostgreSQL работать с последними изменениями, в разных страных, касающимися дневного времени? ===<br />
<br />
PostgreSQL начиная с версии 8.0 зависит от базы данных часовых поясов tzdata (которая также называется базой данных zoneinfo<br />
[http://www.twinsun.com/tz/tz-link.htm Olson timezone database]) в том что касается информации о зимнем/летнем времени. Чтобы PostgreSQL работала с летним/зимнем временем, установите набор файлов tzdata и перезапустите сервер.<br />
<br />
Все обновления выпусков PostgreSQL, включая последние доступные файлы tzdata, также обновляются в младших версиях для каждой старшей версии, чего обычно вполне достаточно.<br />
<br />
На платформах, где производятся регулярные обновления программного обеспечения, включая файлы tzdata, возможно более правильным будет использование системных файлов tzdata. Это возможно, с помощью указания соответствующей опции при компиляции. Большинство дистрибутивов Linux устанавливают эту опцию для сборки своих пакетов PostgreSQL.<br />
<br />
Выпуски PostgreSQL до 8.0 всегда использовали информацию о часовых поясах, получаемую из операционной системы.<br />
<br />
=== Какое компьютерное "железо" я должен использовать? ===<br />
<br />
Поскольку "железо" персональных компьютеров является наиболее совместимым, люди склонны верить, что такое "железо" имеет одинаковое качество. Это не так. Память ECC, SCSI и качественные материнские платы являются более надёжными и имеют более лучшую производительность, чем менее дорогое "железо". PostgreSQL будет работать на любом "железе", но если для вас важны надёжность и производительность, то с вашей стороны будет мудро поставить соответствующее "железо".<br />
<br />
Серверы баз данных, в отличие от многих других приложений обычно упираются в производительность подсистемы ввода/вывода и память, так что вам нужно в первую очередь уделить внимание подсистеме ввода/вывода, а затем ёмкости памяти и наконец производительности процессора. Например, дисковый контроллер с кэшем, который работает на резервной батарейке часто наиболее лёгкий и правильный способ увеличить производительность сервера базы данных. Обсудить разное "железо" можно в наших списках рассылки.<br />
<br />
=== Как PostgreSQL использует ресурсы процессора? ===<br />
<br />
Сервер PostgreSQL основан на процессах (не тредах(нитях)) и использует один процесс операционной системы на одну сессию с базой данных. Одиночная сессия с базой данных (соединение) не может использовать более чем один процессор. Разумеется, несколько соединений автоматически распределяются по всем доступным процессорам, которые доступны операционной системе. Клиентские приложения могут легко использовать треды(нити) и создавать несколько соединений к базе данных из каждого треда.<br />
<br />
Один сложный и независящий от процессора запрос не может использовать более чем один процессор при обработке данного запроса. Система может оставаться доступной для использования других процессоров, дискового ввода/вывода и т.д. но вы не увидите значительного преимущества при использовании более чем одного ядра.<br />
<br />
=== Почему у PostgreSQL так много процессов, даже когда СУБД простаивает? ===<br />
<br />
Как отмечено в [[#Как PostgreSQL использует ресурсы процессора?|ответе выше]], PostgreSQL основан на процессах, так что он запускает один процесс<br />
<code>postgres</code> (или <code>postgres.exe</code> на Windows) на соединение. Процесс postmaster (который принимате соединения и запускает новые процессы postgres для них) запущен всегда. В дополнение, PostgreSQL обычно имеет один или более "вспомогательных" процессов, таких как сборщики статистики, фоновой записи, демон автовакуума, walsender, и т.д., и все из них показываются как экзепляры "postgres" в большинстве инструментов системного мониторинга.<br />
<br />
Не смотря на их количество, эти процессы фактически используют очень мало реальных ресурсов. См [[#Почему PostgreSQL использует так много памяти?|следующий вопрос]].<br />
<br />
=== Почему PostgreSQL использует так много памяти? ===<br />
<br />
Несмотря на видимость это абсолютно нормально и на самом деле PostgreSQL используется не так много памяти как показывают инструменты типа <code>top</code> или монитора процессов в Windows.<br />
<br />
Такие инструменты как <code>top</code> и монитор процессов Windows могут показывать множество экземпляров <code>postgres</code> (см. выше), каждый из которых использует огромное количество памяти. Часто, если просуммировать всю эту память, окажется что её больше, чем фактически установлено всего памяти на компьютере!<br />
<br />
Это следствие того как данные инструменты говорят об использовании памяти. Они обычно не понимают, что используется разделяемая память и показывают её так как будто она используется отдельно и полностью каждым экземпляром процесса. PostgreSQL использует большой кусок разделяемой памяти для взаимодействия между процессами и данными кэша. Поскольку эти инструменты считают, что разделяемая память занята каждым экземпляром процесса <code>postgres</code> вместо того чтобы считать, что память используется <i>всеми</i> экземплярами <code>postgres</code>, то и происходит неправильная оценка как много памяти использует PostgreSQL.<br />
<br />
== Вопросы эксплуатации ==<br />
<br />
=== Как выполнить SELECT только для нескольких первых строчек запроса? Произвольной строки? ===<br />
<br />
Для получения только нескольких строк, если вы знаете их количество на момент выполнения SELECT используйте LIMIT. Если есть какой-либо индекс, который совпадает с ORDER BY, то возможно, что весь запрос выполнен и не будет. Если вы не знаете количества необходимых строк на момент выполнения SELECT, используйте курсор и FETCH. <br />
<br />
Для выбора случайной строки с помощью SELECT используйте:<br />
SELECT col<br />
FROM tab<br />
ORDER BY random()<br />
LIMIT 1;<br />
<br />
Подробности на эту тему см. также в [http://blog.rhodiumtoad.org.uk/2009/03/08/selecting-random-rows-from-a-table/ blog entry by Andrew Gierth].<br />
<br />
=== Как мне найти какие таблицы, индексы, базы данных и пользователи существуют? Как мне увидеть запросы, которые использует psql для получения этой информации? ===<br />
<br />
Чтобы просматривать таблицы в psql, используйте команду \dt. Полный список команд в psql вы можете получить, используя \?. Кроме того, вы можете посмотреть исходный код psql в файле pgsql/src/bin/psql/describe.c. Он содержит команды SQL которые генерируются при вводе в psql команд, начинающихся с обратной косой черты. Вы также можете запустить psql с опцией -E так, чтобы эта программа выдавала запросы, которые она использует для выполнения заданных вами команд. PostgreSQL также предоставляет SQL совместимый с INFORMATION SCHEMA интерфейс, с помощью которого, вы можете сформировать запрос на получение информации о базе данных.<br />
<br />
Также существуют системные таблицы, начинающиеся с pg_, в которых есть эта же информация.<br />
<br />
Используйте psql -l для получения списка всех баз данных.<br />
<br />
Также посмотрите файл pgsql/src/tutorial/syscat.source. Он показывает многие из операторов SELECT необходимых для получения информации из системных таблиц базы данных.<br />
<br />
=== Как изменить тип данных колонки? ===<br />
<br />
В 8.0 и более поздних версиях, изменение типа колонки выполняется очень легко через ALTER TABLE ALTER COLUMN TYPE.<br />
<br />
В более ранних версиях сделайте так:<br />
BEGIN;<br />
ALTER TABLE tab ADD COLUMN new_col new_data_type;<br />
UPDATE tab SET new_col = CAST(old_col AS new_data_type);<br />
ALTER TABLE tab DROP COLUMN old_col;<br />
COMMIT;<br />
<br />
Чтобы освободить дисковое пространство, использованное устаревшими строками, вы можете затем захотеть воспользоваться командой<br />
VACUUM FULL.<br />
<br />
=== Каковы максимальные размеры для строк в таблице, таблиц и базы данных? ===<br />
<br />
Существуют следующие ограничения:<br />
<br />
Максимальный размер базы? неограничен (существуют базы на 32 TB)<br />
Максимальный размер таблицы? 32 TB<br />
Максимальный размер строки? 400 Gb<br />
Максимальный размер поля? 1 GB<br />
Максимальное количество строк в таблице? неограничено<br />
Максимальное количество колонок в таблице? 250-1600 в зависимости от типа<br />
Максимальное количество индексов в таблице? неограничено<br />
<br />
Разумеется, понятие "неограничено" на самом деле ограничивается доступным дисковым пространиством и размерами памяти/своппинга. Когда значения перечисленные выше неоправдано большие, может пострадать производительность.<br />
<br />
Максимальный размер таблицы в 32 TB не требует чтобы операционная система поддерживала файлы больших размеров. Большие таблицы хранятся как множество файлов размером в 1 GB, так что ограничения, которые накладывает файловая система не важны.<br />
<br />
Максимальный размер таблицы и максимальное количество колонок могут быть увеличены в четыре раза, если размер блока по умолчанию будет увеличен до 32k.<br />
Максимальный размер таблицы также может быть увеличен при использовании разбиения таблиц.<br />
<br />
Существует ограничение, по которому индексы не могут создаваться для колонок длиннее чем 2,000 символов. К счастью такие индексы вряд ли действительно кому-то нужны. Уникальность гарантируется наилучим образом, с помощью функционального индекса из хэша MD5 длинной колонки, а полнотекстовое индексирование позволяет искать слова внутри колонки.<br />
<br />
=== Как много дискового пространства в базе данных нужно для сохранения данных из обычного текстового файла? ===<br />
<br />
СУБД PostgreSQL может потребоваться дискового пространства до 5 раз больше для сохранения данных из простого текстового файла.<br />
<br />
В качестве примера, рассмотрим файл в 100,000 строк в каждой, из которых целое число и текстовое описание. При этом длина текста, в среднем, составляет 20 байт. Размер простого файла составит 2.8 MB. Размер базы PostgreSQL, содержащей эти же данные составит приблизительно 5.2 MB из которых:<br />
<br />
24 байт: на каждый заголовок строки в таблице (приблизительно)<br />
+ 24 байта: одно поле с целочисленным типом и одно текстовое поле<br />
+ 4 байта: указатель на странице для всей табличной строки<br />
----------------------------------------<br />
56 байт на строку в таблице<br />
<br />
Размер страницы данных в PostgreSQL составляет 8192 байт (8 KB), так что:<br />
<br />
8192 байт на страницу<br />
--------------------- = 158 строк в таблице на страницу БД (округлённо)<br />
52 байт на строку в таблице<br />
<br />
100000 строк данных<br />
----------------------- = 633 страниц в БД (округлённо)<br />
158 строк в таблице на страницу<br />
<br />
633 страниц БД * 8192 байт на страницу = 5,185,536 байт (5.2 MB)<br />
<br />
Индексы не требуют так много, но поскольку они создаются для большого количества данных, они также могут быть велики.<br />
<br />
Значения NULL хранятся как битовые карты и поэтому они занимают очень мало места.<br />
<br />
Обратите внимание, что значения типа long могут быть прозрачно сжаты.<br />
<br />
См. также данную презентацию: [[Image:How_Long_Is_a_String.pdf]].<br />
<br />
=== Почему мои запросы работают медлено? Почему они не используют мои индексы? ===<br />
<br />
Индексы не используются для каждого запроса. Они используются только если таблица больше минимального размера и запрос выбирает только маленький процент строк в таблице. Так устроено, потому что доступ к диску с применением рандомизации при сканировании индексов может быть медленнее, чем простое чтение таблицы или ее последовательное сканирование.<br />
<br />
Чтобы определить необходимость использования индекса для какой-либо таблицы, PostgreSQL должен иметь статистику по этой таблице. Эта статистика собирается при использовании VACUUM ANALYZE или просто ANALYZE. Используя статистику, оптимизатор узнает о том как много строк в таблице и если он должен использовать индексы, то он может принимать лучшие решения. Статистика также влияет на определение оптимального порядка соединений таблиц и метода соединения. При изменении содержимого таблицы должен периодически выполнятся сбор статистики.<br />
<br />
Обычно индексы не используются для ORDER BY или для выполнения соединений таблиц. Последовательный перебор следующий за явной сортировкой обычно быстрее, чем поиск по индексам в большой таблице. Однако, ORDER BY часто комбинируется с LIMIT и в этом случае индекс будет использоваться, поскольку при выполнении будет возвращаться небольшая часть таблицы.<br />
<br />
Если вам кажется, что оптимизатор некорректно выбирает последовательный перебор, используйте SET enable_seqscan TO 'off' и запустите запрос снова, чтобы увидеть, действительно ли сканирование индексов быстрее. <br />
<br />
Когда используются операции с шаблонами, например LIKE или ~, индексы могут быть использованы в следующих случаях:<br />
<br />
* Начало строки поиска должно совпадать с началом искомой строки, т.е.: <br />
** LIKE шаблоны не должны начинаться с % или _.<br />
** ~ шаблоны регулярных выражений должна начинаться на ^.<br />
<br />
* Строка поиска не должна начинаться с символа класса, т.е. [a-e].<br />
<br />
* Поиск независимый от регистра, такой как ILIKE и ~* не использует индексы. Вместо него, используйте индексы выражений, которые описываются в<br />
[[#Как мне выполнить поиск регулярного выражения и поиск независимый от регистра букв поиск регулярного выражения? Как мне использовать индекс для поиска независимого от регистра букв?| вопросе 6.9]].<br />
<br />
* Во время initdb должна использоваться локаль по умолчанию C, потому что не существует возможности узнать следующий наибольший символ для не-C локали. Вы можете для таких случаев создать специальный индекс text_pattern_ops который работает только для LIKE индексирования. Для поиска слов также можно использовать полнотекстовый индекс.<br />
<br />
Также возможно использовать полнотекстовое индексирование для поиска слов.<br />
<br />
Статья [[SlowQueryQuestions]] содержит несколько больше советов и примеров.<br />
<br />
=== Как посмотреть на то, как оптимизатор выполняет мой запрос? ===<br />
<br />
Это выполняется с помощью команды EXPLAIN. См. страницу посвященную [[Using EXPLAIN]].<br />
<br />
=== Как мне изменить порядок сортировки текстовых данных? ===<br />
<br />
PostgreSQL сортирует текстовые данные в соответствии с порядком, которые определяется текущей локалью, которая была выбрана<br />
при initdb. (В версиях, начиная с 8.4, возможно выбрать другую локаль при создании новой базы данных.) Если вам не нравится<br />
порядок сортировки, вам необходимо использовать другую локаль. В частности, большинство локалей, отличных от "C" сортируют<br />
по алфавиту, что игнорирует пунктуацию и пробелы. Если это не то, что вы хотите, то вам нужна локаль "C".<br />
<br />
=== Как мне выполнить поиск регулярного выражения и поиск независимый от регистра букв поиск регулярного выражения? Как мне использовать индекс для поиска независимого от регистра букв? ===<br />
<br />
Оператор ~ производит поиск регулярного выражения, а оператор ~* производит независимый от регистра букв поиск регулярного выражения. Независимый от регистра вариант LIKE называется ILIKE.<br />
<br />
Независимое от регистра сравнение обычно выражается так:<br />
<br />
SELECT *<br />
FROM tab<br />
WHERE lower(col) = 'abc';<br />
<br />
Эта конструкция не будет использовать стандартный индекс на "col". Однако, если вы создадите индекс выражения "lower(col)", он будет использован:<br />
<br />
CREATE INDEX tabindex ON tab (lower(col));<br />
<br />
Если вышеуказанный индекс создаётся как UNIQUE, то колонка, для которой он создаётся может хранить символы и в верхнем, и в нижнем регистре, индес не может иметь идентичных значений, которые отличаются только регистром. Чтобы в колонке можно было хранить символы только в определённом регистре, используйте ограничение CHECK или проверку через триггер.<br />
<br />
В PostgreSQL, начиная с версии 8.4, вы также можете использовать дополнительный<br />
[http://www.postgresql.org/docs/8.4/static/citext.html тип данных CITEXT], который внутри реализует вызовы "lower()", так что вы можете фактически считать его полностью регистро-независимым типом данных. CITEXT также [https://svn.kineticode.com/citext/trunk/ доступен для 8.3], его более ранняя версия работала только с ASCII символами и для 8.2 и более ранних версий доступна на [http://pgfoundry.org/projects/citext/ pgFoundry].<br />
<br />
=== Как мне определить, что значение поля в каком-либо запросе равно NULL? Как мне соединить возможные NULL? Могу я сортировать поля NULL или нет? ===<br />
<br />
Вы просто сравниваете значение с IS NULL и IS NOT NULL, как здесь:<br />
SELECT *<br />
FROM tab<br />
WHERE col IS NULL;<br />
<br />
Конкатенация NULL с чем-либо другим даёт другой NULL.<br />
Если это не то, что бы вам хотелось, используйте COALESCE() для замены NULL как здесь:<br />
<nowiki>SELECT COALESCE(col1, '') || COALESCE(col2, '')</nowiki><br />
FROM tab;<br />
<br />
Чтобы отсортировать данные по значению используйте модификаторы IS NULL и IS NOT NULL в выражении ORDER BY. Когда они будут генерировать значения истина, то при сортировке они будут выше, чем значения ложь, так что записи с NULL будут в отсортированном списке сверху:<br />
SELECT *<br />
FROM tab<br />
ORDER BY (col IS NOT NULL), col;<br />
<br />
В PostgreSQL, начиная с версии 8.3, вы также можете управлять порядком сортировки значений NULL, используя недавно стандартизированные модификаторы<br />
NULLS FIRST/NULLS LAST, как здесь:<br />
SELECT *<br />
FROM tab<br />
ORDER BY col NULLS FIRST;<br />
<br />
=== Каковы отличия между разными символьными типами? ===<br />
<br />
{| border="1"<br />
!Тип<br />
!Внутреннее имя<br />
!Замечания<br />
|-<br />
|VARCHAR(n) <br />
|varchar<br />
|размер задает максимальную длину, нет заполнения<br />
|- <br />
|CHAR(n)<br />
|bpchar<br />
|заполняется пустотой до фиксированной длины<br />
|-<br />
|TEXT<br />
|text<br />
|нет задаваемого верхнего ограничения или длины<br />
|-<br />
|BYTEA<br />
|bytea<br />
|массив байт переменной длины (можно использовать null-байт без опаски)<br />
|-<br />
|"char" (with the quotes)<br />
|char<br />
|один символ<br />
|}<br />
<br />
Внутреннее имя вы можете увидеть, когда смотрите системные каталоги и в некоторых сообщениях об ошибках.<br />
<br />
Первые четыре типа являются "varlena" типами (т.е., первые четыре байта на диске являются длинной, за которой следуют данные). Таким образом, фактически используемое пространство больше, чем обозначенный размер. Однако, длинные значения также сжимаются, так что занимаемое дисковое пространство может также быть и меньше, чем ожидалось.<br />
<br />
VARCHAR(n) - это лучшее решение, когда нужно хранить строки переменной длины, не превышающие определенного размера.<br />
<br />
TEXT - это лучшее решение для строк неограниченной длины, с максимально допустимой длиной в 1 гигабайт. <br />
<br />
CHAR(n) - это лучшее решение для хранения строк, которые обычно имеют одинаковую длину. CHAR(n) заполняется пустотой до заданной длины, в то время как VARCHAR(n) хранит только символы, из которых состоит строка. BYTEA используется для хранения бинарных данных, значения которых могут включать NULL байты. Все типы описанные здесь, имеют сходные характеристики производительности, за исключением того, что заполнение пробелами в CHAR(n) требует дополнительное пространство для их хранения и некоторое дополнительное время.<br />
<br />
Тип "char" (кавычки требуются, чтобы отличать его от CHAR(n)) является специализированным типом данных, который может хранить точно один байт. Он есть в системных каталогах, но его использование в таблицах пользователей обычно не рекомендуется.<br />
<br />
=== Как мне создать серийное поле/поле с авто увеличением? ===<br />
<br />
PostgreSQL поддерживает тип данных SERIAL. Фактически он не является реальным типом данных. При его использовании создаётся колонка целого типа и завязанную на эту колонку последовательность.<br />
<br />
Например:<br />
CREATE TABLE person (<br />
id SERIAL,<br />
name TEXT<br />
);<br />
автоматически транслируется в: <br />
CREATE SEQUENCE person_id_seq;<br />
CREATE TABLE person (<br />
id INTEGER NOT NULL DEFAULT nextval('person_id_seq'),<br />
name TEXT<br />
);<br />
<br />
Автоматически созданная последовательность имеет имя вида ''таблица''_''колонка_serial''_seq, где ''таблица'' и ''колонка_serial'' - это соответственно имена таблицы и колонки с типом SERIAL. Смотрите подробности о последовательностях на странице руководства посвященной CREATE SEQUENCE.<br />
<br />
Также существует тип BIGSERIAL, который похож на SERIAL, за исключением того, что колонка создаётся с типом BIGINT, а не INTEGER. Используйте этот тип, если вы считаете, что вам будет нужно более чем 2 миллиарда серийных значений в таблице.<br />
<br />
=== Как мне получить значение при вставке SERIAL? ===<br />
<br />
Простейший способ получить назначенное значение SERIAL это использовать RETURNING.<br />
Используя в качестве примера таблицу из прошлого вопроса, это будет выглядеть так:<br />
INSERT INTO person (name) VALUES ('Blaise Pascal') RETURNING id;<br />
<br />
Вы также можете вызвать функцию nextval() и использовать полученное значение в INSERT, или вызвать<br />
функцию currval() после INSERT.<br />
<br />
=== Не может ли получиться так, что использование currval() и nextval() приведет к зациклированию с другими пользователями? ===<br />
<br />
Нет. currval() возвращает текущее значение, назначенное вашей сессией, а не другими сессиями.<br />
<br />
=== Почему числа из моей последовательности не используются снова при отмене транзакции? Почему создаются разрывы при нумерации в колонке, где я использую последовательность/SERIAL? ===<br />
<br />
Для реализации конкуретности, значения последовательностей, при необходимости выдаются во время запуска транзакций и не блокируются до полного выполнения транзакций. Это может вызывать разрывы в нумерации при отмене транзакций.<br />
<br />
=== Что такое OID? ===<br />
<br />
Если таблица создана с WITH OIDS, то каждая строка получает уникальный индентификатор OID. OID - это автоматически назначаемое уникальное 4-х байтовое целое число, которое уникально для всей установленной СУБД. Однако, после того как его значение превысит 4 миллиарда, значения OID начинают дублироваться. PostgreSQL использует OID для связывания своих внутренних таблиц.<br />
<br />
Для уникального значения в строках таблицы пользователя, лучшим способом является создание уникального индекса на колонку OID (но обратите внимание, что выражение WITH OIDS само по себе не создаёт такой индекс).<br />
<br />
Система проверяет индекс, чтобы увидеть не существует уже сгенерированный новый OID и если это так, генерирует новый OID и повторяет проверку. Это работает хорошо, пока таблица не содержащая OID имеет только маленькую часть от возможных 4-х миллиардов строк.<br />
<br />
PostgreSQL использует OID для идентификаторов объектов в системных каталогах, где вышеописанное ограничение размера не может создавать проблему.<br />
<br />
Для уникальной нумерации строк в таблицах пользователей, наилучшим решением будет использование типа SERIAL, вместо колонки OID или BIGSERIAL, если ожидается, что таблица будет иметь более 2-х миллиардов записей.<br />
<br />
=== Что такое CTID? ===<br />
<br />
CTID используется для идентификации специальных физических записей с блочными значениеями и значениями смещений внутри таблицы.<br />
Они используются записями индекса, чтобы указать на физические строки в таблице. Логические CTID изменяется после того как<br />
строки в таблице были изменены, так что CTID нельзя использовать как долговременный идентификатор строки таблицы. Но иногда<br />
использование CTID является удобным для идентификации строки внутри транзакции, когда не ожидается каких-либо обновлений.<br />
<br />
=== Почему я получаю ошибку "ERROR: Memory exhausted in AllocSetAlloc()"? ===<br />
<br />
Предположительно у вас закончилась виртуальная память или что ваше ядро имеет маленький лимит на определенные ресурсы. Попытайтесь перед запуском сервера БД выполнить следующие команды:<br />
ulimit -d 262144<br />
limit datasize 256m<br />
<br />
В зависимости от командного интерпретатора shell, только одна из данных команд выполнится успешно, но она позволит вам установить больший сегмент данных процесса и возможно решит проблему. Эта команда изменяет параметры текущего процесса и всех его потомков, созданных после её запуска. Если у вас возникла проблема с SQL клиентом, потому что backend возвращает слишком большой объем данных, попытайтесь выполнить эту команду перед запуском клиента. <br />
<br />
=== Как мне узнать, какая версия PostgreSQL запущена? ===<br />
<br />
Из psql, наберите SELECT version();<br />
<br />
=== Существует ли какой-либо способ аудита операций с базой данных? ===<br />
<br />
Ничего встроенного нет, но не так уж и трудно сделать такую возможность для себя.<br />
<br />
Простой пример из официальной документации:<br />
http://www.postgresql.org/docs/8.3/static/plpgsql-trigger.html#PLPGSQL-TRIGGER-AUDIT-EXAMPLE<br />
<br />
Проект, нацеленный на такую возможность: http://pgfoundry.org/projects/tablelog/<br />
<br />
Другая информация и примеры реализаций: <br />
http://it.toolbox.com/blogs/database-soup/simple-data-auditing-19014<br />
http://www.go4expert.com/forums/showthread.php?t=7252<br />
http://www.alberton.info/postgresql_table_audit.html<br />
<br />
=== Как мне создать колонку которая по умолчанию будет содержать текущее время? ===<br />
<br />
Используйте CURRENT_TIMESTAMP:<br />
CREATE TABLE test (x int, modtime TIMESTAMP DEFAULT CURRENT_TIMESTAMP );<br />
<br />
=== Как мне выполнить внешнее соединение таблиц? ===<br />
<br />
PostgreSQL поддерживает внешние соединения, используя стандартный синтаксис SQL. Вот два примера:<br />
<br />
SELECT *<br />
FROM t1 LEFT OUTER JOIN t2 ON (t1.col = t2.col);<br />
<br />
или<br />
SELECT *<br />
FROM t1 LEFT OUTER JOIN t2 USING (col);<br />
<br />
Это идентичные запросы соединения t1.col и t2.col, также возвращают любые несоединённые строки из t1 (которые не совпадают с t2). RIGHT соединение должно добавить несоединённые строки из t2. FULL соединение должно возвратить совпавшие строки плюс все несоединённые строки из t1 и t2. Слово OUTER является необязательным и назначается в LEFT, RIGHT и FULL соединениях. Обычные соединения называются INNER соединениями.<br />
<br />
=== Как выполнять запросы, использующие несколько баз данных? ===<br />
<br />
Не существует способа создать запрос к базам данных отличным от текущей. Поскольку PostgreSQL загружает системные каталоги специфичные для базы данных, непонятно даже, как должен себя вести такой межбазовый запрос.<br />
<br />
contrib/dblink позволяет запросы между базами, используя вызовы функций. Разумеется, клиент может одновременно также устанавливать соедиенения с различными базами данных и таких образом объединять информацию из них.<br />
<br />
=== Как мне вернуть из функции несколько строк таблицы? ===<br />
<br />
Вы можете легко использовать функции, возвращающие список,<br />
[[Return more than one row of data from PL/pgSQL functions]].<br />
<br />
=== Почему я получаю ошибку "relation with OID #### не существует", когда обращаютсь к временным таблицам в функциях PL/PgSQL? ===<br />
<br />
В PostgreSQL до версии 8.3, PL/PgSQL кэширует сценарии функции и один из негативных эффектов этого состоит в том, что если функция PL/PgSQL обращается к временной таблице и эта таблица позднее удаляется и пересоздается, а функция затем вызывается снова, то ее вызов приведет к ошибке, потому что скэшированное содержимое функции содержит указатель на старую временную таблицу. Чтобы решить эту проблему, используйте EXECUTE для доступа к временным таблицам в PL/PgSQL. Использование этого оператора заставит запрос перегенерироваться каждый раз.<br />
<br />
В PostgreSQL 8.3 и позднее, этой проблемы нет.<br />
<br />
=== Какие есть решения для репликации? ===<br />
<br />
Хотя "репликация" -- это единый термин, есть несколько разных технологий для выполнения репликаций с разными особенностями, преимуществами и недостатками для каждой. Наша документация содержит хорошее введение по данной теме в<br />
http://www.postgresql.org/docs/8.3/static/high-availability.html и по теме<br />
особенностей репликации на основе сетевых списков на<br />
[[Replication, Clustering, and Connection Pooling]]<br />
<br />
Репликация Master/slave позволяет иметь один главный (master) сервер для выполнения запросов чтения/записи, в то время как подчинённые (slave) сервера могут производить только запросы чтения/SELECT. Наиболее популярным решением для репликации master-slave в PostgreSQL является Slony-I.<br />
<br />
Репликация Multi-master позволяет выполнять запросы чтения/записи на нескольких, реплицируемых друг с другом компьюетрах. Эта особенность также приводит к потере производительности, потому что необходима синхронизация изменений между несколькими серверами. Наиболее популярным решением для такой репликации в PostgreSQL является PGcluster.<br />
<br />
Существуют также проприетарные и основанные на аппаратном обеспечении решения по репликации, работающие на основе различных репликационных моделей.<br />
<br />
=== Возможно ли создать кластер серверов PostgreSQL с разделяемым устройством хранения? ===<br />
<br />
PostgreSQL не поддерживает кластеризацию, используя [[Shared_Storage|shared storage]] на SAN, SCSI-платах,<br />
iSCSI томах или других разделяемых носителях. Кластеры такого типа как "RAC-style" не поддерживаются.<br />
В настоящий момент поддерживаются только кластеры основанные на репликации.<br />
<br />
Подроности см. в [[Replication, Clustering, and Connection Pooling]].<br />
<br />
Использвание [[Shared_Storage|разделяемых устройств хранения]] в режиме 'failover' возможно, но не безопасно, так<br />
как в одно и тоже время более запущен и имеет доступ одним и тем же данным более чем один процесс postmaster.<br />
Рекомендуется Heartbeat и [http://en.wikipedia.org/wiki/STONITH STONITH] или какие-либо другие жёсткие решения по разрыву<br />
соединения.<br />
<br />
=== Почему имена таблицы и колонок не распознаются в в моём запросе? Почему не сохраняются заглавные буквы? ===<br />
<br />
Наиболее часто имена нераспознаются из-за использования двойных кавычек в имени таблицы или колонки при создании таблицы. При использовании двойных кавычек, имя таблицы и колонки (которые называют идентификаторами) сохраняются в регистро-зависимом виде; это означает, что вы должны использовать двойные кавычки, когда указываете эти имена в запросе. Некоторые интерфейсы, такие как pgAdmin, во время создания таблицы добавляют двойные кавычки автоматически. Таким образом, чтобы идентификаторы распознавались вы должны следовать одному из следующих правил: <br />
<br />
* Избегать использования двойных кавычек при создании таблиц<br />
* Использовать в идентификаторах только символы нижнего регистра<br />
* Использовать двойные кавычки для идентификаторов в запросах<br />
<br />
=== Я потерял пароль от базы данных. Как я могу его восстановить? ===<br />
<br />
Никак. Однако, вы можете сбросить этот пароль в какое-либо значение. Чтобы сделать это, вы должны<br />
<br />
* изменить pg_hba.conf так, чтобы временно предоставить ''trust'' авторизацию<br />
* перезагрузить файл конфигурации (pg_ctl reload)<br />
* подключиться к серверу и дать команду ALTER ROLE / PASSWORD чтобы установить новый пароль<br />
* изменить pg_hba.conf снова обратно на старые настройки<br />
* снова перезагрузить файл конфигурации<br />
<br />
=== Есть ли в PostgreSQL хранимые процедуры? ===<br />
<br />
В чистом виде нет. Однако PostgreSQL имеет очень мощные функции и определяемые пользователями функции, которые в своём большинстве совместимы с тем,<br />
что в других СУБД называют хранимыми процедурами (процедурами и функциями), а в некоторых случаях они могут больше.<br />
<br />
Эти функции могут быть различных типов и могут быть написаны на разных языках программирования.<br />
(Подробности см. в документации [http://www.postgresql.org/docs/current/static/xfunc.html Функции определяемые пользователями])<br />
<br />
Функции могут быть вызваны несколькими способами. Если вы хотите вызвать функцию также как хранимую процедуру в других СУБД (обычно функцию выполняющую что-либо, но о получении результатов работы которой вы не волнуетесь, потому что она ничего не возвращает), то один из способов может быть использование<br />
[http://www.postgresql.org/docs/current/static/plpgsql.html языка PL/pgSQL] для вашей процедуры и команды [http://www.postgresql.org/docs/current/static/plpgsql-statements.html#PLPGSQL-STATEMENTS-SQL-NORESULT PERFORM]. Например:<br />
PERFORM theNameOfTheFunction(arg1, arg2);<br />
<br />
Обратите внимание, что если вместо этого вы вызовите:<br />
SELECT theNameOfTheFunction(arg1, arg2);<br />
то вы получите какой-то результат, даже если данная функция ничего не возвращает (в качестве результата будет одна строка, содержащее пустое значение).<br />
<br />
Для того, чтобы избежать получения такого ненужного результата, можно использовать [http://www.postgresql.org/docs/current/static/plpgsql-statements.html#PLPGSQL-STATEMENTS-SQL-NORESULT PERFORM].<br />
<br />
Основные ограничения хранимых функций в PostgreSQL по сравнению с настоящими хранимыми процедурами это:<br />
<br />
* неспособность возвращать несколько наборов данных<br />
* отсутствие поддержки автономных транизакций (<code>BEGIN</code>, <code>COMMIT</code> и <code>ROLLBACK</code> внутри функций)<br />
* отсутствие поддержки стандартного SQL-ситаксиса <code>CALL</code>, через который ODBC и JDBC драйверы будут транслировать вызовы для вас.<br />
<br />
=== Почему не работают BEGIN, ROLLBACK и COMMIT внутри хранимых процедур/функций? ===<br />
<br />
PostgreSQL не поддерживает автономных транзакций в хранимых функциях. Как и все запросы PostgreSQL, хранимые функции всегда запускаются в транзакции и не могут работать снаружи транзакции.<br />
<br />
Если вам нужна хранимая процедура для управления транзакциями, вы можете посмотреть на интерфейс dblink или делать необходимую работу с помощью скрипта на клиенте. В некоторых случаях, вы можете сделать то, что вам нужно, используя<br />
[http://www.postgresql.org/docs/current/static/plpgsql-control-structures.html#PLPGSQL-ERROR-TRAPPING блоки исключений в PL/PgSQL], потому что каждый блок BEGIN/EXCEPTION/END создаёт подтранзакцию.<br />
<br />
=== Почему "SELECT count(*) FROM bigtable;" работает медленно? ===<br />
<br />
Потому что не используется индекс. PostgreSQL выполняет проверку видимости каждой записи и таким образом производит последовательное сканирование всей таблицы. Если вы хотите, вы можете отслеживать количество строк в таблице с помощью триггеров, но это вызовет замедление при операциях записи в таблицу.<br />
<br />
Вы можете получить некоторую оценку. Колонка reptiples в таблице<br />
[http://www.postgresql.org/docs/current/static/catalog-pg-class.html pg_class] содержит информацию из результата выполнения последнего оператора<br />
[http://www.postgresql.org/docs/current/static/sql-analyze.html ANALYZE] на эту таблицу. На большой таблице, точность этого значения составляет тысячные доли процента, что вполне достаточно для многих целей.<br />
<br />
"Точный" результат count, часто не будет точным долгое время в любом случае; из-за конкурентности <br />
[http://www.postgresql.org/docs/current/static/mvcc-intro.html MVCC], count будет точным только на момент вызова ''запущенного'' запроса SELECT count(*) (или ограничиваться уровнями [http://www.postgresql.org/docs/current/static/transaction-iso.html изоляции транзакций] данной транзакции), и может потерять актуальность уже в момент завершения запроса. При постоянной работе транзакций, изменяющий таблицу, два вызова count(*), которые завершатся в одно и то же время могут показать разные значения, если изменяющая транзакция завершилась между их вызовами.<br />
<br />
Подробности см. в [[Slow Counting]].<br />
<br />
=== Почему мой запрос намного медленее, чем когда он запускается в виде подготовленного запроса? ===<br />
<br />
Когда PostgreSQL получает полный запрос со всеми параметрами, он может использовать статистику таблицы, чтобы понять являются ли значения, используемые в запросе часто употребимым или часто неупотребимым какой-либо колонке. Это позволяет изменить способ извлечения данных на более эффективный, так как известно ожидается ли очень много или очень мало результатов из определённой части запроса. Например, PostgreSQL может выбрать последовательное сканирование вместо использования индекса, если осуществляется поиск 'active=y' и при этом известно, что 99% записей в таблице имеют 'active=y', поскольку в этом случае последовательное сканирование будет намного быстрее.<br />
<br />
В подготовленном запросе, PostgreSQL не получает значение всех параметров, когда создаёт план запроса. Он должен попытаться создать "безопасный" план, который должен работать хорошо вне зависимости от того какое значение вы предоставите как параметр, когда вы вызовите подгототовленный запрос. К сожалению, такой план может не оказаться очень хорошим, если значение, которое вы предоставили гораздо более употребительно или гораздо менее употребительно, чем среднее арифметическое из выбираемых значений в таблице.<br />
<br />
Если вы подозреваете, что так оно и есть, запустите команду<br />
[http://www.postgresql.org/docs/current/static/sql-explain.html EXPLAIN], чтобы сравнить медленный и быстрый запросы. Посмотрите вывод команды <code>EXPLAIN SELECT запрос...</code> и сравните его с результатами <code>PREPARE запрос... ; EXPLAIN EXECUTE запрос...</code>, чтобы увидеть, различаются ли планы запроса. <code>EXPLAIN ANALYZE</code> может дать вам больше информации, такой как оценка количества строк и счётчики.<br />
<br />
Иногда люди, у которых возникает эта проблема пытаются использовать подготовленные запросы как меру безопасности для предотвращения SQL иньекций, а не как инструмент тонкой настройки производительности тяжёлых запросов, часто запускающихся с различными параметрами. Такие люди должны подумать на использованием подготовленных операторов на стороне клиента, если их клиентский интерфейс (например PgJDBC) их поддерживает.<br />
<br />
В настоящий момент, PostgreSQL не предлагает способа запросить перепланировку подготовленного оператора, используя отдельный список значений параметров; если делать так, то несколько теряется смысл подготовленных операторов на стороне сервера. Запуск статистики, чтобы проверить выходит ли конкретное значение параметра сильно за пределами нормы и в автоматическое перепланирование в этом случае обсуждались, по пока не согласнованы и не реализованы.<br />
<br />
См. [[Using_EXPLAIN]]. Если вы собираетесь обратится за помощью в список рассылки, прочтите [[Guide to reporting problems]].<br />
<br />
=== Почему мой запрос намного медленее, когда он запускается в функции? ===<br />
<br />
См. [[#Почему мой запрос намного медленее, чем когда он запускается в виде подготовленного запроса?]]. Запросы в функциях PL/PgSQL подготавливаются и кэшируются, так что они запускаются преимущественно тем же способом, что и при выполнении вами <code>PREPARE</code>, а затем <code>EXECUTE</code>.<br />
<br />
Если у вас действительно серьёзные проблемы с этим и сбор статистики для таблиц или настройка вашего запроса не помогают, то вы можете обойти это, используя PL/PgSQL для переподготовки вашего запроса при каждом его выполнении. Чтобы сделать это, используйте оператор <code>EXECUTE ... USING</code> в PL/PgSQL, чтобы указать ваш запрос как текстовую строку. В качестве альтернативы могут быть использованы функции [http://www.postgresql.org/docs/current/static/functions-string.html quote_literal или quote_nullable], чтобы избежать подстановки параметров в текст запроса.<br />
<br />
[[Category:FAQ]]<br />
[[Category:Russian]]</div>Boshomihttps://wiki.postgresql.org/index.php?title=Category:Snippets&diff=17616Category:Snippets2012-05-19T23:33:16Z<p>Boshomi: +cat</p>
<hr />
<div>This is a collection of code examples, queries, functions, etc. for PostgreSQL.<br />
See the [[Talk:Snippets|Talk page]] for instructions on adding a new snippet.<br />
<br />
=== See also ===<br />
The [[:Category:Languages|language category]] contains a list of languages that snippets can be written in.<br />
<br />
[http://www.postgres.cz/index.php/PostgreSQL_SQL_Tricks This page] contains a bunch more useful "tricks". Some of them can be probably moved to this Wiki; {{messageLink|162867790905180929h4df06843q5a808e1732b6acad@mail.gmail.com|we have permission}} from the author.<br />
<br />
[[Category:Documentation]]</div>Boshomihttps://wiki.postgresql.org/index.php?title=Category:Pages_with_bad_code&diff=17615Category:Pages with bad code2012-05-19T23:32:18Z<p>Boshomi: +cat</p>
<hr />
<div>Pages with bad code. Please use the badcode templet:<nowiki>{{Badcode-concurrency}}</nowiki><br />
<br />
[[Category:Historical information]]</div>Boshomihttps://wiki.postgresql.org/index.php?title=Category:Todo&diff=17614Category:Todo2012-05-19T23:31:26Z<p>Boshomi: +cat</p>
<hr />
<div>This category lists the various Todo lists and related pages.<br />
<br />
[[Category:Advocacy]]<br />
[[Category:Development]]</div>Boshomihttps://wiki.postgresql.org/index.php?title=TodoDone91&diff=17613TodoDone912012-05-19T23:29:42Z<p>Boshomi: </p>
<hr />
<div><div style="margin: 1ex 1em; float: right;"><br />
__TOC__<br />
</div><br />
<br />
This list contains '''all PostgreSQL bugs and features requests that were solved in 9.1'''. There is a [[Todo]] page too for '''bugs and features that are still not solved'''.<br />
<br />
<br />
<div style="padding: 1ex 4em;"><br />
== Administration ==<br />
<br />
{{TodoItemDone<br />
|Allow auto-selection of partitioned tables for min/max() operations<br />
|There was a patch on -hackers from July 2009, but it has not been merged: [http://archives.postgresql.org/pgsql-hackers/2009-07/msg01115.php <nowiki>MIN/MAX optimization for partitioned table</nowiki>]}}<br />
<br />
{{TodoItemDone<br />
|Improve server security options<br />
* [http://archives.postgresql.org/pgsql-hackers/2008-04/msg01875.php <nowiki>Re: [0/4] Proposal of SE-PostgreSQL patches</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-hackers/2008-05/msg00000.php <nowiki>Re: [0/4] Proposal of SE-PostgreSQL patches</nowiki>]<br />
}}<br />
<br />
{{TodoItemDone<br />
|Allow the client to authenticate the server in a Unix-domain socket connection, e.g., using SO_PEERCRED<br />
* http://archives.postgresql.org/message-id/20090401173756.GB21229@svana.org<br />
}}<br />
<br />
{{TodoItemDone<br />
|Increase maximum values for max_standby_streaming_delay and log_min_duration_statement<br />
* http://archives.postgresql.org/pgsql-hackers/2010-12/msg01517.php<br />
* Committed: http://archives.postgresql.org/pgsql-committers/2011-03/msg00210.php<br />
}}<br />
<br />
=== Configuration files ===<br />
{{TodoSubsection}}<br />
<br />
{{TodoItemDone<br />
|Allow pg_hba.conf to specify host names along with IP addresses<br />
|Host name lookup could occur when the postmaster reads the pg_hba.conf file, or when the backend starts. Another solution would be to reverse lookup the connection IP and check that hostname against the host names in pg_hba.conf. We could also then check that the host name maps to the IP address. <br />
* [http://archives.postgresql.org/pgsql-hackers/2008-06/msg00569.php <nowiki>TODO Item: Allow pg_hba.conf to specify host names along with IP addresses</nowiki>]<br />
* http://archives.postgresql.org/pgsql-hackers/2010-08/msg00613.php<br />
}}<br />
<br />
{{TodoItemDone<br />
|Have pg_hba.conf consider "replication" special only in the database field<br />
* http://archives.postgresql.org/pgsql-hackers/2010-10/msg00632.php<br />
}}<br />
<br />
{{TodoItemDone<br />
|Rename unix domain socket 'ident' connections to 'peer', to avoid confusion with TCP 'ident'<br />
* http://archives.postgresql.org/pgsql-hackers/2010-11/msg01053.php<br />
}}<br />
<br />
<br />
{{TodoEndSubsection}}<br />
<br />
<br />
=== Statistics Collector ===<br />
{{TodoSubsection}}<br />
<br />
{{TodoItemDone<br />
| Allow the clearing of cluster-level statistics<br />
* [http://archives.postgresql.org/pgsql-hackers/2009-03/msg00917.php <nowiki>Resetting cluster-wide statistics</nowiki>]<br />
* ''pg_stat_reset_shared('bgwriter')'' (9.0) now handles the ''pg_stat_bgwriter'' subset of this<br />
}}<br />
<br />
{{TodoEndSubsection}}<br />
<br />
<br />
=== Point-In-Time Recovery (PITR) ===<br />
{{TodoSubsection}}<br />
<br />
{{TodoItemDone<br />
|Allow recovery.conf to support the same syntax as postgresql.conf, including quoting<br />
* [http://archives.postgresql.org/pgsql-hackers/2006-12/msg00497.php <nowiki>recovery.conf parsing problems</nowiki>]<br />
* http://archives.postgresql.org/pgsql-hackers/2010-05/msg00684.php<br />
}}<br />
<br />
<br />
{{TodoEndSubsection}}<br />
<br />
=== Standby server mode ===<br />
{{TodoSubsection}}<br />
<br />
{{TodoItemDone<br />
| Add a new privilege for connecting for streaming replication<br />
* [http://archives.postgresql.org/message-id/3f0b79eb1003040247p6b092241of91784a505e9abd8@mail.gmail.com <nowiki>Streaming replication and privilege</nowiki>]<br />
}}<br />
<br />
{{TodoItemDone<br />
| Add support for synchronous replication.<br />
}}<br />
<br />
{{TodoItemDone<br />
| Add capability to take and send a base backup over the streaming replication connection, making it possible to initialize a new standby server from a running primary server without a WAL archive or other access to the primary server. <br />
* http://archives.postgresql.org/pgsql-hackers/2010-09/msg00136.php<br />
}}<br />
<br />
<br />
{{TodoItemDone<br />
| Allow the automatic removal of old directories when streaming base backups<br />
* http://archives.postgresql.org/pgsql-hackers/2011-04/msg00558.php<br />
}}<br />
<br />
{{TodoEndSubsection}}<br />
<br />
== Data Types ==<br />
<br />
{{TodoItemDone<br />
|Reduce storage space for small NUMERICs<br />
* [http://archives.postgresql.org/pgsql-hackers/2007-02/msg01331.php <nowiki>Saving space for common kinds of numeric values</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-patches/2007-02/msg00505.php <nowiki>Numeric patch to add special-case representations for &lt; 8 bytes</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-hackers/2007-06/msg00715.php <nowiki>Re: Reducing NUMERIC size for 8.3</nowiki>]<br />
}}<br />
<br />
{{TodoItemDone<br />
|Allow adding enumerated values to an existing enumerated data type<br />
* [http://archives.postgresql.org/pgsql-hackers/2008-04/msg01718.php <nowiki>Re: [COMMITTERS] pgsql: Update: &lt; * Allow adding enumerated values to an existing</nowiki>]<br />
}}<br />
<br />
=== MONEY Data Type ===<br />
{{TodoSubsection}}<br />
<br />
{{TodoItemDone<br />
|Allow MONEY to be easily cast to/from other numeric data types}}<br />
<br />
{{TodoEndSubsection}}<br />
<br />
<br />
=== XML ===<br />
{{TodoSubsection}}<br />
<br />
{{TodoItemDone<br />
|xpath_exists() is needed<br />
|This checks whether or not the path specified exists in the XML value. Without this function we need to use the weird "array_dims(xpath(...)) IS NOT NULL" syntax.}}<br />
<br />
{{TodoEndSubsection}}<br />
<br />
== Functions ==<br />
<br />
{{TodoItemDone<br />
|Add printf()-like functionality<br />
* [http://archives.postgresql.org/pgsql-hackers/2009-09/msg00367.php <nowiki>RfD: more powerful &quot;any&quot; types</nowiki>]<br />
}}<br />
<br />
== Multi-Language Support ==<br />
<br />
{{TodoItemDone<br />
|Allow more fine-grained collation selection<br />
|Right now the collation is fixed at database creation time.<br />
* [http://archives.postgresql.org/pgsql-hackers/2005-03/msg00932.php <nowiki>Re: Patch for collation using ICU</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-patches/2005-08/msg00039.php <nowiki>FW: Win32 unicode vs ICU</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-patches/2005-08/msg00309.php <nowiki>Re: FW: Win32 unicode vs ICU</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-hackers/2005-09/msg00110.php <nowiki>Proof of concept COLLATE support with patch</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-patches/2005-09/msg00020.php <nowiki>For review: Initial support for COLLATE</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-hackers/2005-12/msg01121.php <nowiki>Proposed COLLATE implementation</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-hackers/2006-01/msg00767.php <nowiki>TODO item: locale per database patch (new iteration)</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-patches/2006-03/msg00233.php <nowiki>Re: FW: Win32 unicode vs ICU</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-hackers/2006-09/msg00662.php <nowiki>Re: Fixed length data types issue</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-hackers/2008-07/msg00557.php <nowiki>[WIP] collation support revisited (phase 1)</nowiki>]<br />
* [[Todo:Collate]]<br />
* [[Todo:ICU]]<br />
* [http://archives.postgresql.org/pgsql-hackers/2008-08/msg01362.php <nowiki>WIP patch: Collation support</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-hackers/2008-09/msg00012.php <nowiki>Re: WIP patch: Collation support</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-hackers/2008-10/msg00868.php <nowiki>PGDay.it collation discussion notes</nowiki>]<br />
* [http://www.unicode.org/unicode/reports/tr10/ Unicode collation algorithm]<br />
}}<br />
<br />
{{TodoItemDone<br />
|Set client encoding based on the client operating system encoding<br />
|Currently client_encoding is set in postgresql.conf, which defaults to the server encoding. <br />
* [http://archives.postgresql.org/pgsql-hackers/2006-08/msg01696.php <nowiki>Re: [GENERAL] invalid byte sequence ?</nowiki>]<br />
}}<br />
<br />
== SQL Commands ==<br />
<br />
{{TodoItemDone<br />
|Fix TRUNCATE ... RESTART IDENTITY so its effect on sequences is rolled back on transaction abort<br />
* [http://archives.postgresql.org/pgsql-hackers/2008-05/msg00550.php <nowiki>Re: [PATCHES] TRUNCATE TABLE with IDENTITY</nowiki>]<br />
}}<br />
<br />
{{TodoItemDone<br />
|Enable standard_conforming_strings by default<br />
|When this is done, backslash-quote should be prohibited in non-E<nowiki>''</nowiki> strings because of possible confusion over how such strings treat backslashes. Basically, <nowiki>''</nowiki> is always safe for a literal single quote, while \' might or might not be based on the backslash handling rules.}}<br />
<br />
{{TodoItemDone<br />
|Allow INSERT/UPDATE/DELETE ... RETURNING in common table expressions<br />
* [http://archives.postgresql.org/pgsql-hackers/2009-10/msg00472.php <nowiki>Writeable CTEs and side effects</nowiki>]<br />
}}<br />
<br />
{{TodoItemDone<br />
|Add support for functional dependencies<br />
|This would allow omitting GROUP BY columns when grouping by the primary key.<br />
}}<br />
<br />
=== CREATE ===<br />
{{TodoSubsection}}<br />
<br />
{{TodoItemDone<br />
|Allow CREATE TABLE to optionally create a table if it does not already exist, without throwing an error<br />
|The fact that tables contain data makes this more complex than other CREATE OR REPLACE operations.<br />
* [http://archives.postgresql.org/pgsql-hackers/2010-04/msg01300.php <nowiki>Add column if not exists (CINE)</nowiki>]<br />
}}<br />
<br />
{{TodoEndSubsection}}<br />
<br />
=== ALTER ===<br />
{{TodoSubsection}}<br />
<br />
{{TodoItemDone<br />
|Allow ALTER TABLE to change constraint deferrability}}<br />
<br />
{{TodoItemDone<br />
|Add missing object types for ALTER ... SET SCHEMA}}<br />
<br />
{{TodoItemDone<br />
|Allow an existing index to be marked as a table's primary key<br />
* [http://archives.postgresql.org/pgsql-hackers/2008-04/msg00500.php <nowiki>Setting a pre-existing index as a primary key</nowiki>]<br />
* http://archives.postgresql.org/pgsql-hackers/2010-10/msg00642.php<br />
* http://archives.postgresql.org/pgsql-hackers/2010-12/msg00265.php<br />
}}<br />
<br />
{{TodoItemDone<br />
|Allow ALTER TYPE on composite types to perform operations similar to ALTER TABLE<br />
* [http://archives.postgresql.org/pgsql-hackers/2008-12/msg00245.php <nowiki>ALTER composite type does not work, but ALTER TABLE which ROWTYPE is used as a type - works fine</nowiki>]<br />
}}<br />
<br />
{{TodoItemDone<br />
|Don't require table rewrite on ALTER TABLE ... ALTER COLUMN TYPE, when the old and new data types are binary compatible<br />
* http://archives.postgresql.org/message-id/200903040137.n241bAUV035002@wwwmaster.postgresql.org<br />
* [http://archives.postgresql.org/pgsql-patches/2006-10/msg00154.php <nowiki>Eliminating phase 3 requirement for varlen increases via ALTER COLUMN</nowiki>]<br />
* http://archives.postgresql.org/pgsql-hackers/2010-12/msg02360.php<br />
}}<br />
<br />
{{TodoItemDone<br />
|Reduce locking required for ALTER commands<br />
* [http://archives.postgresql.org/pgsql-hackers/2009-08/msg00533.php <nowiki>ALTER TABLE SET STATISTICS requires AccessExclusiveLock</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-hackers/2009-10/msg01083.php <nowiki>Re: ALTER TABLE SET STATISTICS requires AccessExclusiveLock</nowiki>]<br />
* http://archives.postgresql.org/pgsql-hackers/2008-10/msg01248.php<br />
* http://archives.postgresql.org/pgsql-hackers/2008-10/msg00242.php<br />
}}<br />
<br />
{{TodoItemDone<br />
|Fix removal of NULL constraints in inherited tables<br />
* http://archives.postgresql.org/pgsql-hackers/2010-06/msg00919.php <br />
* http://archives.postgresql.org/pgsql-hackers/2010-09/msg01773.php<br />
* http://archives.postgresql.org/pgsql-hackers/2010-10/msg00329.php<br />
}}<br />
<br />
<br />
{{TodoEndSubsection}}<br />
<br />
=== CLUSTER ===<br />
{{TodoSubsection}}<br />
<br />
{{TodoItemDone<br />
|Improve CLUSTER performance by sorting to reduce random I/O<br />
* [http://archives.postgresql.org/pgsql-hackers/2008-08/msg01371.php <nowiki>Our CLUSTER implementation is pessimal</nowiki>]<br />
}}<br />
<br />
{{TodoItemDone<br />
|Make CLUSTER VERBOSE more verbose.<br />
|It is also used by new VACUUM FULL VERBOSE.}}<br />
<br />
{{TodoEndSubsection}}<br />
<br />
<br />
== Server-Side Languages ==<br />
<br />
=== PL/Python ===<br />
{{TodoSubsection}}<br />
<br />
{{TodoItemDone<br />
|Add table function support}}<br />
<br />
{{TodoItemDone<br />
|Add tracebacks<br />
* [http://archives.postgresql.org/pgsql-patches/2006-02/msg00288.php <nowiki>Re: plpython tracebacks</nowiki>]<br />
}}<br />
<br />
{{TodoEndSubsection}}<br />
<br />
<br />
== Clients ==<br />
<br />
=== psql ===<br />
{{TodoSubsection}}<br />
<br />
{{TodoItemDone<br />
|Have \d+ show child tables that inherit from the specified parent}}<br />
<br />
<br />
{{TodoItemDone<br />
|Consider showing TOAST and index sizes in \dt+<br />
* [http://archives.postgresql.org/pgsql-general/2010-01/msg00912.php <nowiki>\dt+ sizes don't include TOAST data</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-hackers/2011-04/msg00485.php <nowiki>Re: psql \dt and table size</nowiki>]<br />
}}<br />
<br />
{{TodoItemDone<br />
|Add \dL to show languages<br />
* [http://archives.postgresql.org/pgsql-hackers/2009-07/msg00915.php <nowiki>Re: [PATCH] Psql List Languages</nowiki>]<br />
}}<br />
<br />
{{TodoItemDone<br />
|Distinguish between unique indexes and unique constraints in \d+<br />
* http://archives.postgresql.org/message-id/8780.1271187360@sss.pgh.pa.us<br />
}}<br />
<br />
<br />
{{TodoEndSubsection}}<br />
<br />
=== libpq ===<br />
{{TodoSubsection}}<br />
<br />
<br />
{{TodoItemDone<br />
|Add code to detect client encoding and locale from the operating system environment<br />
* [http://archives.postgresql.org/pgsql-hackers/2009-06/msg01040.php <nowiki>Determining client_encoding from client locale</nowiki>]<br />
}}<br />
<br />
<br />
{{TodoEndSubsection}}<br />
<br />
== Indexes ==<br />
=== GIN ===<br />
{{TodoSubsection}}<br />
<br />
{{TodoItemDone<br />
|Support empty indexed values (such as zero-element arrays) properly<br />
* [http://archives.postgresql.org/pgsql-hackers/2009-04/msg00237.php contrib/intarray vs empty arrays]<br />
* [http://archives.postgresql.org/pgsql-bugs/2009-05/msg00118.php BUG #4806: Bug with GiST index and empty integer array]<br />
}}<br />
<br />
{{TodoItemDone<br />
|Behave correctly for cases where some elements of an indexed value are NULL<br />
* [http://archives.postgresql.org/pgsql-hackers/2009-03/msg01003.php <nowiki>GIN versus zero-key queries</nowiki>]<br />
}}<br />
<br />
{{TodoItemDone<br />
|Support queries that require a full scan<br />
* [http://archives.postgresql.org/pgsql-general/2009-05/msg00402.php Issue report]<br />
* [http://archives.postgresql.org/pgsql-general/2007-06/msg01132.php Older issue report]<br />
* [http://archives.postgresql.org/pgsql-hackers/2010-10/msg00521.php Still another complaint]<br />
* [http://archives.postgresql.org/pgsql-hackers/2007-01/msg01581.php Previous partial fix]<br />
}}<br />
<br />
{{TodoItemDone<br />
|Improve GIN's handling of NULL array values<br />
* http://archives.postgresql.org/pgsql-bugs/2010-12/msg00032.php<br />
}}<br />
<br />
{{TodoEndSubsection}}<br />
<br />
<br />
== Locking ==<br />
<br />
{{TodoItemDone<br />
|Consider improving serialized transaction behavior to avoid anomalies<br />
* [http://archives.postgresql.org/pgsql-hackers/2009-05/msg00217.php <nowiki>Serializable Isolation without blocking</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-hackers/2009-05/msg01136.php <nowiki>User-facing aspects of serializable transactions</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-hackers/2009-06/msg00035.php <nowiki>Re: User-facing aspects of serializable transactions</nowiki>]<br />
}}<br />
<br />
<br />
== Write-Ahead Log ==<br />
<br />
{{TodoItemDone<br />
|Allow WAL logging to be turned off for a table, but the table might be dropped or truncated during crash recovery<br />
|Allow tables to bypass WAL writes and just fsync() dirty pages on commit. This should be implemented using ALTER TABLE, e.g. <nowiki>ALTER TABLE PERSISTENCE [ DROP | TRUNCATE | DEFAULT ]</nowiki>. Tables using non-default logging should not use referential integrity with default-logging tables. A table without dirty buffers during a crash could perhaps avoid the drop/truncate. <br />
* [http://archives.postgresql.org/pgsql-hackers/2005-12/msg01016.php <nowiki>Re: [Bizgres-general] WAL bypass for INSERT, UPDATE and</nowiki>]<br />
}}<br />
<br />
== Optimizer / Executor ==<br />
<br />
<br />
=== Hashing ===<br />
{{TodoSubsection}}<br />
<br />
{{TodoItemDone<br />
|Allow hashing to be used on arrays, if the element type is hashable<br />
* http://archives.postgresql.org/message-id/11087.1244905821@sss.pgh.pa.us<br />
}}<br />
<br />
{{TodoEndSubsection}}<br />
<br />
<br />
== Source Code ==<br />
<br />
<br />
{{TodoItemDone<br />
|Improve the module installation experience (/contrib, etc)<br />
* [http://archives.postgresql.org/pgsql-hackers/2008-04/msg00132.php <nowiki>modules</nowiki>]<br />
* {{messageLink|ca33c0a30807231640n6fb4035dod8121a18aa1fa29c@mail.gmail.com|Re: PostgreSQL extensions packaging}}<br />
* {{messageLink|ca33c0a30804061349s41b4d8fcsa9c579454b27ecd2@mail.gmail.com|Database owner installable modules patch}}<br />
* [http://archives.postgresql.org//pgsql-hackers/2009-03/msg00855.php <nowiki>Re: contrib function naming, and upgrade issues</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-hackers/2009-05/msg00912.php <nowiki>search_path vs extensions</nowiki>]<br />
}}<br />
<br />
=== /contrib/pg_upgrade ===<br />
{{TodoSubsection}}<br />
<br />
{{TodoItemDone<br />
|Remove copy_dir() code, or use it<br />
}}<br />
<br />
<br />
{{TodoEndSubsection}}<br />
<br />
<br />
</div><br />
<br />
[[Category:Todo]]<br />
[[Category:PostgreSQL_9.1]]<br />
[[Category:Historical information]]</div>Boshomihttps://wiki.postgresql.org/index.php?title=TodoDone90&diff=17612TodoDone902012-05-19T23:29:28Z<p>Boshomi: </p>
<hr />
<div><div style="margin: 1ex 1em; float: right;"><br />
__TOC__<br />
</div><br />
<br />
This list contains '''all PostgreSQL bugs and features requests that were solved in 9.0'''. There is a [[Todo]] page too for '''bugs and features that are still not solved'''.<br />
<br />
<div style="padding: 1ex 4em;"><br />
== Administration ==<br />
<br />
{{TodoItemDone<br />
|Allow more complex user/database default GUC settings<br />
|Currently ALTER USER and ALTER DATABASE support per-user and per-database defaults. Consider adding per-user-and-database defaults so things like search_path can be defaulted for a specific user connecting to a specific database.<br />
* [http://archives.postgresql.org/pgsql-hackers/2006-09/msg02345.php <nowiki>Re: Per-database search_path</nowiki>]<br />
* http://archives.postgresql.org/message-id/20090811221921.GK16362@alvh.no-ip.org<br />
}}<br />
<br />
{{TodoItemDone<br />
|Allow custom variables to be created only by super-users but modified by ordinary uses, where appropriate<br />
* [http://archives.postgresql.org/pgsql-hackers/2006-11/msg00911.php <nowiki>custom variable classes</nowiki>]<br />
}}<br />
<br />
{{TodoItemDone<br />
|Allow the client to set an application_name to appear in pg_stat_activity<br />
* http://archives.postgresql.org/message-id/407d949e0907161237r76ebd92av6836c6563d8a230e@mail.gmail.com<br />
}}<br />
<br />
{{TodoItemDone<br />
|Allow server-side enforcement of password policies<br />
|Password checks might include password complexity or non-reuse of passwords. This facility will require the client to send password creation/changes to the server in plain-text, not MD5.<br />
* [http://archives.postgresql.org/pgsql-hackers/2009-09/msg01766.php <nowiki>Rejecting weak passwords</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-hackers/2009-10/msg00025.php <nowiki>Re: Rejecting weak passwords</nowiki>]<br />
}}<br />
<br />
=== Tablespaces ===<br />
{{TodoSubsection}}<br />
<br />
{{TodoItemDone<br />
|Allow per-tablespace random_page_cost<br />
* [http://archives.postgresql.org/pgsql-hackers/2009-10/msg01128.php <nowiki>per table random-page-cost?</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-hackers/2009-10/msg01486.php <nowiki>per-tablespace random_page_cost/seq_page_cost</nowiki>]<br />
}}<br />
<br />
{{TodoEndSubsection}}<br />
<br />
=== Point-In-Time Recovery (PITR) ===<br />
{{TodoSubsection}}<br />
<br />
{{TodoItemDone<br />
|Allow a warm standby system to also allow read-only statements<br />
* [http://archives.postgresql.org/pgsql-hackers/2007-03/msg00050.php <nowiki>Updated propsoal for read-only queries on PITR slaves (SoC 2007)</nowiki>]<br />
}}<br />
<br />
{{TodoEndSubsection}}<br />
<br />
=== Standby server mode ===<br />
{{TodoSubsection}}<br />
<br />
{{TodoItemDone<br />
| Redefine smart shutdown in standby mode to exist as soon as all read-only connections are gone.<br />
* [http://archives.postgresql.org/pgsql-hackers/2010-01/msg02044.php <nowiki>Re: HS/SR and smart shutdown</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-committers/2010-04/msg00081.php commit log]<br />
}}<br />
<br />
{{TodoItemDone<br />
| Consider changing the calculation of superused_reserved_connections so that replication connections don't consume superuser_reserved_connections slots.<br />
* [http://archives.postgresql.org/pgsql-docs/2010-03/msg00022.php <nowiki>Re: Streaming replication document improvements</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-committers/2010-04/msg00222.php commit log]<br />
}}<br />
<br />
{{TodoEndSubsection}}<br />
<br />
== Data Types ==<br />
<br />
=== Dates and Times ===<br />
{{TodoSubsection}}<br />
<br />
{{TodoItemDone<br />
|Revise the src/timezone/tznames abbreviation files:<br />
* to add missing abbreviations<br />
* to find abbreviations that can be safely promoted to the Default list<br />
* {{messageLink|7867.1219793881@sss.pgh.pa.us|BUG #4377: casting result of timeofday() to timestamp fails in some timezones}}}}<br />
<br />
{{TodoEndSubsection}}<br />
<br />
=== Binary Data ===<br />
{{TodoSubsection}}<br />
<br />
{{TodoItemDone<br />
|Add security checks for large objects}}<br />
<br />
{{TodoEndSubsection}}<br />
<br />
=== XML ===<br />
{{TodoSubsection}}<br />
<br />
{{TodoItemDone<br />
|Inline ORDER BY for XMLAGG. Example: "... XMLAGG(XMLELEMENT(...) ORDER BY col1) ..." (should be made to work with all aggregate functions)}}<br />
<br />
{{TodoEndSubsection}}<br />
<br />
== Functions ==<br />
<br />
{{TodoItemDone<br />
|Add functions to get/set bit values<br />
* [http://archives.postgresql.org/pgsql-hackers/2004-01/msg00498.php <nowiki>implemented missing bitSetBit() and bitGetBit()</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-hackers/2004-02/msg00478.php <nowiki>Re: implemented missing bitSetBit() and bitGetBit()</nowiki>]<br />
}}<br />
<br />
{{TodoItemDone<br />
|Add missing operators for geometric data types<br />
|Some geometric types do not have the full suite of geometric operators, e.g. box @&gt; point<br />
* {{messageLink|4B0A8F0F.3020308@sigaev.ru|point_ops for GiST}}<br />
}}<br />
<br />
{{TodoItemDone<br />
|Add has_sequence_privilege()<br />
* [http://archives.postgresql.org/pgsql-hackers/2008-09/msg00032.php <nowiki>Re: [PATCH] allow has_table_privilege(..., 'usage') on sequences</nowiki>]<br />
}}<br />
<br />
== SQL Commands ==<br />
<br />
{{TodoItemDone<br />
|Allow EXPLAIN output to be more easily processed by scripts, perhaps XML<br />
* [http://archives.postgresql.org/pgsql-hackers/2009-05/msg00857.php <nowiki>generic options for explain</nowiki>]<br />
}}<br />
<br />
{{TodoItemDone<br />
|Forbid COMMENT on columns of an index<br />
|Postgres currently allows comments to be placed on the columns of an index, but pg_dump doesn't handle them and the column names themselves are implementation-dependent.<br />
* http://archives.postgresql.org/message-id/27676.1237906577@sss.pgh.pa.us<br />
}}<br />
<br />
=== CREATE ===<br />
{{TodoSubsection}}<br />
<br />
{{TodoItemDone<br />
|Add CREATE TABLE LIKE ... INCLUDING COMMENTS}}<br />
<br />
{{TodoItemDone<br />
|Have CREATE TABLE LIKE copy column storage parameters<br />
* [http://archives.postgresql.org/pgsql-hackers/2008-07/msg01417.php <nowiki>Copy storage parameters on CREATE TABLE LIKE/INHERITS</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-hackers/2008-08/msg00423.php <nowiki>Copy column storage parameters on CREATE TABLE LIKE/INHERITS</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-hackers/2008-09/msg00576.php <nowiki>[Patch Review] Copy column storage parameters on CREATE TABLE LIKE/INHERITS</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-hackers/2008-09/msg00824.php <nowiki>Re: Copy column storage parameters on CREATE TABLE LIKE/INHERITS</nowiki>]<br />
}}<br />
<br />
{{TodoItemDone<br />
|Add OR REPLACE to CREATE LANGUAGE<br />
* [http://archives.postgresql.org/pgsql-patches/2008-05/msg00057.php <nowiki>Re: create or replace language</nowiki>]<br />
}}<br />
<br />
{{TodoEndSubsection}}<br />
<br />
=== COPY ===<br />
{{TodoSubsection}}<br />
<br />
{{TodoItemDone<br />
|Improve bytea COPY format<br />
* [http://archives.postgresql.org/pgsql-hackers/2009-05/msg00192.php <nowiki>bytea vs. pg_dump</nowiki>]<br />
}}<br />
<br />
{{TodoEndSubsection}}<br />
<br />
=== GRANT/REVOKE ===<br />
{{TodoSubsection}}<br />
<br />
{{TodoItemDone<br />
|Allow GRANT/REVOKE permissions to be applied to all schema objects with one command<br />
|The proposed syntax is: GRANT SELECT ON ALL TABLES IN public TO phpuser; GRANT SELECT ON NEW TABLES IN public TO phpuser;<br />
* [http://archives.postgresql.org/pgsql-hackers/2009-06/msg01014.php <nowiki>GRANT ON ALL IN schema</nowiki>]<br />
}}<br />
<br />
{{TodoItemDone<br />
|Allow GRANT/REVOKE permissions to be inherited by objects based on schema permissions<br />
* http://wiki.postgresql.org/wiki/DefaultACL<br />
}}<br />
<br />
=== LISTEN/NOTIFY ===<br />
{{TodoSubsection}}<br />
<br />
{{TodoItemDone<br />
|Allow LISTEN/NOTIFY to store info in memory rather than tables<br />
|Currently LISTEN/NOTIFY information is stored in pg_listener. Storing such information in memory would improve performance.}}<br />
<br />
{{TodoItemDone<br />
|Add optional textual message to NOTIFY<br />
|This would allow an informational message to be added to the notify message, perhaps indicating the row modified or other custom information.}}<br />
<br />
{{TodoEndSubsection}}<br />
<br />
=== Window Functions ===<br />
See {{messageLink|357.1230492361@sss.pgh.pa.us|TODO items for window functions}}.<br />
{{TodoSubsection}}<br />
{{TodoItem|Do we really need so much duplicated code between Agg and WindowAgg?}}<br />
<br />
{{TodoEndSubsection}}<br />
<br />
== Integrity Constraints ==<br />
=== Keys ===<br />
<br />
{{TodoSubsection}}<br />
<br />
{{TodoItemDone<br />
|Allow DEFERRABLE UNIQUE constraints<br />
|<nowiki>This would allow UPDATE tab SET col = col + 1 to work if col has a unique index. Currently, uniqueness checks are done while the command is being executed, rather than at the end of the statement or transaction.</nowiki><br />
* http://people.planetpostgresql.org/greg/index.php?/archives/46-Updating-unique-columns.html<br />
* [http://archives.postgresql.org/pgsql-hackers/2006-09/msg01458.php <nowiki>Re: Unique index: update error</nowiki>]<br />
}}<br />
<br />
{{TodoEndSubsection}}<br />
<br />
== Server-Side Languages ==<br />
<br />
=== PL/pgSQL ===<br />
{{TodoSubsection}}<br />
<br />
{{TodoItemDone<br />
|Allow function parameters to be passed by name, get_employee_salary(12345 AS emp_id, 2001 AS tax_year)<br />
* [http://archives.postgresql.org/pgsql-hackers/2008-08/msg00559.php <nowiki>proposal sql: labeled function params</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-hackers/2008-12/msg00880.php <nowiki>WIP: for 8.5 named and mixed notation support</nowiki>]<br />
}}<br />
<br />
{{TodoItemDone<br />
|Review handling of MOVE and FETCH<br />
* [http://archives.postgresql.org/pgsql-patches/2007-04/msg00527.php <nowiki>Re: actualised forgotten Magnus's patch for plpgsql MOVE statement</nowiki>]<br />
}}<br />
<br />
{{TodoItemDone<br />
|Improve logic of determining if an identifier is a variable or a column name<br />
* [http://archives.postgresql.org/pgsql-hackers/2007-07/msg00436.php <nowiki>Re: plpgsql and qualified variable names</nowiki>]<br />
* * http://archives.postgresql.org/message-id/603c8f070903061741l1f11ba59q783745cc3cb79dba@mail.gmail.com<br />
}}<br />
<br />
{{TodoItemDone<br />
|Improve PL/pgSQL's ability to cope with rowtypes containing dropped columns<br />
* [http://archives.postgresql.org/pgsql-bugs/2008-09/msg00004.php <nowiki>Bug in RETURN QUERY</nowiki>]<br />
}}<br />
<br />
{{TodoEndSubsection}}<br />
<br />
=== PL/Python ===<br />
{{TodoSubsection}}<br />
<br />
{{TodoItemDone<br />
|Add support for Python 3<br />
* [http://archives.postgresql.org/message-id/3544.1238817272@sss.pgh.pa.us <nowiki>Re: Python 3.0 does not work with PL/Python</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-hackers/2009-07/msg01519.php <nowiki>WIP: plpython3</nowiki>]<br />
}}<br />
<br />
{{TodoItemDone<br />
|Allow arrays as function arguments and return values.}}<br />
<br />
create table users (first_name text, last_name text);<br />
create function user_name(user) returns text as 'mycode' language plpython;<br />
select user_name(user) from users;<br />
alter table add column user_id integer;<br />
select user_name(user) from users;<br />
<br />
You have to drop and create the function(s) each time its arguments<br />
are modified (not nice), or don't cache the input and output functions<br />
(slower?), or check if the structure of the argument has been<br />
altered (is this possible, easy, quick?) and recreate cache.}}<br />
<br />
{{TodoItemDone<br />
|check encoding validity of values passed back to Postgres in function returns, trigger tuple changes, or SPI calls.}}<br />
<br />
{{TodoEndSubsection}}<br />
<br />
== Clients ==<br />
<br />
=== pg_dump / pg_restore ===<br />
{{TodoSubsection}}<br />
<br />
{{TodoItemDone<br />
|Add dumping of comments on composite type columns<br />
* {{MessageLink|20090723225940.E35D975331E@cvs.postgresql.org|Teach pg_dump to dump comments attached to the columns of a composite type.}}<br />
}}<br />
<br />
{{TodoItemDone<br />
| Add comments to output indicating version of pg_dump and of the database server<br />
}}<br />
<br />
{{TodoEndSubsection}}<br />
<br />
=== ecpg ===<br />
{{TodoSubsection}}<br />
<br />
{{TodoItemDone<br />
|Implement SQLDA<br />
|{{MessageLink|20100105163823.7C70B753FB7@cvs.postgresql.org|add sqlda support to ecpg in both native and compatibility mode}}<br />
}}<br />
<br />
{{TodoEndSubsection}}<br />
<br />
=== libpq ===<br />
{{TodoSubsection}}<br />
<br />
{{TodoItemDone<br />
|Add PQescapeIdentifier()}}<br />
<br />
{{TodoItemDone<br />
|Add keepalive support to libpq<br />
* [http://archives.postgresql.org/pgsql-hackers/2010-02/msg00611.php <nowiki>TCP keepalive support for libpq</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-committers/2010-06/msg00205.php commit log]<br />
}}<br />
<br />
{{TodoEndSubsection}}<br />
<br />
== Triggers ==<br />
<br />
{{TodoItemDone<br />
|Support triggers on columns<br />
* [http://archives.postgresql.org/pgsql-patches/2005-07/msg00107.php <nowiki>Column-level triggers</nowiki>]<br />
}}<br />
<br />
== Indexes ==<br />
<br />
=== Hash ===<br />
{{TodoSubsection}}<br />
<br />
{{TodoItemDone<br />
|Pack hash index buckets onto disk pages more efficiently<br />
|Currently only one hash bucket can be stored on a page. Ideally several hash buckets could be stored on a single page and greater granularity used for the hash algorithm.<br />
* [http://archives.postgresql.org/pgsql-hackers/2004-06/msg00168.php <nowiki>Why hash indexes suck</nowiki>]<br />
However, the binary searching within a hash page probably renders this issue moot.<br />
* [http://archives.postgresql.org/pgsql-committers/2008-09/msg00154.php <nowiki>pgsql: Change hash indexes to store only the hash code rather than the</nowiki>]<br />
}}<br />
<br />
{{TodoEndSubsection}}<br />
<br />
== Catalogs ==<br />
<br />
{{TodoItemDone<br />
|Improve performance of information_schema views<br />
* [http://archives.postgresql.org/message-id/29921.1230246746%40sss.pgh.pa.us table_privileges is way too slow]<br />
}}<br />
<br />
{{TodoItemDone<br />
|Improve information_schema's entries for precision and scale<br />
* [http://archives.postgresql.org/pgsql-hackers/2009-05/msg01485.php <nowiki>Re: information_schema.columns changes needed for OLEDB</nowiki>]<br />
}}<br />
<br />
<br />
<br />
== Vacuum ==<br />
<br />
{{TodoItemDone<br />
|Improve VACUUM FULL's speed when major data movement is needed<br />
|For large table adjustments during VACUUM FULL, it would be faster to cluster or reindex rather than update the indexes piecemeal as it does now. Also, this behavior tends to bloat the indexes.<br />
* [http://archives.postgresql.org/pgsql-hackers/2007-03/msg00024.php <nowiki>Revitalising VACUUM FULL for 8.3</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-performance/2007-05/msg00296.php <nowiki>Re: [doc patch] a slight VACUUM / VACUUM FULL doc improvement proposal</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-hackers/2007-08/msg00307.php <nowiki>Re: Unexpected VACUUM FULL failure</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-hackers/2008-06/msg00656.php A note about VACUUM syntax]<br />
* [http://archives.postgresql.org/pgsql-hackers/2009-09/msg01045.php <nowiki>Feedback on getting rid of VACUUM FULL</nowiki>]<br />
}}<br />
<br />
== Write-Ahead Log ==<br />
<br />
{{TodoItemDone<br />
|Allow WAL traffic to be streamed to another server for stand-by replication}}<br />
<br />
== Source Code ==<br />
<br />
{{TodoItemDone<br />
|Update Bonjour to work with newer cross-platform SDK<br />
* [http://archives.postgresql.org/pgsql-hackers/2006-09/msg02238.php <nowiki>Darwin stuff is getting deprecated</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-patches/2006-10/msg00048.php <nowiki>Use dns_sd.h for Bonjour</nowiki>]<br />
}}<br />
<br />
{{TodoItemDone<br />
|Add automated check for invalid C++ source code constructs<br />
* [http://archives.postgresql.org/pgsql-patches/2007-07/msg00056.php <nowiki>Re: SPI-header-files safe for C++-compiler</nowiki>]<br />
}}<br />
<br />
{{TodoItemDone<br />
|Allow table and index WITH options to be specified via hooks, for use with plugins like GiST index methods<br />
* {{MessageLink|20090105171428.77B29754A17@cvs.postgresql.org|Change the reloptions machinery to use a table-based parser}}<br />
}}<br />
<br />
{{TodoItemDone<br />
|Allow setting of system oids during object creation, for use by pg_migrator<br />
* [http://archives.postgresql.org/pgsql-hackers/2009-08/msg00401.php <nowiki>Re: Re: [Pg-migrator-general] Composite types break pg_migrated tables</nowiki>]<br />
}}<br />
<br />
=== /contrib/pg_upgrade ===<br />
{{TodoSubsection}}<br />
<br />
{{TodoEndSubsection}}<br />
<br />
=== Windows ===<br />
{{TodoSubsection}}<br />
<br />
{{TodoItemDone<br />
|Diagnose problem where shared memory can sometimes not be attached by postmaster children<br />
* [http://archives.postgresql.org/pgsql-general/2007-08/msg01377.php <nowiki>FATAL: could not reattach to shared memory (Win32)</nowiki>]<br />
* [http://archives.postgresql.org/message-id/13271.1241561721@sss.pgh.pa.us <nowiki>Re: "could not reattach to shared memory" captured in buildfarm</nowiki>]<br />
}}<br />
<br />
{{TodoItemDone<br />
|Fix locale-aware handling (e.g. monetary) for specific server/client encoding combinations<br />
* [http://archives.postgresql.org/pgsql-general/2009-04/msg00799.php <nowiki>trouble with to_char('L')</nowiki>]<br />
}}<br />
<br />
{{TodoItemDone<br />
|Reduce compiler warnings on 64-bit Windows<br />
* [http://archives.postgresql.org/pgsql-hackers/2008-07/msg00437.php <nowiki>Summary of some postgres portability issues</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-hackers/2008-07/msg00440.php <nowiki>Re: Windows 64-bit work in progress patch</nowiki>] }}<br />
<br />
{{TodoItemDone<br />
|Allow compilation using MSVC 2008<br />
* [http://archives.postgresql.org/pgsql-general/2009-08/msg01172.php <nowiki>Update /src/tools/msvc to VC++ 2008</nowiki>]<br />
}}<br />
<br />
{{TodoEndSubsection}}<br />
<br />
</div><br />
<br />
[[Category:Todo]]<br />
[[Category:PostgreSQL 9.0]]<br />
[[Category:Historical information]]</div>Boshomihttps://wiki.postgresql.org/index.php?title=TodoDone84&diff=17611TodoDone842012-05-19T23:29:17Z<p>Boshomi: </p>
<hr />
<div><div style="margin: 1ex 1em; float: right;"><br />
__TOC__<br />
</div><br />
<br />
This list contains '''all PostgreSQL bugs and features requests that were solved in 8.4'''. There is a [[Todo]] page too for '''bugs and features that are still not solved'''.<br />
<br />
<div style="padding: 1ex 4em;"><br />
== Administration ==<br />
<br />
{{TodoItemDone<br />
|Allow administrators to safely terminate individual sessions either via an SQL function or SIGTERM}}<br />
<br />
{{TodoItemDone<br />
|Add function to report the time of the most recent server reload}}<br />
<br />
{{TodoItemDone<br />
|Allow SSL client certificate names to be checked against the client hostname<br />
|This is already implemented in libpq/fe-secure.c::verify_peer_name_matches_certificate() but the code is commented out.. Fixed in M. Hagander commit 2008-11-13}}<br />
<br />
=== Configuration files ===<br />
{{TodoSubsection}}<br />
<br />
{{TodoItemDone<br />
|Issue a warning if a change-on-restart-only postgresql.conf value is modified and the server config files are reloaded}}<br />
<br />
{{TodoEndSubsection}}<br />
<br />
=== Statistics Collector ===<br />
{{TodoSubsection}}<br />
<br />
{{TodoItemDone<br />
|Reduce the frequency that the statistics file is written<br />
* http://archives.postgresql.org/pgsql-hackers/2008-09/msg00365.php<br />
}}<br />
<br />
{{TodoItemDone<br />
|Allow statistics file location to be user-configured<br />
* [http://archives.postgresql.org/pgsql-general/2007-12/msg00106.php <nowiki>Moving pgstat.stat and pgstat.tmp</nowiki>]<br />
}}<br />
<br />
{{TodoItemDone<br />
|Allow statistics collector information to be pulled from the collector process directly, rather than requiring the collector to write a filesystem file twice a second?}}<br />
<br />
{{TodoEndSubsection}}<br />
<br />
=== Point-In-Time Recovery (PITR) ===<br />
{{TodoSubsection}}<br />
<br />
{{TodoItemDone<br />
|Fix server restart problem when the server was shutdown during a PITR backup<br />
* [http://archives.postgresql.org/pgsql-hackers/2007-11/msg00800.php <nowiki>backup_label and server start</nowiki>]<br />
}}<br />
<br />
{{TodoItemDone<br />
|Recreate pg_xlog/archive_status/ if it doesn't exist after restoring from a PITR backup<br />
* [http://archives.postgresql.org/pgsql-hackers/2007-12/msg00487.php <nowiki>Recreating archive_status</nowiki>]<br />
}}<br />
<br />
{{TodoEndSubsection}}<br />
<br />
== Data Types ==<br />
<br />
{{TodoItemDone<br />
|Allow the UUID type to accept non-standard formats<br />
* [http://archives.postgresql.org/pgsql-hackers/2008-02/msg01214.php <nowiki>UUID data format 4x-4x-4x-4x-4x-4x-4x-4x</nowiki>]<br />
}}<br />
<br />
{{TodoItemDone<br />
|Simplify integer cross-data-type operators<br />
* [http://archives.postgresql.org/pgsql-bugs/2008-01/msg00189.php <nowiki>why provide cross type arithmetic operators</nowiki>]<br />
}}<br />
<br />
=== Dates and Times ===<br />
{{TodoSubsection}}<br />
<br />
{{TodoItemDone<br />
|Allow infinite dates just like infinite timestamps}}<br />
<br />
{{TodoItemDone<br />
|Add a GUC variable to allow output of interval values in ISO8601 format}}<br />
<br />
{{TodoItemDone<br />
|Extend timezone code to allow 64-bit values so we can represent years beyond 2038<br />
* [http://archives.postgresql.org/pgsql-hackers/2006-09/msg01363.php <nowiki>TODO item: update source/timezone for 64-bit tz files</nowiki>]<br />
}}<br />
<br />
{{TodoItemDone<br />
|Use LC_TIME for localized weekday/month names, rather than LC_MESSAGES<br />
* [http://archives.postgresql.org/pgsql-hackers/2006-11/msg00390.php <nowiki>Day and month name localization uses wrong locale category</nowiki>]<br />
}}<br />
<br />
{{TodoItemDone<br />
|Add ISO INTERVAL handling<br />
* [http://archives.postgresql.org/pgsql-hackers/2006-01/msg00250.php <nowiki>ISO 8601 Intervals</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-bugs/2006-04/msg00248.php <nowiki>Re: BUG #2403: Date arithemtic using INTERVAL in UPDATE command</nowiki>]<br />
}}<br />
<br />
{{TodoItemDone<br />
|Support ISO INTERVAL syntax if units cannot be determined from the string, and are supplied after the string<br />
|The SQL standard states that the units after the string specify the units of the string, e.g. INTERVAL '2' MINUTE should return '00:02:00'. The current behavior has the units restrict the interval value to the specified unit or unit range, INTERVAL '70' SECOND returns '00:00:10'.<br />
For syntax that isn't uniquely ISO or PG syntax, like '1' or '1:30', treat as ISO if there is a range specification clause, and as PG if there no clause is present, e.g. interpret '1:30' MINUTE TO SECOND as '1 minute 30 seconds', and interpret '1:30' as '1 hour, 30 minutes'.<br />
This makes common cases like SELECT INTERVAL '1' MONTH SQL-standard results. The SQL standard supports a limited number of unit combinations and doesn't support unit names in the string. The PostgreSQL syntax is more flexible in the range of units supported, e.g. PostgreSQL supports '1 year 1 hour', while the SQL standard does not.}}<br />
<br />
{{TodoItemDone<br />
|Add support for year-month syntax, INTERVAL '50-6' YEAR TO MONTH}}<br />
<br />
{{TodoItemDone<br />
|Round or truncate values to the requested precision, e.g. INTERVAL '11 months' YEAR should return one or zero}}<br />
<br />
{{TodoEndSubsection}}<br />
<br />
=== Arrays ===<br />
{{TodoSubsection}}<br />
<br />
{{TodoItemDone<br />
|Delay resolution of array expression's data type so assignment coercion can be performed on empty array expressions}}<br />
<br />
{{TodoEndSubsection}}<br />
<br />
== Functions ==<br />
<br />
{{TodoItemDone<br />
|Fix to_date()-related functions to consistently issue errors<br />
* [http://archives.postgresql.org/pgsql-hackers/2007-02/msg00915.php <nowiki>Invalid to_date patterns (was: [PATCHES] [GENERAL] ISO week dates)</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-bugs/2008-08/msg00163.php <nowiki>BUG #4372: TO_DATE with ISO week and day</nowiki>]<br />
}}<br />
<br />
{{TodoItemDone<br />
|Improve to_timestamp() handling of AM/PM, and error messages<br />
* http://archives.postgresql.org/pgsql-bugs/2008-09/msg00152.php<br />
* http://archives.postgresql.org/pgsql-hackers/2008-09/msg01718.php<br />
* http://archives.postgresql.org/pgsql-hackers/2009-01/msg00553.php<br />
}}<br />
<br />
{{TodoItemDone<br />
|Implement inlining of set-returning functions defined in SQL}}<br />
<br />
{{TodoItemDone<br />
|Allow SQL-language functions to return results from RETURNING queries<br />
* [http://archives.postgresql.org/pgsql-hackers/2006-10/msg00665.php <nowiki>SQL functions, INSERT/UPDATE/DELETE RETURNING, and triggers</nowiki>]<br />
}}<br />
<br />
{{TodoItemDone<br />
|Implement Boyer-Moore searching in strpos()<br />
* [http://archives.postgresql.org/pgsql-hackers/2008-09/msg00425.php <nowiki>Boyer-Moore strpos()</nowiki>]<br />
}}<br />
<br />
{{TodoItemDone<br />
|Add temporal versions of generate_series()<br />
* [http://archives.postgresql.org/pgsql-hackers/2007-04/msg01180.php <nowiki>Re: temporal variants of generate_series()</nowiki>]<br />
}}<br />
<br />
{{TodoItemDone<br />
|Add array_agg() and UNNEST functions for arrays<br />
* [http://archives.postgresql.org/pgsql-hackers/2007-08/msg00464.php <nowiki>Re: [GENERAL] array_to_set functions]</nowiki>]<br />
}}<br />
<br />
{{TodoItemDone<br />
|Fix all set-returning system functions so they support a wildcard target list<br />
|SELECT * FROM pg_get_keywords() works but SELECT * FROM pg_show_all_settings() does not.}}<br />
<br />
== Multi-Language Support ==<br />
<br />
{{TodoItemDone<br />
|Allow locale to be set at database creation<br />
|Currently locale can only be set during initdb. No global tables have locale-aware columns. However, the database template used during database creation might have locale-aware indexes. The indexes would need to be reindexed to match the new locale.}}<br />
<br />
== Views / Rules ==<br />
<br />
{{TodoItem<br />
|Improve ability to modify views via ALTER TABLE<br />
* [http://archives.postgresql.org/pgsql-hackers/2008-08/msg00300.php <nowiki>Re: patch: Add columns via CREATE OR REPLACE VIEW</nowiki>]<br />
}}<br />
<br />
== SQL Commands ==<br />
<br />
{{TodoItemDone<br />
|Add a separate TRUNCATE permission<br />
|Currently only the owner can TRUNCATE a table because triggers are not called, and the table is locked in exclusive mode.}}<br />
<br />
{{TodoItemDone<br />
|Change TRUNCATE to operate on an inheritance hierarchy by default, and add ONLY support to affect a single table<br />
* http://archives.postgresql.org/pgsql-hackers/2008-12/msg01627.php<br />
}}<br />
<br />
{{TodoItemDone<br />
|Improve failure message when DROP DATABASE is used on a database that has prepared transactions}}<br />
<br />
{{TodoItemDone<br />
|Add SQL:2008 Common Table Expression (WITH [RECURSIVE]) clause to SELECT<br />
* [[CTEReadme]]<br />
* [http://archives.postgresql.org/pgsql-hackers/2007-01/msg01375.php <nowiki>Recursive query syntax ambiguity</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-hackers/2008-02/msg00642.php <nowiki>RFP: Recursive query in 8.4</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-patches/2007-03/msg00139.php <nowiki>non-recursive WITH clause support</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-hackers/2007-11/msg01334.php <nowiki>Re: PostGreSQL and recursive queries...</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-patches/2008-01/msg00105.php <nowiki>[8.4] Updated WITH clause patch (non-recursive)</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-patches/2008-03/msg00327.php <nowiki>Re: [8.4] Updated WITH clause patch (non-recursive)</nowiki>]<br />
}}<br />
<br />
{{TodoItemDone<br />
|Implement SQL:2008 window functions<br />
* [http://archives.postgresql.org/pgsql-hackers/2008-06/msg00380.php <nowiki>proposal: add window function to 8.4</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-hackers/2008-07/msg00232.php <nowiki>introduction of WIP window function patch</nowiki>]<br />
}}<br />
<br />
{{TodoItemDone<br />
|Increase locking when DROPing objects so dependent objects cannot get dropped while the DROP operation is happening<br />
* [http://archives.postgresql.org/pgsql-hackers/2007-01/msg00937.php <nowiki>DROP FUNCTION failure: cache lookup failed for relation X</nowiki>]<br />
}}<br />
<br />
{{TodoItemDone<br />
|Allow AS in &quot;SELECT col AS label&quot; to be optional in certain cases}}<br />
<br />
{{TodoItemDone<br />
|Improve reporting of UNION type mismatches<br />
* [http://archives.postgresql.org/pgsql-hackers/2007-04/msg00944.php <nowiki>Better error message for select_common_type()</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-hackers/2008-03/msg00597.php <nowiki>Re: Better error message for select_common_type()</nowiki>]<br />
}}<br />
<br />
<br />
=== ALTER ===<br />
{{TodoSubsection}}<br />
<br />
{{TodoItemDone<br />
|Allow databases to be moved to different tablespaces}}<br />
<br />
{{TodoItemDone<br />
|Prevent parent tables from altering or dropping constraints like CHECK that are inherited by child tables unless CASCADE is used}}<br />
<br />
{{TodoItemDone<br />
|Prevent child tables from altering or dropping constraints like CHECK that were inherited from the parent table}}<br />
<br />
{{TodoEndSubsection}}<br />
<br />
=== CLUSTER ===<br />
{{TodoSubsection}}<br />
<br />
{{TodoItemDone<br />
|Add VERBOSE option to report tables as they are processed, like VACUUM VERBOSE}}<br />
<br />
{{TodoEndSubsection}}<br />
<br />
=== COPY ===<br />
{{TodoSubsection}}<br />
<br />
{{TodoItemDone<br />
|Consider using a ring buffer for COPY FROM<br />
* [http://archives.postgresql.org/pgsql-patches/2008-02/msg00140.php <nowiki>Bulk Insert tuning</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-hackers/2008-02/msg01080.php <nowiki>Bulk loading performance improvements</nowiki>]<br />
}}<br />
<br />
{{TodoEndSubsection}}<br />
<br />
=== GRANT/REVOKE ===<br />
{{TodoSubsection}}<br />
<br />
{{TodoItemDone<br />
|Allow column-level privileges}}<br />
<br />
{{TodoEndSubsection}}<br />
<br />
== Server-Side Languages ==<br />
<br />
=== PL/pgSQL ===<br />
{{TodoSubsection}}<br />
<br />
{{TodoItemDone<br />
|Add CASE capability to language (already in SQL)<br />
* [http://archives.postgresql.org/pgsql-hackers/2008-01/msg00696.php <nowiki>proposal for 8.4: PL/pgSQL - statement CASE</nowiki>]<br />
}}<br />
<br />
{{TodoItemDone<br />
|Add translations for PL/pgSQL error messages<br />
* http://archives.postgresql.org/pgsql-hackers/2008-09/msg00336.php<br />
}}<br />
<br />
{{TodoItemDone<br />
|Rethink memory management for simple expression evaluation<br />
* http://archives.postgresql.org/pgsql-bugs/2009-02/msg00153.php<br />
}}<br />
<br />
{{TodoItemDone<br />
|Consider honoring standard_conforming_strings in function bodies<br />
* http://archives.postgresql.org/pgsql-bugs/2008-03/msg00102.php<br />
* http://archives.postgresql.org//pgsql-hackers/2009-04/msg00512.php<br />
}}<br />
<br />
{{TodoEndSubsection}}<br />
<br />
=== psql ===<br />
{{TodoSubsection}}<br />
<br />
{{TodoItemDone<br />
|Have psql show current values for a sequence}}<br />
<br />
{{TodoItemDone<br />
|Have \d show foreign keys that reference a table's primary key<br />
|<br />
* [http://archives.postgresql.org/pgsql-hackers/2007-04/msg00424.php <nowiki>Idle idea for a feature</nowiki>]<br />
}}<br />
<br />
{{TodoItemDone<br />
|Have \l+ show database size, if permissions allow<br />
|Ideally it will not generate an error for invalid permissions}}<br />
<br />
{{TodoItemDone<br />
|Improve display of enums to show valid enum values}}<br />
<br />
{{TodoEndSubsection}}<br />
<br />
=== pg_dump / pg_restore ===<br />
{{TodoSubsection}}<br />
<br />
{{TodoItemDone<br />
|Allow pg_restore to utilize multiple CPUs and I/O channels by restoring multiple objects simultaneously<br />
|This might require a pg_restore flag to indicate how many simultaneous operations should be performed. Only pg_dump's -Fc format has the necessary dependency information. <br />
* [http://archives.postgresql.org/pgsql-hackers/2008-02/msg00963.php <nowiki>Re: 8.3 / 8.2.6 restore comparison</nowiki>]<br />
}}<br />
<br />
{{TodoItemDone<br />
|To better utilize resources, allow pg_restore to check foreign keys simultaneously, where possible}}<br />
<br />
{{TodoItemDone<br />
|Allow pg_restore to create all indexes of a table concurrently, via a single heap scan<br />
|This requires a pg_dump -Fc file because that format contains the required dependency information. <br />
* [http://archives.postgresql.org/pgsql-general/2007-05/msg01274.php <nowiki>Re: why postgresql over other RDBMS</nowiki>]<br />
}}<br />
<br />
{{TodoItemDone<br />
|Prevent pg_dump/pg_restore from being affected by statement_timeout<br />
|Using psql to restore a pg_dump dump is also affected.}}<br />
<br />
{{TodoEndSubsection}}<br />
<br />
=== ecpg ===<br />
{{TodoSubsection}}<br />
<br />
{{TodoItemDone<br />
|Use backend PREPARE/EXECUTE facility for ecpg where possible}}<br />
<br />
{{TodoItemDone<br />
|Add internationalized message strings}}<br />
<br />
{{TodoEndSubsection}}<br />
<br />
=== libpq ===<br />
{{TodoSubsection}}<br />
<br />
{{TodoItemDone<br />
|Fix libpq initialization to play nicely with applications that use libcrypto but not libssl<br />
* [http://archives.postgresql.org//pgsql-hackers/2009-01/msg02488.php PQinitSSL broken in some use cases]<br />
* [http://archives.postgresql.org/message-id/b42b73150902100857l3377bf8geafccb6392f6d129@mail.gmail.com Re: PQinitSSL broken in some use cases]<br />
}}<br />
<br />
{{TodoEndSubsection}}<br />
<br />
== Triggers ==<br />
<br />
{{TodoItemDone<br />
|Add ability to trigger on TRUNCATE}}<br />
<br />
== Inheritance ==<br />
<br />
{{TodoItemDone<br />
|Allow SELECT ... FOR UPDATE on inherited tables}}<br />
<br />
{{TodoItemDone<br />
|Require all CHECK constraints to be inherited<br />
* [http://archives.postgresql.org/pgsql-bugs/2007-04/msg00026.php <nowiki>Problem identifying constraints which should not be inherited</nowiki>]<br />
}}<br />
<br />
{{TodoItemDone<br />
|Add checks to prevent a CREATE RULE views on inherited tables<br />
* [http://archives.postgresql.org/pgsql-general/2008-02/msg01420.php <nowiki>Re: partitioning using dblink</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-general/2008-03/msg00077.php <nowiki>Re: partitioning using dblink</nowiki>]<br />
}}<br />
<br />
== Indexes ==<br />
<br />
{{TodoItemDone<br />
|Increase the default and maximum number of statistics targets<br />
* [http://archives.postgresql.org/pgsql-general/2007-05/msg01228.php <nowiki>Re: index vs. seq scan choice?</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-general/2007-06/msg00542.php <nowiki>Re: index vs. seq scan choice?</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-hackers/2008-01/msg01066.php <nowiki>Re: [PATCHES] Better default_statistics_target</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-hackers/2008-03/msg00188.php <nowiki>Maximum statistics target</nowiki>]<br />
* http://archives.postgresql.org/pgsql-hackers/2008-11/msg00923.php<br />
}}<br />
<br />
=== Hash ===<br />
{{TodoSubsection}}<br />
<br />
{{TodoItemDone<br />
|Consider sorting hash buckets so entries can be found using a binary search, rather than a linear scan}}<br />
<br />
{{TodoItemDone<br />
|In hash indexes, consider storing the hash value with or instead of the key itself}}<br />
<br />
{{TodoItemDone<br />
|During index creation, pre-sort the tuples to improve build speed}}<br />
<br />
{{TodoEndSubsection}}<br />
<br />
== Sorting ==<br />
<br />
{{TodoItemDone<br />
|Consider using hash buckets to do DISTINCT, rather than sorting<br />
|This would be beneficial when there are few distinct values. This is already used by GROUP BY.}}<br />
<br />
{{TodoItemDone<br />
|Avoid some tuple copying in sort routines}}<br />
<br />
== Vacuum ==<br />
<br />
{{TodoItemDone<br />
|Create a bitmap of pages that need vacuuming<br />
|Instead of sequentially scanning the entire table, have the background writer or some other process record pages that have expired rows, then VACUUM can look at just those pages rather than the entire table. In the event of a system crash, the bitmap would probably be invalidated. One complexity is that index entries still have to be vacuumed, and doing this without an index scan (by using the heap values to find the index entry) might be slow and unreliable, especially for user-defined index functions.<br />
* [http://archives.postgresql.org/pgsql-hackers/2006-12/msg01188.php <nowiki>Dead Space Map for vacuum</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-hackers/2007-01/msg00121.php <nowiki>Re: Dead Space Map for vacuum</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-patches/2007-03/msg00508.php <nowiki>Dead Space Map version 3 (simplified)</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-patches/2007-04/msg00347.php <nowiki>Re: Dead Space Map version 3 (simplified)</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-hackers/2007-11/msg00156.php <nowiki>Re: Visibility map thoughts</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-hackers/2008-03/msg00546.php <nowiki>Re: Rewriting Free Space Map</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-hackers/2008-04/msg00416.php <nowiki>Re: Free Space Map data structure</nowiki>]<br />
}}<br />
<br />
{{TodoItemDone<br />
|Improve dead row detection during multi-statement transactions usage<br />
* [http://archives.postgresql.org/pgsql-patches/2007-03/msg00358.php <nowiki>Improvement of procArray.xmin for VACUUM</nowiki>]<br />
}}<br />
<br />
=== Auto-vacuum ===<br />
{{TodoSubsection}}<br />
<br />
{{TodoItemDone<br />
|Improve control of auto-vacuum<br />
* [http://archives.postgresql.org/pgsql-hackers/2006-12/msg00876.php <nowiki>Interface for pg_autovacuum</nowiki>]<br />
}}<br />
<br />
{{TodoItemDone<br />
|Store per-table autovacuum settings in pg_class.reloptions.<br />
* [http://archives.postgresql.org/pgsql-hackers/2007-02/msg01440.php <nowiki>Re: [GENERAL] pg_autovacuum should allow NULL values</nowiki>]<br />
* [http://archives.postgresql.org/pgsql-hackers/2008-01/msg00724.php <nowiki>Simple thing to make pg_autovacuum more useful</nowiki>]<br />
}}<br />
<br />
{{TodoEndSubsection}}<br />
<br />
== Miscellaneous Performance ==<br />
<br />
{{TodoItemDone<br />
|Expire published xmin for read-only and idle transactions<br />
* [http://archives.postgresql.org/pgsql-hackers/2007-09/msg00343.php <nowiki>Re: Low hanging fruit in lazy-XID-assignment patch?</nowiki>]<br />
}}<br />
<br />
{{TodoItemDone<br />
|Improve performance of shared invalidation queue for multiple CPUs<br />
* [http://archives.postgresql.org/pgsql-performance/2008-01/msg00023.php <nowiki>Re: Linux/PostgreSQL scalability issue - problem with 8 cores</nowiki>]<br />
}}<br />
<br />
== Source Code ==<br />
<br />
{{TodoItemDone<br />
|Have configure choose integer datetimes by default<br />
* [http://archives.postgresql.org/pgsql-patches/2007-05/msg00046.php <nowiki>Enable integer datetimes by default</nowiki>]<br />
}}<br />
<br />
{{TodoItemDone<br />
|Consider allowing 64-bit integers and floats to be passed by value on 64-bit platforms<br />
|Also change 32-bit floats (float4) to be passed by value at the same time.}}<br />
<br />
{{TodoItemDone<br />
|Remove use of MAKE_PTR and MAKE_OFFSET macros<br />
* [http://archives.postgresql.org/pgsql-general/2007-08/msg01510.php <nowiki>Re: FATAL: could not reattach to shared memory (Win32)</nowiki>]<br />
}}<br />
<br />
{{TodoItemDone<br />
|Remove old-style routines for manipulating tuples<br />
* [http://archives.postgresql.org/pgsql-hackers/2007-10/msg00851.php <nowiki>Deprecating heap_formtuple/heap_modifytuple/heap_deformtuple</nowiki>]<br />
}}<br />
<br />
=== Windows ===<br />
{{TodoSubsection}}<br />
<br />
{{TodoItemDone<br />
|Remove psql newline patch when we find out why mingw outputs an extra newline}}<br />
<br />
{{TodoItemDone<br />
|Prevent SSL from sending network packets to avoid interference with Win32 signal emulation<br />
* [http://archives.postgresql.org/pgsql-hackers/2007-12/msg00455.php <nowiki> Re: [pgsql-es-ayuda] SLL error 100% cpu]</nowiki>]<br />
}}<br />
<br />
{{TodoEndSubsection}}<br />
<br />
</div><br />
<br />
[[Category:Todo]]<br />
[[Category:PostgreSQL 8.4]]<br />
[[Category:Historical information]]</div>Boshomihttps://wiki.postgresql.org/index.php?title=Category:PostgreSQL_Europe&diff=17610Category:PostgreSQL Europe2012-05-19T23:27:33Z<p>Boshomi: +cat</p>
<hr />
<div>Here are pages directly related to PostgreSQL Europe, some of which have simply been migrated from the old PostgreSQL Europe wiki (now discontinued).<br />
<br />
[[Category:PostgreSQL Events]][[Category:Users group]]</div>Boshomihttps://wiki.postgresql.org/index.php?title=Category:PostgreSQL_Version&diff=17609Category:PostgreSQL Version2012-05-19T23:26:05Z<p>Boshomi: +cat</p>
<hr />
<div>PostgreSQL Version<br />
<br />
[[Category:Documentation]]</div>Boshomihttps://wiki.postgresql.org/index.php?title=Category:PgWiki:Templates&diff=17608Category:PgWiki:Templates2012-05-19T23:25:07Z<p>Boshomi: +cat</p>
<hr />
<div>Main category for PostgreSQL Templates<br />
<br />
[[Category:Main]]</div>Boshomihttps://wiki.postgresql.org/index.php?title=Category:Historical_information&diff=17607Category:Historical information2012-05-19T23:23:14Z<p>Boshomi: </p>
<hr />
<div>Historical information and deprecated articles<br />
<br />
[[Category:Main]]</div>Boshomihttps://wiki.postgresql.org/index.php?title=Category:Help&diff=17606Category:Help2012-05-19T23:22:15Z<p>Boshomi: +cat</p>
<hr />
<div>Online Help<br />
<br />
[[Category:Main]]</div>Boshomihttps://wiki.postgresql.org/index.php?title=Category:Software_Ports&diff=17605Category:Software Ports2012-05-19T23:21:16Z<p>Boshomi: +cat</p>
<hr />
<div>== Software Ports ==<br />
<br />
Many open source projects need your help so that can work with PostgreSQL.<br />
<br />
This category tracks such projects; please see individual pages for details on each project's porting status.<br />
<br />
[[Category:Documentation]]</div>Boshomihttps://wiki.postgresql.org/index.php?title=Category:Asking_Questions&diff=17604Category:Asking Questions2012-05-19T23:19:49Z<p>Boshomi: +cat</p>
<hr />
<div>Asking Questions<br />
<br />
[[Category:Main]]</div>Boshomihttps://wiki.postgresql.org/index.php?title=Category:Languages&diff=17603Category:Languages2012-05-19T23:18:53Z<p>Boshomi: +cat</p>
<hr />
<div>A category for languages that code snippets can be written in.<br />
<br />
== See also ==<br />
<br />
[[Snippets]]<br />
<br />
[[Category:Documentation]]</div>Boshomihttps://wiki.postgresql.org/index.php?title=Category:Main&diff=17602Category:Main2012-05-19T23:13:48Z<p>Boshomi: Categroy to itself</p>
<hr />
<div>[[Main Page]]<br />
<br />
[[Category:Main]]</div>Boshomihttps://wiki.postgresql.org/index.php?title=Category:PgWiki:Templets&diff=17601Category:PgWiki:Templets2012-05-19T23:12:44Z<p>Boshomi: + DELETE ME</p>
<hr />
<div>Templets in PostgreSQL Wiki<br />
<br />
[[Category:DELETEME]]</div>Boshomihttps://wiki.postgresql.org/index.php?title=Category:%E4%B8%AD%E6%96%87&diff=17600Category:中文2012-05-19T23:11:11Z<p>Boshomi: new</p>
<hr />
<div>[[Category:Chinese]]</div>Boshomihttps://wiki.postgresql.org/index.php?title=Category:Operating_system&diff=17599Category:Operating system2012-05-19T23:10:18Z<p>Boshomi: </p>
<hr />
<div>Articles specific for a operating system <br />
<br />
[[Category:Asking Questions]]</div>Boshomihttps://wiki.postgresql.org/index.php?title=Category:Operating_system&diff=17598Category:Operating system2012-05-19T23:09:59Z<p>Boshomi: new</p>
<hr />
<div>Articles specific for a operating system <br />
<br />
[[Category:Asking Question]]</div>Boshomihttps://wiki.postgresql.org/index.php?title=Category:Historical_information&diff=17597Category:Historical information2012-05-19T23:07:47Z<p>Boshomi: +cat</p>
<hr />
<div>Historical information and deprecated articles<br />
<br />
[[Category Main]]</div>Boshomihttps://wiki.postgresql.org/index.php?title=Category:Indexes&diff=17596Category:Indexes2012-05-19T23:05:30Z<p>Boshomi: new</p>
<hr />
<div>Articles relating to Indexes<br />
<br />
[[Category:SQL]]</div>Boshomihttps://wiki.postgresql.org/index.php?title=Category:Howto&diff=17595Category:Howto2012-05-19T23:04:12Z<p>Boshomi: +cat</p>
<hr />
<div>How to do help pages<br />
<br />
[[Category:Asking Questions]]</div>Boshomihttps://wiki.postgresql.org/index.php?title=Category:Main&diff=17594Category:Main2012-05-19T23:02:08Z<p>Boshomi: Created page with "Main Page"</p>
<hr />
<div>[[Main Page]]</div>Boshomihttps://wiki.postgresql.org/index.php?title=Category:Documentation&diff=17593Category:Documentation2012-05-19T23:01:05Z<p>Boshomi: +cat</p>
<hr />
<div>Documentations<br />
<br />
[[Category:Main]]</div>Boshomihttps://wiki.postgresql.org/index.php?title=Category:Community&diff=17592Category:Community2012-05-19T23:00:16Z<p>Boshomi: +cat</p>
<hr />
<div>The PostgreSQL Community<br />
<br />
[[Category:Main]]</div>Boshomihttps://wiki.postgresql.org/index.php?title=Category:Advocacy&diff=17591Category:Advocacy2012-05-19T22:58:59Z<p>Boshomi: +cat</p>
<hr />
<div>= Advocacy Category =<br />
<br />
This category gathers every pages of advocacy effort.<br />
<br />
You can also check out the sub-categories :<br />
<br />
[[Category:Main]]</div>Boshomihttps://wiki.postgresql.org/index.php?title=Category:PgWiki_Translations&diff=17590Category:PgWiki Translations2012-05-19T22:58:15Z<p>Boshomi: +cat</p>
<hr />
<div>PgWiki in not english languages<br />
<br />
[[Category:Main]]</div>Boshomihttps://wiki.postgresql.org/index.php?title=Category:General_articles_and_guides&diff=17589Category:General articles and guides2012-05-19T22:56:54Z<p>Boshomi: new</p>
<hr />
<div>General articles and guides<br />
<br />
[[Category:Main]]</div>Boshomihttps://wiki.postgresql.org/index.php?title=Category:PgWiki:Templates&diff=17588Category:PgWiki:Templates2012-05-19T22:54:23Z<p>Boshomi: new</p>
<hr />
<div>Main category for PostgreSQL Templates</div>Boshomihttps://wiki.postgresql.org/index.php?title=Estimating_Distinct&diff=17587Estimating Distinct2012-05-19T22:49:53Z<p>Boshomi: +cat</p>
<hr />
<div>__NOTOC__<br />
<br />
This page describes possible ways to improve estimates of number of distinct values. Originally this was a side-effect of an [http://wiki.postgresql.org/wiki/Cross_Columns_Stats effort to implement cross-column statistics] as one of the proposed approaches needs more precise distinct estimates, but as it's somehow separate effort I've created a separate page.<br />
<br />
== Sampling based estimators ==<br />
<br />
The traditional estimators in statistics are based on small sample (say 1% of the population). This works quite well except in case of distinct values, where it fails unless a very large portion of the table is sampled (see the following section).<br />
<br />
== Charikar and Chaudhuri ==<br />
<br />
In their paper (published in 2000), they stated and proved that a estimators based on sampling are a dead-end. The theorem they proved (Theorem 1) basically says that for every estimate based on a small-sample, there's a data set where the ratio error can be made arbitrarily large. The theorem is a bit more complicated (relates the size of the sample, maximal error and the probability of getting such data set), but it the end it says that you can't get a good estimator based on a small sample. And if you replace one estimator with another one, you may fix behavior for one data set, but there is another one.<br />
<br />
JOSH BERKUS: Sorry, that paper does NOT say the above. Read it again. It says that perfect sample-based estimates are impossible ... but so are perfect steam-based estimates. In general, the paper says that you can reduce the sample size required or the error rate by knowing enough to choose a sample algorithm based on the expected distribution type of the error, and that reducing the error rate is difficult without this knowledge. Also, I'll note that 2000 was hardly the end of sample estimation papers.<br />
<br />
They provide "optimal estimator" that consistently reaches the lower bound of the ratio error, but in general there are better estimators (although for some data sets they fail much harder).<br />
<br />
TOMAS VONDRA: But that's exactly the point of that theorem. They basically say "for each estimator based on a sample, we'll give you a data set where it fails with error inverse proportional to the sample size (i.e. the smaller the sample, the bigger the error)." Sure, there are estimators that perform better than the proposed "optimal estimator" for some inputs, but the beauty (and purpose) of the optimal estimator is that it's consistent for all possible data sets.<br />
<br />
== Stream based estimators ==<br />
<br />
Databases are not the only field where number of distinct values is needed - another field that needs this is data stream analysis. The proposed estimators are based on one pass through the data with incremental updates of a bitmap - the first such estimator was based on probabilistic counting, the next one on Wegman's adaptive sampling etc. In 2010 an algorithm with arbitrary precision and O(log(n)) space complexity was described - that's very promising.<br />
<br />
It's very similar to [http://en.wikipedia.org/wiki/Bloom_filter Bloom filter], but the Bloom filter needs more space and provides more information - it's designed to identify elements of the set (in this case distinct values). Which is not the case of bitmaps used in probabilistic counting etc.<br />
<br />
A very interesting approach, called Distinct sampling, was described by Gibbons in 2001. Don't be confused by the 'sampling' - it's not a random sampling, it is based on adaptive selection of a sample during one pass through the data (the principle is very similar to the Wegman's adaptive sampling). This algorithm needs much more space, but it can give estimates to question like 'how many distinct values satisfies predicate P' which is not possible with the 'simple' algorithms.<br />
<br />
So this is much more interesting, but there are a few drawbacks. First, these estimators require one pass through the data (and then incremental updates), which is completely different from the current estimators. Second, these estimators are designed for 'data streams' where there are no deletes by default. Some of the algorithms do actually describe some solution.<br />
<br />
== Papers ==<br />
<br />
This is a list of papers relevant to distinct estimation, classified into three sections. The papers are always sorted from newest to the oldest. If you know about an interesting paper not listed here, feel free to add it here.<br />
<br />
=== Sampling papers ===<br />
<br />
# '''Towards Estimation Error Guarantees for Distinct Values''' [http://ftp.cse.buffalo.edu/users/azhang/disc/disc01/cd1/out/papers/pods/towardsestimatimosur.pdf PDF]<br />
#* published: 2000<br />
#* authors: Moses Charikar, Surajit Chaudhuri, Rajeev Motwani, Vivek Narasayya<br />
#* presents a proof that with a limited sample, you really can't get a precise estimate (with limited error)<br />
#* in other words: for each estimator based on a limited sample, there's a probability distribution where the estimator fails spectacularly<br />
#* so to get a good estimate, you really need to sample most of the table (almost all of it)<br />
#* they provide an "optimal estimator" (a hybrid estimator composed of several simple estimators) in the sense that it reaches the lowest possible error (among sampling based estimators)<br />
# '''Estimating the Number of Classes in a Finite Population''' [http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.93.8637 citeseerx] [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.93.8637&rep=rep1&type=pdf PDF]<br />
#* published: 1996<br />
#* authors: Peter J. Haas, Lynne Stokes<br />
#* presents several sampling-based estimators, we're currently using one of them (D_uj1)<br />
# '''Sampling-Based Estimation of the Number of Distinct Values of an Attribute''' [http://www.vldb.org/conf/1995/P311.PDF PDF]<br />
#* published: 1995<br />
#* authors: Peter J. Haas, Jeffrey F. Naughtont, S. Seshadrit, Lynne Stokes<br />
#* presents several sampling-based estimators, compares them etc.<br />
#* this is a year older that the article from Hass/Stokes, so read that one instead<br />
<br />
=== Stream papers ===<br />
<br />
# '''An Optimal Algorithm for the Distinct Elements Problem''' [http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.163.375 citeseerx] [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.163.375&rep=rep1&type=pdf PDF]<br />
#* published: 2010 (PODS’10, June 6–11, 2010)<br />
#* authors: Daniel M. Kane, Jelani Nelson, David P. Woodruff<br />
#* basically an improved version of the "probabilistic counting" (see the paper by P. Flajolet and G. N. Martin)<br />
#* they present an algorithm with O(log(n)) bits of space and O(1) update complexity<br />
#* the precision may be improved by combining several such estimators<br />
# '''Distinct-Values Estimation over Data Streams''' [http://www.pittsburgh.intel-research.net/people/gibbons/talks-surveys/Distinct-Values-Estimation-over-Data-Streams-PBGibbons.pdf PDF]<br />
#* published: 2009<br />
#* author: Phillip B. Gibbons <br />
#* this is a quite nice summary of the possible approaches - a short paragraph about sampling-based algorithms and why this is a dead-end, a more thorough analysis of streaming based algorithms (Flajolet-Martin probabilistic counting algorithm and then another algorithm from Alon, Matias and Szegedy) and then a section about "coordinated sampling"<br />
#* there is a very nice table of various algorithms summarizing their features (if there is a sample of distinct values, if deletions are handled somehow etc.)<br />
# '''Distinct Counting with a Self-Learning Bitmap''' [http://ect.bell-labs.com/who/aychen/sbitmap4p.pdf PDF]<br />
#* published: 2009<br />
#* authors: Aiyou Chen, Jin Cao<br />
#* they describe an algorithm that performs adaptive sampling using a bitmap<br />
#* the algorithm is based on Markov chain model, but in general it seems similar to the Wegman's adaptive sampling (see the paper from 1990)<br />
# '''Distinct Sampling for Highly-Accurate Answers to Distinct Values Queries and Event Reports''' [http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.145.550 citeseerx] [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.145.550&rep=rep1&type=pdf PDF]<br />
#* published: 2001<br />
#* author: Phillip B. Gibbons <br />
#* although the title says "sampling" this paper is not about a traditional sampling (collecting a small random sample from a table and then computing an estimate from it), it's about collecting a sample from a stream of data (one pass through the table) and choosing a "distinct sample"<br />
#* this does not provide just an estimate on number of distinct rows, but estimate for distinct values for arbitrary predicate on the row<br />
#* seems very interesting, although it needs much more span than the other 'probabilistic counting' algoritms<br />
# '''On Adaptive Sampling''' [http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.52.1548 citeseerx] [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.52.1548&rep=rep1&type=pdf PDF]<br />
#* published: 1990<br />
#* authors: Philippe Flajolet<br />
#* presents an algorithm alternative to probabilistic counting, based on Wegman's Adaptive Sampling<br />
#* this algorithm is less precise than the original probabilistic counting algorithm, but is better for small files (unbiased)<br />
# '''Probabilistic Counting Algorithms for Data Base Applications''' [http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.12.7100 citeseerx] [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.12.7100&rep=rep1&type=pdf PDF]<br />
#* published: 1985<br />
#* authors: Philippe Flajolet, G. Nigel Martin<br />
#* this is the first paper on this topic, describes a basic algorithm and an improved "stochastic" version (PCSA)<br />
#* includes quite thorough proofs of theorems, etc.<br />
<br />
=== Related papers ===<br />
<br />
# '''Towards Estimating the Number of Distinct Value Combinations for a Set of Attributes''' [http://www.yorku.ca/xhyu/publications/cikm05.pdf PDF]<br />
#* published: 2005<br />
#* authors: Xiaohui Yu, Calisto Zuzarte, Kenneth C. Sevcik<br />
#* this paper is not about estimating number of distinct values for individual columns, but for combination of multiple columns using knowledge of their distribution (or an approximation in the form of histogram)<br />
#* the algorithm they propose is called COLSCARD<br />
#* a big disadvantage of the paper is that they assume independence of the columns, but it seems this could be solved using a multi-dimensional histogram (just replace the multiplication of distributions with the value from histogram)<br />
#* could be a way if we can't use some 'streaming' solution (in that case we could rather easily collect data not just about individual columns but about an interesting combination too)<br />
<br />
<br />
[[Category:Feature request]]</div>Boshomihttps://wiki.postgresql.org/index.php?title=Cross_Columns_Stats&diff=17586Cross Columns Stats2012-05-19T22:49:37Z<p>Boshomi: +cat</p>
<hr />
<div>__NOTOC__<br />
<br />
This page is an overview of an attempt to implement cross-column statistics, i.e. an effort to enhance the optimizer so that it can perform better in case the columns of a table are not independent. You'll find examples of fail cases here, ideas on how the solution might work, links to papers on this topic, etc.<br />
<br />
Most of the information listed comes from the discussions on a mailing list (especially [http://archives.postgresql.org/pgsql-hackers/2010-12/msg00913.php this thread]), but it's quite difficult to follow the topic once it reaches some size. So from this point of view, this page is just an easily readable summary.<br />
<br />
== Possible road-map ==<br />
<br />
Simply said, there is no clear road-map, rather a general direction that may suddenly change. The current intent is to build a set of proof of concepts, attempting to build various possibilities, and then maybe a contrib module for estimating COUNT(*) results (which is very useful for pagination). And then, if everything works fine, this might be eventually used within the core.<br />
<br />
== Attribute Value Independence assumption ==<br />
<br />
The attribute value independence assumption is the root cause of the problems - it's equivalent to the [http://en.wikipedia.org/wiki/Statistical_independence statistical independence] of columns. According to this assumption, the [http://en.wikipedia.org/wiki/Joint_distribution joint distribution] is equal to multiplication of the probability distributions of individual columns.<br />
<br />
When the columns are not statistically independent, this usually leads to severe underestimate of the number of rows. And in reality, columns are almost never independent. The question is how strong the dependence actually is.<br />
<br />
Let's see a real-world example.<br />
<br />
== Example ==<br />
<br />
A typical fail case is a table with ZIP codes and city names. Those two columns are highly dependent, as a ZIP code generally determines a city.<br />
<br />
Assume there are 100 cities, each of them has 100 ZIP codes. That means there are 100 cities and 10.000 ZIP codes. When estimating a number of rows satisfying a condition <br />
<br />
<pre>WHERE zip_code = '12345' AND city = 'cityname'</pre><br />
<br />
the optimizer currently does this<br />
<br />
# estimates the selectivity of "zip_code = '12345'" (assuming uniform distribution, the selectivity is 1/10.000 = 0.01%)<br />
# estimates the selectivity of "city = 'cityname'" (assuming uniform distribution, the selectivity is 1/100 = 1%)<br />
# multiplies the selectivities and gets selectivity 0.0001%<br />
<br />
The problem is the actual selectivity is 0.01%, as the ZIP code implies the city. So the obtained estimate will be 100x underestimated. And by combining more conditions, this might lead to even worse estimates. This may be serious issue, as the planner might decide to use an index scan instead of a sequential scan in such cases. And with a complicated query, the effects are sometimes very difficult to predict.<br />
<br />
All this is due to "attribute value independence" which is basically the same as [http://en.wikipedia.org/wiki/Independence_(probability_theory) statistical independence] in probability theory.<br />
<br />
If you need a real-world sample data to play with, try [http://www.census.gov/geo/www/tiger/zip1999.html 1999 U.S. Postal Service ZIP Codes] (or directly [http://www.census.gov/geo/www/tiger/zip1999.zip ZIP]). It's not exactly fresh, but it's good enough. It's in DBF format so you'll need to use something to extract the data (e.g. [http://pgdbf.sourceforge.net PgDBF]).<br />
<br />
== Assumptions, assumptions, assumptions ... ==<br />
<br />
When collecting stats and using them to estimate the number of rows, there is always some assumption that says "if this holds, then the estimate should not be very far from the actual value." The problem is real-world data sets almost never satisfy these assumptions perfectly.<br />
<br />
One example of such assumption - attribute value independence assumption (AVI) - was already mentioned above, along with a fail case. But there are several other assumptions, some of them are used at a different place, some of them are a possible replacement for the AVI assumption. Just a very short list<br />
<br />
* '''uniform distribution''' within a histogram bin - the optimizer assumes that within a histogram bin, the values are uniformly distributed<br />
* '''uniform correlation''' - instead of independence, it's assumed that ''P(A=a|B=b)=c'' (constant), so that ''P(A=a,B=b)=P(A=a|B=b)*P(B=b)=c*P(B=b)''<br />
* '''conditional independence''' - this is a bit more complicated, see for example the paper ''Selectivity Estimation using Probabilistic Models'' [4]<br />
<br />
The idea is to replace a very strong assumption (e.g. AVI) with a much weaker one (e.g. the uniform correlation or conditional independence). Breaking a weaker assumption usually results in a much smaller error of the estimate.<br />
<br />
== Instances of the problem ==<br />
<br />
As I've explained in [http://archives.postgresql.org/pgsql-hackers/2010-12/msg01623.php this post], I think there are four very different instances of this problem. Maybe there is a 'unified theory' that handles all of them, but I'm not aware of it. So what instances are there?<br />
<br />
First, there are two quite different types of variables (columns) - numeric and discrete. And by discrete I don't mean integers, but values that serve as a label - names (city, person) are an excellent example. Discrete columns may be actually encoded as numbers, as for example ZIP codes. At first sight these types may seem equal, but that really is not the case - you can do a lot of things with numeric values that either can't be done at all with discrete values or the result does not make much sense. For example subtracting ZIP codes, computing average of city names, and so on.<br />
<br />
Second, there are two types of conditions - equality and inequality (range) conditions. These two types of conditions usually need different types of stats, so let's handle them separately.<br />
<br />
So in the end, there are four distinct instances of the problem:<br />
<br />
{| cellpadding="5" cellspacing="0" border="1"<br />
|<br />
|'''equality conditions'''<br />
|'''inequality conditions'''<br />
|-<br />
|'''discrete values'''<br />
|A<br />
|D<br />
|-<br />
|'''numeric values'''<br />
|C<br />
|B<br />
|}<br />
<br />
=== A) Discrete values and equality conditions ===<br />
<br />
One of the papers (A Bayesian Approach to Estimating The Selectivity of Conjuctive Predicates) describes a quite interesting solution to this problem - I've already posted a description on how to apply it to the ZIP code / city name problem - see [http://archives.postgresql.org/pgsql-hackers/2010-12/msg01576.php this post] and the following discussion.<br />
<br />
This basically replaces the AVI assumption with a uniform correlation assumption, which is much weaker. There are some nice features (easy extension to more than two columns, a small amount of data to keep), and some unsolved issues related to estimating number of distinct values (for individual columns and for the combination that is used in a query). The current (sampling-based) estimator has known problems, especially in case of the combination - an effort to implement better estimator is described [http://wiki.postgresql.org/wiki/Estimating_Distinct here].<br />
<br />
=== B) Numeric values and inequality conditions ===<br />
<br />
Most of the papers dealing with this problem are based on [http://en.wikipedia.org/wiki/Discretization_of_continuous_features discretization] and multi-dimensional histograms to approximate the joint distribution. So I guess my original proposal (see the first PoC) was not a complete nonsense, as it was based on this approach. Once we have a working histogram-based solution, we can work on precision and efficiency (how much space is needed to store the histogram, how long does it take to compute an estimate, etc.). According to the papers, there are two ways to do that (if you know about other solutions, let us know).<br />
<br />
First, there are several papers offering various enhanced types of multi-dimensional histograms (GenHist, SGRID, VMHIST, ...). Sure, every paper states that the histogram they described is actually the best one (most efficient, most precise, etc.) which is a bit suspicious. Anyway there are promising ways to build better multi-dimensional histograms.<br />
<br />
Second, the paper "Selectivity estimation using probabilistic models") describes a completely different solution based on [http://en.wikipedia.org/wiki/Bayesian_network Bayesian Networks]. That seems to be a really interesting alternative (and it actually it addresses join selectivity estimation too).<br />
<br />
So although the initial implementation is probably going to be inefficient and imprecise, I'm quite confident we can improve that significantly. Either by an advanced histogram or using [http://en.wikipedia.org/wiki/Bayesian_network Bayesian Networks].<br />
<br />
=== C) Numeric values and equality conditions ===<br />
<br />
I'm not sure how to handle this case. But the queries against numeric queries are range queries in most cases I guess, so maybe that's not that big deal.<br />
<br />
=== D) Discrete values and inequality conditions ===<br />
<br />
Basically, this can be handled just like numeric values after discretization, i.e. using a histogram. But just like in the previous case this is not a very frequent case. E.g. how often do you run something like this<br />
<pre>SELECT * FROM foo WHERE (zip_code BETWEEN '12899' AND '23890') AND (city_name BETWEEN 'Boston' AND 'Chicago')</pre><br />
Probably not very often.<br />
<br />
=== Combination of discrete / numeric columns ===<br />
<br />
I'm not sure how to deal with this right now. Obviously it's possible to build multi-dimensional histogram, and estimate as many queries as possible.<br />
<br />
== Proof of Concepts ==<br />
<br />
Until now, I've built two proof of concepts - the first one addresses the case B (numeric data with range conditions), the second one addresses case A (discrete data with equality conditions).<br />
<br />
=== Numeric data & range queries ===<br />
<br />
This proof of concept was described in the [http://archives.postgresql.org/pgsql-hackers/2010-12/msg00913.php initial proposal]. It's based on multi-dimensional (a quite primitive one).<br />
<br />
=== Discrete data & equality queries ===<br />
<br />
This proof of concept is thoroughly described in [http://archives.postgresql.org/pgsql-hackers/2010-12/msg01576.php this post]. It's based on the paper ''A Bayesian Approach to Estimating the Selectivity of Conjunctive Predicates'' [2].<br />
<br />
== Possible features ==<br />
<br />
This section discusses various features the solution might possibly have, what are the pros/cons of those features etc.<br />
<br />
=== Optional vs. automatic ===<br />
<br />
It's not very likely the stats will be collected automatically - see the next section.<br />
<br />
=== Collecting data for all combinations of columns ===<br />
<br />
I really don't think we should collect statistics for every combination of columns of a table. Collecting cross-column stats may consume a lot of resources (time, CPU, memory, I/O, ...), so collecting it for every combination is not very efficient. The plan is to allow a DBA to enable cross-column stats (using an ALTER TABLE, a PL/pgSQL procedure etc.) only when really needed, i.e. when these conditions are met:<br />
<br />
* the columns are dependent<br />
* the columns are used in a query together (frequently)<br />
* the current estimate is significantly imprecise, resulting in a choice of an inefficient query plan<br />
<br />
It's not very likely the stats will be collected automatically for every combination of columns.<br />
<br />
=== Collecting stats for multi-column indexes ===<br />
<br />
The only case where collecting the cross-column stats may be collected automatically is when there is a multi-column index. This usually indicates that the columns are frequently used together (which is one of the conditions), and there's a slight chance that the index may be used to build the histogram much more efficiently. But there are some counterarguments<br />
<br />
* a multi-column index does not mean the columns are dependent (producing invalid estimates)<br />
* many developers often replace multi-column index with a collection of simple indexes (and leave the database to handle it using a Bitmap Index Scan)<br />
<br />
=== Testing for independence ===<br />
<br />
There are independence tests for contingency tables (e.g. [http://mathworld.wolfram.com/Chi-SquaredTest.html Pearson's Chi-squared test]), so that it's easy to find out whether the columns are independent. If such test shows that the columns are independent, we can just throw away the cross-column stats and use the simple estimation based on attribute value independence.<br />
<br />
=== Identifying columns frequently used together ===<br />
<br />
I've noticed demands to collect data about columns used frequently together in a single WHERE condition. This might be an interesting feature (especially when the estimate significantly differs from the actual value), but it's not a part of this effort (currently).<br />
<br />
== History & Discussions ==<br />
<br />
This is just a list of thread in archives discussing cross-column statistics. This by no means a comprehensive listing (e.g. there's a lot of items in pgsql-performance archive discussing issues caused by incorrect estimates):<br />
<br />
* [http://archives.postgresql.org/pgsql-performance/2003-05/msg00049.php Hypothetical suggestions for planner, indexing improvement] - pgsql-performance, May 2003<br />
* [http://archives.postgresql.org/pgsql-hackers/2005-02/msg00208.php Cross column statistics] - pgsql-hackers, February 2006<br />
* [http://archives.postgresql.org/pgsql-hackers/2006-08/msg00463.php An Idea for planner hints] - pgsql-hackers, August 2006<br />
* [http://archives.postgresql.org/pgsql-hackers/2007-03/msg01131.php Stats for multi-column indexes] - pgsql-hackers, March 2007<br />
* [http://archives.postgresql.org/pgsql-hackers/2009-06/msg01431.php Multi-Dimensional Histograms] - pgsql-hackers, June 2009<br />
* [http://archives.postgresql.org/pgsql-hackers/2008-10/msg00741.php Cross-column statistics revisited] - pgsql-hackers, October 2010<br />
* [http://archives.postgresql.org/pgsql-hackers/2010-07/msg00529.php cross column correlation revisted] - pgsql-hackers, July 2010<br />
* [http://archives.postgresql.org/pgsql-hackers/2010-12/msg00913.php proposal: cross-column stats] - pgsql-hackers, December 2010<br />
<br />
== Interesting papers ==<br />
<br />
There are many interesting papers on selectivity estimation out there. This is a list of papers I've read recently, along with a short description. If you know about another interesting paper on this topic (selectivity estimation, especially with dependent columns), just put it here. The section is split into two - the 'recommended articles' list the really interesting articles (not obsolete, giving general into into the fields or describing a very interesting approach). The 'additional articles' is used for articles that may be interesting in the future, are obsolete, or describe a solution that is not directly applicable to PostgreSQL (e.g. involving random sampling).<br />
<br />
=== Recommended papers ===<br />
# '''The New Jersey Data Reduction Report''' [http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.47.7751 citeseerx] [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.47.7751&rep=rep1&type=pdf PDF]<br />
#* published in 1997, authors: Daniel Barbara, William Dumouchel, Christos Faloutsos, Peter J. Haas, Joseph M. Hellerstein, Yannis Ioannidis, H. V. Jagadish, Theodore Johnson, Raymond Ng, Viswanath Poosala, Kenneth A. Ross, Kenneth C. Sevcik<br />
#* a very thorough introduction into 'data reduction' i.e. representing data with a model<br />
#* covers about all the possibilities mentioned here (histograms, SVD, sampling) and some more (log linear models)<br />
#* does not cover probabilistic models<br />
#* anyway this is probably the best starting point if you need an intro into this topic - it's thorough, well written, covers most of the knowledge, etc.<br />
# '''A Bayesian Approach to Estimating the Selectivity of Conjunctive Predicates''' [http://subs.emis.de/LNI/Proceedings/Proceedings144/52.pdf PDF]<br />
#* published in 2009, authors: Max Heimel, Volker Markl, Keshava Murthy<br />
#* is based assuming "uniform correlation" which is a much weaker assumption compared to attribute value independence<br />
#* is easily extensible to more than two columns<br />
#* gives good estimates for highly correlated columns<br />
#* does not need sophisticated techniques as multi-dimensional histograms etc.<br />
#* seems to be a quite good solution to the "ZIP code" fail case<br />
#* there are some weak points - most serious one is the need to get good estimates of number of distinct values (individual columns and the combination used for a query)<br />
# '''Selectivity Estimation Without the Attribute Value Independence Assumption''' [http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.105.8126 citeseerx] [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.105.8126&rep=rep1&type=pdf PDF]<br />
#* published in 1997, authors: Viswanath Poosala, Yannis E. Ioannidis<br />
#* there's nothing revolutionary new - it just shows alternative way to build multidimensional histograms (and a completely different approach based on [http://en.wikipedia.org/wiki/Singular_value_decomposition SVD])<br />
#* the histograms are designed to be more efficient and accurate, so it might be a quite interesting improvement in the future, once we have a working (but imprecise) solution<br />
# '''Selectivity Estimation using Probabilistic Models''' [http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.17.5550 citeseerx] [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.17.5550&rep=rep1&type=pdf PDF]<br />
#* published in 2001, authors Lise Getoor, Ben Taskar, Daphne Koller<br />
#* exchanges the dreaded "attribute value independence" assumption for a much weaker "conditional independence" assumption, which is then used to build Bayesian Network (BN) / Probability Relational Model (PRM)<br />
#* obviously this may be used to deduce estimates for a single table as well as for joins<br />
#* I haven't studied the BN / PRM construction thoroughtly, but it seems quite tractable (and there's a list of articles that describe this)<br />
#* the main effect of the BN/PRM approach is that it significantly reduces the amount of data needed to store joint distribution (instead of storing the whole table, it stores just a few conditional probabilities)<br />
#* this may be actually built on top of a multidimensional histogram, as we need to discretize the values somehow (unless the data already is discrete, of course)<br />
# '''Selectivity estimators for multidimensional range queries over real attributes''' [http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.122.914 citeseerx] [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.122.914&rep=rep1&type=pdf PDF]<br />
#* published in 2005, authors: Dimitrios Gunopulos, George Kollios, Vassilis J. Tsotras, Carlotta Domeniconi<br />
#* a really nice wrap-up of problems related to cross-column statistics, and a summary of possible solutions (histograms, SVD, DCT, ...)<br />
#* summarizes problems when building histograms in higher (more than 1D) dimensions, i.e. number of cells growing exponentially (more space to store, more intersections for queries) vs. bigger (less accurate) cells.<br />
#* offers two new estimators - GENHIST and kernel estimators<br />
#* '''GENHIST''' is an alternative way to build histograms, allowing intersecting cells (contrary to usual histograms partitioning the space into non-overlapping regions)<br />
#* '''kernel estimators''' are an enhanced version of random sampling, with a quite interesting speed/accuracy and and other advantages (not based on histograms), but I guess that's not very useful to us as we're not doing any sampling<br />
<br />
=== Additional papers ===<br />
# '''Query Optimization''' [http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.24.4154 citeseerx] [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.24.4154&rep=rep1&type=pdf PDF]<br />
#* published in 1996, author: Yannis E. Ioannidis<br />
#* a quite nice theoretical introduction into selectivity estimation, worth reading if you know nothing about the general principles<br />
# '''Improved Histograms for Selectivity Estimation of Range Predicates''' [http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.52.7679 citeseerx] [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.52.7679&rep=rep1&type=pdf PDF]<br />
#* published in 1996, authors: Viswanath Poosala, Yannis E. Ioannidis, Peter J. Haas, Eugene J. Shekita<br />
#* about the same as "Selectivity Estimation Without the Attribute Value Independence Assumption" (written by two of the authors in 1997)<br />
#* does not discuss some of the alternatives (SVD for example) and contains a slightly different tests.<br />
#* there is a very interesting chapter 7 on computational techniques (spreads, quantiles, distinct values, construction costs for the histograms, required sample size etc.)<br />
# '''STHoles: A MultidimensionalWorkloadAware Histogram''' [http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.21.1695 citeseerx] [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.21.1695&rep=rep1&type=pdf PDF]<br />
#* published in 2001, authors: Nicolas Bruno, Surajit Chaudhuri, Luis Gravano<br />
#* another type of histogram - this case it's not build directly from the datasets, but from query results, and it's not a one-time process, the histogram is continuously improved (refined in the frequently queried regions).<br />
#* I haven't read the whole article, but although it seems quite interesting it's not very probable this would get into the core soon, and there's nothing like this (updating stats based on query results)<br />
#* so it's an interesting topic, but it's out of scope for now.<br />
# '''Summary Grids: Building Accurate Multidimensional Histograms''' [http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.23.8475 citeseerx] [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.23.8475&rep=rep1&type=pdf PDF]<br />
#* published in 1999, authors: Pedro Furtado, H. Madeira<br />
#* describes an alternative way to build multidimensional histograms - traditional algrithms (MHIST, PHASE) work top-down, i.e. partition the space into smaller and smaller more homogenous areas (buckets), this new algorithm (called SGRID) works bottom-up, i.e. it incrementally joins homogenous areas into larger buckets<br />
#* again, this is not quite interesting right at the beginning, maybe later when improving the solution (making it more efficient, occupy less space etc.)<br />
# '''Vmhist: Efficient Multidimensional Histograms with Improved Accuracy''' [http://eden.dei.uc.pt/~henrique/papers/vmhist.pdf PDF]<br />
#* published in 2000, authors: Pedro Furtado, Henrique Madeira<br />
#* description of another histogram, called VMHIST<br />
#* authors claim this gives better results than MHIST (see one of the other articles) and is better scalable<br />
#* the article is quite coarse, there are not many details about the algorithm and the comparison is not very thorough<br />
# '''Balancing histogram optimality and practicality for query result size estimation''' [http://reference.kfupm.edu.sa/content/b/a/balancing_histogram_optimality_and_pract_46453.pdf PDF]<br />
#* published in 1995, authors: Yannis E. Ioannidis, Viswanath Poosala<br />
#* seems to be a quite old article, and is mostly obsolete (i.e. the following articles from Ioannidis are much more interesting as more advanced histograms are presented)<br />
#* contains some basic definitions, lemmas etc.<br />
# '''Fast and Effective Histogram Construction''' [http://felix-halim.net/research/histogram/index.php WWW] [http://felix-halim.net/research/histogram/KM0563-halim.pdf PDF]<br />
#* published in 2009, authors: Felix Halim, Panagiotis Karras, Roland H. C. Yap<br />
#* another article proposing a new way to build histograms, comparing to older histograms, etc.<br />
# '''HASE: A Hybrid Approach to Selectivity Estimation for Conjunctive Predicates''' [http://www.yorku.ca/xhyu/publications/edbt06.pdf PDF]<br />
#* published in 2006, authors: Xiaohui Yu1, Nick Koudas1, Calisto Zuzarte<br />
#* attempts to combine estimates from synopsis (pregenerated info - e.g. histogram) and random sampling (performed when the query is planned)<br />
#* currently these two approaches are used separately, and they attempt to combine, eliminate drawbacks and get the best parts of both<br />
#* right now this is rather useless for us, as we're not using random sampling at all (maybe in the future this might be an interesting improvement)<br />
# '''Histogram-Based Approximation of Set-Valued Query Answers''' [http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.58.5501 citeseerx] [http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.58.5501&rep=rep1&type=pdf PDF]<br />
#* published in 1999, authors: Yannis E. Ioannidis, Viswanath Poosala<br />
#* not exactly about estimation, rather about approximating results of queries returning sets of rows<br />
#* contains some interesting info, but not exactly relevant to estimation<br />
<br />
[[Category:Feature request]]</div>Boshomihttps://wiki.postgresql.org/index.php?title=CompressedTables&diff=17585CompressedTables2012-05-19T22:47:48Z<p>Boshomi: +cat</p>
<hr />
<div>v0.1 11 Dec 2007<br />
<br />
Frequently with large data archives there is a requirement to reduce the<br />
footprint of the data to allow longer term storage costs to be reduced.<br />
<br />
For Insert-only data we might imagine we can reduce the size of tables<br />
by removing unused tuple header information. Although that is possible,<br />
repeated headers compress fairly well, so it seems easier to tackle the<br />
problem directly by having compressed tables.<br />
<br />
Using a streaming library like zlib, it will be easy to read/write data<br />
files into a still-usable form but with much reduced size. Access to a<br />
compressed table only makes sense as a SeqScan. That would be handled by<br />
introducing tablespace-specific access costs, discussed below. Indexes<br />
on compressed tables would still be allowed, but would hardly ever be<br />
used.<br />
<br />
Access would probably be via tablespace-specific storage managers. So<br />
implement mdcompress.c alongside md.c in src/backend/storage/smgr. If<br />
that implementation route was chosen, it would then allow the<br />
compression option to be made at tablespace level, so commands would be:<br />
<br />
CREATE TABLESPACE tablespacename LOCATION 'directory' [COMPRESS];<br />
<br />
(ALTER TABLESPACE support is going to be much more complex, so leave<br />
that alone for now)<br />
<br />
So when we copy a read-only table to another tablespace the compression<br />
would take place without additional syntax at ALTER TABLE level. i.e.<br />
nothing new goes in tblcmds.c. Cool.<br />
<br />
mdcompress.c seems fairly straightforward, though we would need to think<br />
about how to implement smgr_nblocks() since lseek-ing to get it won't<br />
work because the file size is smaller than the actual decompressed<br />
table. Perhaps with an info file that contains something like an index<br />
metapage where we can read the number of blocks. Ideas?<br />
<br />
In the first pass, I would only allow compressed read-only tables. In<br />
time we might allow Inserts, Updates and Deletes though the latter two<br />
will never be very effective. So my initial approach does *not* allow<br />
writing directly to a compressed table. A couple of reasons why that<br />
isn't desirable/easy:<br />
If we write data straight to the table then any aborted loads will be<br />
written to the table, so VACUUMing the table would need to re-compress<br />
the table which sounds horrible. Plus hint status bits would need to be<br />
set *after* the data was written. (Perhaps in conjunction with a<br />
visibility map we can just forget that aspect of it). The other problem<br />
is that blocks would need to be written out of shared buffers<br />
sequentially, which unfortunately we do not guarantee. We can force that<br />
in the smgr layer by keeping track of last written blockid and then<br />
writing all cached blocks up the currently requested one, but that seems<br />
problematic. I'd say if we want more, we do that in the next release, or<br />
at least the next phase of development. So we would prevent the direct<br />
use of CREATE TABLE on a COMPRESSED tablespace, for now.<br />
<br />
I'm open to arguments that we don't need this at all because filesystem<br />
utilities exist that do everything we need. You're experience will be<br />
good to hear about in regard to this feature.<br />
<br />
[[Category:Historical information]][[Category:Development]]</div>Boshomihttps://wiki.postgresql.org/index.php?title=CompressedTables&diff=17584CompressedTables2012-05-19T22:47:27Z<p>Boshomi: +cat</p>
<hr />
<div>v0.1 11 Dec 2007<br />
<br />
Frequently with large data archives there is a requirement to reduce the<br />
footprint of the data to allow longer term storage costs to be reduced.<br />
<br />
For Insert-only data we might imagine we can reduce the size of tables<br />
by removing unused tuple header information. Although that is possible,<br />
repeated headers compress fairly well, so it seems easier to tackle the<br />
problem directly by having compressed tables.<br />
<br />
Using a streaming library like zlib, it will be easy to read/write data<br />
files into a still-usable form but with much reduced size. Access to a<br />
compressed table only makes sense as a SeqScan. That would be handled by<br />
introducing tablespace-specific access costs, discussed below. Indexes<br />
on compressed tables would still be allowed, but would hardly ever be<br />
used.<br />
<br />
Access would probably be via tablespace-specific storage managers. So<br />
implement mdcompress.c alongside md.c in src/backend/storage/smgr. If<br />
that implementation route was chosen, it would then allow the<br />
compression option to be made at tablespace level, so commands would be:<br />
<br />
CREATE TABLESPACE tablespacename LOCATION 'directory' [COMPRESS];<br />
<br />
(ALTER TABLESPACE support is going to be much more complex, so leave<br />
that alone for now)<br />
<br />
So when we copy a read-only table to another tablespace the compression<br />
would take place without additional syntax at ALTER TABLE level. i.e.<br />
nothing new goes in tblcmds.c. Cool.<br />
<br />
mdcompress.c seems fairly straightforward, though we would need to think<br />
about how to implement smgr_nblocks() since lseek-ing to get it won't<br />
work because the file size is smaller than the actual decompressed<br />
table. Perhaps with an info file that contains something like an index<br />
metapage where we can read the number of blocks. Ideas?<br />
<br />
In the first pass, I would only allow compressed read-only tables. In<br />
time we might allow Inserts, Updates and Deletes though the latter two<br />
will never be very effective. So my initial approach does *not* allow<br />
writing directly to a compressed table. A couple of reasons why that<br />
isn't desirable/easy:<br />
If we write data straight to the table then any aborted loads will be<br />
written to the table, so VACUUMing the table would need to re-compress<br />
the table which sounds horrible. Plus hint status bits would need to be<br />
set *after* the data was written. (Perhaps in conjunction with a<br />
visibility map we can just forget that aspect of it). The other problem<br />
is that blocks would need to be written out of shared buffers<br />
sequentially, which unfortunately we do not guarantee. We can force that<br />
in the smgr layer by keeping track of last written blockid and then<br />
writing all cached blocks up the currently requested one, but that seems<br />
problematic. I'd say if we want more, we do that in the next release, or<br />
at least the next phase of development. So we would prevent the direct<br />
use of CREATE TABLE on a COMPRESSED tablespace, for now.<br />
<br />
I'm open to arguments that we don't need this at all because filesystem<br />
utilities exist that do everything we need. You're experience will be<br />
good to hear about in regard to this feature.<br />
<br />
[[Historical information]][[Category:Development]]</div>Boshomihttps://wiki.postgresql.org/index.php?title=CodeCoverage&diff=17583CodeCoverage2012-05-19T22:46:00Z<p>Boshomi: </p>
<hr />
<div>I have a patch that I will be submitting to add to the build system the capability of reporting on test code coverage metrics for the test suite. Actually it can show coverage for any application run against PostgreSQL. Download [[Image:Coverage.tar.gz]] to see an example report. Gunzip and un-tar the file and click on coverage/index.html. I had to delete most of the files to decrease the file size for upload, so only the links for access work.<br />
<br />
gcov reports line, branch, and function coverage, but lcov only reports on line coverage. I've added a link to the html to the gcov output that shows summary statistics for each file for line, branch, and function calls.<br />
<br />
The report gives a very clear and browseable view of what parts of the system might benefit from more extensive testing. It's obviously useful for planning future testing, but also can be used in conjunction with debugging to see what lines and functions are being exercised or missed by existing tests of the functionality under investigation. It could even be helpful to give a static view of lines hit by a bug test case in lieue of using a debugger. Also, when you're writing a unit test for new functionality, it would be good to check what you're actually hitting with the test.<br />
<br />
It uses gcov together with gcc to generate the statistics, and the lcov suite to create the html report. Both of these would obviously have to be installed to get a coverage report, but this would be an optional feature of the build. It only works with gcc.<br />
<br />
To generate coverage statistics, you run configure with --enable-coverage and after building and running tests, you do make coverage. The process generates data files in the same directories as source & object files and produces a coverage directory at the top level with the html files. I've also set it up so a tar file with the html is generated. That is what I've attached.<br />
<br />
More information on gcov at http://gcc.gnu.org/onlinedocs/gcc/Gcov.html, lcov at http://ltp.sourceforge.net/documentation/how-to/ltp.php (coverage/lcov tabs).<br />
<br />
[[Category:Development]]</div>Boshomihttps://wiki.postgresql.org/index.php?title=CodeCoverage&diff=17582CodeCoverage2012-05-19T22:45:38Z<p>Boshomi: +cat</p>
<hr />
<div>I have a patch that I will be submitting to add to the build system the capability of reporting on test code coverage metrics for the test suite. Actually it can show coverage for any application run against PostgreSQL. Download [[Image:Coverage.tar.gz]] to see an example report. Gunzip and un-tar the file and click on coverage/index.html. I had to delete most of the files to decrease the file size for upload, so only the links for access work.<br />
<br />
gcov reports line, branch, and function coverage, but lcov only reports on line coverage. I've added a link to the html to the gcov output that shows summary statistics for each file for line, branch, and function calls.<br />
<br />
The report gives a very clear and browseable view of what parts of the system might benefit from more extensive testing. It's obviously useful for planning future testing, but also can be used in conjunction with debugging to see what lines and functions are being exercised or missed by existing tests of the functionality under investigation. It could even be helpful to give a static view of lines hit by a bug test case in lieue of using a debugger. Also, when you're writing a unit test for new functionality, it would be good to check what you're actually hitting with the test.<br />
<br />
It uses gcov together with gcc to generate the statistics, and the lcov suite to create the html report. Both of these would obviously have to be installed to get a coverage report, but this would be an optional feature of the build. It only works with gcc.<br />
<br />
To generate coverage statistics, you run configure with --enable-coverage and after building and running tests, you do make coverage. The process generates data files in the same directories as source & object files and produces a coverage directory at the top level with the html files. I've also set it up so a tar file with the html is generated. That is what I've attached.<br />
<br />
More information on gcov at http://gcc.gnu.org/onlinedocs/gcc/Gcov.html, lcov at http://ltp.sourceforge.net/documentation/how-to/ltp.php (coverage/lcov tabs).<br />
<br />
[[Dategory:Development]]</div>Boshomi