Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 2e9083c

Browse files
Merge branch 'main' into sqlite-autocommit
2 parents c37ebb5 + 29c8f80 commit 2e9083c

File tree

81 files changed

+1658
-990
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

81 files changed

+1658
-990
lines changed

.github/CODEOWNERS

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ Objects/codeobject.c @markshannon
1818
Objects/frameobject.c @markshannon
1919
Objects/call.c @markshannon
2020
Python/ceval.c @markshannon
21-
Python/compile.c @markshannon
21+
Python/compile.c @markshannon @iritkatriel
2222
Python/ast_opt.c @isidentical
2323
Lib/test/test_patma.py @brandtbucher
2424
Lib/test/test_peepholer.py @brandtbucher
@@ -29,7 +29,6 @@ Lib/test/test_except*.py @iritkatriel
2929
Lib/test/test_traceback.py @iritkatriel
3030
Objects/exceptions.c @iritkatriel
3131
Python/traceback.c @iritkatriel
32-
Python/pythonrun.c @iritkatriel
3332

3433
# Hashing
3534
**/*hashlib* @tiran

Doc/c-api/intro.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,7 @@ complete listing.
153153
.. c:macro:: Py_GETENV(s)
154154
155155
Like ``getenv(s)``, but returns ``NULL`` if :option:`-E` was passed on the
156-
command line (i.e. if ``Py_IgnoreEnvironmentFlag`` is set).
156+
command line (see :c:member:`PyConfig.use_environment`).
157157

158158
.. c:macro:: Py_MAX(x, y)
159159

Doc/c-api/sys.rst

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -167,7 +167,7 @@ Operating System Utilities
167167
168168
.. versionchanged:: 3.8
169169
The function now uses the UTF-8 encoding on Windows if
170-
:c:data:`Py_LegacyWindowsFSEncodingFlag` is zero;
170+
:c:member:`PyConfig.legacy_windows_fs_encoding` is zero;
171171
172172
173173
.. c:function:: char* Py_EncodeLocale(const wchar_t *text, size_t *error_pos)
@@ -209,7 +209,7 @@ Operating System Utilities
209209
210210
.. versionchanged:: 3.8
211211
The function now uses the UTF-8 encoding on Windows if
212-
:c:data:`Py_LegacyWindowsFSEncodingFlag` is zero.
212+
:c:member:`PyConfig.legacy_windows_fs_encoding` is zero.
213213
214214
215215
.. _systemfunctions:

Doc/c-api/veryhigh.rst

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ the same library that the Python runtime is using.
3939
4040
Note that if an otherwise unhandled :exc:`SystemExit` is raised, this
4141
function will not return ``1``, but exit the process, as long as
42-
``Py_InspectFlag`` is not set.
42+
:c:member:`PyConfig.inspect` is zero.
4343
4444
4545
.. c:function:: int Py_BytesMain(int argc, char **argv)
@@ -95,7 +95,7 @@ the same library that the Python runtime is using.
9595
9696
Note that if an otherwise unhandled :exc:`SystemExit` is raised, this
9797
function will not return ``-1``, but exit the process, as long as
98-
``Py_InspectFlag`` is not set.
98+
:c:member:`PyConfig.inspect` is zero.
9999
100100
101101
.. c:function:: int PyRun_SimpleFile(FILE *fp, const char *filename)

Doc/library/ctypes.rst

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1068,18 +1068,16 @@ Accessing values exported from dlls
10681068
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
10691069

10701070
Some shared libraries not only export functions, they also export variables. An
1071-
example in the Python library itself is the :c:data:`Py_OptimizeFlag`, an integer
1072-
set to 0, 1, or 2, depending on the :option:`-O` or :option:`-OO` flag given on
1073-
startup.
1071+
example in the Python library itself is the :c:data:`Py_Version`, Python
1072+
runtime version number encoded in a single constant integer.
10741073

10751074
:mod:`ctypes` can access values like this with the :meth:`in_dll` class methods of
10761075
the type. *pythonapi* is a predefined symbol giving access to the Python C
10771076
api::
10781077

1079-
>>> opt_flag = c_int.in_dll(pythonapi, "Py_OptimizeFlag")
1080-
>>> print(opt_flag)
1081-
c_long(0)
1082-
>>>
1078+
>>> version = ctypes.c_int.in_dll(ctypes.pythonapi, "Py_Version")
1079+
>>> print(hex(version.value))
1080+
0x30c00a0
10831081

10841082
If the interpreter would have been started with :option:`-O`, the sample would
10851083
have printed ``c_long(1)``, or ``c_long(2)`` if :option:`-OO` would have been

Doc/library/errno.rst

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -657,3 +657,12 @@ defined by the module. The specific list of defined symbols is available as
657657
Interface output queue is full
658658

659659
.. versionadded:: 3.11
660+
661+
.. data:: ENOTCAPABLE
662+
663+
Capabilities insufficient. This error is mapped to the exception
664+
:exc:`PermissionError`.
665+
666+
.. availability:: WASI, FreeBSD
667+
668+
.. versionadded:: 3.11.1

Doc/library/exceptions.rst

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -746,7 +746,12 @@ depending on the system error code.
746746

747747
Raised when trying to run an operation without the adequate access
748748
rights - for example filesystem permissions.
749-
Corresponds to :c:data:`errno` :py:data:`~errno.EACCES` and :py:data:`~errno.EPERM`.
749+
Corresponds to :c:data:`errno` :py:data:`~errno.EACCES`,
750+
:py:data:`~errno.EPERM`, and :py:data:`~errno.ENOTCAPABLE`.
751+
752+
.. versionchanged:: 3.11.1
753+
WASI's :py:data:`~errno.ENOTCAPABLE` is now mapped to
754+
:exc:`PermissionError`.
750755

751756
.. exception:: ProcessLookupError
752757

Doc/library/sqlite3.rst

Lines changed: 143 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -47,85 +47,173 @@ This document includes four main sections:
4747
PEP written by Marc-André Lemburg.
4848

4949

50+
.. We use the following practises for SQL code:
51+
- UPPERCASE for keywords
52+
- snake_case for schema
53+
- single quotes for string literals
54+
- singular for table names
55+
- if needed, use double quotes for table and column names
56+
5057
.. _sqlite3-tutorial:
5158

5259
Tutorial
5360
--------
5461

55-
To use the module, start by creating a :class:`Connection` object that
56-
represents the database. Here the data will be stored in the
57-
:file:`example.db` file::
62+
In this tutorial, you will create a database of Monty Python movies
63+
using basic :mod:`!sqlite3` functionality.
64+
It assumes a fundamental understanding of database concepts,
65+
including `cursors`_ and `transactions`_.
66+
67+
First, we need to create a new database and open
68+
a database connection to allow :mod:`!sqlite3` to work with it.
69+
Call :func:`sqlite3.connect` to to create a connection to
70+
the database :file:`tutorial.db` in the current working directory,
71+
implicitly creating it if it does not exist::
5872

5973
import sqlite3
60-
con = sqlite3.connect('example.db')
74+
con = sqlite3.connect("tutorial.db")
6175

62-
The special path name ``:memory:`` can be provided to create a temporary
63-
database in RAM.
76+
The returned :class:`Connection` object ``con``
77+
represents the connection to the on-disk database.
6478

65-
Once a :class:`Connection` has been established, create a :class:`Cursor` object
66-
and call its :meth:`~Cursor.execute` method to perform SQL commands::
79+
In order to execute SQL statements and fetch results from SQL queries,
80+
we will need to use a database cursor.
81+
Call :meth:`con.cursor() <Connection.cursor>` to create the :class:`Cursor`::
6782

6883
cur = con.cursor()
6984

70-
# Create table
71-
cur.execute('''CREATE TABLE stocks
72-
(date text, trans text, symbol text, qty real, price real)''')
73-
74-
# Insert a row of data
75-
cur.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")
85+
Now that we've got a database connection and a cursor,
86+
we can create a database table ``movie`` with columns for title,
87+
release year, and review score.
88+
For simplicity, we can just use column names in the table declaration --
89+
thanks to the `flexible typing`_ feature of SQLite,
90+
specifying the data types is optional.
91+
Execute the ``CREATE TABLE`` statement
92+
by calling :meth:`cur.execute(...) <Cursor.execute>`::
93+
94+
cur.execute("CREATE TABLE movie(title, year, score)")
95+
96+
.. Ideally, we'd use sqlite_schema instead of sqlite_master below,
97+
but SQLite versions older than 3.33.0 do not recognise that variant.
98+
99+
We can verify that the new table has been created by querying
100+
the ``sqlite_master`` table built-in to SQLite,
101+
which should now contain an entry for the ``movie`` table definition
102+
(see `The Schema Table`_ for details).
103+
Execute that query by calling :meth:`cur.execute(...) <Cursor.execute>`,
104+
assign the result to ``res``,
105+
and call :meth:`res.fetchone() <Cursor.fetchone>` to fetch the resulting row::
106+
107+
>>> res = cur.execute("SELECT name FROM sqlite_master")
108+
>>> res.fetchone()
109+
('movie',)
110+
111+
We can see that the table has been created,
112+
as the query returns a :class:`tuple` containing the table's name.
113+
If we query ``sqlite_master`` for a non-existent table ``spam``,
114+
:meth:`!res.fetchone()` will return ``None``::
115+
116+
>>> res = cur.execute("SELECT name FROM sqlite_master WHERE name='spam'")
117+
>>> res.fetchone() is None
118+
True
119+
120+
Now, add two rows of data supplied as SQL literals
121+
by executing an ``INSERT`` statement,
122+
once again by calling :meth:`cur.execute(...) <Cursor.execute>`::
123+
124+
cur.execute("""
125+
INSERT INTO movie VALUES
126+
('Monty Python and the Holy Grail', 1975, 8.2),
127+
('And Now for Something Completely Different', 1971, 7.5)
128+
""")
129+
130+
The ``INSERT`` statement implicitly opens a transaction,
131+
which needs to be committed before changes are saved in the database
132+
(see :ref:`sqlite3-controlling-transactions` for details).
133+
Call :meth:`con.commit() <Connection.commit>` on the connection object
134+
to commit the transaction::
76135

77-
# Save (commit) the changes
78136
con.commit()
79137

80-
# We can also close the connection if we are done with it.
81-
# Just be sure any changes have been committed or they will be lost.
82-
con.close()
83-
84-
The saved data is persistent: it can be reloaded in a subsequent session even
85-
after restarting the Python interpreter::
86-
87-
import sqlite3
88-
con = sqlite3.connect('example.db')
89-
cur = con.cursor()
138+
We can verify that the data was inserted correctly
139+
by executing a ``SELECT`` query.
140+
Use the now-familiar :meth:`cur.execute(...) <Cursor.execute>` to
141+
assign the result to ``res``,
142+
and call :meth:`res.fetchall() <Cursor.fetchall>` to return all resulting rows::
90143

91-
At this point, our database only contains one row::
144+
>>> res = cur.execute("SELECT score FROM movie")
145+
>>> res.fetchall()
146+
[(8.2,), (7.5,)]
92147

93-
>>> res = cur.execute('SELECT count(rowid) FROM stocks')
94-
>>> print(res.fetchone())
95-
(1,)
148+
The result is a :class:`list` of two :class:`!tuple`\s, one per row,
149+
each containing that row's ``score`` value.
96150

97-
The result is a one-item :class:`tuple`:
98-
one row, with one column.
99-
Now, let us insert three more rows of data,
100-
using :meth:`~Cursor.executemany`::
151+
Now, insert three more rows by calling
152+
:meth:`cur.executemany(...) <Cursor.executemany>`::
101153

102-
>>> data = [
103-
... ('2006-03-28', 'BUY', 'IBM', 1000, 45.0),
104-
... ('2006-04-05', 'BUY', 'MSFT', 1000, 72.0),
105-
... ('2006-04-06', 'SELL', 'IBM', 500, 53.0),
106-
... ]
107-
>>> cur.executemany('INSERT INTO stocks VALUES(?, ?, ?, ?, ?)', data)
154+
data = [
155+
("Monty Python Live at the Hollywood Bowl", 1982, 7.9),
156+
("Monty Python's The Meaning of Life", 1983, 7.5),
157+
("Monty Python's Life of Brian", 1979, 8.0),
158+
]
159+
cur.executemany("INSERT INTO movie VALUES(?, ?, ?)", data)
160+
con.commit() # Remember to commit the transaction after executing INSERT.
108161

109-
Notice that we used ``?`` placeholders to bind *data* to the query.
162+
Notice that ``?`` placeholders are used to bind ``data`` to the query.
110163
Always use placeholders instead of :ref:`string formatting <tut-formatting>`
111164
to bind Python values to SQL statements,
112-
to avoid `SQL injection attacks`_.
113-
See the :ref:`placeholders how-to <sqlite3-placeholders>` for more details.
165+
to avoid `SQL injection attacks`_
166+
(see :ref:`sqlite3-placeholders` for more details).
114167

115-
Then, retrieve the data by iterating over the result of a ``SELECT`` statement::
168+
We can verify that the new rows were inserted
169+
by executing a ``SELECT`` query,
170+
this time iterating over the results of the query::
116171

117-
>>> for row in cur.execute('SELECT * FROM stocks ORDER BY price'):
172+
>>> for row in cur.execute("SELECT year, title FROM movie ORDER BY year"):
118173
... print(row)
174+
(1971, "And Now for Something Completely Different")
175+
(1975, "Monty Python and the Holy Grail")
176+
(1979, "Monty Python's Life of Brian")
177+
(1982, "Monty Python Live at the Hollywood Bowl")
178+
(1983, "Monty Python's The Meaning of Life")
179+
180+
Each row is a two-item :class:`tuple` of ``(year, title)``,
181+
matching the columns selected in the query.
182+
183+
Finally, verify that the database has been written to disk
184+
by calling :meth:`con.close() <Connection.close>`
185+
to close the existing connection, opening a new one,
186+
creating a new cursor, then querying the database::
187+
188+
>>> con.close()
189+
>>> new_con = sqlite3.connect("tutorial.db")
190+
>>> new_cur = new_con.cursor()
191+
>>> res = new_cur.execute("SELECT year, title FROM movie ORDER BY score DESC"):
192+
>>> title, year = res.fetchone()
193+
>>> print(f'The highest scoring Monty Python movie is {title!r}, released in {year}')
194+
'The highest scoring Monty Python movie is "Monty Python and the Holy Grail", released in 1975'
195+
196+
You've now created an SQLite database using the :mod:`!sqlite3` module,
197+
inserted data and retrieved values from it in multiple ways.
198+
199+
.. _SQL injection attacks: https://en.wikipedia.org/wiki/SQL_injection
200+
.. _The Schema Table: https://www.sqlite.org/schematab.html
201+
.. _cursors: https://en.wikipedia.org/wiki/Cursor_(databases)
202+
.. _flexible typing: https://www.sqlite.org/flextypegood.html
203+
.. _sqlite_master: https://www.sqlite.org/schematab.html
204+
.. _transactions: https://en.wikipedia.org/wiki/Database_transaction
119205

120-
('2006-01-05', 'BUY', 'RHAT', 100, 35.14)
121-
('2006-03-28', 'BUY', 'IBM', 1000, 45.0)
122-
('2006-04-06', 'SELL', 'IBM', 500, 53.0)
123-
('2006-04-05', 'BUY', 'MSFT', 1000, 72.0)
206+
.. seealso::
124207

125-
You've now created an SQLite database using the :mod:`!sqlite3` module.
208+
* :ref:`sqlite3-howtos` for further reading:
126209

127-
.. _SQL injection attacks: https://en.wikipedia.org/wiki/SQL_injection
210+
* :ref:`sqlite3-placeholders`
211+
* :ref:`sqlite3-adapters`
212+
* :ref:`sqlite3-converters`
213+
* :ref:`sqlite3-columns-by-name`
214+
* :ref:`sqlite3-connection-context-manager`
128215

216+
* :ref:`sqlite3-explanation` for in-depth background on transaction control.
129217

130218
.. _sqlite3-reference:
131219

@@ -525,7 +613,7 @@ Connection objects
525613
supplied, this must be a callable returning an instance of :class:`Cursor`
526614
or its subclasses.
527615

528-
.. method:: blobopen(table, column, row, /, *, readonly=False, name="main")
616+
.. method:: blobopen(table, column, row, /, \*, readonly=False, name="main")
529617

530618
Open a :class:`Blob` handle to an existing
531619
:abbr:`BLOB (Binary Large OBject)`.
@@ -603,7 +691,7 @@ Connection objects
603691
:meth:`~Cursor.executescript` on it with the given *sql_script*.
604692
Return the new cursor object.
605693

606-
.. method:: create_function(name, narg, func, *, deterministic=False)
694+
.. method:: create_function(name, narg, func, \*, deterministic=False)
607695

608696
Create or remove a user-defined SQL function.
609697

@@ -894,7 +982,7 @@ Connection objects
894982
con.close()
895983

896984

897-
.. method:: backup(target, *, pages=-1, progress=None, name="main", sleep=0.250)
985+
.. method:: backup(target, \*, pages=-1, progress=None, name="main", sleep=0.250)
898986

899987
Create a backup of an SQLite database.
900988

@@ -1006,7 +1094,7 @@ Connection objects
10061094
.. _SQLite limit category: https://www.sqlite.org/c3ref/c_limit_attached.html
10071095

10081096

1009-
.. method:: serialize(*, name="main")
1097+
.. method:: serialize(\*, name="main")
10101098

10111099
Serialize a database into a :class:`bytes` object. For an
10121100
ordinary on-disk database file, the serialization is just a copy of the
@@ -1028,7 +1116,7 @@ Connection objects
10281116
.. versionadded:: 3.11
10291117

10301118

1031-
.. method:: deserialize(data, /, *, name="main")
1119+
.. method:: deserialize(data, /, \*, name="main")
10321120

10331121
Deserialize a :meth:`serialized <serialize>` database into a
10341122
:class:`Connection`.

0 commit comments

Comments
 (0)