PostgreSQL – Documentation SQLAlchemy 1.3 – Bien choisir son serveur d impression

Author: Titanfall —

Short summary: Prise en charge de la base de données PostgreSQL. Prise en charge DBAPI Les options dialect / DBAPI suivantes sont disponibles. Veuillez vous reporter aux sections individuelles de DBAPI pour obtenir des informations sur la connexion. Séquences / SERIAL / IDENTITY PostgreSQL supporte les séquences et SQLAlchemy les utilise par défaut de créer de nouvelles […]

Quick overview

Site
Tutos GameServer
Canonical URL
https://tutos-gameserver.fr/2019/10/21/postgresql-documentation-sqlalchemy-1-3-bien-choisir-son-serveur-d-impression/
LLM HTML version
https://tutos-gameserver.fr/2019/10/21/postgresql-documentation-sqlalchemy-1-3-bien-choisir-son-serveur-d-impression/llm
LLM JSON version
https://tutos-gameserver.fr/2019/10/21/postgresql-documentation-sqlalchemy-1-3-bien-choisir-son-serveur-d-impression/llm.json
Manifest
https://tutos-gameserver.fr/llm-endpoints-manifest.json
Estimated reading time
65 minutes (3872 seconds)
Word count
12906

Key points

Structured content

Prise en charge de la base de données PostgreSQL. Prise en charge DBAPI Les options dialect / DBAPI suivantes sont disponibles. Veuillez vous reporter aux sections individuelles de DBAPI pour obtenir des informations sur la connexion.

Séquences / SERIAL / IDENTITY PostgreSQL supporte les séquences et SQLAlchemy les utilise par défaut de créer de nouvelles valeurs de clé primaire pour les colonnes de clé primaire basées sur des nombres entiers. Quand créer des tables, SQLAlchemy va publier le EN SÉRIE type de données pour colonnes de clé primaire basées sur des nombres entiers, qui génèrent une séquence et un côté serveur défaut correspondant à la colonne. Pour spécifier une séquence nommée spécifique à utiliser pour la génération de clé primaire, Utilisez le Séquence() construction:

Table('quelque chose', métadonnées, Colonne('id', Entier, Séquence('some_id_seq'), clé primaire=Vrai) )

Lorsque SQLAlchemy émet une seule instruction INSERT, pour remplir le contrat de ayant le "dernier identifiant d'insertion" disponible, une clause RETURNING est ajoutée à l'instruction INSERT qui spécifie les colonnes de clé primaire doit être retourné une fois la déclaration terminée. La fonctionnalité RETURNING ne prend que place si PostgreSQL 8.2 ou version ultérieure est utilisé. Dans une approche de repli, le séquence, spécifiée explicitement ou implicitement via EN SÉRIE, est préalablement exécutée indépendamment, la valeur renvoyée à utiliser dans la insertion ultérieure. Notez que lorsqu'un insérer() la construction est exécutée en utilisant Sémantique «executemany», la fonctionnalité «dernier identifiant inséré» ne appliquer; aucune clause RETURNING n’est émise et la séquence n’a pas été pré-exécutée dans cette Cas. Pour forcer l'utilisation de RETURNING par défaut, spécifiez l'indicateur. implicit_returning = False à create_engine ().

Colonnes PostgreSQL 10 IDENTITY PostgreSQL 10 a une nouvelle fonctionnalité IDENTITY qui remplace l’utilisation de SERIAL. Le support intégré pour le rendu de IDENTITY n’est pas encore disponible, mais le le crochet de compilation suivant peut être utilisé pour remplacer les occurrences de SERIAL par IDENTITÉ:

de sqlalchemy.schema importation CreateColumn de sqlalchemy.ext.compiler importation compile

@compiles(CreateColumn, 'postgresql') def use_identity(élément, compilateur, **kw): texte = compilateur.visit_create_column(élément, **kw) texte = texte.remplacer("EN SÉRIE", "INT GÉNÉRÉ PAR DÉFAUT COMME IDENTITÉ") revenir texte

En utilisant ce qui précède, un tableau tel que:

t = Table( 't', m, Colonne('id', Entier, clé primaire=Vrai), Colonne('Les données', Chaîne) )

Générera sur la base de données de sauvegarde en tant que:

CRÉER TABLE t ( identifiant INT GÉNÉRÉ PAR DÉFAUT COMME IDENTITÉ NE PAS NUL, Les données VARCHAR, PRIMAIRE CLÉ (identifiant) )

Niveau d'isolation de la transaction Tous les dialectes PostgreSQL supportent la définition du niveau d'isolation des transactions à la fois via un paramètre spécifique au dialecte create_engine.isolation_level accepté par create_engine (), aussi bien que Connection.execution_options.isolation_level argument passé à Connection.execution_options (). Lors de l’utilisation d’un dialecte autre que psycopg2, cette fonction fonctionne en lançant la commande ENSEMBLE SESSION LES CARACTÉRISTIQUES COMME TRANSACTION ISOLEMENT NIVEAU pour chaque nouvelle connexion. Pour le niveau d'isolement AUTOCOMMIT spécial, Des techniques spécifiques à DBAPI sont utilisées. Pour définir le niveau d'isolement à l'aide de create_engine ():

moteur = create_engine( "postgresql + pg8000: // scott: tiger @ localhost / test", niveau_isolement="READ UNCOMMITTED" )

Pour définir à l'aide des options d'exécution par connexion:

lien = moteur.relier() lien = lien.execution_options( niveau_isolement="LIRE ENGAGÉ" )

Valeurs valides pour niveau_isolement comprendre:

Introspection de la table de schémas distants et chemin de recherche PostgreSQL TL; DR;: garder le chemin_recherche variable définie à sa valeur par défaut de Publique, nommer des schémas autre que Publique explicitement dans Table définitions. Le dialecte PostgreSQL peut refléter les tables de n’importe quel schéma. le Table.schema argument, ou bien la MetaData.reflect.schema l'argument détermine quel schéma sera être recherché pour la ou les tables. Le reflété Table objets conservera dans tous les cas cette .schéma attribut comme spécifié. Cependant, en ce qui concerne les tableaux que ces Table les objets font référence à via une contrainte de clé étrangère, une décision doit être prise quant à la .schéma est représenté dans ces tables distantes, dans le cas où cette distance nom de schéma est également un membre du courant Chemin de recherche PostgreSQL. Par défaut, le dialecte PostgreSQL reproduit le comportement encouragé par PostgreSQL propre pg_get_constraintdef () procédure intégrée. Cette fonction renvoie un exemple de définition pour une contrainte de clé étrangère particulière, omettant le nom de schéma référencé de cette définition lorsque le nom est également dans le chemin de recherche du schéma PostgreSQL. L'interaction ci-dessous illustre ce comportement:

tester=> CRÉER TABLE test_schema.référé(identifiant ENTIER PRIMAIRE CLÉ) CRÉER TABLE tester=> CRÉER TABLE référant( tester(> identifiant ENTIER PRIMAIRE CLÉ, tester(> id_référé ENTIER RÉFÉRENCES test_schema.référé(identifiant)); CRÉER TABLE tester=> ENSEMBLE chemin_recherche À Publique, test_schema; tester=> SÉLECTIONNER pg_catalog.pg_get_constraintdef(r.oid, vrai) DE tester-> pg_catalog.pg_class c JOINDRE pg_catalog.pg_namespace n tester-> SUR n.oid = c.espace de noms tester-> JOINDRE pg_catalog.pg_constraint r SUR c.oid = r.conrelide tester-> OÙ c.nom de famille='référant' ET r.contype = 'F' tester-> ; pg_get_constraintdef -------------------------------------------------- - ÉTRANGER CLÉ (id_référé) RÉFÉRENCES référé(identifiant) (1 rangée)

Ci-dessus, nous avons créé une table référé en tant que membre du schéma distant test_schemaCependant, lorsque nous avons ajouté test_schema à la PG chemin_recherche et ensuite demandé pg_get_constraintdef () pour le ÉTRANGER CLÉ syntaxe, test_schema n'a pas été inclus dans la sortie de la fonction. D'autre part, si nous redéfinissons le chemin de recherche sur la valeur par défaut typique de Publique:

tester=> ENSEMBLE chemin_recherche À Publique; ENSEMBLE

La même requête contre pg_get_constraintdef () retourne maintenant complètement nom qualifié du schéma pour nous:

tester=> SÉLECTIONNER pg_catalog.pg_get_constraintdef(r.oid, vrai) DE tester-> pg_catalog.pg_class c JOINDRE pg_catalog.pg_namespace n tester-> SUR n.oid = c.espace de noms tester-> JOINDRE pg_catalog.pg_constraint r SUR c.oid = r.conrelide tester-> OÙ c.nom de famille='référant' ET r.contype = 'F'; pg_get_constraintdef -------------------------------------------------- ------------- ÉTRANGER CLÉ (id_référé) RÉFÉRENCES test_schema.référé(identifiant) (1 rangée)

SQLAlchemy utilisera par défaut la valeur de retour de pg_get_constraintdef () afin de déterminer le nom du schéma distant. C’est-à-dire si notre chemin_recherche ont été mis à inclure test_schemaet nous avons invoqué une table processus de réflexion comme suit:

>>> de sqlalchemy importation Table, MetaData, create_engine >>> moteur = create_engine("postgresql: // scott: tiger @ localhost / test") >>> avec moteur.relier() comme Connecticut: ... Connecticut.exécuter("SET search_path TO test_schema, public") ... méta = MetaData() ... référant = Table('référant', méta, ... chargement automatique=Vrai, autoload_with=Connecticut) ...

Le processus ci-dessus fournirait à la MetaData.tables collection référé table nommée sans pour autant le schéma:

>>> méta.les tables[[[['référé'].schéma est Aucun Vrai

Pour modifier le comportement de la réflexion de sorte que le schéma référencé soit maintenu indépendamment de la chemin_recherche réglage, utilisez le postgresql_ignore_search_path option, qui peut être spécifiée en tant que argument spécifique au dialecte à la fois Table aussi bien que MetaData.reflect ():

>>> avec moteur.relier() comme Connecticut: ... Connecticut.exécuter("SET search_path TO test_schema, public") ... méta = MetaData() ... référant = Table('référant', méta, chargement automatique=Vrai, ... autoload_with=Connecticut, ... postgresql_ignore_search_path=Vrai) ...

Nous allons maintenant avoir test_schema.referred stocké comme qualifié de schéma:

>>> méta.les tables[[[['test_schema.referred'].schéma 'test_schema'

Notez que dans tous les cas, le schéma «par défaut» est toujours reflété comme Aucun. Le schéma «par défaut» sur PostgreSQL est celui qui est renvoyé par le PostgreSQL current_schema () une fonction. Sur un PostgreSQL typique l'installation, c'est le nom Publique. Donc, un tableau qui fait référence à un autre qui est dans le Publique (c'est-à-dire par défaut) le schéma aura toujours le .schéma attribut mis à Aucun.

Nouveau dans la version 0.9.2: Ajouté le postgresql_ignore_search_path option dialecte acceptée par Table et MetaData.reflect ().

INSERT / UPDATE… RETOURNER Le dialecte supporte les PG 8.2 INSERT..RECLINANT, MISE À JOUR..RECLINANT et SUPPRIMER .. RETOURNER syntaxes. INSERT..RECLINANT est utilisé par défaut pour les instructions INSERT à une seule ligne afin d'extraire les données nouvellement générées identificateurs de clé primaire. Pour spécifier un explicite RETOUR clause, Utilisez le _UpdateBase.returning () méthode par déclaration:

# INSERT..RETURNING résultat = table.insérer().rentrant(table.c.col1, table.c.col2). valeurs(Nom='foo') impression résultat.fetchall()

# UPDATE..RETURNING résultat = table.mise à jour().rentrant(table.c.col1, table.c.col2). où(table.c.Nom=='foo').valeurs(Nom='bar') impression résultat.fetchall()

# DELETE..RETURNING résultat = table.effacer().rentrant(table.c.col1, table.c.col2). où(table.c.Nom=='foo') impression résultat.fetchall()

INSERT… SUR CONFLICT (Upsert) A partir de la version 9.5, PostgreSQL permet les «upserts» (mises à jour ou insert) de lignes dans une table via le SUR CONFLIT clause de la INSÉRER déclaration. UNE La ligne candidate ne sera insérée que si cette ligne ne viole aucun code unique. contraintes. Dans le cas d’une violation de contrainte unique, une action secondaire peut être soit “DO UPDATE”, indiquant que les données dans le fichier la ligne cible doit être mise à jour, ou “NE RIEN FAIRE”, ce qui indique de sauter silencieusement cette rangée. Les conflits sont déterminés à l'aide de contraintes et d'index uniques existants. Celles-ci les contraintes peuvent être identifiées en utilisant leur nom comme indiqué dans DDL, ou ils peuvent être inféré en indiquant les colonnes et les conditions qui composent les index. SQLAlchemy fournit SUR CONFLIT support via le spécifique PostgreSQL postgresql.dml.insert () fonction, qui fournit les méthodes génératives on_conflict_do_update () et on_conflict_do_nothing ():

de sqlalchemy.dialects.postgresql importation insérer

insert_stmt = insérer(ma table).valeurs( identifiant='some_existing_id', Les données='valeur insérée')

do_nothing_stmt = insert_stmt.on_conflict_do_nothing( éléments_index=[[[['id'] )

Connecticut.exécuter(do_nothing_stmt)

do_update_stmt = insert_stmt.on_conflict_do_update( contrainte='pk_my_table', ensemble_=dict(Les données='valeur mise à jour') )

Connecticut.exécuter(do_update_stmt)

Les deux méthodes fournissent la "cible" du conflit en utilisant soit la contrainte nommée ou par inférence de colonne:

le Insert.on_conflict_do_update.index_elements argument spécifie une séquence contenant des noms de colonne de chaîne, Colonne des objets, et / ou des éléments d’expression SQL, qui identifieraient un unique indice:

do_update_stmt = insert_stmt.on_conflict_do_update( éléments_index=[[[['id'], ensemble_=dict(Les données='valeur mise à jour') )

do_update_stmt = insert_stmt.on_conflict_do_update( éléments_index=[[[[ma table.c.identifiant], ensemble_=dict(Les données='valeur mise à jour') )

Lors de l'utilisation Insert.on_conflict_do_update.index_elements à déduire un index, un index partiel peut être déduit en spécifiant également le Utilisez le Insert.on_conflict_do_update.index_where paramètre:

de sqlalchemy.dialects.postgresql importation insérer

stmt = insérer(ma table).valeurs(utilisateur_email='a@b.com', Les données='données insérées') stmt = stmt.on_conflict_do_update( éléments_index=[[[[ma table.c.utilisateur_email], index_where=ma table.c.utilisateur_email.comme('%@gmail.com'), ensemble_=dict(Les données=stmt.exclu.Les données) ) Connecticut.exécuter(stmt)

le Insert.on_conflict_do_update.constraint l'argument est utilisé pour spécifier directement un index plutôt que de l'inférer. Cela peut être le nom d'une contrainte UNIQUE, d'une contrainte PRIMARY KEY ou d'un INDEX:

do_update_stmt = insert_stmt.on_conflict_do_update( contrainte='ma_table_idx_1', ensemble_=dict(Les données='valeur mise à jour') )

do_update_stmt = insert_stmt.on_conflict_do_update( contrainte='ma_table_pk', ensemble_=dict(Les données='valeur mise à jour') )

le Insert.on_conflict_do_update.constraint argument peut se référer également à une construction SQLAlchemy représentant une contrainte, par exemple. Contrainte unique, PrimaryKeyConstraint, Indice, ou ExcludeConstraint. Dans cette utilisation, si la contrainte a un nom, elle est utilisée directement. Sinon, si le contrainte est non nommée, alors l’inférence sera utilisée, où les expressions et la clause optionnelle WHERE de la contrainte sera précisée dans le construction. Cette utilisation est particulièrement pratique faire référence à la clé primaire nommée ou non nommée d'un Table en utilisant le Table.primary_key attribut:

do_update_stmt = insert_stmt.on_conflict_do_update( contrainte=ma table.clé primaire, ensemble_=dict(Les données='valeur mise à jour') )

SUR CONFLIT ... FAIRE MISE À JOUR est utilisé pour effectuer une mise à jour du déjà ligne existante, en utilisant n'importe quelle combinaison de nouvelles valeurs ainsi que de valeurs de l'insertion proposée. Ces valeurs sont spécifiées à l'aide du Insert.on_conflict_do_update.set_ paramètre. Cette paramètre accepte un dictionnaire composé de valeurs directes pour UPDATE:

de sqlalchemy.dialects.postgresql importation insérer

stmt = insérer(ma table).valeurs(identifiant='some_id', Les données='valeur insérée') do_update_stmt = stmt.on_conflict_do_update( éléments_index=[[[['id'], ensemble_=dict(Les données='valeur mise à jour') ) Connecticut.exécuter(do_update_stmt)

Pour faire référence à la ligne d’insertion proposée, l’alias spécial exclu est disponible en tant qu'attribut sur le postgresql.dml.Insert objet; cet objet est un ColumnCollection lequel alias contient toutes les colonnes de la cible table:

de sqlalchemy.dialects.postgresql importation insérer

stmt = insérer(ma table).valeurs( identifiant='some_id', Les données='valeur insérée', auteur='jlh') do_update_stmt = stmt.on_conflict_do_update( éléments_index=[[[['id'], ensemble_=dict(Les données='valeur mise à jour', auteur=stmt.exclu.auteur) ) Connecticut.exécuter(do_update_stmt)

le Insert.on_conflict_do_update () méthode accepte également une clause WHERE utilisant le Insert.on_conflict_do_update.where paramètre, qui limitera les lignes qui reçoivent un UPDATE:

de sqlalchemy.dialects.postgresql importation insérer

stmt = insérer(ma table).valeurs( identifiant='some_id', Les données='valeur insérée', auteur='jlh') on_update_stmt = stmt.on_conflict_do_update( éléments_index=[[[['id'], ensemble_=dict(Les données='valeur mise à jour', auteur=stmt.exclu.auteur) où=(ma table.c.statut == 2) ) Connecticut.exécuter(on_update_stmt)

SUR CONFLIT peut également être utilisé pour ignorer l'insertion complète d'une ligne en cas de conflit avec une contrainte unique ou d'exclusion; au dessous de ceci est illustré en utilisant le on_conflict_do_nothing () méthode:

de sqlalchemy.dialects.postgresql importation insérer

stmt = insérer(ma table).valeurs(identifiant='some_id', Les données='valeur insérée') stmt = stmt.on_conflict_do_nothing(éléments_index=[[[['id']) Connecticut.exécuter(stmt)

Si FAIRE RIEN est utilisé sans spécifier de colonne ou de contrainte, il a pour effet de sauter l'INSERT pour toute exception unique ou d'exclusion violation de contrainte qui se produit:

de sqlalchemy.dialects.postgresql importation insérer

stmt = insérer(ma table).valeurs(identifiant='some_id', Les données='valeur insérée') stmt = stmt.on_conflict_do_nothing() Connecticut.exécuter(stmt)

Nouveau dans la version 1.1: Ajout du support pour les clauses PostgreSQL ™ ON CONFLICT

Recherche en texte intégral SQLAlchemy met à disposition le PostgreSQL @@ opérateur via le ColumnElement.match () méthode sur toute expression de colonne textuelle. Sur un dialecte PostgreSQL, une expression comme celle-ci:

sélectionner([[[[quelque chose.c.texte.rencontre("chaîne de recherche")])

émettra dans la base de données:

SÉLECTIONNER texte @@ to_tsquery('chaîne de recherche') DE table

Les fonctions de recherche de texte PostgreSQL telles que to_tsquery () et to_tsvector () sont disponibles en utilisant explicitement la norme func construction. Par exemple:

sélectionner([[[[ func.to_tsvector("les gros chats mangeaient des rats").rencontre('chat et rat') ])

Emet l'équivalent de:

SÉLECTIONNER to_tsvector("les gros chats mangeaient des rats") @@ to_tsquery('chat et rat')

le postgresql.TSVECTOR type peut fournir des CAST explicites:

de sqlalchemy.dialects.postgresql importation TSVECTOR de sqlalchemy importation sélectionner, jeter sélectionner([[[[jeter("Du texte", TSVECTOR)])

produit une déclaration équivalente à:

SÉLECTIONNER JETER('Du texte' COMME TSVECTOR) COMME anon_1

Les recherches en texte intégral dans PostgreSQL sont influencées par la combinaison de: Paramètre PostgreSQL de default_text_search_config, le regconfig utilisé pour construire les index GIN / GiST, et le regconfig éventuellement passé lors d'une requête. Lorsque vous effectuez une recherche en texte intégral sur une colonne comportant un code GIN ou Index GiST déjà pré-calculé (qui est commun au texte intégral recherches), il peut être nécessaire de passer explicitement à un serveur PostgreSQL spécifique. regconfig valeur pour assurer que le planificateur de requêtes utilise l'index et ne pas recalculer la colonne à la demande. Afin de permettre cette planification explicite des requêtes, ou d’utiliser différentes stratégies de recherche, la rencontre méthode accepte un postgresql_regconfig argument de mot clé:

sélectionner([[[[ma table.c.identifiant]).où( ma table.c.Titre.rencontre('somestring', postgresql_regconfig='Anglais') )

Emet l'équivalent de:

SÉLECTIONNER ma table.identifiant DE ma table OÙ ma table.Titre @@ to_tsquery('Anglais', 'somestring')

On peut aussi spécifiquement passer dans un «Regconfig» valeur à la to_tsvector () commande comme argument initial:

sélectionner([[[[ma table.c.identifiant]).où( func.to_tsvector('Anglais', ma table.c.Titre ) .rencontre('somestring', postgresql_regconfig='Anglais') )

produit une déclaration équivalente à:

SÉLECTIONNER ma table.identifiant DE ma table OÙ to_tsvector('Anglais', ma table.Titre) @@ to_tsquery('Anglais', 'somestring')

Il est recommandé d’utiliser le EXPLIQUE ANALYSER... outil de PostgreSQL ™ pour vous assurer que vous générez des requêtes avec SQLAlchemy qui Tirez pleinement parti des index que vous avez éventuellement créés pour la recherche en texte intégral.

DE SEULEMENT… Le dialecte prend en charge le mot clé ONLY de PostgreSQL pour ne cibler que certains table dans une hiérarchie d'héritage. Ceci peut être utilisé pour produire le SÉLECTIONNER ... DE SEULEMENT, MISE À JOUR SEULEMENT ..., et EFFACER DE SEULEMENT ... syntaxes. Il utilise le mécanisme des astuces de SQLAlchemy:

# SELECTIONNER ... A PARTIR DE ... résultat = table.sélectionner().avec_hint(table, 'SEULEMENT', 'postgresql') impression résultat.fetchall()

# MISE À JOUR UNIQUEMENT ... table.mise à jour(valeurs=dict(foo='bar')).avec_hint('SEULEMENT', nom du dialecte='postgresql')

# SUPPRIMER DE SEULEMENT ... table.effacer().avec_hint('SEULEMENT', nom du dialecte='postgresql')

Options d'index spécifiques à PostgreSQL Plusieurs extensions à la Indice construct sont disponibles, spécifiques au dialecte PostgreSQL.

Index partiels Les index partiels ajoutent un critère à la définition de l’index afin que celui-ci soit appliqué à un sous-ensemble de lignes. Ceux-ci peuvent être spécifiés sur Indice en utilisant le postgresql_where argument de mot clé:

Indice('mon_index', ma table.c.identifiant, postgresql_where=ma table.c.valeur > dix)

Classes d'opérateurs PostgreSQL permet la spécification d’un classe d'opérateur pour chaque colonne de un index (voir http://www.postgresql.org/docs/8.3/interactive/indexes-opclass.html). le Indice la construction permet de les spécifier via le postgresql_ops argument de mot clé:

Indice( 'mon_index', ma table.c.identifiant, ma table.c.Les données, postgresql_ops= 'Les données': 'text_pattern_ops', 'id': 'int4_ops' )

Notez que les clés dans le postgresql_ops dictionnaire sont le nom “clé” de le Colonnec'est-à-dire le nom utilisé pour y accéder depuis le .c collection de Table, qui peut être configuré pour être différent de le nom réel de la colonne tel qu'il est exprimé dans la base de données. Si postgresql_ops doit être utilisé contre une expression SQL complexe telle que en tant qu'appel de fonction, pour l'appliquer à la colonne, il faut lui attribuer une étiquette qui est identifié dans le dictionnaire par son nom, par exemple:

Indice( 'mon_index', ma table.c.identifiant, func.inférieur(ma table.c.Les données).étiquette('data_lower'), postgresql_ops= 'data_lower': 'text_pattern_ops', 'id': 'int4_ops' )

Types d'index PostgreSQL fournit plusieurs types d’index: B-Tree, Hash, GiST et GIN, ainsi que comme la possibilité pour les utilisateurs de créer leurs propres projets (voir http://www.postgresql.org/docs/8.3/static/indexes-types.html). Ceux-ci peuvent être spécifié sur Indice en utilisant le postgresql_using argument de mot clé:

Indice('mon_index', ma table.c.Les données, postgresql_using='Gin')

La valeur transmise à l’argument du mot clé sera simplement transmise au commande CREATE INDEX sous-jacente, de sorte doit être un type d'index valide pour votre version de PostgreSQL.

Paramètres de stockage d'index PostgreSQL permet de définir des paramètres de stockage sur des index. Le stockage les paramètres disponibles dépendent de la méthode d'index utilisée par l'index. Espace de rangement les paramètres peuvent être spécifiés sur Indice en utilisant le postgresql_with argument de mot clé:

Indice('mon_index', ma table.c.Les données, postgresql_with="facteur de remplissage": 50)

PostgreSQL permet de définir le tablespace dans lequel créer l'index. Le tablespace peut être spécifié sur Indice en utilisant le postgresql_tablespace argument de mot clé:

Indice('mon_index', ma table.c.Les données, postgresql_tablespace='mon espace de tables')

Notez que la même option est disponible sur Table ainsi que.

Index avec concurremment L’option d’index CONCORDREMENT de PostgreSQL est supportée en passant le drapeau postgresql_concurrently à la Indice construction:

tbl = Table('testtbl', m, Colonne('Les données', Entier))

idx1 = Indice('test_idx1', tbl.c.Les données, postgresql_concurrently=Vrai)

La construction d’index ci-dessus rendra le DDL pour CREATE INDEX, en supposant que PostgreSQL 8.2 ou supérieur est détecté ou pour un dialecte sans connexion, comme:

CRÉER INDICE De manière concurrente test_idx1 SUR testtbl (Les données)

Pour DROP INDEX, en supposant que PostgreSQL 9.2 ou supérieur soit détecté ou pour un dialecte sans connexion, il émettra:

LAISSEZ TOMBER INDICE De manière concurrente test_idx1

Nouveau dans la version 1.1: support pour concurremment sur DROP INDEX. le Le mot clé est simultanément émis uniquement si une version suffisamment élevée de PostgreSQL est détecté sur la connexion (ou pour une connexion sans connexion) dialecte).

Lors de l'utilisation concurrente, la base de données PostgreSQL requiert que l'instruction être appelé en dehors d'un bloc de transaction. La base de données Python DBAPI même pour une seule déclaration, une transaction est présente, donc pour utiliser cette le mode «autocommit» de DBAPI doit être utilisé:

métadonnées = MetaData() table = Table( "foo", métadonnées, Colonne("id", Chaîne)) indice = Indice( "foo_idx", table.c.identifiant, postgresql_concurrently=Vrai)

avec moteur.relier() comme Connecticut: avec Connecticut.execution_options(niveau_isolement='AUTOCOMMIT'): table.créer(Connecticut)

PostgreSQL Index Reflection La base de données PostgreSQL crée implicitement un INDEX UNIQUE chaque fois que le La construction UNIQUE CONSTRAINT est utilisée. Lors de l'inspection d'une table en utilisant Inspecteur, le Inspector.get_indexes () et le Inspector.get_unique_constraints () fera rapport sur ces deux constructions distinctement; dans le cas de l'index, la clé duplicates_constraint sera présent dans l'entrée d'index s'il est détecté comme reflétant une contrainte. Lors de la réflexion en utilisant Table(..., autoload = True), l'INDICE UNIQUE est ne pas revenu dans Table.indexes quand il est détecté comme reflétant un Contrainte unique dans le Table.constraints collection.

Modifié dans la version 1.0.0: – Table la réflexion comprend maintenant Contrainte unique objets présents dans le Table.constraints collection; le backend de PostgreSQL n'inclura plus de “miroir” Indice construire dans Table.indexes si c'est détecté comme correspondant à une contrainte unique.

Options de réflexion spéciales le Inspecteur utilisé pour le backend PostgreSQL est une instance de PGInspector, qui offre des méthodes supplémentaires:

de sqlalchemy importation create_engine, inspecter

moteur = create_engine("postgresql + psycopg2: // localhost / test") insp = inspecter(moteur) # sera un PGInspector

impression(insp.get_enums())

classe sqlalchemy.dialects.postgresql.base.PGInspector(Connecticut)

Bases: sqlalchemy.engine.reflection.Inspector

get_enums(schéma = Aucun)

Retourne une liste d'objets ENUM. Chaque membre est un dictionnaire contenant ces champs:

name – nom de l'énum

schéma – le nom du schéma pour l'énumération.

visible – booléen, que cette énumération soit visible ou non dans le chemin de recherche par défaut.

étiquettes – une liste d'étiquettes de chaîne qui s'appliquent à l'énumération.

Paramètres

schéma – nom du schéma. Si aucun, le schéma par défaut (généralement «public») est utilisé. Peut également être réglé sur '*' pour indiquez des énumérations de charge pour tous les schémas.

get_foreign_table_names(schéma = Aucun)

Renvoie une liste de noms FOREIGN TABLE. Le comportement est similaire à celui de Inspector.get_table_names (), sauf que la liste est limitée aux tables qui signalent une relâchement valeur de F.

get_table_oid(nom de la table, schéma = Aucun)

Renvoie l'OID du nom de la table donnée.

get_view_names(schéma = Aucun, include = ('plain', 'matérialisé'))

Renvoyer tous les noms de vue dans schéma.

Paramètres

schéma – Facultatif, récupérez les noms d'un schéma autre que celui par défaut. Pour les devis spéciaux, utilisez quoted_name.

comprendre – spécifier les types de vues à renvoyer. Passé sous forme de valeur de chaîne (pour un type unique) ou de tuple (pour un nombre quelconque) de types). Par défaut à ('plaine', 'matérialisé').

Options de la table PostgreSQL Plusieurs options pour CREATE TABLE sont supportées directement par PostgreSQL dialecte en conjonction avec le Table construction:

Types de tableau Le dialecte PostgreSQL supporte les tableaux, à la fois en tant que types de colonne multidimensionnels ainsi que des littéraux de tableau:

Types JSON Le dialecte PostgreSQL prend en charge les types de données JSON et JSONB, y compris Le support natif de psycopg2 et celui de tous les logiciels spéciaux de PostgreSQL les opérateurs:

Type HSTORE Le type HSTORE PostgreSQL ainsi que les littéraux hstore sont pris en charge:

Types ENUM PostgreSQL a une structure TYPE pouvant être créée indépendamment qui est utilisée pour implémenter un type énuméré. Cette approche introduit des la complexité du côté SQLAlchemy en termes de quand ce type devrait être Créé et abandonné. Le type object est aussi un reflet indépendant entité. Les sections suivantes doivent être consultées:

Utiliser ENUM avec ARRAY La combinaison de ENUM et ARRAY n’est pas directement prise en charge par le backend DBAPIs à ce moment. Pour envoyer et recevoir un ARRAY of ENUM, utilisez le type de solution de contournement suivant, qui décore le postgresql.ARRAY Type de données.

de sqlalchemy importation TypeDécorateur de sqlalchemy.dialects.postgresql importation Tableau

classe ArrayOfEnum(TypeDécorateur): impl = Tableau

def bind_expression(soi, bindvalue): revenir sa.jeter(bindvalue, soi)

def result_processor(soi, dialecte, coltype): super_rp = super(ArrayOfEnum, soi).result_processor( dialecte, coltype)

def handle_raw_string(valeur): interne = ré.rencontre(r"^ (. *) $", valeur).groupe(1) revenir interne.Divisé(",") si interne autre []

def processus(valeur): si valeur est Aucun: revenir Aucun revenir super_rp(handle_raw_string(valeur)) revenir processus

Par exemple.:

Table( 'mes données', métadonnées, Colonne('id', Entier, clé primaire=Vrai), Colonne('Les données', ArrayOfEnum(ENUM('une', 'b'c', nom ='myenum')))

)

Ce type n'est pas inclus en tant que type intégré car il serait incompatible avec une DBAPI qui décide soudainement de soutenir ARRAY of ENUM directement dans une nouvelle version.

Utilisation de JSON / JSONB avec ARRAY Semblable à utiliser ENUM, pour un ARRAY of JSON / JSONB, nous devons rendre le CAST approprié, cependant les pilotes psycopg2 actuels semblent gérer le résultat pour ARRAY of JSON automatiquement, le type est donc plus simple:

classe CastingArray(Tableau): def bind_expression(soi, bindvalue): revenir sa.jeter(bindvalue, soi)

Par exemple.:

Table( 'mes données', métadonnées, Colonne('id', Entier, clé primaire=Vrai), Colonne('Les données', CastingArray(JSONB)) )

Types de données PostgreSQL Comme avec tous les dialectes SQLAlchemy, tous les types UPPERCASE connus pour être valables avec PostgreSQL sont importables à partir du dialecte de niveau supérieur, que ce soit ils proviennent de sqlalchemy.types ou du dialecte local:

de sqlalchemy.dialects.postgresql importation Tableau, BIGINT, BIT, BOOLÉAN, BYTEA, CARBONISER, CIDR, DATE, DOUBLE PRECISION, ENUM, FLOTTE, HSTORE, INET, ENTIER, INTERVALLE, JSON, JSONB, MACADDR, ARGENT, NUMERIC, OID, REAL, SMALLINT, TEXT, TEMPS, TIMESTAMP, UUID, VARCHAR, INT4RANGE, INT8RANGE, NUMRANGE, DATERANGE, TSRANGE, TSTZRANGE, TSVECTOR

Types which are specific to PostgreSQL, or have PostgreSQL-specific construction arguments, are as follows:

class sqlalchemy.dialects.postgresql.aggregate_order_by(cible, *order_by)

Bases: sqlalchemy.sql.expression.ColumnElement Represent a PostgreSQL aggregate order by expression. E.g.:

de sqlalchemy.dialects.postgresql importation aggregate_order_by expr = func.array_agg(aggregate_order_by(table.c.une, table.c.b.desc())) stmt = sélectionner([[[[expr])

would represent the expression:

SELECT array_agg(une ORDER BY b DESC) FROM table;

Similarly:

expr = func.string_agg( table.c.une, aggregate_order_by(literal_column("','"), table.c.une) ) stmt = sélectionner([[[[expr])

Would represent:

SELECT string_agg(une, ',' ORDER BY une) FROM table;

Changed in version 1.2.13: – the ORDER BY argument may be multiple terms

class sqlalchemy.dialects.postgresql.array(clauses, **kw)

Bases: sqlalchemy.sql.expression.Tuple A PostgreSQL ARRAY literal. This is used to produce ARRAY literals in SQL expressions, e.g.:

de sqlalchemy.dialects.postgresql importation array de sqlalchemy.dialects importation postgresql de sqlalchemy importation sélectionner, func

stmt = sélectionner([[[[ array([[[[1,2]) + array([[[[3,4,5]) ])

impression(stmt.compile(dialect=postgresql.dialect()))

Produces the SQL:

SELECT ARRAY[[[[%(param_1)s, %(param_2)s] || ARRAY[[[[%(param_3)s, %(param_4)s, %(param_5)s]) AS anon_1

An instance of array will always have the datatype ARRAY. The “inner” type of the array is inferred from the values present, unless the type_ keyword argument is passed:

array([[[['foo', 'bar'], type_=CHAR)

Multidimensional arrays are produced by nesting array constructs. The dimensionality of the final ARRAY type is calculated by recursively adding the dimensions of the inner ARRAY type:

stmt = sélectionner([[[[ array([[[[ array([[[[1, 2]), array([[[[3, 4]), array([[[[colonne('q'), colonne('x')]) ]) ]) impression(stmt.compile(dialect=postgresql.dialect()))

Produces:

SELECT ARRAY[[[[ARRAY[[[[%(param_1)s, %(param_2)s], ARRAY[[[[%(param_3)s, %(param_4)s], ARRAY[[[[q, x]] AS anon_1

New in version 1.3.6: added support for multidimensional array literals

class sqlalchemy.dialects.postgresql.ARRAY(item_type, as_tuple=False, dimensions=None, zero_indexes=False)

Bases: sqlalchemy.types.ARRAY PostgreSQL ARRAY type. le postgresql.ARRAY type is constructed in the same way as the core types.ARRAY type; a member type is required, and a number of dimensions is recommended if the type is to be used for more than one dimension:

de sqlalchemy.dialects importation postgresql

mytable = Table("mytable", metadata, Column("data", postgresql.ARRAY(Integer, dimensions=2)) )

le postgresql.ARRAY type provides all operations defined on the core types.ARRAY type, including support for “dimensions”, indexed access, and simple matching such as types.ARRAY.Comparator.any() et types.ARRAY.Comparator.all(). postgresql.ARRAY class also provides PostgreSQL-specific methods for containment operations, including postgresql.ARRAY.Comparator.contains() postgresql.ARRAY.Comparator.contained_by(), et postgresql.ARRAY.Comparator.overlap(), e.g.:

mytable.c.Les données.contient([[[[1, 2])

le postgresql.ARRAY type may not be supported on all PostgreSQL DBAPIs; it is currently known to work on psycopg2 only. De plus, le postgresql.ARRAY type does not work directly in conjunction with the ENUM type. For a workaround, see the special type at Using ENUM with ARRAY.

class Comparator(expr)

Bases: sqlalchemy.types.Comparator Define comparison operations for ARRAY. Note that these operations are in addition to those provided by the base types.ARRAY.Comparator class, including types.ARRAY.Comparator.any() et types.ARRAY.Comparator.all().

contained_by(other)

Boolean expression. Test if elements are a proper subset of the elements of the argument array expression.

contient(other, **kwargs)

Boolean expression. Test if elements are a superset of the elements of the argument array expression.

overlap(other)

Boolean expression. Test if array has elements in common with an argument array expression.

__init__(item_type, as_tuple=False, dimensions=None, zero_indexes=False)

Construct an ARRAY. E.g.:

Column('myarray', ARRAY(Integer))

Arguments are:

Paramètres

item_type – The data type of items of this array. Note that dimensionality is irrelevant here, so multi-dimensional arrays like INTEGER[][], are constructed as ARRAY(Integer), not as ARRAY(ARRAY(Integer)) or such.

as_tuple=False – Specify whether return results should be converted to tuples from lists. DBAPIs such as psycopg2 return lists by default. When tuples are returned, the results are hashable.

dimensions – if non-None, the ARRAY will assume a fixed number of dimensions. This will cause the DDL emitted for this ARRAY to include the exact number of bracket clauses [], and will also optimize the performance of the type overall. Note that PG arrays are always implicitly “non-dimensioned”, meaning they can store any number of dimensions no matter how they were declared.

zero_indexes=False – when True, index values will be converted between Python zero-based and PostgreSQL one-based indexes, e.g. a value of one will be added to all index values before passing to the database.

sqlalchemy.dialects.postgresql.array_agg(*arg, **kw)

PostgreSQL-specific form of array_agg, ensures return type is postgresql.ARRAY and not the plain types.ARRAY, unless an explicit type_ is passed.

sqlalchemy.dialects.postgresql.Any(other, arrexpr, operator=)

A synonym for the ARRAY.Comparator.any() method. This method is legacy and is here for backwards-compatibility.

sqlalchemy.dialects.postgresql.Tout(other, arrexpr, operator=)

A synonym for the ARRAY.Comparator.all() method. This method is legacy and is here for backwards-compatibility.

class sqlalchemy.dialects.postgresql.BIT(length=None, varying=False)

Bases: sqlalchemy.types.TypeEngine

class sqlalchemy.dialects.postgresql.BYTEA(length=None)

Bases: sqlalchemy.types.LargeBinary

__init__(length=None)

Construct a LargeBinary type.

Paramètres

length – optional, a length for the column for use in DDL statements, for those binary types that accept a length, such as the MySQL BLOB type.

class sqlalchemy.dialects.postgresql.CIDR

Bases: sqlalchemy.types.TypeEngine

class sqlalchemy.dialects.postgresql.DOUBLE_PRECISION(precision=None, asdecimal=False, decimal_return_scale=None)

Bases: sqlalchemy.types.Float

__init__(precision=None, asdecimal=False, decimal_return_scale=None)

Construct a Float.

Paramètres

précision – the numeric precision for use in DDL CREATE TABLE.

asdecimal – the same flag as that of Numeric, but defaults to Faux. Note that setting this flag to True results in floating point conversion.

decimal_return_scale – Default scale to use when converting from floats to Python decimals. Floating point values will typically be much longer due to decimal inaccuracy, and most floating point database types don’t have a notion of “scale”, so by default the float type looks for the first ten decimal places when converting. Specifying this value will override that length. Note that the MySQL float types, which do include “scale”, will use “scale” as the default for decimal_return_scale, if not otherwise specified.

class sqlalchemy.dialects.postgresql.ENUM(*enums, **kw)

Bases: sqlalchemy.types.NativeForEmulated, sqlalchemy.types.Enum PostgreSQL ENUM type. This is a subclass of types.Enum which includes support for PG’s CREATE TYPE et DROP TYPE. When the builtin type types.Enum is used and the Enum.native_enum flag is left at its default of True, the PostgreSQL backend will use a postgresql.ENUM type as the implementation, so the special create/drop rules will be used. The create/drop behavior of ENUM is necessarily intricate, due to the awkward relationship the ENUM type has in relationship to the parent table, in that it may be “owned” by just a single table, or may be shared among many tables. When using types.Enum ou postgresql.ENUM in an “inline” fashion, the CREATE TYPE et DROP TYPE is emitted corresponding to when the Table.create() et Table.drop() methods are called:

table = Table('sometable', metadata, Column('some_enum', ENUM('a', 'b', 'c', name='myenum')) )

table.create(engine) # will emit CREATE ENUM and CREATE TABLE table.drop(engine) # will emit DROP TABLE and DROP ENUM

To use a common enumerated type between multiple tables, the best practice is to declare the types.Enum ou postgresql.ENUM independently, and associate it with the MetaData object itself:

my_enum = ENUM('a', 'b', 'c', name='myenum', metadata=metadata)

t1 = Table('sometable_one', metadata, Column('some_enum', myenum) )

t2 = Table('sometable_two', metadata, Column('some_enum', myenum) )

When this pattern is used, care must still be taken at the level of individual table creates. Emitting CREATE TABLE without also specifying checkfirst=True will still cause issues:

t1.create(engine) # will fail: no such type 'myenum'

If we specify checkfirst=True, the individual table-level create operation will check for the ENUM and create if not exists:

# will check if enum exists, and emit CREATE TYPE if not t1.create(engine, checkfirst=True)

When using a metadata-level ENUM type, the type will always be created and dropped if either the metadata-wide create/drop is called:

metadata.create_all(engine) # will emit CREATE TYPE metadata.drop_all(engine) # will emit DROP TYPE

The type can also be created and dropped directly:

my_enum.create(engine) my_enum.drop(engine)

Changed in version 1.0.0: The PostgreSQL postgresql.ENUM type now behaves more strictly with regards to CREATE/DROP. A metadata-level ENUM type will only be created and dropped at the metadata level, not the table level, with the exception of table.create(checkfirst=True). le table.drop() call will now emit a DROP TYPE for a table-level enumerated type.

__init__(*enums, **kw)

Construct an ENUM. Arguments are the same as that of types.Enum, but also including the following parameters.

Paramètres

create_type – Defaults to True. Indicates that CREATE TYPE should be emitted, after optionally checking for the presence of the type, when the parent table is being created; and additionally cette DROP TYPE is called when the table is dropped. Quand Faux, no check will be performed and no CREATE TYPE ou DROP TYPE is emitted, unless create() ou drop() are called directly. Setting to Faux is helpful when invoking a creation scheme to a SQL file without access to the actual database – le create() et drop() methods can be used to emit SQL to a target bind.

create(bind=None, checkfirst=True)

Émettre CREATE TYPE for this ENUM. If the underlying dialect does not support PostgreSQL CREATE TYPE, no action is taken.

Paramètres

bind – a connectable Moteur, Connection, or similar object to emit SQL.

checkfirst – if True, a query against the PG catalog will be first performed to see if the type does not exist already before creating.

drop(bind=None, checkfirst=True)

Émettre DROP TYPE for this ENUM. If the underlying dialect does not support PostgreSQL DROP TYPE, no action is taken.

Paramètres

bind – a connectable Moteur, Connection, or similar object to emit SQL.

checkfirst – if True, a query against the PG catalog will be first performed to see if the type actually exists before dropping.

class sqlalchemy.dialects.postgresql.HSTORE(text_type=None)

Bases: sqlalchemy.types.Indexable, sqlalchemy.types.Concatenable, sqlalchemy.types.TypeEngine Represent the PostgreSQL HSTORE type. le HSTORE type stores dictionaries containing strings, e.g.:

data_table = Table('data_table', metadata, Column('id', Integer, primary_key=True), Column('data', HSTORE) )

avec engine.connect() comme conn: conn.execute( data_table.insérer(), Les données = "key1": "value1", "key2": "value2" )

HSTORE provides for a wide range of operations, including:

Index operations:

data_table.c.Les données[[[['some key'] == 'some value'

Containment operations:

data_table.c.Les données.has_key('some key')

data_table.c.Les données.has_all([[[['one', 'two', 'three'])

Concatenation:

data_table.c.Les données + "k1": "v1"

For a full list of special methods see HSTORE.comparator_factory. For usage with the SQLAlchemy ORM, it may be desirable to combine the usage of HSTORE avec MutableDict dictionary now part of the sqlalchemy.ext.mutable extension. This extension will allow “in-place” changes to the dictionary, e.g. addition of new keys or replacement/removal of existing keys to/from the current dictionary, to produce events which will be detected by the unit of work:

de sqlalchemy.ext.mutable importation MutableDict

class MyClass(Base): __tablename__ = 'data_table'

identifiant = Column(Integer, primary_key=True) Les données = Column(MutableDict.as_mutable(HSTORE))

my_object = session.query(MyClass).un()

# in-place mutation, requires Mutable extension # in order for the ORM to detect my_object.Les données[[[['some_key'] = 'some value'

session.commit()

When the sqlalchemy.ext.mutable extension is not used, the ORM will not be alerted to any changes to the contents of an existing dictionary, unless that dictionary value is re-assigned to the HSTORE-attribute itself, thus generating a change event.

Voir également hstore – render the PostgreSQL hstore() une fonction.

class Comparator(expr)

Bases: sqlalchemy.types.Comparator, sqlalchemy.types.Comparator Define comparison operations for HSTORE.

array()

Text array expression. Returns array of alternating keys and valeurs.

contained_by(other)

Boolean expression. Test if keys are a proper subset of the keys of the argument jsonb expression.

contient(other, **kwargs)

Boolean expression. Test if keys (or array) are a superset of/contained the keys of the argument jsonb expression.

defined(clé)

Boolean expression. Test for presence of a non-NULL value for the key. Note that the key may be a SQLA expression.

effacer(clé)

HStore expression. Returns the contents of this hstore with the given key deleted. Note that the key may be a SQLA expression.

has_all(other)

Boolean expression. Test for presence of all keys in jsonb

has_any(other)

Boolean expression. Test for presence of any key in jsonb

has_key(other)

Boolean expression. Test for presence of a key. Note that the key may be a SQLA expression.

keys()

Text array expression. Returns array of keys.

matrix()

Text array expression. Returns array of [key, value] pairs.

slice(array)

HStore expression. Returns a subset of an hstore defined by array of keys.

vals()

Text array expression. Returns array of values.

__init__(text_type=None)

Construct a new HSTORE.

Paramètres

text_type – the type that should be used for indexed values. Defaults to types.Text.

bind_processor(dialect)

Return a conversion function for processing bind values. Returns a callable which will receive a bind parameter value as the sole positional argument and will return a value to send to the DB-API. If processing is not necessary, the method should return None.

Paramètres

dialect – Dialect instance in use.

comparator_factory

alias of HSTORE.Comparator

result_processor(dialect, coltype)

Return a conversion function for processing result row values. Returns a callable which will receive a result row column value as the sole positional argument and will return a value to return to the user. If processing is not necessary, the method should return None.

Paramètres

class sqlalchemy.dialects.postgresql.hstore(*args, **kwargs)

Bases: sqlalchemy.sql.functions.GenericFunction Construct an hstore value within a SQL expression using the PostgreSQL hstore() une fonction. le hstore function accepts one or two arguments as described in the PostgreSQL documentation. E.g.:

de sqlalchemy.dialects.postgresql importation array, hstore

sélectionner([[[[hstore('key1', 'value1')])

sélectionner([[[[ hstore( array([[[['key1', 'key2', 'key3']), array([[[['value1', 'value2', 'value3']) ) ])

Voir également HSTORE – the PostgreSQL HSTORE datatype.

type

alias of HSTORE

class sqlalchemy.dialects.postgresql.INET

Bases: sqlalchemy.types.TypeEngine

class sqlalchemy.dialects.postgresql.INTERVAL(precision=None, fields=None)

Bases: sqlalchemy.types.NativeForEmulated, sqlalchemy.types._AbstractInterval PostgreSQL INTERVAL type. The INTERVAL type may not be supported on all DBAPIs. It is known to work on psycopg2 and not pg8000 or zxjdbc.

__init__(precision=None, fields=None)

Construct an INTERVAL.

Paramètres

précision – optional integer precision value

fields – string fields specifier. allows storage of fields to be limited, such as "YEAR", "MONTH", "DAY TO HOUR", etc.

class sqlalchemy.dialects.postgresql.JSON(none_as_null=False, astext_type=None)

Bases: sqlalchemy.types.JSON Represent the PostgreSQL JSON type. This type is a specialization of the Core-level types.JSON type. Be sure to read the documentation for types.JSON for important tips regarding treatment of NULL values and ORM use. The operators provided by the PostgreSQL version of JSON include:

Index operations (the -> operator):

data_table.c.Les données[[[['some key']

data_table.c.Les données[[[[5]

Index operations returning text (the ->> operator):

data_table.c.Les données[[[['some key'].astext == 'some value'

Index operations with CAST (equivalent to CAST(col ->> ['some['some['some['some key'] AS )):

data_table.c.Les données[[[['some key'].astext.jeter(Integer) == 5

Path index operations (the #> operator):

data_table.c.Les données[([([([('key_1', 'key_2', 5, ..., 'key_n')]

Path index operations returning text (the #>> operator):

data_table.c.Les données[([([([('key_1', 'key_2', 5, ..., 'key_n')].astext == 'some value'

Changed in version 1.1: le ColumnElement.cast() operator on JSON objects now requires that the JSON.Comparator.astext modifier be called explicitly, if the cast works only from a textual string.

Index operations return an expression object whose type defaults to JSON by default, so that further JSON-oriented instructions may be called upon the result type. Custom serializers and deserializers are specified at the dialect level, that is using create_engine(). The reason for this is that when using psycopg2, the DBAPI only allows serializers at the per-cursor or per-connection level. E.g.:

engine = create_engine("postgresql://scott:tiger@localhost/test", json_serializer=my_serialize_fn, json_deserializer=my_deserialize_fn )

When using the psycopg2 dialect, the json_deserializer is registered against the database using psycopg2.extras.register_default_json.

class Comparator(expr)

Bases: sqlalchemy.types.Comparator Define comparison operations for JSON.

property astext

On an indexed expression, use the “astext” (e.g. “->>”) conversion when rendered in SQL. E.g.:

sélectionner([[[[data_table.c.Les données[[[['some key'].astext])

__init__(none_as_null=False, astext_type=None)

Construct a JSON type.

Paramètres

none_as_null – if True, persist the value None as a SQL NULL value, not the JSON encoding of nul. Note that when this flag is False, the null() construct can still be used to persist a NULL value:

de sqlalchemy importation nul conn.execute(table.insérer(), Les données=nul())

Changed in version 0.9.8: – Added none_as_null, et null() is now supported in order to persist a NULL value.

astext_type – the type to use for the JSON.Comparator.astext accessor on indexed attributes. Defaults to types.Text.

comparator_factory

alias of JSON.Comparator

class sqlalchemy.dialects.postgresql.JSONB(none_as_null=False, astext_type=None)

Bases: sqlalchemy.dialects.postgresql.json.JSON Represent the PostgreSQL JSONB type. le JSONB type stores arbitrary JSONB format data, e.g.:

data_table = Table('data_table', metadata, Column('id', Integer, primary_key=True), Column('data', JSONB) )

avec engine.connect() comme conn: conn.execute( data_table.insérer(), Les données = "key1": "value1", "key2": "value2" )

le JSONB type includes all operations provided by JSON, including the same behaviors for indexing operations. It also adds additional operators specific to JSONB, including JSONB.Comparator.has_key(), JSONB.Comparator.has_all(), JSONB.Comparator.has_any(), JSONB.Comparator.contains(), et JSONB.Comparator.contained_by(). Comme le JSON type, the JSONB type does not detect in-place changes when used with the ORM, unless the sqlalchemy.ext.mutable extension is used. Custom serializers and deserializers are shared with the JSON class, using the json_serializer et json_deserializer keyword arguments. These must be specified at the dialect level using create_engine(). When using psycopg2, the serializers are associated with the jsonb type using psycopg2.extras.register_default_jsonb on a per-connection basis, in the same way that psycopg2.extras.register_default_json is used to register these handlers with the json type.

class Comparator(expr)

Bases: sqlalchemy.dialects.postgresql.json.Comparator Define comparison operations for JSON.

contained_by(other)

Boolean expression. Test if keys are a proper subset of the keys of the argument jsonb expression.

contient(other, **kwargs)

Boolean expression. Test if keys (or array) are a superset of/contained the keys of the argument jsonb expression.

has_all(other)

Boolean expression. Test for presence of all keys in jsonb

has_any(other)

Boolean expression. Test for presence of any key in jsonb

has_key(other)

Boolean expression. Test for presence of a key. Note that the key may be a SQLA expression.

comparator_factory

alias of JSONB.Comparator

class sqlalchemy.dialects.postgresql.MACADDR

Bases: sqlalchemy.types.TypeEngine

class sqlalchemy.dialects.postgresql.ARGENT

Bases: sqlalchemy.types.TypeEngine Provide the PostgreSQL MONEY type.

class sqlalchemy.dialects.postgresql.OID

Bases: sqlalchemy.types.TypeEngine Provide the PostgreSQL OID type.

class sqlalchemy.dialects.postgresql.REAL(precision=None, asdecimal=False, decimal_return_scale=None)

Bases: sqlalchemy.types.Float The SQL REAL type.

__init__(precision=None, asdecimal=False, decimal_return_scale=None)

Construct a Float.

Paramètres

précision – the numeric precision for use in DDL CREATE TABLE.

asdecimal – the same flag as that of Numeric, but defaults to Faux. Note that setting this flag to True results in floating point conversion.

decimal_return_scale – Default scale to use when converting from floats to Python decimals. Floating point values will typically be much longer due to decimal inaccuracy, and most floating point database types don’t have a notion of “scale”, so by default the float type looks for the first ten decimal places when converting. Specifying this value will override that length. Note that the MySQL float types, which do include “scale”, will use “scale” as the default for decimal_return_scale, if not otherwise specified.

class sqlalchemy.dialects.postgresql.REGCLASS

Bases: sqlalchemy.types.TypeEngine Provide the PostgreSQL REGCLASS type.

class sqlalchemy.dialects.postgresql.TSVECTOR

Bases: sqlalchemy.types.TypeEngine le postgresql.TSVECTOR type implements the PostgreSQL text search type TSVECTOR. It can be used to do full text queries on natural language documents.

class sqlalchemy.dialects.postgresql.UUID(as_uuid=False)

Bases: sqlalchemy.types.TypeEngine PostgreSQL UUID type. Represents the UUID column type, interpreting data either as natively returned by the DBAPI or as Python uuid objects. The UUID type may not be supported on all DBAPIs. It is known to work on psycopg2 and not pg8000.

__init__(as_uuid=False)

Construct a UUID type.

Paramètres

as_uuid=False – if True, values will be interpreted as Python uuid objects, converting to/from string via the DBAPI.

Range Types The new range column types found in PostgreSQL 9.2 onwards are catered for by the following types:

class sqlalchemy.dialects.postgresql.INT4RANGE

Bases: sqlalchemy.dialects.postgresql.ranges.RangeOperators, sqlalchemy.types.TypeEngine Represent the PostgreSQL INT4RANGE type.

class sqlalchemy.dialects.postgresql.INT8RANGE

Bases: sqlalchemy.dialects.postgresql.ranges.RangeOperators, sqlalchemy.types.TypeEngine Represent the PostgreSQL INT8RANGE type.

class sqlalchemy.dialects.postgresql.NUMRANGE

Bases: sqlalchemy.dialects.postgresql.ranges.RangeOperators, sqlalchemy.types.TypeEngine Represent the PostgreSQL NUMRANGE type.

class sqlalchemy.dialects.postgresql.DATERANGE

Bases: sqlalchemy.dialects.postgresql.ranges.RangeOperators, sqlalchemy.types.TypeEngine Represent the PostgreSQL DATERANGE type.

class sqlalchemy.dialects.postgresql.TSRANGE

Bases: sqlalchemy.dialects.postgresql.ranges.RangeOperators, sqlalchemy.types.TypeEngine Represent the PostgreSQL TSRANGE type.

class sqlalchemy.dialects.postgresql.TSTZRANGE

Bases: sqlalchemy.dialects.postgresql.ranges.RangeOperators, sqlalchemy.types.TypeEngine Represent the PostgreSQL TSTZRANGE type.

The types above get most of their functionality from the following mixin:

class sqlalchemy.dialects.postgresql.ranges.RangeOperators

This mixin provides functionality for the Range Operators listed in Table 9-44 of the postgres documentation for Range Functions and Operators. It is used by all the range types provided in the postgres dialect and can likely be used for any range types you create yourself. No extra support is provided for the Range Functions listed in Table 9-45 of the postgres documentation. For these, the normal func() object should be used.

class comparator_factory(expr)

Bases: sqlalchemy.types.Comparator Define comparison operations for range types.

__ne__(other)

Boolean expression. Returns true if two ranges are not equal

adjacent_to(other)

Boolean expression. Returns true if the range in the column is adjacent to the range in the operand.

contained_by(other)

Boolean expression. Returns true if the column is contained within the right hand operand.

contient(other, **kw)

Boolean expression. Returns true if the right hand operand, which can be an element or a range, is contained within the column.

not_extend_left_of(other)

Boolean expression. Returns true if the range in the column does not extend left of the range in the operand.

not_extend_right_of(other)

Boolean expression. Returns true if the range in the column does not extend right of the range in the operand.

overlaps(other)

Boolean expression. Returns true if the column overlaps (has points in common with) the right hand operand.

strictly_left_of(other)

Boolean expression. Returns true if the column is strictly left of the right hand operand.

strictly_right_of(other)

Boolean expression. Returns true if the column is strictly right of the right hand operand.

Attention The range type DDL support should work with any PostgreSQL DBAPI driver, however the data types returned may vary. If you are using psycopg2, it’s recommended to upgrade to version 2.5 or later before using these column types.

When instantiating models that use these column types, you should pass whatever data type is expected by the DBAPI driver you’re using for the column type. Pour psycopg2 these are psycopg2.extras.NumericRange, psycopg2.extras.DateRange, psycopg2.extras.DateTimeRange et psycopg2.extras.DateTimeTZRange or the class you’ve registered with psycopg2.extras.register_range. Par exemple:

de psycopg2.extras importation DateTimeRange de sqlalchemy.dialects.postgresql importation TSRANGE

class RoomBooking(Base):

__tablename__ = 'room_booking'

room = Column(Integer(), primary_key=True) pendant = Column(TSRANGE())

booking = RoomBooking( room=101, pendant=DateTimeRange(datetime(2013, 3, 23), None) )

PostgreSQL Constraint Types SQLAlchemy supports PostgreSQL EXCLUDE constraints via the ExcludeConstraint class:

class sqlalchemy.dialects.postgresql.ExcludeConstraint(*elements, **kw)

Bases: sqlalchemy.schema.ColumnCollectionConstraint A table-level EXCLUDE constraint. Defines an EXCLUDE constraint as described in the postgres documentation.

__init__(*elements, **kw)

Créé un ExcludeConstraint object. E.g.:

const = ExcludeConstraint( (Column('period'), '&&'), (Column('group'), '='), where=(Column('group') != 'some group') )

The constraint is normally embedded into the Table construct directly, or added later using append_constraint():

some_table = Table( 'some_table', metadata, Column('id', Integer, primary_key=True), Column('period', TSRANGE()), Column('group', Chaîne) )

some_table.append_constraint( ExcludeConstraint( (some_table.c.period, '&&'), (some_table.c.group, '='), where=some_table.c.group != 'some group', name='some_table_excl_const' ) )

Paramètres

*elements – A sequence of two tuples of the form (column, operator) where “column” is a SQL expression element or a raw SQL string, most typically a Column object, and “operator” is a string containing the operator to use. In order to specify a column name when a Column object is not available, while ensuring that any necessary quoting rules take effect, an ad-hoc Column ou sql.expression.column() object should be used.

name – Optional, the in-database name of this constraint.

deferrable – Optional bool. If set, emit DEFERRABLE or NOT DEFERRABLE when issuing DDL for this constraint.

initialement – Optional string. If set, emit INITIALLY when issuing DDL for this constraint.

using – Optional string. If set, emit USING when issuing DDL for this constraint. Defaults to ‘gist’.

where – Optional SQL expression construct or literal SQL string. If set, emit WHERE when issuing DDL for this constraint.

Attention le ExcludeConstraint.where argument to ExcludeConstraint can be passed as a Python string argument, which will be treated as trusted SQL text and rendered as given. DO NOT PASS UNTRUSTED INPUT TO THIS PARAMETER.

Par exemple: de sqlalchemy.dialects.postgresql importation ExcludeConstraint, TSRANGE

class RoomBooking(Base):

__tablename__ = 'room_booking'

room = Column(Integer(), primary_key=True) pendant = Column(TSRANGE())

__table_args__ = ( ExcludeConstraint(('room', '='), ('during', '&&')), )

PostgreSQL DML Constructs

sqlalchemy.dialects.postgresql.dml.insérer(table, values=None, inline=False, bind=None, prefixes=None, returning=None, return_defaults=False, **dialect_kw)

Construct a new Insert object. This constructor is mirrored as a public API function; voir insert() for a full usage and argument description.

class sqlalchemy.dialects.postgresql.dml.Insert(table, values=None, inline=False, bind=None, prefixes=None, returning=None, return_defaults=False, **dialect_kw)

Bases: sqlalchemy.sql.expression.Insert PostgreSQL-specific implementation of INSERT. Adds methods for PG-specific syntaxes such as ON CONFLICT.

excluded

Provide the excluded namespace for an ON CONFLICT statement PG’s ON CONFLICT clause allows reference to the row that would be inserted, known as excluded. This attribute provides all columns in this row to be referenceable.

on_conflict_do_nothing(constraint=None, index_elements=None, index_where=None)

Specifies a DO NOTHING action for ON CONFLICT clause. le constraint et index_elements arguments are optional, but only one of these can be specified.

Paramètres

constraint – The name of a unique or exclusion constraint on the table, or the constraint object itself if it has a .name attribute.

index_elements – A sequence consisting of string column names, Column objects, or other column expression objects that will be used to infer a target index.

index_where – Additional WHERE criterion that can be used to infer a conditional target index.

on_conflict_do_update(constraint=None, index_elements=None, index_where=None, set_=None, where=None)

Specifies a DO UPDATE SET action for ON CONFLICT clause. Either the constraint ou index_elements argument is required, but only one of these can be specified.

Paramètres

constraint – The name of a unique or exclusion constraint on the table, or the constraint object itself if it has a .name attribute.

index_elements – A sequence consisting of string column names, Column objects, or other column expression objects that will be used to infer a target index.

index_where – Additional WHERE criterion that can be used to infer a conditional target index.

set_ – Required argument. A dictionary or other mapping object with column names as keys and expressions or literals as values, specifying the SET actions to take. If the target Column specifies a “.key” attribute distinct from the column name, that key should be used.

Attention This dictionary does ne pas take into account Python-specified default UPDATE values or generation functions, e.g. those specified using Column.onupdate. These values will not be exercised for an ON CONFLICT style of UPDATE, unless they are manually specified in the Insert.on_conflict_do_update.set_ dictionary.

where – Optional argument. If present, can be a literal SQL string or an acceptable expression for a WHERE clause that restricts the rows affected by DO UPDATE SET. Rows not meeting the WHERE condition will not be updated (effectively a DO NOTHING for those rows).

psycopg2 Support for the PostgreSQL database via the psycopg2 driver.

DBAPI Documentation and download information (if applicable) for psycopg2 is available at: http://pypi.python.org/pypi/psycopg2/

Connecting Connect String:

postgresql+psycopg2://user:password@host:port/dbname[?key=value&key=value...]

psycopg2 Connect Arguments psycopg2-specific keyword arguments which are accepted by create_engine() sont:

server_side_cursors: Enable the usage of “server side cursors” for SQL statements which support this feature. What this essentially means from a psycopg2 point of view is that the cursor is created using a name, e.g. connection.cursor('some name'), which has the effect that result rows are not immediately pre-fetched and buffered after statement execution, but are instead left on the server and only retrieved as needed. SQLAlchemy’s ResultProxy uses special row-buffering behavior when this feature is enabled, such that groups of 100 rows at a time are fetched over the wire to reduce conversational overhead. Note that the Connection.execution_options.stream_results execution option is a more targeted way of enabling this mode on a per-execution basis.

use_native_unicode: Enable the usage of Psycopg2 “native unicode” mode per connection. True by default.

isolation_level: This option, available for all PostgreSQL dialects, comprend le AUTOCOMMIT isolation level when using the psycopg2 dialect.

client_encoding: sets the client encoding in a libpq-agnostic way, using psycopg2’s set_client_encoding() method.

executemany_mode, executemany_batch_page_size, executemany_values_page_size: Allows use of psycopg2 extensions for optimizing “executemany”-stye queries. See the referenced section below for details.

use_batch_mode: this is the previous setting used to affect “executemany” mode and is now deprecated.

Unix Domain Connections psycopg2 supports connecting via Unix domain connections. When the hôte portion of the URL is omitted, SQLAlchemy passes None to psycopg2, which specifies Unix-domain communication rather than TCP/IP communication:

create_engine("postgresql+psycopg2://user:password@/dbname")

By default, the socket file used is to connect to a Unix-domain socket dans /tmp, or whatever socket directory was specified when PostgreSQL was built. This value can be overridden by passing a pathname to psycopg2, using hôte as an additional keyword argument:

create_engine("postgresql+psycopg2://user:password@/dbname?host=/var/lib/postgresql")

Empty DSN Connections / Environment Variable Connections The psycopg2 DBAPI can connect to PostgreSQL by passing an empty DSN to the libpq client library, which by default indicates to connect to a localhost PostgreSQL database that is open for “trust” connections. This behavior can be further tailored using a particular set of environment variables which are prefixed with PG_..., which are consumed by libpq to take the place of any or all elements of the connection string. For this form, the URL can be passed without any elements other than the initial scheme:

engine = create_engine('postgresql+psycopg2://')

In the above form, a blank “dsn” string is passed to the psycopg2.connect() function which in turn represents an empty DSN passed to libpq.

New in version 1.3.2: support for parameter-less connections with psycopg2.

Voir également Environment Variables – PostgreSQL documentation on how to use PG_... environment variables for connections.

Per-Statement/Connection Execution Options The following DBAPI-specific options are respected when used with Connection.execution_options(), Executable.execution_options(), Query.execution_options(), in addition to those not specific to DBAPIs:

isolation_level – Set the transaction isolation level for the lifespan d'un Connection (can only be set on a connection, not a statement or query). See Psycopg2 Transaction Isolation Level.

stream_results – Enable or disable usage of psycopg2 server side cursors – this feature makes use of “named” cursors in combination with special result handling methods so that result rows are not fully buffered. Si None or not set, the server_side_cursors option of the Moteur est utilisé.

max_row_buffer – when using stream_results, an integer value that specifies the maximum number of rows to buffer at a time. This is interpreted by the BufferedRowResultProxy, and if omitted the buffer will grow to ultimately store 1000 rows at a time.

Psycopg2 Fast Execution Helpers Modern versions of psycopg2 include a feature known as Fast Execution Helpers , which have been shown in benchmarking to improve psycopg2’s executemany() performance, primarily with INSERT statements, by multiple orders of magnitude. SQLAlchemy allows this extension to be used for all executemany() style calls invoked by an Moteur when used with multiple parameter ensembles, which includes the use of this feature both by the Core as well as by the ORM for inserts of objects with non-autogenerated primary key values, by adding the executemany_mode flag to create_engine():

engine = create_engine( "postgresql+psycopg2://scott:tiger@host/dbname", executemany_mode='batch')

Changed in version 1.3.7: – le use_batch_mode flag has been superseded by a new parameter executemany_mode which provides support both for psycopg2’s execute_batch helper as well as the execute_values helper.

Possible options for executemany_mode include:

None – By default, psycopg2’s extensions are not used, and the usual cursor.executemany() method is used when invoking batches of statements.

'batch' – Uses psycopg2.extras.execute_batch so that multiple copies of a SQL query, each one corresponding to a parameter set passed to executemany(), are joined into a single SQL string separated by a semicolon. This is the same behavior as was provided by the use_batch_mode=True flag.

'values'– For Core insert() constructs only (including those emitted by the ORM automatically), the psycopg2.extras.execute_values extension is used so that multiple parameter sets are grouped into a single INSERT statement and joined together with multiple VALUES expressions. Cette method requires that the string text of the VALUES clause inside the INSERT statement is manipulated, so is only supported with a compiled insert() construct where the format is predictable. For all other constructs, including plain textual INSERT statements not rendered by the SQLAlchemy expression language compiler, the psycopg2.extras.execute_batch method is used. It is therefore important to note that “values” mode implies that “batch” mode is also used for all statements for which “values” mode does not apply.

For both strategies, the executemany_batch_page_size et executemany_values_page_size arguments control how many parameter sets should be represented in each execution. Because “values” mode implies a fallback down to “batch” mode for non-INSERT statements, there are two independent page size arguments. For each, the default value of None means to use psycopg2’s defaults, which at the time of this writing are quite low at 100. For the execute_values method, a number as high as 10000 may prove to be performant, whereas for execute_batch, as the number represents full statements repeated, a number closer to the default of 100 is likely more appropriate:

engine = create_engine( "postgresql+psycopg2://scott:tiger@host/dbname", executemany_mode='values', executemany_values_page_size=10000, executemany_batch_page_size=500)

Changed in version 1.3.7: – Added support for psycopg2.extras.execute_values. le use_batch_mode flag is superseded by the executemany_mode flag.

Unicode with Psycopg2 By default, the psycopg2 driver uses the psycopg2.extensions.UNICODE extension, such that the DBAPI receives and returns all strings as Python Unicode objects directly – SQLAlchemy passes these values through without change. Psycopg2 here will encode/decode string values based on the current “client encoding” setting; by default this is the value in le postgresql.conf file, which often defaults to SQL_ASCII. Typically, this can be changed to utf8, as a more useful default:

# postgresql.conf file

# client_encoding = sql_ascii # actually, defaults to database # encoding client_encoding = utf8

A second way to affect the client encoding is to set it within Psycopg2 locally. SQLAlchemy will call psycopg2’s psycopg2:connection.set_client_encoding() method on all new connections based on the value passed to create_engine() using the client_encoding parameter:

# set_client_encoding() setting; # works for *all* PostgreSQL versions engine = create_engine("postgresql://user:pass@host/dbname", client_encoding='utf8')

This overrides the encoding specified in the PostgreSQL client configuration. When using the parameter in this way, the psycopg2 driver emits SET client_encoding TO 'utf8' on the connection explicitly, and works in all PostgreSQL versions. Note that the client_encoding setting as passed to create_engine() est not the same as the more recently added client_encoding parameter now supported by libpq directly. This is enabled when client_encoding is passed directly to psycopg2.connect(), and from SQLAlchemy is passed using the create_engine.connect_args parameter:

engine = create_engine( "postgresql://user:pass@host/dbname", connect_args='client_encoding': 'utf8')

# using the query string is equivalent engine = create_engine("postgresql://user:pass@host/dbname?client_encoding=utf8")

The above parameter was only added to libpq as of version 9.1 of PostgreSQL, so using the previous method is better for cross-version support.

Disabling Native Unicode SQLAlchemy can also be instructed to skip the usage of the psycopg2 UNICODE extension and to instead utilize its own unicode encode/decode services, which are normally reserved only for those DBAPIs that don’t fully support unicode directly. Passing use_native_unicode=False à create_engine() will disable usage of psycopg2.extensions.UNICODE. SQLAlchemy will instead encode data itself into Python bytestrings on the way in and coerce from bytes on the way back, using the value of the create_engine() encoding parameter, which defaults to utf-8. SQLAlchemy’s own unicode encode/decode functionality is steadily becoming obsolete as most DBAPIs now support unicode fully.

Bound Parameter Styles The default parameter style for the psycopg2 dialect is “pyformat”, where SQL is rendered using %(paramname)s style. This format has the limitation that it does not accommodate the unusual case of parameter names that actually contain percent or parenthesis symbols; as SQLAlchemy in many cases generates bound parameter names based on the name of a column, the presence of these characters in a column name can lead to problems. There are two solutions to the issue of a schema.Column that contains one of these characters in its name. One is to specify the schema.Column.key for columns that have such names:

measurement = Table('measurement', metadata, Column('Size (meters)', Integer, clé='size_meters') )

Above, an INSERT statement such as measurement.insert() will use size_meters as the parameter name, and a SQL expression such as measurement.c.size_meters > dix will derive the bound parameter name from the size_meters key as well.

Changed in version 1.0.0: – SQL expressions will use Column.key as the source of naming when anonymous bound parameters are created in SQL expressions; previously, this behavior only applied to Table.insert() et Table.update() parameter names.

The other solution is to use a positional format; psycopg2 allows use of the “format” paramstyle, which can be passed to create_engine.paramstyle:

engine = create_engine( 'postgresql://scott:tiger@localhost:5432/test', paramstyle='format')

With the above engine, instead of a statement like:

INSERT INTO measurement ("Size (meters)") VALUES (%(Taille (meters))s) 'Size (meters)': 1

we instead see:

INSERT INTO measurement ("Size (meters)") VALUES (%s) (1, )

Where above, the dictionary style is converted into a tuple with positional style.

Transactions The psycopg2 dialect fully supports SAVEPOINT and two-phase commit operations.

Psycopg2 Transaction Isolation Level As discussed in Transaction Isolation Level, all PostgreSQL dialects support setting of transaction isolation level both via the isolation_level parameter passed to create_engine(), as well as the isolation_level argument used by Connection.execution_options(). When using the psycopg2 dialect, these options make use of psycopg2’s set_isolation_level() connection method, rather than emitting a PostgreSQL directive; this is because psycopg2’s API-level setting is always emitted at the start of each transaction in any Cas. The psycopg2 dialect supports these constants for isolation level:

READ COMMITTED

READ UNCOMMITTED

REPEATABLE READ

SERIALIZABLE

AUTOCOMMIT

NOTICE logging The psycopg2 dialect will log PostgreSQL NOTICE messages via the sqlalchemy.dialects.postgresql logger. When this logger is set to the logging.INFO level, notice messages will be logged:

importation logging

logging.getLogger('sqlalchemy.dialects.postgresql').setLevel(logging.INFO)

Above, it is assumed that logging is configured externally. If this is not the case, configuration such as logging.basicConfig() must be utilized:

importation logging

logging.basicConfig() # log messages to stdout logging.getLogger('sqlalchemy.dialects.postgresql').setLevel(logging.INFO)

HSTORE type le psycopg2 DBAPI includes an extension to natively handle marshalling of the HSTORE type. The SQLAlchemy psycopg2 dialect will enable this extension by default when psycopg2 version 2.4 or greater is used, and it is detected that the target database has the HSTORE type set up for use. In other words, when the dialect makes the first connection, a sequence like the following is performed:

Request the available HSTORE oids using psycopg2.extras.HstoreAdapter.get_oids(). If this function returns a list of HSTORE identifiers, we then determine que le HSTORE extension is present. This function is skipped if the version of psycopg2 installed is less than version 2.4.

If the use_native_hstore flag is at its default of True, et we’ve detected that HSTORE oids are available, the psycopg2.extensions.register_hstore() extension is invoked for all les liaisons.

le register_hstore() extension has the effect of all Python dictionaries being accepted as parameters regardless of the type of target column in SQL. The dictionaries are converted by this extension into a textual HSTORE expression. If this behavior is not desired, disable the use of the hstore extension by setting use_native_hstore à Faux comme follows:

engine = create_engine("postgresql+psycopg2://scott:tiger@localhost/test", use_native_hstore=Faux)

le HSTORE type is still supported when the psycopg2.extensions.register_hstore() extension is not used. It merely means that the coercion between Python dictionaries and the HSTORE string format, on both the parameter side and the result side, will take place within SQLAlchemy’s own marshalling logic, and not that of psycopg2 which may be more performant.

pg8000 Support for the PostgreSQL database via the pg8000 driver.

DBAPI Documentation and download information (if applicable) for pg8000 is available at: https://pythonhosted.org/pg8000/

Connecting Connect String:

postgresql+pg8000://user:password@host:port/dbname[?key=value&key=value...]

Remarque The pg8000 dialect is not tested as part of SQLAlchemy’s continuous integration and may have unresolved issues. The recommended PostgreSQL dialect is psycopg2.

Unicode pg8000 will encode / decode string values between it and the server using the PostgreSQL client_encoding parameter; by default this is the value in le postgresql.conf file, which often defaults to SQL_ASCII. Typically, this can be changed to utf-8, as a more useful default:

#client_encoding = sql_ascii # actually, defaults to database # encoding client_encoding = utf8

le client_encoding can be overridden for a session by executing the SQL: SET CLIENT_ENCODING TO ‘utf8’; SQLAlchemy will execute this SQL on all new connections based on the value passed to create_engine() using the client_encoding parameter:

engine = create_engine( "postgresql+pg8000://user:pass@host/dbname", client_encoding='utf8')

pg8000 Transaction Isolation Level The pg8000 dialect offers the same isolation level settings as that of the psycopg2 dialect:

READ COMMITTED

READ UNCOMMITTED

REPEATABLE READ

SERIALIZABLE

AUTOCOMMIT

New in version 0.9.5: support for AUTOCOMMIT isolation level when using pg8000.

psycopg2cffi Support for the PostgreSQL database via the psycopg2cffi driver.

DBAPI Documentation and download information (if applicable) for psycopg2cffi is available at: http://pypi.python.org/pypi/psycopg2cffi/

Connecting Connect String:

postgresql+psycopg2cffi://user:password@host:port/dbname[?key=value&key=value...]

psycopg2cffi is an adaptation of psycopg2, using CFFI for the C couche. This makes it suitable for use in e.g. PyPy. Documentation is as per psycopg2.

py-postgresql Support for the PostgreSQL database via the py-postgresql driver.

DBAPI Documentation and download information (if applicable) for py-postgresql is available at: http://python.projects.pgfoundry.org/

Connecting Connect String:

postgresql+pypostgresql://user:password@host:port/dbname[?key=value&key=value...]

Remarque The pypostgresql dialect is not tested as part of SQLAlchemy’s continuous integration and may have unresolved issues. The recommended PostgreSQL driver is psycopg2.

pygresql Support for the PostgreSQL database via the pygresql driver.

DBAPI Documentation and download information (if applicable) for pygresql is available at: http://www.pygresql.org/

Connecting Connect String:

postgresql+pygresql://user:password@host:port/dbname[?key=value&key=value...]

Remarque The pygresql dialect is not tested as part of SQLAlchemy’s continuous integration and may have unresolved issues. The recommended PostgreSQL dialect is psycopg2.

zxjdbc Support for the PostgreSQL database via the zxJDBC for Jython driver.

DBAPI Drivers for this database are available at: http://jdbc.postgresql.org/

Connecting Connect String:

postgresql+zxjdbc://scott:tiger@localhost/db

Click to rate this post! [Total: 0 Average: 0]

Topics and keywords

Themes: Serveur d'impression

License & attribution

License: CC BY-ND 4.0.

Attribution required: yes.

Manifest: https://tutos-gameserver.fr/llm-endpoints-manifest.json

LLM Endpoints plugin version 1.1.2.