# -*- coding: utf-8 -*-
from setuptools import setup

packages = \
['postgresqlite']

package_data = \
{'': ['*']}

install_requires = \
['pg8000>=1.24.1,<2.0.0']

setup_kwargs = {
    'name': 'postgresqlite',
    'version': '0.2.3',
    'description': 'Python package that gives you the power of a PostgreSQL server, with the convenience of the sqlite3 package.',
    'long_description': '# PostgreSQLite\n\nPython module that gives you the power of a PostgreSQL server, with the convenience of the `sqlite3` module.\n\n## Features\n\n- Using just a `postgresqlite.connect()` call, the library will automatically...\n    - Download and install PostgreSQL into the user\'s `~/.cache` directory. (Linux EM64T only for now.)\n    - Create a new database (`initdb`) within the project directory with a random password.\n    - Start the PostgreSQL server.\n    - Set up a DB-API connection to the server (using the `pg8000` driver).\n    - Shut down the server when it\'s no longer in use.\n- It also adds a couple of conveniences on top of DB-API, making it more similar to the `sqlite3` module:\n    - Calling `execute` on the connection will create a new cursor.\n    - Calls to `fetchall` and `fetchone` return objects that can address fields both by number (as is standard for DB-API) as well as by name (as `sqlite3` offers when you configure `connection.row_factory = sqlite3.Row`).\n    - Autocommit mode is enabled by default.\n    - Parameterized queries use `?` as a placeholder. (`paramstyle = \'qmark\'`)\n- It can open `psql` and other PostgreSQL clients passing in connection details, while making sure the database is running.\n- For use in production, the configuration file can be modified to point your application at a (non-auto-starting) PostgreSQL server.\n\n\n## Examples\n\n### Using the API directly\n\n```sh\npip install postgresqlite\n```\n\n```python\nimport postgresqlite\n\ndb = postgresqlite.connect()\n\ndb.execute(\'create table if not exists tests(id serial, info text not null, created_at timestamp not null default current_timestamp)\')\ndb.execute("insert into tests(info) values(\'Hi mom!\'),(\'This is great!\')")\n\nrows = db.execute("select * from tests where id=?", [1]).fetchall()\nfor row in rows:\n    print("Row:", row, row[0], row[\'created_at\'])\n\nprint("Count:", db.execute("select count(*) from tests").fetchone())\n```\n\n### Using Flask-SQLAlchemy\n\n```sh\npip install postgresqlite flask_sqlalchemy\n```\n\n```python\nimport postgresqlite, flask, flask_sqlalchemy, datetime\n\napp = flask.Flask(__name__)\napp.config[\'SQLALCHEMY_DATABASE_URI\'] = postgresqlite.get_uri()\napp.config[\'SQLALCHEMY_TRACK_MODIFICATIONS\'] = False\n\ndb = flask_sqlalchemy.SQLAlchemy(app)\n\nclass Car(db.Model):\n    id = db.Column(db.Integer, primary_key=True)\n    brand = db.Column(db.String)\n    model = db.Column(db.String, nullable=False)\n    day_rate = db.Column(db.Integer)\n    rentals = db.relationship(\'Rental\', backref=\'car\')\n\n    def to_dict(self):\n        return {\'id\': self.id, \'brand\': self.brand, \'model\': self.model, \'day_rate\': self.day_rate, \'rentals\': [rental.to_dict() for rental in self.rentals]}\n    \nclass Rental(db.Model):\n    id = db.Column(db.Integer, primary_key=True)\n    car_id = db.Column(db.Integer, db.ForeignKey(\'car.id\'), nullable=False)\n\n    customer_name = db.Column(db.String, nullable=False)\n    start_time = db.Column(db.DateTime, default=datetime.datetime.now)\n    end_time = db.Column(db.DateTime)\n\n    def to_dict(self):\n        return {\'id\': self.id, \'car_id\': self.car_id, \'customer_name\': self.customer_name, \'start_time\': self.start_time, \'end_time\': self.end_time}\n\n@app.route(\'/cars\')\ndef show_all():\n   return flask.jsonify([car.to_dict() for car in Car.query.all()])\n\n@app.route(\'/cars\', methods = [\'POST\'])\ndef new_car():\n    car = Car(**flask.request.get_json())\n    db.session.add(car)\n    db.session.commit()\n    return flask.jsonify(car.to_dict())\n\n@app.route(\'/rentals\', methods = [\'POST\'])\ndef new_rental():\n    rental = Rental(**flask.request.get_json())\n    db.session.add(rental)\n    db.session.commit()\n    return flask.jsonify(rental.to_dict())\n\nif __name__ == \'__main__\':\n   db.create_all()\n   app.run(debug = True)\n```\n\nRunning this should expose a REST API. If you have [httpie](https://httpie.io/) installed, it can be tested from the command like this:\n\n```sh\nhttp http://127.0.0.1:5000/cars brand=Volvo model=S60\nhttp http://127.0.0.1:5000/rentals car_id=1 customer_name=Frank\nhttp http://127.0.0.1:5000/cars\n```\n\n\n\n## Documentation\n\n### API functions\n\n#### `postgresqlite.connect(dirname=\'data/postgresqlite\', sqlite_compatible=True)`\n\nStart a server (if needed), wait for it, and return a DB-API compatible object.\n \nArguments:\n- dirname (str): The directory where the configuration file (`postgresqlite.json`) will be read or created, and where database files will be stored. If the path does not exist, it will be created.\n- sqlite_compatible (bool): When set, a few (superficial) changes are made to the exposed DB-API to make it resemble the Python `sqlite3` API more closely, as described in the *Features* section.\n\nReturns a [DB-API compatible connection object](https://peps.python.org/pep-0249/#connection-objects).\n\n#### `postgresqlite.get_config(dirname=\'data/postgresqlite\')`\n\nStart a server (if needed), wait for it, and return the config object. If the PostgreSQL server is in autostart mode (which is the default), it will be kept running until some time after the calling process (and any other processes that depend on this server) have terminated.\n \nArguments:\n- dirname (str): The directory where the configuration file (`postgresqlite.json`) will be read or created, and where database files will be stored. If the path does not exist, it will be created.\n\nReturns a `Config` object, that includes (among others) the following attributes:\n- `user` (string): Database user name.\n- `password` (string): Database password. (Can be `None`.)\n- `port` (int): Database TCP port. (Can be `None`.)\n- `host` (string): Database host name. (Can be `None`.)\n- `database` (string): Database name.\n- `socket` (string): Database UNIX domain socket. (Can be `None`.)\n\n\n#### `postgresqlite.get_uri(dirname=\'data/postgresqlite\', driver=\'pg8000\')`\nStart a server (if needed), wait for it, and return a connection URL.\n\nArguments:\n- dirname (str): The directory where the configuration file (`postgresqlite.json`) will be read or created, and where database files will be stored. If the path does not exist, it will be created.\n- driver (str): The URI may include a driver part (`postgresql+DRIVER://user:pwd@host/db`), which we\'ll set to `pg8000` by default. This parameter allows you to specify a different direct, or leave it out (by providing `None`).\n\n\n### CLI interface\n\nIn order to easily access the database your application is using, PostgreSQLite can open a client application (such as *psql* or [Beekeeper Studio](https://www.beekeeperstudio.io/)) for you, making sure the database is started (and doesn\'t shutdown) while the application is open, and passing in connection details.\n\nThe connection details are provided in environment variables called `PGHOST`, `PGPORT`, `PGDATABASE`, `PGSOCKET`, `PGUSER`, `PGPASSWORD` and `PGURI`. \n\nAn application can be started by running the `postgresqlite` package with `-m`, providing the executable and its arguments as arguments.\n- When no arguments are passed: `psql`, the default PostgreSQL client, is run. So opening your database in `psql` can be done like this:\n  ```sh\n  python -mpostgresqlite\n  ```\n  The `psql` client uses the environment variables to set up a connection.\n- When exactly one argument is passed and it contains the string `$PG`, it will be executed as a shell command. So in order to pass the URI as the argument to an application, one could use:\n  ```sh\n  python -mpostgresqlite \'xdg-open $PGURI\'\n  ```\n  As Beekeeper Studio registers as an opener for the `postgresql://` protocol, the above command can be used to open your database with it.\n- Otherwise, the arguments are used to launch the application as-is. It can use the environment variables to set up a connection.\n  ```sh\n  python -mpostgresqlite my-client connect --extra-fancy\n  ```\n\nOptionally, the directory where the configuration file (`postgresqlite.json`) will be read or created, and where database files will be stored, can be specified by prefixing the command with `-c` `<dirname>`. For example:\n\n```sh\npython -mpostgresqlite -d mydbdir \'xdg-open $PGURI\'\n```\n\n\n### The config file\n\nWhen PostgreSQLite is first started (for a certain directory), a configuration file called `postgresqlite.json` is created. After initial creation, the file is all yours to modify. It contains the following values:\n\n- `autostart` (bool): When true, PostgreSQLite will automatically start/stop a PostgreSQL server. Otherwise, it will just connect to an existing database given the credentials in this file.\n- `host` (str): Connection host name.\n- `port` (int): Connection TCP port.\n- `socket` (str): Connection UNIX domain socket (optional).\n- `database` (int): Database name.\n- `user` (str): Connection user name.\n- `password` (str): Connection password name (optional).\n\nThese fields are only relevant when `autostart` is true:\n- `expire_seconds` (int): The time in seconds after which a server is shutdown when there are no active clients anymore.\n- `pg_cache_dir` (str): The directory into which PostgreSQL will be installed and from which it will be ran.\n- `postgresql_version` (str): The version of PostgreSQL to use. Currently only `"14.3"` is supported.\n\n\n### The autostart mechanism\n\nPostgreSQLite uses a series of lock files (stored in `locks/` in the configuration directory) to coordinate different application instances that may want to use the database. When such a process starts and no database is running, it forks a daemon that will start and eventually stop the PostgreSQL server. Stopping happens when there have been no more database applications running for `expire_seconds`, based on the lock files created by each application.\n\nIn case you want to force the server to stop immediately, you can do so by deleting the `locks/daemon.lock` file within the configuration directory. Starting the application again will cause the server to start anew.\n\n\n### Standalone PostgreSQL\n\nThe autostart feature installs PostgreSQL from a tarball stored as a [GitHub release](https://github.com/vanviegen/postgresqlite/releases/tag/libs). This tarball is created using the `Dockerfile` and `run.sh` script provided in the `create-standalone-postgresql/` directory.\n\nIt works by copying the PostgreSQL binaries and depend files (including any `.so` files being used) from an Arch linux installation to a `.tar.gz` file. \n',
    'author': 'Frank van Viegen',
    'author_email': 'pp@vanviegen.net',
    'maintainer': None,
    'maintainer_email': None,
    'url': 'https://github.com/vanviegen/postgresqlite',
    'packages': packages,
    'package_data': package_data,
    'install_requires': install_requires,
    'python_requires': '>=3.7,<4.0',
}


setup(**setup_kwargs)
