[sqlalchemy] [alembic] equivalent to `makemigrations --check`
Hi, I got a bounce-back from attempting to email the old alembic google group, so trying here instead! Does Alembic have an equivalent to django's "makemigrations --check"? This is a thing you can use in CI on pull requests to ensure no changes have been made to the model that are not reflected in migrations. I guess this boils down to "is the current db state plus any outstanding migrations equal to the model in this checkout"... cheers, Chris -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/69a5ab37-ada6-4224-8473-423f13481c57%40withers.org.
Re: [sqlalchemy] Composite columns and None
I wanted to follow up on this thread. Mike’s suggestion above <https://groups.google.com/g/sqlalchemy/c/nHz9z_P15qg/m/HWk8g8gGCAAJ> worked, and considering the related discussion Dataclasses and Composites with init-only variables <https://github.com/sqlalchemy/sqlalchemy/discussions/10988> I adjusted the code somewhat: instead of using the *nullable_point()* function (from above) I extended the *as_composite()* class method (from the other thread) as suggested: *@classmethod* *def as_composite(cls, x: int | None, y: int | None) -> Point | None:* *if x is None and y is None:* *return None* *return Point(x, y)* Then adjust the mapper types accordingly, and that’s it Thanks! Jens -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/2e52030a-8772-4876-8c74-1f607d2af049n%40googlegroups.com.
Re: [sqlalchemy] Composite columns and None
Thank you, Mike, for the suggestion! Another thought I mulled over was to create a new *point* table and then use a nullable FK from the *vertex* table. That way, the *Point* class can map to its own dedicated table, and a *Vertex* class would then use a relationship that’s able to map optional *Point*s to a *Vertex* via that FK relationship 樂 Once we get to implementing this, I’ll let you know what we did… -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/f3737188-68c0-4eba-9467-a7aaa520df2fn%40googlegroups.com.
[sqlalchemy] test email
this is a test. -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/287c068c-1194-41a9-82b3-b57fdde3c702%40app.fastmail.com.
[sqlalchemy] TechTool Pro 11.0.6 Build 5444
How to Test and Repair Your Mac with TechTool Pro 11.0.6 Build 5444If you want to keep your Mac running smoothly and avoid data loss, you need a reliable tool that can perform various tests and repairs on your system. TechTool Pro 11.0.6 Build 5444 is one of the most comprehensive and powerful utilities for Mac users, offering a range of features that can help you diagnose and fix any issues with your hard drive, memory, partition map, battery, RAID, and more. TechTool Pro 11.0.6 Build 5444 Download Zip https://shurll.com/2wGlYH In this article, we will show you how to use TechTool Pro 11.0.6 Build 5444 to check the health of your Mac and resolve any problems that may affect its performance or stability. What is TechTool Pro 11.0.6 Build 5444?TechTool Pro 11.0.6 Build 5444 is the latest version of the popular Mac utility developed by Micromat Inc. It is compatible with macOS 10.10 or later and supports both Intel and Apple Silicon processors. TechTool Pro 11.0.6 Build 5444 can perform a variety of tests and repairs on your Mac, including: Testing and repairing MS-DOS (FAT32) and ExFAT formatted volumes, such as flash drives, memory cards, and external hard disks.Testing and repairing the partition map of your drive, which contains the information about the volumes on your drive.Testing and repairing the file system of your Mac volumes, which stores the data on your drive.Testing and repairing the SMART (Self Monitoring, Analysis and Reporting Technology) status of your hard drive, which can alert you to potential failures or errors.Testing and repairing the power on self-test (POST) errors, which can indicate hardware problems during startup.Testing and repairing the internal battery condition of your Mac notebook, which can affect its performance and lifespan.Testing and repairing the RAID status of your drive, if applicable, which can improve its speed and reliability.TechTool Pro 11.0.6 Build 5444 also offers other useful features, such as: Creating an emergency startup partition on your drive that can boot your Mac in case of system failure.Cloning your entire drive or selected volumes to another drive for backup or migration purposes.Recovering deleted files from your drive or other devices using advanced data recovery algorithms.Optimizing your drive by defragmenting files and consolidating free space.Benchmarking your drive by measuring its read and write speeds.Erasing your drive securely by overwriting it with random data multiple times.Monitoring your network performance by testing the connectivity and speed of your internet connection.How to Use TechTool Pro 11.0.6 Build 5444?To use TechTool Pro 11.0.6 Build 5444, you need to download it from the official website or from a trusted source such as InsMac.org. The file size is about 188 MB and you need to have at least 1 GB of free space on your drive to install it. Once you have downloaded TechTool Pro 11.0.6 Build 5444, you need to mount the disk image file and drag the TechTool Pro app to your Applications folder. You may also want to install the TechTool Protection system preference pane, which can monitor your Mac's health in the background and alert you to any issues that may arise. To launch TechTool Pro 11.0.6 Build 5444, you need to double-click on the app icon in your Applications folder or use Spotlight to search for it. You may be asked to enter your administrator password to allow TechTool Pro to access your system files and devices. The main window o -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/5a4968ba-e2c7-4838-aecf-d0d89b18cecbn%40googlegroups.com.
[sqlalchemy] RUPIAH TOTO WEBSITE PENIPU DEPOSIT TIDAK DI PROSES WD TIDAK DI BAYAR
https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip (makananya jgn main phising boy kalau gk mau kena getahnya ) RUPIAH TOTO | login RUPIAH TOTO | RUPIAH TOTO login | RUPIAH TOTO link alternatif | link alternatif rupiah toto | link rupiah toto | login rupiah toto | rupiah toto login | rtp rupiah toto | rupiah toto rtp | rupiah toto promo | promo rupiah toto | free bet | free chip | bonus 10ribu | slot rupiah toto | website rupiah toto | web rupiah toto | free chip rupiah toto | free bet rupiah toto -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/abd190b1-b839-4112-8d64-f080695b27cfn%40googlegroups.com.
[sqlalchemy] RUPIAH TOTO WEBSITE PENIPU DEPOSIT TIDAK DI PROSES WD TIDAK DI BAYAR
https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip (makananya jgn main phising boy kalau gk mau kena getahnya ) RUPIAH TOTO | login RUPIAH TOTO | RUPIAH TOTO login | RUPIAH TOTO link alternatif | link alternatif rupiah toto | link rupiah toto | login rupiah toto | rupiah toto login | rtp rupiah toto | rupiah toto rtp | rupiah toto promo | promo rupiah toto | free bet | free chip | bonus 10ribu | slot rupiah toto | website rupiah toto | web rupiah toto | free chip rupiah toto | free bet rupiah toto -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/8f3e4b2b-3bd8-495f-a410-a1e50c061e27n%40googlegroups.com.
[sqlalchemy] RUPIAH TOTO WEBSITE PENIPU DEPOSIT TIDAK DI PROSES WD TIDAK DI BAYAR
https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip (makananya jgn main phising boy kalau gk mau kena getahnya ) RUPIAH TOTO | login RUPIAH TOTO | RUPIAH TOTO login | RUPIAH TOTO link alternatif | link alternatif rupiah toto | link rupiah toto | login rupiah toto | rupiah toto login | rtp rupiah toto | rupiah toto rtp | rupiah toto promo | promo rupiah toto | free bet | free chip | bonus 10ribu | slot rupiah toto | website rupiah toto | web rupiah toto | free chip rupiah toto | free bet rupiah toto -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/899aa9ef-3ba3-4b06-bc35-734500f2a077n%40googlegroups.com.
[sqlalchemy] RUPIAH TOTO WEBSITE PENIPU DEPOSIT TIDAK DI PROSES WD TIDAK DI BAYAR
https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip https://surelink.online/vip (makananya jgn main phising boy kalau gk mau kena getahnya ) RUPIAH TOTO | login RUPIAH TOTO | RUPIAH TOTO login | RUPIAH TOTO link alternatif | link alternatif rupiah toto | link rupiah toto | login rupiah toto | rupiah toto login | rtp rupiah toto | rupiah toto rtp | rupiah toto promo | promo rupiah toto | free bet | free chip | bonus 10ribu | slot rupiah toto | website rupiah toto | web rupiah toto | free chip rupiah toto | free bet rupiah toto -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/7f3dd070-d183-436f-bce5-3b16d4247cb4n%40googlegroups.com.
[sqlalchemy] MPL777 LINK ALTERNATIF DIBAWAH INI ANTI BLOKIR
rtp | mpl777 promo | promo mpl777 | free bet | free chip | bonus 10ribu | slot mpl777 | website mpl777 | web mpl777 -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/f32a81ca-a37f-4838-8d34-c42748904623n%40googlegroups.com.
[sqlalchemy] SERING RUNGKAT MAIN DI WEBSITE LAIN ? BERALIH KE GAMEPLAY777 TGARANSI WD 100%
://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih GAMEPLAY777 | GAMEPLAY777 LOGIN | LOGIN GAMEPLAY777 | GAMEPLAY777 RTP | RTP GAMEPLAY777 | GAMEPLAY7 | GAMEPLAY77 | GAMEPLAY777 LINK ALTERNATIF | LINK ALTERNATIF GAMEPLAY777 | WEBSITE GAMEPLAY777 | LINK GAMEPLAY777 | URL GAMEPLAY777 | DAFTAR GAMEPLAY777 | WEBSITE JUDI ONLINE | SLOT GACOR GAMEPLAY777 | SLOT GAMEPLAY777 | BERITA GAMEPLAY777 | RTP GACOR GAMEPLAY777 -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/360ec8e3-9724-4415-a745-31459748f43en%40googlegroups.com.
[sqlalchemy] Selamat Datang & Selamat bergabung di website *Gacor GAMEPLAY777* WEBSITE TERGACOR & WEBSITE TERPERCAYA 2023
https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih https://surelink.online/siputih -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/4658b7cd-c6c5-42d0-8347-367cea280b6fn%40googlegroups.com.
[sqlalchemy] Situs Santoto Min Depo 10rb | Min WD 50rb
Link Daftar Santoto : https://heylink.me/jpm4xwiin Link Login Santoto : https://linkr.bio/loginsantoto Link Santoto Gacor : https://linklist.bio/santoto Link Anti Blokir Santoto : https://maxsantoto.com/ Link Alternatif Santoto : https://arenasan.xyz/ SANTOTO » SITUS BANDAR TOGEL ONLINE TERPERCAYA , DAFTAR SLOT GACOR 100% , CASINO ONLINE DENGAN HADIAH TERBESAR DAN TERBUKTI 100% RESMI DI INDONESIA SUDAH BERDIRI SEJAK TAHUN 2014. KAMI MENYEDIAKAN LINK ALTERNATIF SANTOTO ATAU BISA DI SEBUT SANTOTO SLOT DAN TOGEL TERPERCAYA MENANG BERAPA PUN DI BAYAR LUNAS. SANTOTO I SANTOTO TOGEL ONLINE I SANTOTO SLOT ONLINE I SLOT SANTOTO GACOR I CASINO ONLINE SANTOTO I LIVE CASINO SANTOTOI TOGEL SANTOTO I PREDIKSI TOGEL SANTOTO I SAN TOTO | SANTOTO88 -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/ed8879ed-0874-428a-b47f-42ee5e115e57n%40googlegroups.com.
[sqlalchemy] Re: ✅TOTOJITU, ✅DAFTAR TOTOJITU, ✅SITUS TOTOJITU, ✅LINK TOTOJITU
://heyboy.link/googleedi Pada Kamis, 02 November 2023 pukul 14.17.14 UTC+7 Dharmawan Luis menulis: > LINK LOGIN TOTOJITU: https://heylink.me/totojitu1/ > LINK DAFTAR TOTOJITU: https://heylink.me/totojitu1/ > > DAFTAR LINK TOTOJITU > LINK GACOR TOTOJITU > LINK DEPOSIT TOTOJITU > LINK DAFTAR TOTOJITU > LINK ALTERNATIF TOTOJITU > LINK SLOT GACOR > LINK SLOT THAILAND > LINK SLOT PULSA > LINK SLOT DEPO 10K > DIATAS ADALAH LINK TOTOJITU TERPERCAYA 2023 > > Selamat datang di TOTOJITU⚡️! Kami adalah situs terkemuka dalam dunia slot > online, dan kami bangga menyajikan pengalaman bermain slot demo Olympus > yang tak tertandingi kepada seluruh pemain kami. Dalam artikel ini, kami > akan menjelaskan mengapa TOTOJITU⚡️ adalah pilihan utama bagi mereka yang > ingin mendaftar dan mencoba peruntungan dalam permainan slot demo Olympus. > > Keunggulan TOTOJITU⚡️ > TOTOJITU ⚡️ memiliki sejumlah keunggulan yang menjadikannya situs slot > terbaik dan unggul dalam industri ini. Berikut adalah beberapa dari > keunggulan kami: > > 1. Beragam Pilihan Permainan Slot > > TOTOJITU⚡️ menawarkan beragam permainan slot yang bisa Anda nikmati. Mulai > dari tema klasik hingga yang lebih modern, kami memiliki semua jenis > permainan yang Anda cari. Dengan lebih dari 1000 judul permainan yang > tersedia, Anda tidak akan pernah bosan bermain di TOTOJITU⚡️ > > 2.Grafis Berkualitas Tinggi > > Kami sangat memahami bahwa visual yang menarik sangat penting dalam > permainan slot. Oleh karena itu, kami berkolaborasi dengan penyedia > perangkat lunak terbaik untuk memastikan grafis permainan kami selalu > berkualitas tinggi dan memukau. Setiap putaran slot di TOTOJITU⚡️ akan > memberikan pengalaman visual yang luar biasa. > > 3.Jackpot Besar > TOTOJITU⚡️ memberikan peluang untuk memenangkan jackpot besar. Kami > menyediakan berbagai jenis jackpot, beberapa di antaranya mencapai jumlah > yang sangat menggiurkan. Bergabunglah sekarang dan raih peluang Anda untuk > menjadi jutawan! > > 4.Daftar di TOTOJITU⚡️ Sekarang > Jika Anda ingin merasakan semua manfaat yang ditawarkan oleh TOTOJITU⚡️, > jangan ragu untuk mendaftar sekarang. Proses pendaftaran kami mudah dan > cepat, sehingga Anda dapat segera memulai permainan. Jangan sia-siakan > kesempatan untuk bermain slot demo Olympus dan memenangkan hadiah-hadiah > besar. > > Dengan bermain di TOTOJITU⚡️, Anda akan mengalami pengalaman bermain slot > yang tak terlupakan. Bergabunglah dengan komunitas pemain kami sekarang dan > jadilah bagian dari situs slot terbesar dan terbaik di Indonesia. Terima > kasih telah memilih TOTOJITU⚡️ sebagai tempat bermain slot pilihan Anda! > -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/adc86b05-827e-417d-8f9f-e9e838b49cfen%40googlegroups.com.
Re: [sqlalchemy] Composite columns and None
On Tue, Nov 14, 2023, at 6:02 PM, jens.t...@gmail.com wrote: > Hello everyone, > > I wanted to follow up on the examples on Composite Column Types > <https://docs.sqlalchemy.org/en/20/orm/composites.html> and in particular > setting the mapped composite value in Python-land to *None*. > > For instance, this class > *@dataclasses*.dataclass > *class* *Point*: > x: int > y: int > is used in the following composite mapping and I’d like the two mapped > properties to be optional (for the sake of the argument, whether it makes > sense or not): > *class* *Vertex*(Base): > start: Mapped[Point] | None = composite(mapped_column("x1"), > mapped_column("y1")) > end: Mapped[Point] | None = composite(mapped_column("x2"), > mapped_column("y2"))The optional would then have to map to *nullable=True* > for both mapped columns, which in turn would need to be checked to ensure > integrity — either both or neither of the two mapped columns for a *Point* > can be NULL at the same time. > > I wasn’t able to find a recipe > <https://docs.sqlalchemy.org/en/20/orm/examples.html> for this use case. > What’s the recommendation to implement this? Will I have to roll most of this > manually, or does SQLA provide support? you can create this using a custom callable for the actual composite type, where you would be bypassing the new-style annotations and dataclass detection part of things and relying on the older style of declaration. You'd add a composite_values to your dataclass as well and just use the old style import dataclasses from sqlalchemy import create_engine from sqlalchemy import Integer from sqlalchemy import select from sqlalchemy.orm import composite from sqlalchemy.orm import DeclarativeBase from sqlalchemy.orm import Mapped from sqlalchemy.orm import mapped_column from sqlalchemy.orm import Session @dataclasses.dataclass class Point: x: int | None y: int | None def __composite_values__(self): return (self.x, self.y) class Base(DeclarativeBase): pass def nullable_point(x, y): if x is None and y is None: return None else: return Point(x, y) class Vertex(Base): __tablename__ = "vertices" id: Mapped[int] = mapped_column(primary_key=True) start: Mapped[Point | None] = composite( nullable_point, mapped_column("x1", Integer, nullable=True), mapped_column("y1", Integer, nullable=True), ) end: Mapped[Point | None] = composite( nullable_point, mapped_column("x2", Integer, nullable=True), mapped_column("y2", Integer, nullable=True), ) def __repr__(self): return f"Vertex(start={self.start}, end={self.end})" e = create_engine("sqlite://", echo=True) Base.metadata.create_all(e) s = Session(e) s.add_all( [ Vertex(start=Point(5, 10)), Vertex(start=Point(10, None), end=Point(25, 17)), ] ) s.commit() for v in s.scalars(select(Vertex)): print(f"{v.start} {v.end}") > > Much thanks! > Jens > > > -- > SQLAlchemy - > The Python SQL Toolkit and Object Relational Mapper > > http://www.sqlalchemy.org/ > > To post example code, please provide an MCVE: Minimal, Complete, and > Verifiable Example. See http://stackoverflow.com/help/mcve for a full > description. > --- > You received this message because you are subscribed to the Google Groups > "sqlalchemy" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to sqlalchemy+unsubscr...@googlegroups.com. > To view this discussion on the web visit > https://groups.google.com/d/msgid/sqlalchemy/e0a3f019-11d0-4156-9c13-0a0e493dc40an%40googlegroups.com > > <https://groups.google.com/d/msgid/sqlalchemy/e0a3f019-11d0-4156-9c13-0a0e493dc40an%40googlegroups.com?utm_medium=email_source=footer>. -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/8da01a71-032d-4c95-82fb-b27970be111e%40app.fastmail.com.
[sqlalchemy] Re: Composite columns and None
Come to think of it, mapping to *None* doesn’t make much sense because then there’s no mapper. However, it probably would make sense to define an “invalid” mapped Point if all mapped columns are NULL. In that case, I’d still consider adding check constraints to mildly improve integrity, although if any one mapped properties is NULL then by definition to Point would be invalid. Hmm 樂 On Wednesday, November 15, 2023 at 9:02:16 AM UTC+10 jens.t...@gmail.com wrote: > Hello everyone, > > I wanted to follow up on the examples on Composite Column Types > <https://docs.sqlalchemy.org/en/20/orm/composites.html> and in particular > setting the mapped composite value in Python-land to *None*. > > For instance, this class > @dataclasses.dataclass > class Point: > x: int > y: int > is used in the following composite mapping and I’d like the two mapped > properties to be optional (for the sake of the argument, whether it makes > sense or not): > class Vertex(Base): > start: Mapped[Point] | None = composite(mapped_column("x1"), > mapped_column("y1")) > end: Mapped[Point] | None = composite(mapped_column("x2"), > mapped_column("y2"))The optional would then have to map to *nullable=True* > for > both mapped columns, which in turn would need to be checked to ensure > integrity — either both or neither of the two mapped columns for a *Point* > can be NULL at the same time. > > I wasn’t able to find a recipe > <https://docs.sqlalchemy.org/en/20/orm/examples.html> for this use case. > What’s the recommendation to implement this? Will I have to roll most of > this manually, or does SQLA provide support? > > Much thanks! > Jens > -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/e3f64225-bcad-4fde-b77a-08312a0cc46dn%40googlegroups.com.
[sqlalchemy] Composite columns and None
Hello everyone, I wanted to follow up on the examples on Composite Column Types <https://docs.sqlalchemy.org/en/20/orm/composites.html> and in particular setting the mapped composite value in Python-land to *None*. For instance, this class @dataclasses.dataclass class Point: x: int y: int is used in the following composite mapping and I’d like the two mapped properties to be optional (for the sake of the argument, whether it makes sense or not): class Vertex(Base): start: Mapped[Point] | None = composite(mapped_column("x1"), mapped_column("y1")) end: Mapped[Point] | None = composite(mapped_column("x2"), mapped_column ("y2"))The optional would then have to map to *nullable=True* for both mapped columns, which in turn would need to be checked to ensure integrity — either both or neither of the two mapped columns for a *Point* can be NULL at the same time. I wasn’t able to find a recipe <https://docs.sqlalchemy.org/en/20/orm/examples.html> for this use case. What’s the recommendation to implement this? Will I have to roll most of this manually, or does SQLA provide support? Much thanks! Jens -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/e0a3f019-11d0-4156-9c13-0a0e493dc40an%40googlegroups.com.
[sqlalchemy] Re: DAFTAR LINK ALTERNATIF PETIRTOTO SITUS SLOT ONLINE PALING GACOR DAN TERPERCAYA
Link daftar permai4d : https://tinyurl.com/3a7br56d Link daftar slot gacor permai4d: https://tinyurl.com/5atrpfbb Link alternatif slot gacor permai4d : https://tinyurl.com/56m9tc5w slot gacor link daftar : https://tinyurl.com/2txh3zcn slot gacor link login : https://tinyurl.com/5atrpfbb slot gacor Link alternatif : https://tinyurl.com/5atrpfbb Link daftar akun gacor permai4d: https://tinyurl.com/56m9tc5w Link daftar akun gacor : https://tinyurl.com/3a7br56d Link daftar akun gacor : https://tinyurl.com/5atrpfbb Pada Kamis, 02 November 2023 pukul 14.20.17 UTC+7 ayu lestari menulis: > DAFTAR LINK ALTERNATIF PETIRTOTO SITUS SLOT ONLINE PALING GACOR DAN > TERPERCAYA > LINK LOGIN PETIRTOTO : https://heylink.me/Petirtoto.com/ > LINK DAFTAR PETIRTOTO : https://heylink.me/Petirtoto.com/ > LINK AKUN GACOR : https://heylink.me/Petirtoto.com/ > LINK AKUN VIP : https://heylink.me/Petirtoto.com/ > > PETIRTOTO | LINK PETIRTOTO | SLOT PETIRTOTO | LOGIN PETIRTOTO | PETIRTOTO > TERPERCAYA | PETIRTOTO TERBAIK > > Agen Toto Togel Slot Online Terbaik Terpercaya - Petirtoto > > Pada Kamis, 02 November 2023 pukul 14.17.14 UTC+7 Dharmawan Luis menulis: > >> LINK LOGIN TOTOJITU: https://heylink.me/totojitu1/ >> LINK DAFTAR TOTOJITU: https://heylink.me/totojitu1/ >> >> DAFTAR LINK TOTOJITU >> LINK GACOR TOTOJITU >> LINK DEPOSIT TOTOJITU >> LINK DAFTAR TOTOJITU >> LINK ALTERNATIF TOTOJITU >> LINK SLOT GACOR >> LINK SLOT THAILAND >> LINK SLOT PULSA >> LINK SLOT DEPO 10K >> DIATAS ADALAH LINK TOTOJITU TERPERCAYA 2023 >> >> Selamat datang di TOTOJITU⚡️! Kami adalah situs terkemuka dalam dunia >> slot online, dan kami bangga menyajikan pengalaman bermain slot demo >> Olympus yang tak tertandingi kepada seluruh pemain kami. Dalam artikel ini, >> kami akan menjelaskan mengapa TOTOJITU⚡️ adalah pilihan utama bagi mereka >> yang ingin mendaftar dan mencoba peruntungan dalam permainan slot demo >> Olympus. >> >> Keunggulan TOTOJITU⚡️ >> TOTOJITU ⚡️ memiliki sejumlah keunggulan yang menjadikannya situs slot >> terbaik dan unggul dalam industri ini. Berikut adalah beberapa dari >> keunggulan kami: >> >> 1. Beragam Pilihan Permainan Slot >> >> TOTOJITU⚡️ menawarkan beragam permainan slot yang bisa Anda nikmati. >> Mulai dari tema klasik hingga yang lebih modern, kami memiliki semua jenis >> permainan yang Anda cari. Dengan lebih dari 1000 judul permainan yang >> tersedia, Anda tidak akan pernah bosan bermain di TOTOJITU⚡️ >> >> 2.Grafis Berkualitas Tinggi >> >> Kami sangat memahami bahwa visual yang menarik sangat penting dalam >> permainan slot. Oleh karena itu, kami berkolaborasi dengan penyedia >> perangkat lunak terbaik untuk memastikan grafis permainan kami selalu >> berkualitas tinggi dan memukau. Setiap putaran slot di TOTOJITU⚡️ akan >> memberikan pengalaman visual yang luar biasa. >> >> 3.Jackpot Besar >> TOTOJITU⚡️ memberikan peluang untuk memenangkan jackpot besar. Kami >> menyediakan berbagai jenis jackpot, beberapa di antaranya mencapai jumlah >> yang sangat menggiurkan. Bergabunglah sekarang dan raih peluang Anda untuk >> menjadi jutawan! >> >> 4.Daftar di TOTOJITU⚡️ Sekarang >> Jika Anda ingin merasakan semua manfaat yang ditawarkan oleh TOTOJITU⚡️, >> jangan ragu untuk mendaftar sekarang. Proses pendaftaran kami mudah dan >> cepat, sehingga Anda dapat segera memulai permainan. Jangan sia-siakan >> kesempatan untuk bermain slot demo Olympus dan memenangkan hadiah-hadiah >> besar. >> >> Dengan bermain di TOTOJITU⚡️, Anda akan mengalami pengalaman bermain slot >> yang tak terlupakan. Bergabunglah dengan komunitas pemain kami sekarang dan >> jadilah bagian dari situs slot terbesar dan terbaik di Indonesia. Terima >> kasih telah memilih TOTOJITU⚡️ sebagai tempat bermain slot pilihan Anda! >> > -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/56a8df12-1e5a-4fcc-aeda-d71162e4da48n%40googlegroups.com.
[sqlalchemy] Issue with cascade deletion
Hi, so I have the database classes as follows: class Thing(Base): DatasetId = Column(ForeignKey(schema + 'Dataset.DatasetId'), primary_key=True, nullable=False, index=True) RequiredThing_child = relationship('RequiredThing', cascade='all, delete-orphan') class Location(Base): DatasetId = Column(ForeignKey(schema + 'Dataset.DatasetId'), primary_key=True, nullable=False, index=True) RequiredThing_child = relationship('RequiredThing', cascade='all, delete-orphan') class RequiredThing(Base): DatasetId = Column(ForeignKey(schema + 'Dataset.DatasetId'), primary_key=True, nullable=False, index=True) Thing= relationship('Thing', viewonly=True) Location= relationship('Location', viewonly=True) (There are more relationships on both tables but these ones are the only ones that I've had issues with, as they both have that column). I set them up like that because I want to have the cascade deletion functionality: whenever I call for a deletion of a thing object I want the children (in this case RequiredThing) to be deleted as well (as long as it matches with the Thing Id). When I had it active for only one table (in this case Thing), it worked fine but now that I also added the relationship for the Location table it's giving me the following warning: SAWarning: relationship 'Location.RequiredThing_child' will copy column Location.DatasetId to column RequiredThing.DatasetId, which conflicts with relationship: 'Thing.RequiredThing_child' (copies Thing.DatasetId to RequiredThing.DatasetId). I've tried to add back_populates to the RequiredThing class but to no avail. I need this to work because I want to implement the cascade functionality to many more tables as needed but I do not want there to be any errors or ambiguity when running the queries. Or if there's a better way to implement cascade deletion I'm all for it. Any suggestions or corrections to my code would be greatly appreciated! Kind regards, Javier (reposted to edit the paragraphs) -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/eb7201ef-32d5-4858-8b00-5fd6349a2c6dn%40googlegroups.com.
[sqlalchemy] Issue with cascade deletion for multiple tables
Hi, so I have the database classes as follows: class Thing(Base): DatasetId = Column(ForeignKey(schema + 'Dataset.DatasetId'), primary_key=True, nullable=False, index=True) RequiredThing_child = relationship('RequiredThing', cascade='all, delete-orphan') class Location(Base): DatasetId = Column(ForeignKey(schema + 'Dataset.DatasetId'), primary_key=True, nullable=False, index=True) RequiredThing_child = relationship('RequiredThing', cascade='all, delete-orphan') class RequiredThing(Base): DatasetId = Column(ForeignKey(schema + 'Dataset.DatasetId'), primary_key=True, nullable=False, index=True) Thing= relationship('Thing', viewonly=True) Location= relationship('Location', viewonly=True) (There are more relationships on both tables but these ones are the only ones that I've had issues with, as they both have that column). I set them up like that because I want to have the cascade deletion functionality: whenever I call for a deletion of a thing object I want the children (in this case RequiredThing) to be deleted as well (as long as it matches with the Thing Id). When I had it active for only one table (in this case Thing), it worked fine but now that I also added the relationship for the Location table it's giving me the following warning: SAWarning: relationship 'Location.RequiredThing_child' will copy column Location.DatasetId to column RequiredThing.DatasetId, which conflicts with relationship: 'Thing.RequiredThing_child' (copies Thing.DatasetId to RequiredThing.DatasetId). I've tried to add back_populates to the RequiredThing class but to no avail. I need this to work because I want to implement the cascade functionality to many more tables as needed but I do not want there to be any errors or ambiguity when running the queries. Or if there's a better way to implement cascade deletion I'm all for it. Any suggestions or corrections to my code would be greatly appreciated! Kind regards, Javier -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/939c6c1f-6bec-4309-a81e-9303d46af33an%40googlegroups.com.
[sqlalchemy] Re: sqlacodegen --noclaases depracated?
sqlacodegen is a third party tool. Your best option for support is on their Github page: https://github.com/agronholm/sqlacodegen/discussions/categories/q-a On Monday, October 23, 2023 at 2:38:15 PM UTC-4 peter.dani...@gmail.com wrote: > SQLAlchemy and sqlacodegen noob here. I'd like to just get some simple > SQLAlchemy tables generated for my database. I tried using --noclasses, > but it doesn't seem to recognize the option. > > sqlacodegen --noclasses mysql+pymysql://root:@localhost:3306/mydb > > sqlacodegen: error: unrecognized arguments: --noclasses > > How can I get it to just gen some tables? > > This is what I read in the project docs: > "Unless the --noclasses option is used, sqlacodegen tries to generate > declarative model classes from each table." > From: https://pypi.org/project/sqlacodegen/ > > Thanks! > > -Peter > -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/1410ad86-ab12-468b-86f4-e156ddeaeb0bn%40googlegroups.com.
Re: [sqlalchemy] sqlalchemy 2.0 and ABCMeta
hi - I'm not sure what the issue is but if you are tinkering with metaclasses, we first off have an alternate version of DeclarativeBase called DeclarativeBaseNoMeta that has no metaclass installed, and may be a better place to build off custom metaclass solutions as you wont need to be subclassing the internal metaclass used by DeclarativeBase. I would advise reading the source code for the DeclarativeBase / DeclarativeBaseNoMeta classes, paying special attention to the __init_subclass__() method which is where Declarative now does its work, and ensuring any __init_subclass__ method on your own class is working as expected and not interfering with the one called by SQLAlchemy's class (or just vendor the method yourself if necessary). On Thu, Nov 9, 2023, at 3:04 AM, 'Iwan Vosloo' via sqlalchemy wrote: > Hi there, > > We are migrating our code from SqlAlchemy 1.4 to 2.0 (2.0.23 to be > specific). > > We have had the following, which allowed some classes inheriting from > our Base to use an ABCMeta metaclass: > > --- > class DeclarativeABCMeta(DeclarativeMeta, ABCMeta): > pass > > metadata = MetaData(naming_convention=naming_convention) > Base = declarative_base(metadata=metadata, metaclass=DeclarativeABCMeta) > --- > > The code above works fine on 2.0, but if we want heed the 2.0 docs that > comment that declarative_base is superceded by using a class inheriting > from DeclarativeBase, we ought to have something like: > > --- > class DeclarativeABCMeta(DeclarativeMeta, ABCMeta): > pass > > metadata = MetaData(naming_convention=naming_convention) > > class Base(DeclarativeBase, metaclass=DeclarativeABCMeta): > """A Base for using with declarative.""" > __abstract__ = True > metadata = metadata > --- > > This, however breaks when it hits the first class inheriting from Base: > > --- > class SchemaVersion(Base): > __tablename__ = 'reahl_schema_version' > id = Column(Integer, primary_key=True) > version = Column(String(50)) > egg_name = Column(String(80)) > ------- > > With: > > [site-packages]/sqlalchemy/orm/decl_api.py:195: in __init__ > _as_declarative(reg, cls, dict_) > [site-packages]/sqlalchemy/orm/decl_base.py:247: in _as_declarative > return _MapperConfig.setup_mapping(registry, cls, dict_, None, {}) > [site-packages]/sqlalchemy/orm/decl_base.py:328: in setup_mapping > return _ClassScanMapperConfig( > [site-packages]/sqlalchemy/orm/decl_base.py:520: in __init__ > super().__init__(registry, cls_, mapper_kw) > [site-packages]/sqlalchemy/orm/decl_base.py:344: in __init__ > instrumentation.register_class( > [site-packages]/sqlalchemy/orm/instrumentation.py:684: in register_class > manager._update_state( > [site-packages]/sqlalchemy/orm/instrumentation.py:209: in _update_state > registry._add_manager(self) > [site-packages]/sqlalchemy/orm/decl_api.py:1380: in _add_manager > raise exc.ArgumentError( > E sqlalchemy.exc.ArgumentError: Class ' 'reahl.sqlalchemysupport.sqlalchemysupport.SchemaVersion'>' already has > a primary mapper defined. > > Any ideas on what we are doing wrong here? > > Thanks > Iwan > > -- > > -- > SQLAlchemy - > The Python SQL Toolkit and Object Relational Mapper > > http://www.sqlalchemy.org/ > > To post example code, please provide an MCVE: Minimal, Complete, and > Verifiable Example. See http://stackoverflow.com/help/mcve for a full > description. > --- > You received this message because you are subscribed to the Google > Groups "sqlalchemy" group. > To unsubscribe from this group and stop receiving emails from it, send > an email to sqlalchemy+unsubscr...@googlegroups.com. > To view this discussion on the web visit > https://groups.google.com/d/msgid/sqlalchemy/5d616bf0-ffa7-4061-adaf-cf1c7577e0fc%40reahl.org. -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/8ae83685-03c3-4b80-b2a3-c4d228d94626%40app.fastmail.com.
[sqlalchemy] sqlalchemy 2.0 and ABCMeta
Hi there, We are migrating our code from SqlAlchemy 1.4 to 2.0 (2.0.23 to be specific). We have had the following, which allowed some classes inheriting from our Base to use an ABCMeta metaclass: --- class DeclarativeABCMeta(DeclarativeMeta, ABCMeta): pass metadata = MetaData(naming_convention=naming_convention) Base = declarative_base(metadata=metadata, metaclass=DeclarativeABCMeta) --- The code above works fine on 2.0, but if we want heed the 2.0 docs that comment that declarative_base is superceded by using a class inheriting from DeclarativeBase, we ought to have something like: --- class DeclarativeABCMeta(DeclarativeMeta, ABCMeta): pass metadata = MetaData(naming_convention=naming_convention) class Base(DeclarativeBase, metaclass=DeclarativeABCMeta): """A Base for using with declarative.""" __abstract__ = True metadata = metadata --- This, however breaks when it hits the first class inheriting from Base: --- class SchemaVersion(Base): __tablename__ = 'reahl_schema_version' id = Column(Integer, primary_key=True) version = Column(String(50)) egg_name = Column(String(80)) --- With: [site-packages]/sqlalchemy/orm/decl_api.py:195: in __init__ _as_declarative(reg, cls, dict_) [site-packages]/sqlalchemy/orm/decl_base.py:247: in _as_declarative return _MapperConfig.setup_mapping(registry, cls, dict_, None, {}) [site-packages]/sqlalchemy/orm/decl_base.py:328: in setup_mapping return _ClassScanMapperConfig( [site-packages]/sqlalchemy/orm/decl_base.py:520: in __init__ super().__init__(registry, cls_, mapper_kw) [site-packages]/sqlalchemy/orm/decl_base.py:344: in __init__ instrumentation.register_class( [site-packages]/sqlalchemy/orm/instrumentation.py:684: in register_class manager._update_state( [site-packages]/sqlalchemy/orm/instrumentation.py:209: in _update_state registry._add_manager(self) [site-packages]/sqlalchemy/orm/decl_api.py:1380: in _add_manager raise exc.ArgumentError( E sqlalchemy.exc.ArgumentError: Class ''reahl.sqlalchemysupport.sqlalchemysupport.SchemaVersion'>' already has a primary mapper defined. Any ideas on what we are doing wrong here? Thanks Iwan -- -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/5d616bf0-ffa7-4061-adaf-cf1c7577e0fc%40reahl.org.
Re: [sqlalchemy] Issue with type signature of DBAPI Connection
there does seem to be an extra Sequence on the outside that should be removed, please open an issue. On Tue, Nov 7, 2023, at 9:46 PM, William Hakim wrote: > I was recently using the DBAPI Cursor, and it seems to me that the type > signature of the `executemany()` function is incorrect: > > https://github.com/sqlalchemy/sqlalchemy/blob/main/lib/sqlalchemy/engine/interfaces.py#L194 > > The given type signature for the second argument to `executemany()` is ` > "Sequence[Sequence[Sequence[Any]] | Sequence[Mapping[str, Any]]]"`, however > this doesn't appear right (and doesn't actually work) - it seems like it > should instead be `Sequence[Sequence[Any]] | Sequence[Mapping[str, Any]]`. > > Happy to open a Pull Request if this is indeed an issue. > > Will > > > -- > SQLAlchemy - > The Python SQL Toolkit and Object Relational Mapper > > http://www.sqlalchemy.org/ > > To post example code, please provide an MCVE: Minimal, Complete, and > Verifiable Example. See http://stackoverflow.com/help/mcve for a full > description. > --- > You received this message because you are subscribed to the Google Groups > "sqlalchemy" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to sqlalchemy+unsubscr...@googlegroups.com. > To view this discussion on the web visit > https://groups.google.com/d/msgid/sqlalchemy/048482ea-0c27-46e3-9acf-6257d685f855n%40googlegroups.com > > <https://groups.google.com/d/msgid/sqlalchemy/048482ea-0c27-46e3-9acf-6257d685f855n%40googlegroups.com?utm_medium=email_source=footer>. -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/4898aaa6-94da-4bfc-baab-d537688ced68%40app.fastmail.com.
[sqlalchemy] Issue with type signature of DBAPI Connection
I was recently using the DBAPI Cursor, and it seems to me that the type signature of the `executemany()` function is incorrect: https://github.com/sqlalchemy/sqlalchemy/blob/main/lib/sqlalchemy/engine/interfaces.py#L194 The given type signature for the second argument to `executemany()` is ` "Sequence[Sequence[Sequence[Any]] | Sequence[Mapping[str, Any]]]"`, however this doesn't appear right (and doesn't actually work) - it seems like it should instead be `Sequence[Sequence[Any]] | Sequence[Mapping[str, Any]]`. Happy to open a Pull Request if this is indeed an issue. Will -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/048482ea-0c27-46e3-9acf-6257d685f855n%40googlegroups.com.
Re: [sqlalchemy] Connection issue with URL-encoded passwords in `do-connect` event
Yes, it does. Thank you for the explanation. On Saturday, November 4, 2023 at 1:09:32 AM UTC-7 Mike Bayer wrote: > > > On Fri, Nov 3, 2023, at 7:41 PM, SeJun Bae wrote: > > Hello everyone, > I have encountered an odd behavior when using URL-encoded tokens as > passwords for connections with Postgres; my application connects to a > Postgres AWS RDS instance using a token that expires (IAM Authentication > <https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.html>). > > Specifically, if I set `cparams['password']` to a URL-encoded value in the > `do_connect` event, the connection fails. However, it succeeds if the value > isn't URL encoded. This seems inconsistent with how the engine handles > URL-encoded values. Is this the intended behavior ? > > > the password needs to be url encoded, *when embedded into the URL*. When > you handle the password as a single value in the parameters sent to the > DBAPI, this needs to be the actual password, and not URL encoded, since > it's not being extracted from a URL. This is consistent with the API for > the URL object itself, where you have the option to create a URL > progammatically from non-encoded fields (see > https://docs.sqlalchemy.org/en/20/core/engines.html#creating-urls-programmatically). > > hope this helps > > > > If not, would the team be open to a PR that calls `unquote` on the > `cparams['password'] when it's changed to ensure consistency ? > > Here is a minimal example to illustrate the issue: > > from sqlalchemy.orm import sessionmaker > from sqlalchemy import create_engine, event, text > from urllib.parse import quote > > > > > > > > > > > > > > > > > > > > > > > > > > *# Assume there is a db user `test` with some initial tokenPOSTGRES_HOST = > 'localhost'PORT = '5432'USERNAME = 'test'NEW_PASSWORD = '%2FH'engine1 = > create_engine(f"postgresql://{USERNAME}:some_token_that_expires@{POSTGRES_HOST}:{PORT}/esrf", > > echo=True)@event.listens_for(engine1, 'do_connect')def > receive_do_connect(dialect, conn_rec, cargs, cparams):# This doesn't > work.cparams['password'] = quote(NEW_PASSWORD)with engine1.connect() as > connection:connection.execute(text('SELECT 1;'))engine2 = > create_engine(f"postgresql://{USERNAME}:some_token_that_expires@{POSTGRES_HOST}:{PORT}/esrf", > > echo=True)@event.listens_for(engine2, 'do_connect')def > receive_do_connect(dialect, conn_rec, cargs, cparams):# This works > cparams['password'] = NEW_PASSWORDwith engine2.connect() as connection: > connection.execute(text('SELECT 1;'))* > > > > -- > SQLAlchemy - > The Python SQL Toolkit and Object Relational Mapper > > http://www.sqlalchemy.org/ > > To post example code, please provide an MCVE: Minimal, Complete, and > Verifiable Example. See http://stackoverflow.com/help/mcve for a full > description. > --- > You received this message because you are subscribed to the Google Groups > "sqlalchemy" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to sqlalchemy+...@googlegroups.com. > To view this discussion on the web visit > https://groups.google.com/d/msgid/sqlalchemy/6a124e8b-fabc-47b6-8e68-db939acc98f7n%40googlegroups.com > > <https://groups.google.com/d/msgid/sqlalchemy/6a124e8b-fabc-47b6-8e68-db939acc98f7n%40googlegroups.com?utm_medium=email_source=footer> > . > > > -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/e958b2a9-9f8e-4bc1-a73b-fb5ea7ea86fdn%40googlegroups.com.
Re: [sqlalchemy] Connection issue with URL-encoded passwords in `do-connect` event
On Fri, Nov 3, 2023, at 7:41 PM, SeJun Bae wrote: > Hello everyone, > I have encountered an odd behavior when using URL-encoded tokens as passwords > for connections with Postgres; my application connects to a Postgres AWS RDS > instance using a token that expires (IAM Authentication > <https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.html>). > Specifically, if I set `cparams['password']` to a URL-encoded value in the > `do_connect` event, the connection fails. However, it succeeds if the value > isn't URL encoded. This seems inconsistent with how the engine handles > URL-encoded values. Is this the intended behavior ? the password needs to be url encoded, *when embedded into the URL*. When you handle the password as a single value in the parameters sent to the DBAPI, this needs to be the actual password, and not URL encoded, since it's not being extracted from a URL. This is consistent with the API for the URL object itself, where you have the option to create a URL progammatically from non-encoded fields (see https://docs.sqlalchemy.org/en/20/core/engines.html#creating-urls-programmatically). hope this helps > If not, would the team be open to a PR that calls `unquote` on the > `cparams['password'] when it's changed to ensure consistency ? > > Here is a minimal example to illustrate the issue: > > from sqlalchemy.orm import sessionmaker > from sqlalchemy import create_engine, event, text > from urllib.parse import quote > > *# Assume there is a db user `test` with some initial token > POSTGRES_HOST = 'localhost' > PORT = '5432' > USERNAME = 'test' > NEW_PASSWORD = '%2FH' > > engine1 = > create_engine(f"postgresql://{USERNAME}:some_token_that_expires@{POSTGRES_HOST}:{PORT}/esrf", > echo=True) > > @event.listens_for(engine1, 'do_connect') > def receive_do_connect(dialect, conn_rec, cargs, cparams): > # This doesn't work. > cparams['password'] = quote(NEW_PASSWORD) > > with engine1.connect() as connection: > connection.execute(text('SELECT 1;')) > > engine2 = > create_engine(f"postgresql://{USERNAME}:some_token_that_expires@{POSTGRES_HOST}:{PORT}/esrf", > echo=True) > > @event.listens_for(engine2, 'do_connect') > def receive_do_connect(dialect, conn_rec, cargs, cparams): > # This works > cparams['password'] = NEW_PASSWORD > > with engine2.connect() as connection: > connection.execute(text('SELECT 1;'))* > > > > > -- > SQLAlchemy - > The Python SQL Toolkit and Object Relational Mapper > > http://www.sqlalchemy.org/ > > To post example code, please provide an MCVE: Minimal, Complete, and > Verifiable Example. See http://stackoverflow.com/help/mcve for a full > description. > --- > You received this message because you are subscribed to the Google Groups > "sqlalchemy" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to sqlalchemy+unsubscr...@googlegroups.com. > To view this discussion on the web visit > https://groups.google.com/d/msgid/sqlalchemy/6a124e8b-fabc-47b6-8e68-db939acc98f7n%40googlegroups.com > > <https://groups.google.com/d/msgid/sqlalchemy/6a124e8b-fabc-47b6-8e68-db939acc98f7n%40googlegroups.com?utm_medium=email_source=footer>. -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/49e6a38c-c329-4d77-ab6c-a12fd9076a69%40app.fastmail.com.
[sqlalchemy] Connection issue with URL-encoded passwords in `do-connect` event
Hello everyone, I have encountered an odd behavior when using URL-encoded tokens as passwords for connections with Postgres; my application connects to a Postgres AWS RDS instance using a token that expires (IAM Authentication <https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.html>). Specifically, if I set `cparams['password']` to a URL-encoded value in the `do_connect` event, the connection fails. However, it succeeds if the value isn't URL encoded. This seems inconsistent with how the engine handles URL-encoded values. Is this the intended behavior ? If not, would the team be open to a PR that calls `unquote` on the `cparams['password'] when it's changed to ensure consistency ? Here is a minimal example to illustrate the issue: from sqlalchemy.orm import sessionmaker from sqlalchemy import create_engine, event, text from urllib.parse import quote *# Assume there is a db user `test` with some initial tokenPOSTGRES_HOST = 'localhost'PORT = '5432'USERNAME = 'test'NEW_PASSWORD = '%2FH'engine1 = create_engine(f"postgresql://{USERNAME}:some_token_that_expires@{POSTGRES_HOST}:{PORT}/esrf", echo=True)@event.listens_for(engine1, 'do_connect')def receive_do_connect(dialect, conn_rec, cargs, cparams):# This doesn't work.cparams['password'] = quote(NEW_PASSWORD)with engine1.connect() as connection:connection.execute(text('SELECT 1;'))engine2 = create_engine(f"postgresql://{USERNAME}:some_token_that_expires@{POSTGRES_HOST}:{PORT}/esrf", echo=True)@event.listens_for(engine2, 'do_connect')def receive_do_connect(dialect, conn_rec, cargs, cparams):# This works cparams['password'] = NEW_PASSWORDwith engine2.connect() as connection: connection.execute(text('SELECT 1;'))* -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/6a124e8b-fabc-47b6-8e68-db939acc98f7n%40googlegroups.com.
Re: [sqlalchemy] Issuing Raw SQL and Returning a List of Objects
Hi there, This is great. Thanks for adding to the discussion. Rgds mjg On Thursday, November 2, 2023 at 11:13:07 AM UTC-4 mkmo...@gmail.com wrote: > Hi Mike, > > If I understand correctly, you want to work with raw sql and don't want > any ORM getting in your way. I'm the same way, and it is trivial to use > SQLAlchemy Core for this purpose. > > results = conn.execute(text('select foo, bar from > baz')).mappings().fetchall() # mappings().fetchall() returns a list of > dict like objects > for row in results: > print(row['foo'], row['bar']) > > result = conn.execute(text('select foo, bar from baz')).fetchall() # > fetchall() without mappings() returns a list of named tuple like objects > for row in results: > print(row.foo, row.bar) > print(row[0], row[1]) > > On Thursday, August 24, 2023 at 5:06:11 AM UTC-7 Mike Graziano wrote: > >> Hi Simon, >> >> Thanks for responding to my post. It turns out that MyBatis can do >> exactly what you are saying which essentially sounds like a bulk ETL >> process. Again, the key difference is that MyBatis doesn’t require that >> the mapping be done with all the DB-specific definitions which I frankly >> prefer. There is a tool, the MyBatis generator, that does exactly this and >> I have used it when I didn’t want to write my own mapping files since the >> tables had hundreds of fields. >> >> In many cases, you are correct in that I was only loading data. The data >> was retrieved by raw SQL and could involve joins with other tables much as >> in a view. I just needed a data transfer mechanism to translate the SQL >> results to a POJO. Your experience differed in that you did need to create >> the tables with your Python code. I agree that SQLAlchemy is perfect for >> that. I created the tables ahead of time usually with command-line psql >> or, as you said, the tables already existed. In fact, I’d sometimes create >> temp tables with the schema of existing tables and I also did that with >> command-line psql in a Bash script. >> >> Thanks for your insights. >> >> Rgds >> >> mjg >> >> On Wednesday, August 23, 2023 at 12:49:23 PM UTC-4 Simon King wrote: >> >>> My perspective: the SQLAlchemy ORM really comes into its own when you >>> are making use of its Unit of Work system to load a batch of objects from >>> the database, manipulate those objects, and then flush your changes back to >>> the database. If you are only *loading* data then you don't need a lot of >>> the functionality of the ORM, and you might consider using SQLAlchemy Core >>> instead. >>> >>> Using SQLAlchemy Core to execute SQL strings is very simple: >>> >>> https://docs.sqlalchemy.org/en/20/core/connections.html#basic-usage >>> >>> You can use the objects that come back from those calls directly (they >>> have attributes named after the columns from the query), or you could >>> trivially convert them into instances of some class that you've defined. >>> >>> It sounds like the sort of work you do involves writing code to access >>> pre-existing databases, in which case writing SQL directly makes a lot of >>> sense, and you have no need for the schema-definition parts of SQLAlchemy. >>> But there are other classes of application for which the schema-definition >>> tools are very useful. I have written many applications for which the >>> database didn't already exist, so allowing SQLAlchemy to create the tables >>> was the obvious way to go (with Alembic for migrations as the schema >>> changed over time). SQLAlchemy also gives a certain amount of independence >>> from the underlying database, meaning that I can run most of my tests using >>> SQLite despite using Postgres or MySQL in production. >>> >>> In summary: use the right tool for the job :-) >>> >>> Simon >>> >>> >>> On Mon, Aug 21, 2023 at 6:48 PM Mike Graziano wrote: >>> >>>> Hi Mike, >>>> >>>> >>>> >>>> Thanks for that info. It was just what I needed. I also want to thank >>>> you for your YouTube tutorials on SQLAlchemy. They are fantastic. >>>> >>>> >>>> >>>> I don’t want to make this a huge post, but I have a real pet peeve >>>> concerning ORMs. I come from a Java background where I used MyBatis as my >>>> ORM. What I love about MyBatis was >>>> >>>> >>>> >>>>
Re: [sqlalchemy] Postgresq Execute Many with Textual SQL Convenience Issue
On Thu, Nov 2, 2023, at 11:24 AM, mkmo...@gmail.com wrote: > Hi Mike, > > When using Core, we can do a bulk insert and bulk return with Postgresql > trivially: > > from sqlalchemy import table, column > t = table('foo', column('id'), column('bar') > > ins = t.insert().values([{'bar': 'a'}, {'bar': 'b'}]).returning(foo.id) > > results = conn.execute(ins) > > ids = results.fetchall() > > However, with raw textual SQL, it is a bit more inconvenient. > > The following doesn't work: > > results = conn.execute(text( > 'insert into foo values (:bar) returning id > ), [{'bar': 'a'}, {'bar': 'b'}]) > > # raises sqlalchemy.exc.ResourceClosedError: This result object does not > return rows. It has been closed automatically. > results.fetchall() That's because you're using excecutemany. pep-249 executemany does not support rows being returned, so if you send a list of params like that, it's an automatic result close. there's nothing to fetch. I would also note that the statement you have above might not be as useful as you think since I would assume you would want those "RETURNING" rows to line up with the dictionaries you are sending. This is not a guarantee for most backends and the SQL Server backend will actually actively rearrange the rows. Special (extremely inconvenient) forms must be taken to ensure this ordering. SQLAlchemy 2.0 supports a new form of INSERT called insertmanyvalues (https://docs.sqlalchemy.org/en/20/core/connections.html#insert-many-values-behavior-for-insert-statements ) which can receive a list of parameter dictionaries along with an insert() construct and convert the operation into series of batched single statements that are yielded as a single result set. That is, it does **not** use DBAPI executemany (except on Oracle which has special support), it uses DBAPI execute. It also does this very special and inconvenient formatting of the INSERT statement to ensure to the greatest degree possible that RETURNING rows are ordered the same way as the parameter sets. > > To get it working, we have to do it this way: > > results = conn.execute(text( > 'insert into foo values (:bar0), (:bar1) > ), {'bar0': 'x', 'bar1': 'y'}) > > assert results.fetchall() > > > This isn't convenient. For example you would have to convert a list of bars > like [{'bar': 'a'}, {'bar': 'b'}] into a single dict with uniquely name keys > {'bar0': 'a', 'bar1': 'b'}. you do, because there's no result set implied from an executemany, you have to use an execute. if you want SQLAlchemy to convert your multiple parameters into a series of "INSERT..VALUES", do the execution of them, and then with RETURNING work the results back together, that's exactly what insertmanyvalues does.We spent many months developing this feature plus figuring out the RETURNING / ordering thing which took an extra month, so you'd be tapping into a great deal of development efforts by using that feature. However, that feature works only with insert() constructs. With text(), we have no idea what your statement says and we don't parse SQL. you'd be on your own there. > > I imagine sqlalchemy is doing that under the hood when using core. Is there > some convenience function available in sqlalchemy core that I can use to > simplify this? The functions which do this start at https://github.com/sqlalchemy/sqlalchemy/blob/b51cccec6a953555f39c16005cb5a2a49a6f4b21/lib/sqlalchemy/engine/default.py#L758 and then digs into compiler at https://github.com/sqlalchemy/sqlalchemy/blob/b51cccec6a953555f39c16005cb5a2a49a6f4b21/lib/sqlalchemy/sql/compiler.py#L5306 , where you'll note these functions are now huge and complicated, as they must accommodate all cases amongst a wide variety of statements scenarios, typing issues on both the input and output side, and backends. You can definitely write simple helpers to convert simple INSERT statements on your own here, or maybe look at psycopg2's fast execution helpers also at https://www.psycopg.org/docs/extras.html#fast-execution-helpers which are older / simpler versions of this kind of thing (however still probably not generalizable). -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/e408bc7b-efcd-407b-88f0-216fc9de1fc9%40app.fastmail.com.
[sqlalchemy] Postgresq Execute Many with Textual SQL Convenience Issue
Hi Mike, When using Core, we can do a bulk insert and bulk return with Postgresql trivially: from sqlalchemy import table, column t = table('foo', column('id'), column('bar') ins = t.insert().values([{'bar': 'a'}, {'bar': 'b'}]).returning(foo.id) results = conn.execute(ins) ids = results.fetchall() However, with raw textual SQL, it is a bit more inconvenient. The following doesn't work: results = conn.execute(text( 'insert into foo values (:bar) returning id ), [{'bar': 'a'}, {'bar': 'b'}]) # raises sqlalchemy.exc.ResourceClosedError: This result object does not return rows. It has been closed automatically. results.fetchall() To get it working, we have to do it this way: results = conn.execute(text( 'insert into foo values (:bar0), (:bar1) ), {'bar0': 'x', 'bar1': 'y'}) assert results.fetchall() This isn't convenient. For example you would have to convert a list of bars like [{'bar': 'a'}, {'bar': 'b'}] into a single dict with uniquely name keys {'bar0': 'a', 'bar1': 'b'}. I imagine sqlalchemy is doing that under the hood when using core. Is there some convenience function available in sqlalchemy core that I can use to simplify this? -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/ee82dcc7-7ff5-43e6-a405-1e5aedaaaeban%40googlegroups.com.
Re: [sqlalchemy] Issuing Raw SQL and Returning a List of Objects
Hi Mike, If I understand correctly, you want to work with raw sql and don't want any ORM getting in your way. I'm the same way, and it is trivial to use SQLAlchemy Core for this purpose. results = conn.execute(text('select foo, bar from baz')).mappings().fetchall() # mappings().fetchall() returns a list of dict like objects for row in results: print(row['foo'], row['bar']) result = conn.execute(text('select foo, bar from baz')).fetchall() # fetchall() without mappings() returns a list of named tuple like objects for row in results: print(row.foo, row.bar) print(row[0], row[1]) On Thursday, August 24, 2023 at 5:06:11 AM UTC-7 Mike Graziano wrote: > Hi Simon, > > Thanks for responding to my post. It turns out that MyBatis can do > exactly what you are saying which essentially sounds like a bulk ETL > process. Again, the key difference is that MyBatis doesn’t require that > the mapping be done with all the DB-specific definitions which I frankly > prefer. There is a tool, the MyBatis generator, that does exactly this and > I have used it when I didn’t want to write my own mapping files since the > tables had hundreds of fields. > > In many cases, you are correct in that I was only loading data. The data > was retrieved by raw SQL and could involve joins with other tables much as > in a view. I just needed a data transfer mechanism to translate the SQL > results to a POJO. Your experience differed in that you did need to create > the tables with your Python code. I agree that SQLAlchemy is perfect for > that. I created the tables ahead of time usually with command-line psql > or, as you said, the tables already existed. In fact, I’d sometimes create > temp tables with the schema of existing tables and I also did that with > command-line psql in a Bash script. > > Thanks for your insights. > > Rgds > > mjg > > On Wednesday, August 23, 2023 at 12:49:23 PM UTC-4 Simon King wrote: > >> My perspective: the SQLAlchemy ORM really comes into its own when you are >> making use of its Unit of Work system to load a batch of objects from the >> database, manipulate those objects, and then flush your changes back to the >> database. If you are only *loading* data then you don't need a lot of the >> functionality of the ORM, and you might consider using SQLAlchemy Core >> instead. >> >> Using SQLAlchemy Core to execute SQL strings is very simple: >> >> https://docs.sqlalchemy.org/en/20/core/connections.html#basic-usage >> >> You can use the objects that come back from those calls directly (they >> have attributes named after the columns from the query), or you could >> trivially convert them into instances of some class that you've defined. >> >> It sounds like the sort of work you do involves writing code to access >> pre-existing databases, in which case writing SQL directly makes a lot of >> sense, and you have no need for the schema-definition parts of SQLAlchemy. >> But there are other classes of application for which the schema-definition >> tools are very useful. I have written many applications for which the >> database didn't already exist, so allowing SQLAlchemy to create the tables >> was the obvious way to go (with Alembic for migrations as the schema >> changed over time). SQLAlchemy also gives a certain amount of independence >> from the underlying database, meaning that I can run most of my tests using >> SQLite despite using Postgres or MySQL in production. >> >> In summary: use the right tool for the job :-) >> >> Simon >> >> >> On Mon, Aug 21, 2023 at 6:48 PM Mike Graziano wrote: >> >>> Hi Mike, >>> >>> >>> >>> Thanks for that info. It was just what I needed. I also want to thank >>> you for your YouTube tutorials on SQLAlchemy. They are fantastic. >>> >>> >>> >>> I don’t want to make this a huge post, but I have a real pet peeve >>> concerning ORMs. I come from a Java background where I used MyBatis as my >>> ORM. What I love about MyBatis was >>> >>> >>> >>> - I could use raw SQL which I personally feel is superior. My >>> argument here is simple: Why learn another “language” for issuing SQL >>> statements when we have already spent a fair amount of time learning SQL. >>> Also, raw SQL is easily testable with either command line or GUI tools? >>> >>> - The ORM should just use the mapped models in order to execute SQL >>> using mapping that in and of themselves doesn’t/shouldn’t care about the >>> tables. Unless you are crea
[sqlalchemy] DAFTAR LINK ALTERNATIF PETIRTOTO SITUS SLOT ONLINE PALING GACOR DAN TERPERCAYA
DAFTAR LINK ALTERNATIF PETIRTOTO SITUS SLOT ONLINE PALING GACOR DAN TERPERCAYA LINK LOGIN PETIRTOTO : https://heylink.me/Petirtoto.com/ LINK DAFTAR PETIRTOTO : https://heylink.me/Petirtoto.com/ LINK AKUN GACOR : https://heylink.me/Petirtoto.com/ LINK AKUN VIP : https://heylink.me/Petirtoto.com/ PETIRTOTO | LINK PETIRTOTO | SLOT PETIRTOTO | LOGIN PETIRTOTO | PETIRTOTO TERPERCAYA | PETIRTOTO TERBAIK Agen Toto Togel Slot Online Terbaik Terpercaya - Petirtoto Pada Kamis, 02 November 2023 pukul 14.17.14 UTC+7 Dharmawan Luis menulis: > LINK LOGIN TOTOJITU: https://heylink.me/totojitu1/ > LINK DAFTAR TOTOJITU: https://heylink.me/totojitu1/ > > DAFTAR LINK TOTOJITU > LINK GACOR TOTOJITU > LINK DEPOSIT TOTOJITU > LINK DAFTAR TOTOJITU > LINK ALTERNATIF TOTOJITU > LINK SLOT GACOR > LINK SLOT THAILAND > LINK SLOT PULSA > LINK SLOT DEPO 10K > DIATAS ADALAH LINK TOTOJITU TERPERCAYA 2023 > > Selamat datang di TOTOJITU⚡️! Kami adalah situs terkemuka dalam dunia slot > online, dan kami bangga menyajikan pengalaman bermain slot demo Olympus > yang tak tertandingi kepada seluruh pemain kami. Dalam artikel ini, kami > akan menjelaskan mengapa TOTOJITU⚡️ adalah pilihan utama bagi mereka yang > ingin mendaftar dan mencoba peruntungan dalam permainan slot demo Olympus. > > Keunggulan TOTOJITU⚡️ > TOTOJITU ⚡️ memiliki sejumlah keunggulan yang menjadikannya situs slot > terbaik dan unggul dalam industri ini. Berikut adalah beberapa dari > keunggulan kami: > > 1. Beragam Pilihan Permainan Slot > > TOTOJITU⚡️ menawarkan beragam permainan slot yang bisa Anda nikmati. Mulai > dari tema klasik hingga yang lebih modern, kami memiliki semua jenis > permainan yang Anda cari. Dengan lebih dari 1000 judul permainan yang > tersedia, Anda tidak akan pernah bosan bermain di TOTOJITU⚡️ > > 2.Grafis Berkualitas Tinggi > > Kami sangat memahami bahwa visual yang menarik sangat penting dalam > permainan slot. Oleh karena itu, kami berkolaborasi dengan penyedia > perangkat lunak terbaik untuk memastikan grafis permainan kami selalu > berkualitas tinggi dan memukau. Setiap putaran slot di TOTOJITU⚡️ akan > memberikan pengalaman visual yang luar biasa. > > 3.Jackpot Besar > TOTOJITU⚡️ memberikan peluang untuk memenangkan jackpot besar. Kami > menyediakan berbagai jenis jackpot, beberapa di antaranya mencapai jumlah > yang sangat menggiurkan. Bergabunglah sekarang dan raih peluang Anda untuk > menjadi jutawan! > > 4.Daftar di TOTOJITU⚡️ Sekarang > Jika Anda ingin merasakan semua manfaat yang ditawarkan oleh TOTOJITU⚡️, > jangan ragu untuk mendaftar sekarang. Proses pendaftaran kami mudah dan > cepat, sehingga Anda dapat segera memulai permainan. Jangan sia-siakan > kesempatan untuk bermain slot demo Olympus dan memenangkan hadiah-hadiah > besar. > > Dengan bermain di TOTOJITU⚡️, Anda akan mengalami pengalaman bermain slot > yang tak terlupakan. Bergabunglah dengan komunitas pemain kami sekarang dan > jadilah bagian dari situs slot terbesar dan terbaik di Indonesia. Terima > kasih telah memilih TOTOJITU⚡️ sebagai tempat bermain slot pilihan Anda! > -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/018afa90-6a78-48e2-abb9-3c77300ffac3n%40googlegroups.com.
[sqlalchemy] DAFTAR LINK ALTERNATIF PETIRTOTO SITUS SLOT ONLINE PALING GACOR DAN TERPERCAYA
DAFTAR LINK ALTERNATIF PETIRTOTO SITUS SLOT ONLINE PALING GACOR DAN TERPERCAYA LINK LOGIN PETIRTOTO : https://heylink.me/Petirtoto.com/ LINK DAFTAR PETIRTOTO : https://heylink.me/Petirtoto.com/ LINK AKUN GACOR : https://heylink.me/Petirtoto.com/ LINK AKUN VIP : https://heylink.me/Petirtoto.com/ PETIRTOTO | LINK PETIRTOTO | SLOT PETIRTOTO | LOGIN PETIRTOTO | PETIRTOTO TERPERCAYA | PETIRTOTO TERBAIK Agen Toto Togel Slot Online Terbaik Terpercaya - Petirtoto Pada Kamis, 02 November 2023 pukul 14.17.14 UTC+7 Dharmawan Luis menulis: > LINK LOGIN TOTOJITU: https://heylink.me/totojitu1/ > LINK DAFTAR TOTOJITU: https://heylink.me/totojitu1/ > > DAFTAR LINK TOTOJITU > LINK GACOR TOTOJITU > LINK DEPOSIT TOTOJITU > LINK DAFTAR TOTOJITU > LINK ALTERNATIF TOTOJITU > LINK SLOT GACOR > LINK SLOT THAILAND > LINK SLOT PULSA > LINK SLOT DEPO 10K > DIATAS ADALAH LINK TOTOJITU TERPERCAYA 2023 > > Selamat datang di TOTOJITU⚡️! Kami adalah situs terkemuka dalam dunia slot > online, dan kami bangga menyajikan pengalaman bermain slot demo Olympus > yang tak tertandingi kepada seluruh pemain kami. Dalam artikel ini, kami > akan menjelaskan mengapa TOTOJITU⚡️ adalah pilihan utama bagi mereka yang > ingin mendaftar dan mencoba peruntungan dalam permainan slot demo Olympus. > > Keunggulan TOTOJITU⚡️ > TOTOJITU ⚡️ memiliki sejumlah keunggulan yang menjadikannya situs slot > terbaik dan unggul dalam industri ini. Berikut adalah beberapa dari > keunggulan kami: > > 1. Beragam Pilihan Permainan Slot > > TOTOJITU⚡️ menawarkan beragam permainan slot yang bisa Anda nikmati. Mulai > dari tema klasik hingga yang lebih modern, kami memiliki semua jenis > permainan yang Anda cari. Dengan lebih dari 1000 judul permainan yang > tersedia, Anda tidak akan pernah bosan bermain di TOTOJITU⚡️ > > 2.Grafis Berkualitas Tinggi > > Kami sangat memahami bahwa visual yang menarik sangat penting dalam > permainan slot. Oleh karena itu, kami berkolaborasi dengan penyedia > perangkat lunak terbaik untuk memastikan grafis permainan kami selalu > berkualitas tinggi dan memukau. Setiap putaran slot di TOTOJITU⚡️ akan > memberikan pengalaman visual yang luar biasa. > > 3.Jackpot Besar > TOTOJITU⚡️ memberikan peluang untuk memenangkan jackpot besar. Kami > menyediakan berbagai jenis jackpot, beberapa di antaranya mencapai jumlah > yang sangat menggiurkan. Bergabunglah sekarang dan raih peluang Anda untuk > menjadi jutawan! > > 4.Daftar di TOTOJITU⚡️ Sekarang > Jika Anda ingin merasakan semua manfaat yang ditawarkan oleh TOTOJITU⚡️, > jangan ragu untuk mendaftar sekarang. Proses pendaftaran kami mudah dan > cepat, sehingga Anda dapat segera memulai permainan. Jangan sia-siakan > kesempatan untuk bermain slot demo Olympus dan memenangkan hadiah-hadiah > besar. > > Dengan bermain di TOTOJITU⚡️, Anda akan mengalami pengalaman bermain slot > yang tak terlupakan. Bergabunglah dengan komunitas pemain kami sekarang dan > jadilah bagian dari situs slot terbesar dan terbaik di Indonesia. Terima > kasih telah memilih TOTOJITU⚡️ sebagai tempat bermain slot pilihan Anda! > -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/59050ce0-bef4-427c-98c2-55ecc9d19285n%40googlegroups.com.
[sqlalchemy] ✅TOTOJITU, ✅DAFTAR TOTOJITU, ✅SITUS TOTOJITU, ✅LINK TOTOJITU
LINK LOGIN TOTOJITU: https://heylink.me/totojitu1/ LINK DAFTAR TOTOJITU: https://heylink.me/totojitu1/ DAFTAR LINK TOTOJITU LINK GACOR TOTOJITU LINK DEPOSIT TOTOJITU LINK DAFTAR TOTOJITU LINK ALTERNATIF TOTOJITU LINK SLOT GACOR LINK SLOT THAILAND LINK SLOT PULSA LINK SLOT DEPO 10K DIATAS ADALAH LINK TOTOJITU TERPERCAYA 2023 Selamat datang di TOTOJITU⚡️! Kami adalah situs terkemuka dalam dunia slot online, dan kami bangga menyajikan pengalaman bermain slot demo Olympus yang tak tertandingi kepada seluruh pemain kami. Dalam artikel ini, kami akan menjelaskan mengapa TOTOJITU⚡️ adalah pilihan utama bagi mereka yang ingin mendaftar dan mencoba peruntungan dalam permainan slot demo Olympus. Keunggulan TOTOJITU⚡️ TOTOJITU ⚡️ memiliki sejumlah keunggulan yang menjadikannya situs slot terbaik dan unggul dalam industri ini. Berikut adalah beberapa dari keunggulan kami: 1. Beragam Pilihan Permainan Slot TOTOJITU⚡️ menawarkan beragam permainan slot yang bisa Anda nikmati. Mulai dari tema klasik hingga yang lebih modern, kami memiliki semua jenis permainan yang Anda cari. Dengan lebih dari 1000 judul permainan yang tersedia, Anda tidak akan pernah bosan bermain di TOTOJITU⚡️ 2.Grafis Berkualitas Tinggi Kami sangat memahami bahwa visual yang menarik sangat penting dalam permainan slot. Oleh karena itu, kami berkolaborasi dengan penyedia perangkat lunak terbaik untuk memastikan grafis permainan kami selalu berkualitas tinggi dan memukau. Setiap putaran slot di TOTOJITU⚡️ akan memberikan pengalaman visual yang luar biasa. 3.Jackpot Besar TOTOJITU⚡️ memberikan peluang untuk memenangkan jackpot besar. Kami menyediakan berbagai jenis jackpot, beberapa di antaranya mencapai jumlah yang sangat menggiurkan. Bergabunglah sekarang dan raih peluang Anda untuk menjadi jutawan! 4.Daftar di TOTOJITU⚡️ Sekarang Jika Anda ingin merasakan semua manfaat yang ditawarkan oleh TOTOJITU⚡️, jangan ragu untuk mendaftar sekarang. Proses pendaftaran kami mudah dan cepat, sehingga Anda dapat segera memulai permainan. Jangan sia-siakan kesempatan untuk bermain slot demo Olympus dan memenangkan hadiah-hadiah besar. Dengan bermain di TOTOJITU⚡️, Anda akan mengalami pengalaman bermain slot yang tak terlupakan. Bergabunglah dengan komunitas pemain kami sekarang dan jadilah bagian dari situs slot terbesar dan terbaik di Indonesia. Terima kasih telah memilih TOTOJITU⚡️ sebagai tempat bermain slot pilihan Anda! -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/3b8653ed-9441-4ac8-97e3-bd6e1d081856n%40googlegroups.com.
[sqlalchemy] TOTOJITU SITUS TOGEL AMAN TERPERCAYA | TOTOJITU SITUS TERBESAR NO.1 DI INDONESIA
TOTOJITU SITUS TOGEL AMAN TERPERCAYA | TOTOJITU SITUS TERBESAR NO.1 DI INDONESIA Link Login ❱❱ https://heylink.me/totojitu1/ Klik Disini Daftar Togel dan Slot Gacor ❱❱ https://heylink.me/totojitu1/ Klik Disini Daftar Bonus New Member ❱❱ https://heylink.me/totojitu1/ Klik Disini Daftar langsung dapat Bonus ❱❱ https://heylink.me/totojitu1/ TOTOJITU | LINK TOTOJITU | SLOT TOTOJITU | LOGIN TOTOJITU | TOTOJITU TERPERCAYA | TOTOJITU TERBAIK Totojitu Togel Online Singapura - Bandar Togel Online Terpercaya TOTOJITU SITUS TOGEL DAN SLOT GACOR TERLENGKAP DAN TERPERCAYA Selamat datang di slot Anti Rungkad terbaru hari ini. Situs slot gacor modal receh yang menyediakan banyak permainan slot online dengan winrate sempurna dan nilai rtp slot tertinggi untuk anda mainkan hanya melakukan deposit dengan modal receh hari ini. -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/75ead074-5ab4-46b5-b8ec-51e630611bcan%40googlegroups.com.
Re: [sqlalchemy] How correct sort items by @hibrid_property
The error you're getting doesn't have anything to do with using the property in an order_by. It's being triggered just by accessing "Product.Rating". WIth hybrid properties, when you access them via the class as you've done here, the "self" parameter is set to the Product class itself. So on the second line of the function, you are actually saying "reviewsCount = len(Product.Reviews)", which doesn't make any sense. You need to define a separate implementation of the hybrid property that returns an SQL construct so that it can be embedded in an SQL query, using the ".expression" decorator. Since you need to access a separate table to calculate your Rating, you probably need a correlated subquery, something like this: https://docs.sqlalchemy.org/en/20/orm/extensions/hybrid.html#correlated-subquery-relationship-hybrid That example uses "func.sum" to calculate a sum over the related rows. For your purposes, you probably want "func.avg" to calculate the mean. (Note that the performance of this query is going to get worse as the number of products and ratings increases) Hope that helps, Simon On Sun, Oct 29, 2023 at 9:51 AM Nik wrote: > Hello, guys! > I have a simple code, which not correct work > He throw error if i try sort items by @hybrid_property > > *My version of entity class:* > class Product(Base) : > > __tablename__ = 'products' > > Id = Column('id', Integer, primary_key=True, autoincrement=True) > TitleTranslit = Column('title_translit', String) > Title = Column('title', String) > Description = Column('description', String) > CurrentPrice = Column('current_price', Integer) > OldPrice = Column('old_price', Integer) > CategoryId = Column('category_id', Integer, ForeignKey('categories.id > ')) > Characteristics:List[ProductCharacteristic] = > relationship('ProductCharacteristic', > primaryjoin="and_(ProductCharacteristic.ProductId==Product.Id)", > lazy='joined') > Reviews:List[ProductReview] = relationship('ProductReview', > primaryjoin="and_(ProductReview.ProductId==Product.Id)", lazy='joined') > Images:List[ProductImage] = relationship('ProductImage', > primaryjoin="and_(ProductImage.ProductId==Product.Id)", lazy='joined') > NumberOfViews = Column('number_of_views', Integer) > > @hybrid_property > def Rating(self) : > result = 0 > reviewsCount = len(self.Reviews) > if (reviewsCount > 0) : > for review in self.Reviews : > result += review.Rating > result = result / reviewsCount > return result > > *My version of call sort event by @hybrid_property:* > filteredProductsQuery = self._sessionService.DBContext.query(Product)\ > > .filter(Product.CategoryId.in_(categoriesIds)).outerjoin(Product.Characteristics) > > if sortType == SortType.HighestRate.value : > filteredProductsQuery = > filteredProductsQuery.order_by(Product.Rating.desc()) > > *Throwed error if i try execute this query:* > TypeError: object of type 'InstrumentedAttribute' has no len() > > -- > SQLAlchemy - > The Python SQL Toolkit and Object Relational Mapper > > http://www.sqlalchemy.org/ > > To post example code, please provide an MCVE: Minimal, Complete, and > Verifiable Example. See http://stackoverflow.com/help/mcve for a full > description. > --- > You received this message because you are subscribed to the Google Groups > "sqlalchemy" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to sqlalchemy+unsubscr...@googlegroups.com. > To view this discussion on the web visit > https://groups.google.com/d/msgid/sqlalchemy/d6ccf7c1-fd12-4fb8-b16d-5280f54d506an%40googlegroups.com > <https://groups.google.com/d/msgid/sqlalchemy/d6ccf7c1-fd12-4fb8-b16d-5280f54d506an%40googlegroups.com?utm_medium=email_source=footer> > . > -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/CAFHwexdKp5z%3D9CE5WdJMw7ntmSwGxRxCigO0EiqVuwr-YO9R8A%40mail.gmail.com.
[sqlalchemy] How correct sort items by @hibrid_property
Hello, guys! I have a simple code, which not correct work He throw error if i try sort items by @hybrid_property *My version of entity class:* class Product(Base) : __tablename__ = 'products' Id = Column('id', Integer, primary_key=True, autoincrement=True) TitleTranslit = Column('title_translit', String) Title = Column('title', String) Description = Column('description', String) CurrentPrice = Column('current_price', Integer) OldPrice = Column('old_price', Integer) CategoryId = Column('category_id', Integer, ForeignKey('categories.id')) Characteristics:List[ProductCharacteristic] = relationship('ProductCharacteristic', primaryjoin="and_(ProductCharacteristic.ProductId==Product.Id)", lazy='joined') Reviews:List[ProductReview] = relationship('ProductReview', primaryjoin="and_(ProductReview.ProductId==Product.Id)", lazy='joined') Images:List[ProductImage] = relationship('ProductImage', primaryjoin="and_(ProductImage.ProductId==Product.Id)", lazy='joined') NumberOfViews = Column('number_of_views', Integer) @hybrid_property def Rating(self) : result = 0 reviewsCount = len(self.Reviews) if (reviewsCount > 0) : for review in self.Reviews : result += review.Rating result = result / reviewsCount return result *My version of call sort event by @hybrid_property:* filteredProductsQuery = self._sessionService.DBContext.query(Product)\ .filter(Product.CategoryId.in_(categoriesIds)).outerjoin(Product.Characteristics) if sortType == SortType.HighestRate.value : filteredProductsQuery = filteredProductsQuery.order_by(Product.Rating.desc()) *Throwed error if i try execute this query:* TypeError: object of type 'InstrumentedAttribute' has no len() -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/d6ccf7c1-fd12-4fb8-b16d-5280f54d506an%40googlegroups.com.
[sqlalchemy] sqlacodegen --noclaases depracated?
SQLAlchemy and sqlacodegen noob here. I'd like to just get some simple SQLAlchemy tables generated for my database. I tried using --noclasses, but it doesn't seem to recognize the option. sqlacodegen --noclasses mysql+pymysql://root:@localhost:3306/mydb sqlacodegen: error: unrecognized arguments: --noclasses How can I get it to just gen some tables? This is what I read in the project docs: "Unless the --noclasses option is used, sqlacodegen tries to generate declarative model classes from each table." From: https://pypi.org/project/sqlacodegen/ Thanks! -Peter -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/99353284-321c-429c-9e5d-65ab480ded44n%40googlegroups.com.
Re: [sqlalchemy] Event listener for when query results get matched with pre-existing objects on the session
great, glad to know that new API is finding itself useful. On Sun, Oct 22, 2023, at 9:32 PM, 'Tony Cosentini' via sqlalchemy wrote: > do_orm_execute() (and freezing the results) totally allows for what I'm > trying to do! Also I forgot to mention earlier, but this is only going to run > in tests. > > Thanks again for all the help, > Tony > > On Friday, October 20, 2023 at 11:10:23 PM UTC+8 Mike Bayer wrote: >> >> >> On Fri, Oct 20, 2023, at 10:46 AM, 'Tony Cosentini' via sqlalchemy wrote: >>> Oh I see, thanks for clarifying. >>> >>> I'm trying to detect cases where we depend on the autoflush behavior. For >>> example, in the sample above, when the query runs with no_autoflush, we >>> won't get back any results (when previously we would get back one row). >>> It's a fairly large codebase, so I was trying to automate finding these >>> cases in order to add explicit flush calls when needed or just pass in the >>> pending object instead of running a query. >> >> >> there's not really an event for an object that just gets returned by a query >> from the identity map.you would need to do something more drastic like a >> do_orm_execute() hook that runs queries internally and then looks at all the >> returned objects. i wouldnt put that in production. >> >> >> >> >> >> >> >>> >>> >>> Tony >>> >>> On Fri, Oct 20, 2023 at 10:42 PM Mike Bayer >>> wrote: >>>> __ >>>> >>>> >>>> On Fri, Oct 20, 2023, at 9:50 AM, 'Tony Cosentini' via sqlalchemy wrote: >>>>> Weird, I did try that but I can't seem to trigger it. >>>>> >>>>> Here's a self-contained test: >>>>> https://gist.github.com/tonycosentini/4dee3478695d032ca67707b5e26739b6 >>>> >>>> >>>> the object was not affected in that query (that is, not mutated). if you >>>> change the query to this: >>>> >>>> table_one_instances = >>>> session.query(TableOne).populate_existing().all() >>>> >>>> then the refresh event is triggered. >>>> >>>> Im not really following what kind of bug you are trying to detect. >>>> >>>> >>>>> >>>>> I have the event listener set to just crash, but it never triggers. >>>>> >>>>> On Fri, Oct 20, 2023 at 9:20 PM Mike Bayer >>>>> wrote: >>>>>> __ >>>>>> >>>>>> >>>>>> On Fri, Oct 20, 2023, at 8:08 AM, 'Tony Cosentini' via sqlalchemy wrote: >>>>>>> Hi, >>>>>>> >>>>>>> Is there any way to listen for an event for when a query result gets >>>>>>> merged into a pre-existing object in the session? >>>>>> >>>>>> this is the refresh event: >>>>>> >>>>>> https://docs.sqlalchemy.org/en/20/orm/events.html#sqlalchemy.orm.InstanceEvents.refresh >>>>>> >>>>>> >>>>>>> >>>>>>> I'm working on disabling autoflush for some of our codebase (mostly to >>>>>>> cut down on queries on a high QPS path), but before doing that I want >>>>>>> to write a utility to detect when we read data that was flushed via >>>>>>> autoflush to cut down on any potential bugs. >>>>>>> >>>>>>> What I'd like to do is this (while autoflush is still enabled): >>>>>>> >>>>>>> table_one = TableOne(name='test') >>>>>>> session.add(table_one) # Track this object as pending a flush via the >>>>>>> before_* listeners, this is working as expected. >>>>>>> >>>>>>> table_two_instances = session.query(TableTwo).all() # All good, doesn't >>>>>>> do anything with the table_one instance created earlier >>>>>>> >>>>>>> table_one_instances = session.query(TableOne).all() # I would like to >>>>>>> log a warning here as the results of this query depend on a flush >>>>>>> happening. What I'm hoping to do is detect that one of the rows coming >>>>>>> back is the same object that was flagged earlier, but I can't see to >>>>>>> find the correct event to use. >>>>>> >>
Re: [sqlalchemy] Event listener for when query results get matched with pre-existing objects on the session
do_orm_execute() (and freezing the results) totally allows for what I'm trying to do! Also I forgot to mention earlier, but this is only going to run in tests. Thanks again for all the help, Tony On Friday, October 20, 2023 at 11:10:23 PM UTC+8 Mike Bayer wrote: > > > On Fri, Oct 20, 2023, at 10:46 AM, 'Tony Cosentini' via sqlalchemy wrote: > > Oh I see, thanks for clarifying. > > I'm trying to detect cases where we depend on the autoflush behavior. For > example, in the sample above, when the query runs with no_autoflush, we > won't get back any results (when previously we would get back one row). > It's a fairly large codebase, so I was trying to automate finding these > cases in order to add explicit flush calls when needed or just pass in the > pending object instead of running a query. > > > > there's not really an event for an object that just gets returned by a > query from the identity map.you would need to do something more drastic > like a do_orm_execute() hook that runs queries internally and then looks at > all the returned objects. i wouldnt put that in production. > > > > > > > > > Tony > > On Fri, Oct 20, 2023 at 10:42 PM Mike Bayer > wrote: > > > > > On Fri, Oct 20, 2023, at 9:50 AM, 'Tony Cosentini' via sqlalchemy wrote: > > Weird, I did try that but I can't seem to trigger it. > > Here's a self-contained test: > https://gist.github.com/tonycosentini/4dee3478695d032ca67707b5e26739b6 > > > > the object was not affected in that query (that is, not mutated). if you > change the query to this: > > table_one_instances = > session.query(TableOne).populate_existing().all() > > then the refresh event is triggered. > > Im not really following what kind of bug you are trying to detect. > > > > I have the event listener set to just crash, but it never triggers. > > On Fri, Oct 20, 2023 at 9:20 PM Mike Bayer > wrote: > > > > > On Fri, Oct 20, 2023, at 8:08 AM, 'Tony Cosentini' via sqlalchemy wrote: > > Hi, > > Is there any way to listen for an event for when a query result gets > merged into a pre-existing object in the session? > > > this is the refresh event: > > > https://docs.sqlalchemy.org/en/20/orm/events.html#sqlalchemy.orm.InstanceEvents.refresh > > > > I'm working on disabling autoflush for some of our codebase (mostly to cut > down on queries on a high QPS path), but before doing that I want to write > a utility to detect when we read data that was flushed via autoflush to cut > down on any potential bugs. > > What I'd like to do is this (while autoflush is still enabled): > > table_one = TableOne(name='test') > session.add(table_one) # Track this object as pending a flush via the > before_* listeners, this is working as expected. > > table_two_instances = session.query(TableTwo).all() # All good, doesn't do > anything with the table_one instance created earlier > > table_one_instances = session.query(TableOne).all() # I would like to log > a warning here as the results of this query depend on a flush happening. > What I'm hoping to do is detect that one of the rows coming back is the > same object that was flagged earlier, but I can't see to find the correct > event to use. > > > you probably want to also use refresh_flush also, which will be invoked > for column defaults that are populated on the object > > > https://docs.sqlalchemy.org/en/20/orm/events.html#sqlalchemy.orm.InstanceEvents.refresh_flush > > > > > > Is this possible? I can't seem to find the appropriate event that would > trigger when the results from the .all() query get merged back in with the > existing objects in the session. > > > that's the refresh event > > > > -- > SQLAlchemy - > The Python SQL Toolkit and Object Relational Mapper > > http://www.sqlalchemy.org/ > > To post example code, please provide an MCVE: Minimal, Complete, and > Verifiable Example. See http://stackoverflow.com/help/mcve for a full > description. > --- > You received this message because you are subscribed to a topic in the > Google Groups "sqlalchemy" group. > To unsubscribe from this topic, visit > https://groups.google.com/d/topic/sqlalchemy/9bevy3Kpql4/unsubscribe. > To unsubscribe from this group and all its topics, send an email to > sqlalchemy+...@googlegroups.com. > To view this discussion on the web visit > https://groups.google.com/d/msgid/sqlalchemy/c5b89f67-e3fa-45f2-8774-463d154514f3%40app.fastmail.com > > <https://groups.google.com/d/msgid/sqlalchemy/c5b89f67-e3fa-45f2-8774-463d154514f3%40app.fastmail.com?utm_medium=email_source=footer> > . > &g
Re: [sqlalchemy] Event listener for when query results get matched with pre-existing objects on the session
On Fri, Oct 20, 2023, at 10:46 AM, 'Tony Cosentini' via sqlalchemy wrote: > Oh I see, thanks for clarifying. > > I'm trying to detect cases where we depend on the autoflush behavior. For > example, in the sample above, when the query runs with no_autoflush, we won't > get back any results (when previously we would get back one row). It's a > fairly large codebase, so I was trying to automate finding these cases in > order to add explicit flush calls when needed or just pass in the pending > object instead of running a query. there's not really an event for an object that just gets returned by a query from the identity map.you would need to do something more drastic like a do_orm_execute() hook that runs queries internally and then looks at all the returned objects. i wouldnt put that in production. > > Tony > > On Fri, Oct 20, 2023 at 10:42 PM Mike Bayer > wrote: >> __ >> >> >> On Fri, Oct 20, 2023, at 9:50 AM, 'Tony Cosentini' via sqlalchemy wrote: >>> Weird, I did try that but I can't seem to trigger it. >>> >>> Here's a self-contained test: >>> https://gist.github.com/tonycosentini/4dee3478695d032ca67707b5e26739b6 >> >> >> the object was not affected in that query (that is, not mutated). if you >> change the query to this: >> >> table_one_instances = session.query(TableOne).populate_existing().all() >> >> then the refresh event is triggered. >> >> Im not really following what kind of bug you are trying to detect. >> >> >>> >>> I have the event listener set to just crash, but it never triggers. >>> >>> On Fri, Oct 20, 2023 at 9:20 PM Mike Bayer >>> wrote: >>>> __ >>>> >>>> >>>> On Fri, Oct 20, 2023, at 8:08 AM, 'Tony Cosentini' via sqlalchemy wrote: >>>>> Hi, >>>>> >>>>> Is there any way to listen for an event for when a query result gets >>>>> merged into a pre-existing object in the session? >>>> >>>> this is the refresh event: >>>> >>>> https://docs.sqlalchemy.org/en/20/orm/events.html#sqlalchemy.orm.InstanceEvents.refresh >>>> >>>> >>>>> >>>>> I'm working on disabling autoflush for some of our codebase (mostly to >>>>> cut down on queries on a high QPS path), but before doing that I want to >>>>> write a utility to detect when we read data that was flushed via >>>>> autoflush to cut down on any potential bugs. >>>>> >>>>> What I'd like to do is this (while autoflush is still enabled): >>>>> >>>>> table_one = TableOne(name='test') >>>>> session.add(table_one) # Track this object as pending a flush via the >>>>> before_* listeners, this is working as expected. >>>>> >>>>> table_two_instances = session.query(TableTwo).all() # All good, doesn't >>>>> do anything with the table_one instance created earlier >>>>> >>>>> table_one_instances = session.query(TableOne).all() # I would like to log >>>>> a warning here as the results of this query depend on a flush happening. >>>>> What I'm hoping to do is detect that one of the rows coming back is the >>>>> same object that was flagged earlier, but I can't see to find the correct >>>>> event to use. >>>> >>>> you probably want to also use refresh_flush also, which will be invoked >>>> for column defaults that are populated on the object >>>> >>>> https://docs.sqlalchemy.org/en/20/orm/events.html#sqlalchemy.orm.InstanceEvents.refresh_flush >>>> >>>> >>>> >>>> >>>>> >>>>> Is this possible? I can't seem to find the appropriate event that would >>>>> trigger when the results from the .all() query get merged back in with >>>>> the existing objects in the session. >>>> >>>> that's the refresh event >>>> >>>> >>>> >>>> >>>> -- >>>> SQLAlchemy - >>>> The Python SQL Toolkit and Object Relational Mapper >>>> >>>> http://www.sqlalchemy.org/ >>>> >>>> To post example code, please provide an MCVE: Minimal, Complete, and >>>> Verifiable Example. See http://stackoverflow.com/help/mcve for a full >>>> description. >>>> --- >>
Re: [sqlalchemy] Event listener for when query results get matched with pre-existing objects on the session
Oh I see, thanks for clarifying. I'm trying to detect cases where we depend on the autoflush behavior. For example, in the sample above, when the query runs with no_autoflush, we won't get back any results (when previously we would get back one row). It's a fairly large codebase, so I was trying to automate finding these cases in order to add explicit flush calls when needed or just pass in the pending object instead of running a query. Tony On Fri, Oct 20, 2023 at 10:42 PM Mike Bayer < mike_not_on_goo...@zzzcomputing.com> wrote: > > > On Fri, Oct 20, 2023, at 9:50 AM, 'Tony Cosentini' via sqlalchemy wrote: > > Weird, I did try that but I can't seem to trigger it. > > Here's a self-contained test: > https://gist.github.com/tonycosentini/4dee3478695d032ca67707b5e26739b6 > > > > the object was not affected in that query (that is, not mutated). if you > change the query to this: > > table_one_instances = > session.query(TableOne).populate_existing().all() > > then the refresh event is triggered. > > Im not really following what kind of bug you are trying to detect. > > > > I have the event listener set to just crash, but it never triggers. > > On Fri, Oct 20, 2023 at 9:20 PM Mike Bayer < > mike_not_on_goo...@zzzcomputing.com> wrote: > > > > > On Fri, Oct 20, 2023, at 8:08 AM, 'Tony Cosentini' via sqlalchemy wrote: > > Hi, > > Is there any way to listen for an event for when a query result gets > merged into a pre-existing object in the session? > > > this is the refresh event: > > > https://docs.sqlalchemy.org/en/20/orm/events.html#sqlalchemy.orm.InstanceEvents.refresh > > > > I'm working on disabling autoflush for some of our codebase (mostly to cut > down on queries on a high QPS path), but before doing that I want to write > a utility to detect when we read data that was flushed via autoflush to cut > down on any potential bugs. > > What I'd like to do is this (while autoflush is still enabled): > > table_one = TableOne(name='test') > session.add(table_one) # Track this object as pending a flush via the > before_* listeners, this is working as expected. > > table_two_instances = session.query(TableTwo).all() # All good, doesn't do > anything with the table_one instance created earlier > > table_one_instances = session.query(TableOne).all() # I would like to log > a warning here as the results of this query depend on a flush happening. > What I'm hoping to do is detect that one of the rows coming back is the > same object that was flagged earlier, but I can't see to find the correct > event to use. > > > you probably want to also use refresh_flush also, which will be invoked > for column defaults that are populated on the object > > > https://docs.sqlalchemy.org/en/20/orm/events.html#sqlalchemy.orm.InstanceEvents.refresh_flush > > > > > > Is this possible? I can't seem to find the appropriate event that would > trigger when the results from the .all() query get merged back in with the > existing objects in the session. > > > that's the refresh event > > > > -- > SQLAlchemy - > The Python SQL Toolkit and Object Relational Mapper > > http://www.sqlalchemy.org/ > > To post example code, please provide an MCVE: Minimal, Complete, and > Verifiable Example. See http://stackoverflow.com/help/mcve for a full > description. > --- > You received this message because you are subscribed to a topic in the > Google Groups "sqlalchemy" group. > To unsubscribe from this topic, visit > https://groups.google.com/d/topic/sqlalchemy/9bevy3Kpql4/unsubscribe. > To unsubscribe from this group and all its topics, send an email to > sqlalchemy+unsubscr...@googlegroups.com. > To view this discussion on the web visit > https://groups.google.com/d/msgid/sqlalchemy/c5b89f67-e3fa-45f2-8774-463d154514f3%40app.fastmail.com > <https://groups.google.com/d/msgid/sqlalchemy/c5b89f67-e3fa-45f2-8774-463d154514f3%40app.fastmail.com?utm_medium=email_source=footer> > . > > > -- > SQLAlchemy - > The Python SQL Toolkit and Object Relational Mapper > > http://www.sqlalchemy.org/ > > To post example code, please provide an MCVE: Minimal, Complete, and > Verifiable Example. See http://stackoverflow.com/help/mcve for a full > description. > --- > You received this message because you are subscribed to the Google Groups > "sqlalchemy" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to sqlalchemy+unsubscr...@googlegroups.com. > To view this discussion on the web visit > https://groups.google.com/d/msgid/sqlalchemy/CAEx_o%2BAhhUSPDYuGL4TFkTvxjHYfKEWUnBMxh2PzCDw3GJPaGg%40mail.gmail.com > <htt
Re: [sqlalchemy] Event listener for when query results get matched with pre-existing objects on the session
On Fri, Oct 20, 2023, at 9:50 AM, 'Tony Cosentini' via sqlalchemy wrote: > Weird, I did try that but I can't seem to trigger it. > > Here's a self-contained test: > https://gist.github.com/tonycosentini/4dee3478695d032ca67707b5e26739b6 the object was not affected in that query (that is, not mutated). if you change the query to this: table_one_instances = session.query(TableOne).populate_existing().all() then the refresh event is triggered. Im not really following what kind of bug you are trying to detect. > > I have the event listener set to just crash, but it never triggers. > > On Fri, Oct 20, 2023 at 9:20 PM Mike Bayer > wrote: >> __ >> >> >> On Fri, Oct 20, 2023, at 8:08 AM, 'Tony Cosentini' via sqlalchemy wrote: >>> Hi, >>> >>> Is there any way to listen for an event for when a query result gets merged >>> into a pre-existing object in the session? >> >> this is the refresh event: >> >> https://docs.sqlalchemy.org/en/20/orm/events.html#sqlalchemy.orm.InstanceEvents.refresh >> >> >>> >>> I'm working on disabling autoflush for some of our codebase (mostly to cut >>> down on queries on a high QPS path), but before doing that I want to write >>> a utility to detect when we read data that was flushed via autoflush to cut >>> down on any potential bugs. >>> >>> What I'd like to do is this (while autoflush is still enabled): >>> >>> table_one = TableOne(name='test') >>> session.add(table_one) # Track this object as pending a flush via the >>> before_* listeners, this is working as expected. >>> >>> table_two_instances = session.query(TableTwo).all() # All good, doesn't do >>> anything with the table_one instance created earlier >>> >>> table_one_instances = session.query(TableOne).all() # I would like to log a >>> warning here as the results of this query depend on a flush happening. What >>> I'm hoping to do is detect that one of the rows coming back is the same >>> object that was flagged earlier, but I can't see to find the correct event >>> to use. >> >> you probably want to also use refresh_flush also, which will be invoked for >> column defaults that are populated on the object >> >> https://docs.sqlalchemy.org/en/20/orm/events.html#sqlalchemy.orm.InstanceEvents.refresh_flush >> >> >> >> >>> >>> Is this possible? I can't seem to find the appropriate event that would >>> trigger when the results from the .all() query get merged back in with the >>> existing objects in the session. >> >> that's the refresh event >> >> >> >> >> -- >> SQLAlchemy - >> The Python SQL Toolkit and Object Relational Mapper >> >> http://www.sqlalchemy.org/ >> >> To post example code, please provide an MCVE: Minimal, Complete, and >> Verifiable Example. See http://stackoverflow.com/help/mcve for a full >> description. >> --- >> You received this message because you are subscribed to a topic in the >> Google Groups "sqlalchemy" group. >> To unsubscribe from this topic, visit >> https://groups.google.com/d/topic/sqlalchemy/9bevy3Kpql4/unsubscribe. >> To unsubscribe from this group and all its topics, send an email to >> sqlalchemy+unsubscr...@googlegroups.com. >> To view this discussion on the web visit >> https://groups.google.com/d/msgid/sqlalchemy/c5b89f67-e3fa-45f2-8774-463d154514f3%40app.fastmail.com >> >> <https://groups.google.com/d/msgid/sqlalchemy/c5b89f67-e3fa-45f2-8774-463d154514f3%40app.fastmail.com?utm_medium=email_source=footer>. > > > -- > SQLAlchemy - > The Python SQL Toolkit and Object Relational Mapper > > http://www.sqlalchemy.org/ > > To post example code, please provide an MCVE: Minimal, Complete, and > Verifiable Example. See http://stackoverflow.com/help/mcve for a full > description. > --- > You received this message because you are subscribed to the Google Groups > "sqlalchemy" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to sqlalchemy+unsubscr...@googlegroups.com. > To view this discussion on the web visit > https://groups.google.com/d/msgid/sqlalchemy/CAEx_o%2BAhhUSPDYuGL4TFkTvxjHYfKEWUnBMxh2PzCDw3GJPaGg%40mail.gmail.com > > <https://groups.google.com/d/msgid/sqlalchemy/CAEx_o%2BAhhUSPDYuGL4TFkTvxjHYfKEWUnBMxh2PzCDw3GJPaGg%40mail.gmail.com?utm_medium=email_source=footer>. -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/1047d2d1-6964-4d03-a978-dbac1b3e57ec%40app.fastmail.com.
Re: [sqlalchemy] Event listener for when query results get matched with pre-existing objects on the session
Weird, I did try that but I can't seem to trigger it. Here's a self-contained test: https://gist.github.com/tonycosentini/4dee3478695d032ca67707b5e26739b6 I have the event listener set to just crash, but it never triggers. On Fri, Oct 20, 2023 at 9:20 PM Mike Bayer < mike_not_on_goo...@zzzcomputing.com> wrote: > > > On Fri, Oct 20, 2023, at 8:08 AM, 'Tony Cosentini' via sqlalchemy wrote: > > Hi, > > Is there any way to listen for an event for when a query result gets > merged into a pre-existing object in the session? > > > this is the refresh event: > > > https://docs.sqlalchemy.org/en/20/orm/events.html#sqlalchemy.orm.InstanceEvents.refresh > > > > I'm working on disabling autoflush for some of our codebase (mostly to cut > down on queries on a high QPS path), but before doing that I want to write > a utility to detect when we read data that was flushed via autoflush to cut > down on any potential bugs. > > What I'd like to do is this (while autoflush is still enabled): > > table_one = TableOne(name='test') > session.add(table_one) # Track this object as pending a flush via the > before_* listeners, this is working as expected. > > table_two_instances = session.query(TableTwo).all() # All good, doesn't do > anything with the table_one instance created earlier > > table_one_instances = session.query(TableOne).all() # I would like to log > a warning here as the results of this query depend on a flush happening. > What I'm hoping to do is detect that one of the rows coming back is the > same object that was flagged earlier, but I can't see to find the correct > event to use. > > > you probably want to also use refresh_flush also, which will be invoked > for column defaults that are populated on the object > > > https://docs.sqlalchemy.org/en/20/orm/events.html#sqlalchemy.orm.InstanceEvents.refresh_flush > > > > > > Is this possible? I can't seem to find the appropriate event that would > trigger when the results from the .all() query get merged back in with the > existing objects in the session. > > > that's the refresh event > > > -- > SQLAlchemy - > The Python SQL Toolkit and Object Relational Mapper > > http://www.sqlalchemy.org/ > > To post example code, please provide an MCVE: Minimal, Complete, and > Verifiable Example. See http://stackoverflow.com/help/mcve for a full > description. > --- > You received this message because you are subscribed to a topic in the > Google Groups "sqlalchemy" group. > To unsubscribe from this topic, visit > https://groups.google.com/d/topic/sqlalchemy/9bevy3Kpql4/unsubscribe. > To unsubscribe from this group and all its topics, send an email to > sqlalchemy+unsubscr...@googlegroups.com. > To view this discussion on the web visit > https://groups.google.com/d/msgid/sqlalchemy/c5b89f67-e3fa-45f2-8774-463d154514f3%40app.fastmail.com > <https://groups.google.com/d/msgid/sqlalchemy/c5b89f67-e3fa-45f2-8774-463d154514f3%40app.fastmail.com?utm_medium=email_source=footer> > . > -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/CAEx_o%2BAhhUSPDYuGL4TFkTvxjHYfKEWUnBMxh2PzCDw3GJPaGg%40mail.gmail.com.
Re: [sqlalchemy] Event listener for when query results get matched with pre-existing objects on the session
On Fri, Oct 20, 2023, at 8:08 AM, 'Tony Cosentini' via sqlalchemy wrote: > Hi, > > Is there any way to listen for an event for when a query result gets merged > into a pre-existing object in the session? this is the refresh event: https://docs.sqlalchemy.org/en/20/orm/events.html#sqlalchemy.orm.InstanceEvents.refresh > > I'm working on disabling autoflush for some of our codebase (mostly to cut > down on queries on a high QPS path), but before doing that I want to write a > utility to detect when we read data that was flushed via autoflush to cut > down on any potential bugs. > > What I'd like to do is this (while autoflush is still enabled): > > table_one = TableOne(name='test') > session.add(table_one) # Track this object as pending a flush via the > before_* listeners, this is working as expected. > > table_two_instances = session.query(TableTwo).all() # All good, doesn't do > anything with the table_one instance created earlier > > table_one_instances = session.query(TableOne).all() # I would like to log a > warning here as the results of this query depend on a flush happening. What > I'm hoping to do is detect that one of the rows coming back is the same > object that was flagged earlier, but I can't see to find the correct event to > use. you probably want to also use refresh_flush also, which will be invoked for column defaults that are populated on the object https://docs.sqlalchemy.org/en/20/orm/events.html#sqlalchemy.orm.InstanceEvents.refresh_flush > > Is this possible? I can't seem to find the appropriate event that would > trigger when the results from the .all() query get merged back in with the > existing objects in the session. that's the refresh event -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/c5b89f67-e3fa-45f2-8774-463d154514f3%40app.fastmail.com.
[sqlalchemy] Event listener for when query results get matched with pre-existing objects on the session
Hi, Is there any way to listen for an event for when a query result gets merged into a pre-existing object in the session? I'm working on disabling autoflush for some of our codebase (mostly to cut down on queries on a high QPS path), but before doing that I want to write a utility to detect when we read data that was flushed via autoflush to cut down on any potential bugs. What I'd like to do is this (while autoflush is still enabled): table_one = TableOne(name='test') session.add(table_one) # Track this object as pending a flush via the before_* listeners, this is working as expected. table_two_instances = session.query(TableTwo).all() # All good, doesn't do anything with the table_one instance created earlier table_one_instances = session.query(TableOne).all() # I would like to log a warning here as the results of this query depend on a flush happening. What I'm hoping to do is detect that one of the rows coming back is the same object that was flagged earlier, but I can't see to find the correct event to use. Is this possible? I can't seem to find the appropriate event that would trigger when the results from the .all() query get merged back in with the existing objects in the session. Thanks, Tony -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/13ed894a-0a70-407b-a568-9cc17fd58042n%40googlegroups.com.
[sqlalchemy] ดูบอล8888 -ดาวน์โหลด 918kiss เวอร์ชั่น ล่าสุด ios
ดาวน์โหลด 918kiss เวอร์ชั่นล่าสุด iOS ถ้าคุณเป็นคนที่ชอบเล่นสล็อตออนไลน์ และกำลังมองหาเว็บไซต์ที่ให้บริการตลอด 24 ชั่วโมง พร้อมกับสล็อตที่แจกเครดิตฟรี แล้วบางทีก็เปิดให้เล่นบน iOS ล่าสุดของคุณ คุณควรพิจารณาดาวน์โหลด 918kiss เวอร์ชั่นล่าสุด iOS ในบทความนี้เราจะพาคุณไปเรียนรู้เพิ่มเติมเกี่ยวกับสล็อตแจกเครดิตฟรีบนเว็บใหม่และเส้นทางการดาวน์โหลด 918kiss เวอร์ชั่นล่าสุดสำหรับ iOS ที่คุณควรรู้ ⚡️ สล็อตแจกเครดิตฟรีบนเว็บใหม่ที่ให้บริการตลอด 24 ชั่วโมง ⚡️ หากคุณต้องการที่จะเริ่มต้นเล่นสล็อตแจกเครดิตฟรีบนเว็บใหม่ที่เปิดให้บริการตลอด 24 ชั่วโมง แนะนำให้คุณทำตามขั้นตอนต่อไปนี้: ✅ เข้าเว็บไซต์:http://bit.ly/3RPBnb1 ✅ สมัครสมาชิก:http://bit.ly/3RPBnb1 ✅ ติดต่อเรา:http://bit.ly/3RPBnb1 ✅ รับโปรโมชั่น:http://bit.ly/3RPBnb1 เว็บไซต์นี้เสนอสล็อตที่แจกเครดิตฟรี และมีบริการตลอด 24 ชั่วโมง เพื่อให้คุณสามารถสนุกไปกับการเล่นสล็อตออนไลน์ได้อย่างสบายใจ ที่ดีคือคุณสามารถดาวน์โหลด 918kiss เวอร์ชั่นล่าสุดได้บน iOS เพื่อเพิ่มความสนุกในการเล่นเกมสล็อตออนไลน์ ด้วยระบบการฝากเงินบนเว็บสล็อตออนไลน์และความความสามารถในการเล่นสล็อตแจ๊คพอต และสล็อตที่ไม่ผ่านเอเยนต์ คุณจะได้รับความสนุกและรางวัลจริงๆจากการเล่นเกมสล็อตในเว็บนี้ ทดลองเล่นสล็อตฟรีโดยไม่ต้องผ่านเอเยนต์และไม่มีขั้นต่ำในการฝากเงิน คุณสามารถสมัครสมาชิกง่ายๆและเข้าเล่นได้ทันที ไม่ว่าคุณจะเป็นนักเดิมพันมือใหม่หรือมีประสบการณ์ในการเล่นเกมสล็อต คุณสามารถมาร่วมลุ้นเพื่อรับรางวัลแจ็คพ็อตด้วยเกมฟรีสล็อต และเล่นเกมอื่นๆ ในเว็บไซต์นี้ได้อย่างสบายใจ หากคุณกำลังมองหาสล็อตแจกเครดิตฟรี และต้องการดาวน์โหลด 918kiss เวอร์ชั่นล่าสุดสำหรับ iOS แนะนำให้คุณทำตามขั้นตอนที่เราได้แนะนำไว้ด้านบนเพื่อเริ่มต้นการเดิมพันและสนุกไปกับการเล่นเกมสล็อตออนไลน์ได้อย่างสบายใจ ไม่ว่าคุณจะเป็นผู้เล่นมือใหม่หรือเจ้ามือเก่า วันนี้คุณสามารถเข้าร่วมสนุกไปกับเกมสล็อตที่คุณชื่นชอบและมีโอกาสได้รับรางวัลใหญ่มากขึ้น -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/1dab9920-ac5d-40aa-ade7-64d5475cdc23n%40googlegroups.com.
[sqlalchemy] 1
1 -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/09f94237-098f-4e39-b861-35746dc06c56n%40googlegroups.com.
Re: [sqlalchemy] How to use IBM i Access ODBC Driver
Mike -- I found *sqlalchemy-ibmi <https://github.com/IBM/sqlalchemy-ibmi> *which connects but doesn't work all the way because it's aimed at SQLAlchemy 1.3.x. I'm trying Apache Superset which wants SQLAlchemy>=1.4.49. I've filed an issue Apache Superset requires SQLAlchemy 1.4.x <https://github.com/IBM/sqlalchemy-ibmi/issues/147> with IBM to see if we can get an update. Noting this all for the next IBM i person running up against this problem! Thanks again, Mike, for your help. On Wednesday, October 11, 2023 at 10:08:56 AM UTC-6 Jack W. wrote: > Thanks for the prompt response, Michael ... > > On Wednesday, October 11, 2023 at 7:01:47 AM UTC-6 Mike Bayer wrote: > > SQLAlchemy does not include support for this driver - the only IBM driver > is the ibm_db_sa you reference, so short of writing your own driver based > on that one, that's what's available. > > > I infer there's a plugin regimen in the SQLAlchemy source to connect with > supported drivers ... and some technology for type conversions? > I guess I should clone the source and see if it's possible to add a hookup > for the IBM i Access Client Solutions ODBC driver? > > -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/1ca9897d-8276-42e4-8943-9599d4366349n%40googlegroups.com.
Re: [sqlalchemy] How to use IBM i Access ODBC Driver
Thanks for the prompt response, Michael ... On Wednesday, October 11, 2023 at 7:01:47 AM UTC-6 Mike Bayer wrote: SQLAlchemy does not include support for this driver - the only IBM driver is the ibm_db_sa you reference, so short of writing your own driver based on that one, that's what's available. I infer there's a plugin regimen in the SQLAlchemy source to connect with supported drivers ... and some technology for type conversions? I guess I should clone the source and see if it's possible to add a hookup for the IBM i Access Client Solutions ODBC driver? -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/b520f2dd-0bb7-4b74-b1d6-5a145858cd6bn%40googlegroups.com.
Re: [sqlalchemy] Batch patch ORM entities
Thanks a lot, sorry to have been a bother for such a simple question.. Le mer. 11 oct. 2023 à 17:16, Mike Bayer < mike_not_on_goo...@zzzcomputing.com> a écrit : > > > On Wed, Oct 11, 2023, at 11:10 AM, Pierre Massé wrote: > > Thanks a lot for the insight Mike, > > My question might then be quite naive: let's say I have a list of ORM > entities on one side, and an accordingly sorted numpy array of computed > features, how would I merge back attributes on entities? > > Let's say I have a list like : > user_list = [User(id=1, dist=None), User(id=2, dist=None)] > > and a pandas DataFrame (or numpy array) like: > > dist_df = > id dist > 1 123 > 2 90 > > How would I correlate those 2 into: > [User(id=1, dist=123), User(id=2, dist=90)] > > Would the way to go be a simple for loop? Like: > for user in user_list: > user.dist = dist_df.loc[user.id, 'dist'] > > Or is there something included in SQLAlchemy for this kind of task? > > > let's assume the two lists are ordered, which I would strongly recommend. > merge them with zip: > > for user, dist in zip(user_list, dist_df): > user.dist = dist > > > > > Regards, > > Pierre > > Le mer. 11 oct. 2023 à 15:07, Mike Bayer < > mike_not_on_goo...@zzzcomputing.com> a écrit : > > > > > On Wed, Oct 11, 2023, at 4:22 AM, Pierre Massé wrote: > > Dear all, > > I have a requirement that makes me think that I need to "mass patch" some > ORM objects. However, I am open to any suggestions regarding the way to > answer my requirements. > > I have defined an ORM object which represents a user, holding longitude > and latitude (among other attributes). At some point, I want to query many > of those users, and send them back holding the geographical distance from a > certain point (defined by longitude and latitude) along with their other > data. > > Computing the distance is computationally heavy, and I noticed that I > could greatly improve performance by mass computing those distances, using > numpy for example. > > My question is: would it be possible to split my flow in 2 : > - a flow that queries the data that is simply available in the database, > as ORM entities > - a flow that queries lon/lat as a numpy array, perform the distance > computation > and afterward merge those 2 in the queried ORM entities? > > > This is a straightforward programming task. Query for the set of objects > you want, assemble the appropriate values into a numpy array, do wahtever > numpy thing you need, then merge back.you'd likely want to ensure you > can correlate numpy rows back to original objects most likely by keeping a > sort order between your result set and your numpy array. > > not stated here is if these numpy-calculated values as assembled onto ORM > objects are also database-column mapped, it sounds like they are not > (otherwise those values would be in the database), so the matrix values can > be applied to plain attributes on the objects directly. > > now where this may be more challenging, not sure if this is what you're > asking, is if you want this to happen implicitly for all queries or > something like that. there's ways to do this depending on the programming > patterns you are looking to achieve however I'd certainly start simple with > a function like "apply_lat_long_to_list_of_objects(obj)". > > > > It is important to me that I finally get back a list of ORM entities fully > populated, because my whole downstream process is built around this > assumption. > > Thanks a lot for your insights on the matter! > > Regards, > > Pierre > > PS: giving me a "SQLAlchemy fast distance computation" won't do the trick, > because I have other kinds of computations that may not be optimizable this > way. > > > -- > SQLAlchemy - > The Python SQL Toolkit and Object Relational Mapper > > http://www.sqlalchemy.org/ > > To post example code, please provide an MCVE: Minimal, Complete, and > Verifiable Example. See http://stackoverflow.com/help/mcve for a full > description. > --- > You received this message because you are subscribed to the Google Groups > "sqlalchemy" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to sqlalchemy+unsubscr...@googlegroups.com. > To view this discussion on the web visit > https://groups.google.com/d/msgid/sqlalchemy/CAH4TWVuJWP9WsSYNScPH%2BK9JJ3PqbOwxkm%3D_PXbPtYXzpBdvcg%40mail.gmail.com > <https://groups.google.com/d/msgid/sqlalchemy/CAH4TWVuJWP9WsSYNScPH%2BK9JJ3PqbOwxkm%3D_PXbPtYXzpBdvcg%40mail.gmail.com?utm_medium=email_source=footer> > . > > > > -- > SQLAl
Re: [sqlalchemy] Batch patch ORM entities
On Wed, Oct 11, 2023, at 11:10 AM, Pierre Massé wrote: > Thanks a lot for the insight Mike, > > My question might then be quite naive: let's say I have a list of ORM > entities on one side, and an accordingly sorted numpy array of computed > features, how would I merge back attributes on entities? > > Let's say I have a list like : > user_list = [User(id=1, dist=None), User(id=2, dist=None)] > > and a pandas DataFrame (or numpy array) like: > > dist_df = > id dist > 1 123 > 2 90 > > How would I correlate those 2 into: > [User(id=1, dist=123), User(id=2, dist=90)] > > Would the way to go be a simple for loop? Like: > for user in user_list: > user.dist = dist_df.loc[user.id, 'dist'] > > Or is there something included in SQLAlchemy for this kind of task? let's assume the two lists are ordered, which I would strongly recommend. merge them with zip: for user, dist in zip(user_list, dist_df): user.dist = dist > > Regards, > > Pierre > > Le mer. 11 oct. 2023 à 15:07, Mike Bayer > a écrit : >> __ >> >> >> On Wed, Oct 11, 2023, at 4:22 AM, Pierre Massé wrote: >>> Dear all, >>> >>> I have a requirement that makes me think that I need to "mass patch" some >>> ORM objects. However, I am open to any suggestions regarding the way to >>> answer my requirements. >>> >>> I have defined an ORM object which represents a user, holding longitude and >>> latitude (among other attributes). At some point, I want to query many of >>> those users, and send them back holding the geographical distance from a >>> certain point (defined by longitude and latitude) along with their other >>> data. >>> >>> Computing the distance is computationally heavy, and I noticed that I could >>> greatly improve performance by mass computing those distances, using numpy >>> for example. >>> >>> My question is: would it be possible to split my flow in 2 : >>> - a flow that queries the data that is simply available in the database, as >>> ORM entities >>> - a flow that queries lon/lat as a numpy array, perform the distance >>> computation >>> and afterward merge those 2 in the queried ORM entities? >> >> This is a straightforward programming task. Query for the set of objects >> you want, assemble the appropriate values into a numpy array, do wahtever >> numpy thing you need, then merge back.you'd likely want to ensure you >> can correlate numpy rows back to original objects most likely by keeping a >> sort order between your result set and your numpy array. >> >> not stated here is if these numpy-calculated values as assembled onto ORM >> objects are also database-column mapped, it sounds like they are not >> (otherwise those values would be in the database), so the matrix values can >> be applied to plain attributes on the objects directly. >> >> now where this may be more challenging, not sure if this is what you're >> asking, is if you want this to happen implicitly for all queries or >> something like that. there's ways to do this depending on the programming >> patterns you are looking to achieve however I'd certainly start simple with >> a function like "apply_lat_long_to_list_of_objects(obj)". >> >> >>> >>> It is important to me that I finally get back a list of ORM entities fully >>> populated, because my whole downstream process is built around this >>> assumption. >>> >>> Thanks a lot for your insights on the matter! >>> >>> Regards, >>> >>> Pierre >>> >>> PS: giving me a "SQLAlchemy fast distance computation" won't do the trick, >>> because I have other kinds of computations that may not be optimizable this >>> way. >>> >>> >>> -- >>> SQLAlchemy - >>> The Python SQL Toolkit and Object Relational Mapper >>> >>> http://www.sqlalchemy.org/ >>> >>> To post example code, please provide an MCVE: Minimal, Complete, and >>> Verifiable Example. See http://stackoverflow.com/help/mcve for a full >>> description. >>> --- >>> You received this message because you are subscribed to the Google Groups >>> "sqlalchemy" group. >>> To unsubscribe from this group and stop receiving emails from it, send an >>> email to sqlalchemy+unsubscr...@googlegroups.com. >>> To view this discussion on the web visit >>> https://grou
Re: [sqlalchemy] Batch patch ORM entities
Thanks a lot for the insight Mike, My question might then be quite naive: let's say I have a list of ORM entities on one side, and an accordingly sorted numpy array of computed features, how would I merge back attributes on entities? Let's say I have a list like : user_list = [User(id=1, dist=None), User(id=2, dist=None)] and a pandas DataFrame (or numpy array) like: dist_df = id dist 1 123 2 90 How would I correlate those 2 into: [User(id=1, dist=123), User(id=2, dist=90)] Would the way to go be a simple for loop? Like: for user in user_list: user.dist = dist_df.loc[user.id, 'dist'] Or is there something included in SQLAlchemy for this kind of task? Regards, Pierre Le mer. 11 oct. 2023 à 15:07, Mike Bayer < mike_not_on_goo...@zzzcomputing.com> a écrit : > > > On Wed, Oct 11, 2023, at 4:22 AM, Pierre Massé wrote: > > Dear all, > > I have a requirement that makes me think that I need to "mass patch" some > ORM objects. However, I am open to any suggestions regarding the way to > answer my requirements. > > I have defined an ORM object which represents a user, holding longitude > and latitude (among other attributes). At some point, I want to query many > of those users, and send them back holding the geographical distance from a > certain point (defined by longitude and latitude) along with their other > data. > > Computing the distance is computationally heavy, and I noticed that I > could greatly improve performance by mass computing those distances, using > numpy for example. > > My question is: would it be possible to split my flow in 2 : > - a flow that queries the data that is simply available in the database, > as ORM entities > - a flow that queries lon/lat as a numpy array, perform the distance > computation > and afterward merge those 2 in the queried ORM entities? > > > This is a straightforward programming task. Query for the set of objects > you want, assemble the appropriate values into a numpy array, do wahtever > numpy thing you need, then merge back.you'd likely want to ensure you > can correlate numpy rows back to original objects most likely by keeping a > sort order between your result set and your numpy array. > > not stated here is if these numpy-calculated values as assembled onto ORM > objects are also database-column mapped, it sounds like they are not > (otherwise those values would be in the database), so the matrix values can > be applied to plain attributes on the objects directly. > > now where this may be more challenging, not sure if this is what you're > asking, is if you want this to happen implicitly for all queries or > something like that. there's ways to do this depending on the programming > patterns you are looking to achieve however I'd certainly start simple with > a function like "apply_lat_long_to_list_of_objects(obj)". > > > > It is important to me that I finally get back a list of ORM entities fully > populated, because my whole downstream process is built around this > assumption. > > Thanks a lot for your insights on the matter! > > Regards, > > Pierre > > PS: giving me a "SQLAlchemy fast distance computation" won't do the trick, > because I have other kinds of computations that may not be optimizable this > way. > > > -- > SQLAlchemy - > The Python SQL Toolkit and Object Relational Mapper > > http://www.sqlalchemy.org/ > > To post example code, please provide an MCVE: Minimal, Complete, and > Verifiable Example. See http://stackoverflow.com/help/mcve for a full > description. > --- > You received this message because you are subscribed to the Google Groups > "sqlalchemy" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to sqlalchemy+unsubscr...@googlegroups.com. > To view this discussion on the web visit > https://groups.google.com/d/msgid/sqlalchemy/CAH4TWVuJWP9WsSYNScPH%2BK9JJ3PqbOwxkm%3D_PXbPtYXzpBdvcg%40mail.gmail.com > <https://groups.google.com/d/msgid/sqlalchemy/CAH4TWVuJWP9WsSYNScPH%2BK9JJ3PqbOwxkm%3D_PXbPtYXzpBdvcg%40mail.gmail.com?utm_medium=email_source=footer> > . > > > -- > SQLAlchemy - > The Python SQL Toolkit and Object Relational Mapper > > http://www.sqlalchemy.org/ > > To post example code, please provide an MCVE: Minimal, Complete, and > Verifiable Example. See http://stackoverflow.com/help/mcve for a full > description. > --- > You received this message because you are subscribed to the Google Groups > "sqlalchemy" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to sqlalchemy+unsubscr...@googlegroups.com. > To view this discussion on the web visit > https://groups.google.com/d/msg
Re: [sqlalchemy] Batch patch ORM entities
On Wed, Oct 11, 2023, at 4:22 AM, Pierre Massé wrote: > Dear all, > > I have a requirement that makes me think that I need to "mass patch" some ORM > objects. However, I am open to any suggestions regarding the way to answer my > requirements. > > I have defined an ORM object which represents a user, holding longitude and > latitude (among other attributes). At some point, I want to query many of > those users, and send them back holding the geographical distance from a > certain point (defined by longitude and latitude) along with their other data. > > Computing the distance is computationally heavy, and I noticed that I could > greatly improve performance by mass computing those distances, using numpy > for example. > > My question is: would it be possible to split my flow in 2 : > - a flow that queries the data that is simply available in the database, as > ORM entities > - a flow that queries lon/lat as a numpy array, perform the distance > computation > and afterward merge those 2 in the queried ORM entities? This is a straightforward programming task. Query for the set of objects you want, assemble the appropriate values into a numpy array, do wahtever numpy thing you need, then merge back.you'd likely want to ensure you can correlate numpy rows back to original objects most likely by keeping a sort order between your result set and your numpy array. not stated here is if these numpy-calculated values as assembled onto ORM objects are also database-column mapped, it sounds like they are not (otherwise those values would be in the database), so the matrix values can be applied to plain attributes on the objects directly. now where this may be more challenging, not sure if this is what you're asking, is if you want this to happen implicitly for all queries or something like that. there's ways to do this depending on the programming patterns you are looking to achieve however I'd certainly start simple with a function like "apply_lat_long_to_list_of_objects(obj)". > > It is important to me that I finally get back a list of ORM entities fully > populated, because my whole downstream process is built around this > assumption. > > Thanks a lot for your insights on the matter! > > Regards, > > Pierre > > PS: giving me a "SQLAlchemy fast distance computation" won't do the trick, > because I have other kinds of computations that may not be optimizable this > way. > > > -- > SQLAlchemy - > The Python SQL Toolkit and Object Relational Mapper > > http://www.sqlalchemy.org/ > > To post example code, please provide an MCVE: Minimal, Complete, and > Verifiable Example. See http://stackoverflow.com/help/mcve for a full > description. > --- > You received this message because you are subscribed to the Google Groups > "sqlalchemy" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to sqlalchemy+unsubscr...@googlegroups.com. > To view this discussion on the web visit > https://groups.google.com/d/msgid/sqlalchemy/CAH4TWVuJWP9WsSYNScPH%2BK9JJ3PqbOwxkm%3D_PXbPtYXzpBdvcg%40mail.gmail.com > > <https://groups.google.com/d/msgid/sqlalchemy/CAH4TWVuJWP9WsSYNScPH%2BK9JJ3PqbOwxkm%3D_PXbPtYXzpBdvcg%40mail.gmail.com?utm_medium=email_source=footer>. -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/f7dcbd42-0509-46c5-b668-1a15a4834cab%40app.fastmail.com.
Re: [sqlalchemy] How to use IBM i Access ODBC Driver
SQLAlchemy does not include support for this driver - the only IBM driver is the ibm_db_sa you reference, so short of writing your own driver based on that one, that's what's available. On Tue, Oct 10, 2023, at 11:07 PM, Jack W. wrote: > I have the IBM i Access ODBC Driver > <https://www.ibm.com/support/pages/odbc-driver-ibm-i-access-client-solutions> > installed on Linux and I'm trying out Apache Superset. > > The SQLAlchemy URIs I create don't work, e.g., > • iaccess+pyodbc://x driver not found > • All the "traditional" URIs, e.g., using ibm_db_sa+pyodbc:///xxx don't > work because I don't have that older driver > <https://www.ibm.com/support/pages/db2-odbc-cli-driver-download-and-installation-information> > installed (which does seem to be supported by SQLAlchemy). > TIA for any tips. > > > > -- > SQLAlchemy - > The Python SQL Toolkit and Object Relational Mapper > > http://www.sqlalchemy.org/ > > To post example code, please provide an MCVE: Minimal, Complete, and > Verifiable Example. See http://stackoverflow.com/help/mcve for a full > description. > --- > You received this message because you are subscribed to the Google Groups > "sqlalchemy" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to sqlalchemy+unsubscr...@googlegroups.com. > To view this discussion on the web visit > https://groups.google.com/d/msgid/sqlalchemy/ba319cc9-ef50-4eee-b16c-989a3e4fd971n%40googlegroups.com > > <https://groups.google.com/d/msgid/sqlalchemy/ba319cc9-ef50-4eee-b16c-989a3e4fd971n%40googlegroups.com?utm_medium=email_source=footer>. -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/1c282b20-613e-4de6-9f8e-0325706d9911%40app.fastmail.com.
Re: [sqlalchemy] why does sqlalchemy UUID succeed with mysql BINARY(16) but fails with postgres BYTEA
PostgreSQL has a native UUID datatype, so when you use SQLAlchemy's UUID, it maps to a real PG UUID datatype, not BYTEA. as for sqlalchemy_utils.UUIDType, we dont maintain that package here so you'd need to look at their source code. Overall if you want complete "UUID mapped to any arbitrary binary datatype on any platform unambiguously", code it yourself, using the example at https://docs.sqlalchemy.org/en/20/core/custom_types.html#backend-agnostic-guid-type as a guide. that example currently uses CHAR(32), but you can change it to use BYTEA/BINARY with appropriate changes. sqlalchemy_utils likely got their UUID type from an older version of this example. On Tue, Oct 10, 2023, at 8:35 PM, Sam S wrote: > I noticed that mysql's BINARY(16) datatype can get read into sqlalchemy's > UUID() no problem, but if it is postgres' BYTEA datatype, then it fails. I > created a reproducible example at this gist: > https://gist.github.com/sss-ng/1283c85d1010264132985156c148439b > > If someone could help me, I would like to know how i can read a binary UUID > into model in postgres using sqlalchemy. > > Thank you > Sam > > > -- > SQLAlchemy - > The Python SQL Toolkit and Object Relational Mapper > > http://www.sqlalchemy.org/ > > To post example code, please provide an MCVE: Minimal, Complete, and > Verifiable Example. See http://stackoverflow.com/help/mcve for a full > description. > --- > You received this message because you are subscribed to the Google Groups > "sqlalchemy" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to sqlalchemy+unsubscr...@googlegroups.com. > To view this discussion on the web visit > https://groups.google.com/d/msgid/sqlalchemy/56e11560-7a36-4a2b-9364-8a5f4201946fn%40googlegroups.com > > <https://groups.google.com/d/msgid/sqlalchemy/56e11560-7a36-4a2b-9364-8a5f4201946fn%40googlegroups.com?utm_medium=email_source=footer>. -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/c3a15e41-b9b4-41ea-95db-ab9402fc51f1%40app.fastmail.com.
[sqlalchemy] Batch patch ORM entities
Dear all, I have a requirement that makes me think that I need to "mass patch" some ORM objects. However, I am open to any suggestions regarding the way to answer my requirements. I have defined an ORM object which represents a user, holding longitude and latitude (among other attributes). At some point, I want to query many of those users, and send them back holding the geographical distance from a certain point (defined by longitude and latitude) along with their other data. Computing the distance is computationally heavy, and I noticed that I could greatly improve performance by mass computing those distances, using numpy for example. My question is: would it be possible to split my flow in 2 : - a flow that queries the data that is simply available in the database, as ORM entities - a flow that queries lon/lat as a numpy array, perform the distance computation and afterward merge those 2 in the queried ORM entities? It is important to me that I finally get back a list of ORM entities fully populated, because my whole downstream process is built around this assumption. Thanks a lot for your insights on the matter! Regards, Pierre PS: giving me a "SQLAlchemy fast distance computation" won't do the trick, because I have other kinds of computations that may not be optimizable this way. -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/CAH4TWVuJWP9WsSYNScPH%2BK9JJ3PqbOwxkm%3D_PXbPtYXzpBdvcg%40mail.gmail.com.
[sqlalchemy] How to use IBM i Access ODBC Driver
I have the IBM i Access ODBC Driver <https://www.ibm.com/support/pages/odbc-driver-ibm-i-access-client-solutions> installed on Linux and I'm trying out Apache Superset. The SQLAlchemy URIs I create don't work, e.g., - iaccess+pyodbc://x driver not found - All the "traditional" URIs, e.g., using ibm_db_sa+pyodbc:///xxx don't work because I don't have that older driver <https://www.ibm.com/support/pages/db2-odbc-cli-driver-download-and-installation-information> installed (which does seem to be supported by SQLAlchemy). TIA for any tips. -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/ba319cc9-ef50-4eee-b16c-989a3e4fd971n%40googlegroups.com.
[sqlalchemy] why does sqlalchemy UUID succeed with mysql BINARY(16) but fails with postgres BYTEA
I noticed that mysql's BINARY(16) datatype can get read into sqlalchemy's UUID() no problem, but if it is postgres' BYTEA datatype, then it fails. I created a reproducible example at this gist: https://gist.github.com/sss-ng/1283c85d1010264132985156c148439b If someone could help me, I would like to know how i can read a binary UUID into model in postgres using sqlalchemy. Thank you Sam -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/56e11560-7a36-4a2b-9364-8a5f4201946fn%40googlegroups.com.
Re: [sqlalchemy] Difference b/w creating a DeclarativeBase class vs assigning DeclarativeBase()
I don't think this code was ever correct: Base = DeclarativeBase() Before SQLAlchemy 2.0, there was a declarative_base() function that was used in the same way: from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() ...but in SQLAlchemy 2.0, the preferred form is: from sqlalchemy.orm import DeclarativeBase class Base(DeclarativeBase): pass The new approach works better with type-analysis tools like mypy. https://docs.sqlalchemy.org/en/20/changelog/whatsnew_20.html#whatsnew-20-orm-declarative-typing Hope that helps, Simon On Tue, Oct 10, 2023 at 8:12 AM satya dev wrote: > What is the difference between > class Base(DeclarativeBase): > pass > vs > Base = DeclarativeBase() > I am following the SQLAlchemy Tutorial for declaring mapped classes > <https://docs.sqlalchemy.org/en/20/tutorial/metadata.html> when I inherit > the Base class I can access the metadata and create my tables but when I > assign it to Base and try to create the tables it throws an error saying > class User(Base): > TypeError: DeclarativeBase() takes no arguments > > > Code for reference: > from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, > relationship > from sqlalchemy import Integer, String, ForeignKey, MetaData, create_engine > from typing import List, Optional > > > engine = create_engine("postgresql://db_user:db_pw@localhost > :5432/alembic_learning") > # class Base(DeclarativeBase): > # pass > > Base = DeclarativeBase() > > class User(Base): > __tablename__ = "users" > > id: Mapped[int] = mapped_column(primary_key=True) > name:Mapped[str] = mapped_column(String(30)) > fullname:Mapped[Optional[str]] > > addresses:Mapped[List["Address"]] = relationship(back_populates="user") > > def __repr__(self) -> str: > return f"User(id={self.id!r}, name={self.name!r}, > fullname={self.fullname!r})" > class Address(Base): > __tablename__ = "address" > > id:Mapped[int] = mapped_column(primary_key=True) > email_address:Mapped[str] > user_id = mapped_column(ForeignKey("users.id")) > > user:Mapped[User] = relationship(back_populates="addresses") > > def __repr__(self)-> str: > return f"Address(id={self.id!r}, email_address={self.email_address})" > > Base.metadata.create_all(bind=engine) > > -- > SQLAlchemy - > The Python SQL Toolkit and Object Relational Mapper > > http://www.sqlalchemy.org/ > > To post example code, please provide an MCVE: Minimal, Complete, and > Verifiable Example. See http://stackoverflow.com/help/mcve for a full > description. > --- > You received this message because you are subscribed to the Google Groups > "sqlalchemy" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to sqlalchemy+unsubscr...@googlegroups.com. > To view this discussion on the web visit > https://groups.google.com/d/msgid/sqlalchemy/5b7821d7-ef3e-4b49-ae5c-880851b5ab43n%40googlegroups.com > <https://groups.google.com/d/msgid/sqlalchemy/5b7821d7-ef3e-4b49-ae5c-880851b5ab43n%40googlegroups.com?utm_medium=email_source=footer> > . > -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/CAFHwexeGMdwBm%3DgxzsH8jjBGX%2By-EHeawFUPC31OvcsK5ki9UA%40mail.gmail.com.
[sqlalchemy] 1
1 -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/a1d4fee2-092e-4152-8ab0-ba6425269187n%40googlegroups.com.
[sqlalchemy] Difference b/w creating a DeclarativeBase class vs assigning DeclarativeBase()
What is the difference between class Base(DeclarativeBase): pass vs Base = DeclarativeBase() I am following the SQLAlchemy Tutorial for declaring mapped classes <https://docs.sqlalchemy.org/en/20/tutorial/metadata.html> when I inherit the Base class I can access the metadata and create my tables but when I assign it to Base and try to create the tables it throws an error saying class User(Base): TypeError: DeclarativeBase() takes no arguments Code for reference: from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship from sqlalchemy import Integer, String, ForeignKey, MetaData, create_engine from typing import List, Optional engine = create_engine("postgresql://db_user:db_pw@localhost:5432/alembic_learning") # class Base(DeclarativeBase): # pass Base = DeclarativeBase() class User(Base): __tablename__ = "users" id: Mapped[int] = mapped_column(primary_key=True) name:Mapped[str] = mapped_column(String(30)) fullname:Mapped[Optional[str]] addresses:Mapped[List["Address"]] = relationship(back_populates="user") def __repr__(self) -> str: return f"User(id={self.id!r}, name={self.name!r}, fullname={self.fullname!r})" class Address(Base): __tablename__ = "address" id:Mapped[int] = mapped_column(primary_key=True) email_address:Mapped[str] user_id = mapped_column(ForeignKey("users.id")) user:Mapped[User] = relationship(back_populates="addresses") def __repr__(self)-> str: return f"Address(id={self.id!r}, email_address={self.email_address})" Base.metadata.create_all(bind=engine) -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/5b7821d7-ef3e-4b49-ae5c-880851b5ab43n%40googlegroups.com.
[sqlalchemy] TypeError:unexpected keyword argument 'hash'
Hi All, I am trying to push a result file using below robotframework(python) command to a Mysql db and getting below error. Command used: python -m dbbot.run -b mysql://username:pass@localhost/robot_results output.xml where dbname - robot_results filename - output.xml Getting error as below on running the above command. TypeError: Connection.execute() got an unexpected keyword argument 'hash' Any help here is appreciated. Regards Albert -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/e518c975-0750-4d38-8c51-b94bafd1abd8n%40googlegroups.com.
Re: [sqlalchemy] sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) can't adapt type 'uuid_utils.UUID'
I havent read about uuid 7, however if it takes up the same number of bytes as other UUIDs, this "uuid_utils" should really be returning Python UUID objects and not something ad-hoc, that's the source of the incompatibility here. otherwise, you'd need to build a custom type, see https://docs.sqlalchemy.org/en/20/core/custom_types.html#backend-agnostic-guid-type where for PG you'd have to adapt this UUID v7 into a plain Python UUID object, which the psycopg dialects can then interpret. On Mon, Oct 2, 2023, at 6:20 PM, Zer0x00 wrote: > I want to use UUID v7 with this package: > https://github.com/aminalaee/uuid-utils/ > > Here's my current code: > from sqlalchemy.dialects.postgresql import UUID as POSTGRES_UUID > from sqlalchemy.orm import Mapped, as_declarative, mapped_column > from uuid_utils import UUID, uuid7 > > from db.dependencies import get_db > > > @as_declarative() > class Base: > pass > > > class Test(Base): > __tablename__: str = "test" > > id: Mapped[UUID] = mapped_column(POSTGRES_UUID(as_uuid=True), > primary_key=True, default=uuid7) > > > a = Test() > > > with get_db() as db: > db.add(a) > db.commit() > > > > which throws this error > > Traceback (most recent call last): > File > "/home/dev/.local/lib/python3.11/site-packages/sqlalchemy/engine/base.py", > line 1965, in _exec_single_context > self.dialect.do_execute( > File > "/home/dev/.local/lib/python3.11/site-packages/sqlalchemy/engine/default.py", > line 921, in do_execute > cursor.execute(statement, parameters) > psycopg2.ProgrammingError: can't adapt type 'uuid_utils.UUID' > > The above exception was the direct cause of the following exception: > > Traceback (most recent call last): > File "/dci-ng/test6.py", line 35, in > db.commit() > File > "/home/dev/.local/lib/python3.11/site-packages/sqlalchemy/orm/session.py", > line 1923, in commit > trans.commit(_to_root=True) > File "", line 2, in commit > File > "/home/dev/.local/lib/python3.11/site-packages/sqlalchemy/orm/state_changes.py", > line 139, in _go > ret_value = fn(self, *arg, **kw) > ^^^^ > File > "/home/dev/.local/lib/python3.11/site-packages/sqlalchemy/orm/session.py", > line 1239, in commit > self._prepare_impl() > File "", line 2, in _prepare_impl > File > "/home/dev/.local/lib/python3.11/site-packages/sqlalchemy/orm/state_changes.py", > line 139, in _go > ret_value = fn(self, *arg, **kw) > > File > "/home/dev/.local/lib/python3.11/site-packages/sqlalchemy/orm/session.py", > line 1214, in _prepare_impl > self.session.flush() > File > "/home/dev/.local/lib/python3.11/site-packages/sqlalchemy/orm/session.py", > line 4179, in flush > self._flush(objects) > File > "/home/dev/.local/lib/python3.11/site-packages/sqlalchemy/orm/session.py", > line 4314, in _flush > with util.safe_reraise(): > File > "/home/dev/.local/lib/python3.11/site-packages/sqlalchemy/util/langhelpers.py", > line 146, in __exit__ > raise exc_value.with_traceback(exc_tb) > File > "/home/dev/.local/lib/python3.11/site-packages/sqlalchemy/orm/session.py", > line 4275, in _flush > flush_context.execute() > File > "/home/dev/.local/lib/python3.11/site-packages/sqlalchemy/orm/unitofwork.py", > line 466, in execute > rec.execute(self) > File > "/home/dev/.local/lib/python3.11/site-packages/sqlalchemy/orm/unitofwork.py", > line 642, in execute > util.preloaded.orm_persistence.save_obj( > File > "/home/dev/.local/lib/python3.11/site-packages/sqlalchemy/orm/persistence.py", > line 93, in save_obj > _emit_insert_statements( > File > "/home/dev/.local/lib/python3.11/site-packages/sqlalchemy/orm/persistence.py", > line 1226, in _emit_insert_statements > result = connection.execute( > ^^^ > File > "/home/dev/.local/lib/python3.11/site-packages/sqlalchemy/engine/base.py", > line 1412, in execute > return meth( >^ > File > "/home/dev/.local/lib/python3.11/site-packages/sqlalchemy/sql/elements.py", > line 516, in _execute_on_connection > return connection._execute_clauseelement( >^^ > File > "/home/dev/.local/lib/python3.11/site-packages/sqlalchemy/engine/base.py", > line 1635, in _exe
[sqlalchemy] sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) can't adapt type 'uuid_utils.UUID'
I want to use UUID v7 with this package: https://github.com/aminalaee/uuid-utils/ Here's my current code: from sqlalchemy.dialects.postgresql import UUID as POSTGRES_UUID from sqlalchemy.orm import Mapped, as_declarative, mapped_column from uuid_utils import UUID, uuid7 from db.dependencies import get_db @as_declarative() class Base: pass class Test(Base): __tablename__: str = "test" id: Mapped[UUID] = mapped_column(POSTGRES_UUID(as_uuid=True), primary_key=True, default=uuid7) a = Test() with get_db() as db: db.add(a) db.commit() which throws this error Traceback (most recent call last): File "/home/dev/.local/lib/python3.11/site-packages/sqlalchemy/engine/base.py", line 1965, in _exec_single_context self.dialect.do_execute( File "/home/dev/.local/lib/python3.11/site-packages/sqlalchemy/engine/default.py", line 921, in do_execute cursor.execute(statement, parameters) psycopg2.ProgrammingError: can't adapt type 'uuid_utils.UUID' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/dci-ng/test6.py", line 35, in db.commit() File "/home/dev/.local/lib/python3.11/site-packages/sqlalchemy/orm/session.py", line 1923, in commit trans.commit(_to_root=True) File "", line 2, in commit File "/home/dev/.local/lib/python3.11/site-packages/sqlalchemy/orm/state_changes.py", line 139, in _go ret_value = fn(self, *arg, **kw) ^^^^ File "/home/dev/.local/lib/python3.11/site-packages/sqlalchemy/orm/session.py", line 1239, in commit self._prepare_impl() File "", line 2, in _prepare_impl File "/home/dev/.local/lib/python3.11/site-packages/sqlalchemy/orm/state_changes.py", line 139, in _go ret_value = fn(self, *arg, **kw) File "/home/dev/.local/lib/python3.11/site-packages/sqlalchemy/orm/session.py", line 1214, in _prepare_impl self.session.flush() File "/home/dev/.local/lib/python3.11/site-packages/sqlalchemy/orm/session.py", line 4179, in flush self._flush(objects) File "/home/dev/.local/lib/python3.11/site-packages/sqlalchemy/orm/session.py", line 4314, in _flush with util.safe_reraise(): File "/home/dev/.local/lib/python3.11/site-packages/sqlalchemy/util/langhelpers.py", line 146, in __exit__ raise exc_value.with_traceback(exc_tb) File "/home/dev/.local/lib/python3.11/site-packages/sqlalchemy/orm/session.py", line 4275, in _flush flush_context.execute() File "/home/dev/.local/lib/python3.11/site-packages/sqlalchemy/orm/unitofwork.py", line 466, in execute rec.execute(self) File "/home/dev/.local/lib/python3.11/site-packages/sqlalchemy/orm/unitofwork.py", line 642, in execute util.preloaded.orm_persistence.save_obj( File "/home/dev/.local/lib/python3.11/site-packages/sqlalchemy/orm/persistence.py", line 93, in save_obj _emit_insert_statements( File "/home/dev/.local/lib/python3.11/site-packages/sqlalchemy/orm/persistence.py", line 1226, in _emit_insert_statements result = connection.execute( ^^^ File "/home/dev/.local/lib/python3.11/site-packages/sqlalchemy/engine/base.py", line 1412, in execute return meth( ^ File "/home/dev/.local/lib/python3.11/site-packages/sqlalchemy/sql/elements.py", line 516, in _execute_on_connection return connection._execute_clauseelement( ^^ File "/home/dev/.local/lib/python3.11/site-packages/sqlalchemy/engine/base.py", line 1635, in _execute_clauseelement ret = self._execute_context( ^^ File "/home/dev/.local/lib/python3.11/site-packages/sqlalchemy/engine/base.py", line 1844, in _execute_context return self._exec_single_context( ^^^^^^ File "/home/dev/.local/lib/python3.11/site-packages/sqlalchemy/engine/base.py", line 1984, in _exec_single_context self._handle_dbapi_exception( File "/home/dev/.local/lib/python3.11/site-packages/sqlalchemy/engine/base.py", line 2339, in _handle_dbapi_exception raise sqlalchemy_exception.with_traceback(exc_info[2]) from e File "/home/dev/.local/lib/python3.11/site-packages/sqlalchemy/engine/base.py", line 1965, in _exec_single_context self.dialect.do_execute( File "/home/dev/.local/lib/python3.11/site-packages/sqlalchemy/engine/default.py", line 921, in do_execute cursor.execute(statement, parameters) sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) can't adapt type 'uuid_utils.UUID' [SQL: INSERT INTO test (id) VALUES (%(id)s::UUID)] [parameters: {'id': UUID('018af275-54b2-709a-
Re: [sqlalchemy] Issue DELETE statement with LIMIT
I thought we have a github for DELETE..LIMIT but we dont. This would be a construct specific to the MySQL dialect: from sqlalchemy.dialects.mysql import delete , where it would include order_by() and limit() params.We don't have internal resources to carry this through so we'd rely upon high quality pull requests with tests, once the issue is created. for now I would suggest using text() for the case that an application needs this extremely unusual construct once in awhile. On Fri, Sep 22, 2023, at 7:16 AM, 'Grennith' via sqlalchemy wrote: > Hi everyone, > I'd like to issue a LIMIT for a DELETE statement. > By default, this is not possible as far as I can see it. The function limit() > is available for SELECT in general however. > Searching through documentation, I found a reference to with_dialect_option(): > https://docs.sqlalchemy.org/en/20/search.html?q=with_dialect_options_keywords=yes=default# > Which points to > https://docs.sqlalchemy.org/en/20/core/dml.html#sqlalchemy.sql.expression.UpdateBase.with_dialect_options > claiming the function to be available in UpdateBase (although the > documentation off given the claimed method is not callable like documented). > This was the case in 1.4 > (https://github.com/sqlalchemy/sqlalchemy/blob/rel_1_4/lib/sqlalchemy/sql/dml.py#L345) > already and also in 2.0 > (https://github.com/sqlalchemy/sqlalchemy/blob/main/lib/sqlalchemy/sql/dml.py#L438). > > However, trying to call it as per documentation results in an exception being > raised: > ``` > sqlalchemy.exc.ArgumentError: Argument 'mysql_limit' is not accepted by > dialect 'mysql' on behalf of > ``` > This is caused by > https://github.com/sqlalchemy/sqlalchemy/blob/main/lib/sqlalchemy/dialects/mysql/base.py#L2454 > not listing sql.Delete explicitly. UpdateBase apparently cannot be > referenced either given the import (guessing as it's not imported explicitly > in > https://github.com/sqlalchemy/sqlalchemy/blob/main/lib/sqlalchemy/sql/__init__.py > or not referenced another way?). > However, by adding Delete just like Update will have the following line run > fine without an error - but not adding the LIMIT either. My best guess right > now would be due to the lack of limit clause handling? > ``` > stmt = stmt.with_dialect_options(mysql_limit=limit, mariadb_limit=limit) > ``` > where `limit` simply is an integer. > > > Any hints or help is appreciated. I can also raise a ticket on Github :) > > Best regards > > > > > -- > SQLAlchemy - > The Python SQL Toolkit and Object Relational Mapper > > http://www.sqlalchemy.org/ > > To post example code, please provide an MCVE: Minimal, Complete, and > Verifiable Example. See http://stackoverflow.com/help/mcve for a full > description. > --- > You received this message because you are subscribed to the Google Groups > "sqlalchemy" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to sqlalchemy+unsubscr...@googlegroups.com. > To view this discussion on the web visit > https://groups.google.com/d/msgid/sqlalchemy/f13a8ca6-3e52-4287-a6a4-52b5b4672470n%40googlegroups.com > > <https://groups.google.com/d/msgid/sqlalchemy/f13a8ca6-3e52-4287-a6a4-52b5b4672470n%40googlegroups.com?utm_medium=email_source=footer>. -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/ae24d467-9750-496a-a3b7-1da85afc70f2%40app.fastmail.com.
Re: [sqlalchemy] Issue DELETE statement with LIMIT
Hi. Can you do a sub query with the ones you want to delete selected (with limit) and then delete with an IN clause on the sub query items?Warwick A. PrinceMushroom Systems International Pty. Ltd.On 22 Sep 2023, at 9:16 pm, 'Grennith' via sqlalchemy wrote:Hi everyone,I'd like to issue a LIMIT for a DELETE statement.By default, this is not possible as far as I can see it. The function limit() is available for SELECT in general however. Searching through documentation, I found a reference to with_dialect_option():https://docs.sqlalchemy.org/en/20/search.html?q=with_dialect_options_keywords=yes=default#Which points to https://docs.sqlalchemy.org/en/20/core/dml.html#sqlalchemy.sql._expression_.UpdateBase.with_dialect_options claiming the function to be available in UpdateBase (although the documentation off given the claimed method is not callable like documented). This was the case in 1.4 (https://github.com/sqlalchemy/sqlalchemy/blob/rel_1_4/lib/sqlalchemy/sql/dml.py#L345) already and also in 2.0 (https://github.com/sqlalchemy/sqlalchemy/blob/main/lib/sqlalchemy/sql/dml.py#L438).However, trying to call it as per documentation results in an exception being raised:```sqlalchemy.exc.ArgumentError: Argument 'mysql_limit' is not accepted by dialect 'mysql' on behalf of ```This is caused by https://github.com/sqlalchemy/sqlalchemy/blob/main/lib/sqlalchemy/dialects/mysql/base.py#L2454 not listing sql.Delete explicitly. UpdateBase apparently cannot be referenced either given the import (guessing as it's not imported explicitly in https://github.com/sqlalchemy/sqlalchemy/blob/main/lib/sqlalchemy/sql/__init__.py or not referenced another way?).However, by adding Delete just like Update will have the following line run fine without an error - but not adding the LIMIT either. My best guess right now would be due to the lack of limit clause handling?```stmt = stmt.with_dialect_options(mysql_limit=limit, mariadb_limit=limit)```where `limit` simply is an integer.Any hints or help is appreciated. I can also raise a ticket on Github :)Best regards -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/f13a8ca6-3e52-4287-a6a4-52b5b4672470n%40googlegroups.com. -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/978052A5-E996-4839-8DA2-50009A6384AE%40mushroomsys.com.
[sqlalchemy] Issue DELETE statement with LIMIT
Hi everyone, I'd like to issue a LIMIT for a DELETE statement. By default, this is not possible as far as I can see it. The function limit() is available for SELECT in general however. Searching through documentation, I found a reference to with_dialect_option(): https://docs.sqlalchemy.org/en/20/search.html?q=with_dialect_options_keywords=yes=default# Which points to https://docs.sqlalchemy.org/en/20/core/dml.html#sqlalchemy.sql.expression.UpdateBase.with_dialect_options claiming the function to be available in UpdateBase (although the documentation off given the claimed method is not callable like documented). This was the case in 1.4 (https://github.com/sqlalchemy/sqlalchemy/blob/rel_1_4/lib/sqlalchemy/sql/dml.py#L345) already and also in 2.0 (https://github.com/sqlalchemy/sqlalchemy/blob/main/lib/sqlalchemy/sql/dml.py#L438). However, trying to call it as per documentation results in an exception being raised: ``` sqlalchemy.exc.ArgumentError: Argument 'mysql_limit' is not accepted by dialect 'mysql' on behalf of ``` This is caused by https://github.com/sqlalchemy/sqlalchemy/blob/main/lib/sqlalchemy/dialects/mysql/base.py#L2454 not listing sql.Delete explicitly. UpdateBase apparently cannot be referenced either given the import (guessing as it's not imported explicitly in https://github.com/sqlalchemy/sqlalchemy/blob/main/lib/sqlalchemy/sql/__init__.py or not referenced another way?). However, by adding Delete just like Update will have the following line run fine without an error - but not adding the LIMIT either. My best guess right now would be due to the lack of limit clause handling? ``` stmt = stmt.with_dialect_options(mysql_limit=limit, mariadb_limit=limit) ``` where `limit` simply is an integer. Any hints or help is appreciated. I can also raise a ticket on Github :) Best regards -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/f13a8ca6-3e52-4287-a6a4-52b5b4672470n%40googlegroups.com.
[sqlalchemy] Re: Duplicate entry '0' for key 'PRIMARY'
Hi All! Crisis reverted, turned out my database column didn't have the autoincerement flag. Sorry for the topic. Martin Parrag a következőt írta (2023. szeptember 21., csütörtök, 16:53:14 UTC+2): > Hi Guys! > > I have ORMs with autoincrement primary keys, and I'd like to achive a > multiple insert with sqlalchemy. > I'm making a lot of objects and adding them to the session, and after I'm > done, I'd like to make session.commit() but then I get this error: > (MySQLdb.IntegrityError) (1062, "Duplicate entry '0' for key 'PRIMARY'"). > > Some example code. > > class Base(DeclarativeBase): > pass > > class Partner(Base): > __tablename__ = 'partner' > > id: Mapped[int] = mapped_column(Integer, primary_key=True, > autoincrement=True) > name: Mapped[Optional[str]] = mapped_column(String(255, > collation='utf8mb4_unicode_ci'), nullable=True, default=None) > address: Mapped[Optional[str]] = mapped_column(String(255, > collation='utf8mb4_unicode_ci'), nullable=True, default=None) > > class ImportHandler: > > def __init__(self, db_name: str): > plain_engine = create_engine(os.getenv('db_connection') + db_name + > '?charset=utf8mb4', echo='debug') > self.session = Session(plain_engine) > > def import(self): > > for i in range(10): > > partner = Partner() > partner.name = "Some" > partner.address = "Test" > self.session.add(partner) > > self.session.commit() > > Can anybody explain that how can I solve this? > Thank you very much! > -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/ce862ff5-be17-4886-ad8e-49ad51a9dc05n%40googlegroups.com.
[sqlalchemy] Duplicate entry '0' for key 'PRIMARY'
Hi Guys! I have ORMs with autoincrement primary keys, and I'd like to achive a multiple insert with sqlalchemy. I'm making a lot of objects and adding them to the session, and after I'm done, I'd like to make session.commit() but then I get this error: (MySQLdb.IntegrityError) (1062, "Duplicate entry '0' for key 'PRIMARY'"). Some example code. class Base(DeclarativeBase): pass class Partner(Base): __tablename__ = 'partner' id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True) name: Mapped[Optional[str]] = mapped_column(String(255, collation='utf8mb4_unicode_ci'), nullable=True, default=None) address: Mapped[Optional[str]] = mapped_column(String(255, collation='utf8mb4_unicode_ci'), nullable=True, default=None) class ImportHandler: def __init__(self, db_name: str): plain_engine = create_engine(os.getenv('db_connection') + db_name + '?charset=utf8mb4', echo='debug') self.session = Session(plain_engine) def import(self): for i in range(10): partner = Partner() partner.name = "Some" partner.address = "Test" self.session.add(partner) self.session.commit() Can anybody explain that how can I solve this? Thank you very much! -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/e9b04c7e-d402-4025-81c2-62a0f73e2dcbn%40googlegroups.com.
Re: [sqlalchemy] Event: do_orm_execute inserted value
Thank you. środa, 20 września 2023 o 15:54:42 UTC+2 Mike Bayer napisał(a): > for a statement like that where the values are embedded in the insert() > construct directly you would use: > > orm_execute_state.statement.compile().params > > this is mentioned in the tutorial at > https://docs.sqlalchemy.org/en/20/tutorial/data_insert.html#the-insert-sql-expression-construct > > > otherwise if parameters are sent separately, they are in > orm_execute_state.parameters > > > > On Wed, Sep 20, 2023, at 8:37 AM, Tomas Pavlovsky wrote: > > Hi Mike, > > how to access inserted value in do_orm_execute? > Event "before_insert" has "target" parameter, but how to do it in > do_orm_execute? > session.execute(insert(User).values(name="name")) > I need to access name value but don't know how? > Thanks > > > > -- > SQLAlchemy - > The Python SQL Toolkit and Object Relational Mapper > > http://www.sqlalchemy.org/ > > To post example code, please provide an MCVE: Minimal, Complete, and > Verifiable Example. See http://stackoverflow.com/help/mcve for a full > description. > --- > You received this message because you are subscribed to the Google Groups > "sqlalchemy" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to sqlalchemy+...@googlegroups.com. > To view this discussion on the web visit > https://groups.google.com/d/msgid/sqlalchemy/9bea7c27-f67b-4d87-ab5e-71ece8c1dd46n%40googlegroups.com > > <https://groups.google.com/d/msgid/sqlalchemy/9bea7c27-f67b-4d87-ab5e-71ece8c1dd46n%40googlegroups.com?utm_medium=email_source=footer> > . > > > -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/fb85ca42-0a48-4aba-814e-d392f11a12b0n%40googlegroups.com.
Re: [sqlalchemy] Event: do_orm_execute inserted value
for a statement like that where the values are embedded in the insert() construct directly you would use: orm_execute_state.statement.compile().params this is mentioned in the tutorial at https://docs.sqlalchemy.org/en/20/tutorial/data_insert.html#the-insert-sql-expression-construct otherwise if parameters are sent separately, they are in orm_execute_state.parameters On Wed, Sep 20, 2023, at 8:37 AM, Tomas Pavlovsky wrote: > Hi Mike, > > how to access inserted value in do_orm_execute? > Event "before_insert" has "target" parameter, but how to do it in > do_orm_execute? > session.execute(insert(User).values(name="name")) > I need to access name value but don't know how? > Thanks > > > > > -- > SQLAlchemy - > The Python SQL Toolkit and Object Relational Mapper > > http://www.sqlalchemy.org/ > > To post example code, please provide an MCVE: Minimal, Complete, and > Verifiable Example. See http://stackoverflow.com/help/mcve for a full > description. > --- > You received this message because you are subscribed to the Google Groups > "sqlalchemy" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to sqlalchemy+unsubscr...@googlegroups.com. > To view this discussion on the web visit > https://groups.google.com/d/msgid/sqlalchemy/9bea7c27-f67b-4d87-ab5e-71ece8c1dd46n%40googlegroups.com > > <https://groups.google.com/d/msgid/sqlalchemy/9bea7c27-f67b-4d87-ab5e-71ece8c1dd46n%40googlegroups.com?utm_medium=email_source=footer>. -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/7aa3f480-6266-437d-aab6-d2e1c3413f79%40app.fastmail.com.
[sqlalchemy] Event: do_orm_execute inserted value
Hi Mike, how to access inserted value in do_orm_execute? Event "before_insert" has "target" parameter, but how to do it in do_orm_execute? session.execute(insert(User).values(name="name")) I need to access name value but don't know how? Thanks -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/9bea7c27-f67b-4d87-ab5e-71ece8c1dd46n%40googlegroups.com.
Re: [sqlalchemy] Temporarily disable/intercept ORM events on mutation
On Fri, Sep 15, 2023, at 8:59 PM, Mike Bayer wrote: > > unfortunately no, that's a backref event handler, that's within the class > instrumentation and has no mechanism to be disabled on a per-class basis, not > to mention the backref handler is not the only aspect of things that expects > a certain kind of value to be present. Marshmallow should have alternate > APIs that allow the attributes in question to be named by their string name > somewhere, rather than being assigned some out-of-band object; that's not > very good design in today's pep-484 typed Python. sorry, I meant "no mechanism to be disabled on a per-instance basis". > > > > > >> >> >> -- >> SQLAlchemy - >> The Python SQL Toolkit and Object Relational Mapper >> >> http://www.sqlalchemy.org/ >> >> To post example code, please provide an MCVE: Minimal, Complete, and >> Verifiable Example. See http://stackoverflow.com/help/mcve for a full >> description. >> --- >> You received this message because you are subscribed to the Google Groups >> "sqlalchemy" group. >> To unsubscribe from this group and stop receiving emails from it, send an >> email to sqlalchemy+unsubscr...@googlegroups.com. >> To view this discussion on the web visit >> https://groups.google.com/d/msgid/sqlalchemy/34ee3121-e284-4fcb-9c1d-6191557e89bcn%40googlegroups.com >> >> <https://groups.google.com/d/msgid/sqlalchemy/34ee3121-e284-4fcb-9c1d-6191557e89bcn%40googlegroups.com?utm_medium=email_source=footer>. > -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/0183d49d-e442-4512-bf62-8adae2c0e903%40app.fastmail.com.
Re: [sqlalchemy] Temporarily disable/intercept ORM events on mutation
On Fri, Sep 15, 2023, at 4:28 PM, 'Luna Lucadou' via sqlalchemy wrote: > When customers call our JSON:API API, they can use an "include" parameter to > specify related objects to be appended to the response. > > However, requests to include are not always satisfiable (e.g. if > job.supervisor=null, include=supervisor is ignored). > In order to prevent Marshmallow from trying to load nonexistent related > objects to append to our API responses, we need to tell it when to ignore a > relationship attribute, such as via setting > job.supervisor=marshmallow.missing (if it sees job.supervisor=None, it will > attempt (and fail) to load the null supervisor object, so we cannot just > leave it as-is). > > Unfortunately, this causes problems as SQLAlchemy attempts to handle the new > value: > > Error Traceback (most recent call last): File > "/Users/lucadou/IdeaProjects/person-api/api/unit_tests/test_person_service.py", > line 601, in test_get_people_include_job response = > self.person_service.get_people(QueryParameters({"include": "jobs"})) > File > "/Users/lucadou/IdeaProjects/person-api/api/src/person_service.py", line 61, > in get_people response = person_schema.dump(people, many=True) > ^ File > "/Users/lucadou/IdeaProjects/person-api/api/venv/lib/python3.11/site-packages/marshmallow/schema.py", > line 557, in dump result = self._serialize(processed_obj, many=many) > ^ File > "/Users/lucadou/IdeaProjects/person-api/api/venv/lib/python3.11/site-packages/marshmallow/schema.py", > line 519, in _serialize return [ ^ File > "/Users/lucadou/IdeaProjects/person-api/api/venv/lib/python3.11/site-packages/marshmallow/schema.py", > line 520, in self._serialize(d, many=False) File > "/Users/lucadou/IdeaProjects/person-api/api/venv/lib/python3.11/site-packages/marshmallow/schema.py", > line 525, in _serialize value = field_obj.serialize(attr_name, obj, > accessor=self.get_attribute) > File > "/Users/lucadou/IdeaProjects/person-api/api/venv/lib/python3.11/site-packages/marshmallow_jsonapi/fields.py", > line 248, in serialize return super().serialize(attr, obj, accessor) > ^^ File > "/Users/lucadou/IdeaProjects/person-api/api/venv/lib/python3.11/site-packages/marshmallow/fields.py", > line 344, in serialize return self._serialize(value, attr, obj, **kwargs) > ^^^ File > "/Users/lucadou/IdeaProjects/person-api/api/venv/lib/python3.11/site-packages/marshmallow_jsonapi/fields.py", > line 274, in _serialize self._serialize_included(item) File > "/Users/lucadou/IdeaProjects/person-api/api/venv/lib/python3.11/site-packages/marshmallow_jsonapi/fields.py", > line 280, in _serialize_included result = self.schema.dump(value) > ^^^ File > "/Users/lucadou/IdeaProjects/person-api/api/venv/lib/python3.11/site-packages/marshmallow/schema.py", > line 551, in dump processed_obj = self._invoke_dump_processors( > ^ File > "/Users/lucadou/IdeaProjects/person-api/api/venv/lib/python3.11/site-packages/marshmallow/schema.py", > line 1068, in _invoke_dump_processors data = self._invoke_processors( > File > "/Users/lucadou/IdeaProjects/person-api/api/venv/lib/python3.11/site-packages/marshmallow/schema.py", > line 1225, in _invoke_processors data = processor(data, many=many, **kwargs) > File > "/Users/lucadou/IdeaProjects/person-api/api/src/model/schema/job_schema.py", > line 62, in set_null_supervisor job.supervisor = missing ^^ File > "/Users/lucadou/IdeaProjects/person-api/api/venv/lib/python3.11/site-packages/sqlalchemy/orm/attributes.py", > line 536, in __set__ self.impl.set( File > "/Users/lucadou/IdeaProjects/person-api/api/venv/lib/python3.11/site-packages/sqlalchemy/orm/attributes.py", > line 1466, in set value = self.fire_replace_event(state, dict_, value, old, > initiator) File > "/Users/lucadou/IdeaProjects/person-api/api/venv/lib/python3.11/site-packages/sqlalchemy/orm/attributes.py", > line 1505, in fire_replace_event value = fn( ^^^ File > "/Users/lucadou/IdeaProjects/person-api/api/venv/lib/python3.11/site-packages/sqlalchemy/orm/attributes.py", > line 2167, in emit_backref_from_scalar_set_event instance_s
[sqlalchemy] Temporarily disable/intercept ORM events on mutation
When customers call our JSON:API API, they can use an "include" parameter to specify related objects to be appended to the response. However, requests to include are not always satisfiable (e.g. if job.supervisor=null, include=supervisor is ignored). In order to prevent Marshmallow from trying to load nonexistent related objects to append to our API responses, we need to tell it when to ignore a relationship attribute, such as via setting job.supervisor=marshmallow.missing (if it sees job.supervisor=None, it will attempt (and fail) to load the null supervisor object, so we cannot just leave it as-is). Unfortunately, this causes problems as SQLAlchemy attempts to handle the new value: Error Traceback (most recent call last): File "/Users/lucadou/IdeaProjects/person-api/api/unit_tests/test_person_service.py", line 601, in test_get_people_include_job response = self.person_service.get_people(QueryParameters({"include": "jobs"})) File "/Users/lucadou/IdeaProjects/person-api/api/src/person_service.py", line 61, in get_people response = person_schema.dump(people, many=True) ^ File "/Users/lucadou/IdeaProjects/person-api/api/venv/lib/python3.11/site-packages/marshmallow/schema.py", line 557, in dump result = self._serialize(processed_obj, many=many) ^ File "/Users/lucadou/IdeaProjects/person-api/api/venv/lib/python3.11/site-packages/marshmallow/schema.py", line 519, in _serialize return [ ^ File "/Users/lucadou/IdeaProjects/person-api/api/venv/lib/python3.11/site-packages/marshmallow/schema.py", line 520, in self._serialize(d, many=False) File "/Users/lucadou/IdeaProjects/person-api/api/venv/lib/python3.11/site-packages/marshmallow/schema.py", line 525, in _serialize value = field_obj.serialize(attr_name, obj, accessor=self.get_attribute) File "/Users/lucadou/IdeaProjects/person-api/api/venv/lib/python3.11/site-packages/marshmallow_jsonapi/fields.py", line 248, in serialize return super().serialize(attr, obj, accessor) ^^ File "/Users/lucadou/IdeaProjects/person-api/api/venv/lib/python3.11/site-packages/marshmallow/fields.py", line 344, in serialize return self._serialize(value, attr, obj, **kwargs) ^^^ File "/Users/lucadou/IdeaProjects/person-api/api/venv/lib/python3.11/site-packages/marshmallow_jsonapi/fields.py", line 274, in _serialize self._serialize_included(item) File "/Users/lucadou/IdeaProjects/person-api/api/venv/lib/python3.11/site-packages/marshmallow_jsonapi/fields.py", line 280, in _serialize_included result = self.schema.dump(value) ^^^ File "/Users/lucadou/IdeaProjects/person-api/api/venv/lib/python3.11/site-packages/marshmallow/schema.py", line 551, in dump processed_obj = self._invoke_dump_processors( ^ File "/Users/lucadou/IdeaProjects/person-api/api/venv/lib/python3.11/site-packages/marshmallow/schema.py", line 1068, in _invoke_dump_processors data = self._invoke_processors( File "/Users/lucadou/IdeaProjects/person-api/api/venv/lib/python3.11/site-packages/marshmallow/schema.py", line 1225, in _invoke_processors data = processor(data, many=many, **kwargs) File "/Users/lucadou/IdeaProjects/person-api/api/src/model/schema/job_schema.py", line 62, in set_null_supervisor job.supervisor = missing ^^ File "/Users/lucadou/IdeaProjects/person-api/api/venv/lib/python3.11/site-packages/sqlalchemy/orm/attributes.py", line 536, in __set__ self.impl.set( File "/Users/lucadou/IdeaProjects/person-api/api/venv/lib/python3.11/site-packages/sqlalchemy/orm/attributes.py", line 1466, in set value = self.fire_replace_event(state, dict_, value, old, initiator) File "/Users/lucadou/IdeaProjects/person-api/api/venv/lib/python3.11/site-packages/sqlalchemy/orm/attributes.py", line 1505, in fire_replace_event value = fn( ^^^ File "/Users/lucadou/IdeaProjects/person-api/api/venv/lib/python3.11/site-packages/sqlalchemy/orm/attributes.py", line 2167, in emit_backref_from_scalar_set_event instance_state(child), ^ AttributeError: '_Missing' object has no attribute '_sa_instance_state' Is there any way to temporarily disable ORM event listeners when we mutate objects and have no intention of saving the changes/do not intend for the ORM to act on them? -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To
Re: [sqlalchemy] How to combine statement eager loading with polymorphic relations
the recursion_depth feature on selectinload() is also very new and that is actually a very complex and not very mature feature.If you only wanted to apply additional options for N levels deep, you would build out separate options for that, like: options( selectinload(Model.thing, recursion_depth=-1), defaultload(Model.thing).selectinload(Model.otherthing).selectinload(Model.otherthing) ) something like that again, fairly esoteric stuff On Fri, Sep 15, 2023, at 4:25 AM, Cornelis Poppema wrote: > Hello Mike, thank you very much for the in-depth reply and providing a > solution :) > > There is no specific reason that I posted in google groups, I did not visit > the support page, this was just something I decided after thinking where to > post first between googlegroups and stackoverflow, I will use github > discussions when I open a new discussion in the future! > Your workaround will help me continue so many many thanks. I thought I tried > all variations, but I can only concede after seeing this work that I did not > attempt adding the selectinload to the root options(). > > It might warrant a new thread, but can you also tell me if there is a way to > control the options() that sqlalchemy uses for the recursion of next_step ? > > Ie. I included this bit in the original post: > ``` > .options( > selectinload(StepModel.next_step, recursion_depth=-1), > ... > ) > ``` > > and it would be helpful to know if I can chain the same options to next_step, > so that step also has its actions and their relationships() eagerly available > etc. > > PS > FWIW the reason I included `raiseload("*")` in options() is because I am > running async queries, and personally the error I will be confronted with > trying to access lazy attributes is more helpful, so I've come to add it by > default. Without raisedload(*) I would see: > ``` > sqlalchemy.exc.MissingGreenlet: greenlet_spawn has not been called; can't > call await_only() here. Was IO attempted in an unexpected place? (Background > on this error at: https://sqlalche.me/e/20/xd2s) > ``` > > With the help of raisedload(*) I get to see: > ``` > sqlalchemy.exc.InvalidRequestError: 'ServiceActionModel.service' is not > available due to lazy='raise``` > ``` > > This helps me tackle those cases more easily one-by-one. > > On Thursday, 14 September 2023 at 15:30:23 UTC+2 Mike Bayer wrote: >> __ >> >> >> On Thu, Sep 14, 2023, at 7:36 AM, Cornelis Poppema wrote: >>> Hi all, >>> >>> I am new to sqlalchemy, I think the idea of what I am trying to achieve is >>> relatively simple, but I can't seem to figure out how to retrieve >>> `.service` in the same query. I failed to find an example in the 2.0 >>> documentation for exactly this. >>> >>> My attempts have been to simply chain a .selectinload after the >>> .selectin_polymorphic, ie.: >>> >>> ```python >>> .options( >>> selectinload(StepModel.next_step, recursion_depth=-1), >>> selectinload(StepModel.actionbases).selectin_polymorphic( >>> [ >>> ServiceActionModel, >>> ], >>> ) >>> .selectinload(ServiceActionModel.service), >>> raiseload("*"), >>> ) >>> ``` >>> >>> This gives the error: >>> >>> ``` >>> /usr/local/lib/python3.11/site-packages/sqlalchemy/orm/strategy_options.py:2442: >>> in _raise_for_does_not_link >>> raise sa_exc.ArgumentError( >>> E sqlalchemy.exc.ArgumentError: ORM mapped entity or attribute >>> "ServiceActionModel.service" does not link from relationship >>> "StepModel.actionbases". Did you mean to use >>> "StepModel.actionbases.of_type(ServiceActionModel)"? >>> ``` >>> >> >> Hi - >> >> A few up front things, is it possible you can post these questions that have >> a lot of code on github discussions? That's at >> https://github.com/sqlalchemy/sqlalchemy/discussions .I'm sort of >> wondering how new users are still arriving here at the mailing list, did you >> find this list via the support page at >> https://www.sqlalchemy.org/support.html ? I would want to change the >> verbiage there to please refer people to GH discussions instead. >> Especially with these advanced inheritance eager loading problems, which in >> the majority of cases end up being real bugs in SQLAlchemy, as seems to be >> the c
Re: [sqlalchemy] How to combine statement eager loading with polymorphic relations
Hello Mike, thank you very much for the in-depth reply and providing a solution :) There is no specific reason that I posted in google groups, I did not visit the support page, this was just something I decided after thinking where to post first between googlegroups and stackoverflow, I will use github discussions when I open a new discussion in the future! Your workaround will help me continue so many many thanks. I thought I tried all variations, but I can only concede after seeing this work that I did not attempt adding the selectinload to the root options(). It might warrant a new thread, but can you also tell me if there is a way to control the options() that sqlalchemy uses for the recursion of next_step ? Ie. I included this bit in the original post: ``` .options( selectinload(StepModel.next_step, recursion_depth=-1), ... ) ``` and it would be helpful to know if I can chain the same options to next_step, so that step also has its actions and their relationships() eagerly available etc. PS FWIW the reason I included `raiseload("*")` in options() is because I am running async queries, and personally the error I will be confronted with trying to access lazy attributes is more helpful, so I've come to add it by default. Without raisedload(*) I would see: ``` sqlalchemy.exc.MissingGreenlet: greenlet_spawn has not been called; can't call await_only() here. Was IO attempted in an unexpected place? (Background on this error at: https://sqlalche.me/e/20/xd2s) ``` With the help of raisedload(*) I get to see: ``` sqlalchemy.exc.InvalidRequestError: 'ServiceActionModel.service' is not available due to lazy='raise``` ``` This helps me tackle those cases more easily one-by-one. On Thursday, 14 September 2023 at 15:30:23 UTC+2 Mike Bayer wrote: > > > On Thu, Sep 14, 2023, at 7:36 AM, Cornelis Poppema wrote: > > Hi all, > > > I am new to sqlalchemy, I think the idea of what I am trying to achieve is > relatively simple, but I can't seem to figure out how to retrieve > `.service` in the same query. I failed to find an example in the 2.0 > documentation for exactly this. > > My attempts have been to simply chain a .selectinload after the > .selectin_polymorphic, ie.: > > ```python > .options( > selectinload(StepModel.next_step, recursion_depth=-1), > selectinload(StepModel.actionbases).selectin_polymorphic( > [ > ServiceActionModel, > ], > ) > .selectinload(ServiceActionModel.service), > raiseload("*"), > ) > ``` > > This gives the error: > > ``` > /usr/local/lib/python3.11/site-packages/sqlalchemy/orm/strategy_options.py:2442: > > in _raise_for_does_not_link > raise sa_exc.ArgumentError( > E sqlalchemy.exc.ArgumentError: ORM mapped entity or attribute > "ServiceActionModel.service" does not link from relationship > "StepModel.actionbases". Did you mean to use > "StepModel.actionbases.of_type(ServiceActionModel)"? > ``` > > > Hi - > > A few up front things, is it possible you can post these questions that > have a lot of code on github discussions? That's at > https://github.com/sqlalchemy/sqlalchemy/discussions .I'm sort of > wondering how new users are still arriving here at the mailing list, did > you find this list via the support page at > https://www.sqlalchemy.org/support.html ? I would want to change the > verbiage there to please refer people to GH discussions instead. > Especially with these advanced inheritance eager loading problems, which in > the majority of cases end up being real bugs in SQLAlchemy, as seems to be > the case here (at least, there is an inconsistency in the API that somehow > needs to be documented, or something). > > As for the question, first off this is really advanced usage and I've > hardly ever seen people using selectin_polymorphic(), much less deep within > a chain of loaders like this. > > The correct form for this load would follow from how it's described at > https://docs.sqlalchemy.org/en/20/orm/queryguide/inheritance.html#combining-additional-loader-options-with-selectin-polymorphic-subclass-loads > > , where the ORM allows the selectin_polymorphic(Target, [TargetSubclassA]) > to be a sibling to the appropriate relationship load, > selectinload(TargetSubclassA.elements). The example there places both of > these options comma-separated within select().options().This is the > "inconsistent" part because I'm already surprised the ORM is allowing the > selectinload() to be present against TargetSubclassA when that's not one of > the primary entities in the select(). > > However in your case
Re: [sqlalchemy] How to combine statement eager loading with polymorphic relations
working on that issue but you should also be able to do this right now: .options( selectinload(StepModel.actionbases.of_type(ServiceActionModel)).selectinload(ServiceActionModel.service), raiseload("*"), ) that produces more of a LEFT OUTER JOIN with a subquery situation but still "works" On Thu, Sep 14, 2023, at 7:36 AM, Cornelis Poppema wrote: > Hi all, > > I am struggling to combine a joinedload (or selectinload, whatever works) > with the submodels of selectin_polymorphic. > > I have a model "step" that has a collections of "actions" that are relevant > when my application reaches that step. These actions can be anything and also > have their own relationships to other models that I want to eagerly load, all > while querying "step". I would strongly prefer to achieve this in a query > statement over defining eager loading in the relationship declarations on the > models itself. > > Here are my models: > > ```python > from enum import StrEnum, auto > from sqlalchemy import Column, Enum, ForeignKey, Integer, String > from sqlalchemy.dialects.postgresql import UUID > from sqlalchemy.orm import as_declarative, declared_attr, relationship > > > class ActionTypeEnum(StrEnum): > flow = auto() > service = auto() > transition = auto() > > > @as_declarative() > class BaseSqlModel: > pk = Column(Integer, primary_key=True, index=True) > > > class IdColumnMixin: > @declared_attr > def id(cls): > return Column(UUID(as_uuid=True), unique=True, nullable=False, > index=True) > > > class StepModel(IdColumnMixin, BaseSqlModel): > __tablename__ = "step" > next_step_id = Column(ForeignKey("step.id", use_alter=True)) > next_step = relationship("StepModel", remote_side="StepModel.id") > > actionbases = relationship("ActionBaseModel") > > > class ActionBaseModel(IdColumnMixin, BaseSqlModel): > __tablename__ = "actionbase" > action_type = Column(Enum(ActionTypeEnum), nullable=False) > step_id = Column(ForeignKey("step.id"), nullable=False) > step = relationship("StepModel", back_populates="actionbases") > > __mapper_args__ = { > "polymorphic_identity": "actionbase", > "polymorphic_on": "action_type", > } > > > class ServiceModel(IdColumnMixin, BaseSqlModel): > __tablename__ = "service" > name = Column(String(200), nullable=False) > > > class ServiceActionModel(ActionBaseModel): > __tablename__ = "serviceaction" > id = Column(ForeignKey("actionbase.id"), primary_key=True) > service_id = Column(ForeignKey("service.id"), nullable=True) > service = relationship("ServiceModel") > > __mapper_args__ = { > "polymorphic_identity": ActionTypeEnum.service, > } > ``` > > To query step I write this: > > ```python > db_step = ( > await self.session.execute( > select(StepModel) > .filter_by(id=id) > .options( > selectinload(StepModel.next_step, recursion_depth=-1), > selectinload(StepModel.actionbases).selectin_polymorphic( > [ > ServiceActionModel, > ], > ), > raiseload("*"), > ) > ) > ).scalar_one() > ``` > > Accessing `db_step.actionbases[0]` works as expected: it is of type > ServiceActionModel, accessing `db_step.actionbases[0].service.name` throws > the expected error: > ``` > /usr/local/lib/python3.11/site-packages/sqlalchemy/orm/strategies.py:862: in > _invoke_raise_load > raise sa_exc.InvalidRequestError( > E sqlalchemy.exc.InvalidRequestError: 'ServiceActionModel.service' is not > available due to lazy='raise' > ``` > > I am new to sqlalchemy, I think the idea of what I am trying to achieve is > relatively simple, but I can't seem to figure out how to retrieve `.service` > in the same query. I failed to find an example in the 2.0 documentation for > exactly this. > > My attempts have been to simply chain a .selectinload after the > .selectin_polymorphic, ie.: > > ```python > .options( > selectinload(StepModel.next_step, recursion_depth=-1), > selectinload(StepModel.actionbases).selectin_polymorphic( > [ > ServiceActionModel, > ], > ) > .selectinload(ServiceActionModel.service), >
Re: [sqlalchemy] sqlalchemy.orm.exc.FlushError on subclass
Thanks. We went with the helper class route, and it seems to be working much better than attempting to use inheritance in a manner that seems unsupported. On Wednesday, September 6, 2023 at 1:24:04 PM UTC-5 Mike Bayer wrote: > if you can't correct this model to apply the persistence details to the > concrete class you wish to persist and query, then you'd do the suggested > "enable_typechecks=False". There is no attribute in SQLAlchemy named > "meta" and no stack trace is given here so I dont know to what that refers. > > Overall I'm not sure how this API_Person class is useful because you can't > query for them. I would think that if you cant change the original > model then you'd have this API_Person as a series of helper functions that > accept a Person as their argument. > > > > On Wed, Sep 6, 2023, at 1:56 PM, 'Luna Lucadou' via sqlalchemy wrote: > > The project I am working on is split up into several modules. Previously, > each module had its own ORM classes. > However, due to several bugs arising from forgetting to update each > module's ORM classes in lock step when adding new functionality, we have > decided it would be best to extract the ORM classes which interact with our > DB into their own module and make that available to the other modules via > pip. > > One of these modules, which monitors for changes in an upstream DB and > applies them to ours, has some methods which are not present in the other > modules and which cannot be easily extracted out due to its dependencies on > upstream DB functionality. > > As such, in this module, we must subclass the ORM models which interact > with our DB: > > models.apimodels.db.person.py: > #... > @dataclass(init=False, eq=True, unsafe_hash=True) > class Person(Base): > __tablename__ = "person" > > id: Mapped[int] = mapped_column(primary_key=True) > first_name: Mapped[str] > last_name: Mapped[str] > email_address: Mapped[str] > office_address: Mapped[str] > office_phone_number: Mapped[str] > > # ... > > etl.models.api_db.api_person.py: > #... > from apimodels.db.person import Person as PersonBase > # ... > class API_Person(PersonBase): > __tablename__ = "person" > __table_args__ = {"keep_existing": True} > > def get_pvi(self): > # ... > > def get_historical_pvis(self) -> list[str]: > # ... > > def __eq__(self): > # ... > > def __hash__(self): > # ... > > @staticmethod > def from_upstream_hub_person( > uh_person: Optional[UH_Person], > ) -> Optional["API_Person"]: > # ... > > Of note is that this subclass does not add any new attributes or modify > existing ones, it merely adds some helper methods related to identifying > primary key changes in the upstream DB. (This is also why we override the > eq and hash methods provided by dataclasses - incoming changesets have to > be matched against existing records, even when primary keys change > upstream.) > > This is effectively single-table inheritance, but it is not a good fit for > polymorphic_identity since it is not a distinct class, merely adding > module-specific helper methods, and if I am reading the documentation > correctly, using polymorphic_identity would mean any records touched by > the API_Person subclass (which is all of them) would no longer be usable > by other modules, which do not extend any of the models. > > From what I have read, it seems like the keep_existing param should be of > use here, but neither it nor extend_existing set to True help with the > errors I am seeing when attempting to interact with this subclass in any > way: > > sqlalchemy.orm.exc.FlushError: Attempting to flush an item of type 'model.api_db.api_person.API_Person'> as a member of collection > "Identifier.person". Expected an object of type 'apimodels.db.person.Person'> or a polymorphic subclass of this type. If > is a subclass of 'apimodels.db.person.Person'>, configure mapper "Mapper[Person(person)]" to > load this subtype polymorphically, or set enable_typechecks=False to allow > any subtype to be accepted for flush. > > I did try setting enable_typechecks to False, but this results in a > different error when attempting to use getattr on the subclass: > > AttributeError: 'Person' object has no attribute 'meta' > > Is there a better way of doing this? > > > -- > SQLAlchemy - > The Python SQL Toolkit and Object Relational Mapper > > http://www.sqlalchemy.org/ > > To post example code, please provide an MCVE: Minimal, Comple
Re: [sqlalchemy] How to combine statement eager loading with polymorphic relations
On Thu, Sep 14, 2023, at 7:36 AM, Cornelis Poppema wrote: > Hi all, > > I am new to sqlalchemy, I think the idea of what I am trying to achieve is > relatively simple, but I can't seem to figure out how to retrieve `.service` > in the same query. I failed to find an example in the 2.0 documentation for > exactly this. > > My attempts have been to simply chain a .selectinload after the > .selectin_polymorphic, ie.: > > ```python > .options( > selectinload(StepModel.next_step, recursion_depth=-1), > selectinload(StepModel.actionbases).selectin_polymorphic( > [ > ServiceActionModel, > ], > ) > .selectinload(ServiceActionModel.service), > raiseload("*"), > ) > ``` > > This gives the error: > > ``` > /usr/local/lib/python3.11/site-packages/sqlalchemy/orm/strategy_options.py:2442: > in _raise_for_does_not_link > raise sa_exc.ArgumentError( > E sqlalchemy.exc.ArgumentError: ORM mapped entity or attribute > "ServiceActionModel.service" does not link from relationship > "StepModel.actionbases". Did you mean to use > "StepModel.actionbases.of_type(ServiceActionModel)"? > ``` Hi - A few up front things, is it possible you can post these questions that have a lot of code on github discussions? That's at https://github.com/sqlalchemy/sqlalchemy/discussions .I'm sort of wondering how new users are still arriving here at the mailing list, did you find this list via the support page at https://www.sqlalchemy.org/support.html ? I would want to change the verbiage there to please refer people to GH discussions instead.Especially with these advanced inheritance eager loading problems, which in the majority of cases end up being real bugs in SQLAlchemy, as seems to be the case here (at least, there is an inconsistency in the API that somehow needs to be documented, or something). As for the question, first off this is really advanced usage and I've hardly ever seen people using selectin_polymorphic(), much less deep within a chain of loaders like this. The correct form for this load would follow from how it's described at https://docs.sqlalchemy.org/en/20/orm/queryguide/inheritance.html#combining-additional-loader-options-with-selectin-polymorphic-subclass-loads , where the ORM allows the selectin_polymorphic(Target, [TargetSubclassA]) to be a sibling to the appropriate relationship load, selectinload(TargetSubclassA.elements). The example there places both of these options comma-separated within select().options().This is the "inconsistent" part because I'm already surprised the ORM is allowing the selectinload() to be present against TargetSubclassA when that's not one of the primary entities in the select(). However in your case, you are coming off of a parent loader option already. So following from this, the correct form based on a direct reading of those docs would, *in theory*, be: select().options( selectinload(Parent.target).options( selectin_polymorphic(Target, [TargetSubclassA]), selectinload(TargetSubclassA.elements) ) ) that is, you can build up sibling options from a parent loader option using another call to .options(). however, this doesn't work; the validation of the loader chain unsurprisingly notes that TargetSubclass is not linked from Parent.target, and they'd like you to use of_type() instead.So I've made a bug for this here: https://github.com/sqlalchemy/sqlalchemy/issues/10348 as something has to change here, either the docs, or the usage pattern for selectin_polymorphic(), or the error checks have to get a lot smarter to figure this out and let this case pass, since it works fine the way you are expecting if I just have it skip the error checking. What you can do now is use with_polymorphic() instead that is more configurable for this kind of loader chain: TT = with_polymorphic(Target, [TargetSubclassA]) select().options(selectinload(Parent.target.of_type(TT).selectinload(TT.TargetSubclassA.elements))) discussion can continue at the issue above or a new github discussion, thanks! -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/a99d9853-8936-455f-9439-bfe5f2e03faa%40app.fastmail.com.
[sqlalchemy] How to combine statement eager loading with polymorphic relations
Hi all, I am struggling to combine a joinedload (or selectinload, whatever works) with the submodels of selectin_polymorphic. I have a model "step" that has a collections of "actions" that are relevant when my application reaches that step. These actions can be anything and also have their own relationships to other models that I want to eagerly load, all while querying "step". I would strongly prefer to achieve this in a query statement over defining eager loading in the relationship declarations on the models itself. Here are my models: ```python from enum import StrEnum, auto from sqlalchemy import Column, Enum, ForeignKey, Integer, String from sqlalchemy.dialects.postgresql import UUID from sqlalchemy.orm import as_declarative, declared_attr, relationship class ActionTypeEnum(StrEnum): flow = auto() service = auto() transition = auto() @as_declarative() class BaseSqlModel: pk = Column(Integer, primary_key=True, index=True) class IdColumnMixin: @declared_attr def id(cls): return Column(UUID(as_uuid=True), unique=True, nullable=False, index=True) class StepModel(IdColumnMixin, BaseSqlModel): __tablename__ = "step" next_step_id = Column(ForeignKey("step.id", use_alter=True)) next_step = relationship("StepModel", remote_side="StepModel.id") actionbases = relationship("ActionBaseModel") class ActionBaseModel(IdColumnMixin, BaseSqlModel): __tablename__ = "actionbase" action_type = Column(Enum(ActionTypeEnum), nullable=False) step_id = Column(ForeignKey("step.id"), nullable=False) step = relationship("StepModel", back_populates="actionbases") __mapper_args__ = { "polymorphic_identity": "actionbase", "polymorphic_on": "action_type", } class ServiceModel(IdColumnMixin, BaseSqlModel): __tablename__ = "service" name = Column(String(200), nullable=False) class ServiceActionModel(ActionBaseModel): __tablename__ = "serviceaction" id = Column(ForeignKey("actionbase.id"), primary_key=True) service_id = Column(ForeignKey("service.id"), nullable=True) service = relationship("ServiceModel") __mapper_args__ = { "polymorphic_identity": ActionTypeEnum.service, } ``` To query step I write this: ```python db_step = ( await self.session.execute( select(StepModel) .filter_by(id=id) .options( selectinload(StepModel.next_step, recursion_depth=-1), selectinload(StepModel.actionbases).selectin_polymorphic( [ ServiceActionModel, ], ), raiseload("*"), ) ) ).scalar_one() ``` Accessing `db_step.actionbases[0]` works as expected: it is of type ServiceActionModel, accessing `db_step.actionbases[0].service.name` throws the expected error: ``` /usr/local/lib/python3.11/site-packages/sqlalchemy/orm/strategies.py:862: in _invoke_raise_load raise sa_exc.InvalidRequestError( E sqlalchemy.exc.InvalidRequestError: 'ServiceActionModel.service' is not available due to lazy='raise' ``` I am new to sqlalchemy, I think the idea of what I am trying to achieve is relatively simple, but I can't seem to figure out how to retrieve `.service` in the same query. I failed to find an example in the 2.0 documentation for exactly this. My attempts have been to simply chain a .selectinload after the .selectin_polymorphic, ie.: ```python .options( selectinload(StepModel.next_step, recursion_depth=-1), selectinload(StepModel.actionbases).selectin_polymorphic( [ ServiceActionModel, ], ) .selectinload(ServiceActionModel.service), raiseload("*"), ) ``` This gives the error: ``` /usr/local/lib/python3.11/site-packages/sqlalchemy/orm/strategy_options.py:2442: in _raise_for_does_not_link raise sa_exc.ArgumentError( E sqlalchemy.exc.ArgumentError: ORM mapped entity or attribute "ServiceActionModel.service" does not link from relationship "StepModel.actionbases". Did you mean to use "StepModel.actionbases.of_type(ServiceActionModel)"? ``` Which seems fair; there is no relationship defined on ServiceActionModel to StepModel. (but there is on ActionBaseModel). So I've tried part 2 of the hint in the exception, using `of_type`. Again I failed to find much about this feature in the documentation; from what I can tell it is used in combination with join on a select(poly-base-model) to be able to .where() on subclass-specific models, but besides one source that actually uses it in a joinedload() I have not find any examples. It is very
Re: [sqlalchemy] Unique constraint error in PostgrSQL when migrating with Alembic
your revisions table has a composite unique constraint - one constraint with two columns in it. therefore to refer to this constraint via foreign key, you need a single composite foreignkeyconstraint - again, one constraint that links two columns together. you would use ForeignKeyConstraint for this, not ForeignKey, see ForeignKeyConstraint in https://docs.sqlalchemy.org/en/20/core/constraints.html#defining-foreign-keys . On Wed, Sep 13, 2023, at 1:43 PM, Lord Wolfenstein wrote: > I have a database that looks like this that I create with Alembic. The > relationships are trivial except between Revision and ObjectCount, there it > used two foreign keys > aaa.png > > The code looks like this > > > > from datetime import datetime > from typing import Optional > > from sqlalchemy import ForeignKey, create_engine, UniqueConstraint > from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, > relationship, sessionmaker # type: ignore > > > class Base(DeclarativeBase): > pass > > > class Blueprint(Base): > __tablename__ = "blueprints" > > blueprint_id: Mapped[int] = mapped_column(primary_key=True) > filename: Mapped[str] > created: Mapped[datetime] = mapped_column(default=datetime.utcnow) > > revisions: Mapped[list["Revision"]] = > relationship(back_populates="blueprint") # type: ignore > > def get_new_revision_number(self) -> int: > if not self.revisions: > return 1 > return max(revision.revision_number for revision in self.revisions) + > 1 > > def __str__(self): > return f"{self.filename} : {self.blueprint_id}" > > > class Revision(Base): > __tablename__ = "revisions" > __table_args__ = ( > UniqueConstraint("blueprint_id", "revision_number", > name="revision_blueprint_revision_number"), > ) > > blueprint_id: Mapped[int] = > mapped_column(ForeignKey("blueprints.blueprint_id"), primary_key=True) > revision_number: Mapped[int] = mapped_column(primary_key=True) > date: Mapped[datetime] = mapped_column(default=datetime.utcnow) > savedata: Mapped[str] > > blueprint: Mapped["Blueprint"] = relationship(back_populates="revisions") > # type: ignore > object_count: Mapped[Optional[list["ObjectCount"]]] = relationship( > back_populates="revision", > primaryjoin="and_(Revision.blueprint_id==ObjectCount.blueprint_id, > Revision.revision_number==ObjectCount.revision_number)", > ) # type: ignore > > def __str__(self): > return f"{self.blueprint.filename} : {self.blueprint_id} : > {self.revision_number}" > > > class Object(Base): > __tablename__ = "objects" > > object_id: Mapped[int] = mapped_column(primary_key=True) > name: Mapped[str] > > def __str__(self): > return self.name > > > # https://docs.sqlalchemy.org/en/20/orm/join_conditions.html > # https://docs.sqlalchemy.org/en/20/orm/basic_relationships.html > # > https://docs.sqlalchemy.org/en/20/core/constraints.html#sqlalchemy.schema.UniqueConstraint > class ObjectCount(Base): > __tablename__ = "object_count" > __table_args__ = ( > UniqueConstraint("blueprint_id", "revision_number", "object_id", > name="o_c_unique"), > ) > > blueprint_id: Mapped[int] = > mapped_column(ForeignKey("revisions.blueprint_id"), primary_key=True) > revision_number: Mapped[int] = > mapped_column(ForeignKey("revisions.revision_number"), primary_key=True) > object_id: Mapped[int] = mapped_column(ForeignKey("objects.object_id"), > primary_key=True) > > count: Mapped[int] > > object: Mapped["Object"] = relationship() # type: ignore > revision: Mapped["Revision"] = relationship( > back_populates="object_count", > primaryjoin="and_(Revision.blueprint_id==ObjectCount.blueprint_id, > Revision.revision_number==ObjectCount.revision_number)", > ) # type: ignore > > def __str__(self): > return f"{self.revision.blueprint.filename} {self.revision_number} > {self.object.name} {self.count}" > > > DATABASE = "postgresql+psycopg://user:password@192.168.10.111:5432/mydatabase" > DATABASE = > "postgresql+psycopg2://user:password@192.168.10.111:5432/mydatabase" > #DATABASE = "sqlite:///database.db" > engine = create_engine(D
[sqlalchemy] Unique constraint error in PostgrSQL when migrating with Alembic
I have a database that looks like this that I create with Alembic. The relationships are trivial except between Revision and ObjectCount, there it used two foreign keys [image: aaa.png] The code looks like this from datetime import datetime from typing import Optional from sqlalchemy import ForeignKey, create_engine, UniqueConstraint from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship, sessionmaker # type: ignore class Base(DeclarativeBase): pass class Blueprint(Base): __tablename__ = "blueprints" blueprint_id: Mapped[int] = mapped_column(primary_key=True) filename: Mapped[str] created: Mapped[datetime] = mapped_column(default=datetime.utcnow) revisions: Mapped[list["Revision"]] = relationship(back_populates="blueprint") # type: ignore def get_new_revision_number(self) -> int: if not self.revisions: return 1 return max(revision.revision_number for revision in self.revisions) + 1 def __str__(self): return f"{self.filename} : {self.blueprint_id}" class Revision(Base): __tablename__ = "revisions" __table_args__ = ( UniqueConstraint("blueprint_id", "revision_number", name="revision_blueprint_revision_number"), ) blueprint_id: Mapped[int] = mapped_column(ForeignKey("blueprints.blueprint_id"), primary_key=True) revision_number: Mapped[int] = mapped_column(primary_key=True) date: Mapped[datetime] = mapped_column(default=datetime.utcnow) savedata: Mapped[str] blueprint: Mapped["Blueprint"] = relationship(back_populates="revisions") # type: ignore object_count: Mapped[Optional[list["ObjectCount"]]] = relationship( back_populates="revision", primaryjoin="and_(Revision.blueprint_id==ObjectCount.blueprint_id, Revision.revision_number==ObjectCount.revision_number)", ) # type: ignore def __str__(self): return f"{self.blueprint.filename} : {self.blueprint_id} : {self.revision_number}" class Object(Base): __tablename__ = "objects" object_id: Mapped[int] = mapped_column(primary_key=True) name: Mapped[str] def __str__(self): return self.name # https://docs.sqlalchemy.org/en/20/orm/join_conditions.html # https://docs.sqlalchemy.org/en/20/orm/basic_relationships.html # https://docs.sqlalchemy.org/en/20/core/constraints.html#sqlalchemy.schema.UniqueConstraint class ObjectCount(Base): __tablename__ = "object_count" __table_args__ = ( UniqueConstraint("blueprint_id", "revision_number", "object_id", name="o_c_unique"), ) blueprint_id: Mapped[int] = mapped_column(ForeignKey("revisions.blueprint_id"), primary_key=True) revision_number: Mapped[int] = mapped_column(ForeignKey("revisions.revision_number"), primary_key=True) object_id: Mapped[int] = mapped_column(ForeignKey("objects.object_id"), primary_key=True) count: Mapped[int] object: Mapped["Object"] = relationship() # type: ignore revision: Mapped["Revision"] = relationship( back_populates="object_count", primaryjoin="and_(Revision.blueprint_id==ObjectCount.blueprint_id, Revision.revision_number==ObjectCount.revision_number)", ) # type: ignore def __str__(self): return f"{self.revision.blueprint.filename} {self.revision_number} {self.object.name} {self.count}" DATABASE = "postgresql+psycopg://user:password@192.168.10.111:5432/mydatabase" DATABASE = "postgresql+psycopg2://user:password@192.168.10.111:5432/mydatabase" #DATABASE = "sqlite:///database.db" engine = create_engine(DATABASE) SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) I can create migrations with Alembic no problem. And I can migrate when I use SQLite. But when I try to migrate with PostgreSQL I get this error: sqlalchemy.exc.ProgrammingError: (psycopg2.errors.InvalidForeignKey) there is no unique constraint matching given keys for referenced table "revisions" [SQL: CREATE TABLE object_count ( blueprint_id INTEGER NOT NULL, revision_number INTEGER NOT NULL, object_id INTEGER NOT NULL, count INTEGER NOT NULL, PRIMARY KEY (blueprint_id, revision_number, object_id), FOREIGN KEY(blueprint_id) REFERENCES revisions (blueprint_id), FOREIGN KEY(object_id) REFERENCES objects (object_id), FOREIGN KEY(revision_number) REFERENCES revisions (revision_number), CONSTRAINT o_c_unique UNIQUE (blueprint_id, revision_number, object_id) ) ] I think I clearly see a unique constraint in the code. I add the UniqueConstraint i
Re: [sqlalchemy] Doesnt execute any thing at new pc
On 9/12/23 12:31 AM, FURKAN bilgin wrote: Hi, I updated my PC and downloaded my old codes. However, the SQLAlchemy execute function is not working. but it works on Ubuntu. The code is basically like this: My first suggestion is to make sure the directory path points to something that actually exists. Your "username" may have changed. -- Richard Damon -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/12f40a81-3c37-4c9a-a807-8a2f5167be98%40Damon-Family.org.
[sqlalchemy] Doesnt execute any thing at new pc
Hi, I updated my PC and downloaded my old codes. However, the SQLAlchemy execute function is not working. but it works on Ubuntu. The code is basically like this: -- from sqlalchemy import ( MetaData, Table, Column, Integer, String, Boolean, create_engine, DateTime, VARCHAR, ) from datetime import datetime from flask_sqlalchemy import SQLAlchemy from flask import Flask, render_template, abort, request from sqlalchemy.sql import select engine = create_engine( "sqlite:///C:/Users/furka/OneDrive/Masaüstü/programlama/Python/db3.db" ) app = Flask(__name__) app.secret_key = "#$#$#$" app.config[ "SQLALCHEMY_DATABASE_URI" ] = "sqlite:///C:/Users/furka/OneDrive/Masaüstü/programlama/Python/db3.db" meta = MetaData() meta.reflect(bind=engine) db = SQLAlchemy(app) print(len(meta.tables)) if not ("application" in meta.tables): Table( "application", meta, Column("id", Integer, primary_key=True), Column("name", VARCHAR(80)), Column("password", VARCHAR(80)), Column("anaSayfa", VARCHAR(80)), Column("manuelSayfa", VARCHAR(80)), Column("varsayilanlar", VARCHAR(80)), Column("dinamik", VARCHAR(80)), Column("dinamikSayfa", VARCHAR(80)), Column("kitap", VARCHAR(80)), Column("kalem", VARCHAR(80)), Column("date", DateTime, default=datetime.utcnow), ) meta.create_all(engine) if 1: if 1: application = Table("application", meta) conn = engine.connect() app = application.insert().values(name = "name", password = "password", anaSayfa = "anaSayfa", manuelSayfa = "manuelSayfa", varsayilanlar= "varsayilanlar", dinamikSayfa = "dinamikSayfa", dinamik = "dinamik", kitap= "kitap", kalem= "kalem" ) conn.execute(app) conn.close() print("crtd") -- output: -- 1 crtd -- application table is created but new values doesnt appear -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/ced6580a-c3d9-4586-84f7-36a539f4ead2n%40googlegroups.com.
Re: [sqlalchemy] Update Username and Password from vault
makes sense, the connection is pooled. if you make lots of connections, like more than five simultaneous connections, you'd see more of it, if you call engine.dispose() then engine.connect(), you would see it again also, etc. Also try using NullPool, then you'd see the hook run every time the engine is used. On Fri, Sep 8, 2023, at 12:13 PM, Steven Schierholz wrote: > Yes but only once when the app starts up. > > On Friday, September 8, 2023 at 10:04:45 AM UTC-6 Mike Bayer wrote: >> __ >> assuming proper indentation it looks fine. are your print statements being >> seen ? >> >> On Fri, Sep 8, 2023, at 11:54 AM, Steven Schierholz wrote: >>> Ok that makes sense and clarifies some stuff for me. I have tried your >>> implementation but it doesn't seem like its getting new connections. We are >>> using sessionmaker(). So basically this is what we are doing. Can you help >>> me understand if we are doing this right and if any changes need to happen >>> to make this work? Sorry the tabbing is not right after paste. Thanks for >>> your help! >>> >>> >>> *# Create the engine to connect to the database *engine = create_engine( >>> f"postgresql+psycopg2://test:password@{pg_host}:5432/{pg_database}", >>> * # connect_args=ssl_args, *** connect_args={"options": "-c timezone=utc"}, >>> pool_pre_ping=*True*, >>> encoding="utf8", >>> ) >>> >>> @event.listens_for(engine, "do_connect") >>> *def *receive_do_connect(dialect, conn_rec, cargs, cparams): >>> >>> *# Getting the postgres details ** **try*: >>> *# Get the configs ** *configs = Properties() >>> >>> *# Open the file to get the values needed ** **with **open*("/var/secrets/pgsql/vault-credentials.properties", "rb") *as *config_file: >>> configs.load(config_file) >>> >>> *# Get each of the properties, hopefully ** *pg_user = configs.get("username").data >>> pg_password = configs.get("password").data >>> >>> *except **FileNotFoundError*: >>> >>> *# Use whats in the environment ** *pg_user = os.getenv("pg_user") >>> pg_password = os.getenv("pg_password") >>> >>> *print*("Connecting to db with username: ", pg_user) >>> *print*("Connecting to db with password: ", pg_password) >>> >>> cparams["user"] = pg_user >>> cparams["password"] = pg_password >>> >>> session_factory = sessionmaker(bind=engine) >>> sqla_session = session_factory() >>> >>> # Then using the sqla_session to execute queries and make modifications to >>> the database >>> On Thursday, September 7, 2023 at 4:26:05 PM UTC-6 Mike Bayer wrote: >>>> __ >>>> no, create_engine() does not connect at all. connections occur when >>>> you first call `engine.connect()`. From that point, the behavior of >>>> subsequent `engine.connect()` calls depends on connection pool >>>> configuration. all connection pools have points at which they continue >>>> to establish new connections as the application proceeds, it's just a >>>> question of how often and under what circumstances.The default >>>> QueuePool will make new connections when it goes into "overflow", as well >>>> as when existing connections are invalidated due to connectivity problems >>>> or if the pool_recycle timeout is reached. >>>> >>>> >>>> >>>> On Thu, Sep 7, 2023, at 2:34 PM, Steven Schierholz wrote: >>>>> That makes sense but doesn't connect only happen once when >>>>> create_engine() is called? >>>>> >>>>> On Thursday, September 7, 2023 at 12:00:35 PM UTC-6 Mike Bayer wrote: >>>>>> __ >>>>>> the documentation for this pattern is at >>>>>> https://docs.sqlalchemy.org/en/20/core/engines.html#generating-dynamic-authentication-tokens >>>>>> , and a completely specific example is at >>>>>> https://docs.sqlalchemy.org/en/20/dialects/mssql.html#mssql-pyodbc-access-tokens >>>>>> . Basically your application needs to have some way to retrieve the >>>>>> correct credentials as it runs, and you hook that into the event to >>>>>> populate the connect arguments with the correct credentials. >>>>>> >>>>>> On Thu
Re: [sqlalchemy] Update Username and Password from vault
Yes but only once when the app starts up. On Friday, September 8, 2023 at 10:04:45 AM UTC-6 Mike Bayer wrote: > assuming proper indentation it looks fine. are your print statements > being seen ? > > On Fri, Sep 8, 2023, at 11:54 AM, Steven Schierholz wrote: > > Ok that makes sense and clarifies some stuff for me. I have tried your > implementation but it doesn't seem like its getting new connections. We are > using sessionmaker(). So basically this is what we are doing. Can you help > me understand if we are doing this right and if any changes need to happen > to make this work? Sorry the tabbing is not right after paste. Thanks for > your help! > > > > *# Create the engine to connect to the database*engine = create_engine( > f"postgresql+psycopg2://test:password@{pg_host}:5432/{pg_database}", > > * # connect_args=ssl_args,* connect_args={"options": "-c timezone=utc"}, > pool_pre_ping=*True*, > encoding="utf8", > ) > > @event.listens_for(engine, "do_connect") > *def *receive_do_connect(dialect, conn_rec, cargs, cparams): > > > *# Getting the postgres details* *try*: > > *# Get the configs* configs = Properties() > > > *# Open the file to get the values needed* *with **open*( > "/var/secrets/pgsql/vault-credentials.properties", "rb") *as *config_file: > configs.load(config_file) > > > *# Get each of the properties, hopefully* pg_user = configs.get("username" > ).data > pg_password = configs.get("password").data > > *except **FileNotFoundError*: > > > *# Use whats in the environment* pg_user = os.getenv("pg_user") > pg_password = os.getenv("pg_password") > > *print*("Connecting to db with username: ", pg_user) > *print*("Connecting to db with password: ", pg_password) > > cparams["user"] = pg_user > cparams["password"] = pg_password > > session_factory = sessionmaker(bind=engine) > sqla_session = session_factory() > > # Then using the sqla_session to execute queries and make modifications to > the database > On Thursday, September 7, 2023 at 4:26:05 PM UTC-6 Mike Bayer wrote: > > > no, create_engine() does not connect at all. connections occur when > you first call `engine.connect()`. From that point, the behavior of > subsequent `engine.connect()` calls depends on connection pool > configuration. all connection pools have points at which they continue to > establish new connections as the application proceeds, it's just a question > of how often and under what circumstances.The default QueuePool will > make new connections when it goes into "overflow", as well as when existing > connections are invalidated due to connectivity problems or if the > pool_recycle timeout is reached. > > > > On Thu, Sep 7, 2023, at 2:34 PM, Steven Schierholz wrote: > > That makes sense but doesn't connect only happen once when create_engine() > is called? > > On Thursday, September 7, 2023 at 12:00:35 PM UTC-6 Mike Bayer wrote: > > > the documentation for this pattern is at > https://docs.sqlalchemy.org/en/20/core/engines.html#generating-dynamic-authentication-tokens > > , and a completely specific example is at > https://docs.sqlalchemy.org/en/20/dialects/mssql.html#mssql-pyodbc-access-tokens > > . Basically your application needs to have some way to retrieve the > correct credentials as it runs, and you hook that into the event to > populate the connect arguments with the correct credentials. > > On Thu, Sep 7, 2023, at 1:54 PM, Steven Schierholz wrote: > > So I have seen some chats here about cred refresh from vault and some > suggestions have been to use @event.listens_for(engine, "do_connect") to > update creds when the connection is established. My understanding of this > is that connecting to the database should only happen once when my flask > application starts up, but I need to update the creds without restarting my > application so I'm not sure that the event listener will work in my case. > > Am I understanding that correctly? If so, is there a way to get the right > creds to pass to the engine for sqlalchemy every 24 hours when the creds > from vault get updated without restarting my application? > > > -- > SQLAlchemy - > The Python SQL Toolkit and Object Relational Mapper > > http://www.sqlalchemy.org/ > > To post example code, please provide an MCVE: Minimal, Complete, and > Verifiable Example. See http://stackoverflow.com/help/mcve for a full > description. > --- > You received this message because you are subscribed to the Google Groups
Re: [sqlalchemy] Update Username and Password from vault
assuming proper indentation it looks fine. are your print statements being seen ? On Fri, Sep 8, 2023, at 11:54 AM, Steven Schierholz wrote: > Ok that makes sense and clarifies some stuff for me. I have tried your > implementation but it doesn't seem like its getting new connections. We are > using sessionmaker(). So basically this is what we are doing. Can you help me > understand if we are doing this right and if any changes need to happen to > make this work? Sorry the tabbing is not right after paste. Thanks for your > help! > > > *# Create the engine to connect to the database *engine = create_engine( > f"postgresql+psycopg2://test:password@{pg_host}:5432/{pg_database}", > * # connect_args=ssl_args, *** connect_args={"options": "-c timezone=utc"}, > pool_pre_ping=*True*, > encoding="utf8", > ) > > @event.listens_for(engine, "do_connect") > *def *receive_do_connect(dialect, conn_rec, cargs, cparams): > > *# Getting the postgres details ** **try*: > *# Get the configs ** *configs = Properties() > > *# Open the file to get the values needed ** **with **open*("/var/secrets/pgsql/vault-credentials.properties", "rb") *as *config_file: > configs.load(config_file) > > *# Get each of the properties, hopefully ** *pg_user = configs.get("username").data > pg_password = configs.get("password").data > > *except **FileNotFoundError*: > > *# Use whats in the environment ** *pg_user = os.getenv("pg_user") > pg_password = os.getenv("pg_password") > > *print*("Connecting to db with username: ", pg_user) > *print*("Connecting to db with password: ", pg_password) > > cparams["user"] = pg_user > cparams["password"] = pg_password > > session_factory = sessionmaker(bind=engine) > sqla_session = session_factory() > > # Then using the sqla_session to execute queries and make modifications to > the database > On Thursday, September 7, 2023 at 4:26:05 PM UTC-6 Mike Bayer wrote: >> __ >> no, create_engine() does not connect at all. connections occur when you >> first call `engine.connect()`. From that point, the behavior of subsequent >> `engine.connect()` calls depends on connection pool configuration. all >> connection pools have points at which they continue to establish new >> connections as the application proceeds, it's just a question of how often >> and under what circumstances.The default QueuePool will make new >> connections when it goes into "overflow", as well as when existing >> connections are invalidated due to connectivity problems or if the >> pool_recycle timeout is reached. >> >> >> >> On Thu, Sep 7, 2023, at 2:34 PM, Steven Schierholz wrote: >>> That makes sense but doesn't connect only happen once when create_engine() >>> is called? >>> >>> On Thursday, September 7, 2023 at 12:00:35 PM UTC-6 Mike Bayer wrote: >>>> __ >>>> the documentation for this pattern is at >>>> https://docs.sqlalchemy.org/en/20/core/engines.html#generating-dynamic-authentication-tokens >>>> , and a completely specific example is at >>>> https://docs.sqlalchemy.org/en/20/dialects/mssql.html#mssql-pyodbc-access-tokens >>>> . Basically your application needs to have some way to retrieve the >>>> correct credentials as it runs, and you hook that into the event to >>>> populate the connect arguments with the correct credentials. >>>> >>>> On Thu, Sep 7, 2023, at 1:54 PM, Steven Schierholz wrote: >>>>> So I have seen some chats here about cred refresh from vault and some >>>>> suggestions have been to use @event.listens_for(engine, "do_connect") to >>>>> update creds when the connection is established. My understanding of this >>>>> is that connecting to the database should only happen once when my flask >>>>> application starts up, but I need to update the creds without restarting >>>>> my application so I'm not sure that the event listener will work in my >>>>> case. >>>>> >>>>> Am I understanding that correctly? If so, is there a way to get the right >>>>> creds to pass to the engine for sqlalchemy every 24 hours when the creds >>>>> from vault get updated without restarting my application? >>>>> >>>>> >>>>> -- >>>>> SQLAlchemy - >>>>> The Python SQL Toolkit and Object Relati
Re: [sqlalchemy] Update Username and Password from vault
Ok that makes sense and clarifies some stuff for me. I have tried your implementation but it doesn't seem like its getting new connections. We are using sessionmaker(). So basically this is what we are doing. Can you help me understand if we are doing this right and if any changes need to happen to make this work? Sorry the tabbing is not right after paste. Thanks for your help! # Create the engine to connect to the database engine = create_engine( f"postgresql+psycopg2://test:password@{pg_host}:5432/{pg_database}", # connect_args=ssl_args, connect_args={"options": "-c timezone=utc"}, pool_pre_ping=True, encoding="utf8", ) @event.listens_for(engine, "do_connect") def receive_do_connect(dialect, conn_rec, cargs, cparams): # Getting the postgres details try: # Get the configs configs = Properties() # Open the file to get the values needed with open("/var/secrets/pgsql/vault-credentials.properties", "rb") as config_file: configs.load(config_file) # Get each of the properties, hopefully pg_user = configs.get("username").data pg_password = configs.get("password").data except FileNotFoundError: # Use whats in the environment pg_user = os.getenv("pg_user") pg_password = os.getenv("pg_password") print("Connecting to db with username: ", pg_user) print("Connecting to db with password: ", pg_password) cparams["user"] = pg_user cparams["password"] = pg_password session_factory = sessionmaker(bind=engine) sqla_session = session_factory() # Then using the sqla_session to execute queries and make modifications to the database On Thursday, September 7, 2023 at 4:26:05 PM UTC-6 Mike Bayer wrote: > no, create_engine() does not connect at all. connections occur when > you first call `engine.connect()`. From that point, the behavior of > subsequent `engine.connect()` calls depends on connection pool > configuration. all connection pools have points at which they continue to > establish new connections as the application proceeds, it's just a question > of how often and under what circumstances.The default QueuePool will > make new connections when it goes into "overflow", as well as when existing > connections are invalidated due to connectivity problems or if the > pool_recycle timeout is reached. > > > > On Thu, Sep 7, 2023, at 2:34 PM, Steven Schierholz wrote: > > That makes sense but doesn't connect only happen once when create_engine() > is called? > > On Thursday, September 7, 2023 at 12:00:35 PM UTC-6 Mike Bayer wrote: > > > the documentation for this pattern is at > https://docs.sqlalchemy.org/en/20/core/engines.html#generating-dynamic-authentication-tokens > > , and a completely specific example is at > https://docs.sqlalchemy.org/en/20/dialects/mssql.html#mssql-pyodbc-access-tokens > > . Basically your application needs to have some way to retrieve the > correct credentials as it runs, and you hook that into the event to > populate the connect arguments with the correct credentials. > > On Thu, Sep 7, 2023, at 1:54 PM, Steven Schierholz wrote: > > So I have seen some chats here about cred refresh from vault and some > suggestions have been to use @event.listens_for(engine, "do_connect") to > update creds when the connection is established. My understanding of this > is that connecting to the database should only happen once when my flask > application starts up, but I need to update the creds without restarting my > application so I'm not sure that the event listener will work in my case. > > Am I understanding that correctly? If so, is there a way to get the right > creds to pass to the engine for sqlalchemy every 24 hours when the creds > from vault get updated without restarting my application? > > > -- > SQLAlchemy - > The Python SQL Toolkit and Object Relational Mapper > > http://www.sqlalchemy.org/ > > To post example code, please provide an MCVE: Minimal, Complete, and > Verifiable Example. See http://stackoverflow.com/help/mcve for a full > description. > --- > You received this message because you are subscribed to the Google Groups > "sqlalchemy" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to sqlalchemy+...@googlegroups.com. > To view this discussion on the web visit > https://groups.google.com/d/msgid/sqlalchemy/2de2e3fb-526c-49f7-8780-9ef55a9ad8bcn%40googlegroups.com > > <https://groups.google.com/d/msgid/sqlalchemy/2de2e3fb-526c-49f7-8780-9ef55a9ad8bcn%40googlegroups.com?utm_medium=email_source=footer> > . > > > > -- > SQLAlchemy - > The Python SQL Toolkit and Object Relational M
Re: [sqlalchemy] Update Username and Password from vault
no, create_engine() does not connect at all. connections occur when you first call `engine.connect()`. From that point, the behavior of subsequent `engine.connect()` calls depends on connection pool configuration. all connection pools have points at which they continue to establish new connections as the application proceeds, it's just a question of how often and under what circumstances.The default QueuePool will make new connections when it goes into "overflow", as well as when existing connections are invalidated due to connectivity problems or if the pool_recycle timeout is reached. On Thu, Sep 7, 2023, at 2:34 PM, Steven Schierholz wrote: > That makes sense but doesn't connect only happen once when create_engine() is > called? > > On Thursday, September 7, 2023 at 12:00:35 PM UTC-6 Mike Bayer wrote: >> __ >> the documentation for this pattern is at >> https://docs.sqlalchemy.org/en/20/core/engines.html#generating-dynamic-authentication-tokens >> , and a completely specific example is at >> https://docs.sqlalchemy.org/en/20/dialects/mssql.html#mssql-pyodbc-access-tokens >> . Basically your application needs to have some way to retrieve the >> correct credentials as it runs, and you hook that into the event to populate >> the connect arguments with the correct credentials. >> >> On Thu, Sep 7, 2023, at 1:54 PM, Steven Schierholz wrote: >>> So I have seen some chats here about cred refresh from vault and some >>> suggestions have been to use @event.listens_for(engine, "do_connect") to >>> update creds when the connection is established. My understanding of this >>> is that connecting to the database should only happen once when my flask >>> application starts up, but I need to update the creds without restarting my >>> application so I'm not sure that the event listener will work in my case. >>> >>> Am I understanding that correctly? If so, is there a way to get the right >>> creds to pass to the engine for sqlalchemy every 24 hours when the creds >>> from vault get updated without restarting my application? >>> >>> >>> -- >>> SQLAlchemy - >>> The Python SQL Toolkit and Object Relational Mapper >>> >>> http://www.sqlalchemy.org/ >>> >>> To post example code, please provide an MCVE: Minimal, Complete, and >>> Verifiable Example. See http://stackoverflow.com/help/mcve for a full >>> description. >>> --- >>> You received this message because you are subscribed to the Google Groups >>> "sqlalchemy" group. >>> To unsubscribe from this group and stop receiving emails from it, send an >>> email to sqlalchemy+...@googlegroups.com. >>> To view this discussion on the web visit >>> https://groups.google.com/d/msgid/sqlalchemy/2de2e3fb-526c-49f7-8780-9ef55a9ad8bcn%40googlegroups.com >>> >>> <https://groups.google.com/d/msgid/sqlalchemy/2de2e3fb-526c-49f7-8780-9ef55a9ad8bcn%40googlegroups.com?utm_medium=email_source=footer>. >> > > > -- > SQLAlchemy - > The Python SQL Toolkit and Object Relational Mapper > > http://www.sqlalchemy.org/ > > To post example code, please provide an MCVE: Minimal, Complete, and > Verifiable Example. See http://stackoverflow.com/help/mcve for a full > description. > --- > You received this message because you are subscribed to the Google Groups > "sqlalchemy" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to sqlalchemy+unsubscr...@googlegroups.com. > To view this discussion on the web visit > https://groups.google.com/d/msgid/sqlalchemy/5c9c5b5f-a84b-41b8-8eb2-c3117fbf50f5n%40googlegroups.com > > <https://groups.google.com/d/msgid/sqlalchemy/5c9c5b5f-a84b-41b8-8eb2-c3117fbf50f5n%40googlegroups.com?utm_medium=email_source=footer>. -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/71dcdb8d-2493-403d-83f7-7060041a563c%40app.fastmail.com.
Re: [sqlalchemy] Update Username and Password from vault
That makes sense but doesn't connect only happen once when create_engine() is called? On Thursday, September 7, 2023 at 12:00:35 PM UTC-6 Mike Bayer wrote: > the documentation for this pattern is at > https://docs.sqlalchemy.org/en/20/core/engines.html#generating-dynamic-authentication-tokens > > , and a completely specific example is at > https://docs.sqlalchemy.org/en/20/dialects/mssql.html#mssql-pyodbc-access-tokens > > . Basically your application needs to have some way to retrieve the > correct credentials as it runs, and you hook that into the event to > populate the connect arguments with the correct credentials. > > On Thu, Sep 7, 2023, at 1:54 PM, Steven Schierholz wrote: > > So I have seen some chats here about cred refresh from vault and some > suggestions have been to use @event.listens_for(engine, "do_connect") to > update creds when the connection is established. My understanding of this > is that connecting to the database should only happen once when my flask > application starts up, but I need to update the creds without restarting my > application so I'm not sure that the event listener will work in my case. > > Am I understanding that correctly? If so, is there a way to get the right > creds to pass to the engine for sqlalchemy every 24 hours when the creds > from vault get updated without restarting my application? > > > -- > SQLAlchemy - > The Python SQL Toolkit and Object Relational Mapper > > http://www.sqlalchemy.org/ > > To post example code, please provide an MCVE: Minimal, Complete, and > Verifiable Example. See http://stackoverflow.com/help/mcve for a full > description. > --- > You received this message because you are subscribed to the Google Groups > "sqlalchemy" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to sqlalchemy+...@googlegroups.com. > To view this discussion on the web visit > https://groups.google.com/d/msgid/sqlalchemy/2de2e3fb-526c-49f7-8780-9ef55a9ad8bcn%40googlegroups.com > > <https://groups.google.com/d/msgid/sqlalchemy/2de2e3fb-526c-49f7-8780-9ef55a9ad8bcn%40googlegroups.com?utm_medium=email_source=footer> > . > > > -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/2d36beb7-d2ae-4178-8787-442e74cc9615n%40googlegroups.com.
Re: [sqlalchemy] Update Username and Password from vault
That makes sense but doesn't connect only happen once when create_engine() is called? On Thursday, September 7, 2023 at 12:00:35 PM UTC-6 Mike Bayer wrote: > the documentation for this pattern is at > https://docs.sqlalchemy.org/en/20/core/engines.html#generating-dynamic-authentication-tokens > > , and a completely specific example is at > https://docs.sqlalchemy.org/en/20/dialects/mssql.html#mssql-pyodbc-access-tokens > > . Basically your application needs to have some way to retrieve the > correct credentials as it runs, and you hook that into the event to > populate the connect arguments with the correct credentials. > > On Thu, Sep 7, 2023, at 1:54 PM, Steven Schierholz wrote: > > So I have seen some chats here about cred refresh from vault and some > suggestions have been to use @event.listens_for(engine, "do_connect") to > update creds when the connection is established. My understanding of this > is that connecting to the database should only happen once when my flask > application starts up, but I need to update the creds without restarting my > application so I'm not sure that the event listener will work in my case. > > Am I understanding that correctly? If so, is there a way to get the right > creds to pass to the engine for sqlalchemy every 24 hours when the creds > from vault get updated without restarting my application? > > > -- > SQLAlchemy - > The Python SQL Toolkit and Object Relational Mapper > > http://www.sqlalchemy.org/ > > To post example code, please provide an MCVE: Minimal, Complete, and > Verifiable Example. See http://stackoverflow.com/help/mcve for a full > description. > --- > You received this message because you are subscribed to the Google Groups > "sqlalchemy" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to sqlalchemy+...@googlegroups.com. > To view this discussion on the web visit > https://groups.google.com/d/msgid/sqlalchemy/2de2e3fb-526c-49f7-8780-9ef55a9ad8bcn%40googlegroups.com > > <https://groups.google.com/d/msgid/sqlalchemy/2de2e3fb-526c-49f7-8780-9ef55a9ad8bcn%40googlegroups.com?utm_medium=email_source=footer> > . > > > -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/5c9c5b5f-a84b-41b8-8eb2-c3117fbf50f5n%40googlegroups.com.
Re: [sqlalchemy] Update Username and Password from vault
the documentation for this pattern is at https://docs.sqlalchemy.org/en/20/core/engines.html#generating-dynamic-authentication-tokens , and a completely specific example is at https://docs.sqlalchemy.org/en/20/dialects/mssql.html#mssql-pyodbc-access-tokens . Basically your application needs to have some way to retrieve the correct credentials as it runs, and you hook that into the event to populate the connect arguments with the correct credentials. On Thu, Sep 7, 2023, at 1:54 PM, Steven Schierholz wrote: > So I have seen some chats here about cred refresh from vault and some > suggestions have been to use @event.listens_for(engine, "do_connect") to > update creds when the connection is established. My understanding of this is > that connecting to the database should only happen once when my flask > application starts up, but I need to update the creds without restarting my > application so I'm not sure that the event listener will work in my case. > > Am I understanding that correctly? If so, is there a way to get the right > creds to pass to the engine for sqlalchemy every 24 hours when the creds from > vault get updated without restarting my application? > > > -- > SQLAlchemy - > The Python SQL Toolkit and Object Relational Mapper > > http://www.sqlalchemy.org/ > > To post example code, please provide an MCVE: Minimal, Complete, and > Verifiable Example. See http://stackoverflow.com/help/mcve for a full > description. > --- > You received this message because you are subscribed to the Google Groups > "sqlalchemy" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to sqlalchemy+unsubscr...@googlegroups.com. > To view this discussion on the web visit > https://groups.google.com/d/msgid/sqlalchemy/2de2e3fb-526c-49f7-8780-9ef55a9ad8bcn%40googlegroups.com > > <https://groups.google.com/d/msgid/sqlalchemy/2de2e3fb-526c-49f7-8780-9ef55a9ad8bcn%40googlegroups.com?utm_medium=email_source=footer>. -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/a6b972d3-0700-4772-a2c8-243706e4c6e9%40app.fastmail.com.
[sqlalchemy] Update Username and Password from vault
So I have seen some chats here about cred refresh from vault and some suggestions have been to use @event.listens_for(engine, "do_connect") to update creds when the connection is established. My understanding of this is that connecting to the database should only happen once when my flask application starts up, but I need to update the creds without restarting my application so I'm not sure that the event listener will work in my case. Am I understanding that correctly? If so, is there a way to get the right creds to pass to the engine for sqlalchemy every 24 hours when the creds from vault get updated without restarting my application? -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/2de2e3fb-526c-49f7-8780-9ef55a9ad8bcn%40googlegroups.com.
Re: [sqlalchemy] Duplicating a relationship from one ORM model to a subquery model
send viewonly=True to these relationships you make. these are not for writing anyway and that will resolve the overlaps warnings (the warning says as much). On Thu, Sep 7, 2023, at 10:41 AM, zedr...@gmail.com wrote: > Hi Mike, > > Thanks a lot for taking the time to reply… > > Indeed, I came to a similar conclusion and worked out what seems like a > fairly clean way to copy relationships (assuming they do not use > secondary_join). > > The fact that I cannot seem to update the mapper before the class is created > makes my code a bit more convoluted than I'd like… But this seems to work: > > def copy_relationship(source_model, relationship_name): > source_relationship = getattr(source_model.__mapper__.relationships, > relationship_name, None) > kwargs = {} > overlaps = [relationship_name] > for param_name in inspect.signature(relationship).parameters: > if value := getattr(source_relationship, param_name, None): > if param_name in ('backref', 'back_populates'): > overlaps.append(value) > elif param_name not in ('init', 'primaryjoin'): > kwargs[param_name] = value > return relationship(**kwargs, overlaps = ','.join(overlaps)) > > class FooViewMeta(type(db.Model)): > def __new__(mcs, name, bases, attrs): > attrs["__table__"] = (select(Foo).with_only_columns(Foo.id).subquery()) > attrs["bazs"] = copy_relationship(Foo, 'bazs') > return super().__new__(mcs, name, (db.Model,), attrs) > > def __init__(cls, name, bases, attrs): > super().__init__(name, bases, attrs) > for rel_name, rel_attr in cls.__mapper__.relationships.items(): > expr = getattr(rel_attr, 'primaryjoin', None) > if not expr: continue > kwargs = {'operator': expr.operator} > for attr in ('left', 'right'): > side = getattr(expr, attr) > if ('__table__' in side) and (side.table == Foo.__table__) and (side.name in > cls.__table__.c): > side = foreign(getattr(cls.__table__.c, side.name)) > kwargs[attr] = side > rel_attr.primary_join = BinaryExpression(**kwargs) > > class FooView(metaclass=FooViewMeta): > pass > > > > Running the code above without providing an overlaps argument to the new > relationship, results in a relationship conflict warning: > :10: SAWarning: relationship 'FooView.bazs' will copy column > anon_1.id to column baz.foo_id, > which conflicts with relationship(s): 'Baz.foo' (copies foo.id to > baz.foo_id). If this is not the intention, > consider if these relationships should be linked with back_populates, or if > viewonly=True should be applied > to one or more if they are read-only. For the less common case that foreign > key constraints are partially > overlapping, the orm.foreign() annotation can be used to isolate the columns > that should be written towards. > To silence this warning, add the parameter 'overlaps="foo"' to the > 'FooView.bazs' relationship. > (Background on this warning at: https://sqlalche.me/e/20/qzyx) > > As you can see in the code above, adding foreign to the join expression, does > not solve the problem. > > All in all, I wish there was a more straightforward way to create models that > inherit from an existing model, while loading/accessing only a subset of > columns (basically, polymorphism, without a polymorphism key)… Will gladly > take any suggestion on a different approach… > > But at least this seems to work! > > Thanks again, > -- > Dave > > > On Thursday, 7 September 2023 at 13:33:05 UTC+1 Mike Bayer wrote: >> >> >> On Thu, Sep 7, 2023, at 4:39 AM, zedr...@gmail.com wrote: >>> >>> *Is there a clean way to (programmatically) duplicate all relationship from >>> an existing model, over to a new model (that targets the same table and >>> selects a subset of columns as a subquery)?* >> >> relatonships are fixed to their parent class and have internal state that is >> dependent on it, so it can't be shared between two unrelated classes. >> >> you would need to introspect the attributes of each relationship that are >> important to the application, such as the target class etc., and create a >> new relationship() that has those attributes.Assuming the relationships >> dont have special join conditions, this would involve just looking for >> existing_class.__mapper__.attrs.relationship.entity, which is the mapper to >> which it refers, and placing this into a new relationship(). >> >> >>> >> > > > -- > SQLAlchemy - > The Python SQL Toolkit and Object Relational Mapper > > http://www.sqlalchemy.org/ > > To post example code, please provide an MCVE: Minimal, Complete, and > Verifiable Example. See
Re: [sqlalchemy] Duplicating a relationship from one ORM model to a subquery model
Hi Mike, Thanks a lot for taking the time to reply… Indeed, I came to a similar conclusion and worked out what seems like a fairly clean way to copy relationships (assuming they do not use secondary_join). The fact that I cannot seem to update the mapper before the class is created makes my code a bit more convoluted than I'd like… But this seems to work: def copy_relationship(source_model, relationship_name): source_relationship = getattr(source_model.__mapper__.relationships, relationship_name, None) kwargs = {} overlaps = [relationship_name] for param_name in inspect.signature(relationship).parameters: if value := getattr(source_relationship, param_name, None): if param_name in ('backref', 'back_populates'): overlaps.append(value) elif param_name not in ('init', 'primaryjoin'): kwargs[param_name] = value return relationship(**kwargs, overlaps = ','.join(overlaps)) class FooViewMeta(type(db.Model)): def __new__(mcs, name, bases, attrs): attrs["__table__"] = (select(Foo).with_only_columns(Foo.id).subquery()) attrs["bazs"] = copy_relationship(Foo, 'bazs') return super().__new__(mcs, name, (db.Model,), attrs) def __init__(cls, name, bases, attrs): super().__init__(name, bases, attrs) for rel_name, rel_attr in cls.__mapper__.relationships.items(): expr = getattr(rel_attr, 'primaryjoin', None) if not expr: continue kwargs = {'operator': expr.operator} for attr in ('left', 'right'): side = getattr(expr, attr) if ('__table__' in side) and (side.table == Foo.__table__) and (side.name in cls.__table__.c): side = foreign(getattr(cls.__table__.c, side.name)) kwargs[attr] = side rel_attr.primary_join = BinaryExpression(**kwargs) class FooView(metaclass=FooViewMeta): pass Running the code above without providing an overlaps argument to the new relationship, results in a relationship conflict warning: :10: SAWarning: relationship 'FooView.bazs' will copy column anon_1.id to column baz.foo_id, which conflicts with relationship(s): 'Baz.foo' (copies foo.id to baz.foo_id). If this is not the intention, consider if these relationships should be linked with back_populates, or if viewonly=True should be applied to one or more if they are read-only. For the less common case that foreign key constraints are partially overlapping, the orm.foreign() annotation can be used to isolate the columns that should be written towards. To silence this warning, add the parameter 'overlaps="foo"' to the 'FooView.bazs' relationship. (Background on this warning at: https://sqlalche.me/e/20/qzyx) As you can see in the code above, adding foreign to the join expression, does not solve the problem. All in all, I wish there was a more straightforward way to create models that inherit from an existing model, while loading/accessing only a subset of columns (basically, polymorphism, without a polymorphism key)… Will gladly take any suggestion on a different approach… But at least this seems to work! Thanks again, -- Dave On Thursday, 7 September 2023 at 13:33:05 UTC+1 Mike Bayer wrote: > > > On Thu, Sep 7, 2023, at 4:39 AM, zedr...@gmail.com wrote: > > > *Is there a clean way to (programmatically) duplicate all relationship > from an existing model, over to a new model (that targets the same table > and selects a subset of columns as a subquery)?* > > > relatonships are fixed to their parent class and have internal state that > is dependent on it, so it can't be shared between two unrelated classes. > > you would need to introspect the attributes of each relationship that are > important to the application, such as the target class etc., and create a > new relationship() that has those attributes.Assuming the relationships > dont have special join conditions, this would involve just looking for > existing_class.__mapper__.attrs.relationship.entity, which is the mapper to > which it refers, and placing this into a new relationship(). > > > > > -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/3693fbd8-e845-46e8-ad11-b8611a236774n%40googlegroups.com.
Re: [sqlalchemy] Duplicating a relationship from one ORM model to a subquery model
On Thu, Sep 7, 2023, at 4:39 AM, zedr...@gmail.com wrote: > > *Is there a clean way to (programmatically) duplicate all relationship from > an existing model, over to a new model (that targets the same table and > selects a subset of columns as a subquery)?* relatonships are fixed to their parent class and have internal state that is dependent on it, so it can't be shared between two unrelated classes. you would need to introspect the attributes of each relationship that are important to the application, such as the target class etc., and create a new relationship() that has those attributes.Assuming the relationships dont have special join conditions, this would involve just looking for existing_class.__mapper__.attrs.relationship.entity, which is the mapper to which it refers, and placing this into a new relationship(). > -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/3c23e775-f2d1-487d-8f5d-e7785399aeba%40app.fastmail.com.
[sqlalchemy] Duplicating a relationship from one ORM model to a subquery model
I am trying to (programmatically) create partial views of existing SQLAlchemy models, using a metaclass. A streamlined example, trying to get a subquery view on a model Foo with a relationship bar, would look something like that: class Bar(db.Model): id = db.Column(db.Integer, primary_key=True) class Foo(db.Model): id = db.Column(db.Integer, primary_key=True) bar_id = db.Column(db.Integer, db.ForeignKey("bar.id")) bar = db.relationship(Bar, backref='foos') class FooViewMeta(type(db.Model)): def __new__(mcs, name, bases, attrs): attrs["__table__"] = (select(Foo) .with_only_columns(Foo.id, Foo.bar_id, Foo.bar) .subquery()) attrs["bar"] = Foo.__mapper__.relationships["bar"] attrs["__mapper_args__"] = {"exclude_properties": ["bar"]} return super().__new__(mcs, name, (db.Model,), attrs) class FooView(metaclass=FooViewMeta): pass (Omitting exclude_properties gives me a warning about conflicting columns) I am able to load FooView and access its bar property fine. Unfortunately, if I run: q = Foo.query.options(joinedload(Foo.bar),) q.first() I get the following error, which tells me that this is not a correct way to duplicate the mapper for that relationship: : Mapped class Mapper[FooView(anon_1)] does not apply to any of the root entities in this query, e.g. Mapper[Foo(foo)]. Please specify the full path from one of the root entities to the target attribute. Clearly, the re-use of this relationship is confusing the mapper, who tries to use the newer subquery model and fails. Conversely, if I use: attrs["bar"] = getattr(Foo, "bar") The code works for 1-1 relationship, but fails for lazy 1-many… *Is there a clean way to (programmatically) duplicate all relationship from an existing model, over to a new model (that targets the same table and selects a subset of columns as a subquery)?* Note: unfortunately, I am not looking for polymorphic subclassing here (the "view" classes are a subset of columns, not rows), so it does not seem like I can use any of SQLAlchemy mapper options for that… -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/8b32d287-1f74-4ebb-bc86-429fb3651effn%40googlegroups.com.