1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Pythonのsqlite3モジュールでのパラメータースタイルを拡張するPyPIモジュールを書いた

1
Posted at

sqlite3はパラメーターのバインドの形式としてqmarkとnamedを受け付けてくれますが、PEP2491で定義されているformatとpyformat形式は受け付けてくれません23。これは、それらを受け付けるようにするモジュールです。

Pythonのバージョンは2.7.8と3.4.1でテストを実施してあります。

:cake: 使い方

pip install sqlite3paramstyle

%sの箇所にバインドしてくれます。

conn = sqlite3paramstyle.connect(":memory:")
cur = conn.cursor()
cur.execute("select %s, %s", ("foo", "bar"))
cur.fetchall()  # [("foo", "bar")]

Python拡張形式のフォーマットにも対応してます。

cur.execute("select %(who)s, %(age)s", {"who": "John", "age": 20})
cur.fetchall()  # [("John", 20)]$

どこかの誰かの助けになると嬉しいです :beers:

:frog: 作成した背景

テストコードのほぼないPythonコードのメンテをすることになって粛々とテストを追加していたが、psycopg2を生で使ってるPythonコードを発見。ぜひともSQLAlchemyを使っておきたいところだったが、依存モジュールを変更するのがしんどいフェーズだったので、なるべく変更しない方向で進めることに。
CIサーバーでPostgresqlプロセスを常時動かしておくのはいやだったのと、DBコネクションは外部から引き渡せるかたちになっていたので、テスト時はsqlite3のコネクションを渡して実行するようにしてみた。
が、psycopg2が受け付けるパラメータースタイルは上記説明にあるformat形式とpyformat形式であり、sqlite3とまったく互換性がない。
psycopg2を拡張してqmarkスタイルを受け付けるようにするqmarkpgというのを見つけたので、それの逆に動くモジュールを書けばいいんじゃね?と思った次第。

PyPIオーサーになれて嬉しい :smiley_cat: ワーイワーイ

参照したサイト

PyPIへの登録方法

toxの使い方

  1. PEP 249 - Python Database API Specification v2.0 | Python.org

  2. 11.13. sqlite3 — SQLite データベースに対する DB-API 2.0 インタフェース — Python 2.7ja1 documentation

  3. 12.6. sqlite3 — SQLite データベースに対する DB-API 2.0 インタフェース — Python 3.4.2 ドキュメント

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?