diff options
Diffstat (limited to 'psql')
-rw-r--r-- | psql/INSTALL | 20 | ||||
-rw-r--r-- | psql/LICENCE | 66 | ||||
-rw-r--r-- | psql/Makefile | 57 | ||||
-rw-r--r-- | psql/README | 35 | ||||
-rw-r--r-- | psql/help-psql.pd | 50 | ||||
-rw-r--r-- | psql/psql.c | 371 |
6 files changed, 599 insertions, 0 deletions
diff --git a/psql/INSTALL b/psql/INSTALL new file mode 100644 index 0000000..dca6d37 --- /dev/null +++ b/psql/INSTALL @@ -0,0 +1,20 @@ +Requirements +------------ + +This object reuires + +libpq >= 7.4 +PD >= 0.37 + +Installation +------------ + +Modify the Makefile so that PDDIR gives the base directory of your PD installation, and INCLUDE provides the path to your PostgreSQL headers. + +Then from a shell prompt type: + +make <option> +sudo make install + +Where <option> is either 'pd_linux' or 'pd_darwin' (without the quotes). + diff --git a/psql/LICENCE b/psql/LICENCE new file mode 100644 index 0000000..085912e --- /dev/null +++ b/psql/LICENCE @@ -0,0 +1,66 @@ +GNU GENERAL PUBLIC LICENSE
+TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does.
+
+1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.
+
+2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:
+
+a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.
+
+b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.
+
+c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.
+
+3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following:
+
+a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
+
+b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
+
+c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.
+
+If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code.
+
+4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
+
+5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it.
+
+6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.
+
+7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances.
+
+It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.
+
+This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.
+
+8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.
+
+9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation.
+
+10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.
+
+NO WARRANTY
+
+11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
+
+END OF TERMS AND CONDITIONS
diff --git a/psql/Makefile b/psql/Makefile new file mode 100644 index 0000000..f4084e3 --- /dev/null +++ b/psql/Makefile @@ -0,0 +1,57 @@ +NAME=psql +CSYM=psql + +PDDIR=/usr/local/lib/pd +INCLUDE = -I/usr/include/postgresql + +all: pd_linux +current: pd_linux + +LDFLAGS = -lc -lm -lpq + +# Postgres ---------------------- + +SRCDIR= /usr/include +TARGDIR= ./ + +#include Makefile.global #needed for postgresql stuff + +# Linux ---------------------------------------------- + +pd_linux: $(NAME).pd_linux + +.SUFFIXES: .pd_linux + +LINUXCFLAGS = -g -DPD -O0 -fPIC -funroll-loops -fomit-frame-pointer \ + -Wall -W -Wshadow -Wstrict-prototypes -Werror \ + -Wno-unused -Wno-parentheses -Wno-switch + +.c.pd_linux: + $(CC) $(LINUXCFLAGS) $(INCLUDE) -o $*.o -c $*.c + $(CC) -export_dynamic -shared -o $*.pd_linux $*.o $(LDFLAGS) + strip --strip-unneeded $*.pd_linux + rm $*.o + +# Darwin ---------------------------------------------- + +pd_darwin: $(NAME).pd_darwin + +.SUFFIXES: .pd_darwin + +DARWINCFLAGS = -DPD -O3 -Wall -W -Wshadow -Wstrict-prototypes \ + -Wno-unused -Wno-parentheses -Wno-switch -L/usr/local/lib/ + +.c.pd_darwin: + $(CC) $(DARWINCFLAGS) $(INCLUDE) -o $*.o -c $*.c + $(CC) -bundle -undefined dynamic_lookup -o $(NAME).pd_darwin $*.o $(LDFLAGS) + rm -f *.o + +# Install ---------------------------------------------- + +install: + cp $(NAME).pd_* $(PDDIR)/extra/ + +# Clean ---------------------------------------------- + +clean: + rm -f *.pd_* *.o diff --git a/psql/README b/psql/README new file mode 100644 index 0000000..4e56def --- /dev/null +++ b/psql/README @@ -0,0 +1,35 @@ +PSQL - a postgres client for PD +---- + +This is the Readme file is adapted from the Readme for 'sqlsingle' by Iain Mott 2001 - http://soundart.tripod.com + +'psql' allows you to send SQL messages to a PostgreSQL database from Pd and retrieve the results. +In order to use the 'psql' external you will need to install PostgreSQL - available from http://www.postgresql.org. +There's a bit of work to do compiling the source, setting up environment variables etc - but the package comes with good documentation. Read the installation guide and do the introductory tutorial before trying 'psql'. See also 'some tips & notes' below before you decide to use 'psql'. + +As with all applications that connect to a PostgreSQL database, 'psql' requires the 'postmaster' daemon to be running. +'psql' may connect to a database on a local host or on a remote machine via TCP/IP (handled by the external). + +If no arguments are specified in 'psql' - messages will be sent to a postmaster via a local UNIX socket and will attempt to connect to the default PostgreSQL 'template1' database. Such a connection may be used to create new database by sending the SQL message: 'CREATE DATABASE databasename'. Before this can be done, you will need to set your username as a PostgreSQL user. This can be done from a PostgreSQL superuser account (not root) generally called 'postgres' which handles +database administrative duties including access privileges. + +Note: all SQL messages sent to the 'psql' must start with 'sql' and terminate with 'sqlend'. By convention, all PostgreSQL commands (some are non-standard SQL) are written in allcaps. A comma between an 'sqlend' and a 'sql' in a PD message, will execute a new query or command. + +Once you have created a database you can send messages to it with a second 'psql' object with the argument 'databasename'. See the patch 'psql.pd' for an example of this. + +If you wish to connect with a database on a networked machine - two arguments are needed in 'psql' in addition to the name of the database. The first is the name of the machine - the second is the port number. To facilitate this, the server machine must run the 'postmaster' with a '-i' flag to enable remote connections. The postmaster command line must also specify the port number ('-p <num>'). See PostgreSQL documentation for details. A startup script is available (in the Linux distribution of PostgreSQL at least) somewhere to enable automated activation of the postmaster (i think this is described in one of the install guides in the distribution tarball?). For security reasons, the postmaster should +not be run as root. Rather, it should be run from the 'postgres' account. + +psql outputs results of queries as lists. Often there will be more than one instance for a given query (instances are referred to as 'tuples'). eg. the query 'Select * FROM tablename' will return all rows from the specified table in a database. 'psql' retrieves each row as a seperate message, each preceded by an index starting at zero. + + +At present 'psql' handles 6 PostgreSQL data types: PGINT4; PGFLOAT8; PGDOUBLE; PGDATE; PGDATETIME and PGVARCHAR. If a query returns tuples of a different data type, these will be compiled into a list (on output) as Pd 'symbols'. In contrast, PGINT4, PGFLOAT8 and PGDOUBLE are compiled into lists as floats. Like non-specified data types, PGDATE, PGDATETIME and PGVARCHAR are compiled into lists as 'symbols'. + +Installation +------------ + +See the INSTALL file. + + + + diff --git a/psql/help-psql.pd b/psql/help-psql.pd new file mode 100644 index 0000000..e4e60b4 --- /dev/null +++ b/psql/help-psql.pd @@ -0,0 +1,50 @@ +#N canvas 36 70 917 494 10; +#X obj 377 470 print postgres; +#X msg 36 186 sql DROP DATABASE pddbase sqlend; +#X msg 79 87 sql CREATE DATABASE pddbase sqlend; +#X text 69 44 1 Create a new database - by first; +#X text 86 61 connecting to PostgreSQL's default database: 'template1' +; +#X text 479 56 to the newly created 'pddbase' database; +#X text 461 40 2 Create a new table in the database - this time connecting +; +#X text 467 114 3 Insert some data. Each click of the message below +; +#X text 484 132 inserts a new row into the specified table.; +#X text 471 228 4 Retrieve all data in the specified table using a +wild; +#X text 32 208 click this to destroy the database; +#X msg 456 79 sql CREATE TABLE datatable(id INTEGER \, duration FLOAT +\, type VARCHAR \, datetime DATETIME) sqlend; +#X text 487 242 card '*'. Note each row returned is preceded by an +index; +#X text 484 300 Also show the degree of error; +#X msg 466 318 sql SELECT id \, ABS((duration - 1500)/1500) AS error +FROM datatable ORDER BY error LIMIT 1 sqlend; +#X text 470 288 5 Find the 'id' of entry closest to 1500 msec in duration. +; +#X msg 466 150 sql INSERT INTO datatable VALUES(22 \, 1023.33 \, 'singing' +\, datetime('now'::date \, 'now'::time)) sqlend \, sql INSERT INTO +datatable VALUES(24 \, 1500.1 \, 'coughing' \, datetime('now'::date +\, 'now'::time)) sqlend \, sql INSERT INTO datatable VALUES(26 \, 2222.11 +\, 'sobbing' \, datetime('now'::date \, 'now'::time)) sqlend; +#X text 56 350 example of sqlsingle specifying; +#X text 57 366 host machine and port; +#X text 9 9 sqlsingle. Follow the numbered steps; +#X obj 500 393 route 0 1 2 3 4 5 6 7 8; +#X text 649 392 use route to separate indexed 'tuples'; +#X obj 500 428 unpack 0 0 s s; +#X text 596 428 use unpack to access individual fields; +#X msg 470 262 sql select * from datatable WHERE id < 30 sqlend; +#X obj 96 137 psql template1; +#X obj 57 330 psql pddbase localhost 5432; +#X obj 377 365 psql pddbase; +#X connect 1 0 25 0; +#X connect 2 0 25 0; +#X connect 11 0 27 0; +#X connect 14 0 27 0; +#X connect 16 0 27 0; +#X connect 20 0 22 0; +#X connect 24 0 27 0; +#X connect 27 0 20 0; +#X connect 27 0 0 0; diff --git a/psql/psql.c b/psql/psql.c new file mode 100644 index 0000000..5fac954 --- /dev/null +++ b/psql/psql.c @@ -0,0 +1,371 @@ +/* [psql] - A PostgreSQL client for PD + * + * Copyright (C) 2006 Jamie Bullock and others + * + * Large portions of the code are based on [sqlsingle] by Iain Mott + * + * Copyright (C) 2001 Iain Mott + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License, which should be included with this + * program, for more details. + * + */ + +/* up to 10 fields may be returned. returns floats or symbols */ + +/* code for psql pd class */ + +#include "m_pd.h" +#include <string.h> + +/* PSQL */ + +#include <stdio.h> +#include <stdlib.h> +#include "libpq-fe.h" + +#define MAXSQLFIELDS 10 + +/* postgres datatypes and corresponding 'Oid's */ + +#define PGINT4 23 +#define PGFLOAT8 701 +#define PGDOUBLE 1700 +#define PGDATE 1082 +#define PGDATETIME 1184 +#define PGVARCHAR 1043 + +typedef struct psql +{ + t_object t_ob; + t_outlet *x_outlet1; + t_outlet *x_outlet2; + t_atom get_atom; + t_symbol *x_sym; + char sqlStringStore[MAXPDSTRING]; + char *pghost, + *pgport, + *pgoptions, + *pgtty, + *dbName; + char port[20]; + PGconn *conn; + t_int connected; +} t_psql; + +static void psql_float(t_psql *x, t_floatarg f) +{ + post("psql: %f", f); +} + + +static void psql_SQL (t_psql *x, t_symbol *s) +{ + /* post("psql_SQL called");*/ + char sqlString[MAXPDSTRING]; + int argc = 10; + t_atom argv[argc]; + t_atom *test; + int descriptor_fnum; + int starttime_fnum; + int endtime_fnum; + int spurtorder_fnum; + int nFields; + int i, j; + t_symbol *t_sym; + PGresult *res; + int tupplecount; + test = argv; + + /* make a connection to the database */ + if(!x->connected){ + post("Reconnecting to database, %s", x->dbName); + x->conn = PQsetdb(x->pghost, x->pgport, + x->pgoptions, x->pgtty, x->dbName); + } + + + if(PQstatus(x->conn) == CONNECTION_BAD){ + fprintf(stderr, "Connection to database '%s' failed.\n", x->dbName); + fprintf(stderr, "%s", PQerrorMessage(x->conn)); + } + else{ + x->connected = 1; + + res = PQexec(x->conn, x->sqlStringStore); + if (PQresultStatus(res) != PGRES_TUPLES_OK && PQresultStatus(res) != PGRES_COMMAND_OK) + { + fprintf(stderr, "psql: Action failed. PQresultStatus is %s\n", PQresStatus(PQresultStatus(res))); + } + + else { + tupplecount = PQntuples(res); + if (!res || PQresultStatus(res) != PGRES_TUPLES_OK) + { + PQclear(res); + } + else { + + nFields = PQnfields(res); + + + descriptor_fnum = PQfnumber(res, "descriptor"); + starttime_fnum = PQfnumber(res, "starttime"); + endtime_fnum = PQfnumber(res, "endtime"); + spurtorder_fnum = PQfnumber(res, "spurtorder"); + /* fetch the instances */ + for (i = 0; i < PQntuples(res); i++) + { + /* merge field of a query instance into a list */ + SETFLOAT(&argv[0], i); + for (j=0; j<nFields; j++) + { + int fType = PQftype(res, j); + + if (fType == PGINT4) + SETFLOAT(&argv[j+1], (float) atoi(PQgetvalue(res, i, j))); + else if (fType == PGFLOAT8 || fType == PGDOUBLE) + SETFLOAT(&argv[j+1], (float) atof(PQgetvalue(res, i, j))); + else if (fType == PGVARCHAR || fType == PGDATE || fType == PGDATETIME) + { + t_sym = gensym( PQgetvalue(res, i, j)); + SETSYMBOL(&argv[j+1], t_sym); + } + else { + t_sym = gensym( PQgetvalue(res, i, j)); + SETSYMBOL(&argv[j+1], t_sym); + post("Undefined PG data type. OID: %d. Stored in list as Symbol", fType); + } + + } + t_sym = gensym( "A_FLOAT"); + outlet_list(x->x_outlet1, t_sym, nFields+1, argv); + } + PQclear(res); + } + } + } +} + +static void psql_close(t_psql *x){ + post("Closing connection to database %s", x->dbName); + PQfinish(x->conn); + x->connected = 0; +} + +static void psql_anything(t_psql *x, t_symbol *s, int ac, t_atom *av, t_floatarg f) +{ + char sqlString[MAXPDSTRING]; + int i; + char buf[MAXPDSTRING]; + char mybuf[MAXPDSTRING]; + + /*post("Calling psql_anything");*/ + + if(!strcmp(s->s_name,"close")) + psql_close(x); + else{ + if (strcmp(s->s_name, "sql") != 0) + { + strcat(x->sqlStringStore, ", "); + + /* replace the truncated first symbol */ + + strcat(x->sqlStringStore, s->s_name); + strcat(x->sqlStringStore, " "); + + /* see if it ends OK */ + + atom_string(av+ac-1, buf, MAXPDSTRING); + + if (strcmp(buf, "sqlend") == 0) + { + int tc = ac-1; + + + for (i = 0; i < tc; i++) + { + atom_string(av+i, buf, MAXPDSTRING); + strcat(x->sqlStringStore, buf); + if (i < tc - 1) + strcat(x->sqlStringStore, " "); + } + + /*post("executing query");*/ + psql_SQL (x, s); + } + else + { + for (i = 0; i < ac; i++) + { + atom_string(av+i, buf, MAXPDSTRING); + strcat(x->sqlStringStore, buf); + if (i < ac - 1) + strcat(x->sqlStringStore, " "); + } + + } + + } + else { + /* if s->s_name DOES equal "sql" - first clear sqlStringStore then check if end of string terminates with "sqlend" */ + + strcpy(x->sqlStringStore, ""); + atom_string(av+ac-1, buf, MAXPDSTRING); + if (strcmp(buf, "sqlend") != 0) + { + for (i = 0; i < ac; i++) + { + atom_string(av+i, buf, MAXPDSTRING); + strcat(x->sqlStringStore, buf); + if (i < ac - 1) + strcat(x->sqlStringStore, " "); + } + } + + else + { + ac -= 1; + for (i = 0; i < ac; i++) + { + atom_string(av+i, buf, MAXPDSTRING); + strcat(x->sqlStringStore, buf); + if (i < ac - 1) + strcat(x->sqlStringStore, " "); + } + /*post("executing query");*/ + psql_SQL (x, s); + } + + + + } + + atom_string(av+ac-1, buf, MAXPDSTRING); + } +} + +/* this one is needed if the new line begins with a number */ + +static void psql_list(t_psql *x, t_symbol *s, int ac, t_atom *av) +{ + int i; + char buf[MAXPDSTRING]; + /* post("list"); */ + strcat(x->sqlStringStore, ","); + + if (strcmp(x->sqlStringStore, "") != 0) + { + + atom_string(av+ac-1, buf, MAXPDSTRING); + if (strcmp(buf, "sqlend") == 0) + { + ac = ac -1; + for (i = 0; i < ac; i++) + { + strcat(x->sqlStringStore, " "); + atom_string(av+i, buf, MAXPDSTRING); + strcat(x->sqlStringStore, buf); + + } + } + else + { + for (i = 0; i < ac; i++) + { + strcat(x->sqlStringStore, " "); + atom_string(av+i, buf, MAXPDSTRING); + strcat(x->sqlStringStore, buf); + + } + } + } + else + post("psql: Not SQL"); + +} + + +t_class *psql_class; + +static void *psql_new(t_symbol *s, int argc, t_atom *argv) +{ + t_psql *x = (t_psql *)pd_new(psql_class); + x->x_sym = gensym("psql"); + x->x_outlet1 = outlet_new(&x->t_ob, &s_list); + if(argc == 0) + { + x->pghost = NULL; /* host name of the backend server */ + x->pgport = NULL; /* port of the backend server */ + x->pgoptions = NULL; /* special options to start up the backend server */ + x->pgtty = NULL; /* debugging tty for the backend server */ + x->dbName = "template1"; + post("using dbase template1 on local UNIX socket"); + } + else if(argc == 1 && argv[0].a_type == A_SYMBOL) + { + x->pghost = NULL; /* host name of the backend server */ + x->pgport = NULL; /* port of the backend server */ + x->pgoptions = NULL; /* special options to start up the backend server */ + x->pgtty = NULL; /* debugging tty for the backend server */ + x->dbName = argv[0].a_w.w_symbol->s_name; + /* post("using %s on localhost", argv[0].a_w.w_symbol->s_name); */ + } + else if(argc == 3 && argv[0].a_type == A_SYMBOL && argv[1].a_type == A_SYMBOL + && argv[2].a_type == A_FLOAT) + { + x->pghost = argv[1].a_w.w_symbol->s_name; /* host name of the backend server */ + sprintf(x->port, "%d", (int)argv[2].a_w.w_float); + x->pgport = x->port; /* port of the backend server */ + // strncpy(x->pgport, tmp); /* port of the backend server */ + x->pgoptions = NULL; /* special options to start up the backend server */ + x->pgtty = NULL; /* debugging tty for the backend server */ + x->dbName = argv[0].a_w.w_symbol->s_name; + /* post("using dbase %s on %s and port %s", x->dbName, x->pghost, x->pgport); */ + } + + else + { + x->pghost = NULL; /* host name of the backend server */ + x->pgport = NULL; /* port of the backend server */ + x->pgoptions = NULL; /* special options to start up the backend server */ + x->pgtty = NULL; /* debugging tty for the backend server */ + x->dbName = "template1"; + post("psql: invalid arguments using default template1 dbase on localhost"); + } + + // check postmaster is running on specified port and machine by attempting to x->connect to template1 + x->conn = PQsetdb(x->pghost, x->pgport, x->pgoptions, x->pgtty, "template1"); + if (PQstatus(x->conn) == CONNECTION_BAD) + { + fprintf(stderr, "psql: Connection to template1 failed. Perhaps the postmaster is not running on the specified port and machine \n"); + fprintf(stderr, "psql: Connect error is: %s", PQerrorMessage(x->conn)); + } + else + psql_close(x); + return (x); +} + + static void psql_free(t_psql *x){ + if(x->connected) + psql_close(x); + } + +void psql_setup(void) +{ + /* post("psql_setup"); */ + psql_class = class_new(gensym("psql"), (t_newmethod)psql_new, (t_method)psql_free, + sizeof(t_psql), 0, A_GIMME, 0); + class_addanything(psql_class, psql_anything); + class_addlist(psql_class, psql_list); +} + + |