"sqlite3" --- SQLite データベースに対する DB-API 2.0 インタフェース
*******************************************************************

**ソースコード:** Lib/sqlite3/

======================================================================

SQLite は、軽量なディスク上のデータベースを提供する C ライブラリです。
別のサーバプロセスを用意する必要なく、 SQL クエリー言語の非標準的な一
種を使用してデータベースにアクセスできます。一部のアプリケーションは内
部データ保存に SQLite を使えます。また、SQLite を使ってアプリケーショ
ンのプロトタイプを作り、その後そのコードを PostgreSQL や Oracle のよう
な大規模データベースに移植するということも可能です。

sqlite3 モジュールの著者は Gerhard Häring です。 **PEP 249** で記述さ
れている DB-API 2.0 に準拠した SQL インターフェイスを提供します。

このモジュールを使うには、最初にデータベースを表す "Connection" オブジ
ェクトを作ります。ここではデータはファイル "example.db" に格納されてい
るものとします:

   import sqlite3
   con = sqlite3.connect('example.db')

特別な名前である ":memory:" を使うと RAM 上にデータベースを作ることも
できます。

"Connection" があれば、 "Cursor" オブジェクトを作りその "execute()" メ
ソッドを呼んで SQL コマンドを実行することができます:

   cur = con.cursor()

   # Create table
   cur.execute('''CREATE TABLE stocks
                  (date text, trans text, symbol text, qty real, price real)''')

   # Insert a row of data
   cur.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")

   # Save (commit) the changes
   con.commit()

   # We can also close the connection if we are done with it.
   # Just be sure any changes have been committed or they will be lost.
   con.close()

保存されたデータは永続的であり、次回のセッションでもそのまま使用できま
す:

   import sqlite3
   con = sqlite3.connect('example.db')
   cur = con.cursor()

たいてい、SQL 操作では Python 変数の値を使う必要があります。この時、ク
エリーを Python の文字列操作を使って構築することは安全とは言えないので
、すべきではありません。そのようなことをするとプログラムが SQL インジ
ェクション攻撃に対し脆弱になります (https://xkcd.com/327/ ではどうなっ
てしまうかをユーモラスに描いています)。

代わりに、DB-API のパラメータ割り当てを使います。 "?" を変数の値を使い
たいところに埋めておきます。その上で、値のタプルをカーソルの
"execute()" メソッドの第2引数として引き渡します。(他のデータベースモジ
ュールでは変数の場所を示すのに "%s" や ":1" などの異なった表記を用いる
ことがあります。) 例を示します:

   # Never do this -- insecure!
   symbol = 'RHAT'
   cur.execute("SELECT * FROM stocks WHERE symbol = '%s'" % symbol)

   # Do this instead
   t = ('RHAT',)
   cur.execute('SELECT * FROM stocks WHERE symbol=?', t)
   print(cur.fetchone())

   # Larger example that inserts many records at a time
   purchases = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
                ('2006-04-05', 'BUY', 'MSFT', 1000, 72.00),
                ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
               ]
   cur.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases)

SELECT 文を実行した後データを取得する方法は3つありどれを使っても構いま
せん。一つはカーソルを *イテレータ* として扱う、一つはカーソルの
"fetchone()" メソッドを呼んで一致した内の一行を取得する、もう一つは
"fetchall()" メソッドを呼んで一致した全ての行のリストとして受け取る、
という3つです。

以下の例ではイテレータの形を使います:

   >>> for row in cur.execute('SELECT * FROM stocks ORDER BY price'):
           print(row)

   ('2006-01-05', 'BUY', 'RHAT', 100, 35.14)
   ('2006-03-28', 'BUY', 'IBM', 1000, 45.0)
   ('2006-04-06', 'SELL', 'IBM', 500, 53.0)
   ('2006-04-05', 'BUY', 'MSFT', 1000, 72.0)

参考:

  https://www.sqlite.org
     SQLite のウェブページ。ここの文書ではサポートされる SQL 方言の文
     法と使えるデータ型を説明しています。

  https://www.w3schools.com/sql/
     SQL 学習に効くチュートリアル、リファレンス、実例集。

  **PEP 249** - Database API Specification 2.0
     Marc-Andre Lemburg により書かれた PEP。


モジュールの関数と定数
======================

sqlite3.version

   文字列で表現されたモジュールのバージョン番号です。これは SQLite ラ
   イブラリのバージョンではありません。

sqlite3.version_info

   整数のタプルで表現されたモジュールのバージョン番号です。これは
   SQLite ライブラリのバージョンではありません。

sqlite3.sqlite_version

   文字列で表現された SQLite ランタイムライブラリのバージョン番号です
   。

sqlite3.sqlite_version_info

   整数のタプルで表現された SQLite ランタイムライブラリのバージョン番
   号です。

sqlite3.PARSE_DECLTYPES

   この定数は "connect()" 関数の *detect_types* パラメータとして使われ
   ます。

   この定数を設定すると "sqlite3" モジュールは戻り値のカラムの宣言され
   た型を読み取るようになります。意味を持つのは宣言の最初の単語です。
   すなわち、"integer primary key" においては "integer" が読み取られま
   す。また、 "number(10)" では、 "number" が読み取られます。そして、
   そのカラムに対して、変換関数の辞書を探してその型に対して登録された
   関数を使うようにします。

sqlite3.PARSE_COLNAMES

   この定数は "connect()" 関数の *detect_types* パラメータとして使われ
   ます。

   Setting this makes the SQLite interface parse the column name for
   each column it returns.  It will look for a string formed [mytype]
   in there, and then decide that 'mytype' is the type of the column.
   It will try to find an entry of 'mytype' in the converters
   dictionary and then use the converter function found there to
   return the value. The column name found in "Cursor.description"
   does not include the type, i. e. if you use something like "'as
   "Expiration date [datetime]"'" in your SQL, then we will parse out
   everything until the first "'['" for the column name and strip the
   preceeding space: the column name would simply be "Expiration
   date".

sqlite3.connect(database[, timeout, detect_types, isolation_level, check_same_thread, factory, cached_statements, uri])

   Opens a connection to the SQLite database file *database*. By
   default returns a "Connection" object, unless a custom *factory* is
   given.

   *database* is a *path-like object* giving the pathname (absolute or
   relative to the current  working directory) of the database file to
   be opened. You can use "":memory:"" to open a database connection
   to a database that resides in RAM instead of on disk.

   データベースが複数の接続からアクセスされている状況で、その内の一つ
   がデータベースに変更を加えたとき、SQLite データベースはそのトランザ
   クションがコミットされるまでロックされます。*timeout* パラメータで
   、例外を送出するまで接続がロックが解除されるのをどれだけ待つかを決
   めます。デフォルトは 5.0 (5秒) です。

   *isolation_level* パラメータについては、 "Connection" オブジェクト
   の、 "isolation_level" プロパティを参照してください。

   SQLite はネイティブで TEXT、INTEGER、REAL、BLOB および NULL のみを
   サポートしています。その他のタイプを使用したい場合はあなた自身で追
   加しなければなりません。*detect_types* パラメータおよび、
   "register_converter()" 関数でモジュールレベルで登録できるカスタム
   **変換関数** を使用することで簡単に追加できます。

   *detect_types* defaults to 0 (i. e. off, no type detection), you
   can set it to any combination of "PARSE_DECLTYPES" and
   "PARSE_COLNAMES" to turn type detection on. Due to SQLite
   behaviour, types can't be detected for generated fields (for
   example "max(data)"), even when *detect_types* parameter is set. In
   such case, the returned type is "str".

   By default, *check_same_thread* is "True" and only the creating
   thread may use the connection. If set "False", the returned
   connection may be shared across multiple threads. When using
   multiple threads with the same connection writing operations should
   be serialized by the user to avoid data corruption.

   デフォルトでは、 "sqlite3" モジュールは connect の呼び出しの際にモ
   ジュールの "Connection" クラスを使います。しかし、 "Connection" ク
   ラスを継承したクラスを *factory* パラメータに渡して "connect()" に
   そのクラスを使わせることもできます。

   詳しくはこのマニュアルの SQLite と Python の型 節を参考にしてくださ
   い。

   "sqlite3" モジュールは SQL 解析のオーバーヘッドを避けるために内部で
   文キャッシュを使っています。接続に対してキャッシュされる文の数を自
   分で指定したいならば、 *cached_statements* パラメータに設定してくだ
   さい。現在の実装ではデフォルトでキャッシュされる SQL 文の数を 100
   にしています。

   *uri* が真の場合、 *database* は URI として解釈されます。これにより
   、オプションを指定することができます。例えば、データベースを読み出
   し専用モードで使用できるように開くには、次のようにします:

      db = sqlite3.connect('file:path/to/database?mode=ro', uri=True)

   認識されるオプションのリストを含むこの機能についての詳細については
   、>>`<<SQLite URI documentation >>`<<_ を参照してください。

   引数 "database" を指定して 監査イベント "sqlite3.connect" を送出し
   ます。

   バージョン 3.4 で変更: "uri" パラメータが追加されました。

   バージョン 3.7 で変更: *database* は、文字列だけでなく、 *path-like
   object* にすることもできるようになりました。

sqlite3.register_converter(typename, callable)

   Registers a callable to convert a bytestring from the database into
   a custom Python type. The callable will be invoked for all database
   values that are of the type *typename*. Confer the parameter
   *detect_types* of the "connect()" function for how the type
   detection works. Note that *typename* and the name of the type in
   your query are matched in case-insensitive manner.

sqlite3.register_adapter(type, callable)

   自分が使いたい Python の型 *type* を SQLite がサポートしている型に
   変換する呼び出し可能オブジェクト (callable) を登録します。その呼び
   出し可能オブジェクト *callable* はただ一つの引数に Python の値を受
   け取り、int, float, str または bytes のいずれかの型の値を返さなけれ
   ばなりません。

sqlite3.complete_statement(sql)

   文字列 *sql* がセミコロンで終端された一つ以上の完全な SQL 文を含ん
   でいる場合、 "True" を返します。判定は SQL 文として文法的に正しいか
   ではなく、閉じられていない文字列リテラルが無いことおよびセミコロン
   で終端されていることだけで行われます。

   この関数は以下の例にあるような SQLite のシェルを作る際に使われます:

      # A minimal SQLite shell for experiments

      import sqlite3

      con = sqlite3.connect(":memory:")
      con.isolation_level = None
      cur = con.cursor()

      buffer = ""

      print("Enter your SQL commands to execute in sqlite3.")
      print("Enter a blank line to exit.")

      while True:
          line = input()
          if line == "":
              break
          buffer += line
          if sqlite3.complete_statement(buffer):
              try:
                  buffer = buffer.strip()
                  cur.execute(buffer)

                  if buffer.lstrip().upper().startswith("SELECT"):
                      print(cur.fetchall())
              except sqlite3.Error as e:
                  print("An error occurred:", e.args[0])
              buffer = ""

      con.close()

sqlite3.enable_callback_tracebacks(flag)

   デフォルトでは、ユーザ定義の関数、集計関数、変換関数、認可コールバ
   ックなどはトレースバックを出力しません。デバッグの際にはこの関数を
   *flag* に "True" を指定して呼び出します。そうした後は先に述べたよう
   な関数のトレースバックが "sys.stderr" に出力されます。元に戻すには
   "False" を使います。


Connection オブジェクト
=======================

class sqlite3.Connection

   SQLite データベースコネクション。以下の属性やメソッドを持ちます:

   isolation_level

      現在のデフォルト分離レベルを取得または設定します。 "None" で自動
      コミットモードまたは "DEFERRED", "IMMEDIATE", "EXLUSIVE" のどれ
      かです。より詳しい説明は トランザクション制御 節を参照してくださ
      い。

   in_transaction

      トランザクションがアクティブなら (未コミットの変更があるなら)
      "True" 、そうでなければ "False" 。リードオンリー属性です。

      バージョン 3.2 で追加.

   cursor(factory=Cursor)

      cursor メソッドはオション引数 *factory* を 1 つだけ受け付けます
      。 渡された場合は、 "Cursor" またはそのサブクラスのインスタンス
      を返す呼び出し可能オブジェクトでなければなりません。

   commit()

      このメソッドは現在のトランザクションをコミットします。このメソッ
      ドを呼ばないと、前回 "commit()" を呼び出してから行ったすべての変
      更は、他のデータベースコネクションから見ることができません。もし
      、データベースに書き込んだはずのデータが見えなくて悩んでいる場合
      は、このメソッドの呼び出しを忘れていないかチェックしてください。

   rollback()

      このメソッドは最後に行った "commit()" 後の全ての変更をロールバッ
      クします。

   close()

      このメソッドはデータベースコネクションを閉じます。このメソッドが
      自動的に "commit()" を呼び出さないことに注意してください。
      "commit()" をせずにコネクションを閉じると、変更が消えてしまいま
      す！

   execute(sql[, parameters])

      This is a nonstandard shortcut that creates a cursor object by
      calling the "cursor()" method, calls the cursor's "execute()"
      method with the *parameters* given, and returns the cursor.

   executemany(sql[, parameters])

      This is a nonstandard shortcut that creates a cursor object by
      calling the "cursor()" method, calls the cursor's
      "executemany()" method with the *parameters* given, and returns
      the cursor.

   executescript(sql_script)

      This is a nonstandard shortcut that creates a cursor object by
      calling the "cursor()" method, calls the cursor's
      "executescript()" method with the given *sql_script*, and
      returns the cursor.

   create_function(name, num_params, func, *, deterministic=False)

      Creates a user-defined function that you can later use from
      within SQL statements under the function name *name*.
      *num_params* is the number of parameters the function accepts
      (if *num_params* is -1, the function may take any number of
      arguments), and *func* is a Python callable that is called as
      the SQL function. If *deterministic* is true, the created
      function is marked as deterministic, which allows SQLite to
      perform additional optimizations. This flag is supported by
      SQLite 3.8.3 or higher, "NotSupportedError" will be raised if
      used with older versions.

      関数は SQLite でサポートされている任意の型を返すことができます。
      具体的には bytes, str, int, float および "None" です。

      バージョン 3.8 で変更: *deterministic* 引数が追加されました。

      例:

         import sqlite3
         import hashlib

         def md5sum(t):
             return hashlib.md5(t).hexdigest()

         con = sqlite3.connect(":memory:")
         con.create_function("md5", 1, md5sum)
         cur = con.cursor()
         cur.execute("select md5(?)", (b"foo",))
         print(cur.fetchone()[0])

         con.close()

   create_aggregate(name, num_params, aggregate_class)

      ユーザ定義の集計関数を作成します。

      The aggregate class must implement a "step" method, which
      accepts the number of parameters *num_params* (if *num_params*
      is -1, the function may take any number of arguments), and a
      "finalize" method which will return the final result of the
      aggregate.

      "finalize" メソッドは SQLite でサポートされている任意の型を返す
      ことができます。具体的には bytes, str, int, float および "None"
      です。

      例:

         import sqlite3

         class MySum:
             def __init__(self):
                 self.count = 0

             def step(self, value):
                 self.count += value

             def finalize(self):
                 return self.count

         con = sqlite3.connect(":memory:")
         con.create_aggregate("mysum", 1, MySum)
         cur = con.cursor()
         cur.execute("create table test(i)")
         cur.execute("insert into test(i) values (1)")
         cur.execute("insert into test(i) values (2)")
         cur.execute("select mysum(i) from test")
         print(cur.fetchone()[0])

         con.close()

   create_collation(name, callable)

      *name* と *callable* で指定される照合順序を作成します。呼び出し
      可能オブジェクトには二つの文字列が渡されます。一つめのものが二つ
      めのものより低く順序付けられるならば -1 を返し、等しければ 0 を
      返し、一つめのものが二つめのものより高く順序付けられるならば 1
      を返すようにしなければなりません。この関数はソート(SQL での
      ORDER BY)をコントロールするもので、比較を行なうことは他の SQL 操
      作には影響を与えないことに注意しましょう。

      また、呼び出し可能オブジェクトに渡される引数は Python のバイト文
      字列として渡されますが、それは通常 UTF-8 で符号化されたものにな
      ります。

      以下の例は「間違った方法で」ソートする自作の照合順序です:

         import sqlite3

         def collate_reverse(string1, string2):
             if string1 == string2:
                 return 0
             elif string1 < string2:
                 return 1
             else:
                 return -1

         con = sqlite3.connect(":memory:")
         con.create_collation("reverse", collate_reverse)

         cur = con.cursor()
         cur.execute("create table test(x)")
         cur.executemany("insert into test(x) values (?)", [("a",), ("b",)])
         cur.execute("select x from test order by x collate reverse")
         for row in cur:
             print(row)
         con.close()

      照合順序を取り除くには callable に "None" を指定して
      "create_collation" を呼び出します:

         con.create_collation("reverse", None)

   interrupt()

      このメソッドを別スレッドから呼び出して接続上で現在実行中であろう
      クエリを中断させられます。クエリが中断されると呼び出し元は例外を
      受け取ります。

   set_authorizer(authorizer_callback)

      このルーチンはコールバックを登録します。コールバックはデータベー
      スのテーブルのカラムにアクセスしようとするたびに呼び出されます。
      コールバックはアクセスが許可されるならば "SQLITE_OK" を、SQL 文
      全体がエラーとともに中断されるべきならば "SQLITE_DENY" を、カラ
      ムが NULL 値として扱われるべきなら "SQLITE_IGNORE" を返さなけれ
      ばなりません。これらの定数は "sqlite3" モジュールに用意されてい
      ます。

      コールバックの第一引数はどの種類の操作が許可されるかを決めます。
      第二第三引数には第一引数に依存して本当に使われる引数か "None" か
      が渡されます。第四引数はもし適用されるならばデータベースの名前
      ("main", "temp", etc.)です。第五引数はアクセスを試みる要因となっ
      た最も内側のトリガまたはビューの名前、またはアクセスの試みが入力
      された SQL コードに直接起因するものならば "None" です。

      第一引数に与えることができる値や、その第一引数によって決まる第二
      第三引数の意味については、SQLite の文書を参考にしてください。必
      要な定数は全て "sqlite3" モジュールに用意されています。

   set_progress_handler(handler, n)

      このメソッドはコールバックを登録します。コールバックは SQLite 仮
      想マシン上の *n* 個の命令を実行するごとに呼び出されます。これは
      、GUI 更新などのために、長時間かかる処理中に SQLite からの呼び出
      しが欲しい場合に便利です。

      以前登録した progress handler をクリアしたい場合は、このメソッド
      を、 *handler* 引数に "None" を渡して呼び出してください。

      ハンドラー関数からゼロ以外の値を返すと、 現在実行中のクエリが終
      了(terminate)し、 "OperationalError" 例外を送出します。

   set_trace_callback(trace_callback)

      各 SQL 文が SQLite バックエンドによって実際に実行されるたびに呼
      び出される *trace_callback* を登録します。

      コールバックに渡される唯一の引数は、実行されている SQL 文 (の文
      字列)です。コールバックの戻り値は無視されます。バックエンドは
      "Cursor.execute()" メソッドに渡された SQL 文だけを実行するわけで
      はないことに注意してください。他のソースには、 Python モジュール
      のトランザクション管理や、現在のデータベースに定義されたトリガー
      の実行が含まれます。

      *trace_callback* として "None" を渡すと、トレースコールバックを
      無効にできます。

      バージョン 3.3 で追加.

   enable_load_extension(enabled)

      このメソッドは SQLite エンジンが共有ライブラリから SQLite 拡張を
      読み込むのを許可したり、禁止したりします。SQLite 拡張は新しい関
      数や集計関数や仮想テーブルの実装を定義できます。1つの有名な拡張
      は SQLite によって頒布されている全テキスト検索拡張です。

      SQLite 拡張はデフォルトで無効にされています。[1] を見てください
      。

      バージョン 3.2 で追加.

         import sqlite3

         con = sqlite3.connect(":memory:")

         # enable extension loading
         con.enable_load_extension(True)

         # Load the fulltext search extension
         con.execute("select load_extension('./fts3.so')")

         # alternatively you can load the extension using an API call:
         # con.load_extension("./fts3.so")

         # disable extension loading again
         con.enable_load_extension(False)

         # example from SQLite wiki
         con.execute("create virtual table recipe using fts3(name, ingredients)")
         con.executescript("""
             insert into recipe (name, ingredients) values ('broccoli stew', 'broccoli peppers cheese tomatoes');
             insert into recipe (name, ingredients) values ('pumpkin stew', 'pumpkin onions garlic celery');
             insert into recipe (name, ingredients) values ('broccoli pie', 'broccoli cheese onions flour');
             insert into recipe (name, ingredients) values ('pumpkin pie', 'pumpkin sugar flour butter');
             """)
         for row in con.execute("select rowid, name, ingredients from recipe where name match 'pie'"):
             print(row)

         con.close()

   load_extension(path)

      このメソッドは共有ライブラリから SQLite 拡張を読み込みます。この
      メソッドを使う前に "enable_load_extension()" で拡張の読み込みを
      許可しておかなくてはなりません。

      SQLite 拡張はデフォルトで無効にされています。[1] を見てください
      。

      バージョン 3.2 で追加.

   row_factory

      この属性を変更して、カーソルと元の行をタプル形式で受け取り、本当
      の結果の行を返す呼び出し可能オブジェクトにすることができます。こ
      れによって、より進んだ結果の返し方を実装することができます。例え
      ば、各列に列名でもアクセスできるようなオブジェクトを返すことがで
      きます。

      例:

         import sqlite3

         def dict_factory(cursor, row):
             d = {}
             for idx, col in enumerate(cursor.description):
                 d[col[0]] = row[idx]
             return d

         con = sqlite3.connect(":memory:")
         con.row_factory = dict_factory
         cur = con.cursor()
         cur.execute("select 1 as a")
         print(cur.fetchone()["a"])

         con.close()

      タプルを返すのでは物足りず、名前に基づいて列へアクセスしたい場合
      は、 "row_factory" に高度に最適化された "sqlite3.Row" 型を設定す
      ることを検討してください。 "Row" クラスではインデックスでも大文
      字小文字を無視した名前でも列にアクセスでき、しかもほとんどメモリ
      ーを浪費しません。おそらく独自実装の辞書を使うアプローチよりも良
      いもので、もしかすると db の行に基づいた解法よりも優れているかも
      しれません。

   text_factory

      この属性を使って "TEXT" データ型をどのオブジェクトで返すかを制御
      できます。デフォルトではこの属性は "str" に設定されており、
      "sqlite3" モジュールは "TEXT" を Unicode オブジェクトで返します
      。もしバイト列で返したいならば、 "bytes" に設定してください。

      バイト列を受け取って望みの型のオブジェクトを返すような呼び出し可
      能オブジェクトを何でも設定して構いません。

      以下の説明用のコード例を参照してください:

         import sqlite3

         con = sqlite3.connect(":memory:")
         cur = con.cursor()

         AUSTRIA = "\xd6sterreich"

         # by default, rows are returned as Unicode
         cur.execute("select ?", (AUSTRIA,))
         row = cur.fetchone()
         assert row[0] == AUSTRIA

         # but we can make sqlite3 always return bytestrings ...
         con.text_factory = bytes
         cur.execute("select ?", (AUSTRIA,))
         row = cur.fetchone()
         assert type(row[0]) is bytes
         # the bytestrings will be encoded in UTF-8, unless you stored garbage in the
         # database ...
         assert row[0] == AUSTRIA.encode("utf-8")

         # we can also implement a custom text_factory ...
         # here we implement one that appends "foo" to all strings
         con.text_factory = lambda x: x.decode("utf-8") + "foo"
         cur.execute("select ?", ("bar",))
         row = cur.fetchone()
         assert row[0] == "barfoo"

         con.close()

   total_changes

      データベース接続が開始されて以来の行の変更・挿入・削除がなされた
      行の総数を返します。

   iterdump()

      データベースをSQL testフォーマットでダンプするためのイテレータを
      返します。 メモリ内のデータベースの内容を、後で復元するために保
      存する場合に便利です。この関数には、 **sqlite3** シェルの中の
      ".dump" コマンドと同じ機能があります。

      以下はプログラム例です:

         # Convert file existing_db.db to SQL dump file dump.sql
         import sqlite3

         con = sqlite3.connect('existing_db.db')
         with open('dump.sql', 'w') as f:
             for line in con.iterdump():
                 f.write('%s\n' % line)
         con.close()

   backup(target, *, pages=-1, progress=None, name="main", sleep=0.250)

      This method makes a backup of a SQLite database even while it's
      being accessed by other clients, or concurrently by the same
      connection.  The copy will be written into the mandatory
      argument *target*, that must be another "Connection" instance.

      By default, or when *pages* is either "0" or a negative integer,
      the entire database is copied in a single step; otherwise the
      method performs a loop copying up to *pages* pages at a time.

      If *progress* is specified, it must either be "None" or a
      callable object that will be executed at each iteration with
      three integer arguments, respectively the *status* of the last
      iteration, the *remaining* number of pages still to be copied
      and the *total* number of pages.

      The *name* argument specifies the database name that will be
      copied: it must be a string containing either ""main"", the
      default, to indicate the main database, ""temp"" to indicate the
      temporary database or the name specified after the "AS" keyword
      in an "ATTACH DATABASE" statement for an attached database.

      The *sleep* argument specifies the number of seconds to sleep by
      between successive attempts to backup remaining pages, can be
      specified either as an integer or a floating point value.

      Example 1, copy an existing database into another:

         import sqlite3

         def progress(status, remaining, total):
             print(f'Copied {total-remaining} of {total} pages...')

         con = sqlite3.connect('existing_db.db')
         bck = sqlite3.connect('backup.db')
         with bck:
             con.backup(bck, pages=1, progress=progress)
         bck.close()
         con.close()

      Example 2, copy an existing database into a transient copy:

         import sqlite3

         source = sqlite3.connect('existing_db.db')
         dest = sqlite3.connect(':memory:')
         source.backup(dest)

      Availability: SQLite 3.6.11 or higher

      バージョン 3.7 で追加.


カーソルオブジェクト
====================

class sqlite3.Cursor

   "Cursor" インスタンスは以下の属性やメソッドを持ちます。

   execute(sql[, parameters])

      SQL 文を実行します。SQL 文はパラメータ化できます(すなわち SQL リ
      テラルの代わりの場所確保文字 (placeholder) を入れておけます)。
      "sqlite3" モジュールは2種類の場所確保記法をサポートします。一つ
      は疑問符(qmark スタイル)、もう一つは名前(named スタイル)です。

      両方のスタイルの例です:

         import sqlite3

         con = sqlite3.connect(":memory:")
         cur = con.cursor()
         cur.execute("create table people (name_last, age)")

         who = "Yeltsin"
         age = 72

         # This is the qmark style:
         cur.execute("insert into people values (?, ?)", (who, age))

         # And this is the named style:
         cur.execute("select * from people where name_last=:who and age=:age", {"who": who, "age": age})

         print(cur.fetchone())

         con.close()

      "execute()" は一つの SQL 文しか実行しません。二つ以上の文を実行
      しようとすると、 "Warning" を送出します。複数の SQL 文を一つの呼
      び出しで実行したい場合は "executescript()" を使ってください。

   executemany(sql, seq_of_parameters)

      Executes an SQL command against all parameter sequences or
      mappings found in the sequence *seq_of_parameters*.  The
      "sqlite3" module also allows using an *iterator* yielding
      parameters instead of a sequence.

         import sqlite3

         class IterChars:
             def __init__(self):
                 self.count = ord('a')

             def __iter__(self):
                 return self

             def __next__(self):
                 if self.count > ord('z'):
                     raise StopIteration
                 self.count += 1
                 return (chr(self.count - 1),) # this is a 1-tuple

         con = sqlite3.connect(":memory:")
         cur = con.cursor()
         cur.execute("create table characters(c)")

         theIter = IterChars()
         cur.executemany("insert into characters(c) values (?)", theIter)

         cur.execute("select c from characters")
         print(cur.fetchall())

         con.close()

      もう少し短い *ジェネレータ* を使った例です:

         import sqlite3
         import string

         def char_generator():
             for c in string.ascii_lowercase:
                 yield (c,)

         con = sqlite3.connect(":memory:")
         cur = con.cursor()
         cur.execute("create table characters(c)")

         cur.executemany("insert into characters(c) values (?)", char_generator())

         cur.execute("select c from characters")
         print(cur.fetchall())

         con.close()

   executescript(sql_script)

      これは非標準の便宜メソッドで、一度に複数の SQL 文を実行すること
      ができます。メソッドは最初に "COMMIT" 文を発行し、次いで引数とし
      て渡された SQLスクリプトを実行します。

      *sql_script* は  "str" のインスタンスです。

      例:

         import sqlite3

         con = sqlite3.connect(":memory:")
         cur = con.cursor()
         cur.executescript("""
             create table person(
                 firstname,
                 lastname,
                 age
             );

             create table book(
                 title,
                 author,
                 published
             );

             insert into book(title, author, published)
             values (
                 'Dirk Gently''s Holistic Detective Agency',
                 'Douglas Adams',
                 1987
             );
             """)
         con.close()

   fetchone()

      クエリ結果から次の row をフェッチして、1つのシーケンスを返します
      。これ以上データがない場合は "None" を返します。

   fetchmany(size=cursor.arraysize)

      クエリ結果から次の幾つかの row をフェッチして、リストを返します
      。これ以上データがない場合は空のリストを返します。

      一回の呼び出しで返される row の数は、*size* 引数で指定できます。
      この引数が与えられない場合、cursor の arraysize 属性が利用されま
      す。このメソッドは可能な限り指定された *size* の数の row を
      fetch しようとするべきです。もし、指定された数の row が利用可能
      でない場合、それより少ない数の row が返されます。

      *size* 引数とパフォーマンスの関係についての注意です。パフォーマ
      ンスを最適化するためには、大抵、 arraysize 属性を利用するのがベ
      ストです。 *size* 引数を利用したのであれば、次の "fetchmany()"
      の呼び出しでも同じ数を利用するのがベストです。

   fetchall()

      全ての(残りの)クエリ結果の row をフェッチして、リストを返します
      。cursor の arraysize 属性がこの操作のパフォーマンスに影響するこ
      とに気をつけてください。これ以上の row がない場合は、空のリスト
      が返されます。

   close()

      ("__del__" が呼び出される時ではなく、) 今すぐカーソルを閉じます
      。

      この時点から、このカーソルは使用できなくなります。今後、このカー
      ソルで何らかの操作を試みると、 "ProgrammingError" 例外が送出され
      ます。

   rowcount

      一応 "sqlite3" モジュールの "Cursor" クラスはこの属性を実装して
      いますが、データベースエンジン自身の「影響を受けた行」/「選択さ
      れた行」の決定方法は少し風変わりです。

      "executemany()" では、変更数が "rowcount" に合計されます。

      Python DB API 仕様で要求されるように、"rowcount" 属性は「カーソ
      ルに対して "executeXX()" が行なわれていないか、最後の操作の
      rowcount がインターフェースによって決定できなかった場合は -1 」
      です。これには "SELECT" 文も含まれます。すべての列を取得するまで
      クエリによって生じた列の数を決定できないからです。

      SQLite のバージョン 3.6.5 以前は、条件なしで "DELETE FROM table"
      を実行すると "rowcount" が 0 にセットされます。

   lastrowid

      この読み込み専用の属性は、最後に変更した row の rowid を提供しま
      す。この属性は、 "execute()" メソッドを利用して "INSERT" 文また
      は "REPLACE" 文を実行したときのみ設定されます。 "INSERT" と
      "REPLACE" 以外の操作や、 "executemany()" メソッドを呼び出した場
      合は、 "lastrowid" は "None" に設定されます。

      If the "INSERT" or "REPLACE" statement failed to insert the
      previous successful rowid is returned.

      バージョン 3.6 で変更: "REPLACE" 文のサポートが追加されました。

   arraysize

      fetchmany によって返される行(row)数を制御する、読み取りと書き込
      みが可能な属性。 デフォルト値は 1 で、これは呼び出しごとに 1 行
      が取得されることを意味します。

   description

      この読み出し専用の属性は、最後のクエリの結果のカラム名を提供しま
      す。 Python DB API との互換性を維持するために、各カラムに対して
      7つのタプルを返しますが、タプルの後ろ6つの要素は全て "None" です
      。

      この属性は "SELECT" 文にマッチする row が1つもなかった場合でもセ
      ットされます。

   connection

      この読み出し専用の属性は、 "Cursor" オブジェクトが使用する
      SQLite データベースの "Connection" を提供します。"con.cursor()"
      を呼び出すことにより作成される "Cursor" オブジェクトは、 *con*
      を参照する "connection" 属性を持ちます:

         >>> con = sqlite3.connect(":memory:")
         >>> cur = con.cursor()
         >>> cur.connection == con
         True


Row オブジェクト
================

class sqlite3.Row

   "Row" インスタンスは、 "Connection" オブジェクトの "row_factory" と
   して高度に最適化されています。タプルによく似た機能を持つ row を作成
   します。

   カラム名とインデックスによる要素へのアクセス, イテレーション,
   repr(), 同値テスト, "len()" をサポートしています。

   もし、2つの "Row" オブジェクトが完全に同じカラムと値を持っていた場
   合、それらは同値になります。

   keys()

      このメソッドはカラム名のリストを返します。クエリ直後から、これは
      "Cursor.description" の各タプルの最初のメンバになります。

   バージョン 3.5 で変更: スライスがサポートされました。

Rowの例のために、まずサンプルのテーブルを初期化します:

   con = sqlite3.connect(":memory:")
   cur = con.cursor()
   cur.execute('''create table stocks
   (date text, trans text, symbol text,
    qty real, price real)''')
   cur.execute("""insert into stocks
               values ('2006-01-05','BUY','RHAT',100,35.14)""")
   con.commit()
   cur.close()

そして、 "Row" を使ってみます:

   >>> con.row_factory = sqlite3.Row
   >>> cur = con.cursor()
   >>> cur.execute('select * from stocks')
   <sqlite3.Cursor object at 0x7f4e7dd8fa80>
   >>> r = cur.fetchone()
   >>> type(r)
   <class 'sqlite3.Row'>
   >>> tuple(r)
   ('2006-01-05', 'BUY', 'RHAT', 100.0, 35.14)
   >>> len(r)
   5
   >>> r[2]
   'RHAT'
   >>> r.keys()
   ['date', 'trans', 'symbol', 'qty', 'price']
   >>> r['qty']
   100.0
   >>> for member in r:
   ...     print(member)
   ...
   2006-01-05
   BUY
   RHAT
   100.0
   35.14


例外
====

exception sqlite3.Warning

   "Exception" のサブクラスです。

exception sqlite3.Error

   このモジュールにおける他の例外クラスの基底クラスです。 "Exception"
   のサブクラスです。

exception sqlite3.DatabaseError

   Exception raised for errors that are related to the database.

exception sqlite3.IntegrityError

   データベースの参照整合性が影響を受ける場合に発生する例外。 たとえば
   外部キーのチェック(foreign key check)が失敗したとき。
   "DatabaseError" のサブクラスです。

exception sqlite3.ProgrammingError

   Exception raised for programming errors, e.g. table not found or
   already exists, syntax error in the SQL statement, wrong number of
   parameters specified, etc.  It is a subclass of "DatabaseError".

exception sqlite3.OperationalError

   Exception raised for errors that are related to the database's
   operation and not necessarily under the control of the programmer,
   e.g. an unexpected disconnect occurs, the data source name is not
   found, a transaction could not be processed, etc.  It is a subclass
   of "DatabaseError".

exception sqlite3.NotSupportedError

   Exception raised in case a method or database API was used which is
   not supported by the database, e.g. calling the "rollback()" method
   on a connection that does not support transaction or has
   transactions turned off.  It is a subclass of "DatabaseError".


SQLite と Python の型
=====================


はじめに
--------

SQLite は以下の型をネイティブにサポートします: "NULL", "INTEGER",
"REAL", "TEXT", "BLOB"。

したがって、次の Python の型は問題なく SQLite に送り込めます:

+---------------------------------+---------------+
| Python の型                     | SQLite の型   |
|=================================|===============|
| "None"                          | "NULL"        |
+---------------------------------+---------------+
| "int"                           | "INTEGER"     |
+---------------------------------+---------------+
| "float"                         | "REAL"        |
+---------------------------------+---------------+
| "str"                           | "TEXT"        |
+---------------------------------+---------------+
| "bytes"                         | "BLOB"        |
+---------------------------------+---------------+

SQLite の型から Python の型へのデフォルトでの変換は以下の通りです:

+---------------+------------------------------------------------+
| SQLite の型   | Python の型                                    |
|===============|================================================|
| "NULL"        | "None"                                         |
+---------------+------------------------------------------------+
| "INTEGER"     | "int"                                          |
+---------------+------------------------------------------------+
| "REAL"        | "float"                                        |
+---------------+------------------------------------------------+
| "TEXT"        | "text_factory" に依存する。デフォルトでは      |
|               | "str" 。                                       |
+---------------+------------------------------------------------+
| "BLOB"        | "bytes"                                        |
+---------------+------------------------------------------------+

"sqlite3" モジュールの型システムは二つの方法で拡張できます。一つはオブ
ジェクト適合(adaptation)を通じて追加された Python の型を SQLite に格納
することです。もう一つは変換関数(converter)を通じて "sqlite3" モジュー
ルに SQLite の型を違った Python の型に変換させることです。


追加された Python の型を SQLite データベースに格納するために適合関数を使う
--------------------------------------------------------------------------

既に述べたように、SQLite が最初からサポートする型は限られたものだけで
す。それ以外の Python の型を SQLite で使うには、その型を "sqlite3" モ
ジュールがサポートしている型の一つに **適合** させなくてはなりません。
サポートしている型というのは、NoneType, int, float, str, bytes です。

"sqlite3" モジュールで望みの Python の型をサポートされている型の一つに
適合させる方法は二つあります。


オブジェクト自身で適合するようにする
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

自分でクラスを書いているならばこの方法が良いでしょう。次のようなクラス
があるとします:

   class Point:
       def __init__(self, x, y):
           self.x, self.y = x, y

さてこの点を SQLite の一つのカラムに収めたいと考えたとしましょう。最初
にしなければならないのはサポートされている型の中から点を表現するのに使
えるものを選ぶことです。ここでは単純に文字列を使うことにして、座標を区
切るのにはセミコロンを使いましょう。次に必要なのはクラスに変換された値
を返す "__conform__(self, protocol)" メソッドを追加することです。引数
*protocol* は "PrepareProtocol" になります。

   import sqlite3

   class Point:
       def __init__(self, x, y):
           self.x, self.y = x, y

       def __conform__(self, protocol):
           if protocol is sqlite3.PrepareProtocol:
               return "%f;%f" % (self.x, self.y)

   con = sqlite3.connect(":memory:")
   cur = con.cursor()

   p = Point(4.0, -3.2)
   cur.execute("select ?", (p,))
   print(cur.fetchone()[0])

   con.close()


適合関数を登録する
~~~~~~~~~~~~~~~~~~

もう一つの可能性は型を文字列表現に変換する関数を作り
"register_adapter()" でその関数を登録することです。

   import sqlite3

   class Point:
       def __init__(self, x, y):
           self.x, self.y = x, y

   def adapt_point(point):
       return "%f;%f" % (point.x, point.y)

   sqlite3.register_adapter(Point, adapt_point)

   con = sqlite3.connect(":memory:")
   cur = con.cursor()

   p = Point(4.0, -3.2)
   cur.execute("select ?", (p,))
   print(cur.fetchone()[0])

   con.close()

"sqlite3" モジュールには二つの Python 標準型 "datetime.date" と
"datetime.datetime" に対するデフォルト適合関数があります。いま
"datetime.datetime" オブジェクトを ISO 表現でなく Unix タイムスタンプ
として格納したいとしましょう。

   import sqlite3
   import datetime
   import time

   def adapt_datetime(ts):
       return time.mktime(ts.timetuple())

   sqlite3.register_adapter(datetime.datetime, adapt_datetime)

   con = sqlite3.connect(":memory:")
   cur = con.cursor()

   now = datetime.datetime.now()
   cur.execute("select ?", (now,))
   print(cur.fetchone()[0])

   con.close()


SQLite の値を好きな Python 型に変換する
---------------------------------------

適合関数を書くことで好きな Python 型を SQLite に送り込めるようになりま
した。しかし、本当に使い物になるようにするには Python から SQLite さら
に Python へという往還(roundtrip)の変換ができる必要があります。

そこで変換関数(converter)です。

"Point" クラスの例に戻りましょう。x, y 座標をセミコロンで区切った文字
列として SQLite に格納したのでした。

まず、文字列を引数として取り "Point" オブジェクトをそれから構築する変
換関数を定義します。

注釈:

  変換関数は SQLite に送り込んだデータ型に関係なく **常に** "bytes" オ
  ブジェクトを渡されます。

   def convert_point(s):
       x, y = map(float, s.split(b";"))
       return Point(x, y)

次に "sqlite3" モジュールにデータベースから取得したものが本当に点であ
ることを教えなければなりません。二つの方法があります:

* 宣言された型を通じて暗黙的に

* カラム名を通じて明示的に

どちらの方法も モジュールの関数と定数 節の中で説明されています。それぞ
れ "PARSE_DECLTYPES" 定数と "PARSE_COLNAMES" 定数の項目です。

以下の例で両方のアプローチを紹介します。

   import sqlite3

   class Point:
       def __init__(self, x, y):
           self.x, self.y = x, y

       def __repr__(self):
           return "(%f;%f)" % (self.x, self.y)

   def adapt_point(point):
       return ("%f;%f" % (point.x, point.y)).encode('ascii')

   def convert_point(s):
       x, y = list(map(float, s.split(b";")))
       return Point(x, y)

   # Register the adapter
   sqlite3.register_adapter(Point, adapt_point)

   # Register the converter
   sqlite3.register_converter("point", convert_point)

   p = Point(4.0, -3.2)

   #########################
   # 1) Using declared types
   con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES)
   cur = con.cursor()
   cur.execute("create table test(p point)")

   cur.execute("insert into test(p) values (?)", (p,))
   cur.execute("select p from test")
   print("with declared types:", cur.fetchone()[0])
   cur.close()
   con.close()

   #######################
   # 1) Using column names
   con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_COLNAMES)
   cur = con.cursor()
   cur.execute("create table test(p)")

   cur.execute("insert into test(p) values (?)", (p,))
   cur.execute('select p as "p [point]" from test')
   print("with column names:", cur.fetchone()[0])
   cur.close()
   con.close()


デフォルトの適合関数と変換関数
------------------------------

datetime モジュールの date 型および datetime 型のためのデフォルト適合
関数があります。これらの型は ISO 日付 / ISO タイムスタンプとして
SQLite に送られます。

デフォルトの変換関数は "datetime.date" 用が "date" という名前で、
"datetime.datetime" 用が "timestamp" という名前で登録されています。

これにより、多くの場合特別な細工無しに Python の日付 / タイムスタンプ
を使えます。適合関数の書式は実験的な SQLite の date/time 関数とも互換
性があります。

以下の例でこのことを確かめます。

   import sqlite3
   import datetime

   con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
   cur = con.cursor()
   cur.execute("create table test(d date, ts timestamp)")

   today = datetime.date.today()
   now = datetime.datetime.now()

   cur.execute("insert into test(d, ts) values (?, ?)", (today, now))
   cur.execute("select d, ts from test")
   row = cur.fetchone()
   print(today, "=>", row[0], type(row[0]))
   print(now, "=>", row[1], type(row[1]))

   cur.execute('select current_date as "d [date]", current_timestamp as "ts [timestamp]"')
   row = cur.fetchone()
   print("current_date", row[0], type(row[0]))
   print("current_timestamp", row[1], type(row[1]))

   con.close()

SQLite に格納されているタイムスタンプが6桁より長い小数部を持っている場
合、タイムスタンプの変換関数によってマイクロ秒精度に丸められます。


トランザクション制御
====================

The underlying "sqlite3" library operates in "autocommit" mode by
default, but the Python "sqlite3" module by default does not.

"autocommit" mode means that statements that modify the database take
effect immediately.  A "BEGIN" or "SAVEPOINT" statement disables
"autocommit" mode, and a "COMMIT", a "ROLLBACK", or a "RELEASE" that
ends the outermost transaction, turns "autocommit" mode back on.

The Python "sqlite3" module by default issues a "BEGIN" statement
implicitly before a Data Modification Language (DML) statement (i.e.
"INSERT"/"UPDATE"/"DELETE"/"REPLACE").

You can control which kind of "BEGIN" statements "sqlite3" implicitly
executes via the *isolation_level* parameter to the "connect()" call,
or via the "isolation_level" property of connections. If you specify
no *isolation_level*, a plain "BEGIN" is used, which is equivalent to
specifying "DEFERRED".  Other possible values are "IMMEDIATE" and
"EXCLUSIVE".

You can disable the "sqlite3" module's implicit transaction management
by setting "isolation_level" to "None".  This will leave the
underlying "sqlite3" library operating in "autocommit" mode.  You can
then completely control the transaction state by explicitly issuing
"BEGIN", "ROLLBACK", "SAVEPOINT", and "RELEASE" statements in your
code.

バージョン 3.6 で変更: "sqlite3" used to implicitly commit an open
transaction before DDL statements.  This is no longer the case.


"sqlite3" の効率的な使い方
==========================


ショートカットメソッドを使う
----------------------------

"Connection" オブジェクトの非標準的なメソッド "execute()",
"executemany()", "executescript()" を使うことで、 (しばしば余計な)
"Cursor" オブジェクトをわざわざ作り出さずに済むので、コードをより簡潔
に書くことができます。 "Cursor" オブジェクトは暗黙裡に生成されショート
カットメソッドの戻り値として受け取ることができます。この方法を使えば、
"SELECT" 文を実行してその結果について反復することが、 "Connection" オ
ブジェクトに対する呼び出し一つで行なえます。

   import sqlite3

   persons = [
       ("Hugo", "Boss"),
       ("Calvin", "Klein")
       ]

   con = sqlite3.connect(":memory:")

   # Create the table
   con.execute("create table person(firstname, lastname)")

   # Fill the table
   con.executemany("insert into person(firstname, lastname) values (?, ?)", persons)

   # Print the table contents
   for row in con.execute("select firstname, lastname from person"):
       print(row)

   print("I just deleted", con.execute("delete from person").rowcount, "rows")

   # close is not a shortcut method and it's not called automatically,
   # so the connection object should be closed manually
   con.close()


位置ではなく名前でカラムにアクセスする
--------------------------------------

"sqlite3" モジュールの有用な機能の一つに、行生成関数として使われるため
の "sqlite3.Row" クラスがあります。

このクラスでラップされた行は、位置インデクス(タプルのような)でも大文字
小文字を区別しない名前でもアクセスできます:

   import sqlite3

   con = sqlite3.connect(":memory:")
   con.row_factory = sqlite3.Row

   cur = con.cursor()
   cur.execute("select 'John' as name, 42 as age")
   for row in cur:
       assert row[0] == row["name"]
       assert row["name"] == row["nAmE"]
       assert row[1] == row["age"]
       assert row[1] == row["AgE"]

   con.close()


コネクションをコンテキストマネージャーとして利用する
----------------------------------------------------

Connection オブジェクトはコンテキストマネージャーとして利用して、トラ
ンザクションを自動的にコミットしたりロールバックすることができます。例
外が発生したときにトランザクションはロールバックされ、それ以外の場合、
トランザクションはコミットされます:

   import sqlite3

   con = sqlite3.connect(":memory:")
   con.execute("create table person (id integer primary key, firstname varchar unique)")

   # Successful, con.commit() is called automatically afterwards
   with con:
       con.execute("insert into person(firstname) values (?)", ("Joe",))

   # con.rollback() is called after the with block finishes with an exception, the
   # exception is still raised and must be caught
   try:
       with con:
           con.execute("insert into person(firstname) values (?)", ("Joe",))
   except sqlite3.IntegrityError:
       print("couldn't add Joe twice")

   # Connection object used as context manager only commits or rollbacks transactions,
   # so the connection object should be closed manually
   con.close()

-[ 脚注 ]-

[1] いくつかのプラットフォームでこの機能なしでコンパイルされる SQLite
    ライブラリがあるので (特にMac OS X)、sqlite3 モジュールはデフォル
    トで SQLite 拡張サポートなしで構築されます。SQLite 拡張サポートを
    有効にするには、configure に "--enable-loadable-sqlite-extensions"
    を渡す必要があります。
