v1a0 / sqllex

The most pythonic ORM (for SQLite and PostgreSQL). Seriously, try it out!
https://v1a0.github.io/sqllex
GNU General Public License v3.0
92 stars 8 forks source link

INSERTMANY [ { }, { }, { } ] (DICTIONARIES) #2

Closed v1a0 closed 3 years ago

v1a0 commented 3 years ago
users_list = [
    [0, "User_0", 1],
    [1, "User_1", 2],
    [2, "User_2", 3],
    [3, "User_3", 1],
    [4, "User_4", 2],
    [5, "User_5", 3],
    [6, "User_6", 1],
    [7, "User_7", 2],
    (8, "User_8", 3),
    {'id': 9, 'username': "User_9", 'user_group': 1},
]

db.insertmany('users', users_list)

Traceback (most recent call last):
  File "test-new.py", line 110, in <module>
    db.insertmany('users', users_list)
  File "sqlite3x.py", line 883, in insertmany
    return self._insertmany_stmt_(table, *args, **kwargs)
  File "sqlite3x.py", line 274, in wrapper
    cur.executemany(stmt.request.script, stmt.request.values)
sqlite3.IntegrityError: datatype mismatch
``
v1a0 commented 3 years ago

I'm currently not sure is there possible to solve this issue for dictionaries without sh*tcoding. I guess it's better to remind that SQLite3x.selectmany can read data from **kwargs like this:

db.insertmany(
    'users',
    id=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
    username=[
        "User_0",
        "User_1",
        "User_2",
        "User_3",
        "User_4",
        "User_5",
        "User_6",
        "User_7",
        "User_8",
        "User_9"
    ],
    user_group=[1, 2, 3, 1, 2, 3, 1, 2, 3, 1]
)

Or like this:

users_list = [
    [0, "User_0", 1],
    [1, "User_1", 2],
    [2, "User_2", 3],
    [3, "User_3", 1],
    [4, "User_4", 2],
    [5, "User_5", 3],
    [6, "User_6", 1],
    [7, "User_7", 2],
    [8, "User_8", 3],
    [9, "User_9", 1],
]

db.insertmany('users', users_list)

But if you have an list of dicts, you can prepare it this way:

users_list = [
    {'id': 1, 'username': "User_0", 'user_group': 1},
    {'id': 2, 'username': "User_1", 'user_group': 2},
    {'id': 3, 'username': "User_2", 'user_group': 3},
    {'id': 4, 'username': "User_3", 'user_group': 1},
]

ids = [i.get('id') for i in users_list]
usernames = [i.get('username') for i in users_list]
user_groups = [i.get('user_group') for i in users_list]

db.insertmany(
    TABLE='users',
    id=ids, username=usernames, user_group=user_groups
)