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

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

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

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

The sqlite3 module was written by Gerhard Häring.  It provides an SQL
interface compliant with the DB-API 2.0 specification described by
**PEP 249**.

To use the module, start by creating a "Connection" object that
represents the database.  Here the data will be stored in the
"example.db" file:

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

The special path name ":memory:" can be provided to create a temporary
database in RAM.

Once a "Connection" has been established, create a "Cursor" object and
call its "execute()" method to perform SQL commands:

   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()

The saved data is persistent: it can be reloaded in a subsequent
session even after restarting the Python interpreter:

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

To retrieve data after executing a SELECT statement, either treat the
cursor as an *iterator*, call the cursor's "fetchone()" method to
retrieve a single matching row, or call "fetchall()" to get a list of
the matching rows.

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

   >>> 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)

SQL operations usually need to use values from Python variables.
However, beware of using Python's string operations to assemble
queries, as they are vulnerable to SQL injection attacks (see the xkcd
webcomic for a humorous example of what can go wrong):

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

Instead, use the DB-API's parameter substitution. To insert a variable
into a query string, use a placeholder in the string, and substitute
the actual values into the query by providing them as a "tuple" of
values to the second argument of the cursor's "execute()" method. An
SQL statement may use one of two kinds of placeholders: question marks
(qmark style) or named placeholders (named style). For the qmark
style, "parameters" must be a *sequence*. For the named style, it can
be either a *sequence* or "dict" instance. The length of the
*sequence* must match the number of placeholders, or a
"ProgrammingError" is raised. If a "dict" is given, it must contain
keys for all named parameters. Any extra items are ignored. Here's an
example of both styles:

   import sqlite3

   con = sqlite3.connect(":memory:")
   cur = con.cursor()
   cur.execute("create table lang (name, first_appeared)")

   # This is the qmark style:
   cur.execute("insert into lang values (?, ?)", ("C", 1972))

   # The qmark style used with executemany():
   lang_list = [
       ("Fortran", 1957),
       ("Python", 1991),
       ("Go", 2009),
   ]
   cur.executemany("insert into lang values (?, ?)", lang_list)

   # And this is the named style:
   cur.execute("select * from lang where first_appeared=:year", {"year": 1972})
   print(cur.fetchall())

   con.close()

参考:

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

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

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


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

sqlite3.apilevel

   String constant stating the supported DB-API level. Required by the
   DB-API. Hard-coded to ""2.0"".

sqlite3.paramstyle

   String constant stating the type of parameter marker formatting
   expected by the "sqlite3" module. Required by the DB-API. Hard-
   coded to ""qmark"".

   注釈:

     The "sqlite3" module supports both "qmark" and "numeric" DB-API
     parameter styles, because that is what the underlying SQLite
     library supports. However, the DB-API does not allow multiple
     values for the "paramstyle" attribute.

sqlite3.version

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

sqlite3.version_info

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

sqlite3.sqlite_version

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

sqlite3.sqlite_version_info

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

sqlite3.threadsafety

   Integer constant required by the DB-API, stating the level of
   thread safety the "sqlite3" module supports. Currently hard-coded
   to "1", meaning *"Threads may share the module, but not
   connections."* However, this may not always be true. You can check
   the underlying SQLite library's compile-time threaded mode using
   the following query:

      import sqlite3
      con = sqlite3.connect(":memory:")
      con.execute("""
          select * from pragma_compile_options
          where compile_options like 'THREADSAFE=%'
      """).fetchall()

   Note that the SQLITE_THREADSAFE levels do not match the DB-API 2.0
   "threadsafety" levels.

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
   preceding 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
   にしています。

   If *uri* is "True", *database* is interpreted as a URI (Uniform
   Resource Identifier) with a file path and an optional query string.
   The scheme part *must* be ""file:"".  The path can be a relative or
   absolute file path.  The query string allows us to pass parameters
   to SQLite. Some useful URI tricks include:

      # Open a database in read-only mode.
      con = sqlite3.connect("file:template.db?mode=ro", uri=True)

      # Don't implicitly create a new database file if it does not already exist.
      # Will raise sqlite3.OperationalError if unable to open a database file.
      con = sqlite3.connect("file:nosuchdb.db?mode=rw", uri=True)

      # Create a shared named in-memory database.
      con1 = sqlite3.connect("file:mem1?mode=memory&cache=shared", uri=True)
      con2 = sqlite3.connect("file:mem1?mode=memory&cache=shared", uri=True)
      con1.executescript("create table t(t); insert into t values(28);")
      rows = con2.execute("select * from t").fetchall()

   More information about this feature, including a list of recognized
   parameters, can be found in the 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

   An SQLite database connection has the following attributes and
   methods:

   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])

      Create a new "Cursor" object and call "execute()" on it with the
      given *sql* and *parameters*. Return the new cursor object.

   executemany(sql[, parameters])

      Create a new "Cursor" object and call "executemany()" on it with
      the given *sql* and *parameters*. Return the new cursor object.

   executescript(sql_script)

      Create a new "Cursor" object and call "executescript()" on it
      with the given *sql_script*. Return the new cursor object.

   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* を登録します。

      The only argument passed to the callback is the statement (as
      "str") that is being executed. The return value of the callback
      is ignored. Note that the backend does not only run statements
      passed to the "Cursor.execute()" methods.  Other sources include
      the transaction management of the sqlite3 module and the
      execution of triggers defined in the current database.

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

      注釈:

        Exceptions raised in the trace callback are not propagated. As
        a development and debugging aid, use
        "enable_callback_tracebacks()" to enable printing tracebacks
        from exceptions raised in the trace callback.

      バージョン 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)

      This routine loads an SQLite extension from a shared library.
      You have to enable extension loading with
      "enable_load_extension()" before you can use this routine.

      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

      Using this attribute you can control what objects are returned
      for the "TEXT" data type. By default, this attribute is set to
      "str" and the "sqlite3" module will return "str" objects for
      "TEXT". If you want to return "bytes" instead, you can set it to
      "bytes".

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

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

         import sqlite3

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

         AUSTRIA = "Österreich"

         # by default, rows are returned as str
         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 an 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])

      Executes an SQL statement. Values may be bound to the statement
      using placeholders.

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

   executemany(sql, seq_of_parameters)

      Executes a parameterized 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)

      This is a nonstandard convenience method for executing multiple
      SQL statements at once. It issues a "COMMIT" statement first,
      then executes the SQL script it gets as a parameter.  This
      method disregards "isolation_level"; any transaction control
      must be added to *sql_script*.

      *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" 例外が送出され
      ます。

   setinputsizes(sizes)

      Required by the DB-API. Does nothing in "sqlite3".

   setoutputsize(size[, column])

      Required by the DB-API. Does nothing in "sqlite3".

   rowcount

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

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

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

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

   lastrowid

      This read-only attribute provides the row id of the last
      inserted row. It is only updated after successful "INSERT" or
      "REPLACE" statements using the "execute()" method.  For other
      statements, after "executemany()" or "executescript()", or if
      the insertion failed, the value of "lastrowid" is left
      unchanged.  The initial value of "lastrowid" is "None".

      注釈:

        Inserts into "WITHOUT ROWID" tables are not recorded.

      バージョン 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"                                        |
+---------------+------------------------------------------------+

The type system of the "sqlite3" module is extensible in two ways: you
can store additional Python types in an SQLite database via object
adaptation, and you can let the "sqlite3" module convert SQLite types
to different Python types via converters.


追加された 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

Now you want to store the point in a single SQLite column.  First
you'll have to choose one of the supported types to be used for
representing the point. Let's just use str and separate the
coordinates using a semicolon. Then you need to give your class a
method "__conform__(self, protocol)" which must return the converted
value. The parameter *protocol* will be "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 default "timestamp" converter ignores UTC offsets in the
  database and always returns a naive "datetime.datetime" object. To
  preserve UTC offsets in timestamps, either leave converters
  disabled, or register an offset-aware converter with
  "register_converter()".


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

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.

Note that "executescript()" disregards "isolation_level"; any
transaction control must be added explicitly.

バージョン 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

   langs = [
       ("C++", 1985),
       ("Objective-C", 1984),
   ]

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

   # Create the table
   con.execute("create table lang(name, first_appeared)")

   # Fill the table
   con.executemany("insert into lang(name, first_appeared) values (?, ?)", langs)

   # Print the table contents
   for row in con.execute("select name, first_appeared from lang"):
       print(row)

   print("I just deleted", con.execute("delete from lang").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 lang (id integer primary key, name varchar unique)")

   # Successful, con.commit() is called automatically afterwards
   with con:
       con.execute("insert into lang(name) values (?)", ("Python",))

   # 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 lang(name) values (?)", ("Python",))
   except sqlite3.IntegrityError:
       print("couldn't add Python twice")

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

-[ 脚注 ]-

[1] The sqlite3 module is not built with loadable extension support by
    default, because some platforms (notably macOS) have SQLite
    libraries which are compiled without this feature. To get loadable
    extension support, you must pass "--enable-loadable-sqlite-
    extensions" to configure.
