Saravanan666/pypi-org huggingface dataset:
Package: postgis-toolkit
PostGIS commands.DescriptionWraps cli operations into a single interfacepsql,shp2pgsql,\copy,ogr2ogr, etc.Import/export to desired formatTested on MacOSUsage$ pgtk
Usage: pgtk [OPTIONS] COMMAND [ARGS]...

  PostGIS Command Line Tool

Options:
  -h, --host TEXT    hostname
  -p, --port TEXT    port number
  -d, --dbname TEXT  database
  -u, --user TEXT    user
  -s, --schema TEXT  database schema
  -c, --crs TEXT     EPSG code
  --help             Show this message and exit.

Commands:
  export  Export PostGIS data
  import  Import data to PostgreSQL
  layers  Layer commandsViewing data:$ pgtk -h suffolk.geoserver.org -d boundary_data -s public_works layers list
--- public_works.boundary_data ---
 * zip_codes
 * suffolk_boundary
 * fire_districts
 * landmark_historic_districts
 * waterfront
 * zongin_district
 * boston_neighborhoods
 * land_use
 * planning_districts
 * water
 * parcels
 * downtown
 * airports
 * harbor_islands
$
$ pgtk -h suffolk.geoserver.org -d boundary_data -s public_works layers preview boston_neighborhoods
--- preview boston_neighborhoods ---
gid        name    acres    neighborho    sqmiles    shapestare    shapestlen  geom
  1  Roslindale  1605.57            15       2.51   6.99383e+07       53563.9  01060000...Export PostGIS data:$ pgtk -h suffolk.geoserver.org -d boundary_data -s public_works \
> export -o ~/Downloads --driver csv boston_neighborhoods suffolk_boundary
--- export csv ---
>> boston_neighborhoods
COPY 26
>> suffolk_boundary
COPY 1
$
$ head -5 ~/Downloads/boston_neighborhoods.csv | column -t -s,
gid  name           acres                 neighborho  sqmiles  shapestare                shapestlen             coordinate_y      coordinate_x
1    Roslindale     1605.568237499999896  15          2.510    69938272.925570487976074  53563.912597056623781  42.2825239371116  -71.1266625924454
2    Jamaica Plain  2519.245393770000192  11          3.940    109737890.75433960556983  56349.937161410227418  42.3077695033488  -71.1150969429541
3    Bay Village    26.539839160000000    33          0.040    1156070.765868443064392   4650.635493295902052   42.3491032446921  -71.0690319987556
4    Roxbury        2108.469071760000134  16          3.290    91844545.974815726280212  49488.800484731051256  42.3185185721262  -71.0866432257429Install$ pip install postgis-toolkitPython 3.7+Requires postgis tools installed on your computer -shp2pgsql&pgsqlshould be on your path.easiest way is throughPostgres.app
Package: postgoose
SQL migrations for PostgresPGPASSWORD=top-secret goose ./tests/master_migrations(Assuming you have a Postgres server running onlocalhost:5432with a high-entropy admin password)Installationpip install postgooseUsageusage: goose [-h] [--host HOST] [-p PORT] [-U USERNAME] [-d DBNAME]
             [-s SCHEMA] [-r ROLE] [--strict_digest_check STRICT_DIGEST_CHECK]
             [-m MIGRATIONS_TABLE_NAME] [-a AUTO_APPLY_DOWN] [-V VERBOSE] [-v]
             migrations_directory

positional arguments:
  migrations_directory  Path to directory containing migrations

optional arguments:
  -h, --help            show this help message and exit
  --host HOST
  -p PORT, --port PORT
  -U USERNAME, --username USERNAME
  -d DBNAME, --dbname DBNAME
  -s SCHEMA, --schema SCHEMA
  -r ROLE, --role ROLE

  --strict_digest_check STRICT_DIGEST_CHECK
                        Set Flase to compare with saved digest instead of re-computing digest.
                        Default is True

  -m MIGRATIONS_TABLE_NAME, --migrations_table_name MIGRATIONS_TABLE_NAME
                        Default is goose_migrations

  -a AUTO_APPLY_DOWN, --auto_apply_down AUTO_APPLY_DOWN
                        Accepts True/False, default is True

  -V VERBOSE, --verbose VERBOSE
                        Accepts True/False, default is True

  -v, --version         show program's version number and exitWheremigrations_directoryis some directory of form:./migrations
  1_up.sql
  1_down.sql
  2_up.sql
  2_down.sql
  3_up.sql
  3_down.sqlCurrent main difference from Play Framework migrations is that a migration in Goose is all-or-nothing.E.g. you are on master branch on revision 5 and want to switch to a feature branch whose latest revision is 4'.1 <- 2 <- 3 <- 4 <- 5
       \
         3' <- 4'Applying migrations through Goose will leave you on either revision 5 (if an error is encountered) or revision 4' (if migration is successful) but not on any of 4, 3, 2, or 3'.Testing on local machineCheckdocs/testing.mdLicenseCopyright 2018 LeanTaas, Inc.Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License athttp://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Package: postgres-adm
Postgres ADMPostgreSQL has the function of facilitating the use of methods for executing SQL statements.How to import?from postgres_adm import *How to create the instance?bank = PostgreSQL(dbname="my_db", user="my_user", password="my_password", host="localhost", port="5432")How to connect?bank.connect()How to disconnect?bank.disconnect()How to check the bank version?bank.version()How to execute instructions?bank.execute("instructions")How to save changes?bank.commit()How to create delete a table?bank.deleteTable(table='my_table')How to get all values within the database?bank.get(table='my_table')How to get a single value?bank.getSingleData(value='my_value',table='my_table',column='my_column')How to obtain complete data?bank.getFullData(table='my_table',unique='my_unique')
Package: postgres-audit-triggers
Postgres audit database via triggersThis app sets up a postgres audit database via triggers.
Seehttps://wiki.postgresql.org/wiki/Audit_trigger_91plusandhttps://github.com/2ndQuadrant/audit-trigger/for more information.Installationpip install postgres_audit_triggersUsageAdd thepostgres_audit_triggersapp toINSTALLED_APPSbeforeany apps that will be audited:# settings.py
INSTALLED_APPS = {
    'django.contrib.postgres',
    'postgres_audit_triggers',
    ...
}Install thepostgres_audit_triggersmiddleware:# settings.py
MIDDLEWARE = [
    ...
    'postgres_audit_triggers.middleware.AuditMiddleware',
]This middleware will add metadata to the audit row. To send metadata, the client must send aPostgres-Audit-Triggers-Metaheader in the request to your Django view. The data within
that header must be JSON serializable to a python dictionary.Run migrations:python manage.py migrate postgres_audit_triggersAddaudit_trigger = Trueto the Model Meta options of the models that will be audited:# models.py
class MyAuditedModel(models.Model):
    ...
    class Meta:
        audit_trigger = True
        ...Make migrations:python manage.py makemigrationsRun migrations:python manage.py migrateTriggers introduce performance overhead. In certain cases, you may need to disable triggers while
performing bulk operations. To turn off all triggers, a decorator is provided:from postgres_audit_triggers.decorators import disable_triggers


@disable_triggers
def foo():
    # auditing will not be triggered on any database operations performed here
    Bar.objects.bulk_create(items)
Package: postgres-copy-binary
postgres-copy-binaryProvides a decoder for postgresCOPY FROM WITH BINARYformat that spits out pyarrow / pandas / numpy arraysExamplesCopy and decode the whole tableimportpsycopg2frompostgres_copy_binaryimportread_tablewithpsycopg2.connect(...)asconn:withconn.cursor()ascursor:columns=read_table(cursor,'my_table')Linkshttps://www.postgresql.org/docs/current/sql-copy.htmlhttps://docs.rs/postgres/latest/postgres/binary_copy/index.htmlhttps://docs.rs/tokio-postgres/latest/tokio_postgres/binary_copy/index.htmlhttps://github.com/spitz-dan-l/postgres-binary-parserhttps://github.com/sfackler/rust-postgres-binary-copy
Package: postgres-csv-uploader
Postgres CSV UploaderThis package provides a simple utility to upload CSV files to a Postgres DB without explicitly specifying the table schema in advance by inferring the column types from the corresponding Pandas dtypes.Libraries such as SQLAlchemy provide systems to do this -- however, the SQLAlchemy ORM is substantially slower than interacting with the database driver directly (which is done by libraries like psycopg2). As a result, there was a (very small, very specific) need to create a smoother interface for uploading CSVs to Postgres quickly and with some kind of type inference.Note that this is averylimited library. It requires being able to load the dataset into memory, and currently doesn't do any kind of partitioning or support parallelism. It also requires superadmin privileges within the DB. However, it does work decently well on small datasets.As a word of caution, uploading is adestructiveoperation, meaning that it willoverwritethe the existing table specified by thetable_nameparameter if it exists.Example Usage:from postgres_csv_uploader.uploader import PostgresCSVUploader
import psycopg2 as ps

conn = ps.connect(
    host="hostname",
    user="username",
    password="password",
    port=5432
)
uploader = PostgresCSVUploader(conn)
uploader.upload(
    "my_file.csv",
    "my_table_name",
    index_col="uid",
    datetime_cols=["first_date", "second_date"]
)
Package: postgres-database-utils
Postgres Database UtilsA python package for postgres database utilities.Table of ContentsInstallationUsageSupportContributingInstallationInstall the package using pip:pipinstalldatabase-utilsUsageCreate a database connection:frompostgres_database_utilsimportcreate_connection,PostgresCredentialscredentials=PostgresCredentials(host='localhost',database='postgres',user='postgres',password='postgres',port=5432)connection=create_connection(credentials)SupportPleaseopen an issuefor support.ContributingPlease contribute usingGithub Flow. Create a branch, add commits, andopen a pull request.
Package: postgresdave-package
postgresdaveA simple wrapper on psycopg2 to access Postgresinstall with pippip install postgresdave_packagecommand line testpy -m postgresdave_package.postgresdaveQuick Start Guidehttps://github.com/daveskura/postgresdave/blob/main/QuickStart.mdMethodshttps://github.com/daveskura/postgresdave/blob/main/methods.md
Package: postgres-ddl
DescriptionPostgreSQL metadata (DDL) grabber and database schema diffDependenciesPython 3psycopg2Installationpipinstallpsycopg2-binarypostgres-ddlGrabbing1 ) Create config file with connection params and other settings:{"connect":{"host":"localhost","port":5432,"database":"db","username":"some_user","password":"some_password"},"path":"/some/path/to/grabber/result/folder","exclude_schemas":["information_schema","pg_catalog"],"threads":8,"new_line":"\n","indent":2}2 ) By default script opens config fileconfig_grab.jsonfrom the same directory aszzz_Grabber.pyfile.3 ) Alternatively you can specify path to config file as a first run parameter.4 ) Run grabber:# Run with default config (config_grab.json)python"zzz_Grabber.py"# Run with specified config file pathpython"zzz_Grabber.py""/some/path/to/config.json"Compare (diff) databases1 ) Create config file with connection params and other settings:{"source":{"host":"localhost","port":5432,"database":"db_from","username":"user","password":"password"},"target":{"host":"localhost","port":5432,"database":"db_to","username":"user","password":"password"},"path":"/some/path/to/compare/result/folder","exclude_schemas":["information_schema","pg_catalog"]}2 ) By default script opens config fileconfig_diff.jsonfrom the same directory aszzz_Grabber.pyfile.3 ) Alternatively you can specify path to config file as a first run parameter.4 ) Run diff:# Run with default config (config_grab.json)python"zzz_Diff.py"# Run with specified config file pathpython"zzz_Diff.py""/some/path/to/config.json"LinksGitHubPyPI
Package: postgresfixture
A Python fixture for creating PostgreSQL clusters and databases, and
tearing them down again, intended for use during development and
testing.For more information see theLaunchpad project page.Getting startedUse like any other fixture:from contextlib import closing
from postgresfixture import ClusterFixture

def test_something(self):
    cluster = self.useFixture(ClusterFixture("db"))
    cluster.createdb("example")
    with closing(cluster.connect("example")) as conn:
        ...
    cluster.dropdb("example")  # Optional.This will create a new cluster, create a database called “example”,
then tear it all down at the end; nothing will remain on disk. If you
want the cluster and its databases to remain on disk, passpreserve=Trueto theClusterFixtureconstructor.From the command lineOnce this package is installed, you’ll have apostgresfixturescript. Alternatively you can usepython-mpostgresfixtureto
achieve the same thing. Use--helpto discover the options
available to you.
Package: postgres-helper
Postgres HelperThepostgres-helperlibrary is build on top ofpsycopg2. It will be really helpful for running the basic postgresql query in python.Checkout the official documentation of this library here:postgres-helper.readthedocs.io/InstallationFor installation ofpostgres-helper, you need to run following commandpipinstallpostgres-helperExamples using this libraryPlease check the official documentation here:https://postgres-helper.readthedocs.io/.#Library importfrompg.pgimportPg# Initialization of librarypg=Db(dbname='postgres',user='postgres',password='admin',host='localhost',port='5432')# Get the column names of the specific tablepg.get_columns_name(table='pg_table')# Get values from specific column of tablepg.get_values_from_column(column='pg_table_col',table='pg_table',schema='public')# Create schemapg.create_schema(name='schema_name')# Create columnpg.create_column(column='col_name',table='pg_table',col_datatype='varchar',schema='public')# Update columnpg.update_column(column='col_name',value='updated_value',table='pg_table',where_column='where_col',where_value="where_val",schema='public')# Delete tablepg.delete_table(name='pg_table',schema='public')# Delete valuespg.delete_values(table_name='pg_table',condition='name=value',schema='public')
Package: postgres_kernel
# A simple Jupyter kernel for PostgreSQLInstall withpip install postgres_kernelTo use, run one of:`bash jupyter notebook # In the notebook interface, select PostgreSQL from the 'New' menu jupyter qtconsole--kernelpostgres jupyter console--kernelpostgres `## How to use:There are a couple of specially formatted comments for controlling the connection string and autocommit mode.`sql--connection:postgres://brian:password@localhost:5432/dbname--autocommit: true--(or false) `For details of how this works, see Jupyter’s docs on [wrapper kernels](http://jupyter-client.readthedocs.io/en/latest/wrapperkernels.html).
This is heavily based on [takluyver/bash_kernel](https://github.com/takluyver/bash_kernel). Just look at our git log :)![](images/console.png)![](images/notebook.png)RelatedCatherine Devlin has an ipython magic that seems very full featured: [catherinedevlin/ipython-sql](https://github.com/catherinedevlin/ipython-sql)As noted, this is based on [takluyver/bash_kernel](https://github.com/takluyver/bash_kernel)
Package: postgres-mktempdb
Installation$[sudo]pipinstallpostgres-mktempdb$[sudo]npmi-gpostgres-mktempdbExamples$mktempdb
tmp_LH8LqXy8UGlfMR8zfB3todrc4mwC9Snsdelete temp databases:$psql-At-c"SELECT datname FROM pg_database WHERE datname LIKE 'tmp_%'"|xargs-L1dropdbdelete temp databases created more than 5 minutes ago:$psql-At-c"SELECT datname FROM pg_databaseWHERE datname LIKE 'tmp_%' AND (pg_stat_file('base/'||oid||'/PG_VERSION')).modification<now()+interval '5 minutes'"|xargs-L1dropdbreadme42.com
Package: postgresql-audit
Auditing extension for PostgreSQL. Provides additional extensions for SQLAlchemy and Flask. PostgreSQL-Audit tries to combine the best of breed from existing solutions such asSQLAlchemy-Continuum,Papertrailand especiallyAudit Trigger by 2nd Quadrant.Compared to existing solutions PostgreSQL-Audit has the following charasteristics:Stores all versions into single table called ‘activity’Uses minimalistic trigger based approach to keep INSERTs, UPDATEs and DELETEs as fast as possibleTracks actor IDs to be able to answer these questions quickly:Who modified record x on day x?What did person x do between y and z?Can you show me the activity history of record x?Installationpip install PostgreSQL-AuditRunning the testsgit clone https://github.com/kvesteri/postgresql-audit.git
cd postgresql-audit
pip install tox
createdb postgresql_audit_test
toxFlask extensionfrompostgresql_audit.flaskimportversioning_managerfrommy_app.extensionsimportdbversioning_manager.init(db.Model)classArticle(db.Model):__tablename__='article'__versioned__={}# <- IMPORTANT!id=db.Column(db.Integer,primary_key=True)name=db.Column(db.String)article=Article(name='Some article')db.session.add(article)db.session.commit()Now we can check the newly created activity.Activity=versioning_manager.activity_clsactivity=Activity.query.first()activity.id# 1activity.table_name# 'article'activity.verb# 'insert'activity.old_data# Noneactivity.changed_data# {'id': '1', 'name': 'Some article'}article.name='Some other article'db.session.commit()activity=Activity.query.order_by(db.desc(Activity.id)).first()activity.id# 2activity.table_name# 'article'activity.verb# 'update'activity.object_id# 1activity.old_data# {'id': '1', 'name': 'Some article'}activity.changed_data# {'name': 'Some other article'}db.session.delete(article)db.session.commit()activity=Activity.query.order_by(db.desc(Activity.id)).first()activity.id# 3activity.table_name# 'article'activity.verb# 'delete'activity.object_id# 1activity.old_data# {'id': '1', 'name': 'Some other article'}activity.changed_data# None
Package: postgresqlconnector
AboutA small module for working quickly with the PostgreSQLSimple Start for home projectInstall package from pippip install postgresqlconnectorUse connectorfrom postgresqlconnector import DB
print(DB.query('''select * from pg_stat_activity'''))APIqueryGet all rows from your sql queryParam:sql: str - Your queryparams: dict - Params for queryResult:Array of Recordresult = DB.query('''select * from pg_stat_activity''')
print(result[0])
print(result[0].pid)rowGet first row from your sql queryParam:sql: str - Your queryparams: dict - Params for queryResult:Recordresult = DB.row('''select * from pg_stat_activity''')
print(result.pid)scalarGet first column from first row from you sql queryParam:sql: str - Your queryparams: dict - Params for queryResult:Scalarresult = DB.scalar('''select pid, * from pg_stat_activity''')
print(result)set_connection_infoSet database connectionsParam:host: str = 'localhose' - Hostport: str = '5432' - Portdbname: str = 'postgres' - Database nameuser: str = 'postgres' - Userpassword: str = 'postgres' - Passwordcreate_transactionWork with transaction.If an exception occurs in your code, the transaction will rollbackwith DB.create_transaction():
    # block for your code
Package: postgresqlfacil
PostgreSQLFacilO pacote PostgreSQLFacil oferece uma interface simplificada para interagir com o banco de dados PostgreSQL, abstraindo as operações comuns de SELECT, INSERT, UPDATE e DELETE em métodos convenientes e com integrações em DataFrames do pandas.InstalaçãoPara utilizar o pacote CalendarioFinanceiro, você precisa instalá-lo primeiro. Isso pode ser feito utilizando o gerenciador de pacotes pip. Execute o seguinte comando no terminal:pipinstallPostgreSQLFacilUso BásicoAqui está um exemplo de como você pode usar o PostgreSQLFacil para realizar operações com o banco de dados PostgreSQL:fromPostgreSQLFacilimportConectorPostgreSQLimportpandasaspd# Configuração das informações de conexãoconfig={"database":"seu_banco_de_dados","user":"seu_usuario","password":"sua_senha","host":"seu_host","port":"sua_porta",}# Inicialização do ConectorPostgreSQLwithConectorPostgreSQL(**config)asSQL:# Executa uma consulta SELECT e obtém o resultado como um DataFramedf_consulta=SQL.executa_query_select('SELECT * FROM sua_tabela;')# Executa uma inserção de dadosquery_insert='INSERT INTO sua_tabela (coluna1, coluna2) VALUES (valor1, valor2);'SQL.executa_query_insert(query_insert)# Executa um updatequery_update='UPDATE sua_tabela SET coluna1 = novo_valor WHERE coluna2 = valor_alvo;'SQL.executa_query_update(query_update)# Executa um deletequery_delete='DELETE FROM sua_tabela WHERE coluna = valor_alvo;'SQL.executa_query_delete(query_delete)Métodos Disponíveisexecuta_query_select(query: str) -> pd.DataFrameExecuta um SELECT statement e retorna o resultado como um DataFrame. Em caso de erro, retorna um DataFrame vazio.executa_query_insert(query: str, returning=False) -> intExecuta um INSERT statement e retorna o valor solicitado (geralmente o último ID inserido) se especificado. Retorna True em caso de sucesso.executa_query_update(query: str) -> boolExecuta um UPDATE statement e retorna True em caso de sucesso.executa_query_delete(query: str) -> boolExecuta um DELETE statement e retorna True em caso de sucesso.transforma_df_em_insert_statement(df: pd.DataFrame, tabela: str) -> strTransforma um DataFrame em um INSERT statement para a tabela especificada.
Package: postgresql-fastquery
postgresql_fastquery"postgresql_fastquery" is a module or library designed to simplify Postgresql database interactions and CRUD operations.if you're considering using "mysql_fastconnector" in your projects, it's essential to refer to its resources to get a more detailed understanding of its capabilities, how to integrate it into your applications, and any specific benefits it offers compared to other MySQL connectors or libraries. Additionally, checking for updates and community feedback can help you gauge its reliability and suitability for your needs.Required  client and connectorpip install psycopg2Postgresql Database connection examplefrom  postgresql_fastquery import  Model ,table,query

obj=Model.connect(database="user", user = "postgres", password = "admin123", host = "127.0.0.1")Postgresql Query Exampleres=query("select * from users").fetchAll()forvinres:print(res)Object based Query Exampleres=table("players").all()res=table("players").one()res=table("players").fromTable('pk').where('pk=37').all()res=table("players").fromTable('pk').where('pk=37').limit(0,50).all()res=table("players").fromTable('players.pk').leftJoin('player_images','player_id=players.pk').where('players.pk=37').limit(0,50).all()res=table("players").fromTable('players.pk').rightJoin('player_images','player_id=players.pk').where('players.pk=37').limit(0,50).all()forvinres:print(res)## Print Query Exampleusers=table("users")users.printQuery=Trueres=users.fromTable('users.pk').leftJoin('images','user_id=users.pk').where('users.pk=27').limit(50,0).all()forvinres:print(res)## Sub Query Exampleusers=table("users")users.printQuery=Trueusers.subQuery("(select count(*) from users ) as m,")res=users.fromTable('users.pk').leftJoin('images','user_id=users.pk').where('users.pk=27').limit(50,0).all()forvinres:print(res)Insert Exampleid=obj.table("players").insert({'first_name':'r222222222','last_name':'r33333333','id':'555','email':'aa@gmail.com','mobile':'987654321'}).getId()print(id)ids=obj.table("players").insertMany([{'first_name':'r222222222','last_name':'r33333333','id':'555','email':'aa@gmail.com','mobile':'987654321'},{'first_name':'r222222223333333333','last_name':'r33333333','id':'555','email':'aa@gmail.com','mobile':'987654321'}])print(ids)update Exampleid=obj.table("players").update({'first_name':'0000000000000000000','last_name':'r33333333','id':'555','email':'aa@gmail.com','mobile':'987654321'},"pk=66")delete Exampletable("players").delete("pk=66")Any help , contact meemail : ilayaraja.python@gmail.com