Changeset 962 for trunk


Ignore:
Timestamp:
Jan 4, 2019, 5:32:04 PM (7 months ago)
Author:
cito
Message:

Some improvements to the docs by Justin Pryzby

Location:
trunk/docs/contents
Files:
12 edited

Legend:

Unmodified
Added
Removed
  • trunk/docs/contents/general.rst

    r960 r962  
    2020    The authoritative programming information for the DB-API is :pep:`0249`.
    2121
    22 Both Python modules utilize the same lower level C extension module that
    23 serves as a wrapper for the C API to PostgreSQL that is available in form
    24 of the so-called "libpq" library.
     22Both Python modules utilize the same low-level C extension, which
     23serves as a wrapper for the "libpq" library, the C API to PostgreSQL.
    2524
    2625This means you must have the libpq library installed as a shared library
  • trunk/docs/contents/install.rst

    r960 r962  
    55-------
    66
    7 You must first have installed Python and PostgreSQL on your system.
    8 If you want to access remote database only, you don't need to install
    9 the full PostgreSQL server, but only the C interface (libpq). If you
    10 are on Windows, make sure that the directory with libpq.dll is in your
    11 ``PATH`` environment variable.
     7You must first install Python and PostgreSQL on your system.
     8If you want to access remote databases only, you don't need to install
     9the full PostgreSQL server, but only the libpq C-interface library.
     10If you are on Windows, make sure that the directory that contains
     11libpq.dll is part of your ``PATH`` environment variable.
    1212
    1313The current version of PyGreSQL has been tested with Python versions
    14142.6, 2.7 and 3.3 to 3.7, and PostgreSQL versions 9.0 to 9.6 and 10 or 11.
    1515
    16 PyGreSQL will be installed as three modules, a dynamic module called
    17 _pg.pyd, and two pure Python wrapper modules called pg.py and pgdb.py.
     16PyGreSQL will be installed as three modules, a shared library called
     17_pg.so (on Linux) or a DLL called _pg.pyd (on Windows), and two pure
     18Python wrapper modules called pg.py and pgdb.py.
    1819All three files will be installed directly into the Python site-packages
    19 directory. To uninstall PyGreSQL, simply remove these three files again.
     20directory. To uninstall PyGreSQL, simply remove these three files.
    2021
    2122
     
    2324-------------------
    2425
    25 This is the most easy way to install PyGreSQL if you have "pip" installed
    26 on your computer. Just run the following command in your terminal::
     26This is the most easy way to install PyGreSQL if you have "pip" installed.
     27Just run the following command in your terminal::
    2728
    2829  pip install PyGreSQL
     
    3031This will automatically try to find and download a distribution on the
    3132`Python Package Index <https://pypi.python.org/>`_ that matches your operating
    32 system and Python version and install it on your computer.
     33system and Python version and install it.
    3334
    3435
     
    4142
    4243When you download the source distribution, you will need to compile the
    43 C extensions, for which you need a C compiler installed on your computer.
     44C extension, for which you need a C compiler installed.
    4445If you don't want to install a C compiler or avoid possible problems
    4546with the compilation, you can search for a pre-compiled binary distribution
     
    8788~~~~~~~~~~~~~~~~~~
    8889
    89 The source file for compiling the dynamic module is called pgmodule.c.
     90The source file for compiling the C extension module is pgmodule.c.
    9091You have two options. You can compile PyGreSQL as a stand-alone module
    9192or you can build it into the Python interpreter.
  • trunk/docs/contents/pg/adaptation.rst

    r960 r962  
    6565manually and sending them to the database using the :meth:`DB.query` method.
    6666
    67 Imagine you have created a user  login form that stores the login name as
     67Imagine you have created a user login form that stores the login name as
    6868*login* and the password as *passwd* and you now want to get the user
    6969data for that user.  You may be tempted to execute a query like this::
     
    7575This seems to work at a first glance, but you will notice an error as soon as
    7676you try to use a login name containing a single quote.  Even worse, this error
    77 can be exploited through a so called "SQL injection", where an attacker inserts
     77can be exploited through so-called "SQL injection", where an attacker inserts
    7878malicious SQL statements into the query that you never intended to be executed.
    79 For instance, with a login name something like ``' OR ''='`` the user could
     79For instance, with a login name something like ``' OR ''='`` the attacker could
    8080easily log in and see the user data of another user in the database.
    8181
    82 One solution for this problem would be to clean your input from "dangerous"
     82One solution for this problem would be to cleanse your input of "dangerous"
    8383characters like the single quote, but this is tedious and it is likely that
    8484you overlook something or break the application e.g. for users with names
     
    165165table column the data type will be clear from the context.
    166166
    167 When binding the parameters to a query, PyGreSQL does not only adapt the basic
     167When binding the parameters to a query, PyGreSQL not only adapts the basic
    168168types like ``int``, ``float``, ``bool`` and ``str``, but also tries to make
    169169sense of Python lists and tuples.
     
    223223            supplier_id=42, price=Decimal('1.99'))}
    224224
    225 However, we may not want to use named tuples, but custom Python classes
    226 to hold our values, like this one::
     225Perhaps we want to use custom Python classes instead of named tuples to hold
     226our values::
    227227
    228228    >>> class InventoryItem:
  • trunk/docs/contents/pg/connection.rst

    r960 r962  
    4444
    4545This method simply sends a SQL query to the database. If the query is an
    46 insert statement that inserted exactly one row into a table that has OIDs, the
    47 return value is the OID of the newly inserted row. If the query is an update
    48 or delete statement, or an insert statement that did not insert exactly one
    49 row in a table with OIDs, then the number of rows affected is returned as a
    50 string. If it is a statement that returns rows as a result (usually a select
    51 statement, but maybe also an ``"insert/update ... returning"`` statement),
    52 this method returns a :class:`Query` that can be accessed via the
     46insert statement that inserted exactly one row into a table that has OIDs,
     47the return value is the OID of the newly inserted row as an integer.
     48If the query is an update or delete statement, or an insert statement that
     49did not insert exactly one row, or on a table without OIDs, then the number
     50of rows affected is returned as a string. If it is a statement that returns
     51rows as a result (usually a select statement, but maybe also an
     52``"insert/update ... returning"`` statement), this method returns
     53a :class:`Query` that can be accessed via the
    5354:meth:`Query.getresult`, :meth:`Query.dictresult` or
    5455:meth:`Query.namedresult` methods or simply printed.
     
    5758The SQL command may optionally contain positional parameters of the form
    5859``$1``, ``$2``, etc instead of literal data, in which case the values
    59 have to be supplied separately as a tuple.  The values are substituted by
     60must be supplied separately as a tuple.  The values are substituted by
    6061the database in such a way that they don't need to be escaped, making this
    6162an effective way to pass arbitrary or unknown data without worrying about
     
    9293This method works exactly like :meth:`Connection.query` except that instead
    9394of passing the command itself, you pass the name of a prepared statement.
    94 An empty name corresponds to the unnamed statement.  You must have created
    95 the corresponding named or unnamed statement with :meth:`Connection.prepare`
    96 before, or an :exc:`pg.OperationalError` will be raised.
     95An empty name corresponds to the unnamed statement.  You must have previously
     96created the corresponding named or unnamed statement with
     97:meth:`Connection.prepare`, or an :exc:`pg.OperationalError` will be raised.
    9798
    9899.. versionadded:: 5.1
     
    112113    :raises pg.ProgrammingError: error in query or duplicate query
    113114
    114 This method creates a prepared statement for the given command with the
    115 given name for later execution with the :meth:`Connection.query_prepared`
     115This method creates a prepared statement with the specified name for the
     116given command for later execution with the :meth:`Connection.query_prepared`
    116117method. The name can be empty to create an unnamed statement, in which case
    117118any pre-existing unnamed statement is automatically replaced; otherwise a
     
    318319
    319320    This method doesn't type check the fields according to the table definition;
    320     it just look whether or not it knows how to handle such types.
     321    it just looks whether or not it knows how to handle such types.
    321322
    322323get/set_notice_receiver -- custom notice receiver
     
    452453    :raises ValueError: bad OID value (0 is invalid_oid)
    453454
    454 This method allows to reuse a formerly created large object through the
    455 :class:`LargeObject` interface, providing the user have its OID.
     455This method allows reusing a previously created large object through the
     456:class:`LargeObject` interface, provided the user has its OID.
    456457
    457458loimport -- import a file to a large object [LO]
  • trunk/docs/contents/pg/db_types.rst

    r814 r962  
    9090
    9191    Also note that the typecasting for all of the basic types happens already
    92     in the C extension module.  The typecast functions that can be set with
    93     the above methods are only called for the types that are not already
    94     supported by the C extension module.
     92    in the C low-level extension module.  The typecast functions that can be
     93    set with the above methods are only called for the types that are not
     94    already supported by the C extension.
  • trunk/docs/contents/pg/db_wrapper.rst

    r961 r962  
    135135
    136136By default, only a limited number of simple types will be returned.
    137 You can get the regular types after enabling this by calling the
     137You can get the regular types instead, if you enable this by calling the
    138138:meth:`DB.use_regtypes` method.
    139139
     
    183183
    184184Note that you can request most of the important parameters also using
    185 :meth:`Connection.parameter()` which does not involve a database query
    186 like it is the case for :meth:`DB.get_parameter` and :meth:`DB.set_parameter`.
     185:meth:`Connection.parameter()` which does not involve a database query,
     186unlike :meth:`DB.get_parameter` and :meth:`DB.set_parameter`.
    187187
    188188.. versionadded:: 4.2
     
    315315corresponding to the passed *keyname* or primary key.  The fetched row
    316316from the table will be returned as a new dictionary or used to replace
    317 the existing values when row was passed as aa dictionary.
     317the existing values if the row was passed as a dictionary.
    318318
    319319The OID is also put into the dictionary if the table has one, but
     
    347347
    348348Note that since PyGreSQL 5.0 it is possible to insert a value for an
    349 array type column by passing it as Python list.
     349array type column by passing it as a Python list.
    350350
    351351update -- update a row in a database table
     
    373373
    374374Like insert, the dictionary is optional and updates will be performed
    375 on the fields in the keywords.  There must be an OID or primary key
    376 either in the dictionary where the OID must be munged, or in the keywords
    377 where it can be simply the string ``'oid'``.
     375on the fields in the keywords.  There must be an OID or primary key either
     376specified using the ``'oid'`` keyword or in the dictionary, in which case the
     377OID must be munged.
     378
    378379
    379380upsert -- insert a row with conflict resolution
     
    392393
    393394This method inserts a row into a table, but instead of raising a
    394 ProgrammingError exception in case a row with the same primary key already
    395 exists, an update will be executed instead.  This will be performed as a
     395ProgrammingError exception in case of violating a constraint or unique index,
     396an update will be executed instead.  This will be performed as a
    396397single atomic operation on the database, so race conditions can be avoided.
    397398
     
    525526
    526527This methods works like the :meth:`DB.query` method, except that instead of
    527 passing the SQL command, you pass the name of a prepared statement.  If you
    528 pass an empty name, the unnamed statement will be executed.
    529 
    530 You must have created the corresponding named or unnamed statement with
    531 the :meth:`DB.prepare` method before, otherwise an :exc:`pg.OperationalError`
    532 will be raised.
     528passing the SQL command, you pass the name of an prepared statement that you
     529have created previously using the :meth:`DB.prepare` method.
     530
     531Passing an empty string or *None* as the name will execute the unnamed
     532statement (see warning about the limited lifetime of the unnamed statement
     533in :meth:`DB.prepare`).
    533534
    534535.. versionadded:: 5.1
     
    548549    :raises pg.ProgrammingError: error in query or duplicate query
    549550
    550 This method creates a prepared statement for the given command with the
    551 given name for later execution with the :meth:`DB.query_prepared` method.
     551This method creates a prepared statement with the given name for the given
     552command for later execution with the :meth:`DB.query_prepared` method.
    552553The name can be empty to create an unnamed statement, in which case any
    553554pre-existing unnamed statement is automatically replaced; otherwise a
     
    807808This method escapes a string for use as an SQL identifier, such as a table,
    808809column, or function name. This is useful when a user-supplied identifier
    809 might contain special characters that would otherwise not be interpreted
    810 as part of the identifier by the SQL parser, or when the identifier might
    811 contain upper case characters whose case should be preserved.
     810might contain special characters that would otherwise be misinterpreted
     811by the SQL parser, or when the identifier might contain upper case characters
     812whose case should be preserved.
    812813
    813814.. versionadded:: 4.1
     
    891892in PostgreSQL or you can set the decoding function to *None* or a different
    892893function using :func:`pg.set_jsondecode`.  By default this is the same as
    893 the :func:`json.dumps` function from the standard library.
     894the :func:`json.loads` function from the standard library.
    894895
    895896.. versionadded:: 5.0
     
    910911If you pass a boolean, it sets whether regular type names shall be used.
    911912The method can also be used to check through its return value whether
    912 currently regular type names are used.
     913regular type names are currently used.
    913914
    914915.. versionadded:: 4.1
  • trunk/docs/contents/pg/query.rst

    r901 r962  
    2222    :raises MemoryError: internal memory error
    2323
    24 This method returns the list of the values returned by the query.
     24This method returns query results as a list of tuples.
    2525More information about this result may be accessed using
    2626:meth:`Query.listfields`, :meth:`Query.fieldname`
     
    4242    :raises MemoryError: internal memory error
    4343
    44 This method returns the list of the values returned by the query
    45 with each tuple returned as a dictionary with the field names
    46 used as the dictionary index.
     44This method returns query results as a list of dictionaries which have
     45the field names as keys.
    4746
    4847Note that since PyGreSQL 5.0 this will return the values of array type
     
    6261    :raises MemoryError: internal memory error
    6362
    64 This method returns the list of the values returned by the query
    65 with each row returned as a named tuple with proper field names.
     63This method returns query results as a list of named tuples with
     64proper field names.
    6665
    6766Column names in the database that are not valid as field names for
     
    8584    :raises TypeError: too many parameters
    8685
    87 This method returns the list of names of the fields defined for the
     86This method returns the list of field names defined for the
    8887query result. The fields are in the same order as the result values.
    8988
     
    115114    :raises ValueError: unknown field name
    116115
    117 This method returns a field number from its name. It can be used to
     116This method returns a field number given its name. It can be used to
    118117build a function that converts result list strings to their correct
    119118type, using a hardcoded table definition. The number returned is the
    120 field rank in the result values list.
     119field rank in the query result.
    121120
    122121ntuples -- return number of tuples in query object
  • trunk/docs/contents/postgres/advanced.rst

    r746 r962  
    1212    >>> from pg import DB
    1313    >>> db = DB()
    14     >>> query = query
     14    >>> query = db.query
    1515
    1616Inheritance
  • trunk/docs/contents/postgres/basic.rst

    r746 r962  
    7272    ...     VALUES ('San Francisco', '(-194.0, 53.0)')""")
    7373
    74 You can also specify what column the values correspond to. The columns can
     74You can also specify the columns to which the values correspond. The columns can
    7575be specified in any order. You may also omit any number of columns,
    76 unknown precipitation below::
     76such as with unknown precipitation, below::
    7777
    7878    >>> db.query("""INSERT INTO weather (date, city, temp_hi, temp_lo)
     
    268268    (1 row)
    269269
    270 Now let's join two tables. The following joins the "weather" table and the
    271 "cities" table::
     270Now let's join two different tables. The following joins the "weather" table
     271and the "cities" table::
    272272
    273273    >>> print(db.query("""SELECT city, location, prcp, date
  • trunk/docs/contents/postgres/func.rst

    r746 r962  
    2323    ...     AS 'SELECT 1 as ONE' LANGUAGE SQL""")
    2424
    25 Functions can be used in any expressions (eg. in the target"list or
     25Functions can be used in any expressions (eg. in the target list or
    2626qualifications)::
    2727
     
    9090    ...     $$ LANGUAGE SQL""")
    9191
    92 You can then project a column out of resulting the tuple by using the
     92You can then extract a column out of the resulting tuple by using the
    9393"function notation" for projection columns (i.e. ``bar(foo)`` is equivalent
    9494to ``foo.bar``). Note that ``new_emp().name`` isn't supported::
     
    132132    (5 rows)
    133133    >>> query("""CREATE FUNCTION clean_EMP () RETURNS int4 AS
    134     ...         'DELETE FROM EMP WHERE EMP.salary <= 0;
     134    ...         'DELETE FROM EMP WHERE EMP.salary < 0;
    135135    ...          SELECT 1 AS ignore_this'
    136136    ...     LANGUAGE SQL""")
  • trunk/docs/contents/postgres/syscat.rst

    r746 r962  
    88information. You can drop and recreate the tables, add columns, insert and
    99update values, and severely mess up your system that way. Normally, one
    10 should not change the system catalogs by hand, there are always SQL commands
    11 to do that. For example, CREATE DATABASE inserts a row into the *pg_database*
    12 catalog — and actually creates the database on disk.
     10should not change the system catalogs by hand: there are SQL commands
     11to make all supported changes.  For example, CREATE DATABASE inserts a row
     12into the *pg_database* catalog — and actually creates the database on disk.
    1313
    1414It this section we want to show examples for how to parse some of the system
     
    2020    >>> from pg import DB
    2121    >>> db = DB()
    22     >>> query = query
     22    >>> query = db.query
     23
    2324
    2425Lists indices
     
    3233        WHERE i.indrelid = bc.oid AND i.indexrelid = ic.oid
    3334            AND i.indkey[0] = a.attnum AND a.attrelid = bc.oid
    34             AND NOT a.attisdropped
     35            AND NOT a.attisdropped AND a.attnum>0
    3536        ORDER BY class_name, index_name, attname"""))
    3637
     
    3940----------------------------
    4041
    41 This query lists all user defined attributes and their type
    42 in user-defined classes::
     42This query lists all user-defined attributes and their types
     43in user-defined tables::
    4344
    44     print(query("""SELECT c.relname, a.attname, t.typname
    45         FROM pg_class c, pg_attribute a, pg_type t
    46         WHERE c.relkind = 'r' and c.relname !~ '^pg_'
    47             AND c.relname !~ '^Inv' and a.attnum > 0
    48             AND a.attrelid = c.oid and a.atttypid = t.oid
     45    print(query("""SELECT c.relname, a.attname,
     46            format_type(a.atttypid, a.atttypmod)
     47        FROM pg_class c, pg_attribute a
     48        WHERE c.relkind = 'r' AND c.relnamespace!=ALL(ARRAY[
     49            'pg_catalog','pg_toast', 'information_schema']::regnamespace[])
     50            AND a.attnum > 0
     51            AND a.attrelid = c.oid
    4952            AND NOT a.attisdropped
    5053        ORDER BY relname, attname"""))
     54
    5155
    5256List user defined base types
     
    6367
    6468
    65 List  operators
    66 ---------------
     69List operators
     70--------------
    6771
    6872This query lists all right-unary operators::
     
    122126        ORDER BY proname, typname"""))
    123127
     128
    124129List operator families
    125130----------------------
  • trunk/docs/contents/tutorial.rst

    r908 r962  
    1414.. py:currentmodule:: pg
    1515
    16 The first thing you need to do anything with your PostgreSQL database is
    17 to create a database connection.
     16Before doing anything else, it's necessary to create a database connection.
    1817
    1918To do this, simply import the :class:`DB` wrapper class and create an
     
    195194    ...     user='scott', password='tiger')
    196195
    197 Note that like in the classic interface, you can omit parameters if they
     196As in the classic interface, you can omit parameters if they
    198197are the default values used by PostgreSQL.
    199198
     
    204203   >>> cursor = con.cursor()
    205204
    206 The cursor now has a method that lets you execute database queries::
     205The cursor has a method that lets you execute database queries::
    207206
    208207   >>> cursor.execute("create table fruits("
    209208   ...     "id serial primary key, name varchar)")
    210209
    211 
    212 To insert data into the table, also can also use this method::
     210You can also use this method to insert data into the table::
    213211
    214212   >>> cursor.execute("insert into fruits (name) values ('apple')")
     
    218216   >>> cursor.execute("insert into fruits (name) values (%s)", ('banana',))
    219217
    220 For inserting multiple rows at once, you can use the following method::
     218To insert multiple rows at once, you can use the following method::
    221219
    222220   >>> more_fruits = 'cherimaya durian eggfruit fig grapefruit'.split()
     
    232230Also note that the DB API 2.0 interface does not have an autocommit as you
    233231may be used from PostgreSQL. So in order to make these inserts permanent,
    234 you need to commit them to the database first::
     232you need to commit them to the database::
    235233
    236234   >>> con.commit()
    237235
    238236If you end the program without calling the commit method of the connection,
    239 or if you call the rollback method of the connection, then all the changes
     237or if you call the rollback method of the connection, then the changes
    240238will be discarded.
    241239
    242 In a similar way, you can also update or delete rows in the database,
     240In a similar way, you can update or delete rows in the database,
    243241executing UPDATE or DELETE statements instead of INSERT statements.
    244242
     
    252250
    253251The result is a named tuple. This means you can access its elements either
    254 using an index number like in an ordinary tuple, or using the column name
    255 like you access object attributes.
     252using an index number as for an ordinary tuple, or using the column name
     253as for access to object attributes.
    256254
    257255To fetch all rows of the query, use this method instead::
Note: See TracChangeset for help on using the changeset viewer.